Skip to content
This repository has been archived by the owner on Oct 7, 2023. It is now read-only.

Add support for an HTTP reverse proxy #5

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,26 @@ Configuration should look like this:
]
```

There is also support for HTTP proxying:

```json
[
{
"from": 443,
"to": "http://127.0.0.1:8000/",
"tls": true,
"protocol": "http",
"http": {
"host": "localhost",
"headers": {
"User-Agent": "SomeAgent/2.0"
}
}
}
]
```


## Disclaimer

THIS IS NOT OFFICIALLY ENDORSED BY TAILSCALE.
Expand Down
70 changes: 67 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import (
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sync"

Expand All @@ -16,9 +19,16 @@ import (
)

type Binding struct {
From uint16 `json:"from"`
To string `json:"to"`
Tls bool `json:"tls"`
From uint16 `json:"from"`
To string `json:"to"`
Tls bool `json:"tls"`
Protocol string `json:"protocol"`
Http *HttpBinding `json:"http"`
}

type HttpBinding struct {
Host string `json:"host"`
Headers map[string]string `json:"headers"`
}

func loadBindings() ([]Binding, error) {
Expand Down Expand Up @@ -81,6 +91,60 @@ func proxyBind(s *tsnet.Server, b *Binding) {
})
}

if b.Protocol == "http" {
serveHTTP(b, ln)
} else if b.Protocol == "tcp" || b.Protocol == "" {
serveTCP(b, ln)
} else {
log.Printf("unknown protocol %q", b.Protocol)
}

}

func serveHTTP(b *Binding, ln net.Listener) {
uri, err := url.Parse(b.To)
if err != nil {
var err2 error
uri, err2 = url.Parse("http://" + b.To)
if err2 != nil {
log.Println(err)
return
}
}

proxy := httputil.NewSingleHostReverseProxy(uri)

if b.Http != nil {
originalDirector := proxy.Director
proxy.Director = func(req *http.Request) {
originalDirector(req)

for k, v := range b.Http.Headers {
req.Header.Set(k, v)
}

if b.Http.Host != "" {
req.Host = b.Http.Host
}
}
}

log.Printf("started proxy bind from %d to %v (tls: %t)", b.From, uri.String(), b.Tls)

mux := http.NewServeMux()

// handle all requests to your server using the proxy
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
proxy.ServeHTTP(w, r)
})

err = http.Serve(ln, mux)
if err != nil {
log.Println(err)
}
}

func serveTCP(b *Binding, ln net.Listener) {
log.Printf("started proxy bind from %d to %v (tls: %t)", b.From, b.To, b.Tls)

for {
Expand Down