github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/net/http/h2_bundle.go (about)

     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 = http2NewPriorityWriteScheduler(nil)
  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 a 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  		if clen == "" && rws.handlerDone && http2bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  6390  			clen = strconv.Itoa(len(p))
  6391  		}
  6392  		_, hasContentType := rws.snapHeader["Content-Type"]
  6393  		// If the Content-Encoding is non-blank, we shouldn't
  6394  		// sniff the body. See Issue golang.org/issue/31753.
  6395  		ce := rws.snapHeader.Get("Content-Encoding")
  6396  		hasCE := len(ce) > 0
  6397  		if !hasCE && !hasContentType && http2bodyAllowedForStatus(rws.status) && len(p) > 0 {
  6398  			ctype = DetectContentType(p)
  6399  		}
  6400  		var date string
  6401  		if _, ok := rws.snapHeader["Date"]; !ok {
  6402  			// TODO(bradfitz): be faster here, like net/http? measure.
  6403  			date = time.Now().UTC().Format(TimeFormat)
  6404  		}
  6405  
  6406  		for _, v := range rws.snapHeader["Trailer"] {
  6407  			http2foreachHeaderElement(v, rws.declareTrailer)
  6408  		}
  6409  
  6410  		// "Connection" headers aren't allowed in HTTP/2 (RFC 7540, 8.1.2.2),
  6411  		// but respect "Connection" == "close" to mean sending a GOAWAY and tearing
  6412  		// down the TCP connection when idle, like we do for HTTP/1.
  6413  		// TODO: remove more Connection-specific header fields here, in addition
  6414  		// to "Connection".
  6415  		if _, ok := rws.snapHeader["Connection"]; ok {
  6416  			v := rws.snapHeader.Get("Connection")
  6417  			delete(rws.snapHeader, "Connection")
  6418  			if v == "close" {
  6419  				rws.conn.startGracefulShutdown()
  6420  			}
  6421  		}
  6422  
  6423  		endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  6424  		err = rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
  6425  			streamID:      rws.stream.id,
  6426  			httpResCode:   rws.status,
  6427  			h:             rws.snapHeader,
  6428  			endStream:     endStream,
  6429  			contentType:   ctype,
  6430  			contentLength: clen,
  6431  			date:          date,
  6432  		})
  6433  		if err != nil {
  6434  			rws.dirty = true
  6435  			return 0, err
  6436  		}
  6437  		if endStream {
  6438  			return 0, nil
  6439  		}
  6440  	}
  6441  	if isHeadResp {
  6442  		return len(p), nil
  6443  	}
  6444  	if len(p) == 0 && !rws.handlerDone {
  6445  		return 0, nil
  6446  	}
  6447  
  6448  	// only send trailers if they have actually been defined by the
  6449  	// server handler.
  6450  	hasNonemptyTrailers := rws.hasNonemptyTrailers()
  6451  	endStream := rws.handlerDone && !hasNonemptyTrailers
  6452  	if len(p) > 0 || endStream {
  6453  		// only send a 0 byte DATA frame if we're ending the stream.
  6454  		if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  6455  			rws.dirty = true
  6456  			return 0, err
  6457  		}
  6458  	}
  6459  
  6460  	if rws.handlerDone && hasNonemptyTrailers {
  6461  		err = rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
  6462  			streamID:  rws.stream.id,
  6463  			h:         rws.handlerHeader,
  6464  			trailers:  rws.trailers,
  6465  			endStream: true,
  6466  		})
  6467  		if err != nil {
  6468  			rws.dirty = true
  6469  		}
  6470  		return len(p), err
  6471  	}
  6472  	return len(p), nil
  6473  }
  6474  
  6475  // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
  6476  // that, if present, signals that the map entry is actually for
  6477  // the response trailers, and not the response headers. The prefix
  6478  // is stripped after the ServeHTTP call finishes and the values are
  6479  // sent in the trailers.
  6480  //
  6481  // This mechanism is intended only for trailers that are not known
  6482  // prior to the headers being written. If the set of trailers is fixed
  6483  // or known before the header is written, the normal Go trailers mechanism
  6484  // is preferred:
  6485  //
  6486  //	https://golang.org/pkg/net/http/#ResponseWriter
  6487  //	https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
  6488  const http2TrailerPrefix = "Trailer:"
  6489  
  6490  // promoteUndeclaredTrailers permits http.Handlers to set trailers
  6491  // after the header has already been flushed. Because the Go
  6492  // ResponseWriter interface has no way to set Trailers (only the
  6493  // Header), and because we didn't want to expand the ResponseWriter
  6494  // interface, and because nobody used trailers, and because RFC 7230
  6495  // says you SHOULD (but not must) predeclare any trailers in the
  6496  // header, the official ResponseWriter rules said trailers in Go must
  6497  // be predeclared, and then we reuse the same ResponseWriter.Header()
  6498  // map to mean both Headers and Trailers. When it's time to write the
  6499  // Trailers, we pick out the fields of Headers that were declared as
  6500  // trailers. That worked for a while, until we found the first major
  6501  // user of Trailers in the wild: gRPC (using them only over http2),
  6502  // and gRPC libraries permit setting trailers mid-stream without
  6503  // predeclaring them. So: change of plans. We still permit the old
  6504  // way, but we also permit this hack: if a Header() key begins with
  6505  // "Trailer:", the suffix of that key is a Trailer. Because ':' is an
  6506  // invalid token byte anyway, there is no ambiguity. (And it's already
  6507  // filtered out) It's mildly hacky, but not terrible.
  6508  //
  6509  // This method runs after the Handler is done and promotes any Header
  6510  // fields to be trailers.
  6511  func (rws *http2responseWriterState) promoteUndeclaredTrailers() {
  6512  	for k, vv := range rws.handlerHeader {
  6513  		if !strings.HasPrefix(k, http2TrailerPrefix) {
  6514  			continue
  6515  		}
  6516  		trailerKey := strings.TrimPrefix(k, http2TrailerPrefix)
  6517  		rws.declareTrailer(trailerKey)
  6518  		rws.handlerHeader[CanonicalHeaderKey(trailerKey)] = vv
  6519  	}
  6520  
  6521  	if len(rws.trailers) > 1 {
  6522  		sorter := http2sorterPool.Get().(*http2sorter)
  6523  		sorter.SortStrings(rws.trailers)
  6524  		http2sorterPool.Put(sorter)
  6525  	}
  6526  }
  6527  
  6528  func (w *http2responseWriter) SetReadDeadline(deadline time.Time) error {
  6529  	st := w.rws.stream
  6530  	if !deadline.IsZero() && deadline.Before(time.Now()) {
  6531  		// If we're setting a deadline in the past, reset the stream immediately
  6532  		// so writes after SetWriteDeadline returns will fail.
  6533  		st.onReadTimeout()
  6534  		return nil
  6535  	}
  6536  	w.rws.conn.sendServeMsg(func(sc *http2serverConn) {
  6537  		if st.readDeadline != nil {
  6538  			if !st.readDeadline.Stop() {
  6539  				// Deadline already exceeded, or stream has been closed.
  6540  				return
  6541  			}
  6542  		}
  6543  		if deadline.IsZero() {
  6544  			st.readDeadline = nil
  6545  		} else if st.readDeadline == nil {
  6546  			st.readDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onReadTimeout)
  6547  		} else {
  6548  			st.readDeadline.Reset(deadline.Sub(time.Now()))
  6549  		}
  6550  	})
  6551  	return nil
  6552  }
  6553  
  6554  func (w *http2responseWriter) SetWriteDeadline(deadline time.Time) error {
  6555  	st := w.rws.stream
  6556  	if !deadline.IsZero() && deadline.Before(time.Now()) {
  6557  		// If we're setting a deadline in the past, reset the stream immediately
  6558  		// so writes after SetWriteDeadline returns will fail.
  6559  		st.onWriteTimeout()
  6560  		return nil
  6561  	}
  6562  	w.rws.conn.sendServeMsg(func(sc *http2serverConn) {
  6563  		if st.writeDeadline != nil {
  6564  			if !st.writeDeadline.Stop() {
  6565  				// Deadline already exceeded, or stream has been closed.
  6566  				return
  6567  			}
  6568  		}
  6569  		if deadline.IsZero() {
  6570  			st.writeDeadline = nil
  6571  		} else if st.writeDeadline == nil {
  6572  			st.writeDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onWriteTimeout)
  6573  		} else {
  6574  			st.writeDeadline.Reset(deadline.Sub(time.Now()))
  6575  		}
  6576  	})
  6577  	return nil
  6578  }
  6579  
  6580  func (w *http2responseWriter) Flush() {
  6581  	w.FlushError()
  6582  }
  6583  
  6584  func (w *http2responseWriter) FlushError() error {
  6585  	rws := w.rws
  6586  	if rws == nil {
  6587  		panic("Header called after Handler finished")
  6588  	}
  6589  	var err error
  6590  	if rws.bw.Buffered() > 0 {
  6591  		err = rws.bw.Flush()
  6592  	} else {
  6593  		// The bufio.Writer won't call chunkWriter.Write
  6594  		// (writeChunk with zero bytes, so we have to do it
  6595  		// ourselves to force the HTTP response header and/or
  6596  		// final DATA frame (with END_STREAM) to be sent.
  6597  		_, err = http2chunkWriter{rws}.Write(nil)
  6598  		if err == nil {
  6599  			select {
  6600  			case <-rws.stream.cw:
  6601  				err = rws.stream.closeErr
  6602  			default:
  6603  			}
  6604  		}
  6605  	}
  6606  	return err
  6607  }
  6608  
  6609  func (w *http2responseWriter) CloseNotify() <-chan bool {
  6610  	rws := w.rws
  6611  	if rws == nil {
  6612  		panic("CloseNotify called after Handler finished")
  6613  	}
  6614  	rws.closeNotifierMu.Lock()
  6615  	ch := rws.closeNotifierCh
  6616  	if ch == nil {
  6617  		ch = make(chan bool, 1)
  6618  		rws.closeNotifierCh = ch
  6619  		cw := rws.stream.cw
  6620  		go func() {
  6621  			cw.Wait() // wait for close
  6622  			ch <- true
  6623  		}()
  6624  	}
  6625  	rws.closeNotifierMu.Unlock()
  6626  	return ch
  6627  }
  6628  
  6629  func (w *http2responseWriter) Header() Header {
  6630  	rws := w.rws
  6631  	if rws == nil {
  6632  		panic("Header called after Handler finished")
  6633  	}
  6634  	if rws.handlerHeader == nil {
  6635  		rws.handlerHeader = make(Header)
  6636  	}
  6637  	return rws.handlerHeader
  6638  }
  6639  
  6640  // checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode.
  6641  func http2checkWriteHeaderCode(code int) {
  6642  	// Issue 22880: require valid WriteHeader status codes.
  6643  	// For now we only enforce that it's three digits.
  6644  	// In the future we might block things over 599 (600 and above aren't defined
  6645  	// at http://httpwg.org/specs/rfc7231.html#status.codes).
  6646  	// But for now any three digits.
  6647  	//
  6648  	// We used to send "HTTP/1.1 000 0" on the wire in responses but there's
  6649  	// no equivalent bogus thing we can realistically send in HTTP/2,
  6650  	// so we'll consistently panic instead and help people find their bugs
  6651  	// early. (We can't return an error from WriteHeader even if we wanted to.)
  6652  	if code < 100 || code > 999 {
  6653  		panic(fmt.Sprintf("invalid WriteHeader code %v", code))
  6654  	}
  6655  }
  6656  
  6657  func (w *http2responseWriter) WriteHeader(code int) {
  6658  	rws := w.rws
  6659  	if rws == nil {
  6660  		panic("WriteHeader called after Handler finished")
  6661  	}
  6662  	rws.writeHeader(code)
  6663  }
  6664  
  6665  func (rws *http2responseWriterState) writeHeader(code int) {
  6666  	if rws.wroteHeader {
  6667  		return
  6668  	}
  6669  
  6670  	http2checkWriteHeaderCode(code)
  6671  
  6672  	// Handle informational headers
  6673  	if code >= 100 && code <= 199 {
  6674  		// Per RFC 8297 we must not clear the current header map
  6675  		h := rws.handlerHeader
  6676  
  6677  		_, cl := h["Content-Length"]
  6678  		_, te := h["Transfer-Encoding"]
  6679  		if cl || te {
  6680  			h = h.Clone()
  6681  			h.Del("Content-Length")
  6682  			h.Del("Transfer-Encoding")
  6683  		}
  6684  
  6685  		if rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
  6686  			streamID:    rws.stream.id,
  6687  			httpResCode: code,
  6688  			h:           h,
  6689  			endStream:   rws.handlerDone && !rws.hasTrailers(),
  6690  		}) != nil {
  6691  			rws.dirty = true
  6692  		}
  6693  
  6694  		return
  6695  	}
  6696  
  6697  	rws.wroteHeader = true
  6698  	rws.status = code
  6699  	if len(rws.handlerHeader) > 0 {
  6700  		rws.snapHeader = http2cloneHeader(rws.handlerHeader)
  6701  	}
  6702  }
  6703  
  6704  func http2cloneHeader(h Header) Header {
  6705  	h2 := make(Header, len(h))
  6706  	for k, vv := range h {
  6707  		vv2 := make([]string, len(vv))
  6708  		copy(vv2, vv)
  6709  		h2[k] = vv2
  6710  	}
  6711  	return h2
  6712  }
  6713  
  6714  // The Life Of A Write is like this:
  6715  //
  6716  // * Handler calls w.Write or w.WriteString ->
  6717  // * -> rws.bw (*bufio.Writer) ->
  6718  // * (Handler might call Flush)
  6719  // * -> chunkWriter{rws}
  6720  // * -> responseWriterState.writeChunk(p []byte)
  6721  // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  6722  func (w *http2responseWriter) Write(p []byte) (n int, err error) {
  6723  	return w.write(len(p), p, "")
  6724  }
  6725  
  6726  func (w *http2responseWriter) WriteString(s string) (n int, err error) {
  6727  	return w.write(len(s), nil, s)
  6728  }
  6729  
  6730  // either dataB or dataS is non-zero.
  6731  func (w *http2responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  6732  	rws := w.rws
  6733  	if rws == nil {
  6734  		panic("Write called after Handler finished")
  6735  	}
  6736  	if !rws.wroteHeader {
  6737  		w.WriteHeader(200)
  6738  	}
  6739  	if !http2bodyAllowedForStatus(rws.status) {
  6740  		return 0, ErrBodyNotAllowed
  6741  	}
  6742  	rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  6743  	if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  6744  		// TODO: send a RST_STREAM
  6745  		return 0, errors.New("http2: handler wrote more than declared Content-Length")
  6746  	}
  6747  
  6748  	if dataB != nil {
  6749  		return rws.bw.Write(dataB)
  6750  	} else {
  6751  		return rws.bw.WriteString(dataS)
  6752  	}
  6753  }
  6754  
  6755  func (w *http2responseWriter) handlerDone() {
  6756  	rws := w.rws
  6757  	dirty := rws.dirty
  6758  	rws.handlerDone = true
  6759  	w.Flush()
  6760  	w.rws = nil
  6761  	if !dirty {
  6762  		// Only recycle the pool if all prior Write calls to
  6763  		// the serverConn goroutine completed successfully. If
  6764  		// they returned earlier due to resets from the peer
  6765  		// there might still be write goroutines outstanding
  6766  		// from the serverConn referencing the rws memory. See
  6767  		// issue 20704.
  6768  		http2responseWriterStatePool.Put(rws)
  6769  	}
  6770  }
  6771  
  6772  // Push errors.
  6773  var (
  6774  	http2ErrRecursivePush    = errors.New("http2: recursive push not allowed")
  6775  	http2ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
  6776  )
  6777  
  6778  var _ Pusher = (*http2responseWriter)(nil)
  6779  
  6780  func (w *http2responseWriter) Push(target string, opts *PushOptions) error {
  6781  	st := w.rws.stream
  6782  	sc := st.sc
  6783  	sc.serveG.checkNotOn()
  6784  
  6785  	// No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
  6786  	// http://tools.ietf.org/html/rfc7540#section-6.6
  6787  	if st.isPushed() {
  6788  		return http2ErrRecursivePush
  6789  	}
  6790  
  6791  	if opts == nil {
  6792  		opts = new(PushOptions)
  6793  	}
  6794  
  6795  	// Default options.
  6796  	if opts.Method == "" {
  6797  		opts.Method = "GET"
  6798  	}
  6799  	if opts.Header == nil {
  6800  		opts.Header = Header{}
  6801  	}
  6802  	wantScheme := "http"
  6803  	if w.rws.req.TLS != nil {
  6804  		wantScheme = "https"
  6805  	}
  6806  
  6807  	// Validate the request.
  6808  	u, err := url.Parse(target)
  6809  	if err != nil {
  6810  		return err
  6811  	}
  6812  	if u.Scheme == "" {
  6813  		if !strings.HasPrefix(target, "/") {
  6814  			return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
  6815  		}
  6816  		u.Scheme = wantScheme
  6817  		u.Host = w.rws.req.Host
  6818  	} else {
  6819  		if u.Scheme != wantScheme {
  6820  			return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
  6821  		}
  6822  		if u.Host == "" {
  6823  			return errors.New("URL must have a host")
  6824  		}
  6825  	}
  6826  	for k := range opts.Header {
  6827  		if strings.HasPrefix(k, ":") {
  6828  			return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
  6829  		}
  6830  		// These headers are meaningful only if the request has a body,
  6831  		// but PUSH_PROMISE requests cannot have a body.
  6832  		// http://tools.ietf.org/html/rfc7540#section-8.2
  6833  		// Also disallow Host, since the promised URL must be absolute.
  6834  		if http2asciiEqualFold(k, "content-length") ||
  6835  			http2asciiEqualFold(k, "content-encoding") ||
  6836  			http2asciiEqualFold(k, "trailer") ||
  6837  			http2asciiEqualFold(k, "te") ||
  6838  			http2asciiEqualFold(k, "expect") ||
  6839  			http2asciiEqualFold(k, "host") {
  6840  			return fmt.Errorf("promised request headers cannot include %q", k)
  6841  		}
  6842  	}
  6843  	if err := http2checkValidHTTP2RequestHeaders(opts.Header); err != nil {
  6844  		return err
  6845  	}
  6846  
  6847  	// The RFC effectively limits promised requests to GET and HEAD:
  6848  	// "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
  6849  	// http://tools.ietf.org/html/rfc7540#section-8.2
  6850  	if opts.Method != "GET" && opts.Method != "HEAD" {
  6851  		return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
  6852  	}
  6853  
  6854  	msg := &http2startPushRequest{
  6855  		parent: st,
  6856  		method: opts.Method,
  6857  		url:    u,
  6858  		header: http2cloneHeader(opts.Header),
  6859  		done:   http2errChanPool.Get().(chan error),
  6860  	}
  6861  
  6862  	select {
  6863  	case <-sc.doneServing:
  6864  		return http2errClientDisconnected
  6865  	case <-st.cw:
  6866  		return http2errStreamClosed
  6867  	case sc.serveMsgCh <- msg:
  6868  	}
  6869  
  6870  	select {
  6871  	case <-sc.doneServing:
  6872  		return http2errClientDisconnected
  6873  	case <-st.cw:
  6874  		return http2errStreamClosed
  6875  	case err := <-msg.done:
  6876  		http2errChanPool.Put(msg.done)
  6877  		return err
  6878  	}
  6879  }
  6880  
  6881  type http2startPushRequest struct {
  6882  	parent *http2stream
  6883  	method string
  6884  	url    *url.URL
  6885  	header Header
  6886  	done   chan error
  6887  }
  6888  
  6889  func (sc *http2serverConn) startPush(msg *http2startPushRequest) {
  6890  	sc.serveG.check()
  6891  
  6892  	// http://tools.ietf.org/html/rfc7540#section-6.6.
  6893  	// PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
  6894  	// is in either the "open" or "half-closed (remote)" state.
  6895  	if msg.parent.state != http2stateOpen && msg.parent.state != http2stateHalfClosedRemote {
  6896  		// responseWriter.Push checks that the stream is peer-initiated.
  6897  		msg.done <- http2errStreamClosed
  6898  		return
  6899  	}
  6900  
  6901  	// http://tools.ietf.org/html/rfc7540#section-6.6.
  6902  	if !sc.pushEnabled {
  6903  		msg.done <- ErrNotSupported
  6904  		return
  6905  	}
  6906  
  6907  	// PUSH_PROMISE frames must be sent in increasing order by stream ID, so
  6908  	// we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
  6909  	// is written. Once the ID is allocated, we start the request handler.
  6910  	allocatePromisedID := func() (uint32, error) {
  6911  		sc.serveG.check()
  6912  
  6913  		// Check this again, just in case. Technically, we might have received
  6914  		// an updated SETTINGS by the time we got around to writing this frame.
  6915  		if !sc.pushEnabled {
  6916  			return 0, ErrNotSupported
  6917  		}
  6918  		// http://tools.ietf.org/html/rfc7540#section-6.5.2.
  6919  		if sc.curPushedStreams+1 > sc.clientMaxStreams {
  6920  			return 0, http2ErrPushLimitReached
  6921  		}
  6922  
  6923  		// http://tools.ietf.org/html/rfc7540#section-5.1.1.
  6924  		// Streams initiated by the server MUST use even-numbered identifiers.
  6925  		// A server that is unable to establish a new stream identifier can send a GOAWAY
  6926  		// frame so that the client is forced to open a new connection for new streams.
  6927  		if sc.maxPushPromiseID+2 >= 1<<31 {
  6928  			sc.startGracefulShutdownInternal()
  6929  			return 0, http2ErrPushLimitReached
  6930  		}
  6931  		sc.maxPushPromiseID += 2
  6932  		promisedID := sc.maxPushPromiseID
  6933  
  6934  		// http://tools.ietf.org/html/rfc7540#section-8.2.
  6935  		// Strictly speaking, the new stream should start in "reserved (local)", then
  6936  		// transition to "half closed (remote)" after sending the initial HEADERS, but
  6937  		// we start in "half closed (remote)" for simplicity.
  6938  		// See further comments at the definition of stateHalfClosedRemote.
  6939  		promised := sc.newStream(promisedID, msg.parent.id, http2stateHalfClosedRemote)
  6940  		rw, req, err := sc.newWriterAndRequestNoBody(promised, http2requestParam{
  6941  			method:    msg.method,
  6942  			scheme:    msg.url.Scheme,
  6943  			authority: msg.url.Host,
  6944  			path:      msg.url.RequestURI(),
  6945  			header:    http2cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE
  6946  		})
  6947  		if err != nil {
  6948  			// Should not happen, since we've already validated msg.url.
  6949  			panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
  6950  		}
  6951  
  6952  		go sc.runHandler(rw, req, sc.handler.ServeHTTP)
  6953  		return promisedID, nil
  6954  	}
  6955  
  6956  	sc.writeFrame(http2FrameWriteRequest{
  6957  		write: &http2writePushPromise{
  6958  			streamID:           msg.parent.id,
  6959  			method:             msg.method,
  6960  			url:                msg.url,
  6961  			h:                  msg.header,
  6962  			allocatePromisedID: allocatePromisedID,
  6963  		},
  6964  		stream: msg.parent,
  6965  		done:   msg.done,
  6966  	})
  6967  }
  6968  
  6969  // foreachHeaderElement splits v according to the "#rule" construction
  6970  // in RFC 7230 section 7 and calls fn for each non-empty element.
  6971  func http2foreachHeaderElement(v string, fn func(string)) {
  6972  	v = textproto.TrimString(v)
  6973  	if v == "" {
  6974  		return
  6975  	}
  6976  	if !strings.Contains(v, ",") {
  6977  		fn(v)
  6978  		return
  6979  	}
  6980  	for _, f := range strings.Split(v, ",") {
  6981  		if f = textproto.TrimString(f); f != "" {
  6982  			fn(f)
  6983  		}
  6984  	}
  6985  }
  6986  
  6987  // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
  6988  var http2connHeaders = []string{
  6989  	"Connection",
  6990  	"Keep-Alive",
  6991  	"Proxy-Connection",
  6992  	"Transfer-Encoding",
  6993  	"Upgrade",
  6994  }
  6995  
  6996  // checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
  6997  // per RFC 7540 Section 8.1.2.2.
  6998  // The returned error is reported to users.
  6999  func http2checkValidHTTP2RequestHeaders(h Header) error {
  7000  	for _, k := range http2connHeaders {
  7001  		if _, ok := h[k]; ok {
  7002  			return fmt.Errorf("request header %q is not valid in HTTP/2", k)
  7003  		}
  7004  	}
  7005  	te := h["Te"]
  7006  	if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
  7007  		return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
  7008  	}
  7009  	return nil
  7010  }
  7011  
  7012  func http2new400Handler(err error) HandlerFunc {
  7013  	return func(w ResponseWriter, r *Request) {
  7014  		Error(w, err.Error(), StatusBadRequest)
  7015  	}
  7016  }
  7017  
  7018  // h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
  7019  // disabled. See comments on h1ServerShutdownChan above for why
  7020  // the code is written this way.
  7021  func http2h1ServerKeepAlivesDisabled(hs *Server) bool {
  7022  	var x interface{} = hs
  7023  	type I interface {
  7024  		doKeepAlives() bool
  7025  	}
  7026  	if hs, ok := x.(I); ok {
  7027  		return !hs.doKeepAlives()
  7028  	}
  7029  	return false
  7030  }
  7031  
  7032  func (sc *http2serverConn) countError(name string, err error) error {
  7033  	if sc == nil || sc.srv == nil {
  7034  		return err
  7035  	}
  7036  	f := sc.srv.CountError
  7037  	if f == nil {
  7038  		return err
  7039  	}
  7040  	var typ string
  7041  	var code http2ErrCode
  7042  	switch e := err.(type) {
  7043  	case http2ConnectionError:
  7044  		typ = "conn"
  7045  		code = http2ErrCode(e)
  7046  	case http2StreamError:
  7047  		typ = "stream"
  7048  		code = http2ErrCode(e.Code)
  7049  	default:
  7050  		return err
  7051  	}
  7052  	codeStr := http2errCodeName[code]
  7053  	if codeStr == "" {
  7054  		codeStr = strconv.Itoa(int(code))
  7055  	}
  7056  	f(fmt.Sprintf("%s_%s_%s", typ, codeStr, name))
  7057  	return err
  7058  }
  7059  
  7060  const (
  7061  	// transportDefaultConnFlow is how many connection-level flow control
  7062  	// tokens we give the server at start-up, past the default 64k.
  7063  	http2transportDefaultConnFlow = 1 << 30
  7064  
  7065  	// transportDefaultStreamFlow is how many stream-level flow
  7066  	// control tokens we announce to the peer, and how many bytes
  7067  	// we buffer per stream.
  7068  	http2transportDefaultStreamFlow = 4 << 20
  7069  
  7070  	http2defaultUserAgent = "Go-http-client/2.0"
  7071  
  7072  	// initialMaxConcurrentStreams is a connections maxConcurrentStreams until
  7073  	// it's received servers initial SETTINGS frame, which corresponds with the
  7074  	// spec's minimum recommended value.
  7075  	http2initialMaxConcurrentStreams = 100
  7076  
  7077  	// defaultMaxConcurrentStreams is a connections default maxConcurrentStreams
  7078  	// if the server doesn't include one in its initial SETTINGS frame.
  7079  	http2defaultMaxConcurrentStreams = 1000
  7080  )
  7081  
  7082  // Transport is an HTTP/2 Transport.
  7083  //
  7084  // A Transport internally caches connections to servers. It is safe
  7085  // for concurrent use by multiple goroutines.
  7086  type http2Transport struct {
  7087  	// DialTLSContext specifies an optional dial function with context for
  7088  	// creating TLS connections for requests.
  7089  	//
  7090  	// If DialTLSContext and DialTLS is nil, tls.Dial is used.
  7091  	//
  7092  	// If the returned net.Conn has a ConnectionState method like tls.Conn,
  7093  	// it will be used to set http.Response.TLS.
  7094  	DialTLSContext func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error)
  7095  
  7096  	// DialTLS specifies an optional dial function for creating
  7097  	// TLS connections for requests.
  7098  	//
  7099  	// If DialTLSContext and DialTLS is nil, tls.Dial is used.
  7100  	//
  7101  	// Deprecated: Use DialTLSContext instead, which allows the transport
  7102  	// to cancel dials as soon as they are no longer needed.
  7103  	// If both are set, DialTLSContext takes priority.
  7104  	DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
  7105  
  7106  	// TLSClientConfig specifies the TLS configuration to use with
  7107  	// tls.Client. If nil, the default configuration is used.
  7108  	TLSClientConfig *tls.Config
  7109  
  7110  	// ConnPool optionally specifies an alternate connection pool to use.
  7111  	// If nil, the default is used.
  7112  	ConnPool http2ClientConnPool
  7113  
  7114  	// DisableCompression, if true, prevents the Transport from
  7115  	// requesting compression with an "Accept-Encoding: gzip"
  7116  	// request header when the Request contains no existing
  7117  	// Accept-Encoding value. If the Transport requests gzip on
  7118  	// its own and gets a gzipped response, it's transparently
  7119  	// decoded in the Response.Body. However, if the user
  7120  	// explicitly requested gzip it is not automatically
  7121  	// uncompressed.
  7122  	DisableCompression bool
  7123  
  7124  	// AllowHTTP, if true, permits HTTP/2 requests using the insecure,
  7125  	// plain-text "http" scheme. Note that this does not enable h2c support.
  7126  	AllowHTTP bool
  7127  
  7128  	// MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
  7129  	// send in the initial settings frame. It is how many bytes
  7130  	// of response headers are allowed. Unlike the http2 spec, zero here
  7131  	// means to use a default limit (currently 10MB). If you actually
  7132  	// want to advertise an unlimited value to the peer, Transport
  7133  	// interprets the highest possible value here (0xffffffff or 1<<32-1)
  7134  	// to mean no limit.
  7135  	MaxHeaderListSize uint32
  7136  
  7137  	// MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the
  7138  	// initial settings frame. It is the size in bytes of the largest frame
  7139  	// payload that the sender is willing to receive. If 0, no setting is
  7140  	// sent, and the value is provided by the peer, which should be 16384
  7141  	// according to the spec:
  7142  	// https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2.
  7143  	// Values are bounded in the range 16k to 16M.
  7144  	MaxReadFrameSize uint32
  7145  
  7146  	// MaxDecoderHeaderTableSize optionally specifies the http2
  7147  	// SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
  7148  	// informs the remote endpoint of the maximum size of the header compression
  7149  	// table used to decode header blocks, in octets. If zero, the default value
  7150  	// of 4096 is used.
  7151  	MaxDecoderHeaderTableSize uint32
  7152  
  7153  	// MaxEncoderHeaderTableSize optionally specifies an upper limit for the
  7154  	// header compression table used for encoding request headers. Received
  7155  	// SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
  7156  	// the default value of 4096 is used.
  7157  	MaxEncoderHeaderTableSize uint32
  7158  
  7159  	// StrictMaxConcurrentStreams controls whether the server's
  7160  	// SETTINGS_MAX_CONCURRENT_STREAMS should be respected
  7161  	// globally. If false, new TCP connections are created to the
  7162  	// server as needed to keep each under the per-connection
  7163  	// SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
  7164  	// server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
  7165  	// a global limit and callers of RoundTrip block when needed,
  7166  	// waiting for their turn.
  7167  	StrictMaxConcurrentStreams bool
  7168  
  7169  	// ReadIdleTimeout is the timeout after which a health check using ping
  7170  	// frame will be carried out if no frame is received on the connection.
  7171  	// Note that a ping response will is considered a received frame, so if
  7172  	// there is no other traffic on the connection, the health check will
  7173  	// be performed every ReadIdleTimeout interval.
  7174  	// If zero, no health check is performed.
  7175  	ReadIdleTimeout time.Duration
  7176  
  7177  	// PingTimeout is the timeout after which the connection will be closed
  7178  	// if a response to Ping is not received.
  7179  	// Defaults to 15s.
  7180  	PingTimeout time.Duration
  7181  
  7182  	// WriteByteTimeout is the timeout after which the connection will be
  7183  	// closed no data can be written to it. The timeout begins when data is
  7184  	// available to write, and is extended whenever any bytes are written.
  7185  	WriteByteTimeout time.Duration
  7186  
  7187  	// CountError, if non-nil, is called on HTTP/2 transport errors.
  7188  	// It's intended to increment a metric for monitoring, such
  7189  	// as an expvar or Prometheus metric.
  7190  	// The errType consists of only ASCII word characters.
  7191  	CountError func(errType string)
  7192  
  7193  	// t1, if non-nil, is the standard library Transport using
  7194  	// this transport. Its settings are used (but not its
  7195  	// RoundTrip method, etc).
  7196  	t1 *Transport
  7197  
  7198  	connPoolOnce  sync.Once
  7199  	connPoolOrDef http2ClientConnPool // non-nil version of ConnPool
  7200  }
  7201  
  7202  func (t *http2Transport) maxHeaderListSize() uint32 {
  7203  	if t.MaxHeaderListSize == 0 {
  7204  		return 10 << 20
  7205  	}
  7206  	if t.MaxHeaderListSize == 0xffffffff {
  7207  		return 0
  7208  	}
  7209  	return t.MaxHeaderListSize
  7210  }
  7211  
  7212  func (t *http2Transport) maxFrameReadSize() uint32 {
  7213  	if t.MaxReadFrameSize == 0 {
  7214  		return 0 // use the default provided by the peer
  7215  	}
  7216  	if t.MaxReadFrameSize < http2minMaxFrameSize {
  7217  		return http2minMaxFrameSize
  7218  	}
  7219  	if t.MaxReadFrameSize > http2maxFrameSize {
  7220  		return http2maxFrameSize
  7221  	}
  7222  	return t.MaxReadFrameSize
  7223  }
  7224  
  7225  func (t *http2Transport) disableCompression() bool {
  7226  	return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
  7227  }
  7228  
  7229  func (t *http2Transport) pingTimeout() time.Duration {
  7230  	if t.PingTimeout == 0 {
  7231  		return 15 * time.Second
  7232  	}
  7233  	return t.PingTimeout
  7234  
  7235  }
  7236  
  7237  // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
  7238  // It returns an error if t1 has already been HTTP/2-enabled.
  7239  //
  7240  // Use ConfigureTransports instead to configure the HTTP/2 Transport.
  7241  func http2ConfigureTransport(t1 *Transport) error {
  7242  	_, err := http2ConfigureTransports(t1)
  7243  	return err
  7244  }
  7245  
  7246  // ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2.
  7247  // It returns a new HTTP/2 Transport for further configuration.
  7248  // It returns an error if t1 has already been HTTP/2-enabled.
  7249  func http2ConfigureTransports(t1 *Transport) (*http2Transport, error) {
  7250  	return http2configureTransports(t1)
  7251  }
  7252  
  7253  func http2configureTransports(t1 *Transport) (*http2Transport, error) {
  7254  	connPool := new(http2clientConnPool)
  7255  	t2 := &http2Transport{
  7256  		ConnPool: http2noDialClientConnPool{connPool},
  7257  		t1:       t1,
  7258  	}
  7259  	connPool.t = t2
  7260  	if err := http2registerHTTPSProtocol(t1, http2noDialH2RoundTripper{t2}); err != nil {
  7261  		return nil, err
  7262  	}
  7263  	if t1.TLSClientConfig == nil {
  7264  		t1.TLSClientConfig = new(tls.Config)
  7265  	}
  7266  	if !http2strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
  7267  		t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
  7268  	}
  7269  	if !http2strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
  7270  		t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
  7271  	}
  7272  	upgradeFn := func(authority string, c *tls.Conn) RoundTripper {
  7273  		addr := http2authorityAddr("https", authority)
  7274  		if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
  7275  			go c.Close()
  7276  			return http2erringRoundTripper{err}
  7277  		} else if !used {
  7278  			// Turns out we don't need this c.
  7279  			// For example, two goroutines made requests to the same host
  7280  			// at the same time, both kicking off TCP dials. (since protocol
  7281  			// was unknown)
  7282  			go c.Close()
  7283  		}
  7284  		return t2
  7285  	}
  7286  	if m := t1.TLSNextProto; len(m) == 0 {
  7287  		t1.TLSNextProto = map[string]func(string, *tls.Conn) RoundTripper{
  7288  			"h2": upgradeFn,
  7289  		}
  7290  	} else {
  7291  		m["h2"] = upgradeFn
  7292  	}
  7293  	return t2, nil
  7294  }
  7295  
  7296  func (t *http2Transport) connPool() http2ClientConnPool {
  7297  	t.connPoolOnce.Do(t.initConnPool)
  7298  	return t.connPoolOrDef
  7299  }
  7300  
  7301  func (t *http2Transport) initConnPool() {
  7302  	if t.ConnPool != nil {
  7303  		t.connPoolOrDef = t.ConnPool
  7304  	} else {
  7305  		t.connPoolOrDef = &http2clientConnPool{t: t}
  7306  	}
  7307  }
  7308  
  7309  // ClientConn is the state of a single HTTP/2 client connection to an
  7310  // HTTP/2 server.
  7311  type http2ClientConn struct {
  7312  	t             *http2Transport
  7313  	tconn         net.Conn // usually *tls.Conn, except specialized impls
  7314  	tconnClosed   bool
  7315  	tlsState      *tls.ConnectionState // nil only for specialized impls
  7316  	reused        uint32               // whether conn is being reused; atomic
  7317  	singleUse     bool                 // whether being used for a single http.Request
  7318  	getConnCalled bool                 // used by clientConnPool
  7319  
  7320  	// readLoop goroutine fields:
  7321  	readerDone chan struct{} // closed on error
  7322  	readerErr  error         // set before readerDone is closed
  7323  
  7324  	idleTimeout time.Duration // or 0 for never
  7325  	idleTimer   *time.Timer
  7326  
  7327  	mu              sync.Mutex   // guards following
  7328  	cond            *sync.Cond   // hold mu; broadcast on flow/closed changes
  7329  	flow            http2outflow // our conn-level flow control quota (cs.outflow is per stream)
  7330  	inflow          http2inflow  // peer's conn-level flow control
  7331  	doNotReuse      bool         // whether conn is marked to not be reused for any future requests
  7332  	closing         bool
  7333  	closed          bool
  7334  	seenSettings    bool                          // true if we've seen a settings frame, false otherwise
  7335  	wantSettingsAck bool                          // we sent a SETTINGS frame and haven't heard back
  7336  	goAway          *http2GoAwayFrame             // if non-nil, the GoAwayFrame we received
  7337  	goAwayDebug     string                        // goAway frame's debug data, retained as a string
  7338  	streams         map[uint32]*http2clientStream // client-initiated
  7339  	streamsReserved int                           // incr by ReserveNewRequest; decr on RoundTrip
  7340  	nextStreamID    uint32
  7341  	pendingRequests int                       // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
  7342  	pings           map[[8]byte]chan struct{} // in flight ping data to notification channel
  7343  	br              *bufio.Reader
  7344  	lastActive      time.Time
  7345  	lastIdle        time.Time // time last idle
  7346  	// Settings from peer: (also guarded by wmu)
  7347  	maxFrameSize           uint32
  7348  	maxConcurrentStreams   uint32
  7349  	peerMaxHeaderListSize  uint64
  7350  	peerMaxHeaderTableSize uint32
  7351  	initialWindowSize      uint32
  7352  
  7353  	// reqHeaderMu is a 1-element semaphore channel controlling access to sending new requests.
  7354  	// Write to reqHeaderMu to lock it, read from it to unlock.
  7355  	// Lock reqmu BEFORE mu or wmu.
  7356  	reqHeaderMu chan struct{}
  7357  
  7358  	// wmu is held while writing.
  7359  	// Acquire BEFORE mu when holding both, to avoid blocking mu on network writes.
  7360  	// Only acquire both at the same time when changing peer settings.
  7361  	wmu  sync.Mutex
  7362  	bw   *bufio.Writer
  7363  	fr   *http2Framer
  7364  	werr error        // first write error that has occurred
  7365  	hbuf bytes.Buffer // HPACK encoder writes into this
  7366  	henc *hpack.Encoder
  7367  }
  7368  
  7369  // clientStream is the state for a single HTTP/2 stream. One of these
  7370  // is created for each Transport.RoundTrip call.
  7371  type http2clientStream struct {
  7372  	cc *http2ClientConn
  7373  
  7374  	// Fields of Request that we may access even after the response body is closed.
  7375  	ctx       context.Context
  7376  	reqCancel <-chan struct{}
  7377  
  7378  	trace         *httptrace.ClientTrace // or nil
  7379  	ID            uint32
  7380  	bufPipe       http2pipe // buffered pipe with the flow-controlled response payload
  7381  	requestedGzip bool
  7382  	isHead        bool
  7383  
  7384  	abortOnce sync.Once
  7385  	abort     chan struct{} // closed to signal stream should end immediately
  7386  	abortErr  error         // set if abort is closed
  7387  
  7388  	peerClosed chan struct{} // closed when the peer sends an END_STREAM flag
  7389  	donec      chan struct{} // closed after the stream is in the closed state
  7390  	on100      chan struct{} // buffered; written to if a 100 is received
  7391  
  7392  	respHeaderRecv chan struct{} // closed when headers are received
  7393  	res            *Response     // set if respHeaderRecv is closed
  7394  
  7395  	flow        http2outflow // guarded by cc.mu
  7396  	inflow      http2inflow  // guarded by cc.mu
  7397  	bytesRemain int64        // -1 means unknown; owned by transportResponseBody.Read
  7398  	readErr     error        // sticky read error; owned by transportResponseBody.Read
  7399  
  7400  	reqBody              io.ReadCloser
  7401  	reqBodyContentLength int64         // -1 means unknown
  7402  	reqBodyClosed        chan struct{} // guarded by cc.mu; non-nil on Close, closed when done
  7403  
  7404  	// owned by writeRequest:
  7405  	sentEndStream bool // sent an END_STREAM flag to the peer
  7406  	sentHeaders   bool
  7407  
  7408  	// owned by clientConnReadLoop:
  7409  	firstByte    bool  // got the first response byte
  7410  	pastHeaders  bool  // got first MetaHeadersFrame (actual headers)
  7411  	pastTrailers bool  // got optional second MetaHeadersFrame (trailers)
  7412  	num1xx       uint8 // number of 1xx responses seen
  7413  	readClosed   bool  // peer sent an END_STREAM flag
  7414  	readAborted  bool  // read loop reset the stream
  7415  
  7416  	trailer    Header  // accumulated trailers
  7417  	resTrailer *Header // client's Response.Trailer
  7418  }
  7419  
  7420  var http2got1xxFuncForTests func(int, textproto.MIMEHeader) error
  7421  
  7422  // get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
  7423  // if any. It returns nil if not set or if the Go version is too old.
  7424  func (cs *http2clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
  7425  	if fn := http2got1xxFuncForTests; fn != nil {
  7426  		return fn
  7427  	}
  7428  	return http2traceGot1xxResponseFunc(cs.trace)
  7429  }
  7430  
  7431  func (cs *http2clientStream) abortStream(err error) {
  7432  	cs.cc.mu.Lock()
  7433  	defer cs.cc.mu.Unlock()
  7434  	cs.abortStreamLocked(err)
  7435  }
  7436  
  7437  func (cs *http2clientStream) abortStreamLocked(err error) {
  7438  	cs.abortOnce.Do(func() {
  7439  		cs.abortErr = err
  7440  		close(cs.abort)
  7441  	})
  7442  	if cs.reqBody != nil {
  7443  		cs.closeReqBodyLocked()
  7444  	}
  7445  	// TODO(dneil): Clean up tests where cs.cc.cond is nil.
  7446  	if cs.cc.cond != nil {
  7447  		// Wake up writeRequestBody if it is waiting on flow control.
  7448  		cs.cc.cond.Broadcast()
  7449  	}
  7450  }
  7451  
  7452  func (cs *http2clientStream) abortRequestBodyWrite() {
  7453  	cc := cs.cc
  7454  	cc.mu.Lock()
  7455  	defer cc.mu.Unlock()
  7456  	if cs.reqBody != nil && cs.reqBodyClosed == nil {
  7457  		cs.closeReqBodyLocked()
  7458  		cc.cond.Broadcast()
  7459  	}
  7460  }
  7461  
  7462  func (cs *http2clientStream) closeReqBodyLocked() {
  7463  	if cs.reqBodyClosed != nil {
  7464  		return
  7465  	}
  7466  	cs.reqBodyClosed = make(chan struct{})
  7467  	reqBodyClosed := cs.reqBodyClosed
  7468  	go func() {
  7469  		cs.reqBody.Close()
  7470  		close(reqBodyClosed)
  7471  	}()
  7472  }
  7473  
  7474  type http2stickyErrWriter struct {
  7475  	conn    net.Conn
  7476  	timeout time.Duration
  7477  	err     *error
  7478  }
  7479  
  7480  func (sew http2stickyErrWriter) Write(p []byte) (n int, err error) {
  7481  	if *sew.err != nil {
  7482  		return 0, *sew.err
  7483  	}
  7484  	for {
  7485  		if sew.timeout != 0 {
  7486  			sew.conn.SetWriteDeadline(time.Now().Add(sew.timeout))
  7487  		}
  7488  		nn, err := sew.conn.Write(p[n:])
  7489  		n += nn
  7490  		if n < len(p) && nn > 0 && errors.Is(err, os.ErrDeadlineExceeded) {
  7491  			// Keep extending the deadline so long as we're making progress.
  7492  			continue
  7493  		}
  7494  		if sew.timeout != 0 {
  7495  			sew.conn.SetWriteDeadline(time.Time{})
  7496  		}
  7497  		*sew.err = err
  7498  		return n, err
  7499  	}
  7500  }
  7501  
  7502  // noCachedConnError is the concrete type of ErrNoCachedConn, which
  7503  // needs to be detected by net/http regardless of whether it's its
  7504  // bundled version (in h2_bundle.go with a rewritten type name) or
  7505  // from a user's x/net/http2. As such, as it has a unique method name
  7506  // (IsHTTP2NoCachedConnError) that net/http sniffs for via func
  7507  // isNoCachedConnError.
  7508  type http2noCachedConnError struct{}
  7509  
  7510  func (http2noCachedConnError) IsHTTP2NoCachedConnError() {}
  7511  
  7512  func (http2noCachedConnError) Error() string { return "http2: no cached connection was available" }
  7513  
  7514  // isNoCachedConnError reports whether err is of type noCachedConnError
  7515  // or its equivalent renamed type in net/http2's h2_bundle.go. Both types
  7516  // may coexist in the same running program.
  7517  func http2isNoCachedConnError(err error) bool {
  7518  	_, ok := err.(interface{ IsHTTP2NoCachedConnError() })
  7519  	return ok
  7520  }
  7521  
  7522  var http2ErrNoCachedConn error = http2noCachedConnError{}
  7523  
  7524  // RoundTripOpt are options for the Transport.RoundTripOpt method.
  7525  type http2RoundTripOpt struct {
  7526  	// OnlyCachedConn controls whether RoundTripOpt may
  7527  	// create a new TCP connection. If set true and
  7528  	// no cached connection is available, RoundTripOpt
  7529  	// will return ErrNoCachedConn.
  7530  	OnlyCachedConn bool
  7531  }
  7532  
  7533  func (t *http2Transport) RoundTrip(req *Request) (*Response, error) {
  7534  	return t.RoundTripOpt(req, http2RoundTripOpt{})
  7535  }
  7536  
  7537  // authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
  7538  // and returns a host:port. The port 443 is added if needed.
  7539  func http2authorityAddr(scheme string, authority string) (addr string) {
  7540  	host, port, err := net.SplitHostPort(authority)
  7541  	if err != nil { // authority didn't have a port
  7542  		port = "443"
  7543  		if scheme == "http" {
  7544  			port = "80"
  7545  		}
  7546  		host = authority
  7547  	}
  7548  	if a, err := idna.ToASCII(host); err == nil {
  7549  		host = a
  7550  	}
  7551  	// IPv6 address literal, without a port:
  7552  	if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  7553  		return host + ":" + port
  7554  	}
  7555  	return net.JoinHostPort(host, port)
  7556  }
  7557  
  7558  var http2retryBackoffHook func(time.Duration) *time.Timer
  7559  
  7560  func http2backoffNewTimer(d time.Duration) *time.Timer {
  7561  	if http2retryBackoffHook != nil {
  7562  		return http2retryBackoffHook(d)
  7563  	}
  7564  	return time.NewTimer(d)
  7565  }
  7566  
  7567  // RoundTripOpt is like RoundTrip, but takes options.
  7568  func (t *http2Transport) RoundTripOpt(req *Request, opt http2RoundTripOpt) (*Response, error) {
  7569  	if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
  7570  		return nil, errors.New("http2: unsupported scheme")
  7571  	}
  7572  
  7573  	addr := http2authorityAddr(req.URL.Scheme, req.URL.Host)
  7574  	for retry := 0; ; retry++ {
  7575  		cc, err := t.connPool().GetClientConn(req, addr)
  7576  		if err != nil {
  7577  			t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
  7578  			return nil, err
  7579  		}
  7580  		reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1)
  7581  		http2traceGotConn(req, cc, reused)
  7582  		res, err := cc.RoundTrip(req)
  7583  		if err != nil && retry <= 6 {
  7584  			roundTripErr := err
  7585  			if req, err = http2shouldRetryRequest(req, err); err == nil {
  7586  				// After the first retry, do exponential backoff with 10% jitter.
  7587  				if retry == 0 {
  7588  					t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
  7589  					continue
  7590  				}
  7591  				backoff := float64(uint(1) << (uint(retry) - 1))
  7592  				backoff += backoff * (0.1 * mathrand.Float64())
  7593  				d := time.Second * time.Duration(backoff)
  7594  				timer := http2backoffNewTimer(d)
  7595  				select {
  7596  				case <-timer.C:
  7597  					t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
  7598  					continue
  7599  				case <-req.Context().Done():
  7600  					timer.Stop()
  7601  					err = req.Context().Err()
  7602  				}
  7603  			}
  7604  		}
  7605  		if err != nil {
  7606  			t.vlogf("RoundTrip failure: %v", err)
  7607  			return nil, err
  7608  		}
  7609  		return res, nil
  7610  	}
  7611  }
  7612  
  7613  // CloseIdleConnections closes any connections which were previously
  7614  // connected from previous requests but are now sitting idle.
  7615  // It does not interrupt any connections currently in use.
  7616  func (t *http2Transport) CloseIdleConnections() {
  7617  	if cp, ok := t.connPool().(http2clientConnPoolIdleCloser); ok {
  7618  		cp.closeIdleConnections()
  7619  	}
  7620  }
  7621  
  7622  var (
  7623  	http2errClientConnClosed    = errors.New("http2: client conn is closed")
  7624  	http2errClientConnUnusable  = errors.New("http2: client conn not usable")
  7625  	http2errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
  7626  )
  7627  
  7628  // shouldRetryRequest is called by RoundTrip when a request fails to get
  7629  // response headers. It is always called with a non-nil error.
  7630  // It returns either a request to retry (either the same request, or a
  7631  // modified clone), or an error if the request can't be replayed.
  7632  func http2shouldRetryRequest(req *Request, err error) (*Request, error) {
  7633  	if !http2canRetryError(err) {
  7634  		return nil, err
  7635  	}
  7636  	// If the Body is nil (or http.NoBody), it's safe to reuse
  7637  	// this request and its Body.
  7638  	if req.Body == nil || req.Body == NoBody {
  7639  		return req, nil
  7640  	}
  7641  
  7642  	// If the request body can be reset back to its original
  7643  	// state via the optional req.GetBody, do that.
  7644  	if req.GetBody != nil {
  7645  		body, err := req.GetBody()
  7646  		if err != nil {
  7647  			return nil, err
  7648  		}
  7649  		newReq := *req
  7650  		newReq.Body = body
  7651  		return &newReq, nil
  7652  	}
  7653  
  7654  	// The Request.Body can't reset back to the beginning, but we
  7655  	// don't seem to have started to read from it yet, so reuse
  7656  	// the request directly.
  7657  	if err == http2errClientConnUnusable {
  7658  		return req, nil
  7659  	}
  7660  
  7661  	return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
  7662  }
  7663  
  7664  func http2canRetryError(err error) bool {
  7665  	if err == http2errClientConnUnusable || err == http2errClientConnGotGoAway {
  7666  		return true
  7667  	}
  7668  	if se, ok := err.(http2StreamError); ok {
  7669  		if se.Code == http2ErrCodeProtocol && se.Cause == http2errFromPeer {
  7670  			// See golang/go#47635, golang/go#42777
  7671  			return true
  7672  		}
  7673  		return se.Code == http2ErrCodeRefusedStream
  7674  	}
  7675  	return false
  7676  }
  7677  
  7678  func (t *http2Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*http2ClientConn, error) {
  7679  	host, _, err := net.SplitHostPort(addr)
  7680  	if err != nil {
  7681  		return nil, err
  7682  	}
  7683  	tconn, err := t.dialTLS(ctx, "tcp", addr, t.newTLSConfig(host))
  7684  	if err != nil {
  7685  		return nil, err
  7686  	}
  7687  	return t.newClientConn(tconn, singleUse)
  7688  }
  7689  
  7690  func (t *http2Transport) newTLSConfig(host string) *tls.Config {
  7691  	cfg := new(tls.Config)
  7692  	if t.TLSClientConfig != nil {
  7693  		*cfg = *t.TLSClientConfig.Clone()
  7694  	}
  7695  	if !http2strSliceContains(cfg.NextProtos, http2NextProtoTLS) {
  7696  		cfg.NextProtos = append([]string{http2NextProtoTLS}, cfg.NextProtos...)
  7697  	}
  7698  	if cfg.ServerName == "" {
  7699  		cfg.ServerName = host
  7700  	}
  7701  	return cfg
  7702  }
  7703  
  7704  func (t *http2Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) {
  7705  	if t.DialTLSContext != nil {
  7706  		return t.DialTLSContext(ctx, network, addr, tlsCfg)
  7707  	} else if t.DialTLS != nil {
  7708  		return t.DialTLS(network, addr, tlsCfg)
  7709  	}
  7710  
  7711  	tlsCn, err := t.dialTLSWithContext(ctx, network, addr, tlsCfg)
  7712  	if err != nil {
  7713  		return nil, err
  7714  	}
  7715  	state := tlsCn.ConnectionState()
  7716  	if p := state.NegotiatedProtocol; p != http2NextProtoTLS {
  7717  		return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, http2NextProtoTLS)
  7718  	}
  7719  	if !state.NegotiatedProtocolIsMutual {
  7720  		return nil, errors.New("http2: could not negotiate protocol mutually")
  7721  	}
  7722  	return tlsCn, nil
  7723  }
  7724  
  7725  // disableKeepAlives reports whether connections should be closed as
  7726  // soon as possible after handling the first request.
  7727  func (t *http2Transport) disableKeepAlives() bool {
  7728  	return t.t1 != nil && t.t1.DisableKeepAlives
  7729  }
  7730  
  7731  func (t *http2Transport) expectContinueTimeout() time.Duration {
  7732  	if t.t1 == nil {
  7733  		return 0
  7734  	}
  7735  	return t.t1.ExpectContinueTimeout
  7736  }
  7737  
  7738  func (t *http2Transport) maxDecoderHeaderTableSize() uint32 {
  7739  	if v := t.MaxDecoderHeaderTableSize; v > 0 {
  7740  		return v
  7741  	}
  7742  	return http2initialHeaderTableSize
  7743  }
  7744  
  7745  func (t *http2Transport) maxEncoderHeaderTableSize() uint32 {
  7746  	if v := t.MaxEncoderHeaderTableSize; v > 0 {
  7747  		return v
  7748  	}
  7749  	return http2initialHeaderTableSize
  7750  }
  7751  
  7752  func (t *http2Transport) NewClientConn(c net.Conn) (*http2ClientConn, error) {
  7753  	return t.newClientConn(c, t.disableKeepAlives())
  7754  }
  7755  
  7756  func (t *http2Transport) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error) {
  7757  	cc := &http2ClientConn{
  7758  		t:                     t,
  7759  		tconn:                 c,
  7760  		readerDone:            make(chan struct{}),
  7761  		nextStreamID:          1,
  7762  		maxFrameSize:          16 << 10,                         // spec default
  7763  		initialWindowSize:     65535,                            // spec default
  7764  		maxConcurrentStreams:  http2initialMaxConcurrentStreams, // "infinite", per spec. Use a smaller value until we have received server settings.
  7765  		peerMaxHeaderListSize: 0xffffffffffffffff,               // "infinite", per spec. Use 2^64-1 instead.
  7766  		streams:               make(map[uint32]*http2clientStream),
  7767  		singleUse:             singleUse,
  7768  		wantSettingsAck:       true,
  7769  		pings:                 make(map[[8]byte]chan struct{}),
  7770  		reqHeaderMu:           make(chan struct{}, 1),
  7771  	}
  7772  	if d := t.idleConnTimeout(); d != 0 {
  7773  		cc.idleTimeout = d
  7774  		cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
  7775  	}
  7776  	if http2VerboseLogs {
  7777  		t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
  7778  	}
  7779  
  7780  	cc.cond = sync.NewCond(&cc.mu)
  7781  	cc.flow.add(int32(http2initialWindowSize))
  7782  
  7783  	// TODO: adjust this writer size to account for frame size +
  7784  	// MTU + crypto/tls record padding.
  7785  	cc.bw = bufio.NewWriter(http2stickyErrWriter{
  7786  		conn:    c,
  7787  		timeout: t.WriteByteTimeout,
  7788  		err:     &cc.werr,
  7789  	})
  7790  	cc.br = bufio.NewReader(c)
  7791  	cc.fr = http2NewFramer(cc.bw, cc.br)
  7792  	if t.maxFrameReadSize() != 0 {
  7793  		cc.fr.SetMaxReadFrameSize(t.maxFrameReadSize())
  7794  	}
  7795  	if t.CountError != nil {
  7796  		cc.fr.countError = t.CountError
  7797  	}
  7798  	maxHeaderTableSize := t.maxDecoderHeaderTableSize()
  7799  	cc.fr.ReadMetaHeaders = hpack.NewDecoder(maxHeaderTableSize, nil)
  7800  	cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
  7801  
  7802  	cc.henc = hpack.NewEncoder(&cc.hbuf)
  7803  	cc.henc.SetMaxDynamicTableSizeLimit(t.maxEncoderHeaderTableSize())
  7804  	cc.peerMaxHeaderTableSize = http2initialHeaderTableSize
  7805  
  7806  	if t.AllowHTTP {
  7807  		cc.nextStreamID = 3
  7808  	}
  7809  
  7810  	if cs, ok := c.(http2connectionStater); ok {
  7811  		state := cs.ConnectionState()
  7812  		cc.tlsState = &state
  7813  	}
  7814  
  7815  	initialSettings := []http2Setting{
  7816  		{ID: http2SettingEnablePush, Val: 0},
  7817  		{ID: http2SettingInitialWindowSize, Val: http2transportDefaultStreamFlow},
  7818  	}
  7819  	if max := t.maxFrameReadSize(); max != 0 {
  7820  		initialSettings = append(initialSettings, http2Setting{ID: http2SettingMaxFrameSize, Val: max})
  7821  	}
  7822  	if max := t.maxHeaderListSize(); max != 0 {
  7823  		initialSettings = append(initialSettings, http2Setting{ID: http2SettingMaxHeaderListSize, Val: max})
  7824  	}
  7825  	if maxHeaderTableSize != http2initialHeaderTableSize {
  7826  		initialSettings = append(initialSettings, http2Setting{ID: http2SettingHeaderTableSize, Val: maxHeaderTableSize})
  7827  	}
  7828  
  7829  	cc.bw.Write(http2clientPreface)
  7830  	cc.fr.WriteSettings(initialSettings...)
  7831  	cc.fr.WriteWindowUpdate(0, http2transportDefaultConnFlow)
  7832  	cc.inflow.init(http2transportDefaultConnFlow + http2initialWindowSize)
  7833  	cc.bw.Flush()
  7834  	if cc.werr != nil {
  7835  		cc.Close()
  7836  		return nil, cc.werr
  7837  	}
  7838  
  7839  	go cc.readLoop()
  7840  	return cc, nil
  7841  }
  7842  
  7843  func (cc *http2ClientConn) healthCheck() {
  7844  	pingTimeout := cc.t.pingTimeout()
  7845  	// We don't need to periodically ping in the health check, because the readLoop of ClientConn will
  7846  	// trigger the healthCheck again if there is no frame received.
  7847  	ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
  7848  	defer cancel()
  7849  	cc.vlogf("http2: Transport sending health check")
  7850  	err := cc.Ping(ctx)
  7851  	if err != nil {
  7852  		cc.vlogf("http2: Transport health check failure: %v", err)
  7853  		cc.closeForLostPing()
  7854  	} else {
  7855  		cc.vlogf("http2: Transport health check success")
  7856  	}
  7857  }
  7858  
  7859  // SetDoNotReuse marks cc as not reusable for future HTTP requests.
  7860  func (cc *http2ClientConn) SetDoNotReuse() {
  7861  	cc.mu.Lock()
  7862  	defer cc.mu.Unlock()
  7863  	cc.doNotReuse = true
  7864  }
  7865  
  7866  func (cc *http2ClientConn) setGoAway(f *http2GoAwayFrame) {
  7867  	cc.mu.Lock()
  7868  	defer cc.mu.Unlock()
  7869  
  7870  	old := cc.goAway
  7871  	cc.goAway = f
  7872  
  7873  	// Merge the previous and current GoAway error frames.
  7874  	if cc.goAwayDebug == "" {
  7875  		cc.goAwayDebug = string(f.DebugData())
  7876  	}
  7877  	if old != nil && old.ErrCode != http2ErrCodeNo {
  7878  		cc.goAway.ErrCode = old.ErrCode
  7879  	}
  7880  	last := f.LastStreamID
  7881  	for streamID, cs := range cc.streams {
  7882  		if streamID > last {
  7883  			cs.abortStreamLocked(http2errClientConnGotGoAway)
  7884  		}
  7885  	}
  7886  }
  7887  
  7888  // CanTakeNewRequest reports whether the connection can take a new request,
  7889  // meaning it has not been closed or received or sent a GOAWAY.
  7890  //
  7891  // If the caller is going to immediately make a new request on this
  7892  // connection, use ReserveNewRequest instead.
  7893  func (cc *http2ClientConn) CanTakeNewRequest() bool {
  7894  	cc.mu.Lock()
  7895  	defer cc.mu.Unlock()
  7896  	return cc.canTakeNewRequestLocked()
  7897  }
  7898  
  7899  // ReserveNewRequest is like CanTakeNewRequest but also reserves a
  7900  // concurrent stream in cc. The reservation is decremented on the
  7901  // next call to RoundTrip.
  7902  func (cc *http2ClientConn) ReserveNewRequest() bool {
  7903  	cc.mu.Lock()
  7904  	defer cc.mu.Unlock()
  7905  	if st := cc.idleStateLocked(); !st.canTakeNewRequest {
  7906  		return false
  7907  	}
  7908  	cc.streamsReserved++
  7909  	return true
  7910  }
  7911  
  7912  // ClientConnState describes the state of a ClientConn.
  7913  type http2ClientConnState struct {
  7914  	// Closed is whether the connection is closed.
  7915  	Closed bool
  7916  
  7917  	// Closing is whether the connection is in the process of
  7918  	// closing. It may be closing due to shutdown, being a
  7919  	// single-use connection, being marked as DoNotReuse, or
  7920  	// having received a GOAWAY frame.
  7921  	Closing bool
  7922  
  7923  	// StreamsActive is how many streams are active.
  7924  	StreamsActive int
  7925  
  7926  	// StreamsReserved is how many streams have been reserved via
  7927  	// ClientConn.ReserveNewRequest.
  7928  	StreamsReserved int
  7929  
  7930  	// StreamsPending is how many requests have been sent in excess
  7931  	// of the peer's advertised MaxConcurrentStreams setting and
  7932  	// are waiting for other streams to complete.
  7933  	StreamsPending int
  7934  
  7935  	// MaxConcurrentStreams is how many concurrent streams the
  7936  	// peer advertised as acceptable. Zero means no SETTINGS
  7937  	// frame has been received yet.
  7938  	MaxConcurrentStreams uint32
  7939  
  7940  	// LastIdle, if non-zero, is when the connection last
  7941  	// transitioned to idle state.
  7942  	LastIdle time.Time
  7943  }
  7944  
  7945  // State returns a snapshot of cc's state.
  7946  func (cc *http2ClientConn) State() http2ClientConnState {
  7947  	cc.wmu.Lock()
  7948  	maxConcurrent := cc.maxConcurrentStreams
  7949  	if !cc.seenSettings {
  7950  		maxConcurrent = 0
  7951  	}
  7952  	cc.wmu.Unlock()
  7953  
  7954  	cc.mu.Lock()
  7955  	defer cc.mu.Unlock()
  7956  	return http2ClientConnState{
  7957  		Closed:               cc.closed,
  7958  		Closing:              cc.closing || cc.singleUse || cc.doNotReuse || cc.goAway != nil,
  7959  		StreamsActive:        len(cc.streams),
  7960  		StreamsReserved:      cc.streamsReserved,
  7961  		StreamsPending:       cc.pendingRequests,
  7962  		LastIdle:             cc.lastIdle,
  7963  		MaxConcurrentStreams: maxConcurrent,
  7964  	}
  7965  }
  7966  
  7967  // clientConnIdleState describes the suitability of a client
  7968  // connection to initiate a new RoundTrip request.
  7969  type http2clientConnIdleState struct {
  7970  	canTakeNewRequest bool
  7971  }
  7972  
  7973  func (cc *http2ClientConn) idleState() http2clientConnIdleState {
  7974  	cc.mu.Lock()
  7975  	defer cc.mu.Unlock()
  7976  	return cc.idleStateLocked()
  7977  }
  7978  
  7979  func (cc *http2ClientConn) idleStateLocked() (st http2clientConnIdleState) {
  7980  	if cc.singleUse && cc.nextStreamID > 1 {
  7981  		return
  7982  	}
  7983  	var maxConcurrentOkay bool
  7984  	if cc.t.StrictMaxConcurrentStreams {
  7985  		// We'll tell the caller we can take a new request to
  7986  		// prevent the caller from dialing a new TCP
  7987  		// connection, but then we'll block later before
  7988  		// writing it.
  7989  		maxConcurrentOkay = true
  7990  	} else {
  7991  		maxConcurrentOkay = int64(len(cc.streams)+cc.streamsReserved+1) <= int64(cc.maxConcurrentStreams)
  7992  	}
  7993  
  7994  	st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
  7995  		!cc.doNotReuse &&
  7996  		int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 &&
  7997  		!cc.tooIdleLocked()
  7998  	return
  7999  }
  8000  
  8001  func (cc *http2ClientConn) canTakeNewRequestLocked() bool {
  8002  	st := cc.idleStateLocked()
  8003  	return st.canTakeNewRequest
  8004  }
  8005  
  8006  // tooIdleLocked reports whether this connection has been been sitting idle
  8007  // for too much wall time.
  8008  func (cc *http2ClientConn) tooIdleLocked() bool {
  8009  	// The Round(0) strips the monontonic clock reading so the
  8010  	// times are compared based on their wall time. We don't want
  8011  	// to reuse a connection that's been sitting idle during
  8012  	// VM/laptop suspend if monotonic time was also frozen.
  8013  	return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout
  8014  }
  8015  
  8016  // onIdleTimeout is called from a time.AfterFunc goroutine. It will
  8017  // only be called when we're idle, but because we're coming from a new
  8018  // goroutine, there could be a new request coming in at the same time,
  8019  // so this simply calls the synchronized closeIfIdle to shut down this
  8020  // connection. The timer could just call closeIfIdle, but this is more
  8021  // clear.
  8022  func (cc *http2ClientConn) onIdleTimeout() {
  8023  	cc.closeIfIdle()
  8024  }
  8025  
  8026  func (cc *http2ClientConn) closeConn() {
  8027  	t := time.AfterFunc(250*time.Millisecond, cc.forceCloseConn)
  8028  	defer t.Stop()
  8029  	cc.tconn.Close()
  8030  }
  8031  
  8032  // A tls.Conn.Close can hang for a long time if the peer is unresponsive.
  8033  // Try to shut it down more aggressively.
  8034  func (cc *http2ClientConn) forceCloseConn() {
  8035  	tc, ok := cc.tconn.(*tls.Conn)
  8036  	if !ok {
  8037  		return
  8038  	}
  8039  	if nc := http2tlsUnderlyingConn(tc); nc != nil {
  8040  		nc.Close()
  8041  	}
  8042  }
  8043  
  8044  func (cc *http2ClientConn) closeIfIdle() {
  8045  	cc.mu.Lock()
  8046  	if len(cc.streams) > 0 || cc.streamsReserved > 0 {
  8047  		cc.mu.Unlock()
  8048  		return
  8049  	}
  8050  	cc.closed = true
  8051  	nextID := cc.nextStreamID
  8052  	// TODO: do clients send GOAWAY too? maybe? Just Close:
  8053  	cc.mu.Unlock()
  8054  
  8055  	if http2VerboseLogs {
  8056  		cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
  8057  	}
  8058  	cc.closeConn()
  8059  }
  8060  
  8061  func (cc *http2ClientConn) isDoNotReuseAndIdle() bool {
  8062  	cc.mu.Lock()
  8063  	defer cc.mu.Unlock()
  8064  	return cc.doNotReuse && len(cc.streams) == 0
  8065  }
  8066  
  8067  var http2shutdownEnterWaitStateHook = func() {}
  8068  
  8069  // Shutdown gracefully closes the client connection, waiting for running streams to complete.
  8070  func (cc *http2ClientConn) Shutdown(ctx context.Context) error {
  8071  	if err := cc.sendGoAway(); err != nil {
  8072  		return err
  8073  	}
  8074  	// Wait for all in-flight streams to complete or connection to close
  8075  	done := make(chan struct{})
  8076  	cancelled := false // guarded by cc.mu
  8077  	go func() {
  8078  		cc.mu.Lock()
  8079  		defer cc.mu.Unlock()
  8080  		for {
  8081  			if len(cc.streams) == 0 || cc.closed {
  8082  				cc.closed = true
  8083  				close(done)
  8084  				break
  8085  			}
  8086  			if cancelled {
  8087  				break
  8088  			}
  8089  			cc.cond.Wait()
  8090  		}
  8091  	}()
  8092  	http2shutdownEnterWaitStateHook()
  8093  	select {
  8094  	case <-done:
  8095  		cc.closeConn()
  8096  		return nil
  8097  	case <-ctx.Done():
  8098  		cc.mu.Lock()
  8099  		// Free the goroutine above
  8100  		cancelled = true
  8101  		cc.cond.Broadcast()
  8102  		cc.mu.Unlock()
  8103  		return ctx.Err()
  8104  	}
  8105  }
  8106  
  8107  func (cc *http2ClientConn) sendGoAway() error {
  8108  	cc.mu.Lock()
  8109  	closing := cc.closing
  8110  	cc.closing = true
  8111  	maxStreamID := cc.nextStreamID
  8112  	cc.mu.Unlock()
  8113  	if closing {
  8114  		// GOAWAY sent already
  8115  		return nil
  8116  	}
  8117  
  8118  	cc.wmu.Lock()
  8119  	defer cc.wmu.Unlock()
  8120  	// Send a graceful shutdown frame to server
  8121  	if err := cc.fr.WriteGoAway(maxStreamID, http2ErrCodeNo, nil); err != nil {
  8122  		return err
  8123  	}
  8124  	if err := cc.bw.Flush(); err != nil {
  8125  		return err
  8126  	}
  8127  	// Prevent new requests
  8128  	return nil
  8129  }
  8130  
  8131  // closes the client connection immediately. In-flight requests are interrupted.
  8132  // err is sent to streams.
  8133  func (cc *http2ClientConn) closeForError(err error) {
  8134  	cc.mu.Lock()
  8135  	cc.closed = true
  8136  	for _, cs := range cc.streams {
  8137  		cs.abortStreamLocked(err)
  8138  	}
  8139  	cc.cond.Broadcast()
  8140  	cc.mu.Unlock()
  8141  	cc.closeConn()
  8142  }
  8143  
  8144  // Close closes the client connection immediately.
  8145  //
  8146  // In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
  8147  func (cc *http2ClientConn) Close() error {
  8148  	err := errors.New("http2: client connection force closed via ClientConn.Close")
  8149  	cc.closeForError(err)
  8150  	return nil
  8151  }
  8152  
  8153  // closes the client connection immediately. In-flight requests are interrupted.
  8154  func (cc *http2ClientConn) closeForLostPing() {
  8155  	err := errors.New("http2: client connection lost")
  8156  	if f := cc.t.CountError; f != nil {
  8157  		f("conn_close_lost_ping")
  8158  	}
  8159  	cc.closeForError(err)
  8160  }
  8161  
  8162  // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
  8163  // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
  8164  var http2errRequestCanceled = errors.New("net/http: request canceled")
  8165  
  8166  func http2commaSeparatedTrailers(req *Request) (string, error) {
  8167  	keys := make([]string, 0, len(req.Trailer))
  8168  	for k := range req.Trailer {
  8169  		k = http2canonicalHeader(k)
  8170  		switch k {
  8171  		case "Transfer-Encoding", "Trailer", "Content-Length":
  8172  			return "", fmt.Errorf("invalid Trailer key %q", k)
  8173  		}
  8174  		keys = append(keys, k)
  8175  	}
  8176  	if len(keys) > 0 {
  8177  		sort.Strings(keys)
  8178  		return strings.Join(keys, ","), nil
  8179  	}
  8180  	return "", nil
  8181  }
  8182  
  8183  func (cc *http2ClientConn) responseHeaderTimeout() time.Duration {
  8184  	if cc.t.t1 != nil {
  8185  		return cc.t.t1.ResponseHeaderTimeout
  8186  	}
  8187  	// No way to do this (yet?) with just an http2.Transport. Probably
  8188  	// no need. Request.Cancel this is the new way. We only need to support
  8189  	// this for compatibility with the old http.Transport fields when
  8190  	// we're doing transparent http2.
  8191  	return 0
  8192  }
  8193  
  8194  // checkConnHeaders checks whether req has any invalid connection-level headers.
  8195  // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
  8196  // Certain headers are special-cased as okay but not transmitted later.
  8197  func http2checkConnHeaders(req *Request) error {
  8198  	if v := req.Header.Get("Upgrade"); v != "" {
  8199  		return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
  8200  	}
  8201  	if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
  8202  		return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
  8203  	}
  8204  	if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !http2asciiEqualFold(vv[0], "close") && !http2asciiEqualFold(vv[0], "keep-alive")) {
  8205  		return fmt.Errorf("http2: invalid Connection request header: %q", vv)
  8206  	}
  8207  	return nil
  8208  }
  8209  
  8210  // actualContentLength returns a sanitized version of
  8211  // req.ContentLength, where 0 actually means zero (not unknown) and -1
  8212  // means unknown.
  8213  func http2actualContentLength(req *Request) int64 {
  8214  	if req.Body == nil || req.Body == NoBody {
  8215  		return 0
  8216  	}
  8217  	if req.ContentLength != 0 {
  8218  		return req.ContentLength
  8219  	}
  8220  	return -1
  8221  }
  8222  
  8223  func (cc *http2ClientConn) decrStreamReservations() {
  8224  	cc.mu.Lock()
  8225  	defer cc.mu.Unlock()
  8226  	cc.decrStreamReservationsLocked()
  8227  }
  8228  
  8229  func (cc *http2ClientConn) decrStreamReservationsLocked() {
  8230  	if cc.streamsReserved > 0 {
  8231  		cc.streamsReserved--
  8232  	}
  8233  }
  8234  
  8235  func (cc *http2ClientConn) RoundTrip(req *Request) (*Response, error) {
  8236  	ctx := req.Context()
  8237  	cs := &http2clientStream{
  8238  		cc:                   cc,
  8239  		ctx:                  ctx,
  8240  		reqCancel:            req.Cancel,
  8241  		isHead:               req.Method == "HEAD",
  8242  		reqBody:              req.Body,
  8243  		reqBodyContentLength: http2actualContentLength(req),
  8244  		trace:                httptrace.ContextClientTrace(ctx),
  8245  		peerClosed:           make(chan struct{}),
  8246  		abort:                make(chan struct{}),
  8247  		respHeaderRecv:       make(chan struct{}),
  8248  		donec:                make(chan struct{}),
  8249  	}
  8250  	go cs.doRequest(req)
  8251  
  8252  	waitDone := func() error {
  8253  		select {
  8254  		case <-cs.donec:
  8255  			return nil
  8256  		case <-ctx.Done():
  8257  			return ctx.Err()
  8258  		case <-cs.reqCancel:
  8259  			return http2errRequestCanceled
  8260  		}
  8261  	}
  8262  
  8263  	handleResponseHeaders := func() (*Response, error) {
  8264  		res := cs.res
  8265  		if res.StatusCode > 299 {
  8266  			// On error or status code 3xx, 4xx, 5xx, etc abort any
  8267  			// ongoing write, assuming that the server doesn't care
  8268  			// about our request body. If the server replied with 1xx or
  8269  			// 2xx, however, then assume the server DOES potentially
  8270  			// want our body (e.g. full-duplex streaming:
  8271  			// golang.org/issue/13444). If it turns out the server
  8272  			// doesn't, they'll RST_STREAM us soon enough. This is a
  8273  			// heuristic to avoid adding knobs to Transport. Hopefully
  8274  			// we can keep it.
  8275  			cs.abortRequestBodyWrite()
  8276  		}
  8277  		res.Request = req
  8278  		res.TLS = cc.tlsState
  8279  		if res.Body == http2noBody && http2actualContentLength(req) == 0 {
  8280  			// If there isn't a request or response body still being
  8281  			// written, then wait for the stream to be closed before
  8282  			// RoundTrip returns.
  8283  			if err := waitDone(); err != nil {
  8284  				return nil, err
  8285  			}
  8286  		}
  8287  		return res, nil
  8288  	}
  8289  
  8290  	cancelRequest := func(cs *http2clientStream, err error) error {
  8291  		cs.cc.mu.Lock()
  8292  		defer cs.cc.mu.Unlock()
  8293  		cs.abortStreamLocked(err)
  8294  		if cs.ID != 0 {
  8295  			// This request may have failed because of a problem with the connection,
  8296  			// or for some unrelated reason. (For example, the user might have canceled
  8297  			// the request without waiting for a response.) Mark the connection as
  8298  			// not reusable, since trying to reuse a dead connection is worse than
  8299  			// unnecessarily creating a new one.
  8300  			//
  8301  			// If cs.ID is 0, then the request was never allocated a stream ID and
  8302  			// whatever went wrong was unrelated to the connection. We might have
  8303  			// timed out waiting for a stream slot when StrictMaxConcurrentStreams
  8304  			// is set, for example, in which case retrying on a different connection
  8305  			// will not help.
  8306  			cs.cc.doNotReuse = true
  8307  		}
  8308  		return err
  8309  	}
  8310  
  8311  	for {
  8312  		select {
  8313  		case <-cs.respHeaderRecv:
  8314  			return handleResponseHeaders()
  8315  		case <-cs.abort:
  8316  			select {
  8317  			case <-cs.respHeaderRecv:
  8318  				// If both cs.respHeaderRecv and cs.abort are signaling,
  8319  				// pick respHeaderRecv. The server probably wrote the
  8320  				// response and immediately reset the stream.
  8321  				// golang.org/issue/49645
  8322  				return handleResponseHeaders()
  8323  			default:
  8324  				waitDone()
  8325  				return nil, cancelRequest(cs, cs.abortErr)
  8326  			}
  8327  		case <-ctx.Done():
  8328  			return nil, cancelRequest(cs, ctx.Err())
  8329  		case <-cs.reqCancel:
  8330  			return nil, cancelRequest(cs, http2errRequestCanceled)
  8331  		}
  8332  	}
  8333  }
  8334  
  8335  // doRequest runs for the duration of the request lifetime.
  8336  //
  8337  // It sends the request and performs post-request cleanup (closing Request.Body, etc.).
  8338  func (cs *http2clientStream) doRequest(req *Request) {
  8339  	err := cs.writeRequest(req)
  8340  	cs.cleanupWriteRequest(err)
  8341  }
  8342  
  8343  // writeRequest sends a request.
  8344  //
  8345  // It returns nil after the request is written, the response read,
  8346  // and the request stream is half-closed by the peer.
  8347  //
  8348  // It returns non-nil if the request ends otherwise.
  8349  // If the returned error is StreamError, the error Code may be used in resetting the stream.
  8350  func (cs *http2clientStream) writeRequest(req *Request) (err error) {
  8351  	cc := cs.cc
  8352  	ctx := cs.ctx
  8353  
  8354  	if err := http2checkConnHeaders(req); err != nil {
  8355  		return err
  8356  	}
  8357  
  8358  	// Acquire the new-request lock by writing to reqHeaderMu.
  8359  	// This lock guards the critical section covering allocating a new stream ID
  8360  	// (requires mu) and creating the stream (requires wmu).
  8361  	if cc.reqHeaderMu == nil {
  8362  		panic("RoundTrip on uninitialized ClientConn") // for tests
  8363  	}
  8364  	select {
  8365  	case cc.reqHeaderMu <- struct{}{}:
  8366  	case <-cs.reqCancel:
  8367  		return http2errRequestCanceled
  8368  	case <-ctx.Done():
  8369  		return ctx.Err()
  8370  	}
  8371  
  8372  	cc.mu.Lock()
  8373  	if cc.idleTimer != nil {
  8374  		cc.idleTimer.Stop()
  8375  	}
  8376  	cc.decrStreamReservationsLocked()
  8377  	if err := cc.awaitOpenSlotForStreamLocked(cs); err != nil {
  8378  		cc.mu.Unlock()
  8379  		<-cc.reqHeaderMu
  8380  		return err
  8381  	}
  8382  	cc.addStreamLocked(cs) // assigns stream ID
  8383  	if http2isConnectionCloseRequest(req) {
  8384  		cc.doNotReuse = true
  8385  	}
  8386  	cc.mu.Unlock()
  8387  
  8388  	// TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
  8389  	if !cc.t.disableCompression() &&
  8390  		req.Header.Get("Accept-Encoding") == "" &&
  8391  		req.Header.Get("Range") == "" &&
  8392  		!cs.isHead {
  8393  		// Request gzip only, not deflate. Deflate is ambiguous and
  8394  		// not as universally supported anyway.
  8395  		// See: https://zlib.net/zlib_faq.html#faq39
  8396  		//
  8397  		// Note that we don't request this for HEAD requests,
  8398  		// due to a bug in nginx:
  8399  		//   http://trac.nginx.org/nginx/ticket/358
  8400  		//   https://golang.org/issue/5522
  8401  		//
  8402  		// We don't request gzip if the request is for a range, since
  8403  		// auto-decoding a portion of a gzipped document will just fail
  8404  		// anyway. See https://golang.org/issue/8923
  8405  		cs.requestedGzip = true
  8406  	}
  8407  
  8408  	continueTimeout := cc.t.expectContinueTimeout()
  8409  	if continueTimeout != 0 {
  8410  		if !httpguts.HeaderValuesContainsToken(req.Header["Expect"], "100-continue") {
  8411  			continueTimeout = 0
  8412  		} else {
  8413  			cs.on100 = make(chan struct{}, 1)
  8414  		}
  8415  	}
  8416  
  8417  	// Past this point (where we send request headers), it is possible for
  8418  	// RoundTrip to return successfully. Since the RoundTrip contract permits
  8419  	// the caller to "mutate or reuse" the Request after closing the Response's Body,
  8420  	// we must take care when referencing the Request from here on.
  8421  	err = cs.encodeAndWriteHeaders(req)
  8422  	<-cc.reqHeaderMu
  8423  	if err != nil {
  8424  		return err
  8425  	}
  8426  
  8427  	hasBody := cs.reqBodyContentLength != 0
  8428  	if !hasBody {
  8429  		cs.sentEndStream = true
  8430  	} else {
  8431  		if continueTimeout != 0 {
  8432  			http2traceWait100Continue(cs.trace)
  8433  			timer := time.NewTimer(continueTimeout)
  8434  			select {
  8435  			case <-timer.C:
  8436  				err = nil
  8437  			case <-cs.on100:
  8438  				err = nil
  8439  			case <-cs.abort:
  8440  				err = cs.abortErr
  8441  			case <-ctx.Done():
  8442  				err = ctx.Err()
  8443  			case <-cs.reqCancel:
  8444  				err = http2errRequestCanceled
  8445  			}
  8446  			timer.Stop()
  8447  			if err != nil {
  8448  				http2traceWroteRequest(cs.trace, err)
  8449  				return err
  8450  			}
  8451  		}
  8452  
  8453  		if err = cs.writeRequestBody(req); err != nil {
  8454  			if err != http2errStopReqBodyWrite {
  8455  				http2traceWroteRequest(cs.trace, err)
  8456  				return err
  8457  			}
  8458  		} else {
  8459  			cs.sentEndStream = true
  8460  		}
  8461  	}
  8462  
  8463  	http2traceWroteRequest(cs.trace, err)
  8464  
  8465  	var respHeaderTimer <-chan time.Time
  8466  	var respHeaderRecv chan struct{}
  8467  	if d := cc.responseHeaderTimeout(); d != 0 {
  8468  		timer := time.NewTimer(d)
  8469  		defer timer.Stop()
  8470  		respHeaderTimer = timer.C
  8471  		respHeaderRecv = cs.respHeaderRecv
  8472  	}
  8473  	// Wait until the peer half-closes its end of the stream,
  8474  	// or until the request is aborted (via context, error, or otherwise),
  8475  	// whichever comes first.
  8476  	for {
  8477  		select {
  8478  		case <-cs.peerClosed:
  8479  			return nil
  8480  		case <-respHeaderTimer:
  8481  			return http2errTimeout
  8482  		case <-respHeaderRecv:
  8483  			respHeaderRecv = nil
  8484  			respHeaderTimer = nil // keep waiting for END_STREAM
  8485  		case <-cs.abort:
  8486  			return cs.abortErr
  8487  		case <-ctx.Done():
  8488  			return ctx.Err()
  8489  		case <-cs.reqCancel:
  8490  			return http2errRequestCanceled
  8491  		}
  8492  	}
  8493  }
  8494  
  8495  func (cs *http2clientStream) encodeAndWriteHeaders(req *Request) error {
  8496  	cc := cs.cc
  8497  	ctx := cs.ctx
  8498  
  8499  	cc.wmu.Lock()
  8500  	defer cc.wmu.Unlock()
  8501  
  8502  	// If the request was canceled while waiting for cc.mu, just quit.
  8503  	select {
  8504  	case <-cs.abort:
  8505  		return cs.abortErr
  8506  	case <-ctx.Done():
  8507  		return ctx.Err()
  8508  	case <-cs.reqCancel:
  8509  		return http2errRequestCanceled
  8510  	default:
  8511  	}
  8512  
  8513  	// Encode headers.
  8514  	//
  8515  	// we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
  8516  	// sent by writeRequestBody below, along with any Trailers,
  8517  	// again in form HEADERS{1}, CONTINUATION{0,})
  8518  	trailers, err := http2commaSeparatedTrailers(req)
  8519  	if err != nil {
  8520  		return err
  8521  	}
  8522  	hasTrailers := trailers != ""
  8523  	contentLen := http2actualContentLength(req)
  8524  	hasBody := contentLen != 0
  8525  	hdrs, err := cc.encodeHeaders(req, cs.requestedGzip, trailers, contentLen)
  8526  	if err != nil {
  8527  		return err
  8528  	}
  8529  
  8530  	// Write the request.
  8531  	endStream := !hasBody && !hasTrailers
  8532  	cs.sentHeaders = true
  8533  	err = cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
  8534  	http2traceWroteHeaders(cs.trace)
  8535  	return err
  8536  }
  8537  
  8538  // cleanupWriteRequest performs post-request tasks.
  8539  //
  8540  // If err (the result of writeRequest) is non-nil and the stream is not closed,
  8541  // cleanupWriteRequest will send a reset to the peer.
  8542  func (cs *http2clientStream) cleanupWriteRequest(err error) {
  8543  	cc := cs.cc
  8544  
  8545  	if cs.ID == 0 {
  8546  		// We were canceled before creating the stream, so return our reservation.
  8547  		cc.decrStreamReservations()
  8548  	}
  8549  
  8550  	// TODO: write h12Compare test showing whether
  8551  	// Request.Body is closed by the Transport,
  8552  	// and in multiple cases: server replies <=299 and >299
  8553  	// while still writing request body
  8554  	cc.mu.Lock()
  8555  	mustCloseBody := false
  8556  	if cs.reqBody != nil && cs.reqBodyClosed == nil {
  8557  		mustCloseBody = true
  8558  		cs.reqBodyClosed = make(chan struct{})
  8559  	}
  8560  	bodyClosed := cs.reqBodyClosed
  8561  	cc.mu.Unlock()
  8562  	if mustCloseBody {
  8563  		cs.reqBody.Close()
  8564  		close(bodyClosed)
  8565  	}
  8566  	if bodyClosed != nil {
  8567  		<-bodyClosed
  8568  	}
  8569  
  8570  	if err != nil && cs.sentEndStream {
  8571  		// If the connection is closed immediately after the response is read,
  8572  		// we may be aborted before finishing up here. If the stream was closed
  8573  		// cleanly on both sides, there is no error.
  8574  		select {
  8575  		case <-cs.peerClosed:
  8576  			err = nil
  8577  		default:
  8578  		}
  8579  	}
  8580  	if err != nil {
  8581  		cs.abortStream(err) // possibly redundant, but harmless
  8582  		if cs.sentHeaders {
  8583  			if se, ok := err.(http2StreamError); ok {
  8584  				if se.Cause != http2errFromPeer {
  8585  					cc.writeStreamReset(cs.ID, se.Code, err)
  8586  				}
  8587  			} else {
  8588  				cc.writeStreamReset(cs.ID, http2ErrCodeCancel, err)
  8589  			}
  8590  		}
  8591  		cs.bufPipe.CloseWithError(err) // no-op if already closed
  8592  	} else {
  8593  		if cs.sentHeaders && !cs.sentEndStream {
  8594  			cc.writeStreamReset(cs.ID, http2ErrCodeNo, nil)
  8595  		}
  8596  		cs.bufPipe.CloseWithError(http2errRequestCanceled)
  8597  	}
  8598  	if cs.ID != 0 {
  8599  		cc.forgetStreamID(cs.ID)
  8600  	}
  8601  
  8602  	cc.wmu.Lock()
  8603  	werr := cc.werr
  8604  	cc.wmu.Unlock()
  8605  	if werr != nil {
  8606  		cc.Close()
  8607  	}
  8608  
  8609  	close(cs.donec)
  8610  }
  8611  
  8612  // awaitOpenSlotForStreamLocked waits until len(streams) < maxConcurrentStreams.
  8613  // Must hold cc.mu.
  8614  func (cc *http2ClientConn) awaitOpenSlotForStreamLocked(cs *http2clientStream) error {
  8615  	for {
  8616  		cc.lastActive = time.Now()
  8617  		if cc.closed || !cc.canTakeNewRequestLocked() {
  8618  			return http2errClientConnUnusable
  8619  		}
  8620  		cc.lastIdle = time.Time{}
  8621  		if int64(len(cc.streams)) < int64(cc.maxConcurrentStreams) {
  8622  			return nil
  8623  		}
  8624  		cc.pendingRequests++
  8625  		cc.cond.Wait()
  8626  		cc.pendingRequests--
  8627  		select {
  8628  		case <-cs.abort:
  8629  			return cs.abortErr
  8630  		default:
  8631  		}
  8632  	}
  8633  }
  8634  
  8635  // requires cc.wmu be held
  8636  func (cc *http2ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
  8637  	first := true // first frame written (HEADERS is first, then CONTINUATION)
  8638  	for len(hdrs) > 0 && cc.werr == nil {
  8639  		chunk := hdrs
  8640  		if len(chunk) > maxFrameSize {
  8641  			chunk = chunk[:maxFrameSize]
  8642  		}
  8643  		hdrs = hdrs[len(chunk):]
  8644  		endHeaders := len(hdrs) == 0
  8645  		if first {
  8646  			cc.fr.WriteHeaders(http2HeadersFrameParam{
  8647  				StreamID:      streamID,
  8648  				BlockFragment: chunk,
  8649  				EndStream:     endStream,
  8650  				EndHeaders:    endHeaders,
  8651  			})
  8652  			first = false
  8653  		} else {
  8654  			cc.fr.WriteContinuation(streamID, endHeaders, chunk)
  8655  		}
  8656  	}
  8657  	cc.bw.Flush()
  8658  	return cc.werr
  8659  }
  8660  
  8661  // internal error values; they don't escape to callers
  8662  var (
  8663  	// abort request body write; don't send cancel
  8664  	http2errStopReqBodyWrite = errors.New("http2: aborting request body write")
  8665  
  8666  	// abort request body write, but send stream reset of cancel.
  8667  	http2errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
  8668  
  8669  	http2errReqBodyTooLong = errors.New("http2: request body larger than specified content length")
  8670  )
  8671  
  8672  // frameScratchBufferLen returns the length of a buffer to use for
  8673  // outgoing request bodies to read/write to/from.
  8674  //
  8675  // It returns max(1, min(peer's advertised max frame size,
  8676  // Request.ContentLength+1, 512KB)).
  8677  func (cs *http2clientStream) frameScratchBufferLen(maxFrameSize int) int {
  8678  	const max = 512 << 10
  8679  	n := int64(maxFrameSize)
  8680  	if n > max {
  8681  		n = max
  8682  	}
  8683  	if cl := cs.reqBodyContentLength; cl != -1 && cl+1 < n {
  8684  		// Add an extra byte past the declared content-length to
  8685  		// give the caller's Request.Body io.Reader a chance to
  8686  		// give us more bytes than they declared, so we can catch it
  8687  		// early.
  8688  		n = cl + 1
  8689  	}
  8690  	if n < 1 {
  8691  		return 1
  8692  	}
  8693  	return int(n) // doesn't truncate; max is 512K
  8694  }
  8695  
  8696  var http2bufPool sync.Pool // of *[]byte
  8697  
  8698  func (cs *http2clientStream) writeRequestBody(req *Request) (err error) {
  8699  	cc := cs.cc
  8700  	body := cs.reqBody
  8701  	sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  8702  
  8703  	hasTrailers := req.Trailer != nil
  8704  	remainLen := cs.reqBodyContentLength
  8705  	hasContentLen := remainLen != -1
  8706  
  8707  	cc.mu.Lock()
  8708  	maxFrameSize := int(cc.maxFrameSize)
  8709  	cc.mu.Unlock()
  8710  
  8711  	// Scratch buffer for reading into & writing from.
  8712  	scratchLen := cs.frameScratchBufferLen(maxFrameSize)
  8713  	var buf []byte
  8714  	if bp, ok := http2bufPool.Get().(*[]byte); ok && len(*bp) >= scratchLen {
  8715  		defer http2bufPool.Put(bp)
  8716  		buf = *bp
  8717  	} else {
  8718  		buf = make([]byte, scratchLen)
  8719  		defer http2bufPool.Put(&buf)
  8720  	}
  8721  
  8722  	var sawEOF bool
  8723  	for !sawEOF {
  8724  		n, err := body.Read(buf)
  8725  		if hasContentLen {
  8726  			remainLen -= int64(n)
  8727  			if remainLen == 0 && err == nil {
  8728  				// The request body's Content-Length was predeclared and
  8729  				// we just finished reading it all, but the underlying io.Reader
  8730  				// returned the final chunk with a nil error (which is one of
  8731  				// the two valid things a Reader can do at EOF). Because we'd prefer
  8732  				// to send the END_STREAM bit early, double-check that we're actually
  8733  				// at EOF. Subsequent reads should return (0, EOF) at this point.
  8734  				// If either value is different, we return an error in one of two ways below.
  8735  				var scratch [1]byte
  8736  				var n1 int
  8737  				n1, err = body.Read(scratch[:])
  8738  				remainLen -= int64(n1)
  8739  			}
  8740  			if remainLen < 0 {
  8741  				err = http2errReqBodyTooLong
  8742  				return err
  8743  			}
  8744  		}
  8745  		if err != nil {
  8746  			cc.mu.Lock()
  8747  			bodyClosed := cs.reqBodyClosed != nil
  8748  			cc.mu.Unlock()
  8749  			switch {
  8750  			case bodyClosed:
  8751  				return http2errStopReqBodyWrite
  8752  			case err == io.EOF:
  8753  				sawEOF = true
  8754  				err = nil
  8755  			default:
  8756  				return err
  8757  			}
  8758  		}
  8759  
  8760  		remain := buf[:n]
  8761  		for len(remain) > 0 && err == nil {
  8762  			var allowed int32
  8763  			allowed, err = cs.awaitFlowControl(len(remain))
  8764  			if err != nil {
  8765  				return err
  8766  			}
  8767  			cc.wmu.Lock()
  8768  			data := remain[:allowed]
  8769  			remain = remain[allowed:]
  8770  			sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
  8771  			err = cc.fr.WriteData(cs.ID, sentEnd, data)
  8772  			if err == nil {
  8773  				// TODO(bradfitz): this flush is for latency, not bandwidth.
  8774  				// Most requests won't need this. Make this opt-in or
  8775  				// opt-out?  Use some heuristic on the body type? Nagel-like
  8776  				// timers?  Based on 'n'? Only last chunk of this for loop,
  8777  				// unless flow control tokens are low? For now, always.
  8778  				// If we change this, see comment below.
  8779  				err = cc.bw.Flush()
  8780  			}
  8781  			cc.wmu.Unlock()
  8782  		}
  8783  		if err != nil {
  8784  			return err
  8785  		}
  8786  	}
  8787  
  8788  	if sentEnd {
  8789  		// Already sent END_STREAM (which implies we have no
  8790  		// trailers) and flushed, because currently all
  8791  		// WriteData frames above get a flush. So we're done.
  8792  		return nil
  8793  	}
  8794  
  8795  	// Since the RoundTrip contract permits the caller to "mutate or reuse"
  8796  	// a request after the Response's Body is closed, verify that this hasn't
  8797  	// happened before accessing the trailers.
  8798  	cc.mu.Lock()
  8799  	trailer := req.Trailer
  8800  	err = cs.abortErr
  8801  	cc.mu.Unlock()
  8802  	if err != nil {
  8803  		return err
  8804  	}
  8805  
  8806  	cc.wmu.Lock()
  8807  	defer cc.wmu.Unlock()
  8808  	var trls []byte
  8809  	if len(trailer) > 0 {
  8810  		trls, err = cc.encodeTrailers(trailer)
  8811  		if err != nil {
  8812  			return err
  8813  		}
  8814  	}
  8815  
  8816  	// Two ways to send END_STREAM: either with trailers, or
  8817  	// with an empty DATA frame.
  8818  	if len(trls) > 0 {
  8819  		err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
  8820  	} else {
  8821  		err = cc.fr.WriteData(cs.ID, true, nil)
  8822  	}
  8823  	if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  8824  		err = ferr
  8825  	}
  8826  	return err
  8827  }
  8828  
  8829  // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  8830  // control tokens from the server.
  8831  // It returns either the non-zero number of tokens taken or an error
  8832  // if the stream is dead.
  8833  func (cs *http2clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  8834  	cc := cs.cc
  8835  	ctx := cs.ctx
  8836  	cc.mu.Lock()
  8837  	defer cc.mu.Unlock()
  8838  	for {
  8839  		if cc.closed {
  8840  			return 0, http2errClientConnClosed
  8841  		}
  8842  		if cs.reqBodyClosed != nil {
  8843  			return 0, http2errStopReqBodyWrite
  8844  		}
  8845  		select {
  8846  		case <-cs.abort:
  8847  			return 0, cs.abortErr
  8848  		case <-ctx.Done():
  8849  			return 0, ctx.Err()
  8850  		case <-cs.reqCancel:
  8851  			return 0, http2errRequestCanceled
  8852  		default:
  8853  		}
  8854  		if a := cs.flow.available(); a > 0 {
  8855  			take := a
  8856  			if int(take) > maxBytes {
  8857  
  8858  				take = int32(maxBytes) // can't truncate int; take is int32
  8859  			}
  8860  			if take > int32(cc.maxFrameSize) {
  8861  				take = int32(cc.maxFrameSize)
  8862  			}
  8863  			cs.flow.take(take)
  8864  			return take, nil
  8865  		}
  8866  		cc.cond.Wait()
  8867  	}
  8868  }
  8869  
  8870  var http2errNilRequestURL = errors.New("http2: Request.URI is nil")
  8871  
  8872  // requires cc.wmu be held.
  8873  func (cc *http2ClientConn) encodeHeaders(req *Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
  8874  	cc.hbuf.Reset()
  8875  	if req.URL == nil {
  8876  		return nil, http2errNilRequestURL
  8877  	}
  8878  
  8879  	host := req.Host
  8880  	if host == "" {
  8881  		host = req.URL.Host
  8882  	}
  8883  	host, err := httpguts.PunycodeHostPort(host)
  8884  	if err != nil {
  8885  		return nil, err
  8886  	}
  8887  
  8888  	var path string
  8889  	if req.Method != "CONNECT" {
  8890  		path = req.URL.RequestURI()
  8891  		if !http2validPseudoPath(path) {
  8892  			orig := path
  8893  			path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
  8894  			if !http2validPseudoPath(path) {
  8895  				if req.URL.Opaque != "" {
  8896  					return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
  8897  				} else {
  8898  					return nil, fmt.Errorf("invalid request :path %q", orig)
  8899  				}
  8900  			}
  8901  		}
  8902  	}
  8903  
  8904  	// Check for any invalid headers and return an error before we
  8905  	// potentially pollute our hpack state. (We want to be able to
  8906  	// continue to reuse the hpack encoder for future requests)
  8907  	for k, vv := range req.Header {
  8908  		if !httpguts.ValidHeaderFieldName(k) {
  8909  			return nil, fmt.Errorf("invalid HTTP header name %q", k)
  8910  		}
  8911  		for _, v := range vv {
  8912  			if !httpguts.ValidHeaderFieldValue(v) {
  8913  				// Don't include the value in the error, because it may be sensitive.
  8914  				return nil, fmt.Errorf("invalid HTTP header value for header %q", k)
  8915  			}
  8916  		}
  8917  	}
  8918  
  8919  	enumerateHeaders := func(f func(name, value string)) {
  8920  		// 8.1.2.3 Request Pseudo-Header Fields
  8921  		// The :path pseudo-header field includes the path and query parts of the
  8922  		// target URI (the path-absolute production and optionally a '?' character
  8923  		// followed by the query production (see Sections 3.3 and 3.4 of
  8924  		// [RFC3986]).
  8925  		f(":authority", host)
  8926  		m := req.Method
  8927  		if m == "" {
  8928  			m = MethodGet
  8929  		}
  8930  		f(":method", m)
  8931  		if req.Method != "CONNECT" {
  8932  			f(":path", path)
  8933  			f(":scheme", req.URL.Scheme)
  8934  		}
  8935  		if trailers != "" {
  8936  			f("trailer", trailers)
  8937  		}
  8938  
  8939  		var didUA bool
  8940  		for k, vv := range req.Header {
  8941  			if http2asciiEqualFold(k, "host") || http2asciiEqualFold(k, "content-length") {
  8942  				// Host is :authority, already sent.
  8943  				// Content-Length is automatic, set below.
  8944  				continue
  8945  			} else if http2asciiEqualFold(k, "connection") ||
  8946  				http2asciiEqualFold(k, "proxy-connection") ||
  8947  				http2asciiEqualFold(k, "transfer-encoding") ||
  8948  				http2asciiEqualFold(k, "upgrade") ||
  8949  				http2asciiEqualFold(k, "keep-alive") {
  8950  				// Per 8.1.2.2 Connection-Specific Header
  8951  				// Fields, don't send connection-specific
  8952  				// fields. We have already checked if any
  8953  				// are error-worthy so just ignore the rest.
  8954  				continue
  8955  			} else if http2asciiEqualFold(k, "user-agent") {
  8956  				// Match Go's http1 behavior: at most one
  8957  				// User-Agent. If set to nil or empty string,
  8958  				// then omit it. Otherwise if not mentioned,
  8959  				// include the default (below).
  8960  				didUA = true
  8961  				if len(vv) < 1 {
  8962  					continue
  8963  				}
  8964  				vv = vv[:1]
  8965  				if vv[0] == "" {
  8966  					continue
  8967  				}
  8968  			} else if http2asciiEqualFold(k, "cookie") {
  8969  				// Per 8.1.2.5 To allow for better compression efficiency, the
  8970  				// Cookie header field MAY be split into separate header fields,
  8971  				// each with one or more cookie-pairs.
  8972  				for _, v := range vv {
  8973  					for {
  8974  						p := strings.IndexByte(v, ';')
  8975  						if p < 0 {
  8976  							break
  8977  						}
  8978  						f("cookie", v[:p])
  8979  						p++
  8980  						// strip space after semicolon if any.
  8981  						for p+1 <= len(v) && v[p] == ' ' {
  8982  							p++
  8983  						}
  8984  						v = v[p:]
  8985  					}
  8986  					if len(v) > 0 {
  8987  						f("cookie", v)
  8988  					}
  8989  				}
  8990  				continue
  8991  			}
  8992  
  8993  			for _, v := range vv {
  8994  				f(k, v)
  8995  			}
  8996  		}
  8997  		if http2shouldSendReqContentLength(req.Method, contentLength) {
  8998  			f("content-length", strconv.FormatInt(contentLength, 10))
  8999  		}
  9000  		if addGzipHeader {
  9001  			f("accept-encoding", "gzip")
  9002  		}
  9003  		if !didUA {
  9004  			f("user-agent", http2defaultUserAgent)
  9005  		}
  9006  	}
  9007  
  9008  	// Do a first pass over the headers counting bytes to ensure
  9009  	// we don't exceed cc.peerMaxHeaderListSize. This is done as a
  9010  	// separate pass before encoding the headers to prevent
  9011  	// modifying the hpack state.
  9012  	hlSize := uint64(0)
  9013  	enumerateHeaders(func(name, value string) {
  9014  		hf := hpack.HeaderField{Name: name, Value: value}
  9015  		hlSize += uint64(hf.Size())
  9016  	})
  9017  
  9018  	if hlSize > cc.peerMaxHeaderListSize {
  9019  		return nil, http2errRequestHeaderListSize
  9020  	}
  9021  
  9022  	trace := httptrace.ContextClientTrace(req.Context())
  9023  	traceHeaders := http2traceHasWroteHeaderField(trace)
  9024  
  9025  	// Header list size is ok. Write the headers.
  9026  	enumerateHeaders(func(name, value string) {
  9027  		name, ascii := http2lowerHeader(name)
  9028  		if !ascii {
  9029  			// Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
  9030  			// field names have to be ASCII characters (just as in HTTP/1.x).
  9031  			return
  9032  		}
  9033  		cc.writeHeader(name, value)
  9034  		if traceHeaders {
  9035  			http2traceWroteHeaderField(trace, name, value)
  9036  		}
  9037  	})
  9038  
  9039  	return cc.hbuf.Bytes(), nil
  9040  }
  9041  
  9042  // shouldSendReqContentLength reports whether the http2.Transport should send
  9043  // a "content-length" request header. This logic is basically a copy of the net/http
  9044  // transferWriter.shouldSendContentLength.
  9045  // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  9046  // -1 means unknown.
  9047  func http2shouldSendReqContentLength(method string, contentLength int64) bool {
  9048  	if contentLength > 0 {
  9049  		return true
  9050  	}
  9051  	if contentLength < 0 {
  9052  		return false
  9053  	}
  9054  	// For zero bodies, whether we send a content-length depends on the method.
  9055  	// It also kinda doesn't matter for http2 either way, with END_STREAM.
  9056  	switch method {
  9057  	case "POST", "PUT", "PATCH":
  9058  		return true
  9059  	default:
  9060  		return false
  9061  	}
  9062  }
  9063  
  9064  // requires cc.wmu be held.
  9065  func (cc *http2ClientConn) encodeTrailers(trailer Header) ([]byte, error) {
  9066  	cc.hbuf.Reset()
  9067  
  9068  	hlSize := uint64(0)
  9069  	for k, vv := range trailer {
  9070  		for _, v := range vv {
  9071  			hf := hpack.HeaderField{Name: k, Value: v}
  9072  			hlSize += uint64(hf.Size())
  9073  		}
  9074  	}
  9075  	if hlSize > cc.peerMaxHeaderListSize {
  9076  		return nil, http2errRequestHeaderListSize
  9077  	}
  9078  
  9079  	for k, vv := range trailer {
  9080  		lowKey, ascii := http2lowerHeader(k)
  9081  		if !ascii {
  9082  			// Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
  9083  			// field names have to be ASCII characters (just as in HTTP/1.x).
  9084  			continue
  9085  		}
  9086  		// Transfer-Encoding, etc.. have already been filtered at the
  9087  		// start of RoundTrip
  9088  		for _, v := range vv {
  9089  			cc.writeHeader(lowKey, v)
  9090  		}
  9091  	}
  9092  	return cc.hbuf.Bytes(), nil
  9093  }
  9094  
  9095  func (cc *http2ClientConn) writeHeader(name, value string) {
  9096  	if http2VerboseLogs {
  9097  		log.Printf("http2: Transport encoding header %q = %q", name, value)
  9098  	}
  9099  	cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  9100  }
  9101  
  9102  type http2resAndError struct {
  9103  	_   http2incomparable
  9104  	res *Response
  9105  	err error
  9106  }
  9107  
  9108  // requires cc.mu be held.
  9109  func (cc *http2ClientConn) addStreamLocked(cs *http2clientStream) {
  9110  	cs.flow.add(int32(cc.initialWindowSize))
  9111  	cs.flow.setConnFlow(&cc.flow)
  9112  	cs.inflow.init(http2transportDefaultStreamFlow)
  9113  	cs.ID = cc.nextStreamID
  9114  	cc.nextStreamID += 2
  9115  	cc.streams[cs.ID] = cs
  9116  	if cs.ID == 0 {
  9117  		panic("assigned stream ID 0")
  9118  	}
  9119  }
  9120  
  9121  func (cc *http2ClientConn) forgetStreamID(id uint32) {
  9122  	cc.mu.Lock()
  9123  	slen := len(cc.streams)
  9124  	delete(cc.streams, id)
  9125  	if len(cc.streams) != slen-1 {
  9126  		panic("forgetting unknown stream id")
  9127  	}
  9128  	cc.lastActive = time.Now()
  9129  	if len(cc.streams) == 0 && cc.idleTimer != nil {
  9130  		cc.idleTimer.Reset(cc.idleTimeout)
  9131  		cc.lastIdle = time.Now()
  9132  	}
  9133  	// Wake up writeRequestBody via clientStream.awaitFlowControl and
  9134  	// wake up RoundTrip if there is a pending request.
  9135  	cc.cond.Broadcast()
  9136  
  9137  	closeOnIdle := cc.singleUse || cc.doNotReuse || cc.t.disableKeepAlives() || cc.goAway != nil
  9138  	if closeOnIdle && cc.streamsReserved == 0 && len(cc.streams) == 0 {
  9139  		if http2VerboseLogs {
  9140  			cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, cc.nextStreamID-2)
  9141  		}
  9142  		cc.closed = true
  9143  		defer cc.closeConn()
  9144  	}
  9145  
  9146  	cc.mu.Unlock()
  9147  }
  9148  
  9149  // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  9150  type http2clientConnReadLoop struct {
  9151  	_  http2incomparable
  9152  	cc *http2ClientConn
  9153  }
  9154  
  9155  // readLoop runs in its own goroutine and reads and dispatches frames.
  9156  func (cc *http2ClientConn) readLoop() {
  9157  	rl := &http2clientConnReadLoop{cc: cc}
  9158  	defer rl.cleanup()
  9159  	cc.readerErr = rl.run()
  9160  	if ce, ok := cc.readerErr.(http2ConnectionError); ok {
  9161  		cc.wmu.Lock()
  9162  		cc.fr.WriteGoAway(0, http2ErrCode(ce), nil)
  9163  		cc.wmu.Unlock()
  9164  	}
  9165  }
  9166  
  9167  // GoAwayError is returned by the Transport when the server closes the
  9168  // TCP connection after sending a GOAWAY frame.
  9169  type http2GoAwayError struct {
  9170  	LastStreamID uint32
  9171  	ErrCode      http2ErrCode
  9172  	DebugData    string
  9173  }
  9174  
  9175  func (e http2GoAwayError) Error() string {
  9176  	return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
  9177  		e.LastStreamID, e.ErrCode, e.DebugData)
  9178  }
  9179  
  9180  func http2isEOFOrNetReadError(err error) bool {
  9181  	if err == io.EOF {
  9182  		return true
  9183  	}
  9184  	ne, ok := err.(*net.OpError)
  9185  	return ok && ne.Op == "read"
  9186  }
  9187  
  9188  func (rl *http2clientConnReadLoop) cleanup() {
  9189  	cc := rl.cc
  9190  	cc.t.connPool().MarkDead(cc)
  9191  	defer cc.closeConn()
  9192  	defer close(cc.readerDone)
  9193  
  9194  	if cc.idleTimer != nil {
  9195  		cc.idleTimer.Stop()
  9196  	}
  9197  
  9198  	// Close any response bodies if the server closes prematurely.
  9199  	// TODO: also do this if we've written the headers but not
  9200  	// gotten a response yet.
  9201  	err := cc.readerErr
  9202  	cc.mu.Lock()
  9203  	if cc.goAway != nil && http2isEOFOrNetReadError(err) {
  9204  		err = http2GoAwayError{
  9205  			LastStreamID: cc.goAway.LastStreamID,
  9206  			ErrCode:      cc.goAway.ErrCode,
  9207  			DebugData:    cc.goAwayDebug,
  9208  		}
  9209  	} else if err == io.EOF {
  9210  		err = io.ErrUnexpectedEOF
  9211  	}
  9212  	cc.closed = true
  9213  
  9214  	for _, cs := range cc.streams {
  9215  		select {
  9216  		case <-cs.peerClosed:
  9217  			// The server closed the stream before closing the conn,
  9218  			// so no need to interrupt it.
  9219  		default:
  9220  			cs.abortStreamLocked(err)
  9221  		}
  9222  	}
  9223  	cc.cond.Broadcast()
  9224  	cc.mu.Unlock()
  9225  }
  9226  
  9227  // countReadFrameError calls Transport.CountError with a string
  9228  // representing err.
  9229  func (cc *http2ClientConn) countReadFrameError(err error) {
  9230  	f := cc.t.CountError
  9231  	if f == nil || err == nil {
  9232  		return
  9233  	}
  9234  	if ce, ok := err.(http2ConnectionError); ok {
  9235  		errCode := http2ErrCode(ce)
  9236  		f(fmt.Sprintf("read_frame_conn_error_%s", errCode.stringToken()))
  9237  		return
  9238  	}
  9239  	if errors.Is(err, io.EOF) {
  9240  		f("read_frame_eof")
  9241  		return
  9242  	}
  9243  	if errors.Is(err, io.ErrUnexpectedEOF) {
  9244  		f("read_frame_unexpected_eof")
  9245  		return
  9246  	}
  9247  	if errors.Is(err, http2ErrFrameTooLarge) {
  9248  		f("read_frame_too_large")
  9249  		return
  9250  	}
  9251  	f("read_frame_other")
  9252  }
  9253  
  9254  func (rl *http2clientConnReadLoop) run() error {
  9255  	cc := rl.cc
  9256  	gotSettings := false
  9257  	readIdleTimeout := cc.t.ReadIdleTimeout
  9258  	var t *time.Timer
  9259  	if readIdleTimeout != 0 {
  9260  		t = time.AfterFunc(readIdleTimeout, cc.healthCheck)
  9261  		defer t.Stop()
  9262  	}
  9263  	for {
  9264  		f, err := cc.fr.ReadFrame()
  9265  		if t != nil {
  9266  			t.Reset(readIdleTimeout)
  9267  		}
  9268  		if err != nil {
  9269  			cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
  9270  		}
  9271  		if se, ok := err.(http2StreamError); ok {
  9272  			if cs := rl.streamByID(se.StreamID); cs != nil {
  9273  				if se.Cause == nil {
  9274  					se.Cause = cc.fr.errDetail
  9275  				}
  9276  				rl.endStreamError(cs, se)
  9277  			}
  9278  			continue
  9279  		} else if err != nil {
  9280  			cc.countReadFrameError(err)
  9281  			return err
  9282  		}
  9283  		if http2VerboseLogs {
  9284  			cc.vlogf("http2: Transport received %s", http2summarizeFrame(f))
  9285  		}
  9286  		if !gotSettings {
  9287  			if _, ok := f.(*http2SettingsFrame); !ok {
  9288  				cc.logf("protocol error: received %T before a SETTINGS frame", f)
  9289  				return http2ConnectionError(http2ErrCodeProtocol)
  9290  			}
  9291  			gotSettings = true
  9292  		}
  9293  
  9294  		switch f := f.(type) {
  9295  		case *http2MetaHeadersFrame:
  9296  			err = rl.processHeaders(f)
  9297  		case *http2DataFrame:
  9298  			err = rl.processData(f)
  9299  		case *http2GoAwayFrame:
  9300  			err = rl.processGoAway(f)
  9301  		case *http2RSTStreamFrame:
  9302  			err = rl.processResetStream(f)
  9303  		case *http2SettingsFrame:
  9304  			err = rl.processSettings(f)
  9305  		case *http2PushPromiseFrame:
  9306  			err = rl.processPushPromise(f)
  9307  		case *http2WindowUpdateFrame:
  9308  			err = rl.processWindowUpdate(f)
  9309  		case *http2PingFrame:
  9310  			err = rl.processPing(f)
  9311  		default:
  9312  			cc.logf("Transport: unhandled response frame type %T", f)
  9313  		}
  9314  		if err != nil {
  9315  			if http2VerboseLogs {
  9316  				cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, http2summarizeFrame(f), err)
  9317  			}
  9318  			return err
  9319  		}
  9320  	}
  9321  }
  9322  
  9323  func (rl *http2clientConnReadLoop) processHeaders(f *http2MetaHeadersFrame) error {
  9324  	cs := rl.streamByID(f.StreamID)
  9325  	if cs == nil {
  9326  		// We'd get here if we canceled a request while the
  9327  		// server had its response still in flight. So if this
  9328  		// was just something we canceled, ignore it.
  9329  		return nil
  9330  	}
  9331  	if cs.readClosed {
  9332  		rl.endStreamError(cs, http2StreamError{
  9333  			StreamID: f.StreamID,
  9334  			Code:     http2ErrCodeProtocol,
  9335  			Cause:    errors.New("protocol error: headers after END_STREAM"),
  9336  		})
  9337  		return nil
  9338  	}
  9339  	if !cs.firstByte {
  9340  		if cs.trace != nil {
  9341  			// TODO(bradfitz): move first response byte earlier,
  9342  			// when we first read the 9 byte header, not waiting
  9343  			// until all the HEADERS+CONTINUATION frames have been
  9344  			// merged. This works for now.
  9345  			http2traceFirstResponseByte(cs.trace)
  9346  		}
  9347  		cs.firstByte = true
  9348  	}
  9349  	if !cs.pastHeaders {
  9350  		cs.pastHeaders = true
  9351  	} else {
  9352  		return rl.processTrailers(cs, f)
  9353  	}
  9354  
  9355  	res, err := rl.handleResponse(cs, f)
  9356  	if err != nil {
  9357  		if _, ok := err.(http2ConnectionError); ok {
  9358  			return err
  9359  		}
  9360  		// Any other error type is a stream error.
  9361  		rl.endStreamError(cs, http2StreamError{
  9362  			StreamID: f.StreamID,
  9363  			Code:     http2ErrCodeProtocol,
  9364  			Cause:    err,
  9365  		})
  9366  		return nil // return nil from process* funcs to keep conn alive
  9367  	}
  9368  	if res == nil {
  9369  		// (nil, nil) special case. See handleResponse docs.
  9370  		return nil
  9371  	}
  9372  	cs.resTrailer = &res.Trailer
  9373  	cs.res = res
  9374  	close(cs.respHeaderRecv)
  9375  	if f.StreamEnded() {
  9376  		rl.endStream(cs)
  9377  	}
  9378  	return nil
  9379  }
  9380  
  9381  // may return error types nil, or ConnectionError. Any other error value
  9382  // is a StreamError of type ErrCodeProtocol. The returned error in that case
  9383  // is the detail.
  9384  //
  9385  // As a special case, handleResponse may return (nil, nil) to skip the
  9386  // frame (currently only used for 1xx responses).
  9387  func (rl *http2clientConnReadLoop) handleResponse(cs *http2clientStream, f *http2MetaHeadersFrame) (*Response, error) {
  9388  	if f.Truncated {
  9389  		return nil, http2errResponseHeaderListSize
  9390  	}
  9391  
  9392  	status := f.PseudoValue("status")
  9393  	if status == "" {
  9394  		return nil, errors.New("malformed response from server: missing status pseudo header")
  9395  	}
  9396  	statusCode, err := strconv.Atoi(status)
  9397  	if err != nil {
  9398  		return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
  9399  	}
  9400  
  9401  	regularFields := f.RegularFields()
  9402  	strs := make([]string, len(regularFields))
  9403  	header := make(Header, len(regularFields))
  9404  	res := &Response{
  9405  		Proto:      "HTTP/2.0",
  9406  		ProtoMajor: 2,
  9407  		Header:     header,
  9408  		StatusCode: statusCode,
  9409  		Status:     status + " " + StatusText(statusCode),
  9410  	}
  9411  	for _, hf := range regularFields {
  9412  		key := http2canonicalHeader(hf.Name)
  9413  		if key == "Trailer" {
  9414  			t := res.Trailer
  9415  			if t == nil {
  9416  				t = make(Header)
  9417  				res.Trailer = t
  9418  			}
  9419  			http2foreachHeaderElement(hf.Value, func(v string) {
  9420  				t[http2canonicalHeader(v)] = nil
  9421  			})
  9422  		} else {
  9423  			vv := header[key]
  9424  			if vv == nil && len(strs) > 0 {
  9425  				// More than likely this will be a single-element key.
  9426  				// Most headers aren't multi-valued.
  9427  				// Set the capacity on strs[0] to 1, so any future append
  9428  				// won't extend the slice into the other strings.
  9429  				vv, strs = strs[:1:1], strs[1:]
  9430  				vv[0] = hf.Value
  9431  				header[key] = vv
  9432  			} else {
  9433  				header[key] = append(vv, hf.Value)
  9434  			}
  9435  		}
  9436  	}
  9437  
  9438  	if statusCode >= 100 && statusCode <= 199 {
  9439  		if f.StreamEnded() {
  9440  			return nil, errors.New("1xx informational response with END_STREAM flag")
  9441  		}
  9442  		cs.num1xx++
  9443  		const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http
  9444  		if cs.num1xx > max1xxResponses {
  9445  			return nil, errors.New("http2: too many 1xx informational responses")
  9446  		}
  9447  		if fn := cs.get1xxTraceFunc(); fn != nil {
  9448  			if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil {
  9449  				return nil, err
  9450  			}
  9451  		}
  9452  		if statusCode == 100 {
  9453  			http2traceGot100Continue(cs.trace)
  9454  			select {
  9455  			case cs.on100 <- struct{}{}:
  9456  			default:
  9457  			}
  9458  		}
  9459  		cs.pastHeaders = false // do it all again
  9460  		return nil, nil
  9461  	}
  9462  
  9463  	res.ContentLength = -1
  9464  	if clens := res.Header["Content-Length"]; len(clens) == 1 {
  9465  		if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
  9466  			res.ContentLength = int64(cl)
  9467  		} else {
  9468  			// TODO: care? unlike http/1, it won't mess up our framing, so it's
  9469  			// more safe smuggling-wise to ignore.
  9470  		}
  9471  	} else if len(clens) > 1 {
  9472  		// TODO: care? unlike http/1, it won't mess up our framing, so it's
  9473  		// more safe smuggling-wise to ignore.
  9474  	} else if f.StreamEnded() && !cs.isHead {
  9475  		res.ContentLength = 0
  9476  	}
  9477  
  9478  	if cs.isHead {
  9479  		res.Body = http2noBody
  9480  		return res, nil
  9481  	}
  9482  
  9483  	if f.StreamEnded() {
  9484  		if res.ContentLength > 0 {
  9485  			res.Body = http2missingBody{}
  9486  		} else {
  9487  			res.Body = http2noBody
  9488  		}
  9489  		return res, nil
  9490  	}
  9491  
  9492  	cs.bufPipe.setBuffer(&http2dataBuffer{expected: res.ContentLength})
  9493  	cs.bytesRemain = res.ContentLength
  9494  	res.Body = http2transportResponseBody{cs}
  9495  
  9496  	if cs.requestedGzip && http2asciiEqualFold(res.Header.Get("Content-Encoding"), "gzip") {
  9497  		res.Header.Del("Content-Encoding")
  9498  		res.Header.Del("Content-Length")
  9499  		res.ContentLength = -1
  9500  		res.Body = &http2gzipReader{body: res.Body}
  9501  		res.Uncompressed = true
  9502  	}
  9503  	return res, nil
  9504  }
  9505  
  9506  func (rl *http2clientConnReadLoop) processTrailers(cs *http2clientStream, f *http2MetaHeadersFrame) error {
  9507  	if cs.pastTrailers {
  9508  		// Too many HEADERS frames for this stream.
  9509  		return http2ConnectionError(http2ErrCodeProtocol)
  9510  	}
  9511  	cs.pastTrailers = true
  9512  	if !f.StreamEnded() {
  9513  		// We expect that any headers for trailers also
  9514  		// has END_STREAM.
  9515  		return http2ConnectionError(http2ErrCodeProtocol)
  9516  	}
  9517  	if len(f.PseudoFields()) > 0 {
  9518  		// No pseudo header fields are defined for trailers.
  9519  		// TODO: ConnectionError might be overly harsh? Check.
  9520  		return http2ConnectionError(http2ErrCodeProtocol)
  9521  	}
  9522  
  9523  	trailer := make(Header)
  9524  	for _, hf := range f.RegularFields() {
  9525  		key := http2canonicalHeader(hf.Name)
  9526  		trailer[key] = append(trailer[key], hf.Value)
  9527  	}
  9528  	cs.trailer = trailer
  9529  
  9530  	rl.endStream(cs)
  9531  	return nil
  9532  }
  9533  
  9534  // transportResponseBody is the concrete type of Transport.RoundTrip's
  9535  // Response.Body. It is an io.ReadCloser.
  9536  type http2transportResponseBody struct {
  9537  	cs *http2clientStream
  9538  }
  9539  
  9540  func (b http2transportResponseBody) Read(p []byte) (n int, err error) {
  9541  	cs := b.cs
  9542  	cc := cs.cc
  9543  
  9544  	if cs.readErr != nil {
  9545  		return 0, cs.readErr
  9546  	}
  9547  	n, err = b.cs.bufPipe.Read(p)
  9548  	if cs.bytesRemain != -1 {
  9549  		if int64(n) > cs.bytesRemain {
  9550  			n = int(cs.bytesRemain)
  9551  			if err == nil {
  9552  				err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  9553  				cs.abortStream(err)
  9554  			}
  9555  			cs.readErr = err
  9556  			return int(cs.bytesRemain), err
  9557  		}
  9558  		cs.bytesRemain -= int64(n)
  9559  		if err == io.EOF && cs.bytesRemain > 0 {
  9560  			err = io.ErrUnexpectedEOF
  9561  			cs.readErr = err
  9562  			return n, err
  9563  		}
  9564  	}
  9565  	if n == 0 {
  9566  		// No flow control tokens to send back.
  9567  		return
  9568  	}
  9569  
  9570  	cc.mu.Lock()
  9571  	connAdd := cc.inflow.add(n)
  9572  	var streamAdd int32
  9573  	if err == nil { // No need to refresh if the stream is over or failed.
  9574  		streamAdd = cs.inflow.add(n)
  9575  	}
  9576  	cc.mu.Unlock()
  9577  
  9578  	if connAdd != 0 || streamAdd != 0 {
  9579  		cc.wmu.Lock()
  9580  		defer cc.wmu.Unlock()
  9581  		if connAdd != 0 {
  9582  			cc.fr.WriteWindowUpdate(0, http2mustUint31(connAdd))
  9583  		}
  9584  		if streamAdd != 0 {
  9585  			cc.fr.WriteWindowUpdate(cs.ID, http2mustUint31(streamAdd))
  9586  		}
  9587  		cc.bw.Flush()
  9588  	}
  9589  	return
  9590  }
  9591  
  9592  var http2errClosedResponseBody = errors.New("http2: response body closed")
  9593  
  9594  func (b http2transportResponseBody) Close() error {
  9595  	cs := b.cs
  9596  	cc := cs.cc
  9597  
  9598  	cs.bufPipe.BreakWithError(http2errClosedResponseBody)
  9599  	cs.abortStream(http2errClosedResponseBody)
  9600  
  9601  	unread := cs.bufPipe.Len()
  9602  	if unread > 0 {
  9603  		cc.mu.Lock()
  9604  		// Return connection-level flow control.
  9605  		connAdd := cc.inflow.add(unread)
  9606  		cc.mu.Unlock()
  9607  
  9608  		// TODO(dneil): Acquiring this mutex can block indefinitely.
  9609  		// Move flow control return to a goroutine?
  9610  		cc.wmu.Lock()
  9611  		// Return connection-level flow control.
  9612  		if connAdd > 0 {
  9613  			cc.fr.WriteWindowUpdate(0, uint32(connAdd))
  9614  		}
  9615  		cc.bw.Flush()
  9616  		cc.wmu.Unlock()
  9617  	}
  9618  
  9619  	select {
  9620  	case <-cs.donec:
  9621  	case <-cs.ctx.Done():
  9622  		// See golang/go#49366: The net/http package can cancel the
  9623  		// request context after the response body is fully read.
  9624  		// Don't treat this as an error.
  9625  		return nil
  9626  	case <-cs.reqCancel:
  9627  		return http2errRequestCanceled
  9628  	}
  9629  	return nil
  9630  }
  9631  
  9632  func (rl *http2clientConnReadLoop) processData(f *http2DataFrame) error {
  9633  	cc := rl.cc
  9634  	cs := rl.streamByID(f.StreamID)
  9635  	data := f.Data()
  9636  	if cs == nil {
  9637  		cc.mu.Lock()
  9638  		neverSent := cc.nextStreamID
  9639  		cc.mu.Unlock()
  9640  		if f.StreamID >= neverSent {
  9641  			// We never asked for this.
  9642  			cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
  9643  			return http2ConnectionError(http2ErrCodeProtocol)
  9644  		}
  9645  		// We probably did ask for this, but canceled. Just ignore it.
  9646  		// TODO: be stricter here? only silently ignore things which
  9647  		// we canceled, but not things which were closed normally
  9648  		// by the peer? Tough without accumulating too much state.
  9649  
  9650  		// But at least return their flow control:
  9651  		if f.Length > 0 {
  9652  			cc.mu.Lock()
  9653  			ok := cc.inflow.take(f.Length)
  9654  			connAdd := cc.inflow.add(int(f.Length))
  9655  			cc.mu.Unlock()
  9656  			if !ok {
  9657  				return http2ConnectionError(http2ErrCodeFlowControl)
  9658  			}
  9659  			if connAdd > 0 {
  9660  				cc.wmu.Lock()
  9661  				cc.fr.WriteWindowUpdate(0, uint32(connAdd))
  9662  				cc.bw.Flush()
  9663  				cc.wmu.Unlock()
  9664  			}
  9665  		}
  9666  		return nil
  9667  	}
  9668  	if cs.readClosed {
  9669  		cc.logf("protocol error: received DATA after END_STREAM")
  9670  		rl.endStreamError(cs, http2StreamError{
  9671  			StreamID: f.StreamID,
  9672  			Code:     http2ErrCodeProtocol,
  9673  		})
  9674  		return nil
  9675  	}
  9676  	if !cs.firstByte {
  9677  		cc.logf("protocol error: received DATA before a HEADERS frame")
  9678  		rl.endStreamError(cs, http2StreamError{
  9679  			StreamID: f.StreamID,
  9680  			Code:     http2ErrCodeProtocol,
  9681  		})
  9682  		return nil
  9683  	}
  9684  	if f.Length > 0 {
  9685  		if cs.isHead && len(data) > 0 {
  9686  			cc.logf("protocol error: received DATA on a HEAD request")
  9687  			rl.endStreamError(cs, http2StreamError{
  9688  				StreamID: f.StreamID,
  9689  				Code:     http2ErrCodeProtocol,
  9690  			})
  9691  			return nil
  9692  		}
  9693  		// Check connection-level flow control.
  9694  		cc.mu.Lock()
  9695  		if !http2takeInflows(&cc.inflow, &cs.inflow, f.Length) {
  9696  			cc.mu.Unlock()
  9697  			return http2ConnectionError(http2ErrCodeFlowControl)
  9698  		}
  9699  		// Return any padded flow control now, since we won't
  9700  		// refund it later on body reads.
  9701  		var refund int
  9702  		if pad := int(f.Length) - len(data); pad > 0 {
  9703  			refund += pad
  9704  		}
  9705  
  9706  		didReset := false
  9707  		var err error
  9708  		if len(data) > 0 {
  9709  			if _, err = cs.bufPipe.Write(data); err != nil {
  9710  				// Return len(data) now if the stream is already closed,
  9711  				// since data will never be read.
  9712  				didReset = true
  9713  				refund += len(data)
  9714  			}
  9715  		}
  9716  
  9717  		sendConn := cc.inflow.add(refund)
  9718  		var sendStream int32
  9719  		if !didReset {
  9720  			sendStream = cs.inflow.add(refund)
  9721  		}
  9722  		cc.mu.Unlock()
  9723  
  9724  		if sendConn > 0 || sendStream > 0 {
  9725  			cc.wmu.Lock()
  9726  			if sendConn > 0 {
  9727  				cc.fr.WriteWindowUpdate(0, uint32(sendConn))
  9728  			}
  9729  			if sendStream > 0 {
  9730  				cc.fr.WriteWindowUpdate(cs.ID, uint32(sendStream))
  9731  			}
  9732  			cc.bw.Flush()
  9733  			cc.wmu.Unlock()
  9734  		}
  9735  
  9736  		if err != nil {
  9737  			rl.endStreamError(cs, err)
  9738  			return nil
  9739  		}
  9740  	}
  9741  
  9742  	if f.StreamEnded() {
  9743  		rl.endStream(cs)
  9744  	}
  9745  	return nil
  9746  }
  9747  
  9748  func (rl *http2clientConnReadLoop) endStream(cs *http2clientStream) {
  9749  	// TODO: check that any declared content-length matches, like
  9750  	// server.go's (*stream).endStream method.
  9751  	if !cs.readClosed {
  9752  		cs.readClosed = true
  9753  		// Close cs.bufPipe and cs.peerClosed with cc.mu held to avoid a
  9754  		// race condition: The caller can read io.EOF from Response.Body
  9755  		// and close the body before we close cs.peerClosed, causing
  9756  		// cleanupWriteRequest to send a RST_STREAM.
  9757  		rl.cc.mu.Lock()
  9758  		defer rl.cc.mu.Unlock()
  9759  		cs.bufPipe.closeWithErrorAndCode(io.EOF, cs.copyTrailers)
  9760  		close(cs.peerClosed)
  9761  	}
  9762  }
  9763  
  9764  func (rl *http2clientConnReadLoop) endStreamError(cs *http2clientStream, err error) {
  9765  	cs.readAborted = true
  9766  	cs.abortStream(err)
  9767  }
  9768  
  9769  func (rl *http2clientConnReadLoop) streamByID(id uint32) *http2clientStream {
  9770  	rl.cc.mu.Lock()
  9771  	defer rl.cc.mu.Unlock()
  9772  	cs := rl.cc.streams[id]
  9773  	if cs != nil && !cs.readAborted {
  9774  		return cs
  9775  	}
  9776  	return nil
  9777  }
  9778  
  9779  func (cs *http2clientStream) copyTrailers() {
  9780  	for k, vv := range cs.trailer {
  9781  		t := cs.resTrailer
  9782  		if *t == nil {
  9783  			*t = make(Header)
  9784  		}
  9785  		(*t)[k] = vv
  9786  	}
  9787  }
  9788  
  9789  func (rl *http2clientConnReadLoop) processGoAway(f *http2GoAwayFrame) error {
  9790  	cc := rl.cc
  9791  	cc.t.connPool().MarkDead(cc)
  9792  	if f.ErrCode != 0 {
  9793  		// TODO: deal with GOAWAY more. particularly the error code
  9794  		cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  9795  		if fn := cc.t.CountError; fn != nil {
  9796  			fn("recv_goaway_" + f.ErrCode.stringToken())
  9797  		}
  9798  	}
  9799  	cc.setGoAway(f)
  9800  	return nil
  9801  }
  9802  
  9803  func (rl *http2clientConnReadLoop) processSettings(f *http2SettingsFrame) error {
  9804  	cc := rl.cc
  9805  	// Locking both mu and wmu here allows frame encoding to read settings with only wmu held.
  9806  	// Acquiring wmu when f.IsAck() is unnecessary, but convenient and mostly harmless.
  9807  	cc.wmu.Lock()
  9808  	defer cc.wmu.Unlock()
  9809  
  9810  	if err := rl.processSettingsNoWrite(f); err != nil {
  9811  		return err
  9812  	}
  9813  	if !f.IsAck() {
  9814  		cc.fr.WriteSettingsAck()
  9815  		cc.bw.Flush()
  9816  	}
  9817  	return nil
  9818  }
  9819  
  9820  func (rl *http2clientConnReadLoop) processSettingsNoWrite(f *http2SettingsFrame) error {
  9821  	cc := rl.cc
  9822  	cc.mu.Lock()
  9823  	defer cc.mu.Unlock()
  9824  
  9825  	if f.IsAck() {
  9826  		if cc.wantSettingsAck {
  9827  			cc.wantSettingsAck = false
  9828  			return nil
  9829  		}
  9830  		return http2ConnectionError(http2ErrCodeProtocol)
  9831  	}
  9832  
  9833  	var seenMaxConcurrentStreams bool
  9834  	err := f.ForeachSetting(func(s http2Setting) error {
  9835  		switch s.ID {
  9836  		case http2SettingMaxFrameSize:
  9837  			cc.maxFrameSize = s.Val
  9838  		case http2SettingMaxConcurrentStreams:
  9839  			cc.maxConcurrentStreams = s.Val
  9840  			seenMaxConcurrentStreams = true
  9841  		case http2SettingMaxHeaderListSize:
  9842  			cc.peerMaxHeaderListSize = uint64(s.Val)
  9843  		case http2SettingInitialWindowSize:
  9844  			// Values above the maximum flow-control
  9845  			// window size of 2^31-1 MUST be treated as a
  9846  			// connection error (Section 5.4.1) of type
  9847  			// FLOW_CONTROL_ERROR.
  9848  			if s.Val > math.MaxInt32 {
  9849  				return http2ConnectionError(http2ErrCodeFlowControl)
  9850  			}
  9851  
  9852  			// Adjust flow control of currently-open
  9853  			// frames by the difference of the old initial
  9854  			// window size and this one.
  9855  			delta := int32(s.Val) - int32(cc.initialWindowSize)
  9856  			for _, cs := range cc.streams {
  9857  				cs.flow.add(delta)
  9858  			}
  9859  			cc.cond.Broadcast()
  9860  
  9861  			cc.initialWindowSize = s.Val
  9862  		case http2SettingHeaderTableSize:
  9863  			cc.henc.SetMaxDynamicTableSize(s.Val)
  9864  			cc.peerMaxHeaderTableSize = s.Val
  9865  		default:
  9866  			cc.vlogf("Unhandled Setting: %v", s)
  9867  		}
  9868  		return nil
  9869  	})
  9870  	if err != nil {
  9871  		return err
  9872  	}
  9873  
  9874  	if !cc.seenSettings {
  9875  		if !seenMaxConcurrentStreams {
  9876  			// This was the servers initial SETTINGS frame and it
  9877  			// didn't contain a MAX_CONCURRENT_STREAMS field so
  9878  			// increase the number of concurrent streams this
  9879  			// connection can establish to our default.
  9880  			cc.maxConcurrentStreams = http2defaultMaxConcurrentStreams
  9881  		}
  9882  		cc.seenSettings = true
  9883  	}
  9884  
  9885  	return nil
  9886  }
  9887  
  9888  func (rl *http2clientConnReadLoop) processWindowUpdate(f *http2WindowUpdateFrame) error {
  9889  	cc := rl.cc
  9890  	cs := rl.streamByID(f.StreamID)
  9891  	if f.StreamID != 0 && cs == nil {
  9892  		return nil
  9893  	}
  9894  
  9895  	cc.mu.Lock()
  9896  	defer cc.mu.Unlock()
  9897  
  9898  	fl := &cc.flow
  9899  	if cs != nil {
  9900  		fl = &cs.flow
  9901  	}
  9902  	if !fl.add(int32(f.Increment)) {
  9903  		return http2ConnectionError(http2ErrCodeFlowControl)
  9904  	}
  9905  	cc.cond.Broadcast()
  9906  	return nil
  9907  }
  9908  
  9909  func (rl *http2clientConnReadLoop) processResetStream(f *http2RSTStreamFrame) error {
  9910  	cs := rl.streamByID(f.StreamID)
  9911  	if cs == nil {
  9912  		// TODO: return error if server tries to RST_STREAM an idle stream
  9913  		return nil
  9914  	}
  9915  	serr := http2streamError(cs.ID, f.ErrCode)
  9916  	serr.Cause = http2errFromPeer
  9917  	if f.ErrCode == http2ErrCodeProtocol {
  9918  		rl.cc.SetDoNotReuse()
  9919  	}
  9920  	if fn := cs.cc.t.CountError; fn != nil {
  9921  		fn("recv_rststream_" + f.ErrCode.stringToken())
  9922  	}
  9923  	cs.abortStream(serr)
  9924  
  9925  	cs.bufPipe.CloseWithError(serr)
  9926  	return nil
  9927  }
  9928  
  9929  // Ping sends a PING frame to the server and waits for the ack.
  9930  func (cc *http2ClientConn) Ping(ctx context.Context) error {
  9931  	c := make(chan struct{})
  9932  	// Generate a random payload
  9933  	var p [8]byte
  9934  	for {
  9935  		if _, err := rand.Read(p[:]); err != nil {
  9936  			return err
  9937  		}
  9938  		cc.mu.Lock()
  9939  		// check for dup before insert
  9940  		if _, found := cc.pings[p]; !found {
  9941  			cc.pings[p] = c
  9942  			cc.mu.Unlock()
  9943  			break
  9944  		}
  9945  		cc.mu.Unlock()
  9946  	}
  9947  	errc := make(chan error, 1)
  9948  	go func() {
  9949  		cc.wmu.Lock()
  9950  		defer cc.wmu.Unlock()
  9951  		if err := cc.fr.WritePing(false, p); err != nil {
  9952  			errc <- err
  9953  			return
  9954  		}
  9955  		if err := cc.bw.Flush(); err != nil {
  9956  			errc <- err
  9957  			return
  9958  		}
  9959  	}()
  9960  	select {
  9961  	case <-c:
  9962  		return nil
  9963  	case err := <-errc:
  9964  		return err
  9965  	case <-ctx.Done():
  9966  		return ctx.Err()
  9967  	case <-cc.readerDone:
  9968  		// connection closed
  9969  		return cc.readerErr
  9970  	}
  9971  }
  9972  
  9973  func (rl *http2clientConnReadLoop) processPing(f *http2PingFrame) error {
  9974  	if f.IsAck() {
  9975  		cc := rl.cc
  9976  		cc.mu.Lock()
  9977  		defer cc.mu.Unlock()
  9978  		// If ack, notify listener if any
  9979  		if c, ok := cc.pings[f.Data]; ok {
  9980  			close(c)
  9981  			delete(cc.pings, f.Data)
  9982  		}
  9983  		return nil
  9984  	}
  9985  	cc := rl.cc
  9986  	cc.wmu.Lock()
  9987  	defer cc.wmu.Unlock()
  9988  	if err := cc.fr.WritePing(true, f.Data); err != nil {
  9989  		return err
  9990  	}
  9991  	return cc.bw.Flush()
  9992  }
  9993  
  9994  func (rl *http2clientConnReadLoop) processPushPromise(f *http2PushPromiseFrame) error {
  9995  	// We told the peer we don't want them.
  9996  	// Spec says:
  9997  	// "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  9998  	// setting of the peer endpoint is set to 0. An endpoint that
  9999  	// has set this setting and has received acknowledgement MUST
 10000  	// treat the receipt of a PUSH_PROMISE frame as a connection
 10001  	// error (Section 5.4.1) of type PROTOCOL_ERROR."
 10002  	return http2ConnectionError(http2ErrCodeProtocol)
 10003  }
 10004  
 10005  func (cc *http2ClientConn) writeStreamReset(streamID uint32, code http2ErrCode, err error) {
 10006  	// TODO: map err to more interesting error codes, once the
 10007  	// HTTP community comes up with some. But currently for
 10008  	// RST_STREAM there's no equivalent to GOAWAY frame's debug
 10009  	// data, and the error codes are all pretty vague ("cancel").
 10010  	cc.wmu.Lock()
 10011  	cc.fr.WriteRSTStream(streamID, code)
 10012  	cc.bw.Flush()
 10013  	cc.wmu.Unlock()
 10014  }
 10015  
 10016  var (
 10017  	http2errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
 10018  	http2errRequestHeaderListSize  = errors.New("http2: request header list larger than peer's advertised limit")
 10019  )
 10020  
 10021  func (cc *http2ClientConn) logf(format string, args ...interface{}) {
 10022  	cc.t.logf(format, args...)
 10023  }
 10024  
 10025  func (cc *http2ClientConn) vlogf(format string, args ...interface{}) {
 10026  	cc.t.vlogf(format, args...)
 10027  }
 10028  
 10029  func (t *http2Transport) vlogf(format string, args ...interface{}) {
 10030  	if http2VerboseLogs {
 10031  		t.logf(format, args...)
 10032  	}
 10033  }
 10034  
 10035  func (t *http2Transport) logf(format string, args ...interface{}) {
 10036  	log.Printf(format, args...)
 10037  }
 10038  
 10039  var http2noBody io.ReadCloser = http2noBodyReader{}
 10040  
 10041  type http2noBodyReader struct{}
 10042  
 10043  func (http2noBodyReader) Close() error { return nil }
 10044  
 10045  func (http2noBodyReader) Read([]byte) (int, error) { return 0, io.EOF }
 10046  
 10047  type http2missingBody struct{}
 10048  
 10049  func (http2missingBody) Close() error { return nil }
 10050  
 10051  func (http2missingBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
 10052  
 10053  func http2strSliceContains(ss []string, s string) bool {
 10054  	for _, v := range ss {
 10055  		if v == s {
 10056  			return true
 10057  		}
 10058  	}
 10059  	return false
 10060  }
 10061  
 10062  type http2erringRoundTripper struct{ err error }
 10063  
 10064  func (rt http2erringRoundTripper) RoundTripErr() error { return rt.err }
 10065  
 10066  func (rt http2erringRoundTripper) RoundTrip(*Request) (*Response, error) { return nil, rt.err }
 10067  
 10068  // gzipReader wraps a response body so it can lazily
 10069  // call gzip.NewReader on the first call to Read
 10070  type http2gzipReader struct {
 10071  	_    http2incomparable
 10072  	body io.ReadCloser // underlying Response.Body
 10073  	zr   *gzip.Reader  // lazily-initialized gzip reader
 10074  	zerr error         // sticky error
 10075  }
 10076  
 10077  func (gz *http2gzipReader) Read(p []byte) (n int, err error) {
 10078  	if gz.zerr != nil {
 10079  		return 0, gz.zerr
 10080  	}
 10081  	if gz.zr == nil {
 10082  		gz.zr, err = gzip.NewReader(gz.body)
 10083  		if err != nil {
 10084  			gz.zerr = err
 10085  			return 0, err
 10086  		}
 10087  	}
 10088  	return gz.zr.Read(p)
 10089  }
 10090  
 10091  func (gz *http2gzipReader) Close() error {
 10092  	if err := gz.body.Close(); err != nil {
 10093  		return err
 10094  	}
 10095  	gz.zerr = fs.ErrClosed
 10096  	return nil
 10097  }
 10098  
 10099  type http2errorReader struct{ err error }
 10100  
 10101  func (r http2errorReader) Read(p []byte) (int, error) { return 0, r.err }
 10102  
 10103  // isConnectionCloseRequest reports whether req should use its own
 10104  // connection for a single request and then close the connection.
 10105  func http2isConnectionCloseRequest(req *Request) bool {
 10106  	return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
 10107  }
 10108  
 10109  // registerHTTPSProtocol calls Transport.RegisterProtocol but
 10110  // converting panics into errors.
 10111  func http2registerHTTPSProtocol(t *Transport, rt http2noDialH2RoundTripper) (err error) {
 10112  	defer func() {
 10113  		if e := recover(); e != nil {
 10114  			err = fmt.Errorf("%v", e)
 10115  		}
 10116  	}()
 10117  	t.RegisterProtocol("https", rt)
 10118  	return nil
 10119  }
 10120  
 10121  // noDialH2RoundTripper is a RoundTripper which only tries to complete the request
 10122  // if there's already has a cached connection to the host.
 10123  // (The field is exported so it can be accessed via reflect from net/http; tested
 10124  // by TestNoDialH2RoundTripperType)
 10125  type http2noDialH2RoundTripper struct{ *http2Transport }
 10126  
 10127  func (rt http2noDialH2RoundTripper) RoundTrip(req *Request) (*Response, error) {
 10128  	res, err := rt.http2Transport.RoundTrip(req)
 10129  	if http2isNoCachedConnError(err) {
 10130  		return nil, ErrSkipAltProtocol
 10131  	}
 10132  	return res, err
 10133  }
 10134  
 10135  func (t *http2Transport) idleConnTimeout() time.Duration {
 10136  	if t.t1 != nil {
 10137  		return t.t1.IdleConnTimeout
 10138  	}
 10139  	return 0
 10140  }
 10141  
 10142  func http2traceGetConn(req *Request, hostPort string) {
 10143  	trace := httptrace.ContextClientTrace(req.Context())
 10144  	if trace == nil || trace.GetConn == nil {
 10145  		return
 10146  	}
 10147  	trace.GetConn(hostPort)
 10148  }
 10149  
 10150  func http2traceGotConn(req *Request, cc *http2ClientConn, reused bool) {
 10151  	trace := httptrace.ContextClientTrace(req.Context())
 10152  	if trace == nil || trace.GotConn == nil {
 10153  		return
 10154  	}
 10155  	ci := httptrace.GotConnInfo{Conn: cc.tconn}
 10156  	ci.Reused = reused
 10157  	cc.mu.Lock()
 10158  	ci.WasIdle = len(cc.streams) == 0 && reused
 10159  	if ci.WasIdle && !cc.lastActive.IsZero() {
 10160  		ci.IdleTime = time.Since(cc.lastActive)
 10161  	}
 10162  	cc.mu.Unlock()
 10163  
 10164  	trace.GotConn(ci)
 10165  }
 10166  
 10167  func http2traceWroteHeaders(trace *httptrace.ClientTrace) {
 10168  	if trace != nil && trace.WroteHeaders != nil {
 10169  		trace.WroteHeaders()
 10170  	}
 10171  }
 10172  
 10173  func http2traceGot100Continue(trace *httptrace.ClientTrace) {
 10174  	if trace != nil && trace.Got100Continue != nil {
 10175  		trace.Got100Continue()
 10176  	}
 10177  }
 10178  
 10179  func http2traceWait100Continue(trace *httptrace.ClientTrace) {
 10180  	if trace != nil && trace.Wait100Continue != nil {
 10181  		trace.Wait100Continue()
 10182  	}
 10183  }
 10184  
 10185  func http2traceWroteRequest(trace *httptrace.ClientTrace, err error) {
 10186  	if trace != nil && trace.WroteRequest != nil {
 10187  		trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
 10188  	}
 10189  }
 10190  
 10191  func http2traceFirstResponseByte(trace *httptrace.ClientTrace) {
 10192  	if trace != nil && trace.GotFirstResponseByte != nil {
 10193  		trace.GotFirstResponseByte()
 10194  	}
 10195  }
 10196  
 10197  // writeFramer is implemented by any type that is used to write frames.
 10198  type http2writeFramer interface {
 10199  	writeFrame(http2writeContext) error
 10200  
 10201  	// staysWithinBuffer reports whether this writer promises that
 10202  	// it will only write less than or equal to size bytes, and it
 10203  	// won't Flush the write context.
 10204  	staysWithinBuffer(size int) bool
 10205  }
 10206  
 10207  // writeContext is the interface needed by the various frame writer
 10208  // types below. All the writeFrame methods below are scheduled via the
 10209  // frame writing scheduler (see writeScheduler in writesched.go).
 10210  //
 10211  // This interface is implemented by *serverConn.
 10212  //
 10213  // TODO: decide whether to a) use this in the client code (which didn't
 10214  // end up using this yet, because it has a simpler design, not
 10215  // currently implementing priorities), or b) delete this and
 10216  // make the server code a bit more concrete.
 10217  type http2writeContext interface {
 10218  	Framer() *http2Framer
 10219  	Flush() error
 10220  	CloseConn() error
 10221  	// HeaderEncoder returns an HPACK encoder that writes to the
 10222  	// returned buffer.
 10223  	HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
 10224  }
 10225  
 10226  // writeEndsStream reports whether w writes a frame that will transition
 10227  // the stream to a half-closed local state. This returns false for RST_STREAM,
 10228  // which closes the entire stream (not just the local half).
 10229  func http2writeEndsStream(w http2writeFramer) bool {
 10230  	switch v := w.(type) {
 10231  	case *http2writeData:
 10232  		return v.endStream
 10233  	case *http2writeResHeaders:
 10234  		return v.endStream
 10235  	case nil:
 10236  		// This can only happen if the caller reuses w after it's
 10237  		// been intentionally nil'ed out to prevent use. Keep this
 10238  		// here to catch future refactoring breaking it.
 10239  		panic("writeEndsStream called on nil writeFramer")
 10240  	}
 10241  	return false
 10242  }
 10243  
 10244  type http2flushFrameWriter struct{}
 10245  
 10246  func (http2flushFrameWriter) writeFrame(ctx http2writeContext) error {
 10247  	return ctx.Flush()
 10248  }
 10249  
 10250  func (http2flushFrameWriter) staysWithinBuffer(max int) bool { return false }
 10251  
 10252  type http2writeSettings []http2Setting
 10253  
 10254  func (s http2writeSettings) staysWithinBuffer(max int) bool {
 10255  	const settingSize = 6 // uint16 + uint32
 10256  	return http2frameHeaderLen+settingSize*len(s) <= max
 10257  
 10258  }
 10259  
 10260  func (s http2writeSettings) writeFrame(ctx http2writeContext) error {
 10261  	return ctx.Framer().WriteSettings([]http2Setting(s)...)
 10262  }
 10263  
 10264  type http2writeGoAway struct {
 10265  	maxStreamID uint32
 10266  	code        http2ErrCode
 10267  }
 10268  
 10269  func (p *http2writeGoAway) writeFrame(ctx http2writeContext) error {
 10270  	err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil)
 10271  	ctx.Flush() // ignore error: we're hanging up on them anyway
 10272  	return err
 10273  }
 10274  
 10275  func (*http2writeGoAway) staysWithinBuffer(max int) bool { return false } // flushes
 10276  
 10277  type http2writeData struct {
 10278  	streamID  uint32
 10279  	p         []byte
 10280  	endStream bool
 10281  }
 10282  
 10283  func (w *http2writeData) String() string {
 10284  	return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream)
 10285  }
 10286  
 10287  func (w *http2writeData) writeFrame(ctx http2writeContext) error {
 10288  	return ctx.Framer().WriteData(w.streamID, w.endStream, w.p)
 10289  }
 10290  
 10291  func (w *http2writeData) staysWithinBuffer(max int) bool {
 10292  	return http2frameHeaderLen+len(w.p) <= max
 10293  }
 10294  
 10295  // handlerPanicRST is the message sent from handler goroutines when
 10296  // the handler panics.
 10297  type http2handlerPanicRST struct {
 10298  	StreamID uint32
 10299  }
 10300  
 10301  func (hp http2handlerPanicRST) writeFrame(ctx http2writeContext) error {
 10302  	return ctx.Framer().WriteRSTStream(hp.StreamID, http2ErrCodeInternal)
 10303  }
 10304  
 10305  func (hp http2handlerPanicRST) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
 10306  
 10307  func (se http2StreamError) writeFrame(ctx http2writeContext) error {
 10308  	return ctx.Framer().WriteRSTStream(se.StreamID, se.Code)
 10309  }
 10310  
 10311  func (se http2StreamError) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
 10312  
 10313  type http2writePingAck struct{ pf *http2PingFrame }
 10314  
 10315  func (w http2writePingAck) writeFrame(ctx http2writeContext) error {
 10316  	return ctx.Framer().WritePing(true, w.pf.Data)
 10317  }
 10318  
 10319  func (w http2writePingAck) staysWithinBuffer(max int) bool {
 10320  	return http2frameHeaderLen+len(w.pf.Data) <= max
 10321  }
 10322  
 10323  type http2writeSettingsAck struct{}
 10324  
 10325  func (http2writeSettingsAck) writeFrame(ctx http2writeContext) error {
 10326  	return ctx.Framer().WriteSettingsAck()
 10327  }
 10328  
 10329  func (http2writeSettingsAck) staysWithinBuffer(max int) bool { return http2frameHeaderLen <= max }
 10330  
 10331  // splitHeaderBlock splits headerBlock into fragments so that each fragment fits
 10332  // in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true
 10333  // for the first/last fragment, respectively.
 10334  func http2splitHeaderBlock(ctx http2writeContext, headerBlock []byte, fn func(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error) error {
 10335  	// For now we're lazy and just pick the minimum MAX_FRAME_SIZE
 10336  	// that all peers must support (16KB). Later we could care
 10337  	// more and send larger frames if the peer advertised it, but
 10338  	// there's little point. Most headers are small anyway (so we
 10339  	// generally won't have CONTINUATION frames), and extra frames
 10340  	// only waste 9 bytes anyway.
 10341  	const maxFrameSize = 16384
 10342  
 10343  	first := true
 10344  	for len(headerBlock) > 0 {
 10345  		frag := headerBlock
 10346  		if len(frag) > maxFrameSize {
 10347  			frag = frag[:maxFrameSize]
 10348  		}
 10349  		headerBlock = headerBlock[len(frag):]
 10350  		if err := fn(ctx, frag, first, len(headerBlock) == 0); err != nil {
 10351  			return err
 10352  		}
 10353  		first = false
 10354  	}
 10355  	return nil
 10356  }
 10357  
 10358  // writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames
 10359  // for HTTP response headers or trailers from a server handler.
 10360  type http2writeResHeaders struct {
 10361  	streamID    uint32
 10362  	httpResCode int      // 0 means no ":status" line
 10363  	h           Header   // may be nil
 10364  	trailers    []string // if non-nil, which keys of h to write. nil means all.
 10365  	endStream   bool
 10366  
 10367  	date          string
 10368  	contentType   string
 10369  	contentLength string
 10370  }
 10371  
 10372  func http2encKV(enc *hpack.Encoder, k, v string) {
 10373  	if http2VerboseLogs {
 10374  		log.Printf("http2: server encoding header %q = %q", k, v)
 10375  	}
 10376  	enc.WriteField(hpack.HeaderField{Name: k, Value: v})
 10377  }
 10378  
 10379  func (w *http2writeResHeaders) staysWithinBuffer(max int) bool {
 10380  	// TODO: this is a common one. It'd be nice to return true
 10381  	// here and get into the fast path if we could be clever and
 10382  	// calculate the size fast enough, or at least a conservative
 10383  	// upper bound that usually fires. (Maybe if w.h and
 10384  	// w.trailers are nil, so we don't need to enumerate it.)
 10385  	// Otherwise I'm afraid that just calculating the length to
 10386  	// answer this question would be slower than the ~2µs benefit.
 10387  	return false
 10388  }
 10389  
 10390  func (w *http2writeResHeaders) writeFrame(ctx http2writeContext) error {
 10391  	enc, buf := ctx.HeaderEncoder()
 10392  	buf.Reset()
 10393  
 10394  	if w.httpResCode != 0 {
 10395  		http2encKV(enc, ":status", http2httpCodeString(w.httpResCode))
 10396  	}
 10397  
 10398  	http2encodeHeaders(enc, w.h, w.trailers)
 10399  
 10400  	if w.contentType != "" {
 10401  		http2encKV(enc, "content-type", w.contentType)
 10402  	}
 10403  	if w.contentLength != "" {
 10404  		http2encKV(enc, "content-length", w.contentLength)
 10405  	}
 10406  	if w.date != "" {
 10407  		http2encKV(enc, "date", w.date)
 10408  	}
 10409  
 10410  	headerBlock := buf.Bytes()
 10411  	if len(headerBlock) == 0 && w.trailers == nil {
 10412  		panic("unexpected empty hpack")
 10413  	}
 10414  
 10415  	return http2splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
 10416  }
 10417  
 10418  func (w *http2writeResHeaders) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error {
 10419  	if firstFrag {
 10420  		return ctx.Framer().WriteHeaders(http2HeadersFrameParam{
 10421  			StreamID:      w.streamID,
 10422  			BlockFragment: frag,
 10423  			EndStream:     w.endStream,
 10424  			EndHeaders:    lastFrag,
 10425  		})
 10426  	} else {
 10427  		return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
 10428  	}
 10429  }
 10430  
 10431  // writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames.
 10432  type http2writePushPromise struct {
 10433  	streamID uint32   // pusher stream
 10434  	method   string   // for :method
 10435  	url      *url.URL // for :scheme, :authority, :path
 10436  	h        Header
 10437  
 10438  	// Creates an ID for a pushed stream. This runs on serveG just before
 10439  	// the frame is written. The returned ID is copied to promisedID.
 10440  	allocatePromisedID func() (uint32, error)
 10441  	promisedID         uint32
 10442  }
 10443  
 10444  func (w *http2writePushPromise) staysWithinBuffer(max int) bool {
 10445  	// TODO: see writeResHeaders.staysWithinBuffer
 10446  	return false
 10447  }
 10448  
 10449  func (w *http2writePushPromise) writeFrame(ctx http2writeContext) error {
 10450  	enc, buf := ctx.HeaderEncoder()
 10451  	buf.Reset()
 10452  
 10453  	http2encKV(enc, ":method", w.method)
 10454  	http2encKV(enc, ":scheme", w.url.Scheme)
 10455  	http2encKV(enc, ":authority", w.url.Host)
 10456  	http2encKV(enc, ":path", w.url.RequestURI())
 10457  	http2encodeHeaders(enc, w.h, nil)
 10458  
 10459  	headerBlock := buf.Bytes()
 10460  	if len(headerBlock) == 0 {
 10461  		panic("unexpected empty hpack")
 10462  	}
 10463  
 10464  	return http2splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
 10465  }
 10466  
 10467  func (w *http2writePushPromise) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error {
 10468  	if firstFrag {
 10469  		return ctx.Framer().WritePushPromise(http2PushPromiseParam{
 10470  			StreamID:      w.streamID,
 10471  			PromiseID:     w.promisedID,
 10472  			BlockFragment: frag,
 10473  			EndHeaders:    lastFrag,
 10474  		})
 10475  	} else {
 10476  		return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
 10477  	}
 10478  }
 10479  
 10480  type http2write100ContinueHeadersFrame struct {
 10481  	streamID uint32
 10482  }
 10483  
 10484  func (w http2write100ContinueHeadersFrame) writeFrame(ctx http2writeContext) error {
 10485  	enc, buf := ctx.HeaderEncoder()
 10486  	buf.Reset()
 10487  	http2encKV(enc, ":status", "100")
 10488  	return ctx.Framer().WriteHeaders(http2HeadersFrameParam{
 10489  		StreamID:      w.streamID,
 10490  		BlockFragment: buf.Bytes(),
 10491  		EndStream:     false,
 10492  		EndHeaders:    true,
 10493  	})
 10494  }
 10495  
 10496  func (w http2write100ContinueHeadersFrame) staysWithinBuffer(max int) bool {
 10497  	// Sloppy but conservative:
 10498  	return 9+2*(len(":status")+len("100")) <= max
 10499  }
 10500  
 10501  type http2writeWindowUpdate struct {
 10502  	streamID uint32 // or 0 for conn-level
 10503  	n        uint32
 10504  }
 10505  
 10506  func (wu http2writeWindowUpdate) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
 10507  
 10508  func (wu http2writeWindowUpdate) writeFrame(ctx http2writeContext) error {
 10509  	return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n)
 10510  }
 10511  
 10512  // encodeHeaders encodes an http.Header. If keys is not nil, then (k, h[k])
 10513  // is encoded only if k is in keys.
 10514  func http2encodeHeaders(enc *hpack.Encoder, h Header, keys []string) {
 10515  	if keys == nil {
 10516  		sorter := http2sorterPool.Get().(*http2sorter)
 10517  		// Using defer here, since the returned keys from the
 10518  		// sorter.Keys method is only valid until the sorter
 10519  		// is returned:
 10520  		defer http2sorterPool.Put(sorter)
 10521  		keys = sorter.Keys(h)
 10522  	}
 10523  	for _, k := range keys {
 10524  		vv := h[k]
 10525  		k, ascii := http2lowerHeader(k)
 10526  		if !ascii {
 10527  			// Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
 10528  			// field names have to be ASCII characters (just as in HTTP/1.x).
 10529  			continue
 10530  		}
 10531  		if !http2validWireHeaderFieldName(k) {
 10532  			// Skip it as backup paranoia. Per
 10533  			// golang.org/issue/14048, these should
 10534  			// already be rejected at a higher level.
 10535  			continue
 10536  		}
 10537  		isTE := k == "transfer-encoding"
 10538  		for _, v := range vv {
 10539  			if !httpguts.ValidHeaderFieldValue(v) {
 10540  				// TODO: return an error? golang.org/issue/14048
 10541  				// For now just omit it.
 10542  				continue
 10543  			}
 10544  			// TODO: more of "8.1.2.2 Connection-Specific Header Fields"
 10545  			if isTE && v != "trailers" {
 10546  				continue
 10547  			}
 10548  			http2encKV(enc, k, v)
 10549  		}
 10550  	}
 10551  }
 10552  
 10553  // WriteScheduler is the interface implemented by HTTP/2 write schedulers.
 10554  // Methods are never called concurrently.
 10555  type http2WriteScheduler interface {
 10556  	// OpenStream opens a new stream in the write scheduler.
 10557  	// It is illegal to call this with streamID=0 or with a streamID that is
 10558  	// already open -- the call may panic.
 10559  	OpenStream(streamID uint32, options http2OpenStreamOptions)
 10560  
 10561  	// CloseStream closes a stream in the write scheduler. Any frames queued on
 10562  	// this stream should be discarded. It is illegal to call this on a stream
 10563  	// that is not open -- the call may panic.
 10564  	CloseStream(streamID uint32)
 10565  
 10566  	// AdjustStream adjusts the priority of the given stream. This may be called
 10567  	// on a stream that has not yet been opened or has been closed. Note that
 10568  	// RFC 7540 allows PRIORITY frames to be sent on streams in any state. See:
 10569  	// https://tools.ietf.org/html/rfc7540#section-5.1
 10570  	AdjustStream(streamID uint32, priority http2PriorityParam)
 10571  
 10572  	// Push queues a frame in the scheduler. In most cases, this will not be
 10573  	// called with wr.StreamID()!=0 unless that stream is currently open. The one
 10574  	// exception is RST_STREAM frames, which may be sent on idle or closed streams.
 10575  	Push(wr http2FrameWriteRequest)
 10576  
 10577  	// Pop dequeues the next frame to write. Returns false if no frames can
 10578  	// be written. Frames with a given wr.StreamID() are Pop'd in the same
 10579  	// order they are Push'd, except RST_STREAM frames. No frames should be
 10580  	// discarded except by CloseStream.
 10581  	Pop() (wr http2FrameWriteRequest, ok bool)
 10582  }
 10583  
 10584  // OpenStreamOptions specifies extra options for WriteScheduler.OpenStream.
 10585  type http2OpenStreamOptions struct {
 10586  	// PusherID is zero if the stream was initiated by the client. Otherwise,
 10587  	// PusherID names the stream that pushed the newly opened stream.
 10588  	PusherID uint32
 10589  }
 10590  
 10591  // FrameWriteRequest is a request to write a frame.
 10592  type http2FrameWriteRequest struct {
 10593  	// write is the interface value that does the writing, once the
 10594  	// WriteScheduler has selected this frame to write. The write
 10595  	// functions are all defined in write.go.
 10596  	write http2writeFramer
 10597  
 10598  	// stream is the stream on which this frame will be written.
 10599  	// nil for non-stream frames like PING and SETTINGS.
 10600  	// nil for RST_STREAM streams, which use the StreamError.StreamID field instead.
 10601  	stream *http2stream
 10602  
 10603  	// done, if non-nil, must be a buffered channel with space for
 10604  	// 1 message and is sent the return value from write (or an
 10605  	// earlier error) when the frame has been written.
 10606  	done chan error
 10607  }
 10608  
 10609  // StreamID returns the id of the stream this frame will be written to.
 10610  // 0 is used for non-stream frames such as PING and SETTINGS.
 10611  func (wr http2FrameWriteRequest) StreamID() uint32 {
 10612  	if wr.stream == nil {
 10613  		if se, ok := wr.write.(http2StreamError); ok {
 10614  			// (*serverConn).resetStream doesn't set
 10615  			// stream because it doesn't necessarily have
 10616  			// one. So special case this type of write
 10617  			// message.
 10618  			return se.StreamID
 10619  		}
 10620  		return 0
 10621  	}
 10622  	return wr.stream.id
 10623  }
 10624  
 10625  // isControl reports whether wr is a control frame for MaxQueuedControlFrames
 10626  // purposes. That includes non-stream frames and RST_STREAM frames.
 10627  func (wr http2FrameWriteRequest) isControl() bool {
 10628  	return wr.stream == nil
 10629  }
 10630  
 10631  // DataSize returns the number of flow control bytes that must be consumed
 10632  // to write this entire frame. This is 0 for non-DATA frames.
 10633  func (wr http2FrameWriteRequest) DataSize() int {
 10634  	if wd, ok := wr.write.(*http2writeData); ok {
 10635  		return len(wd.p)
 10636  	}
 10637  	return 0
 10638  }
 10639  
 10640  // Consume consumes min(n, available) bytes from this frame, where available
 10641  // is the number of flow control bytes available on the stream. Consume returns
 10642  // 0, 1, or 2 frames, where the integer return value gives the number of frames
 10643  // returned.
 10644  //
 10645  // If flow control prevents consuming any bytes, this returns (_, _, 0). If
 10646  // the entire frame was consumed, this returns (wr, _, 1). Otherwise, this
 10647  // returns (consumed, rest, 2), where 'consumed' contains the consumed bytes and
 10648  // 'rest' contains the remaining bytes. The consumed bytes are deducted from the
 10649  // underlying stream's flow control budget.
 10650  func (wr http2FrameWriteRequest) Consume(n int32) (http2FrameWriteRequest, http2FrameWriteRequest, int) {
 10651  	var empty http2FrameWriteRequest
 10652  
 10653  	// Non-DATA frames are always consumed whole.
 10654  	wd, ok := wr.write.(*http2writeData)
 10655  	if !ok || len(wd.p) == 0 {
 10656  		return wr, empty, 1
 10657  	}
 10658  
 10659  	// Might need to split after applying limits.
 10660  	allowed := wr.stream.flow.available()
 10661  	if n < allowed {
 10662  		allowed = n
 10663  	}
 10664  	if wr.stream.sc.maxFrameSize < allowed {
 10665  		allowed = wr.stream.sc.maxFrameSize
 10666  	}
 10667  	if allowed <= 0 {
 10668  		return empty, empty, 0
 10669  	}
 10670  	if len(wd.p) > int(allowed) {
 10671  		wr.stream.flow.take(allowed)
 10672  		consumed := http2FrameWriteRequest{
 10673  			stream: wr.stream,
 10674  			write: &http2writeData{
 10675  				streamID: wd.streamID,
 10676  				p:        wd.p[:allowed],
 10677  				// Even if the original had endStream set, there
 10678  				// are bytes remaining because len(wd.p) > allowed,
 10679  				// so we know endStream is false.
 10680  				endStream: false,
 10681  			},
 10682  			// Our caller is blocking on the final DATA frame, not
 10683  			// this intermediate frame, so no need to wait.
 10684  			done: nil,
 10685  		}
 10686  		rest := http2FrameWriteRequest{
 10687  			stream: wr.stream,
 10688  			write: &http2writeData{
 10689  				streamID:  wd.streamID,
 10690  				p:         wd.p[allowed:],
 10691  				endStream: wd.endStream,
 10692  			},
 10693  			done: wr.done,
 10694  		}
 10695  		return consumed, rest, 2
 10696  	}
 10697  
 10698  	// The frame is consumed whole.
 10699  	// NB: This cast cannot overflow because allowed is <= math.MaxInt32.
 10700  	wr.stream.flow.take(int32(len(wd.p)))
 10701  	return wr, empty, 1
 10702  }
 10703  
 10704  // String is for debugging only.
 10705  func (wr http2FrameWriteRequest) String() string {
 10706  	var des string
 10707  	if s, ok := wr.write.(fmt.Stringer); ok {
 10708  		des = s.String()
 10709  	} else {
 10710  		des = fmt.Sprintf("%T", wr.write)
 10711  	}
 10712  	return fmt.Sprintf("[FrameWriteRequest stream=%d, ch=%v, writer=%v]", wr.StreamID(), wr.done != nil, des)
 10713  }
 10714  
 10715  // replyToWriter sends err to wr.done and panics if the send must block
 10716  // This does nothing if wr.done is nil.
 10717  func (wr *http2FrameWriteRequest) replyToWriter(err error) {
 10718  	if wr.done == nil {
 10719  		return
 10720  	}
 10721  	select {
 10722  	case wr.done <- err:
 10723  	default:
 10724  		panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wr.write))
 10725  	}
 10726  	wr.write = nil // prevent use (assume it's tainted after wr.done send)
 10727  }
 10728  
 10729  // writeQueue is used by implementations of WriteScheduler.
 10730  type http2writeQueue struct {
 10731  	s []http2FrameWriteRequest
 10732  }
 10733  
 10734  func (q *http2writeQueue) empty() bool { return len(q.s) == 0 }
 10735  
 10736  func (q *http2writeQueue) push(wr http2FrameWriteRequest) {
 10737  	q.s = append(q.s, wr)
 10738  }
 10739  
 10740  func (q *http2writeQueue) shift() http2FrameWriteRequest {
 10741  	if len(q.s) == 0 {
 10742  		panic("invalid use of queue")
 10743  	}
 10744  	wr := q.s[0]
 10745  	// TODO: less copy-happy queue.
 10746  	copy(q.s, q.s[1:])
 10747  	q.s[len(q.s)-1] = http2FrameWriteRequest{}
 10748  	q.s = q.s[:len(q.s)-1]
 10749  	return wr
 10750  }
 10751  
 10752  // consume consumes up to n bytes from q.s[0]. If the frame is
 10753  // entirely consumed, it is removed from the queue. If the frame
 10754  // is partially consumed, the frame is kept with the consumed
 10755  // bytes removed. Returns true iff any bytes were consumed.
 10756  func (q *http2writeQueue) consume(n int32) (http2FrameWriteRequest, bool) {
 10757  	if len(q.s) == 0 {
 10758  		return http2FrameWriteRequest{}, false
 10759  	}
 10760  	consumed, rest, numresult := q.s[0].Consume(n)
 10761  	switch numresult {
 10762  	case 0:
 10763  		return http2FrameWriteRequest{}, false
 10764  	case 1:
 10765  		q.shift()
 10766  	case 2:
 10767  		q.s[0] = rest
 10768  	}
 10769  	return consumed, true
 10770  }
 10771  
 10772  type http2writeQueuePool []*http2writeQueue
 10773  
 10774  // put inserts an unused writeQueue into the pool.
 10775  
 10776  // put inserts an unused writeQueue into the pool.
 10777  func (p *http2writeQueuePool) put(q *http2writeQueue) {
 10778  	for i := range q.s {
 10779  		q.s[i] = http2FrameWriteRequest{}
 10780  	}
 10781  	q.s = q.s[:0]
 10782  	*p = append(*p, q)
 10783  }
 10784  
 10785  // get returns an empty writeQueue.
 10786  func (p *http2writeQueuePool) get() *http2writeQueue {
 10787  	ln := len(*p)
 10788  	if ln == 0 {
 10789  		return new(http2writeQueue)
 10790  	}
 10791  	x := ln - 1
 10792  	q := (*p)[x]
 10793  	(*p)[x] = nil
 10794  	*p = (*p)[:x]
 10795  	return q
 10796  }
 10797  
 10798  // RFC 7540, Section 5.3.5: the default weight is 16.
 10799  const http2priorityDefaultWeight = 15 // 16 = 15 + 1
 10800  
 10801  // PriorityWriteSchedulerConfig configures a priorityWriteScheduler.
 10802  type http2PriorityWriteSchedulerConfig struct {
 10803  	// MaxClosedNodesInTree controls the maximum number of closed streams to
 10804  	// retain in the priority tree. Setting this to zero saves a small amount
 10805  	// of memory at the cost of performance.
 10806  	//
 10807  	// See RFC 7540, Section 5.3.4:
 10808  	//   "It is possible for a stream to become closed while prioritization
 10809  	//   information ... is in transit. ... This potentially creates suboptimal
 10810  	//   prioritization, since the stream could be given a priority that is
 10811  	//   different from what is intended. To avoid these problems, an endpoint
 10812  	//   SHOULD retain stream prioritization state for a period after streams
 10813  	//   become closed. The longer state is retained, the lower the chance that
 10814  	//   streams are assigned incorrect or default priority values."
 10815  	MaxClosedNodesInTree int
 10816  
 10817  	// MaxIdleNodesInTree controls the maximum number of idle streams to
 10818  	// retain in the priority tree. Setting this to zero saves a small amount
 10819  	// of memory at the cost of performance.
 10820  	//
 10821  	// See RFC 7540, Section 5.3.4:
 10822  	//   Similarly, streams that are in the "idle" state can be assigned
 10823  	//   priority or become a parent of other streams. This allows for the
 10824  	//   creation of a grouping node in the dependency tree, which enables
 10825  	//   more flexible expressions of priority. Idle streams begin with a
 10826  	//   default priority (Section 5.3.5).
 10827  	MaxIdleNodesInTree int
 10828  
 10829  	// ThrottleOutOfOrderWrites enables write throttling to help ensure that
 10830  	// data is delivered in priority order. This works around a race where
 10831  	// stream B depends on stream A and both streams are about to call Write
 10832  	// to queue DATA frames. If B wins the race, a naive scheduler would eagerly
 10833  	// write as much data from B as possible, but this is suboptimal because A
 10834  	// is a higher-priority stream. With throttling enabled, we write a small
 10835  	// amount of data from B to minimize the amount of bandwidth that B can
 10836  	// steal from A.
 10837  	ThrottleOutOfOrderWrites bool
 10838  }
 10839  
 10840  // NewPriorityWriteScheduler constructs a WriteScheduler that schedules
 10841  // frames by following HTTP/2 priorities as described in RFC 7540 Section 5.3.
 10842  // If cfg is nil, default options are used.
 10843  func http2NewPriorityWriteScheduler(cfg *http2PriorityWriteSchedulerConfig) http2WriteScheduler {
 10844  	if cfg == nil {
 10845  		// For justification of these defaults, see:
 10846  		// https://docs.google.com/document/d/1oLhNg1skaWD4_DtaoCxdSRN5erEXrH-KnLrMwEpOtFY
 10847  		cfg = &http2PriorityWriteSchedulerConfig{
 10848  			MaxClosedNodesInTree:     10,
 10849  			MaxIdleNodesInTree:       10,
 10850  			ThrottleOutOfOrderWrites: false,
 10851  		}
 10852  	}
 10853  
 10854  	ws := &http2priorityWriteScheduler{
 10855  		nodes:                make(map[uint32]*http2priorityNode),
 10856  		maxClosedNodesInTree: cfg.MaxClosedNodesInTree,
 10857  		maxIdleNodesInTree:   cfg.MaxIdleNodesInTree,
 10858  		enableWriteThrottle:  cfg.ThrottleOutOfOrderWrites,
 10859  	}
 10860  	ws.nodes[0] = &ws.root
 10861  	if cfg.ThrottleOutOfOrderWrites {
 10862  		ws.writeThrottleLimit = 1024
 10863  	} else {
 10864  		ws.writeThrottleLimit = math.MaxInt32
 10865  	}
 10866  	return ws
 10867  }
 10868  
 10869  type http2priorityNodeState int
 10870  
 10871  const (
 10872  	http2priorityNodeOpen http2priorityNodeState = iota
 10873  	http2priorityNodeClosed
 10874  	http2priorityNodeIdle
 10875  )
 10876  
 10877  // priorityNode is a node in an HTTP/2 priority tree.
 10878  // Each node is associated with a single stream ID.
 10879  // See RFC 7540, Section 5.3.
 10880  type http2priorityNode struct {
 10881  	q            http2writeQueue        // queue of pending frames to write
 10882  	id           uint32                 // id of the stream, or 0 for the root of the tree
 10883  	weight       uint8                  // the actual weight is weight+1, so the value is in [1,256]
 10884  	state        http2priorityNodeState // open | closed | idle
 10885  	bytes        int64                  // number of bytes written by this node, or 0 if closed
 10886  	subtreeBytes int64                  // sum(node.bytes) of all nodes in this subtree
 10887  
 10888  	// These links form the priority tree.
 10889  	parent     *http2priorityNode
 10890  	kids       *http2priorityNode // start of the kids list
 10891  	prev, next *http2priorityNode // doubly-linked list of siblings
 10892  }
 10893  
 10894  func (n *http2priorityNode) setParent(parent *http2priorityNode) {
 10895  	if n == parent {
 10896  		panic("setParent to self")
 10897  	}
 10898  	if n.parent == parent {
 10899  		return
 10900  	}
 10901  	// Unlink from current parent.
 10902  	if parent := n.parent; parent != nil {
 10903  		if n.prev == nil {
 10904  			parent.kids = n.next
 10905  		} else {
 10906  			n.prev.next = n.next
 10907  		}
 10908  		if n.next != nil {
 10909  			n.next.prev = n.prev
 10910  		}
 10911  	}
 10912  	// Link to new parent.
 10913  	// If parent=nil, remove n from the tree.
 10914  	// Always insert at the head of parent.kids (this is assumed by walkReadyInOrder).
 10915  	n.parent = parent
 10916  	if parent == nil {
 10917  		n.next = nil
 10918  		n.prev = nil
 10919  	} else {
 10920  		n.next = parent.kids
 10921  		n.prev = nil
 10922  		if n.next != nil {
 10923  			n.next.prev = n
 10924  		}
 10925  		parent.kids = n
 10926  	}
 10927  }
 10928  
 10929  func (n *http2priorityNode) addBytes(b int64) {
 10930  	n.bytes += b
 10931  	for ; n != nil; n = n.parent {
 10932  		n.subtreeBytes += b
 10933  	}
 10934  }
 10935  
 10936  // walkReadyInOrder iterates over the tree in priority order, calling f for each node
 10937  // with a non-empty write queue. When f returns true, this function returns true and the
 10938  // walk halts. tmp is used as scratch space for sorting.
 10939  //
 10940  // f(n, openParent) takes two arguments: the node to visit, n, and a bool that is true
 10941  // if any ancestor p of n is still open (ignoring the root node).
 10942  func (n *http2priorityNode) walkReadyInOrder(openParent bool, tmp *[]*http2priorityNode, f func(*http2priorityNode, bool) bool) bool {
 10943  	if !n.q.empty() && f(n, openParent) {
 10944  		return true
 10945  	}
 10946  	if n.kids == nil {
 10947  		return false
 10948  	}
 10949  
 10950  	// Don't consider the root "open" when updating openParent since
 10951  	// we can't send data frames on the root stream (only control frames).
 10952  	if n.id != 0 {
 10953  		openParent = openParent || (n.state == http2priorityNodeOpen)
 10954  	}
 10955  
 10956  	// Common case: only one kid or all kids have the same weight.
 10957  	// Some clients don't use weights; other clients (like web browsers)
 10958  	// use mostly-linear priority trees.
 10959  	w := n.kids.weight
 10960  	needSort := false
 10961  	for k := n.kids.next; k != nil; k = k.next {
 10962  		if k.weight != w {
 10963  			needSort = true
 10964  			break
 10965  		}
 10966  	}
 10967  	if !needSort {
 10968  		for k := n.kids; k != nil; k = k.next {
 10969  			if k.walkReadyInOrder(openParent, tmp, f) {
 10970  				return true
 10971  			}
 10972  		}
 10973  		return false
 10974  	}
 10975  
 10976  	// Uncommon case: sort the child nodes. We remove the kids from the parent,
 10977  	// then re-insert after sorting so we can reuse tmp for future sort calls.
 10978  	*tmp = (*tmp)[:0]
 10979  	for n.kids != nil {
 10980  		*tmp = append(*tmp, n.kids)
 10981  		n.kids.setParent(nil)
 10982  	}
 10983  	sort.Sort(http2sortPriorityNodeSiblings(*tmp))
 10984  	for i := len(*tmp) - 1; i >= 0; i-- {
 10985  		(*tmp)[i].setParent(n) // setParent inserts at the head of n.kids
 10986  	}
 10987  	for k := n.kids; k != nil; k = k.next {
 10988  		if k.walkReadyInOrder(openParent, tmp, f) {
 10989  			return true
 10990  		}
 10991  	}
 10992  	return false
 10993  }
 10994  
 10995  type http2sortPriorityNodeSiblings []*http2priorityNode
 10996  
 10997  func (z http2sortPriorityNodeSiblings) Len() int { return len(z) }
 10998  
 10999  func (z http2sortPriorityNodeSiblings) Swap(i, k int) { z[i], z[k] = z[k], z[i] }
 11000  
 11001  func (z http2sortPriorityNodeSiblings) Less(i, k int) bool {
 11002  	// Prefer the subtree that has sent fewer bytes relative to its weight.
 11003  	// See sections 5.3.2 and 5.3.4.
 11004  	wi, bi := float64(z[i].weight+1), float64(z[i].subtreeBytes)
 11005  	wk, bk := float64(z[k].weight+1), float64(z[k].subtreeBytes)
 11006  	if bi == 0 && bk == 0 {
 11007  		return wi >= wk
 11008  	}
 11009  	if bk == 0 {
 11010  		return false
 11011  	}
 11012  	return bi/bk <= wi/wk
 11013  }
 11014  
 11015  type http2priorityWriteScheduler struct {
 11016  	// root is the root of the priority tree, where root.id = 0.
 11017  	// The root queues control frames that are not associated with any stream.
 11018  	root http2priorityNode
 11019  
 11020  	// nodes maps stream ids to priority tree nodes.
 11021  	nodes map[uint32]*http2priorityNode
 11022  
 11023  	// maxID is the maximum stream id in nodes.
 11024  	maxID uint32
 11025  
 11026  	// lists of nodes that have been closed or are idle, but are kept in
 11027  	// the tree for improved prioritization. When the lengths exceed either
 11028  	// maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded.
 11029  	closedNodes, idleNodes []*http2priorityNode
 11030  
 11031  	// From the config.
 11032  	maxClosedNodesInTree int
 11033  	maxIdleNodesInTree   int
 11034  	writeThrottleLimit   int32
 11035  	enableWriteThrottle  bool
 11036  
 11037  	// tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations.
 11038  	tmp []*http2priorityNode
 11039  
 11040  	// pool of empty queues for reuse.
 11041  	queuePool http2writeQueuePool
 11042  }
 11043  
 11044  func (ws *http2priorityWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
 11045  	// The stream may be currently idle but cannot be opened or closed.
 11046  	if curr := ws.nodes[streamID]; curr != nil {
 11047  		if curr.state != http2priorityNodeIdle {
 11048  			panic(fmt.Sprintf("stream %d already opened", streamID))
 11049  		}
 11050  		curr.state = http2priorityNodeOpen
 11051  		return
 11052  	}
 11053  
 11054  	// RFC 7540, Section 5.3.5:
 11055  	//  "All streams are initially assigned a non-exclusive dependency on stream 0x0.
 11056  	//  Pushed streams initially depend on their associated stream. In both cases,
 11057  	//  streams are assigned a default weight of 16."
 11058  	parent := ws.nodes[options.PusherID]
 11059  	if parent == nil {
 11060  		parent = &ws.root
 11061  	}
 11062  	n := &http2priorityNode{
 11063  		q:      *ws.queuePool.get(),
 11064  		id:     streamID,
 11065  		weight: http2priorityDefaultWeight,
 11066  		state:  http2priorityNodeOpen,
 11067  	}
 11068  	n.setParent(parent)
 11069  	ws.nodes[streamID] = n
 11070  	if streamID > ws.maxID {
 11071  		ws.maxID = streamID
 11072  	}
 11073  }
 11074  
 11075  func (ws *http2priorityWriteScheduler) CloseStream(streamID uint32) {
 11076  	if streamID == 0 {
 11077  		panic("violation of WriteScheduler interface: cannot close stream 0")
 11078  	}
 11079  	if ws.nodes[streamID] == nil {
 11080  		panic(fmt.Sprintf("violation of WriteScheduler interface: unknown stream %d", streamID))
 11081  	}
 11082  	if ws.nodes[streamID].state != http2priorityNodeOpen {
 11083  		panic(fmt.Sprintf("violation of WriteScheduler interface: stream %d already closed", streamID))
 11084  	}
 11085  
 11086  	n := ws.nodes[streamID]
 11087  	n.state = http2priorityNodeClosed
 11088  	n.addBytes(-n.bytes)
 11089  
 11090  	q := n.q
 11091  	ws.queuePool.put(&q)
 11092  	n.q.s = nil
 11093  	if ws.maxClosedNodesInTree > 0 {
 11094  		ws.addClosedOrIdleNode(&ws.closedNodes, ws.maxClosedNodesInTree, n)
 11095  	} else {
 11096  		ws.removeNode(n)
 11097  	}
 11098  }
 11099  
 11100  func (ws *http2priorityWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {
 11101  	if streamID == 0 {
 11102  		panic("adjustPriority on root")
 11103  	}
 11104  
 11105  	// If streamID does not exist, there are two cases:
 11106  	// - A closed stream that has been removed (this will have ID <= maxID)
 11107  	// - An idle stream that is being used for "grouping" (this will have ID > maxID)
 11108  	n := ws.nodes[streamID]
 11109  	if n == nil {
 11110  		if streamID <= ws.maxID || ws.maxIdleNodesInTree == 0 {
 11111  			return
 11112  		}
 11113  		ws.maxID = streamID
 11114  		n = &http2priorityNode{
 11115  			q:      *ws.queuePool.get(),
 11116  			id:     streamID,
 11117  			weight: http2priorityDefaultWeight,
 11118  			state:  http2priorityNodeIdle,
 11119  		}
 11120  		n.setParent(&ws.root)
 11121  		ws.nodes[streamID] = n
 11122  		ws.addClosedOrIdleNode(&ws.idleNodes, ws.maxIdleNodesInTree, n)
 11123  	}
 11124  
 11125  	// Section 5.3.1: A dependency on a stream that is not currently in the tree
 11126  	// results in that stream being given a default priority (Section 5.3.5).
 11127  	parent := ws.nodes[priority.StreamDep]
 11128  	if parent == nil {
 11129  		n.setParent(&ws.root)
 11130  		n.weight = http2priorityDefaultWeight
 11131  		return
 11132  	}
 11133  
 11134  	// Ignore if the client tries to make a node its own parent.
 11135  	if n == parent {
 11136  		return
 11137  	}
 11138  
 11139  	// Section 5.3.3:
 11140  	//   "If a stream is made dependent on one of its own dependencies, the
 11141  	//   formerly dependent stream is first moved to be dependent on the
 11142  	//   reprioritized stream's previous parent. The moved dependency retains
 11143  	//   its weight."
 11144  	//
 11145  	// That is: if parent depends on n, move parent to depend on n.parent.
 11146  	for x := parent.parent; x != nil; x = x.parent {
 11147  		if x == n {
 11148  			parent.setParent(n.parent)
 11149  			break
 11150  		}
 11151  	}
 11152  
 11153  	// Section 5.3.3: The exclusive flag causes the stream to become the sole
 11154  	// dependency of its parent stream, causing other dependencies to become
 11155  	// dependent on the exclusive stream.
 11156  	if priority.Exclusive {
 11157  		k := parent.kids
 11158  		for k != nil {
 11159  			next := k.next
 11160  			if k != n {
 11161  				k.setParent(n)
 11162  			}
 11163  			k = next
 11164  		}
 11165  	}
 11166  
 11167  	n.setParent(parent)
 11168  	n.weight = priority.Weight
 11169  }
 11170  
 11171  func (ws *http2priorityWriteScheduler) Push(wr http2FrameWriteRequest) {
 11172  	var n *http2priorityNode
 11173  	if wr.isControl() {
 11174  		n = &ws.root
 11175  	} else {
 11176  		id := wr.StreamID()
 11177  		n = ws.nodes[id]
 11178  		if n == nil {
 11179  			// id is an idle or closed stream. wr should not be a HEADERS or
 11180  			// DATA frame. In other case, we push wr onto the root, rather
 11181  			// than creating a new priorityNode.
 11182  			if wr.DataSize() > 0 {
 11183  				panic("add DATA on non-open stream")
 11184  			}
 11185  			n = &ws.root
 11186  		}
 11187  	}
 11188  	n.q.push(wr)
 11189  }
 11190  
 11191  func (ws *http2priorityWriteScheduler) Pop() (wr http2FrameWriteRequest, ok bool) {
 11192  	ws.root.walkReadyInOrder(false, &ws.tmp, func(n *http2priorityNode, openParent bool) bool {
 11193  		limit := int32(math.MaxInt32)
 11194  		if openParent {
 11195  			limit = ws.writeThrottleLimit
 11196  		}
 11197  		wr, ok = n.q.consume(limit)
 11198  		if !ok {
 11199  			return false
 11200  		}
 11201  		n.addBytes(int64(wr.DataSize()))
 11202  		// If B depends on A and B continuously has data available but A
 11203  		// does not, gradually increase the throttling limit to allow B to
 11204  		// steal more and more bandwidth from A.
 11205  		if openParent {
 11206  			ws.writeThrottleLimit += 1024
 11207  			if ws.writeThrottleLimit < 0 {
 11208  				ws.writeThrottleLimit = math.MaxInt32
 11209  			}
 11210  		} else if ws.enableWriteThrottle {
 11211  			ws.writeThrottleLimit = 1024
 11212  		}
 11213  		return true
 11214  	})
 11215  	return wr, ok
 11216  }
 11217  
 11218  func (ws *http2priorityWriteScheduler) addClosedOrIdleNode(list *[]*http2priorityNode, maxSize int, n *http2priorityNode) {
 11219  	if maxSize == 0 {
 11220  		return
 11221  	}
 11222  	if len(*list) == maxSize {
 11223  		// Remove the oldest node, then shift left.
 11224  		ws.removeNode((*list)[0])
 11225  		x := (*list)[1:]
 11226  		copy(*list, x)
 11227  		*list = (*list)[:len(x)]
 11228  	}
 11229  	*list = append(*list, n)
 11230  }
 11231  
 11232  func (ws *http2priorityWriteScheduler) removeNode(n *http2priorityNode) {
 11233  	for k := n.kids; k != nil; k = k.next {
 11234  		k.setParent(n.parent)
 11235  	}
 11236  	n.setParent(nil)
 11237  	delete(ws.nodes, n.id)
 11238  }
 11239  
 11240  // NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2
 11241  // priorities. Control frames like SETTINGS and PING are written before DATA
 11242  // frames, but if no control frames are queued and multiple streams have queued
 11243  // HEADERS or DATA frames, Pop selects a ready stream arbitrarily.
 11244  func http2NewRandomWriteScheduler() http2WriteScheduler {
 11245  	return &http2randomWriteScheduler{sq: make(map[uint32]*http2writeQueue)}
 11246  }
 11247  
 11248  type http2randomWriteScheduler struct {
 11249  	// zero are frames not associated with a specific stream.
 11250  	zero http2writeQueue
 11251  
 11252  	// sq contains the stream-specific queues, keyed by stream ID.
 11253  	// When a stream is idle, closed, or emptied, it's deleted
 11254  	// from the map.
 11255  	sq map[uint32]*http2writeQueue
 11256  
 11257  	// pool of empty queues for reuse.
 11258  	queuePool http2writeQueuePool
 11259  }
 11260  
 11261  func (ws *http2randomWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
 11262  	// no-op: idle streams are not tracked
 11263  }
 11264  
 11265  func (ws *http2randomWriteScheduler) CloseStream(streamID uint32) {
 11266  	q, ok := ws.sq[streamID]
 11267  	if !ok {
 11268  		return
 11269  	}
 11270  	delete(ws.sq, streamID)
 11271  	ws.queuePool.put(q)
 11272  }
 11273  
 11274  func (ws *http2randomWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {
 11275  	// no-op: priorities are ignored
 11276  }
 11277  
 11278  func (ws *http2randomWriteScheduler) Push(wr http2FrameWriteRequest) {
 11279  	if wr.isControl() {
 11280  		ws.zero.push(wr)
 11281  		return
 11282  	}
 11283  	id := wr.StreamID()
 11284  	q, ok := ws.sq[id]
 11285  	if !ok {
 11286  		q = ws.queuePool.get()
 11287  		ws.sq[id] = q
 11288  	}
 11289  	q.push(wr)
 11290  }
 11291  
 11292  func (ws *http2randomWriteScheduler) Pop() (http2FrameWriteRequest, bool) {
 11293  	// Control and RST_STREAM frames first.
 11294  	if !ws.zero.empty() {
 11295  		return ws.zero.shift(), true
 11296  	}
 11297  	// Iterate over all non-idle streams until finding one that can be consumed.
 11298  	for streamID, q := range ws.sq {
 11299  		if wr, ok := q.consume(math.MaxInt32); ok {
 11300  			if q.empty() {
 11301  				delete(ws.sq, streamID)
 11302  				ws.queuePool.put(q)
 11303  			}
 11304  			return wr, true
 11305  		}
 11306  	}
 11307  	return http2FrameWriteRequest{}, false
 11308  }