...

Source file src/net/http/h2_bundle.go

Documentation: net/http

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

View as plain text