205 lines
4.5 KiB
Go
205 lines
4.5 KiB
Go
package relay
|
|
|
|
import (
|
|
"context"
|
|
"crypto/subtle"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/coder/websocket"
|
|
)
|
|
|
|
type pair struct {
|
|
lease string
|
|
peers map[string]*websocket.Conn
|
|
ready chan struct{}
|
|
ctx context.Context
|
|
cancel context.CancelFunc
|
|
expires int64
|
|
}
|
|
|
|
type Node struct {
|
|
ID, Secret string
|
|
Capacity int
|
|
mu sync.Mutex
|
|
pairs map[string]*pair
|
|
used map[string]int64
|
|
revoked map[string]int64
|
|
bytes atomic.Int64
|
|
ctx context.Context
|
|
}
|
|
|
|
func NewNode(ctx context.Context, id, secret string, capacity int) *Node {
|
|
return &Node{ID: id, Secret: secret, Capacity: capacity, ctx: ctx, pairs: make(map[string]*pair), used: make(map[string]int64), revoked: make(map[string]int64)}
|
|
}
|
|
|
|
func (n *Node) cleanupLocked() {
|
|
now := time.Now().Unix()
|
|
for id, expiry := range n.used {
|
|
if expiry <= now {
|
|
delete(n.used, id)
|
|
}
|
|
}
|
|
for id, expiry := range n.revoked {
|
|
if expiry <= now {
|
|
delete(n.revoked, id)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (n *Node) Handler() http.Handler {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
|
n.mu.Lock()
|
|
count := len(n.pairs)
|
|
n.mu.Unlock()
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]any{"id": n.ID, "sessions": count, "capacity": n.Capacity, "bytes": n.bytes.Load()})
|
|
})
|
|
mux.HandleFunc("POST /internal/revoke", n.revoke)
|
|
mux.HandleFunc("GET /v2/tunnel", n.tunnel)
|
|
return mux
|
|
}
|
|
|
|
func (n *Node) revoke(w http.ResponseWriter, r *http.Request) {
|
|
if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+n.Secret)) != 1 {
|
|
http.Error(w, "unauthorized", 401)
|
|
return
|
|
}
|
|
var body struct {
|
|
Lease string `json:"lease"`
|
|
}
|
|
if json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&body) != nil || body.Lease == "" {
|
|
http.Error(w, "bad request", 400)
|
|
return
|
|
}
|
|
n.mu.Lock()
|
|
n.cleanupLocked()
|
|
n.revoked[body.Lease] = time.Now().Add(2 * time.Minute).Unix()
|
|
for _, p := range n.pairs {
|
|
if p.lease == body.Lease {
|
|
p.cancel()
|
|
}
|
|
}
|
|
n.mu.Unlock()
|
|
w.WriteHeader(204)
|
|
}
|
|
|
|
func (n *Node) tunnel(w http.ResponseWriter, r *http.Request) {
|
|
ticket, err := Verify(n.Secret, strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "), n.ID, time.Now())
|
|
if err != nil {
|
|
http.Error(w, "unauthorized", 401)
|
|
return
|
|
}
|
|
n.mu.Lock()
|
|
n.cleanupLocked()
|
|
key := ticket.Session + ":" + ticket.Side
|
|
if n.revoked[ticket.Lease] > 0 || n.used[key] > 0 {
|
|
n.mu.Unlock()
|
|
http.Error(w, "revoked or replayed ticket", 409)
|
|
return
|
|
}
|
|
p := n.pairs[ticket.Session]
|
|
if p == nil {
|
|
if len(n.pairs) >= n.Capacity {
|
|
n.mu.Unlock()
|
|
http.Error(w, "node full", 429)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithCancel(n.ctx)
|
|
p = &pair{lease: ticket.Lease, peers: make(map[string]*websocket.Conn), ready: make(chan struct{}), ctx: ctx, cancel: cancel, expires: ticket.Expires}
|
|
n.pairs[ticket.Session] = p
|
|
}
|
|
if p.lease != ticket.Lease || p.ctx.Err() != nil {
|
|
n.mu.Unlock()
|
|
http.Error(w, "session closed", 409)
|
|
return
|
|
}
|
|
n.used[key] = ticket.Expires
|
|
n.mu.Unlock()
|
|
defer func() {
|
|
p.cancel()
|
|
n.mu.Lock()
|
|
if n.pairs[ticket.Session] == p {
|
|
delete(n.pairs, ticket.Session)
|
|
}
|
|
n.mu.Unlock()
|
|
}()
|
|
ws, err := websocket.Accept(w, r, nil)
|
|
if err != nil {
|
|
p.cancel()
|
|
return
|
|
}
|
|
defer ws.CloseNow()
|
|
ws.SetReadLimit(128 * 1024)
|
|
n.mu.Lock()
|
|
if p.ctx.Err() != nil {
|
|
n.mu.Unlock()
|
|
return
|
|
}
|
|
p.peers[ticket.Side] = ws
|
|
if len(p.peers) == 2 {
|
|
close(p.ready)
|
|
}
|
|
n.mu.Unlock()
|
|
timer := time.NewTimer(15 * time.Second)
|
|
defer timer.Stop()
|
|
select {
|
|
case <-p.ready:
|
|
case <-p.ctx.Done():
|
|
return
|
|
case <-timer.C:
|
|
return
|
|
}
|
|
// Only the client handler owns copying; both handlers remain until it ends.
|
|
if ticket.Side == "client" {
|
|
n.mu.Lock()
|
|
agent := p.peers["agent"]
|
|
n.mu.Unlock()
|
|
n.copy(p.ctx, ws, agent)
|
|
p.cancel()
|
|
} else {
|
|
<-p.ctx.Done()
|
|
}
|
|
}
|
|
|
|
func (n *Node) copy(parent context.Context, a, b *websocket.Conn) {
|
|
ctx, cancel := context.WithCancel(parent)
|
|
defer cancel()
|
|
var wg sync.WaitGroup
|
|
copyOne := func(dst, src *websocket.Conn) {
|
|
defer wg.Done()
|
|
defer cancel()
|
|
for {
|
|
typ, data, err := src.Read(ctx)
|
|
if err != nil || typ != websocket.MessageBinary {
|
|
return
|
|
}
|
|
deadline, stop := context.WithTimeout(ctx, 30*time.Second)
|
|
err = dst.Write(deadline, typ, data)
|
|
stop()
|
|
if err != nil {
|
|
return
|
|
}
|
|
n.bytes.Add(int64(len(data)))
|
|
}
|
|
}
|
|
wg.Add(2)
|
|
go copyOne(a, b)
|
|
go copyOne(b, a)
|
|
wg.Wait()
|
|
}
|
|
|
|
func (n *Node) Close() {
|
|
n.mu.Lock()
|
|
defer n.mu.Unlock()
|
|
for _, p := range n.pairs {
|
|
p.cancel()
|
|
}
|
|
}
|