-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
68 lines (61 loc) · 1.85 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package tsproxy
import (
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"github.com/davecgh/go-spew/spew"
)
func init() {
_ = spew.Dump
}
type TailscaleHTTPProxyServer struct {
server *TailscaleProxyServer
proxy *httputil.ReverseProxy
}
func NewTailscaleHTTPProxyServer(server *TailscaleProxyServer) (Server, error) {
u := &url.URL{
Scheme: "http",
Host: server.Hostname(),
}
proxy := httputil.NewSingleHostReverseProxy(u)
proxy.Transport = &http.Transport{
Dial: server.Dial,
}
return &TailscaleHTTPProxyServer{
server: server,
proxy: proxy,
}, nil
}
func (tps *TailscaleHTTPProxyServer) Serve(l net.Listener) error {
server := http.Server{Handler: tps}
return server.Serve(l)
}
func (tps *TailscaleHTTPProxyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
userInfo, err := tps.server.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
log.Printf("error/http/ts-auth: %s", err.Error())
w.WriteHeader(500)
return
}
if r.URL.Hostname() != "" && r.URL.Hostname() != tps.server.Hostname() {
destinationURL := new(url.URL)
*destinationURL = *r.URL
destinationURL.Host = tps.server.Hostname() + tps.server.options.Listen
if tps.server.options.EnableTLS {
destinationURL.Scheme = "https"
} else {
destinationURL.Scheme = "http"
}
log.Printf("redirect: '%s' -> '%s'", r.URL.String(), destinationURL.String())
http.Redirect(w, r, destinationURL.String(), http.StatusMovedPermanently)
return
}
log.Printf("%s %s %s %s", r.Method, userInfo.UserProfile.LoginName, r.Host, r.URL.String())
r.Header.Set("Tailscale-User-Login", userInfo.UserProfile.LoginName)
r.Header.Set("Tailscale-User-Name", userInfo.UserProfile.DisplayName)
r.Header.Set("Tailscale-User-Profile-Pic", userInfo.UserProfile.ProfilePicURL)
r.Header.Set("Tailscale-Headers-Info", "https://tailscale.com/s/serve-headers")
tps.proxy.ServeHTTP(w, r)
}