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

View as plain text