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.

538 lines
16 KiB

  1. // Copyright 2014 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. // +build h2demo
  5. package main
  6. import (
  7. "bytes"
  8. "crypto/tls"
  9. "flag"
  10. "fmt"
  11. "hash/crc32"
  12. "image"
  13. "image/jpeg"
  14. "io"
  15. "io/ioutil"
  16. "log"
  17. "net"
  18. "net/http"
  19. "os"
  20. "path"
  21. "regexp"
  22. "runtime"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "time"
  27. "go4.org/syncutil/singleflight"
  28. "golang.org/x/crypto/acme/autocert"
  29. "golang.org/x/net/http2"
  30. )
  31. var (
  32. prod = flag.Bool("prod", false, "Whether to configure itself to be the production http2.golang.org server.")
  33. httpsAddr = flag.String("https_addr", "localhost:4430", "TLS address to listen on ('host:port' or ':port'). Required.")
  34. httpAddr = flag.String("http_addr", "", "Plain HTTP address to listen on ('host:port', or ':port'). Empty means no HTTP.")
  35. hostHTTP = flag.String("http_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -http_addr.")
  36. hostHTTPS = flag.String("https_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -https_addr.")
  37. )
  38. func homeOldHTTP(w http.ResponseWriter, r *http.Request) {
  39. io.WriteString(w, `<html>
  40. <body>
  41. <h1>Go + HTTP/2</h1>
  42. <p>Welcome to <a href="https://golang.org/">the Go language</a>'s <a href="https://http2.github.io/">HTTP/2</a> demo & interop server.</p>
  43. <p>Unfortunately, you're <b>not</b> using HTTP/2 right now. To do so:</p>
  44. <ul>
  45. <li>Use Firefox Nightly or go to <b>about:config</b> and enable "network.http.spdy.enabled.http2draft"</li>
  46. <li>Use Google Chrome Canary and/or go to <b>chrome://flags/#enable-spdy4</b> to <i>Enable SPDY/4</i> (Chrome's name for HTTP/2)</li>
  47. </ul>
  48. <p>See code & instructions for connecting at <a href="https://github.com/golang/net/tree/master/http2">https://github.com/golang/net/tree/master/http2</a>.</p>
  49. </body></html>`)
  50. }
  51. func home(w http.ResponseWriter, r *http.Request) {
  52. if r.URL.Path != "/" {
  53. http.NotFound(w, r)
  54. return
  55. }
  56. io.WriteString(w, `<html>
  57. <body>
  58. <h1>Go + HTTP/2</h1>
  59. <p>Welcome to <a href="https://golang.org/">the Go language</a>'s <a
  60. href="https://http2.github.io/">HTTP/2</a> demo & interop server.</p>
  61. <p>Congratulations, <b>you're using HTTP/2 right now</b>.</p>
  62. <p>This server exists for others in the HTTP/2 community to test their HTTP/2 client implementations and point out flaws in our server.</p>
  63. <p>
  64. The code is at <a href="https://golang.org/x/net/http2">golang.org/x/net/http2</a> and
  65. is used transparently by the Go standard library from Go 1.6 and later.
  66. </p>
  67. <p>Contact info: <i>bradfitz@golang.org</i>, or <a
  68. href="https://golang.org/s/http2bug">file a bug</a>.</p>
  69. <h2>Handlers for testing</h2>
  70. <ul>
  71. <li>GET <a href="/reqinfo">/reqinfo</a> to dump the request + headers received</li>
  72. <li>GET <a href="/clockstream">/clockstream</a> streams the current time every second</li>
  73. <li>GET <a href="/gophertiles">/gophertiles</a> to see a page with a bunch of images</li>
  74. <li>GET <a href="/serverpush">/serverpush</a> to see a page with server push</li>
  75. <li>GET <a href="/file/gopher.png">/file/gopher.png</a> for a small file (does If-Modified-Since, Content-Range, etc)</li>
  76. <li>GET <a href="/file/go.src.tar.gz">/file/go.src.tar.gz</a> for a larger file (~10 MB)</li>
  77. <li>GET <a href="/redirect">/redirect</a> to redirect back to / (this page)</li>
  78. <li>GET <a href="/goroutines">/goroutines</a> to see all active goroutines in this server</li>
  79. <li>PUT something to <a href="/crc32">/crc32</a> to get a count of number of bytes and its CRC-32</li>
  80. <li>PUT something to <a href="/ECHO">/ECHO</a> and it will be streamed back to you capitalized</li>
  81. </ul>
  82. </body></html>`)
  83. }
  84. func reqInfoHandler(w http.ResponseWriter, r *http.Request) {
  85. w.Header().Set("Content-Type", "text/plain")
  86. fmt.Fprintf(w, "Method: %s\n", r.Method)
  87. fmt.Fprintf(w, "Protocol: %s\n", r.Proto)
  88. fmt.Fprintf(w, "Host: %s\n", r.Host)
  89. fmt.Fprintf(w, "RemoteAddr: %s\n", r.RemoteAddr)
  90. fmt.Fprintf(w, "RequestURI: %q\n", r.RequestURI)
  91. fmt.Fprintf(w, "URL: %#v\n", r.URL)
  92. fmt.Fprintf(w, "Body.ContentLength: %d (-1 means unknown)\n", r.ContentLength)
  93. fmt.Fprintf(w, "Close: %v (relevant for HTTP/1 only)\n", r.Close)
  94. fmt.Fprintf(w, "TLS: %#v\n", r.TLS)
  95. fmt.Fprintf(w, "\nHeaders:\n")
  96. r.Header.Write(w)
  97. }
  98. func crcHandler(w http.ResponseWriter, r *http.Request) {
  99. if r.Method != "PUT" {
  100. http.Error(w, "PUT required.", 400)
  101. return
  102. }
  103. crc := crc32.NewIEEE()
  104. n, err := io.Copy(crc, r.Body)
  105. if err == nil {
  106. w.Header().Set("Content-Type", "text/plain")
  107. fmt.Fprintf(w, "bytes=%d, CRC32=%x", n, crc.Sum(nil))
  108. }
  109. }
  110. type capitalizeReader struct {
  111. r io.Reader
  112. }
  113. func (cr capitalizeReader) Read(p []byte) (n int, err error) {
  114. n, err = cr.r.Read(p)
  115. for i, b := range p[:n] {
  116. if b >= 'a' && b <= 'z' {
  117. p[i] = b - ('a' - 'A')
  118. }
  119. }
  120. return
  121. }
  122. type flushWriter struct {
  123. w io.Writer
  124. }
  125. func (fw flushWriter) Write(p []byte) (n int, err error) {
  126. n, err = fw.w.Write(p)
  127. if f, ok := fw.w.(http.Flusher); ok {
  128. f.Flush()
  129. }
  130. return
  131. }
  132. func echoCapitalHandler(w http.ResponseWriter, r *http.Request) {
  133. if r.Method != "PUT" {
  134. http.Error(w, "PUT required.", 400)
  135. return
  136. }
  137. io.Copy(flushWriter{w}, capitalizeReader{r.Body})
  138. }
  139. var (
  140. fsGrp singleflight.Group
  141. fsMu sync.Mutex // guards fsCache
  142. fsCache = map[string]http.Handler{}
  143. )
  144. // fileServer returns a file-serving handler that proxies URL.
  145. // It lazily fetches URL on the first access and caches its contents forever.
  146. func fileServer(url string, latency time.Duration) http.Handler {
  147. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  148. if latency > 0 {
  149. time.Sleep(latency)
  150. }
  151. hi, err := fsGrp.Do(url, func() (interface{}, error) {
  152. fsMu.Lock()
  153. if h, ok := fsCache[url]; ok {
  154. fsMu.Unlock()
  155. return h, nil
  156. }
  157. fsMu.Unlock()
  158. res, err := http.Get(url)
  159. if err != nil {
  160. return nil, err
  161. }
  162. defer res.Body.Close()
  163. slurp, err := ioutil.ReadAll(res.Body)
  164. if err != nil {
  165. return nil, err
  166. }
  167. modTime := time.Now()
  168. var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  169. http.ServeContent(w, r, path.Base(url), modTime, bytes.NewReader(slurp))
  170. })
  171. fsMu.Lock()
  172. fsCache[url] = h
  173. fsMu.Unlock()
  174. return h, nil
  175. })
  176. if err != nil {
  177. http.Error(w, err.Error(), 500)
  178. return
  179. }
  180. hi.(http.Handler).ServeHTTP(w, r)
  181. })
  182. }
  183. func clockStreamHandler(w http.ResponseWriter, r *http.Request) {
  184. clientGone := w.(http.CloseNotifier).CloseNotify()
  185. w.Header().Set("Content-Type", "text/plain")
  186. ticker := time.NewTicker(1 * time.Second)
  187. defer ticker.Stop()
  188. fmt.Fprintf(w, "# ~1KB of junk to force browsers to start rendering immediately: \n")
  189. io.WriteString(w, strings.Repeat("# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n", 13))
  190. for {
  191. fmt.Fprintf(w, "%v\n", time.Now())
  192. w.(http.Flusher).Flush()
  193. select {
  194. case <-ticker.C:
  195. case <-clientGone:
  196. log.Printf("Client %v disconnected from the clock", r.RemoteAddr)
  197. return
  198. }
  199. }
  200. }
  201. func registerHandlers() {
  202. tiles := newGopherTilesHandler()
  203. push := newPushHandler()
  204. mux2 := http.NewServeMux()
  205. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  206. switch {
  207. case r.URL.Path == "/gophertiles":
  208. tiles.ServeHTTP(w, r) // allow HTTP/2 + HTTP/1.x
  209. return
  210. case strings.HasPrefix(r.URL.Path, "/serverpush"):
  211. push.ServeHTTP(w, r) // allow HTTP/2 + HTTP/1.x
  212. return
  213. case r.TLS == nil: // do not allow HTTP/1.x for anything else
  214. http.Redirect(w, r, "https://"+httpsHost()+"/", http.StatusFound)
  215. return
  216. }
  217. if r.ProtoMajor == 1 {
  218. if r.URL.Path == "/reqinfo" {
  219. reqInfoHandler(w, r)
  220. return
  221. }
  222. homeOldHTTP(w, r)
  223. return
  224. }
  225. mux2.ServeHTTP(w, r)
  226. })
  227. mux2.HandleFunc("/", home)
  228. mux2.Handle("/file/gopher.png", fileServer("https://golang.org/doc/gopher/frontpage.png", 0))
  229. mux2.Handle("/file/go.src.tar.gz", fileServer("https://storage.googleapis.com/golang/go1.4.1.src.tar.gz", 0))
  230. mux2.HandleFunc("/reqinfo", reqInfoHandler)
  231. mux2.HandleFunc("/crc32", crcHandler)
  232. mux2.HandleFunc("/ECHO", echoCapitalHandler)
  233. mux2.HandleFunc("/clockstream", clockStreamHandler)
  234. mux2.Handle("/gophertiles", tiles)
  235. mux2.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
  236. http.Redirect(w, r, "/", http.StatusFound)
  237. })
  238. stripHomedir := regexp.MustCompile(`/(Users|home)/\w+`)
  239. mux2.HandleFunc("/goroutines", func(w http.ResponseWriter, r *http.Request) {
  240. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  241. buf := make([]byte, 2<<20)
  242. w.Write(stripHomedir.ReplaceAll(buf[:runtime.Stack(buf, true)], nil))
  243. })
  244. }
  245. var pushResources = map[string]http.Handler{
  246. "/serverpush/static/jquery.min.js": fileServer("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", 100*time.Millisecond),
  247. "/serverpush/static/godocs.js": fileServer("https://golang.org/lib/godoc/godocs.js", 100*time.Millisecond),
  248. "/serverpush/static/playground.js": fileServer("https://golang.org/lib/godoc/playground.js", 100*time.Millisecond),
  249. "/serverpush/static/style.css": fileServer("https://golang.org/lib/godoc/style.css", 100*time.Millisecond),
  250. }
  251. func newPushHandler() http.Handler {
  252. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  253. for path, handler := range pushResources {
  254. if r.URL.Path == path {
  255. handler.ServeHTTP(w, r)
  256. return
  257. }
  258. }
  259. cacheBust := time.Now().UnixNano()
  260. if pusher, ok := w.(http.Pusher); ok {
  261. for path := range pushResources {
  262. url := fmt.Sprintf("%s?%d", path, cacheBust)
  263. if err := pusher.Push(url, nil); err != nil {
  264. log.Printf("Failed to push %v: %v", path, err)
  265. }
  266. }
  267. }
  268. time.Sleep(100 * time.Millisecond) // fake network latency + parsing time
  269. if err := pushTmpl.Execute(w, struct {
  270. CacheBust int64
  271. HTTPSHost string
  272. HTTPHost string
  273. }{
  274. CacheBust: cacheBust,
  275. HTTPSHost: httpsHost(),
  276. HTTPHost: httpHost(),
  277. }); err != nil {
  278. log.Printf("Executing server push template: %v", err)
  279. }
  280. })
  281. }
  282. func newGopherTilesHandler() http.Handler {
  283. const gopherURL = "https://blog.golang.org/go-programming-language-turns-two_gophers.jpg"
  284. res, err := http.Get(gopherURL)
  285. if err != nil {
  286. log.Fatal(err)
  287. }
  288. if res.StatusCode != 200 {
  289. log.Fatalf("Error fetching %s: %v", gopherURL, res.Status)
  290. }
  291. slurp, err := ioutil.ReadAll(res.Body)
  292. res.Body.Close()
  293. if err != nil {
  294. log.Fatal(err)
  295. }
  296. im, err := jpeg.Decode(bytes.NewReader(slurp))
  297. if err != nil {
  298. if len(slurp) > 1024 {
  299. slurp = slurp[:1024]
  300. }
  301. log.Fatalf("Failed to decode gopher image: %v (got %q)", err, slurp)
  302. }
  303. type subImager interface {
  304. SubImage(image.Rectangle) image.Image
  305. }
  306. const tileSize = 32
  307. xt := im.Bounds().Max.X / tileSize
  308. yt := im.Bounds().Max.Y / tileSize
  309. var tile [][][]byte // y -> x -> jpeg bytes
  310. for yi := 0; yi < yt; yi++ {
  311. var row [][]byte
  312. for xi := 0; xi < xt; xi++ {
  313. si := im.(subImager).SubImage(image.Rectangle{
  314. Min: image.Point{xi * tileSize, yi * tileSize},
  315. Max: image.Point{(xi + 1) * tileSize, (yi + 1) * tileSize},
  316. })
  317. buf := new(bytes.Buffer)
  318. if err := jpeg.Encode(buf, si, &jpeg.Options{Quality: 90}); err != nil {
  319. log.Fatal(err)
  320. }
  321. row = append(row, buf.Bytes())
  322. }
  323. tile = append(tile, row)
  324. }
  325. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  326. ms, _ := strconv.Atoi(r.FormValue("latency"))
  327. const nanosPerMilli = 1e6
  328. if r.FormValue("x") != "" {
  329. x, _ := strconv.Atoi(r.FormValue("x"))
  330. y, _ := strconv.Atoi(r.FormValue("y"))
  331. if ms <= 1000 {
  332. time.Sleep(time.Duration(ms) * nanosPerMilli)
  333. }
  334. if x >= 0 && x < xt && y >= 0 && y < yt {
  335. http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(tile[y][x]))
  336. return
  337. }
  338. }
  339. io.WriteString(w, "<html><body onload='showtimes()'>")
  340. fmt.Fprintf(w, "A grid of %d tiled images is below. Compare:<p>", xt*yt)
  341. for _, ms := range []int{0, 30, 200, 1000} {
  342. d := time.Duration(ms) * nanosPerMilli
  343. fmt.Fprintf(w, "[<a href='https://%s/gophertiles?latency=%d'>HTTP/2, %v latency</a>] [<a href='http://%s/gophertiles?latency=%d'>HTTP/1, %v latency</a>]<br>\n",
  344. httpsHost(), ms, d,
  345. httpHost(), ms, d,
  346. )
  347. }
  348. io.WriteString(w, "<p>\n")
  349. cacheBust := time.Now().UnixNano()
  350. for y := 0; y < yt; y++ {
  351. for x := 0; x < xt; x++ {
  352. fmt.Fprintf(w, "<img width=%d height=%d src='/gophertiles?x=%d&y=%d&cachebust=%d&latency=%d'>",
  353. tileSize, tileSize, x, y, cacheBust, ms)
  354. }
  355. io.WriteString(w, "<br/>\n")
  356. }
  357. io.WriteString(w, `<p><div id='loadtimes'></div></p>
  358. <script>
  359. function showtimes() {
  360. var times = 'Times from connection start:<br>'
  361. times += 'DOM loaded: ' + (window.performance.timing.domContentLoadedEventEnd - window.performance.timing.connectStart) + 'ms<br>'
  362. times += 'DOM complete (images loaded): ' + (window.performance.timing.domComplete - window.performance.timing.connectStart) + 'ms<br>'
  363. document.getElementById('loadtimes').innerHTML = times
  364. }
  365. </script>
  366. <hr><a href='/'>&lt;&lt Back to Go HTTP/2 demo server</a></body></html>`)
  367. })
  368. }
  369. func httpsHost() string {
  370. if *hostHTTPS != "" {
  371. return *hostHTTPS
  372. }
  373. if v := *httpsAddr; strings.HasPrefix(v, ":") {
  374. return "localhost" + v
  375. } else {
  376. return v
  377. }
  378. }
  379. func httpHost() string {
  380. if *hostHTTP != "" {
  381. return *hostHTTP
  382. }
  383. if v := *httpAddr; strings.HasPrefix(v, ":") {
  384. return "localhost" + v
  385. } else {
  386. return v
  387. }
  388. }
  389. func serveProdTLS() error {
  390. const cacheDir = "/var/cache/autocert"
  391. if err := os.MkdirAll(cacheDir, 0700); err != nil {
  392. return err
  393. }
  394. m := autocert.Manager{
  395. Cache: autocert.DirCache(cacheDir),
  396. Prompt: autocert.AcceptTOS,
  397. HostPolicy: autocert.HostWhitelist("http2.golang.org"),
  398. }
  399. srv := &http.Server{
  400. TLSConfig: &tls.Config{
  401. GetCertificate: m.GetCertificate,
  402. },
  403. }
  404. http2.ConfigureServer(srv, &http2.Server{
  405. NewWriteScheduler: func() http2.WriteScheduler {
  406. return http2.NewPriorityWriteScheduler(nil)
  407. },
  408. })
  409. ln, err := net.Listen("tcp", ":443")
  410. if err != nil {
  411. return err
  412. }
  413. return srv.Serve(tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig))
  414. }
  415. type tcpKeepAliveListener struct {
  416. *net.TCPListener
  417. }
  418. func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
  419. tc, err := ln.AcceptTCP()
  420. if err != nil {
  421. return
  422. }
  423. tc.SetKeepAlive(true)
  424. tc.SetKeepAlivePeriod(3 * time.Minute)
  425. return tc, nil
  426. }
  427. func serveProd() error {
  428. errc := make(chan error, 2)
  429. go func() { errc <- http.ListenAndServe(":80", nil) }()
  430. go func() { errc <- serveProdTLS() }()
  431. return <-errc
  432. }
  433. const idleTimeout = 5 * time.Minute
  434. const activeTimeout = 10 * time.Minute
  435. // TODO: put this into the standard library and actually send
  436. // PING frames and GOAWAY, etc: golang.org/issue/14204
  437. func idleTimeoutHook() func(net.Conn, http.ConnState) {
  438. var mu sync.Mutex
  439. m := map[net.Conn]*time.Timer{}
  440. return func(c net.Conn, cs http.ConnState) {
  441. mu.Lock()
  442. defer mu.Unlock()
  443. if t, ok := m[c]; ok {
  444. delete(m, c)
  445. t.Stop()
  446. }
  447. var d time.Duration
  448. switch cs {
  449. case http.StateNew, http.StateIdle:
  450. d = idleTimeout
  451. case http.StateActive:
  452. d = activeTimeout
  453. default:
  454. return
  455. }
  456. m[c] = time.AfterFunc(d, func() {
  457. log.Printf("closing idle conn %v after %v", c.RemoteAddr(), d)
  458. go c.Close()
  459. })
  460. }
  461. }
  462. func main() {
  463. var srv http.Server
  464. flag.BoolVar(&http2.VerboseLogs, "verbose", false, "Verbose HTTP/2 debugging.")
  465. flag.Parse()
  466. srv.Addr = *httpsAddr
  467. srv.ConnState = idleTimeoutHook()
  468. registerHandlers()
  469. if *prod {
  470. *hostHTTP = "http2.golang.org"
  471. *hostHTTPS = "http2.golang.org"
  472. log.Fatal(serveProd())
  473. }
  474. url := "https://" + httpsHost() + "/"
  475. log.Printf("Listening on " + url)
  476. http2.ConfigureServer(&srv, &http2.Server{})
  477. if *httpAddr != "" {
  478. go func() {
  479. log.Printf("Listening on http://" + httpHost() + "/ (for unencrypted HTTP/1)")
  480. log.Fatal(http.ListenAndServe(*httpAddr, nil))
  481. }()
  482. }
  483. go func() {
  484. log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
  485. }()
  486. select {}
  487. }