2020-02-05 22:16:58 +00:00
|
|
|
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package derphttp
|
|
|
|
|
|
|
|
import (
|
2020-08-18 22:32:32 +00:00
|
|
|
"fmt"
|
2020-02-28 21:18:10 +00:00
|
|
|
"log"
|
2020-02-05 22:16:58 +00:00
|
|
|
"net/http"
|
2021-10-21 17:12:51 +00:00
|
|
|
"strings"
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
"tailscale.com/derp"
|
|
|
|
)
|
|
|
|
|
2020-08-18 22:32:32 +00:00
|
|
|
// fastStartHeader is the header (with value "1") that signals to the HTTP
|
|
|
|
// server that the DERP HTTP client does not want the HTTP 101 response
|
|
|
|
// headers and it will begin writing & reading the DERP protocol immediately
|
|
|
|
// following its HTTP request.
|
|
|
|
const fastStartHeader = "Derp-Fast-Start"
|
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
func Handler(s *derp.Server) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2021-10-21 17:12:51 +00:00
|
|
|
up := strings.ToLower(r.Header.Get("Upgrade"))
|
|
|
|
if up != "websocket" && up != "derp" {
|
2021-10-27 16:41:25 +00:00
|
|
|
if up != "" {
|
|
|
|
log.Printf("Weird upgrade: %q", up)
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
http.Error(w, "DERP requires connection upgrade", http.StatusUpgradeRequired)
|
|
|
|
return
|
|
|
|
}
|
2021-10-21 17:12:51 +00:00
|
|
|
|
2020-08-18 22:32:32 +00:00
|
|
|
fastStart := r.Header.Get(fastStartHeader) == "1"
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
h, ok := w.(http.Hijacker)
|
|
|
|
if !ok {
|
|
|
|
http.Error(w, "HTTP does not support general TCP support", 500)
|
|
|
|
return
|
|
|
|
}
|
2020-08-18 22:32:32 +00:00
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
netConn, conn, err := h.Hijack()
|
|
|
|
if err != nil {
|
2020-02-28 21:18:10 +00:00
|
|
|
log.Printf("Hijack failed: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
http.Error(w, "HTTP does not support general TCP support", 500)
|
|
|
|
return
|
|
|
|
}
|
2020-08-18 22:32:32 +00:00
|
|
|
|
|
|
|
if !fastStart {
|
|
|
|
pubKey := s.PublicKey()
|
|
|
|
fmt.Fprintf(conn, "HTTP/1.1 101 Switching Protocols\r\n"+
|
|
|
|
"Upgrade: DERP\r\n"+
|
|
|
|
"Connection: Upgrade\r\n"+
|
|
|
|
"Derp-Version: %v\r\n"+
|
2021-10-28 22:42:50 +00:00
|
|
|
"Derp-Public-Key: %s\r\n\r\n",
|
2020-08-18 22:32:32 +00:00
|
|
|
derp.ProtocolVersion,
|
2021-10-28 22:42:50 +00:00
|
|
|
pubKey.UntypedHexString())
|
2020-08-18 22:32:32 +00:00
|
|
|
}
|
|
|
|
|
2022-07-18 22:43:03 +00:00
|
|
|
s.Accept(r.Context(), netConn, conn, netConn.RemoteAddr().String())
|
2020-02-05 22:16:58 +00:00
|
|
|
})
|
|
|
|
}
|