...

Source file src/net/http/h2_bundle.go

Documentation: net/http

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

View as plain text