Source file src/net/http/h2_bundle.go

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

View as plain text