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

View as plain text