streamd: serve start/stop/update, streamd.yaml, egress, module panel fixes
- Add streamd serve start|stop|restart|status|update with auto-written streamd.yaml - Panel modules: STREAMD_MODULES_DIR for describe, YAML channel fallback, textarea value fix - Per-stream WireGuard/SOCKS egress profiles + Settings UI - Drop drm-* from release builds; track streamd-bg.sh / streamd-update.sh wrappers - Docs: streamd-server-setup lifecycle and update flow
This commit is contained in:
parent
da8e1123ec
commit
8fc7e4c0b8
57 changed files with 4031 additions and 257 deletions
|
|
@ -13,6 +13,7 @@ import (
|
|||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/deps"
|
||||
"streamd/apps/streamd/internal/egress"
|
||||
"streamd/apps/streamd/internal/httpx"
|
||||
"streamd/apps/streamd/internal/modstore"
|
||||
)
|
||||
|
|
@ -61,6 +62,7 @@ type Handler struct {
|
|||
Modules *modstore.Store
|
||||
// ModulesNotify is set when the hub supports module change pushes.
|
||||
ModulesNotify ModulesNotifier
|
||||
Egress *egress.Manager
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
|
|
@ -70,6 +72,7 @@ func (h *Handler) Mount(mux *http.ServeMux) {
|
|||
mux.HandleFunc("/api/streams/", h.streamAction)
|
||||
mux.HandleFunc("/api/overview", h.overview)
|
||||
h.MountControl(mux)
|
||||
h.MountEgress(mux)
|
||||
mux.HandleFunc("/api/apps", h.apps)
|
||||
mux.HandleFunc("/api/modules", h.modules)
|
||||
mux.HandleFunc("/api/modules/", h.modules)
|
||||
|
|
@ -539,6 +542,7 @@ func changeNote(before, after db.Stream, in db.PatchStream) string {
|
|||
add("key", in.Key != nil && before.Key != after.Key)
|
||||
add("headers", in.HeadersJSON != nil && before.HeadersJSON != after.HeadersJSON)
|
||||
add("proxy", in.Proxy != nil && before.Proxy != after.Proxy)
|
||||
add("egress", in.Egress != nil && before.Egress != after.Egress)
|
||||
add("variants", before.VariantsJSON != after.VariantsJSON)
|
||||
add("outputs", before.OutputsJSON != after.OutputsJSON)
|
||||
add("settings", before.SettingsJSON != after.SettingsJSON)
|
||||
|
|
@ -570,6 +574,9 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
|
|||
if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) {
|
||||
return true
|
||||
}
|
||||
if in.Egress != nil && strings.TrimSpace(before.Egress) != strings.TrimSpace(after.Egress) {
|
||||
return true
|
||||
}
|
||||
if in.VariantsJSON != nil || len(in.Variants) > 0 {
|
||||
if strings.TrimSpace(before.VariantsJSON) != strings.TrimSpace(after.VariantsJSON) {
|
||||
return true
|
||||
|
|
|
|||
|
|
@ -2,8 +2,12 @@ package api
|
|||
|
||||
import (
|
||||
"net/http"
|
||||
"sort"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/modstore"
|
||||
"streamd/modhost"
|
||||
"streamd/mpd"
|
||||
"streamd/repo"
|
||||
|
|
@ -44,13 +48,17 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
|
|||
for _, m := range mods {
|
||||
bin, err := modhost.EnsureBuilt(m)
|
||||
if err != nil {
|
||||
out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()})
|
||||
info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}
|
||||
h.fillChannelsFromStore(&info, m.Name)
|
||||
out = append(out, info)
|
||||
h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
|
||||
continue
|
||||
}
|
||||
d, err := modhost.RunDescribe(bin)
|
||||
if err != nil {
|
||||
out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()})
|
||||
info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}
|
||||
h.fillChannelsFromStore(&info, m.Name)
|
||||
out = append(out, info)
|
||||
h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
|
||||
continue
|
||||
}
|
||||
|
|
@ -61,10 +69,14 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
|
|||
for _, ch := range d.Channels {
|
||||
info.Channels = append(info.Channels, channelInfo{ID: ch.ID, Label: ch.Label})
|
||||
}
|
||||
info.HasConfig = len(info.Channels) > 0
|
||||
if d.Rewriter != "" {
|
||||
info.Rewriter = d.Rewriter
|
||||
}
|
||||
// Older module binaries may not see the panel store; fill from module.yaml.
|
||||
if len(info.Channels) == 0 {
|
||||
h.fillChannelsFromStore(&info, m.Name)
|
||||
}
|
||||
info.HasConfig = len(info.Channels) > 0
|
||||
out = append(out, info)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
|
|
@ -72,3 +84,53 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
|
|||
"rewriters": mpd.Names(),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) fillChannelsFromStore(info *appInfo, name string) {
|
||||
if h == nil || h.Modules == nil || info == nil {
|
||||
return
|
||||
}
|
||||
chans := channelsFromStoreYAML(h.Modules, name)
|
||||
if len(chans) == 0 {
|
||||
return
|
||||
}
|
||||
info.Channels = chans
|
||||
info.HasConfig = true
|
||||
if info.Error != "" {
|
||||
// Soft: yaml channels recovered even though describe failed.
|
||||
info.Error = ""
|
||||
}
|
||||
}
|
||||
|
||||
// channelsFromStoreYAML reads channels from the panel module.yaml when describe
|
||||
// returns none (common with uploaded binaries that resolve values via cwd).
|
||||
func channelsFromStoreYAML(store *modstore.Store, name string) []channelInfo {
|
||||
if store == nil {
|
||||
return nil
|
||||
}
|
||||
raw, err := store.ReadYAML(name)
|
||||
if err != nil || len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
var doc struct {
|
||||
Channels map[string]struct {
|
||||
Label string `yaml:"label"`
|
||||
} `yaml:"channels"`
|
||||
}
|
||||
if err := yaml.Unmarshal(raw, &doc); err != nil || len(doc.Channels) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]string, 0, len(doc.Channels))
|
||||
for id := range doc.Channels {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
out := make([]channelInfo, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
label := doc.Channels[id].Label
|
||||
if label == "" {
|
||||
label = id
|
||||
}
|
||||
out = append(out, channelInfo{ID: id, Label: label})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
|
|||
45
apps/streamd/internal/api/apps_test.go
Normal file
45
apps/streamd/internal/api/apps_test.go
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"streamd/apps/streamd/internal/modstore"
|
||||
)
|
||||
|
||||
func TestChannelsFromStoreYAML(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
store := modstore.New(root)
|
||||
modDir := filepath.Join(root, "rte")
|
||||
if err := os.MkdirAll(modDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
yaml := []byte(`package: air.RTE
|
||||
channels:
|
||||
rteone:
|
||||
label: RTE One
|
||||
rtetwo:
|
||||
label: RTE 2
|
||||
`)
|
||||
if err := os.WriteFile(filepath.Join(modDir, "module.yaml"), yaml, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chans := channelsFromStoreYAML(store, "rte")
|
||||
if len(chans) != 2 {
|
||||
t.Fatalf("got %d channels: %+v", len(chans), chans)
|
||||
}
|
||||
if chans[0].ID != "rteone" || chans[0].Label != "RTE One" {
|
||||
t.Fatalf("first channel: %+v", chans[0])
|
||||
}
|
||||
if chans[1].ID != "rtetwo" {
|
||||
t.Fatalf("second channel: %+v", chans[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelsFromStoreYAMLMissing(t *testing.T) {
|
||||
store := modstore.New(t.TempDir())
|
||||
if chans := channelsFromStoreYAML(store, "nope"); chans != nil {
|
||||
t.Fatalf("expected nil, got %+v", chans)
|
||||
}
|
||||
}
|
||||
|
|
@ -162,6 +162,7 @@ func (h *Handler) duplicate(w http.ResponseWriter, r *http.Request, id int64) {
|
|||
Key: src.Key,
|
||||
HeadersJSON: src.HeadersJSON,
|
||||
Proxy: src.Proxy,
|
||||
Egress: src.Egress,
|
||||
VideoSelect: src.VideoSelect,
|
||||
AudioSelect: src.AudioSelect,
|
||||
Rewriter: src.Rewriter,
|
||||
|
|
@ -271,9 +272,19 @@ func (h *Handler) doProbe(ctx context.Context, st db.Stream, target string) prob
|
|||
start := time.Now()
|
||||
|
||||
client := &http.Client{Timeout: 20 * time.Second}
|
||||
// Fetch through the stream's own proxy, so a geo-restricted origin is
|
||||
// probed the same way the downloader would reach it.
|
||||
if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
|
||||
// Fetch through the stream's effective proxy (explicit or named egress),
|
||||
// so a geo-restricted origin is probed the same way the downloader would.
|
||||
proxy := strings.TrimSpace(st.Proxy)
|
||||
if h.Egress != nil {
|
||||
if p, err := h.Egress.ResolveProxy(st); err == nil {
|
||||
proxy = p
|
||||
} else if strings.TrimSpace(st.Egress) != "" && proxy == "" {
|
||||
res.Error = "egress: " + err.Error()
|
||||
res.Summary = "egress profile could not be brought up"
|
||||
return res
|
||||
}
|
||||
}
|
||||
if proxy != "" {
|
||||
if c, err := httpClientWithProxy(proxy); err == nil {
|
||||
client = c
|
||||
} else {
|
||||
|
|
|
|||
254
apps/streamd/internal/api/egress.go
Normal file
254
apps/streamd/internal/api/egress.go
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// MountEgress registers /api/egress routes.
|
||||
func (h *Handler) MountEgress(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/egress", h.egressRoot)
|
||||
mux.HandleFunc("/api/egress/", h.egressAction)
|
||||
}
|
||||
|
||||
func (h *Handler) egressRoot(w http.ResponseWriter, r *http.Request) {
|
||||
if h.Egress == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "egress manager not configured")
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
list, err := h.Store.ListEgressProfiles()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
for i := range list {
|
||||
h.Egress.Enrich(&list[i])
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"profiles": list})
|
||||
case http.MethodPost:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in db.CreateEgressProfile
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
prof, err := h.Store.CreateEgressProfile(in)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.Egress.Enrich(&prof)
|
||||
h.audit(r, p, http.StatusOK, "create egress "+prof.Name)
|
||||
writeJSON(w, http.StatusOK, prof)
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) egressAction(w http.ResponseWriter, r *http.Request) {
|
||||
if h.Egress == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "egress manager not configured")
|
||||
return
|
||||
}
|
||||
path := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/egress/"), "/")
|
||||
if path == "" {
|
||||
h.egressRoot(w, r)
|
||||
return
|
||||
}
|
||||
parts := strings.Split(path, "/")
|
||||
name := db.Slug(parts[0])
|
||||
if name == "" {
|
||||
writeErr(w, http.StatusBadRequest, "invalid name")
|
||||
return
|
||||
}
|
||||
action := ""
|
||||
if len(parts) > 1 {
|
||||
action = strings.ToLower(parts[1])
|
||||
}
|
||||
|
||||
switch {
|
||||
case action == "" && r.Method == http.MethodGet:
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
prof, err := h.Egress.Status(name)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, prof)
|
||||
|
||||
case action == "" && r.Method == http.MethodPut:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.putEgress(w, r, p, name)
|
||||
|
||||
case action == "" && r.Method == http.MethodDelete:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
prof, err := h.Store.GetEgressProfileByName(name)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
_ = h.Egress.Down(name)
|
||||
if err := h.Store.DeleteEgressProfile(prof.ID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
_ = h.Egress.RemoveFiles(name)
|
||||
h.audit(r, p, http.StatusOK, "delete egress "+name)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
|
||||
case action == "up" && r.Method == http.MethodPost:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.Egress.EnsureUp(name); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
prof, _ := h.Egress.Status(name)
|
||||
h.audit(r, p, http.StatusOK, "egress up "+name)
|
||||
writeJSON(w, http.StatusOK, prof)
|
||||
|
||||
case action == "down" && r.Method == http.MethodPost:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.Egress.Down(name); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
prof, _ := h.Egress.Status(name)
|
||||
h.audit(r, p, http.StatusOK, "egress down "+name)
|
||||
writeJSON(w, http.StatusOK, prof)
|
||||
|
||||
case action == "test" && r.Method == http.MethodPost:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out, err := h.Egress.TestDial(name)
|
||||
if err != nil {
|
||||
if out == nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "egress test "+name+" fail")
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "egress test "+name)
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
|
||||
case action == "conf" && r.Method == http.MethodPut:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
_ = r.Body.Close()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
contents := string(body)
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if strings.Contains(ct, "json") || strings.HasPrefix(strings.TrimSpace(contents), "{") {
|
||||
var in struct {
|
||||
Conf string `json:"conf"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &in); err != nil || strings.TrimSpace(in.Conf) == "" {
|
||||
writeErr(w, http.StatusBadRequest, "conf required")
|
||||
return
|
||||
}
|
||||
contents = in.Conf
|
||||
}
|
||||
if strings.TrimSpace(contents) == "" {
|
||||
writeErr(w, http.StatusBadRequest, "empty conf")
|
||||
return
|
||||
}
|
||||
if _, err := h.Store.GetEgressProfileByName(name); err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
if err := h.Egress.WriteConf(name, contents); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
prof, _ := h.Egress.Status(name)
|
||||
h.audit(r, p, http.StatusOK, "egress conf "+name)
|
||||
writeJSON(w, http.StatusOK, prof)
|
||||
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) putEgress(w http.ResponseWriter, r *http.Request, p *auth.Principal, name string) {
|
||||
prof, err := h.Store.GetEgressProfileByName(name)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
SocksURL *string `json:"socks_url"`
|
||||
Kind *string `json:"kind"`
|
||||
Conf *string `json:"conf"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
upd, err := h.Store.UpdateEgressProfile(prof.ID, db.UpdateEgressProfile{
|
||||
Enabled: in.Enabled, SocksURL: in.SocksURL, Kind: in.Kind,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if in.Conf != nil && strings.TrimSpace(*in.Conf) != "" {
|
||||
if err := h.Egress.WriteConf(name, *in.Conf); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
h.Egress.Enrich(&upd)
|
||||
if in.Enabled != nil && *in.Enabled {
|
||||
_ = h.Egress.EnsureUp(name)
|
||||
upd, _ = h.Egress.Status(name)
|
||||
}
|
||||
if in.Enabled != nil && !*in.Enabled {
|
||||
_ = h.Egress.Down(name)
|
||||
upd, _ = h.Egress.Status(name)
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "update egress "+name)
|
||||
writeJSON(w, http.StatusOK, upd)
|
||||
}
|
||||
|
|
@ -222,6 +222,14 @@ func (h *Handler) uploadModule(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
defer file.Close()
|
||||
if name == "" && hdr != nil {
|
||||
// rte.zip → rte (helps flat release zips before binary inference).
|
||||
base := strings.TrimSuffix(filepath.Base(hdr.Filename), filepath.Ext(hdr.Filename))
|
||||
base = strings.ToLower(strings.TrimSpace(base))
|
||||
if modstore.NameRe.MatchString(base) {
|
||||
name = base
|
||||
}
|
||||
}
|
||||
if hdr.Size > modstore.MaxPackageBytes {
|
||||
writeErr(w, http.StatusBadRequest, "zip too large")
|
||||
return
|
||||
|
|
|
|||
|
|
@ -41,7 +41,8 @@ type Stream struct {
|
|||
MPD string `json:"mpd"`
|
||||
Key string `json:"key"`
|
||||
HeadersJSON string `json:"headers_json"`
|
||||
Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE)
|
||||
Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE)
|
||||
Egress string `json:"egress"` // named egress profile (wireguard/socks); used when Proxy empty
|
||||
VideoSelect string `json:"video_select"`
|
||||
AudioSelect string `json:"audio_select"`
|
||||
Enabled bool `json:"enabled"`
|
||||
|
|
@ -81,6 +82,7 @@ type Stream struct {
|
|||
HasKey bool `json:"has_key"`
|
||||
HasHeaders bool `json:"has_headers"`
|
||||
HasProxy bool `json:"has_proxy"`
|
||||
HasEgress bool `json:"has_egress"`
|
||||
KeyValid bool `json:"key_valid"`
|
||||
// DRMRequired is DRMMode resolved: whether this stream needs keys at all.
|
||||
DRMRequired bool `json:"drm_required"`
|
||||
|
|
@ -103,6 +105,7 @@ type CreateStream struct {
|
|||
Key string `json:"key"`
|
||||
HeadersJSON string `json:"headers_json"`
|
||||
Proxy string `json:"proxy"`
|
||||
Egress string `json:"egress"`
|
||||
VideoSelect string `json:"video_select"`
|
||||
AudioSelect string `json:"audio_select"`
|
||||
Rewriter string `json:"rewriter"`
|
||||
|
|
@ -128,6 +131,7 @@ type PatchStream struct {
|
|||
Key *string `json:"key"`
|
||||
HeadersJSON *string `json:"headers_json"`
|
||||
Proxy *string `json:"proxy"`
|
||||
Egress *string `json:"egress"`
|
||||
VideoSelect *string `json:"video_select"`
|
||||
AudioSelect *string `json:"audio_select"`
|
||||
Rewriter *string `json:"rewriter"`
|
||||
|
|
@ -230,6 +234,7 @@ CREATE TABLE IF NOT EXISTS agent_claims (
|
|||
`ALTER TABLE streams ADD COLUMN on_demand INTEGER NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE streams ADD COLUMN idle_timeout_s INTEGER NOT NULL DEFAULT 300`,
|
||||
`ALTER TABLE streams ADD COLUMN public INTEGER NOT NULL DEFAULT 1`,
|
||||
`ALTER TABLE streams ADD COLUMN egress TEXT NOT NULL DEFAULT ''`,
|
||||
} {
|
||||
_, _ = s.DB.Exec(stmt)
|
||||
}
|
||||
|
|
@ -239,7 +244,10 @@ CREATE TABLE IF NOT EXISTS agent_claims (
|
|||
if err := s.migrateSettings(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateSchedules()
|
||||
if err := s.migrateSchedules(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateEgress()
|
||||
}
|
||||
|
||||
func now() string {
|
||||
|
|
@ -264,10 +272,13 @@ func slug(name string) string {
|
|||
return out
|
||||
}
|
||||
|
||||
// Slug normalises a name the same way stream and egress profile names are stored.
|
||||
func Slug(name string) string { return slug(name) }
|
||||
|
||||
const streamSelect = `
|
||||
SELECT s.id, s.name, s.title, COALESCE(s.description,''), COALESCE(s.tags,''),
|
||||
s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
|
||||
COALESCE(s.proxy,''), s.video_select, s.audio_select, s.enabled, s.rewriter,
|
||||
COALESCE(s.proxy,''), COALESCE(s.egress,''), s.video_select, s.audio_select, s.enabled, s.rewriter,
|
||||
COALESCE(s.variants_json,''), COALESCE(s.outputs_json,''), COALESCE(s.settings_json,''),
|
||||
COALESCE(s.drm_mode,'auto'), COALESCE(s.on_demand,0),
|
||||
COALESCE(s.idle_timeout_s,300), COALESCE(s.public,1),
|
||||
|
|
@ -318,7 +329,7 @@ func scanStream(row rowScanner) (Stream, error) {
|
|||
err := row.Scan(
|
||||
&st.ID, &st.Name, &st.Title, &st.Description, &st.Tags,
|
||||
&st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
|
||||
&st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter,
|
||||
&st.Proxy, &st.Egress, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter,
|
||||
&st.VariantsJSON, &st.OutputsJSON, &st.SettingsJSON,
|
||||
&st.DRMMode, &onDemand, &st.IdleTimeoutS, &public,
|
||||
&st.CreatedAt, &st.UpdatedAt,
|
||||
|
|
@ -361,6 +372,7 @@ func (st *Stream) fillDerived() {
|
|||
hdr := strings.TrimSpace(st.HeadersJSON)
|
||||
st.HasHeaders = hdr != "" && hdr != "{}" && hdr != "null"
|
||||
st.HasProxy = strings.TrimSpace(st.Proxy) != ""
|
||||
st.HasEgress = strings.TrimSpace(st.Egress) != ""
|
||||
switch strings.ToLower(strings.TrimSpace(st.DRMMode)) {
|
||||
case DRMYes:
|
||||
st.DRMRequired = true
|
||||
|
|
@ -557,12 +569,13 @@ func (s *Store) CreateStream(in CreateStream) (Stream, error) {
|
|||
}
|
||||
ts := now()
|
||||
res, err := s.DB.Exec(`
|
||||
INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,
|
||||
INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,egress,
|
||||
video_select,audio_select,enabled,rewriter,variants_json,outputs_json,
|
||||
settings_json,drm_mode,on_demand,idle_timeout_s,public,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
name, in.Title, strings.TrimSpace(in.Description), normalizeTags(in.Tags),
|
||||
in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy),
|
||||
slug(strings.TrimSpace(in.Egress)),
|
||||
in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, outputsJSON,
|
||||
settingsJSON, normalizeDRMMode(in.DRMMode), onDemand, idle, public, ts, ts)
|
||||
if err != nil {
|
||||
|
|
@ -654,6 +667,9 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
|
|||
if in.Proxy != nil {
|
||||
cur.Proxy = strings.TrimSpace(*in.Proxy)
|
||||
}
|
||||
if in.Egress != nil {
|
||||
cur.Egress = slug(strings.TrimSpace(*in.Egress))
|
||||
}
|
||||
if in.VideoSelect != nil {
|
||||
cur.VideoSelect = *in.VideoSelect
|
||||
}
|
||||
|
|
@ -730,11 +746,11 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
|
|||
ts := now()
|
||||
_, err = s.DB.Exec(`
|
||||
UPDATE streams SET title=?, description=?, tags=?, app=?, channel=?, mpd=?, key_kid_key=?,
|
||||
headers_json=?, proxy=?, video_select=?, audio_select=?, enabled=?, rewriter=?,
|
||||
headers_json=?, proxy=?, egress=?, video_select=?, audio_select=?, enabled=?, rewriter=?,
|
||||
variants_json=?, outputs_json=?, settings_json=?, drm_mode=?, on_demand=?,
|
||||
idle_timeout_s=?, public=?, updated_at=? WHERE id=?`,
|
||||
cur.Title, cur.Description, cur.Tags, cur.App, cur.Channel, cur.MPD, cur.Key,
|
||||
cur.HeadersJSON, cur.Proxy, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter,
|
||||
cur.HeadersJSON, cur.Proxy, cur.Egress, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter,
|
||||
cur.VariantsJSON, cur.OutputsJSON, cur.SettingsJSON, cur.DRMMode, onDemand,
|
||||
cur.IdleTimeoutS, public, ts, id)
|
||||
if err != nil {
|
||||
|
|
|
|||
226
apps/streamd/internal/db/egress.go
Normal file
226
apps/streamd/internal/db/egress.go
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
EgressKindWireGuard = "wireguard"
|
||||
EgressKindSocks = "socks"
|
||||
|
||||
EgressStopped = "stopped"
|
||||
EgressStarting = "starting"
|
||||
EgressUp = "up"
|
||||
EgressDown = "down"
|
||||
EgressError = "error"
|
||||
)
|
||||
|
||||
// EgressProfile is a named origin-egress path (WireGuard netns or plain SOCKS).
|
||||
// Conf blobs live on disk under data/egress/<name>/; never in this table.
|
||||
type EgressProfile struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Enabled bool `json:"enabled"`
|
||||
ListenPort int `json:"listen_port"`
|
||||
SocksURL string `json:"socks_url,omitempty"`
|
||||
Status string `json:"status"`
|
||||
LastError string `json:"last_error,omitempty"`
|
||||
EgressIP string `json:"egress_ip,omitempty"`
|
||||
HasConf bool `json:"has_conf"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (s *Store) migrateEgress() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS egress_profiles (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
kind TEXT NOT NULL DEFAULT 'wireguard',
|
||||
enabled INTEGER NOT NULL DEFAULT 0,
|
||||
listen_port INTEGER NOT NULL DEFAULT 0,
|
||||
socks_url TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'stopped',
|
||||
last_error TEXT NOT NULL DEFAULT '',
|
||||
egress_ip TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
type CreateEgressProfile struct {
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
SocksURL string `json:"socks_url"`
|
||||
}
|
||||
|
||||
type UpdateEgressProfile struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
SocksURL *string `json:"socks_url"`
|
||||
Kind *string `json:"kind"`
|
||||
}
|
||||
|
||||
func normalizeEgressKind(k string) (string, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(k)) {
|
||||
case "", EgressKindWireGuard:
|
||||
return EgressKindWireGuard, nil
|
||||
case EgressKindSocks:
|
||||
return EgressKindSocks, nil
|
||||
default:
|
||||
return "", fmt.Errorf("kind must be %q or %q", EgressKindWireGuard, EgressKindSocks)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) ListEgressProfiles() ([]EgressProfile, error) {
|
||||
rows, err := s.DB.Query(`
|
||||
SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at
|
||||
FROM egress_profiles ORDER BY name`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []EgressProfile
|
||||
for rows.Next() {
|
||||
p, err := scanEgress(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
if out == nil {
|
||||
out = []EgressProfile{}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) GetEgressProfile(id int64) (EgressProfile, error) {
|
||||
row := s.DB.QueryRow(`
|
||||
SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at
|
||||
FROM egress_profiles WHERE id=?`, id)
|
||||
return scanEgress(row)
|
||||
}
|
||||
|
||||
func (s *Store) GetEgressProfileByName(name string) (EgressProfile, error) {
|
||||
name = slug(name)
|
||||
if name == "" {
|
||||
return EgressProfile{}, fmt.Errorf("name required")
|
||||
}
|
||||
row := s.DB.QueryRow(`
|
||||
SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at
|
||||
FROM egress_profiles WHERE name=?`, name)
|
||||
return scanEgress(row)
|
||||
}
|
||||
|
||||
func scanEgress(row rowScanner) (EgressProfile, error) {
|
||||
var p EgressProfile
|
||||
var enabled int
|
||||
err := row.Scan(
|
||||
&p.ID, &p.Name, &p.Kind, &enabled, &p.ListenPort, &p.SocksURL,
|
||||
&p.Status, &p.LastError, &p.EgressIP, &p.CreatedAt, &p.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
p.Enabled = enabled != 0
|
||||
if p.Status == "" {
|
||||
p.Status = EgressStopped
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateEgressProfile(in CreateEgressProfile) (EgressProfile, error) {
|
||||
name := slug(in.Name)
|
||||
if name == "" {
|
||||
return EgressProfile{}, fmt.Errorf("name required (slug of letters, digits, hyphens)")
|
||||
}
|
||||
kind, err := normalizeEgressKind(in.Kind)
|
||||
if err != nil {
|
||||
return EgressProfile{}, err
|
||||
}
|
||||
socks := strings.TrimSpace(in.SocksURL)
|
||||
if kind == EgressKindSocks && socks == "" {
|
||||
return EgressProfile{}, fmt.Errorf("socks_url required for kind=socks")
|
||||
}
|
||||
enabled := 0
|
||||
if in.Enabled != nil && *in.Enabled {
|
||||
enabled = 1
|
||||
}
|
||||
ts := now()
|
||||
res, err := s.DB.Exec(`
|
||||
INSERT INTO egress_profiles(name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at)
|
||||
VALUES(?,?,?,0,?,?, '','',?,?)`,
|
||||
name, kind, enabled, socks, EgressStopped, ts, ts)
|
||||
if err != nil {
|
||||
if strings.Contains(strings.ToLower(err.Error()), "unique") {
|
||||
return EgressProfile{}, fmt.Errorf("egress profile %q already exists", name)
|
||||
}
|
||||
return EgressProfile{}, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return s.GetEgressProfile(id)
|
||||
}
|
||||
|
||||
func (s *Store) UpdateEgressProfile(id int64, in UpdateEgressProfile) (EgressProfile, error) {
|
||||
cur, err := s.GetEgressProfile(id)
|
||||
if err != nil {
|
||||
return EgressProfile{}, err
|
||||
}
|
||||
if in.Enabled != nil {
|
||||
cur.Enabled = *in.Enabled
|
||||
}
|
||||
if in.SocksURL != nil {
|
||||
cur.SocksURL = strings.TrimSpace(*in.SocksURL)
|
||||
}
|
||||
if in.Kind != nil {
|
||||
kind, err := normalizeEgressKind(*in.Kind)
|
||||
if err != nil {
|
||||
return EgressProfile{}, err
|
||||
}
|
||||
cur.Kind = kind
|
||||
}
|
||||
if cur.Kind == EgressKindSocks && cur.SocksURL == "" {
|
||||
return EgressProfile{}, fmt.Errorf("socks_url required for kind=socks")
|
||||
}
|
||||
enabled := 0
|
||||
if cur.Enabled {
|
||||
enabled = 1
|
||||
}
|
||||
ts := now()
|
||||
_, err = s.DB.Exec(`
|
||||
UPDATE egress_profiles SET kind=?, enabled=?, socks_url=?, updated_at=? WHERE id=?`,
|
||||
cur.Kind, enabled, cur.SocksURL, ts, id)
|
||||
if err != nil {
|
||||
return EgressProfile{}, err
|
||||
}
|
||||
return s.GetEgressProfile(id)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteEgressProfile(id int64) error {
|
||||
res, err := s.DB.Exec(`DELETE FROM egress_profiles WHERE id=?`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
if n == 0 {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetEgressRuntime updates live status fields without touching config.
|
||||
func (s *Store) SetEgressRuntime(id int64, status, lastErr, egressIP string, listenPort int) error {
|
||||
status = strings.TrimSpace(status)
|
||||
if status == "" {
|
||||
status = EgressStopped
|
||||
}
|
||||
_, err := s.DB.Exec(`
|
||||
UPDATE egress_profiles SET status=?, last_error=?, egress_ip=?, listen_port=?, updated_at=? WHERE id=?`,
|
||||
status, strings.TrimSpace(lastErr), strings.TrimSpace(egressIP), listenPort, now(), id)
|
||||
return err
|
||||
}
|
||||
117
apps/streamd/internal/db/egress_test.go
Normal file
117
apps/streamd/internal/db/egress_test.go
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSlugValidation(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
in, want string
|
||||
}{
|
||||
{"London", "london"},
|
||||
{"dublin-1", "dublin-1"},
|
||||
{" RTE IE ", "rte-ie"},
|
||||
{"!!!", ""},
|
||||
{"Wire_Guard", "wire-guard"},
|
||||
{"a--b", "a-b"},
|
||||
} {
|
||||
if got := Slug(c.in); got != c.want {
|
||||
t.Errorf("Slug(%q) = %q want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEgressCRUD(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store, err := Open(filepath.Join(dir, "data"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
_, err = store.CreateEgressProfile(CreateEgressProfile{Name: "!!!"})
|
||||
if err == nil {
|
||||
t.Fatal("expected empty slug to fail")
|
||||
}
|
||||
|
||||
on := true
|
||||
p, err := store.CreateEgressProfile(CreateEgressProfile{
|
||||
Name: "London", Kind: "wireguard", Enabled: &on,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Name != "london" || p.Kind != EgressKindWireGuard || !p.Enabled {
|
||||
t.Fatalf("create: %+v", p)
|
||||
}
|
||||
if p.Status != EgressStopped {
|
||||
t.Fatalf("status = %q", p.Status)
|
||||
}
|
||||
|
||||
got, err := store.GetEgressProfileByName("LONDON")
|
||||
if err != nil || got.ID != p.ID {
|
||||
t.Fatalf("GetByName: %+v %v", got, err)
|
||||
}
|
||||
|
||||
off := false
|
||||
url := "socks5://127.0.0.1:1080"
|
||||
kind := EgressKindSocks
|
||||
upd, err := store.UpdateEgressProfile(p.ID, UpdateEgressProfile{
|
||||
Enabled: &off, SocksURL: &url, Kind: &kind,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if upd.Enabled || upd.SocksURL != url || upd.Kind != EgressKindSocks {
|
||||
t.Fatalf("update: %+v", upd)
|
||||
}
|
||||
|
||||
if err := store.SetEgressRuntime(p.ID, EgressUp, "", "1.2.3.4", 18080); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ = store.GetEgressProfile(p.ID)
|
||||
if got.Status != EgressUp || got.EgressIP != "1.2.3.4" || got.ListenPort != 18080 {
|
||||
t.Fatalf("runtime: %+v", got)
|
||||
}
|
||||
|
||||
list, err := store.ListEgressProfiles()
|
||||
if err != nil || len(list) != 1 {
|
||||
t.Fatalf("list: %v %#v", err, list)
|
||||
}
|
||||
|
||||
if err := store.DeleteEgressProfile(p.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.GetEgressProfile(p.ID); err == nil {
|
||||
t.Fatal("expected missing after delete")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamEgressField(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store, err := Open(filepath.Join(dir, "data"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
st, err := store.CreateStream(CreateStream{Name: "rte1", MPD: "https://x/a.mpd", Egress: "Dublin"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Egress != "dublin" || !st.HasEgress || st.HasProxy {
|
||||
t.Fatalf("create egress: %+v has_egress=%v has_proxy=%v", st.Egress, st.HasEgress, st.HasProxy)
|
||||
}
|
||||
|
||||
empty := ""
|
||||
london := "london"
|
||||
st, err = store.PatchStream(st.ID, PatchStream{Egress: &london})
|
||||
if err != nil || st.Egress != "london" {
|
||||
t.Fatalf("patch: %+v %v", st, err)
|
||||
}
|
||||
st, err = store.PatchStream(st.ID, PatchStream{Egress: &empty})
|
||||
if err != nil || st.HasEgress {
|
||||
t.Fatalf("clear egress: %+v %v", st, err)
|
||||
}
|
||||
}
|
||||
80
apps/streamd/internal/egress/conf.go
Normal file
80
apps/streamd/internal/egress/conf.go
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
package egress
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// wgInterfaceAddrs extracts Address= values from the [Interface] section of a
|
||||
// wg-quick style conf. Private keys are never returned or logged.
|
||||
func wgInterfaceAddrs(conf string) []string {
|
||||
var addrs []string
|
||||
section := ""
|
||||
sc := bufio.NewScanner(strings.NewReader(conf))
|
||||
for sc.Scan() {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
|
||||
section = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1]))
|
||||
continue
|
||||
}
|
||||
if section != "interface" {
|
||||
continue
|
||||
}
|
||||
key, val, ok := strings.Cut(line, "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(key), "Address") {
|
||||
for _, part := range strings.Split(val, ",") {
|
||||
if a := strings.TrimSpace(part); a != "" {
|
||||
addrs = append(addrs, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return addrs
|
||||
}
|
||||
|
||||
// wgSetconfBody strips wg-quick-only keys so the result is valid for `wg setconf`.
|
||||
func wgSetconfBody(conf string) string {
|
||||
var b strings.Builder
|
||||
section := ""
|
||||
sc := bufio.NewScanner(strings.NewReader(conf))
|
||||
for sc.Scan() {
|
||||
raw := sc.Text()
|
||||
line := strings.TrimSpace(raw)
|
||||
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
|
||||
section = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1]))
|
||||
b.WriteString(line)
|
||||
b.WriteByte('\n')
|
||||
continue
|
||||
}
|
||||
key, _, ok := strings.Cut(line, "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
k := strings.ToLower(strings.TrimSpace(key))
|
||||
if section == "interface" {
|
||||
switch k {
|
||||
case "privatekey", "listenport", "fwmark":
|
||||
b.WriteString(line)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
continue
|
||||
}
|
||||
if section == "peer" {
|
||||
switch k {
|
||||
case "publickey", "presharedkey", "allowedips", "endpoint", "persistentkeepalive":
|
||||
b.WriteString(line)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
401
apps/streamd/internal/egress/manager.go
Normal file
401
apps/streamd/internal/egress/manager.go
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
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{},
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
100
apps/streamd/internal/egress/manager_test.go
Normal file
100
apps/streamd/internal/egress/manager_test.go
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
package egress
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
func TestResolveProxyOrder(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store, err := db.Open(filepath.Join(dir, "data"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
m := New(filepath.Join(dir, "data"), store, nil, "")
|
||||
|
||||
// Neither proxy nor egress.
|
||||
got, err := m.ResolveProxy(db.Stream{Name: "a"})
|
||||
if err != nil || got != "" {
|
||||
t.Fatalf("empty: got %q err %v", got, err)
|
||||
}
|
||||
|
||||
// Explicit proxy wins over egress.
|
||||
got, err = m.ResolveProxy(db.Stream{
|
||||
Proxy: "socks5://127.0.0.1:9999",
|
||||
Egress: "london",
|
||||
})
|
||||
if err != nil || got != "socks5://127.0.0.1:9999" {
|
||||
t.Fatalf("proxy wins: got %q err %v", got, err)
|
||||
}
|
||||
|
||||
on := true
|
||||
_, err = store.CreateEgressProfile(db.CreateEgressProfile{
|
||||
Name: "dublin",
|
||||
Kind: db.EgressKindSocks,
|
||||
Enabled: &on,
|
||||
SocksURL: "socks5://10.0.0.5:1080",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err = m.ResolveProxy(db.Stream{Egress: "dublin"})
|
||||
if err != nil || got != "socks5://10.0.0.5:1080" {
|
||||
t.Fatalf("egress socks: got %q err %v", got, err)
|
||||
}
|
||||
|
||||
// Missing profile.
|
||||
_, err = m.ResolveProxy(db.Stream{Egress: "missing"})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing profile")
|
||||
}
|
||||
|
||||
// WireGuard on non-Linux must fail EnsureUp (covered when GOOS != linux).
|
||||
_, err = store.CreateEgressProfile(db.CreateEgressProfile{
|
||||
Name: "london", Kind: db.EgressKindWireGuard, Enabled: &on,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = m.ResolveProxy(db.Stream{Egress: "london"})
|
||||
// On Linux without conf/tools this also errors; on Windows always errors.
|
||||
if err == nil {
|
||||
t.Fatal("expected wireguard EnsureUp to fail without a working tunnel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWgConfParse(t *testing.T) {
|
||||
conf := `[Interface]
|
||||
PrivateKey = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEE=
|
||||
Address = 10.64.0.2/32
|
||||
Address = fd00::2/128
|
||||
DNS = 1.1.1.1
|
||||
|
||||
[Peer]
|
||||
PublicKey = BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBEE=
|
||||
AllowedIPs = 0.0.0.0/0, ::/0
|
||||
Endpoint = 203.0.113.1:51820
|
||||
`
|
||||
addrs := wgInterfaceAddrs(conf)
|
||||
if len(addrs) != 2 || addrs[0] != "10.64.0.2/32" || addrs[1] != "fd00::2/128" {
|
||||
t.Fatalf("addrs: %#v", addrs)
|
||||
}
|
||||
body := wgSetconfBody(conf)
|
||||
lower := strings.ToLower(body)
|
||||
if strings.Contains(lower, "address") || strings.Contains(lower, "dns") {
|
||||
t.Fatalf("setconf body still has wg-quick keys:\n%s", body)
|
||||
}
|
||||
if !strings.Contains(body, "PrivateKey") || !strings.Contains(body, "PublicKey") {
|
||||
t.Fatalf("setconf missing keys:\n%s", body)
|
||||
}
|
||||
addrs = wgInterfaceAddrs("[Interface]\nAddress = 10.1.0.2/32, 10.1.0.3/32\n")
|
||||
if len(addrs) != 2 {
|
||||
t.Fatalf("combined: %#v", addrs)
|
||||
}
|
||||
}
|
||||
262
apps/streamd/internal/egress/wg_linux.go
Normal file
262
apps/streamd/internal/egress/wg_linux.go
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
//go:build linux
|
||||
|
||||
package egress
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
|
||||
name := p.Name
|
||||
confPath := m.confPath(name)
|
||||
raw, err := os.ReadFile(confPath)
|
||||
if err != nil {
|
||||
msg := "wg.conf missing; upload a WireGuard conf first"
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
|
||||
return fmt.Errorf("egress %q: %s", name, msg)
|
||||
}
|
||||
addrs := wgInterfaceAddrs(string(raw))
|
||||
if len(addrs) == 0 {
|
||||
msg := "wg.conf has no Interface Address="
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
|
||||
return fmt.Errorf("egress %q: %s", name, msg)
|
||||
}
|
||||
socksBin, err := m.findSocksBin()
|
||||
if err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
return err
|
||||
}
|
||||
if _, err := exec.LookPath("ip"); err != nil {
|
||||
msg := "ip (iproute2) not found on PATH"
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
|
||||
return fmt.Errorf("%s", msg)
|
||||
}
|
||||
if _, err := exec.LookPath("wg"); err != nil {
|
||||
msg := "wg (wireguard-tools) not found on PATH"
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
|
||||
return fmt.Errorf("%s", msg)
|
||||
}
|
||||
|
||||
listenPort := p.ListenPort
|
||||
if listenPort <= 0 {
|
||||
listenPort = m.allocListenPort(p.ID)
|
||||
}
|
||||
hostIP, nsIP, _ := m.vethAddrs(p.ID)
|
||||
nsName := netnsName(name)
|
||||
wgDev := wgDevName(name)
|
||||
hostVeth := hostVethName(name)
|
||||
nsVeth := "hv0"
|
||||
|
||||
// Tear down any leftover state before bringing up.
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
|
||||
run := func(args ...string) error {
|
||||
cmd := exec.Command(args[0], args[1:]...)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w (%s)", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
nsExec := func(args ...string) error {
|
||||
full := append([]string{"ip", "netns", "exec", nsName}, args...)
|
||||
return run(full...)
|
||||
}
|
||||
|
||||
if err := run("ip", "netns", "add", nsName); err != nil {
|
||||
// Already exists is fine after a partial teardown.
|
||||
if !strings.Contains(err.Error(), "File exists") {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Loopback inside ns.
|
||||
_ = nsExec("ip", "link", "set", "lo", "up")
|
||||
|
||||
if err := run("ip", "link", "add", wgDev, "type", "wireguard"); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
return err
|
||||
}
|
||||
if err := run("ip", "link", "set", wgDev, "netns", nsName); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = run("ip", "link", "del", wgDev)
|
||||
return err
|
||||
}
|
||||
|
||||
setconfPath := filepath.Join(m.profileDir(name), "wg.setconf")
|
||||
body := wgSetconfBody(string(raw))
|
||||
if err := os.WriteFile(setconfPath, []byte(body), 0o600); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
return err
|
||||
}
|
||||
if err := nsExec("wg", "setconf", wgDev, setconfPath); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
for _, a := range addrs {
|
||||
if err := nsExec("ip", "address", "add", a, "dev", wgDev); err != nil {
|
||||
// "File exists" after restart is fine.
|
||||
if !strings.Contains(err.Error(), "File exists") {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := nsExec("ip", "link", "set", wgDev, "up"); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
// Default route only inside the netns — never the host table.
|
||||
_ = nsExec("ip", "route", "replace", "default", "dev", wgDev)
|
||||
|
||||
if err := run("ip", "link", "add", hostVeth, "type", "veth", "peer", "name", nsVeth); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
if err := run("ip", "link", "set", nsVeth, "netns", nsName); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
if err := run("ip", "addr", "add", hostIP+"/24", "dev", hostVeth); err != nil && !strings.Contains(err.Error(), "File exists") {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
if err := run("ip", "link", "set", hostVeth, "up"); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
if err := nsExec("ip", "addr", "add", nsIP+"/24", "dev", nsVeth); err != nil && !strings.Contains(err.Error(), "File exists") {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
if err := nsExec("ip", "link", "set", nsVeth, "up"); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
socksCmd, err := m.startSocksInNS(nsName, socksBin, nsIP)
|
||||
if err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
ln, stopFwd, err := m.startLocalForward(listenPort, nsIP, socksPortInNS)
|
||||
if err != nil {
|
||||
_ = socksCmd.Process.Kill()
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
_ = m.teardownWireGuard(name, p.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
rs := &runState{
|
||||
name: name,
|
||||
listenPort: listenPort,
|
||||
nsIP: nsIP,
|
||||
socksCmd: socksCmd,
|
||||
forwardLn: ln,
|
||||
stopFwd: stopFwd,
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.running[name] = rs
|
||||
m.mu.Unlock()
|
||||
|
||||
egressIP := probeEgressIP(nsName)
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressUp, "", egressIP, listenPort)
|
||||
m.logger().Info("egress up", "name", name, "listen", listenPort, "ns", nsName, "egress_ip", egressIP)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) startSocksInNS(nsName, socksBin, bindIP string) (*exec.Cmd, error) {
|
||||
base := filepath.Base(socksBin)
|
||||
var cmd *exec.Cmd
|
||||
switch {
|
||||
case strings.Contains(base, "gost"):
|
||||
cmd = exec.Command("ip", "netns", "exec", nsName, socksBin,
|
||||
"-L", fmt.Sprintf("socks5://%s:%d", bindIP, socksPortInNS))
|
||||
default:
|
||||
// microsocks
|
||||
cmd = exec.Command("ip", "netns", "exec", nsName, socksBin,
|
||||
"-i", bindIP, "-p", fmt.Sprintf("%d", socksPortInNS))
|
||||
}
|
||||
cmd.Stdout = nil
|
||||
cmd.Stderr = nil
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, fmt.Errorf("start socks in netns: %w", err)
|
||||
}
|
||||
// Brief wait so a crash-on-start is visible.
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if cmd.ProcessState != nil && cmd.ProcessState.Exited() {
|
||||
return nil, fmt.Errorf("socks exited immediately")
|
||||
}
|
||||
return cmd, nil
|
||||
}
|
||||
|
||||
func (m *Manager) teardownWireGuard(name string, _ int64) error {
|
||||
nsName := netnsName(name)
|
||||
wgDev := wgDevName(name)
|
||||
hostVeth := hostVethName(name)
|
||||
|
||||
runQuiet := func(args ...string) {
|
||||
_ = exec.Command(args[0], args[1:]...).Run()
|
||||
}
|
||||
runQuiet("ip", "netns", "exec", nsName, "ip", "link", "del", wgDev)
|
||||
runQuiet("ip", "link", "del", hostVeth)
|
||||
runQuiet("ip", "link", "del", wgDev) // if still in init ns
|
||||
runQuiet("ip", "netns", "del", nsName)
|
||||
_ = os.Remove(filepath.Join(m.profileDir(name), "wg.setconf"))
|
||||
return nil
|
||||
}
|
||||
|
||||
func netnsName(name string) string {
|
||||
return "streamd-" + name
|
||||
}
|
||||
|
||||
func wgDevName(name string) string {
|
||||
// IFNAMSIZ is 15.
|
||||
s := "wg-" + name
|
||||
if len(s) > 15 {
|
||||
s = s[:15]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func hostVethName(name string) string {
|
||||
s := "sv-" + name
|
||||
if len(s) > 15 {
|
||||
s = s[:15]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func probeEgressIP(nsName string) string {
|
||||
// Best-effort: ask a public echo over the ns default route.
|
||||
cmd := exec.Command("ip", "netns", "exec", nsName,
|
||||
"curl", "-4", "-fsS", "--max-time", "5", "https://ifconfig.me/ip")
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
cmd = exec.Command("ip", "netns", "exec", nsName,
|
||||
"wget", "-qO-", "--timeout=5", "https://ifconfig.me/ip")
|
||||
out, err = cmd.Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
19
apps/streamd/internal/egress/wg_stub.go
Normal file
19
apps/streamd/internal/egress/wg_stub.go
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
//go:build !linux
|
||||
|
||||
package egress
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
|
||||
msg := "wireguard egress requires Linux"
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
|
||||
return fmt.Errorf("%s", msg)
|
||||
}
|
||||
|
||||
func (m *Manager) teardownWireGuard(name string, id int64) error {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -28,6 +28,9 @@ const (
|
|||
|
||||
var NameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`)
|
||||
|
||||
// archDirRe matches .bin/<goos>-<goarch>/ folder names (never a module name).
|
||||
var archDirRe = regexp.MustCompile(`^[a-z0-9]+-(amd64|arm64|386|arm)$`)
|
||||
|
||||
// Info is one module's metadata for the API and agent sync.
|
||||
type Info struct {
|
||||
Name string `json:"name"`
|
||||
|
|
@ -387,23 +390,7 @@ func inspectZipReader(zr *zip.Reader, nameHint string) (string, []zipEntry, erro
|
|||
}
|
||||
|
||||
if hint == "" {
|
||||
// Try to infer from .bin/<arch>/<name> or .bin/<name>.
|
||||
for _, f := range zr.File {
|
||||
n := strings.ReplaceAll(f.Name, "\\", "/")
|
||||
n = strings.TrimPrefix(n, "./")
|
||||
if prefix != "" {
|
||||
if !strings.HasPrefix(n, prefix) {
|
||||
continue
|
||||
}
|
||||
n = strings.TrimPrefix(n, prefix)
|
||||
}
|
||||
base := filepath.Base(n)
|
||||
base = strings.TrimSuffix(base, ".exe")
|
||||
if strings.HasPrefix(n, ".bin/") && NameRe.MatchString(base) && base != ".bin" {
|
||||
hint = base
|
||||
break
|
||||
}
|
||||
}
|
||||
hint = inferNameFromBinEntries(zr, prefix)
|
||||
}
|
||||
if hint == "" {
|
||||
return "", nil, fmt.Errorf("cannot infer module name from zip; pass name=")
|
||||
|
|
@ -476,6 +463,47 @@ func extractZipEntries(zipBytes []byte, entries []zipEntry, destDir string) erro
|
|||
return nil
|
||||
}
|
||||
|
||||
// inferNameFromBinEntries picks the module binary basename from
|
||||
// .bin/<arch>/<name>[.exe] or .bin/<name>[.exe]. Directory entries and
|
||||
// arch folder names (linux-amd64, darwin-arm64, …) are skipped — those used
|
||||
// to be mistaken for the module name on flat release zips.
|
||||
func inferNameFromBinEntries(zr *zip.Reader, prefix string) string {
|
||||
var fallback string
|
||||
for _, f := range zr.File {
|
||||
if f.FileInfo().IsDir() {
|
||||
continue
|
||||
}
|
||||
n := strings.ReplaceAll(f.Name, "\\", "/")
|
||||
n = strings.TrimPrefix(n, "./")
|
||||
if prefix != "" {
|
||||
if !strings.HasPrefix(n, prefix) {
|
||||
continue
|
||||
}
|
||||
n = strings.TrimPrefix(n, prefix)
|
||||
}
|
||||
n = strings.TrimSuffix(n, "/")
|
||||
if !strings.HasPrefix(n, ".bin/") {
|
||||
continue
|
||||
}
|
||||
rel := strings.TrimPrefix(n, ".bin/")
|
||||
parts := strings.Split(rel, "/")
|
||||
base := parts[len(parts)-1]
|
||||
base = strings.TrimSuffix(base, ".exe")
|
||||
if !NameRe.MatchString(base) || archDirRe.MatchString(base) {
|
||||
continue
|
||||
}
|
||||
// Prefer .bin/<arch>/<name>
|
||||
if len(parts) >= 2 && archDirRe.MatchString(parts[0]) {
|
||||
return base
|
||||
}
|
||||
// .bin/<name>
|
||||
if len(parts) == 1 && fallback == "" {
|
||||
fallback = base
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func isUnder(root, path string) bool {
|
||||
absRoot, err1 := filepath.Abs(root)
|
||||
absPath, err2 := filepath.Abs(path)
|
||||
|
|
|
|||
|
|
@ -29,6 +29,27 @@ func makeZip(t *testing.T, files map[string][]byte) []byte {
|
|||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestInstallZipInfersNameNotArchDir(t *testing.T) {
|
||||
// Flat release zips list .bin/darwin-arm64/ before the binary; that arch
|
||||
// folder must not become the module name.
|
||||
root := t.TempDir()
|
||||
s := New(root)
|
||||
zipBytes := makeZip(t, map[string][]byte{
|
||||
"module.yaml": []byte("package: air.RTE\nchannels:\n rteone: {label: One}\n"),
|
||||
".bin/": nil, // directory markers via path only
|
||||
".bin/darwin-arm64/rte": []byte("mac-bin"),
|
||||
".bin/linux-amd64/rte": []byte("linux-bin"),
|
||||
".bin/windows-amd64/rte.exe": []byte("win-bin"),
|
||||
})
|
||||
info, err := s.InstallZip(zipBytes, "")
|
||||
if err != nil {
|
||||
t.Fatalf("InstallZip: %v", err)
|
||||
}
|
||||
if info.Name != "rte" {
|
||||
t.Fatalf("inferred name=%q want rte", info.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallZipFlatAndYAMLOnly(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s := New(root)
|
||||
|
|
|
|||
|
|
@ -37,12 +37,19 @@ type Media struct {
|
|||
// ViewersFn reports the live client count for a stream, for the metrics
|
||||
// series. Optional.
|
||||
ViewersFn func(streamName string) int
|
||||
// ProxyResolver resolves stream.Proxy / stream.Egress to a SOCKS/HTTP URL.
|
||||
ProxyResolver ProxyResolver
|
||||
|
||||
mu sync.Mutex
|
||||
procs map[int64]*streamProc
|
||||
stopMon chan struct{}
|
||||
}
|
||||
|
||||
// ProxyResolver turns a stream row into an origin-fetch proxy URL.
|
||||
type ProxyResolver interface {
|
||||
ResolveProxy(st db.Stream) (string, error)
|
||||
}
|
||||
|
||||
// Notifier is the subset of the websocket hub the supervisor needs.
|
||||
type Notifier interface {
|
||||
NotifyRuntime(name, health string)
|
||||
|
|
@ -82,15 +89,16 @@ type streamProc struct {
|
|||
|
||||
// Options for constructing the media supervisor.
|
||||
type Options struct {
|
||||
Store *db.Store
|
||||
DataDir string
|
||||
NRE string
|
||||
FFmpeg string
|
||||
MP4Decrypt string
|
||||
Log *slog.Logger
|
||||
Fanout *tsfanout.Set
|
||||
Notifier Notifier
|
||||
ViewersFn func(streamName string) int
|
||||
Store *db.Store
|
||||
DataDir string
|
||||
NRE string
|
||||
FFmpeg string
|
||||
MP4Decrypt string
|
||||
Log *slog.Logger
|
||||
Fanout *tsfanout.Set
|
||||
Notifier Notifier
|
||||
ViewersFn func(streamName string) int
|
||||
ProxyResolver ProxyResolver
|
||||
}
|
||||
|
||||
func NewMedia(opt Options) *Media {
|
||||
|
|
@ -103,17 +111,18 @@ func NewMedia(opt Options) *Media {
|
|||
fan = tsfanout.NewSet(tsfanout.DefaultBufferBytes)
|
||||
}
|
||||
m := &Media{
|
||||
Store: opt.Store,
|
||||
DataDir: opt.DataDir,
|
||||
NRE: opt.NRE,
|
||||
FFmpeg: opt.FFmpeg,
|
||||
MP4Decrypt: opt.MP4Decrypt,
|
||||
Log: lg,
|
||||
Fanout: fan,
|
||||
Notifier: opt.Notifier,
|
||||
ViewersFn: opt.ViewersFn,
|
||||
procs: map[int64]*streamProc{},
|
||||
stopMon: make(chan struct{}),
|
||||
Store: opt.Store,
|
||||
DataDir: opt.DataDir,
|
||||
NRE: opt.NRE,
|
||||
FFmpeg: opt.FFmpeg,
|
||||
MP4Decrypt: opt.MP4Decrypt,
|
||||
Log: lg,
|
||||
Fanout: fan,
|
||||
Notifier: opt.Notifier,
|
||||
ViewersFn: opt.ViewersFn,
|
||||
ProxyResolver: opt.ProxyResolver,
|
||||
procs: map[int64]*streamProc{},
|
||||
stopMon: make(chan struct{}),
|
||||
}
|
||||
go m.monitorLoop()
|
||||
return m
|
||||
|
|
@ -143,6 +152,13 @@ func (m *Media) Running(id int64) bool {
|
|||
|
||||
func (m *Media) logsDir() string { return filepath.Join(m.DataDir, "logs") }
|
||||
|
||||
func (m *Media) effectiveProxy(st db.Stream) (string, error) {
|
||||
if m.ProxyResolver != nil {
|
||||
return m.ProxyResolver.ResolveProxy(st)
|
||||
}
|
||||
return strings.TrimSpace(st.Proxy), nil
|
||||
}
|
||||
|
||||
func (m *Media) Start(id int64) error {
|
||||
st, err := m.Store.GetStream(id)
|
||||
if err != nil {
|
||||
|
|
@ -203,12 +219,17 @@ func (m *Media) Start(id int64) error {
|
|||
saveName := st.Name
|
||||
headers := headerMap(st.HeadersJSON)
|
||||
cfg := settingsFor(st, m.Store.GlobalPackagerSettings())
|
||||
originProxy, err := m.effectiveProxy(st)
|
||||
if err != nil {
|
||||
m.fail(id, st.Name, "egress: "+err.Error())
|
||||
return err
|
||||
}
|
||||
manifestURL := st.MPD
|
||||
var mpdProxy *mpd.LocalServer
|
||||
// The rewriter is named by the stream row or its app module and looked up in
|
||||
// the mpd registry, so streamd needs no knowledge of any provider.
|
||||
if rw, needed := mpd.Lookup(cfg.Rewriter); needed && strings.TrimSpace(st.MPD) != "" && !cfg.IsHLS {
|
||||
srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, st.Proxy)
|
||||
srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, originProxy)
|
||||
if err != nil {
|
||||
m.fail(id, st.Name, "mpd rewrite server: "+err.Error())
|
||||
return err
|
||||
|
|
@ -246,7 +267,7 @@ func (m *Media) Start(id int64) error {
|
|||
"--mp4-real-time-decryption",
|
||||
)
|
||||
}
|
||||
if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
|
||||
if proxy := strings.TrimSpace(originProxy); proxy != "" {
|
||||
// NRE prefers --custom-proxy over the system proxy when both are set.
|
||||
// The proxy may carry credentials, so it is not logged.
|
||||
nreArgs = append(nreArgs, "--custom-proxy", proxy)
|
||||
|
|
|
|||
|
|
@ -117,6 +117,20 @@ export const api = {
|
|||
patchSchedule: (sid, body) => api.patch(`/api/schedules/${sid}`, body),
|
||||
deleteSchedule: (sid) => api.del(`/api/schedules/${sid}`),
|
||||
|
||||
// --- egress tunnels ---
|
||||
egress: () => api.get("/api/egress"),
|
||||
egressProfiles: () => api.get("/api/egress"),
|
||||
egressProfile: (name) => api.get(`/api/egress/${encodeURIComponent(name)}`),
|
||||
createEgress: (body) => api.post("/api/egress", body),
|
||||
saveEgress: (name, body) => api.put(`/api/egress/${encodeURIComponent(name)}`, body),
|
||||
updateEgress: (name, body) => api.put(`/api/egress/${encodeURIComponent(name)}`, body),
|
||||
deleteEgress: (name) => api.del(`/api/egress/${encodeURIComponent(name)}`),
|
||||
egressUp: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/up`),
|
||||
egressDown: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/down`),
|
||||
egressTest: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/test`),
|
||||
egressConf: (name, conf) =>
|
||||
api.put(`/api/egress/${encodeURIComponent(name)}/conf`, { conf }),
|
||||
|
||||
// --- admin ---
|
||||
settings: () => api.get("/api/settings"),
|
||||
saveSettings: (body) => api.put("/api/settings", body),
|
||||
|
|
|
|||
|
|
@ -36,6 +36,11 @@ export function el(spec, attrs, ...children) {
|
|||
else if (k === "dataset") Object.assign(node.dataset, v);
|
||||
else if (k === "style" && typeof v === "object") Object.assign(node.style, v);
|
||||
else if (k.startsWith("on") && typeof v === "function") node.addEventListener(k.slice(2), v);
|
||||
// Form controls: set the live property. setAttribute("value") does not fill
|
||||
// <textarea>, and checked must be a property too.
|
||||
else if (k === "value") node.value = v;
|
||||
else if (k === "checked") node.checked = !!v;
|
||||
else if (k === "selected") node.selected = !!v;
|
||||
else if (v === true) node.setAttribute(k, "");
|
||||
else node.setAttribute(k, v);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -192,12 +192,186 @@ export function settingsView(root) {
|
|||
),
|
||||
),
|
||||
);
|
||||
wrap.append(await egressCard());
|
||||
}
|
||||
|
||||
load();
|
||||
return () => {};
|
||||
}
|
||||
|
||||
async function egressCard() {
|
||||
const box = el("div.card",
|
||||
el("div.card-head",
|
||||
el("h2", { text: "Egress tunnels" }),
|
||||
el("span.spacer"),
|
||||
el("button.sm", { type: "button", text: "+ Add profile", onclick: () => openEgressDialog(reload) }),
|
||||
),
|
||||
el("p.hint", {
|
||||
text: "Named WireGuard (Linux netns + local SOCKS) or SOCKS URL profiles. " +
|
||||
"Assign a profile per stream so only that stream’s origin fetch exits via the tunnel. " +
|
||||
"Full-tunnel WG stays inside a network namespace — SSH and the dashboard keep the host route.",
|
||||
}),
|
||||
);
|
||||
const list = el("div");
|
||||
box.append(list);
|
||||
|
||||
async function reload() {
|
||||
clear(list);
|
||||
let data;
|
||||
try {
|
||||
data = await api.egress();
|
||||
} catch (err) {
|
||||
list.append(el("p.msg.err", { text: err.message }));
|
||||
return;
|
||||
}
|
||||
const profiles = data.profiles || [];
|
||||
if (!profiles.length) {
|
||||
list.append(el("p.hint", { text: "No profiles yet. Add london (or dublin, …) from a WireGuard client .conf." }));
|
||||
return;
|
||||
}
|
||||
for (const p of profiles) {
|
||||
const status = p.status || "stopped";
|
||||
const meta = [
|
||||
p.kind,
|
||||
status,
|
||||
p.listen_port ? `:${p.listen_port}` : null,
|
||||
p.egress_ip || null,
|
||||
p.has_conf ? "conf" : null,
|
||||
p.enabled ? "autostart" : null,
|
||||
].filter(Boolean).join(" · ");
|
||||
const row = el("div.row", {
|
||||
style: { alignItems: "center", gap: "8px", flexWrap: "wrap", padding: "8px 0", borderBottom: "1px solid var(--border)" },
|
||||
},
|
||||
el("div", { style: { flex: "1 1 160px" } },
|
||||
el("div.mono", { text: p.name }),
|
||||
el("small.muted", { text: meta }),
|
||||
p.last_error ? el("div.msg.err", { text: p.last_error, style: { marginTop: "4px" } }) : null,
|
||||
),
|
||||
el("button.ghost.sm", {
|
||||
type: "button", text: "Up",
|
||||
onclick: async () => {
|
||||
try { await api.egressUp(p.name); toast(`${p.name} up`); reload(); }
|
||||
catch (err) { toast(err.message, true); }
|
||||
},
|
||||
}),
|
||||
el("button.ghost.sm", {
|
||||
type: "button", text: "Down",
|
||||
onclick: async () => {
|
||||
try { await api.egressDown(p.name); toast(`${p.name} down`); reload(); }
|
||||
catch (err) { toast(err.message, true); }
|
||||
},
|
||||
}),
|
||||
el("button.ghost.sm", {
|
||||
type: "button", text: "Test IP",
|
||||
onclick: async () => {
|
||||
try {
|
||||
const r = await api.egressTest(p.name);
|
||||
toast(`${p.name} egress IP: ${r.egress_ip || r.ip || JSON.stringify(r)}`);
|
||||
reload();
|
||||
} catch (err) { toast(err.message, true); }
|
||||
},
|
||||
}),
|
||||
el("button.ghost.sm", {
|
||||
type: "button", text: "Edit",
|
||||
onclick: () => openEgressDialog(reload, p),
|
||||
}),
|
||||
el("button.ghost.sm.danger", {
|
||||
type: "button", text: "Delete",
|
||||
onclick: async () => {
|
||||
if (!confirm(`Delete egress profile ${p.name}?`)) return;
|
||||
try { await api.deleteEgress(p.name); toast("Deleted"); reload(); }
|
||||
catch (err) { toast(err.message, true); }
|
||||
},
|
||||
}),
|
||||
);
|
||||
list.append(row);
|
||||
}
|
||||
}
|
||||
|
||||
await reload();
|
||||
return box;
|
||||
}
|
||||
|
||||
function openEgressDialog(onDone, existing) {
|
||||
const isEdit = !!existing;
|
||||
const name = el("input", {
|
||||
required: true, placeholder: "london",
|
||||
value: existing?.name || "",
|
||||
disabled: isEdit,
|
||||
});
|
||||
const kind = el("select",
|
||||
el("option", { value: "wireguard", text: "WireGuard (Linux netns)", selected: !existing || existing.kind === "wireguard" }),
|
||||
el("option", { value: "socks", text: "SOCKS/HTTP URL only", selected: existing?.kind === "socks" }),
|
||||
);
|
||||
const enabled = el("input", { type: "checkbox", checked: existing ? !!existing.enabled : true });
|
||||
const socksURL = el("input", {
|
||||
placeholder: "socks5://127.0.0.1:1081",
|
||||
value: existing?.socks_url || "",
|
||||
});
|
||||
const conf = el("textarea", {
|
||||
rows: "12",
|
||||
placeholder: "[Interface]\nPrivateKey = …\nAddress = …\n\n[Peer]\nPublicKey = …\nEndpoint = …\nAllowedIPs = 0.0.0.0/0, ::/0\n",
|
||||
spellcheck: "false",
|
||||
});
|
||||
const msg = el("p.msg");
|
||||
|
||||
function syncKind() {
|
||||
socksURL.closest("label").hidden = kind.value !== "socks";
|
||||
conf.closest("label").hidden = kind.value !== "wireguard";
|
||||
}
|
||||
kind.addEventListener("change", syncKind);
|
||||
|
||||
const form = el("form",
|
||||
el("div.grid",
|
||||
el("label", el("span.lbl", { text: "Name (slug)" }), name),
|
||||
el("label", el("span.lbl", { text: "Kind" }), kind),
|
||||
el("label.inline-check", enabled, el("span", { text: "Auto-start with streamd serve" })),
|
||||
el("label.span2", el("span.lbl", { text: "SOCKS/HTTP URL" }), socksURL),
|
||||
el("label.span2", el("span.lbl", { text: "WireGuard client config" }), conf,
|
||||
el("small.hint", { text: isEdit ? "Leave blank to keep the stored conf. Pasting replaces it." : "Paste a client .conf (e.g. vps-london.conf). Private keys stay on the server." })),
|
||||
),
|
||||
msg,
|
||||
el("div.row.end", { style: { marginTop: "12px" } },
|
||||
el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }),
|
||||
el("button", { type: "submit", text: isEdit ? "Save" : "Create" }),
|
||||
),
|
||||
);
|
||||
syncKind();
|
||||
|
||||
form.addEventListener("submit", async (ev) => {
|
||||
ev.preventDefault();
|
||||
msg.textContent = "";
|
||||
msg.classList.remove("err");
|
||||
const slug = name.value.trim();
|
||||
try {
|
||||
if (isEdit) {
|
||||
const body = { kind: kind.value, enabled: enabled.checked };
|
||||
if (kind.value === "socks") body.socks_url = socksURL.value.trim();
|
||||
if (kind.value === "wireguard" && conf.value.trim()) body.conf = conf.value;
|
||||
await api.saveEgress(existing.name, body);
|
||||
} else {
|
||||
const body = { name: slug, kind: kind.value, enabled: enabled.checked };
|
||||
if (kind.value === "socks") body.socks_url = socksURL.value.trim();
|
||||
await api.createEgress(body);
|
||||
if (kind.value === "wireguard" && conf.value.trim()) {
|
||||
await api.saveEgress(slug, { conf: conf.value });
|
||||
}
|
||||
}
|
||||
toast(isEdit ? "Saved" : "Created");
|
||||
close();
|
||||
onDone();
|
||||
} catch (err) {
|
||||
msg.textContent = err.message;
|
||||
msg.classList.add("err");
|
||||
}
|
||||
});
|
||||
|
||||
const close = openModal(
|
||||
el("h2", { text: isEdit ? `Edit egress · ${existing.name}` : "Add egress profile" }),
|
||||
form,
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- people and API keys ----------
|
||||
|
||||
export function peopleView(root) {
|
||||
|
|
|
|||
|
|
@ -215,8 +215,12 @@ async function uploadFile(file, reload) {
|
|||
}
|
||||
toast(`Uploading ${file.name}…`);
|
||||
try {
|
||||
const res = await api.uploadModuleZip(file);
|
||||
const name = (res.module && res.module.name) || file.name;
|
||||
// Pass stem of rte.zip → "rte" so flat release zips never become "darwin-arm64".
|
||||
let hint = "";
|
||||
const base = (file.name || "").replace(/\.zip$/i, "").trim();
|
||||
if (/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(base)) hint = base;
|
||||
const res = await api.uploadModuleZip(file, hint || undefined);
|
||||
const name = (res.module && res.module.name) || hint || file.name;
|
||||
toast(`Uploaded ${name}`);
|
||||
reload();
|
||||
} catch (err) {
|
||||
|
|
|
|||
|
|
@ -33,7 +33,8 @@ export function streamCreate(root) {
|
|||
|
||||
const mpd = el("input", { placeholder: "https://…/manifest.mpd" });
|
||||
const key = el("textarea", { rows: "3", placeholder: "KID:KEY per line — leave empty for clear streams", spellcheck: "false" });
|
||||
const proxy = el("input", { placeholder: "socks5://127.0.0.1:1080 (optional)" });
|
||||
const egress = el("select", el("option", { value: "", text: "Direct (no tunnel)" }));
|
||||
const proxy = el("input", { placeholder: "socks5://… overrides egress if set" });
|
||||
const headers = el("input", { value: "{}" });
|
||||
const idle = el("input", { type: "number", value: "300", min: "30", max: "86400" });
|
||||
const drm = el("select",
|
||||
|
|
@ -98,6 +99,7 @@ export function streamCreate(root) {
|
|||
channel: chanSel.value,
|
||||
mpd: mpd.value.trim(),
|
||||
key: key.value.trim(),
|
||||
egress: egress.value.trim(),
|
||||
proxy: proxy.value.trim(),
|
||||
headers_json: headers.value.trim() || "{}",
|
||||
tags: tags.value,
|
||||
|
|
@ -171,7 +173,10 @@ export function streamCreate(root) {
|
|||
panel.append(el("div.grid",
|
||||
el("label.span2", el("span.lbl", { text: "Manifest URL" }), mpd),
|
||||
el("label.span2", el("span.lbl", { text: "Keys" }), key),
|
||||
el("label", el("span.lbl", { text: "Origin proxy" }), proxy),
|
||||
el("label", el("span.lbl", { text: "Egress tunnel" }), egress,
|
||||
el("small.hint", { text: "Named WireGuard / SOCKS profile (Settings → Egress). Direct = normal server route." })),
|
||||
el("label", el("span.lbl", { text: "Origin proxy URL" }), proxy,
|
||||
el("small.hint", { text: "Optional raw socks5:// or http://. If set, it overrides the egress dropdown." })),
|
||||
el("label", el("span.lbl", { text: "Headers JSON" }), headers),
|
||||
el("label", el("span.lbl", { text: "Encryption" }), drm),
|
||||
el("label", el("span.lbl", { text: "Rewriter" }), rewriter),
|
||||
|
|
@ -190,6 +195,8 @@ export function streamCreate(root) {
|
|||
row("Title", b.title || "—"),
|
||||
row("Module", b.app ? `${b.app} / ${b.channel || "—"}` : "—"),
|
||||
row("Manifest", b.mpd || "(from module / capture)"),
|
||||
row("Egress", b.egress || "Direct"),
|
||||
row("Origin proxy", b.proxy || "—"),
|
||||
row("Encryption", b.drm_mode),
|
||||
row("On-demand", b.on_demand ? "yes" : "no"),
|
||||
row("Public", b.public ? "yes" : "no"),
|
||||
|
|
@ -256,6 +263,19 @@ export function streamCreate(root) {
|
|||
} catch {
|
||||
// Module list is optional.
|
||||
}
|
||||
try {
|
||||
const eg = await api.egress();
|
||||
clear(egress);
|
||||
egress.append(el("option", { value: "", text: "Direct (no tunnel)" }));
|
||||
for (const p of eg.profiles || []) {
|
||||
const label = p.status && p.status !== "stopped"
|
||||
? `${p.name} (${p.kind}, ${p.status})`
|
||||
: `${p.name} (${p.kind})`;
|
||||
egress.append(el("option", { value: p.name, text: label }));
|
||||
}
|
||||
} catch {
|
||||
// Egress API optional on older servers.
|
||||
}
|
||||
paint();
|
||||
})();
|
||||
|
||||
|
|
|
|||
|
|
@ -402,6 +402,7 @@ export function streamView(root, id, tab = "live") {
|
|||
const tags = el("input", { value: s.tags || "" });
|
||||
const mpd = el("input", { value: s.mpd || "" });
|
||||
const key = el("textarea", { rows: "3", placeholder: s.has_key ? "unchanged — type to replace" : "none", spellcheck: "false" });
|
||||
const egress = el("select", el("option", { value: "", text: "Direct (no tunnel)", selected: !s.egress }));
|
||||
const proxy = el("input", { placeholder: s.has_proxy ? "unchanged — type to replace" : "none" });
|
||||
const headers = el("input", { placeholder: s.has_headers ? "unchanged — type to replace" : "{}" });
|
||||
const drm = el("select",
|
||||
|
|
@ -482,6 +483,23 @@ export function streamView(root, id, tab = "live") {
|
|||
if (s.rewriter && !rewriters.includes(s.rewriter)) {
|
||||
rewriter.append(el("option", { value: s.rewriter, text: `${s.rewriter} (stored)`, selected: true }));
|
||||
}
|
||||
try {
|
||||
const eg = await api.egress();
|
||||
clear(egress);
|
||||
egress.append(el("option", { value: "", text: "Direct (no tunnel)", selected: !s.egress }));
|
||||
for (const p of eg.profiles || []) {
|
||||
egress.append(el("option", {
|
||||
value: p.name,
|
||||
text: `${p.name} (${p.kind}${p.status ? ", " + p.status : ""})`,
|
||||
selected: s.egress === p.name,
|
||||
}));
|
||||
}
|
||||
if (s.egress && !(eg.profiles || []).some((p) => p.name === s.egress)) {
|
||||
egress.append(el("option", { value: s.egress, text: `${s.egress} (stored)`, selected: true }));
|
||||
}
|
||||
} catch {
|
||||
// Older servers without /api/egress.
|
||||
}
|
||||
})();
|
||||
|
||||
const revealBtn = el("button.ghost.sm", {
|
||||
|
|
@ -514,7 +532,8 @@ export function streamView(root, id, tab = "live") {
|
|||
el("label", el("span.lbl", { text: "Audio select" }), audioSel),
|
||||
el("label.span2", el("span.lbl", { text: "Manifest URL" }), mpd),
|
||||
el("label.span2", el("span.lbl", { text: "Keys" }), key),
|
||||
el("label", el("span.lbl", { text: "Origin proxy" }), proxy),
|
||||
el("label", el("span.lbl", { text: "Egress tunnel" }), egress),
|
||||
el("label", el("span.lbl", { text: "Origin proxy URL" }), proxy),
|
||||
el("label", el("span.lbl", { text: "Headers JSON" }), headers),
|
||||
el("label", el("span.lbl", { text: "Idle timeout (s)" }), idle),
|
||||
el("label", el("span.lbl", { text: "Segment seconds" }), hlsTime),
|
||||
|
|
@ -560,6 +579,7 @@ export function streamView(root, id, tab = "live") {
|
|||
};
|
||||
// Only send a credential when it was actually typed, so saving the form
|
||||
// does not wipe a key the browser was never given.
|
||||
body.egress = egress.value.trim();
|
||||
if (key.value.trim()) body.key = key.value.trim();
|
||||
if (proxy.value.trim()) body.proxy = proxy.value.trim();
|
||||
if (headers.value.trim()) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue