All checks were successful
release / build-and-upload (push) Successful in 7m2s
Dashboard Live uptimes + Recent runs from stream_sessions; overview.recent_sessions. WireGuard netns resolv.conf + missing-deps WARN. Support donations card. Agent start/stop/update, job_backoff default off, wvkey ensure/venv, phonecap retries, modhost YAML enrich, DRM SetCredentials requires keys.
418 lines
10 KiB
Go
418 lines
10 KiB
Go
package egress
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"streamd/apps/streamd/internal/db"
|
|
)
|
|
|
|
const (
|
|
baseListenPort = 18080
|
|
socksPortInNS = 1080
|
|
)
|
|
|
|
// Manager brings named egress profiles up and resolves a stream's origin proxy.
|
|
type Manager struct {
|
|
DataDir string
|
|
Store *db.Store
|
|
Log *slog.Logger
|
|
SocksBin string // microsocks or gost; looked up if empty
|
|
|
|
mu sync.Mutex
|
|
running map[string]*runState // by profile name
|
|
}
|
|
|
|
type runState struct {
|
|
name string
|
|
listenPort int
|
|
nsIP string // veth IP inside netns, e.g. 10.255.N.2
|
|
socksCmd *exec.Cmd
|
|
forwardLn net.Listener
|
|
stopFwd chan struct{}
|
|
}
|
|
|
|
// New builds a Manager. SocksBin may be empty (auto LookPath).
|
|
func New(dataDir string, store *db.Store, log *slog.Logger, socksBin string) *Manager {
|
|
if log == nil {
|
|
log = slog.Default()
|
|
}
|
|
return &Manager{
|
|
DataDir: dataDir,
|
|
Store: store,
|
|
Log: log,
|
|
SocksBin: socksBin,
|
|
running: map[string]*runState{},
|
|
}
|
|
}
|
|
|
|
// WarnMissingDeps logs once when WireGuard host tools are absent. Safe to call
|
|
// on every platform; non-Linux hosts skip the check.
|
|
func (m *Manager) WarnMissingDeps() {
|
|
if runtime.GOOS != "linux" {
|
|
return
|
|
}
|
|
for _, bin := range []string{"ip", "wg"} {
|
|
if _, err := exec.LookPath(bin); err != nil {
|
|
m.logger().Warn("egress: tool missing from PATH (WireGuard profiles need it)",
|
|
"bin", bin)
|
|
}
|
|
}
|
|
if _, err := m.findSocksBin(); err != nil {
|
|
m.logger().Warn("egress: microsocks or gost missing from PATH (WireGuard profiles need a SOCKS forwarder in the netns)")
|
|
}
|
|
}
|
|
|
|
func (m *Manager) logger() *slog.Logger {
|
|
if m.Log != nil {
|
|
return m.Log
|
|
}
|
|
return slog.Default()
|
|
}
|
|
|
|
func (m *Manager) profileDir(name string) string {
|
|
return filepath.Join(m.DataDir, "egress", db.Slug(name))
|
|
}
|
|
|
|
func (m *Manager) confPath(name string) string {
|
|
return filepath.Join(m.profileDir(name), "wg.conf")
|
|
}
|
|
|
|
// HasConf reports whether a WireGuard conf file exists for name.
|
|
func (m *Manager) HasConf(name string) bool {
|
|
st, err := os.Stat(m.confPath(name))
|
|
return err == nil && st.Size() > 0
|
|
}
|
|
|
|
// WriteConf stores a WireGuard conf on disk (0600). Does not log contents.
|
|
func (m *Manager) WriteConf(name, contents string) error {
|
|
name = db.Slug(name)
|
|
if name == "" {
|
|
return fmt.Errorf("name required")
|
|
}
|
|
dir := m.profileDir(name)
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return err
|
|
}
|
|
path := m.confPath(name)
|
|
tmp := path + ".tmp"
|
|
if err := os.WriteFile(tmp, []byte(contents), 0o600); err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(tmp, path)
|
|
}
|
|
|
|
// ReadConf returns the raw conf for admin use. Callers must not log it.
|
|
func (m *Manager) ReadConf(name string) (string, error) {
|
|
b, err := os.ReadFile(m.confPath(name))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(b), nil
|
|
}
|
|
|
|
// RemoveFiles deletes on-disk conf for a profile (after DB delete).
|
|
func (m *Manager) RemoveFiles(name string) error {
|
|
name = db.Slug(name)
|
|
if name == "" {
|
|
return nil
|
|
}
|
|
return os.RemoveAll(m.profileDir(name))
|
|
}
|
|
|
|
// Enrich fills HasConf on profiles (conf is never stored in the DB).
|
|
func (m *Manager) Enrich(p *db.EgressProfile) {
|
|
if p == nil {
|
|
return
|
|
}
|
|
if p.Kind == db.EgressKindWireGuard {
|
|
p.HasConf = m.HasConf(p.Name)
|
|
}
|
|
}
|
|
|
|
// ResolveProxy returns the SOCKS/HTTP proxy URL a stream should use for origin
|
|
// fetch. Order: explicit stream.Proxy, then named egress profile, else empty.
|
|
func (m *Manager) ResolveProxy(st db.Stream) (string, error) {
|
|
if p := strings.TrimSpace(st.Proxy); p != "" {
|
|
return p, nil
|
|
}
|
|
name := strings.TrimSpace(st.Egress)
|
|
if name == "" {
|
|
return "", nil
|
|
}
|
|
if err := m.EnsureUp(name); err != nil {
|
|
return "", err
|
|
}
|
|
p, err := m.Store.GetEgressProfileByName(name)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
switch p.Kind {
|
|
case db.EgressKindSocks:
|
|
u := strings.TrimSpace(p.SocksURL)
|
|
if u == "" {
|
|
return "", fmt.Errorf("egress %q has no socks_url", p.Name)
|
|
}
|
|
return u, nil
|
|
default:
|
|
if p.ListenPort <= 0 {
|
|
return "", fmt.Errorf("egress %q is up but has no listen port", p.Name)
|
|
}
|
|
return fmt.Sprintf("socks5://127.0.0.1:%d", p.ListenPort), nil
|
|
}
|
|
}
|
|
|
|
// StartEnabled brings up every profile marked enabled.
|
|
func (m *Manager) StartEnabled() {
|
|
list, err := m.Store.ListEgressProfiles()
|
|
if err != nil {
|
|
m.logger().Error("list egress profiles", "err", err)
|
|
return
|
|
}
|
|
for _, p := range list {
|
|
if !p.Enabled {
|
|
continue
|
|
}
|
|
if err := m.EnsureUp(p.Name); err != nil {
|
|
m.logger().Warn("egress start", "name", p.Name, "err", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// StopAll tears down every running profile.
|
|
func (m *Manager) StopAll() {
|
|
m.mu.Lock()
|
|
names := make([]string, 0, len(m.running))
|
|
for n := range m.running {
|
|
names = append(names, n)
|
|
}
|
|
m.mu.Unlock()
|
|
for _, n := range names {
|
|
_ = m.Down(n)
|
|
}
|
|
}
|
|
|
|
// Status returns the DB row for a profile (with HasConf filled).
|
|
func (m *Manager) Status(name string) (db.EgressProfile, error) {
|
|
p, err := m.Store.GetEgressProfileByName(name)
|
|
if err != nil {
|
|
return p, err
|
|
}
|
|
m.Enrich(&p)
|
|
return p, nil
|
|
}
|
|
|
|
// EnsureUp brings a profile to a usable SOCKS endpoint.
|
|
func (m *Manager) EnsureUp(name string) error {
|
|
name = db.Slug(name)
|
|
if name == "" {
|
|
return fmt.Errorf("egress name required")
|
|
}
|
|
p, err := m.Store.GetEgressProfileByName(name)
|
|
if err != nil {
|
|
return fmt.Errorf("egress profile %q: %w", name, err)
|
|
}
|
|
|
|
m.mu.Lock()
|
|
if rs, ok := m.running[name]; ok && rs != nil {
|
|
m.mu.Unlock()
|
|
return nil
|
|
}
|
|
m.mu.Unlock()
|
|
|
|
_ = m.Store.SetEgressRuntime(p.ID, db.EgressStarting, "", p.EgressIP, p.ListenPort)
|
|
|
|
switch p.Kind {
|
|
case db.EgressKindSocks:
|
|
u := strings.TrimSpace(p.SocksURL)
|
|
if u == "" {
|
|
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, "socks_url required", "", 0)
|
|
return fmt.Errorf("egress %q: socks_url required", name)
|
|
}
|
|
m.mu.Lock()
|
|
m.running[name] = &runState{name: name}
|
|
m.mu.Unlock()
|
|
_ = m.Store.SetEgressRuntime(p.ID, db.EgressUp, "", "", 0)
|
|
return nil
|
|
case db.EgressKindWireGuard:
|
|
if runtime.GOOS != "linux" {
|
|
msg := "wireguard egress requires Linux"
|
|
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
|
|
return fmt.Errorf("%s", msg)
|
|
}
|
|
return m.ensureWireGuardUp(p)
|
|
default:
|
|
msg := fmt.Sprintf("unknown egress kind %q", p.Kind)
|
|
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
|
|
return fmt.Errorf("%s", msg)
|
|
}
|
|
}
|
|
|
|
// Down stops a profile's local SOCKS / netns.
|
|
func (m *Manager) Down(name string) error {
|
|
name = db.Slug(name)
|
|
p, err := m.Store.GetEgressProfileByName(name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
m.mu.Lock()
|
|
rs := m.running[name]
|
|
delete(m.running, name)
|
|
m.mu.Unlock()
|
|
|
|
if rs != nil {
|
|
m.stopRun(rs)
|
|
}
|
|
if p.Kind == db.EgressKindWireGuard && runtime.GOOS == "linux" {
|
|
if err := m.teardownWireGuard(name, p.ID); err != nil {
|
|
m.logger().Warn("egress teardown", "name", name, "err", err)
|
|
}
|
|
}
|
|
_ = m.Store.SetEgressRuntime(p.ID, db.EgressStopped, "", "", 0)
|
|
return nil
|
|
}
|
|
|
|
func (m *Manager) stopRun(rs *runState) {
|
|
if rs.stopFwd != nil {
|
|
close(rs.stopFwd)
|
|
rs.stopFwd = nil
|
|
}
|
|
if rs.forwardLn != nil {
|
|
_ = rs.forwardLn.Close()
|
|
rs.forwardLn = nil
|
|
}
|
|
if rs.socksCmd != nil && rs.socksCmd.Process != nil {
|
|
_ = rs.socksCmd.Process.Kill()
|
|
_, _ = rs.socksCmd.Process.Wait()
|
|
rs.socksCmd = nil
|
|
}
|
|
}
|
|
|
|
func (m *Manager) findSocksBin() (string, error) {
|
|
if m.SocksBin != "" {
|
|
return m.SocksBin, nil
|
|
}
|
|
for _, n := range []string{"microsocks", "gost"} {
|
|
if p, err := exec.LookPath(n); err == nil {
|
|
m.SocksBin = p
|
|
return p, nil
|
|
}
|
|
}
|
|
return "", fmt.Errorf("microsocks (or gost) not found on PATH")
|
|
}
|
|
|
|
func (m *Manager) allocListenPort(id int64) int {
|
|
return baseListenPort + int(id%1000)
|
|
}
|
|
|
|
func (m *Manager) vethAddrs(id int64) (hostIP, nsIP, subnet string) {
|
|
// Unique /30-ish /24 host pair per profile id (1..254).
|
|
n := int(id % 200)
|
|
if n <= 0 {
|
|
n = 1
|
|
}
|
|
hostIP = fmt.Sprintf("10.255.%d.1", n)
|
|
nsIP = fmt.Sprintf("10.255.%d.2", n)
|
|
subnet = fmt.Sprintf("10.255.%d.0/24", n)
|
|
return hostIP, nsIP, subnet
|
|
}
|
|
|
|
func (m *Manager) startLocalForward(listenPort int, destHost string, destPort int) (net.Listener, chan struct{}, error) {
|
|
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", listenPort))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
stop := make(chan struct{})
|
|
go func() {
|
|
for {
|
|
c, err := ln.Accept()
|
|
if err != nil {
|
|
select {
|
|
case <-stop:
|
|
return
|
|
default:
|
|
return
|
|
}
|
|
}
|
|
go proxyTCP(c, fmt.Sprintf("%s:%d", destHost, destPort))
|
|
}
|
|
}()
|
|
return ln, stop, nil
|
|
}
|
|
|
|
func proxyTCP(client net.Conn, addr string) {
|
|
defer client.Close()
|
|
_ = client.SetDeadline(time.Now().Add(60 * time.Second))
|
|
upstream, err := net.DialTimeout("tcp", addr, 15*time.Second)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer upstream.Close()
|
|
_ = client.SetDeadline(time.Time{})
|
|
_ = upstream.SetDeadline(time.Time{})
|
|
done := make(chan struct{}, 2)
|
|
go func() { _, _ = io.Copy(upstream, client); done <- struct{}{} }()
|
|
go func() { _, _ = io.Copy(client, upstream); done <- struct{}{} }()
|
|
<-done
|
|
}
|
|
|
|
// TestDial tries a short TCP connect through the resolved SOCKS endpoint of a
|
|
// profile (after EnsureUp). Used by POST /api/egress/:name/test.
|
|
func (m *Manager) TestDial(name string) (map[string]any, error) {
|
|
if err := m.EnsureUp(name); err != nil {
|
|
return nil, err
|
|
}
|
|
p, err := m.Store.GetEgressProfileByName(name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var proxyURL string
|
|
switch p.Kind {
|
|
case db.EgressKindSocks:
|
|
proxyURL = strings.TrimSpace(p.SocksURL)
|
|
default:
|
|
if p.ListenPort <= 0 {
|
|
return nil, fmt.Errorf("no listen port")
|
|
}
|
|
proxyURL = fmt.Sprintf("socks5://127.0.0.1:%d", p.ListenPort)
|
|
}
|
|
out := map[string]any{
|
|
"ok": true,
|
|
"name": p.Name,
|
|
"kind": p.Kind,
|
|
"proxy_url": proxyURL,
|
|
"status": p.Status,
|
|
"egress_ip": p.EgressIP,
|
|
}
|
|
// Dial the local SOCKS port to confirm it accepts TCP.
|
|
hostPort := ""
|
|
if p.Kind == db.EgressKindWireGuard && p.ListenPort > 0 {
|
|
hostPort = fmt.Sprintf("127.0.0.1:%d", p.ListenPort)
|
|
} else if u := strings.TrimPrefix(strings.TrimPrefix(proxyURL, "socks5://"), "socks5h://"); u != proxyURL {
|
|
if i := strings.LastIndex(u, "@"); i >= 0 {
|
|
u = u[i+1:]
|
|
}
|
|
hostPort = u
|
|
}
|
|
if hostPort != "" {
|
|
c, err := net.DialTimeout("tcp", hostPort, 5*time.Second)
|
|
if err != nil {
|
|
out["ok"] = false
|
|
out["error"] = err.Error()
|
|
return out, fmt.Errorf("socks dial: %w", err)
|
|
}
|
|
_ = c.Close()
|
|
out["socks_reachable"] = true
|
|
}
|
|
return out, nil
|
|
}
|