server.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (c) 2021 Tailscale Inc & 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 controlhttp
  5. import (
  6. "context"
  7. "encoding/base64"
  8. "errors"
  9. "fmt"
  10. "net/http"
  11. "tailscale.com/control/controlbase"
  12. "tailscale.com/net/netutil"
  13. "tailscale.com/types/key"
  14. )
  15. // AcceptHTTP upgrades the HTTP request given by w and r into a
  16. // Tailscale control protocol base transport connection.
  17. //
  18. // AcceptHTTP always writes an HTTP response to w. The caller must not
  19. // attempt their own response after calling AcceptHTTP.
  20. func AcceptHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request, private key.MachinePrivate) (*controlbase.Conn, error) {
  21. next := r.Header.Get("Upgrade")
  22. if next == "" {
  23. http.Error(w, "missing next protocol", http.StatusBadRequest)
  24. return nil, errors.New("no next protocol in HTTP request")
  25. }
  26. if next != upgradeHeaderValue {
  27. http.Error(w, "unknown next protocol", http.StatusBadRequest)
  28. return nil, fmt.Errorf("client requested unhandled next protocol %q", next)
  29. }
  30. initB64 := r.Header.Get(handshakeHeaderName)
  31. if initB64 == "" {
  32. http.Error(w, "missing Tailscale handshake header", http.StatusBadRequest)
  33. return nil, errors.New("no tailscale handshake header in HTTP request")
  34. }
  35. init, err := base64.StdEncoding.DecodeString(initB64)
  36. if err != nil {
  37. http.Error(w, "invalid tailscale handshake header", http.StatusBadRequest)
  38. return nil, fmt.Errorf("decoding base64 handshake header: %v", err)
  39. }
  40. hijacker, ok := w.(http.Hijacker)
  41. if !ok {
  42. http.Error(w, "make request over HTTP/1", http.StatusBadRequest)
  43. return nil, errors.New("can't hijack client connection")
  44. }
  45. w.Header().Set("Upgrade", upgradeHeaderValue)
  46. w.Header().Set("Connection", "upgrade")
  47. w.WriteHeader(http.StatusSwitchingProtocols)
  48. conn, brw, err := hijacker.Hijack()
  49. if err != nil {
  50. return nil, fmt.Errorf("hijacking client connection: %w", err)
  51. }
  52. if err := brw.Flush(); err != nil {
  53. conn.Close()
  54. return nil, fmt.Errorf("flushing hijacked HTTP buffer: %w", err)
  55. }
  56. conn = netutil.NewDrainBufConn(conn, brw.Reader)
  57. nc, err := controlbase.Server(ctx, conn, private, init)
  58. if err != nil {
  59. conn.Close()
  60. return nil, fmt.Errorf("noise handshake failed: %w", err)
  61. }
  62. return nc, nil
  63. }