You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

496 lines
14 KiB

  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package h2c implements the unencrypted "h2c" form of HTTP/2.
  5. //
  6. // The h2c protocol is the non-TLS version of HTTP/2 which is not available from
  7. // net/http or golang.org/x/net/http2.
  8. package h2c
  9. import (
  10. "bufio"
  11. "bytes"
  12. "encoding/base64"
  13. "encoding/binary"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "log"
  18. "net"
  19. "net/http"
  20. "net/textproto"
  21. "os"
  22. "strings"
  23. "golang.org/x/net/http/httpguts"
  24. "golang.org/x/net/http2"
  25. "golang.org/x/net/http2/hpack"
  26. )
  27. var (
  28. http2VerboseLogs bool
  29. )
  30. func init() {
  31. e := os.Getenv("GODEBUG")
  32. if strings.Contains(e, "http2debug=1") || strings.Contains(e, "http2debug=2") {
  33. http2VerboseLogs = true
  34. }
  35. }
  36. // h2cHandler is a Handler which implements h2c by hijacking the HTTP/1 traffic
  37. // that should be h2c traffic. There are two ways to begin a h2c connection
  38. // (RFC 7540 Section 3.2 and 3.4): (1) Starting with Prior Knowledge - this
  39. // works by starting an h2c connection with a string of bytes that is valid
  40. // HTTP/1, but unlikely to occur in practice and (2) Upgrading from HTTP/1 to
  41. // h2c - this works by using the HTTP/1 Upgrade header to request an upgrade to
  42. // h2c. When either of those situations occur we hijack the HTTP/1 connection,
  43. // convert it to a HTTP/2 connection and pass the net.Conn to http2.ServeConn.
  44. type h2cHandler struct {
  45. Handler http.Handler
  46. s *http2.Server
  47. }
  48. // NewHandler returns an http.Handler that wraps h, intercepting any h2c
  49. // traffic. If a request is an h2c connection, it's hijacked and redirected to
  50. // s.ServeConn. Otherwise the returned Handler just forwards requests to h. This
  51. // works because h2c is designed to be parseable as valid HTTP/1, but ignored by
  52. // any HTTP server that does not handle h2c. Therefore we leverage the HTTP/1
  53. // compatible parts of the Go http library to parse and recognize h2c requests.
  54. // Once a request is recognized as h2c, we hijack the connection and convert it
  55. // to an HTTP/2 connection which is understandable to s.ServeConn. (s.ServeConn
  56. // understands HTTP/2 except for the h2c part of it.)
  57. func NewHandler(h http.Handler, s *http2.Server) http.Handler {
  58. return &h2cHandler{
  59. Handler: h,
  60. s: s,
  61. }
  62. }
  63. // ServeHTTP implement the h2c support that is enabled by h2c.GetH2CHandler.
  64. func (s h2cHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  65. // Handle h2c with prior knowledge (RFC 7540 Section 3.4)
  66. if r.Method == "PRI" && len(r.Header) == 0 && r.URL.Path == "*" && r.Proto == "HTTP/2.0" {
  67. if http2VerboseLogs {
  68. log.Print("h2c: attempting h2c with prior knowledge.")
  69. }
  70. conn, err := initH2CWithPriorKnowledge(w)
  71. if err != nil {
  72. if http2VerboseLogs {
  73. log.Printf("h2c: error h2c with prior knowledge: %v", err)
  74. }
  75. return
  76. }
  77. defer conn.Close()
  78. s.s.ServeConn(conn, &http2.ServeConnOpts{Handler: s.Handler})
  79. return
  80. }
  81. // Handle Upgrade to h2c (RFC 7540 Section 3.2)
  82. if conn, err := h2cUpgrade(w, r); err == nil {
  83. defer conn.Close()
  84. s.s.ServeConn(conn, &http2.ServeConnOpts{Handler: s.Handler})
  85. return
  86. }
  87. s.Handler.ServeHTTP(w, r)
  88. return
  89. }
  90. // initH2CWithPriorKnowledge implements creating a h2c connection with prior
  91. // knowledge (Section 3.4) and creates a net.Conn suitable for http2.ServeConn.
  92. // All we have to do is look for the client preface that is suppose to be part
  93. // of the body, and reforward the client preface on the net.Conn this function
  94. // creates.
  95. func initH2CWithPriorKnowledge(w http.ResponseWriter) (net.Conn, error) {
  96. hijacker, ok := w.(http.Hijacker)
  97. if !ok {
  98. panic("Hijack not supported.")
  99. }
  100. conn, rw, err := hijacker.Hijack()
  101. if err != nil {
  102. panic(fmt.Sprintf("Hijack failed: %v", err))
  103. }
  104. const expectedBody = "SM\r\n\r\n"
  105. buf := make([]byte, len(expectedBody))
  106. n, err := io.ReadFull(rw, buf)
  107. if err != nil {
  108. return nil, fmt.Errorf("could not read from the buffer: %s", err)
  109. }
  110. if string(buf[:n]) == expectedBody {
  111. c := &rwConn{
  112. Conn: conn,
  113. Reader: io.MultiReader(strings.NewReader(http2.ClientPreface), rw),
  114. BufWriter: rw.Writer,
  115. }
  116. return c, nil
  117. }
  118. conn.Close()
  119. if http2VerboseLogs {
  120. log.Printf(
  121. "h2c: missing the request body portion of the client preface. Wanted: %v Got: %v",
  122. []byte(expectedBody),
  123. buf[0:n],
  124. )
  125. }
  126. return nil, errors.New("invalid client preface")
  127. }
  128. // drainClientPreface reads a single instance of the HTTP/2 client preface from
  129. // the supplied reader.
  130. func drainClientPreface(r io.Reader) error {
  131. var buf bytes.Buffer
  132. prefaceLen := int64(len(http2.ClientPreface))
  133. n, err := io.CopyN(&buf, r, prefaceLen)
  134. if err != nil {
  135. return err
  136. }
  137. if n != prefaceLen || buf.String() != http2.ClientPreface {
  138. return fmt.Errorf("Client never sent: %s", http2.ClientPreface)
  139. }
  140. return nil
  141. }
  142. // h2cUpgrade establishes a h2c connection using the HTTP/1 upgrade (Section 3.2).
  143. func h2cUpgrade(w http.ResponseWriter, r *http.Request) (net.Conn, error) {
  144. if !isH2CUpgrade(r.Header) {
  145. return nil, errors.New("non-conforming h2c headers")
  146. }
  147. // Initial bytes we put into conn to fool http2 server
  148. initBytes, _, err := convertH1ReqToH2(r)
  149. if err != nil {
  150. return nil, err
  151. }
  152. hijacker, ok := w.(http.Hijacker)
  153. if !ok {
  154. return nil, errors.New("hijack not supported.")
  155. }
  156. conn, rw, err := hijacker.Hijack()
  157. if err != nil {
  158. return nil, fmt.Errorf("hijack failed: %v", err)
  159. }
  160. rw.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n" +
  161. "Connection: Upgrade\r\n" +
  162. "Upgrade: h2c\r\n\r\n"))
  163. rw.Flush()
  164. // A conforming client will now send an H2 client preface which need to drain
  165. // since we already sent this.
  166. if err := drainClientPreface(rw); err != nil {
  167. return nil, err
  168. }
  169. c := &rwConn{
  170. Conn: conn,
  171. Reader: io.MultiReader(initBytes, rw),
  172. BufWriter: newSettingsAckSwallowWriter(rw.Writer),
  173. }
  174. return c, nil
  175. }
  176. // convert the data contained in the HTTP/1 upgrade request into the HTTP/2
  177. // version in byte form.
  178. func convertH1ReqToH2(r *http.Request) (*bytes.Buffer, []http2.Setting, error) {
  179. h2Bytes := bytes.NewBuffer([]byte((http2.ClientPreface)))
  180. framer := http2.NewFramer(h2Bytes, nil)
  181. settings, err := getH2Settings(r.Header)
  182. if err != nil {
  183. return nil, nil, err
  184. }
  185. if err := framer.WriteSettings(settings...); err != nil {
  186. return nil, nil, err
  187. }
  188. headerBytes, err := getH2HeaderBytes(r, getMaxHeaderTableSize(settings))
  189. if err != nil {
  190. return nil, nil, err
  191. }
  192. maxFrameSize := int(getMaxFrameSize(settings))
  193. needOneHeader := len(headerBytes) < maxFrameSize
  194. err = framer.WriteHeaders(http2.HeadersFrameParam{
  195. StreamID: 1,
  196. BlockFragment: headerBytes,
  197. EndHeaders: needOneHeader,
  198. })
  199. if err != nil {
  200. return nil, nil, err
  201. }
  202. for i := maxFrameSize; i < len(headerBytes); i += maxFrameSize {
  203. if len(headerBytes)-i > maxFrameSize {
  204. if err := framer.WriteContinuation(1,
  205. false, // endHeaders
  206. headerBytes[i:maxFrameSize]); err != nil {
  207. return nil, nil, err
  208. }
  209. } else {
  210. if err := framer.WriteContinuation(1,
  211. true, // endHeaders
  212. headerBytes[i:]); err != nil {
  213. return nil, nil, err
  214. }
  215. }
  216. }
  217. return h2Bytes, settings, nil
  218. }
  219. // getMaxFrameSize returns the SETTINGS_MAX_FRAME_SIZE. If not present default
  220. // value is 16384 as specified by RFC 7540 Section 6.5.2.
  221. func getMaxFrameSize(settings []http2.Setting) uint32 {
  222. for _, setting := range settings {
  223. if setting.ID == http2.SettingMaxFrameSize {
  224. return setting.Val
  225. }
  226. }
  227. return 16384
  228. }
  229. // getMaxHeaderTableSize returns the SETTINGS_HEADER_TABLE_SIZE. If not present
  230. // default value is 4096 as specified by RFC 7540 Section 6.5.2.
  231. func getMaxHeaderTableSize(settings []http2.Setting) uint32 {
  232. for _, setting := range settings {
  233. if setting.ID == http2.SettingHeaderTableSize {
  234. return setting.Val
  235. }
  236. }
  237. return 4096
  238. }
  239. // bufWriter is a Writer interface that also has a Flush method.
  240. type bufWriter interface {
  241. io.Writer
  242. Flush() error
  243. }
  244. // rwConn implements net.Conn but overrides Read and Write so that reads and
  245. // writes are forwarded to the provided io.Reader and bufWriter.
  246. type rwConn struct {
  247. net.Conn
  248. io.Reader
  249. BufWriter bufWriter
  250. }
  251. // Read forwards reads to the underlying Reader.
  252. func (c *rwConn) Read(p []byte) (int, error) {
  253. return c.Reader.Read(p)
  254. }
  255. // Write forwards writes to the underlying bufWriter and immediately flushes.
  256. func (c *rwConn) Write(p []byte) (int, error) {
  257. n, err := c.BufWriter.Write(p)
  258. if err := c.BufWriter.Flush(); err != nil {
  259. return 0, err
  260. }
  261. return n, err
  262. }
  263. // settingsAckSwallowWriter is a writer that normally forwards bytes to its
  264. // underlying Writer, but swallows the first SettingsAck frame that it sees.
  265. type settingsAckSwallowWriter struct {
  266. Writer *bufio.Writer
  267. buf []byte
  268. didSwallow bool
  269. }
  270. // newSettingsAckSwallowWriter returns a new settingsAckSwallowWriter.
  271. func newSettingsAckSwallowWriter(w *bufio.Writer) *settingsAckSwallowWriter {
  272. return &settingsAckSwallowWriter{
  273. Writer: w,
  274. buf: make([]byte, 0),
  275. didSwallow: false,
  276. }
  277. }
  278. // Write implements io.Writer interface. Normally forwards bytes to w.Writer,
  279. // except for the first Settings ACK frame that it sees.
  280. func (w *settingsAckSwallowWriter) Write(p []byte) (int, error) {
  281. if !w.didSwallow {
  282. w.buf = append(w.buf, p...)
  283. // Process all the frames we have collected into w.buf
  284. for {
  285. // Append until we get full frame header which is 9 bytes
  286. if len(w.buf) < 9 {
  287. break
  288. }
  289. // Check if we have collected a whole frame.
  290. fh, err := http2.ReadFrameHeader(bytes.NewBuffer(w.buf))
  291. if err != nil {
  292. // Corrupted frame, fail current Write
  293. return 0, err
  294. }
  295. fSize := fh.Length + 9
  296. if uint32(len(w.buf)) < fSize {
  297. // Have not collected whole frame. Stop processing buf, and withold on
  298. // forward bytes to w.Writer until we get the full frame.
  299. break
  300. }
  301. // We have now collected a whole frame.
  302. if fh.Type == http2.FrameSettings && fh.Flags.Has(http2.FlagSettingsAck) {
  303. // If Settings ACK frame, do not forward to underlying writer, remove
  304. // bytes from w.buf, and record that we have swallowed Settings Ack
  305. // frame.
  306. w.didSwallow = true
  307. w.buf = w.buf[fSize:]
  308. continue
  309. }
  310. // Not settings ack frame. Forward bytes to w.Writer.
  311. if _, err := w.Writer.Write(w.buf[:fSize]); err != nil {
  312. // Couldn't forward bytes. Fail current Write.
  313. return 0, err
  314. }
  315. w.buf = w.buf[fSize:]
  316. }
  317. return len(p), nil
  318. }
  319. return w.Writer.Write(p)
  320. }
  321. // Flush calls w.Writer.Flush.
  322. func (w *settingsAckSwallowWriter) Flush() error {
  323. return w.Writer.Flush()
  324. }
  325. // isH2CUpgrade returns true if the header properly request an upgrade to h2c
  326. // as specified by Section 3.2.
  327. func isH2CUpgrade(h http.Header) bool {
  328. return httpguts.HeaderValuesContainsToken(h[textproto.CanonicalMIMEHeaderKey("Upgrade")], "h2c") &&
  329. httpguts.HeaderValuesContainsToken(h[textproto.CanonicalMIMEHeaderKey("Connection")], "HTTP2-Settings")
  330. }
  331. // getH2Settings returns the []http2.Setting that are encoded in the
  332. // HTTP2-Settings header.
  333. func getH2Settings(h http.Header) ([]http2.Setting, error) {
  334. vals, ok := h[textproto.CanonicalMIMEHeaderKey("HTTP2-Settings")]
  335. if !ok {
  336. return nil, errors.New("missing HTTP2-Settings header")
  337. }
  338. if len(vals) != 1 {
  339. return nil, fmt.Errorf("expected 1 HTTP2-Settings. Got: %v", vals)
  340. }
  341. settings, err := decodeSettings(vals[0])
  342. if err != nil {
  343. return nil, fmt.Errorf("Invalid HTTP2-Settings: %q", vals[0])
  344. }
  345. return settings, nil
  346. }
  347. // decodeSettings decodes the base64url header value of the HTTP2-Settings
  348. // header. RFC 7540 Section 3.2.1.
  349. func decodeSettings(headerVal string) ([]http2.Setting, error) {
  350. b, err := base64.RawURLEncoding.DecodeString(headerVal)
  351. if err != nil {
  352. return nil, err
  353. }
  354. if len(b)%6 != 0 {
  355. return nil, err
  356. }
  357. settings := make([]http2.Setting, 0)
  358. for i := 0; i < len(b)/6; i++ {
  359. settings = append(settings, http2.Setting{
  360. ID: http2.SettingID(binary.BigEndian.Uint16(b[i*6 : i*6+2])),
  361. Val: binary.BigEndian.Uint32(b[i*6+2 : i*6+6]),
  362. })
  363. }
  364. return settings, nil
  365. }
  366. // getH2HeaderBytes return the headers in r a []bytes encoded by HPACK.
  367. func getH2HeaderBytes(r *http.Request, maxHeaderTableSize uint32) ([]byte, error) {
  368. headerBytes := bytes.NewBuffer(nil)
  369. hpackEnc := hpack.NewEncoder(headerBytes)
  370. hpackEnc.SetMaxDynamicTableSize(maxHeaderTableSize)
  371. // Section 8.1.2.3
  372. err := hpackEnc.WriteField(hpack.HeaderField{
  373. Name: ":method",
  374. Value: r.Method,
  375. })
  376. if err != nil {
  377. return nil, err
  378. }
  379. err = hpackEnc.WriteField(hpack.HeaderField{
  380. Name: ":scheme",
  381. Value: "http",
  382. })
  383. if err != nil {
  384. return nil, err
  385. }
  386. err = hpackEnc.WriteField(hpack.HeaderField{
  387. Name: ":authority",
  388. Value: r.Host,
  389. })
  390. if err != nil {
  391. return nil, err
  392. }
  393. path := r.URL.Path
  394. if r.URL.RawQuery != "" {
  395. path = strings.Join([]string{path, r.URL.RawQuery}, "?")
  396. }
  397. err = hpackEnc.WriteField(hpack.HeaderField{
  398. Name: ":path",
  399. Value: path,
  400. })
  401. if err != nil {
  402. return nil, err
  403. }
  404. // TODO Implement Section 8.3
  405. for header, values := range r.Header {
  406. // Skip non h2 headers
  407. if isNonH2Header(header) {
  408. continue
  409. }
  410. for _, v := range values {
  411. err := hpackEnc.WriteField(hpack.HeaderField{
  412. Name: strings.ToLower(header),
  413. Value: v,
  414. })
  415. if err != nil {
  416. return nil, err
  417. }
  418. }
  419. }
  420. return headerBytes.Bytes(), nil
  421. }
  422. // Connection specific headers listed in RFC 7540 Section 8.1.2.2 that are not
  423. // suppose to be transferred to HTTP/2. The Http2-Settings header is skipped
  424. // since already use to create the HTTP/2 SETTINGS frame.
  425. var nonH2Headers = []string{
  426. "Connection",
  427. "Keep-Alive",
  428. "Proxy-Connection",
  429. "Transfer-Encoding",
  430. "Upgrade",
  431. "Http2-Settings",
  432. }
  433. // isNonH2Header returns true if header should not be transferred to HTTP/2.
  434. func isNonH2Header(header string) bool {
  435. for _, nonH2h := range nonH2Headers {
  436. if header == nonH2h {
  437. return true
  438. }
  439. }
  440. return false
  441. }