http2.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Package http2 implements the HTTP/2 protocol.
  2. //
  3. // It currently targets draft-13. See http://http2.github.io/
  4. package http2
  5. import (
  6. "bytes"
  7. "crypto/tls"
  8. "io"
  9. "log"
  10. "net/http"
  11. "sync"
  12. )
  13. const (
  14. // ClientPreface is the string that must be sent by new
  15. // connections from clients.
  16. ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
  17. )
  18. var (
  19. clientPreface = []byte(ClientPreface)
  20. )
  21. const npnProto = "h2-13"
  22. // Server is an HTTP2 server.
  23. type Server struct {
  24. // MaxStreams optionally ...
  25. MaxStreams int
  26. mu sync.Mutex
  27. }
  28. func (srv *Server) handleClientConn(hs *http.Server, c *tls.Conn, h http.Handler) {
  29. cc := &clientConn{hs, c, h}
  30. cc.serve()
  31. }
  32. type clientConn struct {
  33. hs *http.Server
  34. c *tls.Conn
  35. h http.Handler
  36. }
  37. func (cc *clientConn) logf(format string, args ...interface{}) {
  38. if lg := cc.hs.ErrorLog; lg != nil {
  39. lg.Printf(format, args...)
  40. } else {
  41. log.Printf(format, args...)
  42. }
  43. }
  44. func (cc *clientConn) serve() {
  45. defer cc.c.Close()
  46. log.Printf("HTTP/2 connection from %v on %p", cc.c.RemoteAddr(), cc.hs)
  47. buf := make([]byte, len(ClientPreface))
  48. // TODO: timeout reading from the client
  49. if _, err := io.ReadFull(cc.c, buf); err != nil {
  50. cc.logf("error reading client preface: %v", err)
  51. return
  52. }
  53. if !bytes.Equal(buf, clientPreface) {
  54. cc.logf("bogus greeting from client: %q", buf)
  55. return
  56. }
  57. log.Printf("client %v said hello", cc.c.RemoteAddr())
  58. }
  59. // ConfigureServer adds HTTP2 support to s as configured by the HTTP/2
  60. // server configuration in conf. The configuration may be nil.
  61. //
  62. // ConfigureServer must be called before s beings serving.
  63. func ConfigureServer(s *http.Server, conf *Server) {
  64. if conf == nil {
  65. conf = new(Server)
  66. }
  67. if s.TLSConfig == nil {
  68. s.TLSConfig = new(tls.Config)
  69. }
  70. haveNPN := false
  71. for _, p := range s.TLSConfig.NextProtos {
  72. if p == npnProto {
  73. haveNPN = true
  74. break
  75. }
  76. }
  77. if !haveNPN {
  78. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, npnProto)
  79. }
  80. if s.TLSNextProto == nil {
  81. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  82. }
  83. s.TLSNextProto[npnProto] = func(hs *http.Server, c *tls.Conn, h http.Handler) {
  84. conf.handleClientConn(hs, c, h)
  85. }
  86. }