package geckorelay import ( "bytes" "context" "encoding/binary" "encoding/json" "errors" "io" "net" "net/http" "path/filepath" "strings" "sync" "sync/atomic" "time" "golang.org/x/net/websocket" ) const ( window = 8 maxFrame = 256 << 10 maxStreams = 16 maxBytes = 256 << 20 bytesPerSecond = 2 << 20 ) type Relay struct { Key, Assets string mu sync.Mutex active map[string]bool used map[string]int64 rx, tx, rejected atomic.Int64 // Overridden only by package tests; deployment always resolves and pins public IPs. dial func(context.Context, string, uint16) (net.Conn, error) } func New(key, assets string) (*Relay, error) { if len(key) < 32 { return nil, errors.New("relay key must contain at least 32 bytes") } r := &Relay{Key: key, Assets: assets, active: map[string]bool{}, used: map[string]int64{}} r.dial = func(ctx context.Context, host string, port uint16) (net.Conn, error) { ctx, cancel := context.WithTimeout(ctx, 8*time.Second) defer cancel() return dialPublic(ctx, host, port, net.DefaultResolver.LookupNetIP, (&net.Dialer{Timeout: 2 * time.Second}).DialContext) } return r, nil } func (r *Relay) ServeHTTP(w http.ResponseWriter, req *http.Request) { w.Header().Set("Cache-Control", "no-store") if req.URL.Path == "/health" && req.Method == "GET" { io.WriteString(w, "ok") return } grant, err := Verify(r.Key, req.Header.Get(GrantHeader), time.Now()) if err != nil { http.Error(w, "forbidden", 403) return } if req.Method != "GET" || req.URL.RawQuery != "" { http.Error(w, "invalid request", 400) return } if req.URL.Path == "/status" { r.mu.Lock() active := len(r.active) r.mu.Unlock() w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]any{"active_sessions": active, "received_bytes": r.rx.Load(), "sent_bytes": r.tx.Load(), "rejected": r.rejected.Load(), "profile": "tcp-80-443", "max_sessions": 4, "max_streams": maxStreams, "bytes_per_second": bytesPerSecond, "max_session_bytes": maxBytes}) return } if req.URL.Path == AssetsPrefix+"gecko.js" || req.URL.Path == AssetsPrefix+"gecko.wasm.zst" { w.Header().Set("Cross-Origin-Resource-Policy", "same-origin") w.Header().Set("Cache-Control", "private, max-age=86400, immutable") if strings.HasSuffix(req.URL.Path, ".js") { w.Header().Set("Content-Type", "text/javascript") } else { w.Header().Set("Content-Type", "application/octet-stream") } http.ServeFile(w, req, filepath.Join(r.Assets, filepath.Base(req.URL.Path))) return } if req.URL.Path != "/wisp/" { http.NotFound(w, req) return } r.mu.Lock() now := time.Now().Unix() for nonce, expires := range r.used { if expires <= now { delete(r.used, nonce) } } if r.active[grant.Subject] || len(r.active) >= 4 || r.used[grant.Nonce] > now || len(r.used) >= 256 { r.mu.Unlock() r.rejected.Add(1) http.Error(w, "session limit", 429) return } r.active[grant.Subject] = true r.used[grant.Nonce] = grant.Expires r.mu.Unlock() defer func() { r.mu.Lock(); delete(r.active, grant.Subject); r.mu.Unlock() }() wsServer := websocket.Server{Handshake: func(c *websocket.Config, req *http.Request) error { // Only the authenticated PagesWiki proxy can sign a grant. It validates // the browser Origin before forwarding, not the untrusted client header. if req.Header.Get("Origin") == "" { return errors.New("origin required") } return nil }, Handler: func(ws *websocket.Conn) { r.serve(ws) }} wsServer.ServeHTTP(w, req) } type stream struct { data chan []byte done chan struct{} once sync.Once mu sync.Mutex conn net.Conn } func (s *stream) close() { s.once.Do(func() { close(s.done) s.mu.Lock() if s.conn != nil { s.conn.Close() } s.mu.Unlock() }) } func packet(kind byte, id uint32, data []byte) []byte { b := make([]byte, 5+len(data)) b[0] = kind binary.LittleEndian.PutUint32(b[1:], id) copy(b[5:], data) return b } func credit() []byte { b := make([]byte, 4); binary.LittleEndian.PutUint32(b, window); return b } func (r *Relay) serve(ws *websocket.Conn) { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute) defer cancel() defer ws.Close() ws.MaxPayloadBytes = maxFrame + 5 var mu, sendMu, budgetMu sync.Mutex streams := map[uint32]*stream{} var workers sync.WaitGroup var spent int64 tokens := float64(bytesPerSecond) last := time.Now() account := func(n int) bool { budgetMu.Lock() defer budgetMu.Unlock() spent += int64(n) if spent > maxBytes { return false } now := time.Now() tokens += now.Sub(last).Seconds() * bytesPerSecond if tokens > bytesPerSecond { tokens = bytesPerSecond } last = now tokens -= float64(n) if tokens < 0 { timer := time.NewTimer(time.Duration(-tokens / bytesPerSecond * float64(time.Second))) defer timer.Stop() select { case <-timer.C: tokens = 0 last = time.Now() case <-ctx.Done(): return false } } return true } send := func(kind byte, id uint32, data []byte) error { sendMu.Lock() defer sendMu.Unlock() ws.SetWriteDeadline(time.Now().Add(10 * time.Second)) return websocket.Message.Send(ws, packet(kind, id, data)) } defer func() { cancel() mu.Lock() for _, s := range streams { s.close() } mu.Unlock() workers.Wait() }() go func() { <-ctx.Done(); ws.Close() }() if send(3, 0, credit()) != nil { return } connections := 0 for { ws.SetReadDeadline(time.Now().Add(90 * time.Second)) var b []byte if websocket.Message.Receive(ws, &b) != nil { return } if len(b) < 5 || !account(len(b)) { return } r.rx.Add(int64(len(b))) kind, id := b[0], binary.LittleEndian.Uint32(b[1:]) if id == 0 { return } mu.Lock() s := streams[id] mu.Unlock() switch kind { case 1: connections++ if s != nil || len(b) < 9 || len(b) > 261 || connections > 256 { return } port := binary.LittleEndian.Uint16(b[6:8]) host := string(b[8:]) if b[5] != 1 || !ValidDestination(host, port) { r.rejected.Add(1) if send(4, id, []byte{0x48}) != nil { return } continue } mu.Lock() full := len(streams) >= maxStreams mu.Unlock() if full { r.rejected.Add(1) if send(4, id, []byte{0x49}) != nil { return } continue } s = &stream{data: make(chan []byte, window), done: make(chan struct{})} mu.Lock() streams[id] = s mu.Unlock() workers.Add(1) go func(id uint32, s *stream, host string, port uint16) { defer workers.Done() defer func() { s.close(); mu.Lock(); delete(streams, id); mu.Unlock() }() dialCtx, stop := context.WithCancel(ctx) defer stop() go func() { select { case <-s.done: stop() case <-dialCtx.Done(): } }() conn, e := r.dial(dialCtx, host, port) if e != nil { r.rejected.Add(1) send(4, id, []byte{0x48}) return } s.mu.Lock() s.conn = conn s.mu.Unlock() select { case <-s.done: conn.Close() return default: } readerDone := make(chan struct{}) defer func() { conn.Close(); <-readerDone }() go func() { defer close(readerDone) defer s.close() buffer := make([]byte, 64<<10) for { conn.SetReadDeadline(time.Now().Add(60 * time.Second)) n, e := conn.Read(buffer) if n > 0 { if !account(n) { cancel() return } r.tx.Add(int64(n)) if send(2, id, buffer[:n]) != nil { cancel() return } } if e != nil { send(4, id, []byte{2}) return } } }() count := 0 for { select { case <-ctx.Done(): return case <-s.done: return case data := <-s.data: conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) if _, e = io.Copy(conn, bytes.NewReader(data)); e != nil { send(4, id, []byte{3}) return } count++ if count == window { count = 0 if send(3, id, credit()) != nil { cancel() return } } } } }(id, s, host, port) case 2: if s == nil { continue } select { case <-s.done: case s.data <- b[5:]: default: r.rejected.Add(1) s.close() if send(4, id, []byte{0x49}) != nil { return } } case 4: if len(b) != 6 { return } if s != nil { s.close() } default: return } } }