...
Run Format

Source file src/net/http/h2_bundle.go

Documentation: net/http

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

View as plain text