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-02-28 21:18:10 +00:00
|
|
|
"log"
|
2020-02-05 22:16:58 +00:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"tailscale.com/derp"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Handler(s *derp.Server) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2020-02-28 21:18:10 +00:00
|
|
|
if p := r.Header.Get("Upgrade"); p != "WebSocket" && p != "DERP" {
|
2020-02-05 22:16:58 +00:00
|
|
|
http.Error(w, "DERP requires connection upgrade", http.StatusUpgradeRequired)
|
|
|
|
return
|
|
|
|
}
|
2020-02-28 21:18:10 +00:00
|
|
|
w.Header().Set("Upgrade", "DERP")
|
2020-02-05 22:16:58 +00:00
|
|
|
w.Header().Set("Connection", "Upgrade")
|
|
|
|
w.WriteHeader(http.StatusSwitchingProtocols)
|
|
|
|
|
|
|
|
h, ok := w.(http.Hijacker)
|
|
|
|
if !ok {
|
|
|
|
http.Error(w, "HTTP does not support general TCP support", 500)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
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
|
|
|
|
}
|
|
|
|
s.Accept(netConn, conn)
|
|
|
|
})
|
|
|
|
}
|