Source file src/net/http/h2_bundle.go

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

View as plain text