package main import ( "archive/tar" "archive/zip" "bufio" "bytes" "compress/bzip2" "compress/gzip" "context" "crypto/rand" "crypto/sha256" "crypto/subtle" "crypto/tls" "encoding/base64" "encoding/binary" "encoding/hex" "encoding/json" "errors" "fmt" "io" "io/fs" "mime" "mime/multipart" "net" "net/http" "net/netip" "net/url" "nhooyr.io/websocket" "nhooyr.io/websocket/wsjson" "os" "os/exec" "os/signal" "path" "path/filepath" "reflect" "regexp" "runtime" "sort" "strconv" "strings" "sync" "syscall" "time" "unicode/utf8" "github.com/creack/pty" "github.com/ulikunitz/xz" ) const ( NodeVersion = "1.2.5" DefaultConfigPath = "/var/lib/node/config.yml" DefaultDataRoot = "/var/lib/node" // DefaultAPIHost stays the wildcard bind for TLS-enabled listeners // (unchanged legacy behavior); plaintext listeners default to // DefaultAPILoopbackHost instead — see resolveAPIBindHost. DefaultAPIHost = "0.0.0.0" DefaultAPILoopbackHost = "127.0.0.1" DefaultAPIPort = 8080 NodeInfoFileName = "node-information.json" NodeUpdateMaxBody = 20 * 1024 * 1024 ) type Config struct { Raw map[string]any } type NodeInformation struct { NodeVersion string `json:"node-version"` NodeArchitecture string `json:"node-architecture"` NodeAutoUpdate bool `json:"node-auto-update"` UpdatedAt string `json:"updated-at,omitempty"` // adpanel:multidisk - registered additional disks. nil/empty => primary-only. Disks []NodeDisk `json:"disks,omitempty"` } // NodeDisk describes a storage location available to this node. The primary disk // is synthetic (ID="primary", MountPath=a.dataRoot) and is never persisted here // nor deletable; only additional disks live in NodeInformation.Disks. type NodeDisk struct { ID string `json:"id"` MountPath string `json:"mountPath"` LimitGb int64 `json:"limitGb"` Primary bool `json:"primary,omitempty"` CreatedAt string `json:"createdAt,omitempty"` } type nodeUpdateFilePayload struct { Path string `json:"path"` ContentBase64 string `json:"contentBase64"` } type nodeUpdateInstallRequest struct { Version string `json:"version"` Files []nodeUpdateFilePayload `json:"files"` } type nodeUpdateAutoRequest struct { Enabled bool `json:"enabled"` } func (c Config) Bool(path ...string) bool { v := c.Any(path...) b, _ := v.(bool) return b } func (c Config) String(path ...string) string { v := c.Any(path...) switch x := v.(type) { case string: return x default: return "" } } func (c Config) Int(path ...string) int { v := c.Any(path...) switch x := v.(type) { case int: return x case int64: return int(x) case float64: return int(x) case string: n, _ := strconv.Atoi(strings.TrimSpace(x)) return n default: return 0 } } func (c Config) Any(path ...string) any { cur := any(c.Raw) for _, k := range path { m, ok := cur.(map[string]any) if !ok { return nil } cur = m[k] } return cur } func parseYAMLSubset(src string) (map[string]any, error) { lines := strings.Split(strings.ReplaceAll(src, "\r\n", "\n"), "\n") root := map[string]any{} type frame struct { indent int obj map[string]any } stack := []frame{{indent: -1, obj: root}} for lineNum, raw := range lines { line := strings.ReplaceAll(raw, "\t", " ") trim := strings.TrimSpace(line) if trim == "" || strings.HasPrefix(trim, "#") { continue } indent := len(line) - len(strings.TrimLeft(line, " ")) for len(stack) > 0 && indent <= stack[len(stack)-1].indent { stack = stack[:len(stack)-1] } if len(stack) == 0 { return nil, fmt.Errorf("yaml parse: invalid indent at line %d", lineNum+1) } cur := stack[len(stack)-1].obj parts := strings.SplitN(strings.TrimSpace(line), ":", 2) if len(parts) != 2 { fmt.Fprintf(os.Stderr, "[warn] yaml parse: malformed line %d (missing colon): %s\n", lineNum+1, trim) continue } key := strings.TrimSpace(parts[0]) valRaw := strings.TrimSpace(parts[1]) if valRaw == "" { obj := map[string]any{} cur[key] = obj stack = append(stack, frame{indent: indent, obj: obj}) continue } val := any(valRaw) if (strings.HasPrefix(valRaw, `"`) && strings.HasSuffix(valRaw, `"`)) || (strings.HasPrefix(valRaw, `'`) && strings.HasSuffix(valRaw, `'`)) { val = valRaw[1 : len(valRaw)-1] } else if strings.EqualFold(valRaw, "true") || strings.EqualFold(valRaw, "false") { val = strings.EqualFold(valRaw, "true") } else if n, err := strconv.ParseInt(valRaw, 10, 64); err == nil { val = int(n) } else if f, err := strconv.ParseFloat(valRaw, 64); err == nil { val = f } cur[key] = val } return root, nil } func mustReadFile(p string) []byte { b, err := os.ReadFile(p) if err != nil { fmt.Fprintf(os.Stderr, "[fatal] read %s: %v\n", p, err) os.Exit(1) } return b } func ensureDir(p string) error { return os.MkdirAll(p, 0o755) } func anyToInt(v any) int { switch x := v.(type) { case int: return x case int64: return int(x) case float64: return int(x) case float32: return int(x) case string: n, _ := strconv.Atoi(strings.TrimSpace(x)) return n default: return 0 } } func anyToInt64(v any) int64 { switch x := v.(type) { case int: return int64(x) case int64: return x case int32: return int64(x) case float64: return int64(x) case float32: return int64(x) case string: n, _ := strconv.ParseInt(strings.TrimSpace(x), 10, 64) return n default: return 0 } } func anyToFloat64(v any) float64 { switch x := v.(type) { case float64: return x case float32: return float64(x) case int: return float64(x) case int64: return float64(x) case string: n, _ := strconv.ParseFloat(strings.TrimSpace(x), 64) return n default: return 0 } } // openWriteNoFollowMode opens path for a truncating write without following a // symlink in the final path component. When excl is true, O_EXCL is added so // the open only succeeds if the file does NOT exist yet: the existence check // then happens inside the same open(2) that produces the handle, which makes // handleFSWrite's "create" mode race-free (a plain Lstat pre-check leaves a // window where another process can create the target between the check and // the write, turning a create into an overwrite). func openWriteNoFollowMode(path string, perm os.FileMode, excl bool) (*os.File, error) { flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC | openNoFollow if excl { flags |= os.O_EXCL } f, err := os.OpenFile(path, flags, perm) if err != nil { if errors.Is(err, syscall.ELOOP) { return nil, fmt.Errorf("refusing to write through symlink: %s", path) } return nil, err } return f, nil } func openWriteNoFollow(path string, perm os.FileMode) (*os.File, error) { return openWriteNoFollowMode(path, perm, false) } func writeFileNoFollow(path string, data []byte, perm os.FileMode) error { f, err := openWriteNoFollow(path, perm) if err != nil { return err } _, werr := f.Write(data) cerr := f.Close() if werr != nil { return werr } return cerr } func normalizeNodeVersionTag(version string) string { clean := strings.TrimSpace(version) if clean == "" { return "v" + NodeVersion } if strings.HasPrefix(strings.ToLower(clean), "v") { return "v" + strings.TrimPrefix(strings.TrimPrefix(clean, "v"), "V") } return "v" + clean } func validNodeUpdateVersion(version string) bool { return regexp.MustCompile(`^v?\d+\.\d+\.\d+([\-+][A-Za-z0-9_.-]+)?$`).MatchString(strings.TrimSpace(version)) } func allowedNodeUpdateFile(rel string) bool { raw := strings.TrimSpace(rel) if strings.Contains(raw, "/") || strings.Contains(raw, "\\") { return false } clean := filepath.Clean(raw) if clean == "." || clean == "" || strings.Contains(clean, "/") || strings.Contains(clean, string(filepath.Separator)) { return false } if clean == "go.mod" || clean == "go.sum" { return true } return regexp.MustCompile(`^[A-Za-z0-9_.-]+\.go$`).MatchString(clean) } func validateNodeUpdateFileContent(rel string, data []byte) error { if len(data) == 0 { return fmt.Errorf("%s is empty", rel) } if len(data) > 8*1024*1024 { return fmt.Errorf("%s is too large", rel) } if strings.HasSuffix(rel, ".go") && !bytes.HasPrefix(bytes.TrimSpace(data), []byte("package main")) { return fmt.Errorf("%s is not a package main Go file", rel) } if rel == "go.mod" && !bytes.HasPrefix(bytes.TrimSpace(data), []byte("module ")) { return fmt.Errorf("go.mod is invalid") } return nil } func copyRegularFile(src, dst string) error { in, err := os.Open(src) if err != nil { return err } defer in.Close() st, err := in.Stat() if err != nil { return err } if !st.Mode().IsRegular() { return nil } if err := ensureDir(filepath.Dir(dst)); err != nil { return err } out, err := openWriteNoFollow(dst, st.Mode().Perm()) if err != nil { return err } _, copyErr := io.Copy(out, in) closeErr := out.Close() if copyErr != nil { return copyErr } return closeErr } func sanitizeName(raw string) string { s := strings.TrimSpace(raw) s = regexp.MustCompile(`\s+`).ReplaceAllString(s, "-") s = regexp.MustCompile(`[^\w\-_.]+`).ReplaceAllString(s, "") s = strings.Trim(s, "-_.") for len(s) > 0 && !((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z') || (s[0] >= '0' && s[0] <= '9')) { s = s[1:] } if len(s) > 120 { s = s[:120] } return s } // sanitizeUploadFilename normalizes a client-supplied upload file name and is // the single sanitizer shared by every upload route (/v1/fs/upload stream, // /v1/fs/uploadRaw base64 and the legacy files upload), so all of them store // the same name for the same upload. Unlike sanitizeName — which is for // server/container names and must stay strict — uploaded file names keep // leading dots (game servers require .env-style dotfiles) and valid non-ASCII // UTF-8 characters. Traversal is removed by filepath.Base ("a/b" -> "b", // "a/.." -> ".."); backslashes, NUL, other control characters and invalid // UTF-8 bytes each become "_", edge whitespace is trimmed first (like the // panel's sanitizer) and the name is capped at 200 bytes on a rune boundary // (the same cap the URL-upload sanitizer applies). // Empty, ".", ".." and "/" results return "" so callers answer 400 with // "invalid filename" instead of silently substituting a fallback name. func sanitizeUploadFilename(raw string) string { s := filepath.Base(strings.TrimSpace(raw)) var b strings.Builder for i := 0; i < len(s); { r, size := utf8.DecodeRuneInString(s[i:]) switch { case r == '\\', r < 0x20, r == 0x7f, r == utf8.RuneError && size == 1: b.WriteByte('_') default: b.WriteRune(r) } i += size } s = strings.TrimSpace(b.String()) if s == "" || s == "." || s == ".." || s == "/" { return "" } for len(s) > 200 { _, size := utf8.DecodeLastRuneInString(s) s = s[:len(s)-size] } if s == "" || s == "." || s == ".." || s == "/" { return "" } return s } func isValidContainerName(name string) bool { if name == "" || len(name) > 120 { return false } if !((name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z') || (name[0] >= '0' && name[0] <= '9')) { return false } for _, c := range name { if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '.' || c == '-') { return false } } return true } func isDockerNativeContainerName(name string) bool { if name == "" || len(name) > 128 { return false } if len(name) < 2 { return false } if !((name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z') || (name[0] >= '0' && name[0] <= '9')) { return false } for _, c := range name { if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '.' || c == '-') { return false } } return true } func dockerContainerName(name string) string { clean := strings.TrimSpace(name) if isDockerNativeContainerName(clean) { return clean } safe := sanitizeName(clean) if safe == "" { return clean } sum := sha256.Sum256([]byte(clean)) hash := hex.EncodeToString(sum[:])[:12] if len(safe) > 64 { safe = safe[:64] } return "adpanel-" + hash + "-" + safe } func dockerContainerSpecName(spec string) string { if left, right, ok := strings.Cut(spec, ":"); ok && left != "" && !strings.Contains(left, "/") { return dockerContainerName(left) + ":" + right } return spec } func rewriteDockerCLIArgs(args []string) []string { if len(args) == 0 { return args } out := append([]string(nil), args...) rewriteLast := func() { if len(out) > 1 { out[len(out)-1] = dockerContainerName(out[len(out)-1]) } } switch out[0] { case "logs", "diff", "stop", "kill", "restart", "stats", "update": rewriteLast() case "inspect": rewriteLast() case "rm": for i := 1; i < len(out); i++ { if strings.HasPrefix(out[i], "-") { continue } out[i] = dockerContainerName(out[i]) } case "exec": for i := 1; i < len(out); i++ { if strings.HasPrefix(out[i], "-") { continue } out[i] = dockerContainerName(out[i]) break } case "cp": for i := 1; i < len(out); i++ { out[i] = dockerContainerSpecName(out[i]) } case "run": for i := 1; i < len(out)-1; i++ { if out[i] == "--name" { out[i+1] = dockerContainerName(out[i+1]) i++ } } } return out } func safeJoin(base, rel string) (string, bool) { r := rel if r == "" { return filepath.Clean(base), true } if filepath.IsAbs(r) { r = strings.TrimLeft(r, string(os.PathSeparator)) } target := filepath.Join(base, r) baseC := filepath.Clean(base) targetC := filepath.Clean(target) relToBase, err := filepath.Rel(baseC, targetC) if err != nil { return "", false } if relToBase == "." { return targetC, true } if strings.HasPrefix(relToBase, ".."+string(os.PathSeparator)) || relToBase == ".." || filepath.IsAbs(relToBase) { return "", false } return targetC, true } func isUnder(base, target string) bool { baseC := filepath.Clean(base) targetC := filepath.Clean(target) rel, err := filepath.Rel(baseC, targetC) if err != nil { return false } return rel == "." || (!strings.HasPrefix(rel, ".."+string(os.PathSeparator)) && rel != ".." && !filepath.IsAbs(rel)) } func ensureResolvedUnder(base, p string) error { resolved, err := filepath.EvalSymlinks(p) if err != nil { return err } baseC := filepath.Clean(base) if !isUnder(baseC, resolved) && baseC != resolved { return fmt.Errorf("symlink escape blocked") } return nil } func panelSafeCaps() []string { return []string{ "--cap-add=CHOWN", "--cap-add=DAC_OVERRIDE", "--cap-add=FOWNER", "--cap-add=SETUID", "--cap-add=SETGID", "--cap-add=KILL", "--cap-add=NET_BIND_SERVICE", "--cap-add=NET_RAW", "--cap-add=SYS_CHROOT", "--cap-add=AUDIT_WRITE", } } func containerSecurityArgs(uid, gid int, readOnly bool) []string { args := []string{"--cap-drop=ALL"} args = append(args, panelSafeCaps()...) args = append(args, "--security-opt=no-new-privileges", "--pids-limit=512", fmt.Sprintf("--user=%d:%d", uid, gid), ) if readOnly { args = append(args, "--read-only", "--tmpfs", "/tmp:rw,noexec,nosuid,size=256m", "--tmpfs", "/var/tmp:rw,noexec,nosuid,size=64m", "--tmpfs", "/run:rw,noexec,nosuid,size=32m", ) } return args } func timingSafeEq(a, b string) bool { return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 } func jsonWrite(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } // errBodyTooLarge marks a request body that exceeded the readJSON byte cap. // The panel maps the daemon's 400 for an over-budget write body to its // friendly 413 by matching the substring "content too large" (index.js // NODE_FS_WRITE_TOO_LARGE_MARKER, nodes.js, utils/dashboard-assistant-tools.js), // so handlers must keep that substring in their too-large responses and must // never send it for a plain JSON decode failure. var errBodyTooLarge = errors.New("request body too large") func readJSON(w http.ResponseWriter, r *http.Request, limitBytes int64, dst any) error { r.Body = http.MaxBytesReader(w, r.Body, limitBytes) defer r.Body.Close() dec := json.NewDecoder(r.Body) dec.DisallowUnknownFields() err := dec.Decode(dst) if err != nil { var maxBytesErr *http.MaxBytesError if errors.As(err, &maxBytesErr) { // *http.MaxBytesError only surfaces from the MaxBytesReader above // (its boundary is inclusive: a body of exactly limitBytes decodes // fine), so a truncated-body decode error can never be // misclassified as over-cap. return fmt.Errorf("%w (limit %d bytes)", errBodyTooLarge, maxBytesErr.Limit) } } return err } func (d Docker) containerExists(ctx context.Context, name string) bool { _, _, _, err := d.runCollect(ctx, "inspect", name) return err == nil } func (d Docker) containerState(ctx context.Context, name string) string { out, _, _, err := d.runCollect(ctx, "inspect", "-f", "{{.State.Status}}", name) if err != nil { return "" } return strings.ToLower(strings.TrimSpace(out)) } func (d Docker) kill(ctx context.Context, name string) { _, _, _, _ = d.runCollect(ctx, "kill", name) } func (d Docker) rmForce(ctx context.Context, name string) { d.kill(ctx, name) _, _, _, _ = d.runCollect(ctx, "rm", "-f", "-v", name) } func (d Docker) brutalRemoveContainer(ctx context.Context, name string) error { dockerName := dockerContainerName(name) if dockerName == "" { return fmt.Errorf("missing container name") } runAPIStep := func(timeout time.Duration, fn func(context.Context) error) error { if ctx.Err() != nil { return ctx.Err() } stepCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() return fn(stepCtx) } var lastErr error if err := runAPIStep(2*time.Second, func(stepCtx context.Context) error { return d.updateRestartNoAPI(stepCtx, dockerName) }); err != nil { lastErr = err } if err := runAPIStep(2*time.Second, func(stepCtx context.Context) error { return d.killContainerAPI(stepCtx, dockerName) }); err != nil { lastErr = err } if err := runAPIStep(5*time.Second, func(stepCtx context.Context) error { return d.removeContainerAPI(stepCtx, dockerName, true) }); err == nil { return nil } else { lastErr = err } cliCtx, cancel := context.WithTimeout(ctx, 4*time.Second) _, errText, code, err := d.runCollect(cliCtx, "rm", "-f", "-v", dockerName) cancel() if err == nil && code == 0 { return nil } if strings.TrimSpace(errText) != "" { lastErr = errors.New(strings.TrimSpace(errText)) } else if err != nil { lastErr = err } checkCtx, checkCancel := context.WithTimeout(context.Background(), 1500*time.Millisecond) exists, inspectErr := d.containerExistsAPI(checkCtx, dockerName) checkCancel() if inspectErr == nil { if !exists { return nil } } else { cliCheckCtx, cliCheckCancel := context.WithTimeout(context.Background(), 1500*time.Millisecond) _, cliInspectText, _, cliInspectErr := d.runCollect(cliCheckCtx, "inspect", dockerName) cliTimedOut := cliCheckCtx.Err() != nil cliCheckCancel() if cliInspectErr != nil && !cliTimedOut { msg := strings.ToLower(cliInspectText) if strings.Contains(msg, "no such object") || strings.Contains(msg, "no such container") || strings.Contains(msg, "not found") { return nil } } if lastErr == nil { if cliTimedOut { lastErr = cliCheckCtx.Err() } else { lastErr = inspectErr } } } if lastErr != nil { return lastErr } return fmt.Errorf("container still exists after force removal") } func (d Docker) pull(ctx context.Context, ref string) { if err := d.pullImageAPI(ctx, ref); err != nil { _, _, _, _ = d.runCollect(ctx, "pull", ref) } } func (d Docker) imageExistsLocally(ctx context.Context, ref string) bool { _, _, exitCode, _ := d.runCollect(ctx, "image", "inspect", ref) return exitCode == 0 } type imageConfig struct { ID string DeclaresRootVolume bool Volumes []string Workdir string User string Env map[string]string Entrypoint []string Cmd []string Labels map[string]string } func (d Docker) inspectImageConfig(ctx context.Context, ref string) imageConfig { if apiCfg, err := d.inspectImageConfigAPI(ctx, ref); err == nil { return apiCfg } cfg := imageConfig{Env: map[string]string{}} // `image inspect`, not bare `inspect`: rewriteDockerCLIArgs rewrites the // last argument of `docker inspect` through dockerContainerName (a // container-name mangler), which corrupts image references containing ":" // or "/" — the subcommand form skips that rewrite and takes the reference // verbatim. This CLI fallback only runs when the engine API is // unreachable, which is exactly when a silently mangled reference would // fail anyway, so the wrong lookup would be invisible. out, _, code, err := d.runCollect(ctx, "image", "inspect", "--format", `{{json .Config.Volumes}}||{{.Config.WorkingDir}}||{{.Config.User}}||{{json .Config.Env}}||{{json .Config.Entrypoint}}||{{json .Config.Cmd}}||{{json .Config.Labels}}`, ref) if err != nil || code != 0 { return cfg } parts := strings.SplitN(strings.TrimSpace(out), "||", 7) if len(parts) < 3 { return cfg } volJson := strings.TrimSpace(parts[0]) if volJson != "" && volJson != "null" && volJson != "{}" { var vols map[string]any if jsonErr := json.Unmarshal([]byte(volJson), &vols); jsonErr == nil { for p := range vols { p = strings.TrimSpace(p) if p != "" && p != "/" { cfg.Volumes = append(cfg.Volumes, p) } } // Map iteration is randomized; sort to match the API path // (inspectImageConfigAPI sorts Volumes too) so the derived // candidate order — and with it the reported winner among // multiple data-bearing volumes — is deterministic. sort.Strings(cfg.Volumes) } } cfg.Workdir = strings.TrimSpace(parts[1]) cfg.User = strings.TrimSpace(parts[2]) if len(parts) >= 4 { envJson := strings.TrimSpace(parts[3]) if envJson != "" && envJson != "null" { var envArr []string if jsonErr := json.Unmarshal([]byte(envJson), &envArr); jsonErr == nil { for _, kv := range envArr { if k, v, ok := strings.Cut(kv, "="); ok { cfg.Env[k] = v } } } } } if len(parts) >= 5 { cfg.Entrypoint = parseImageConfigStringList(parts[4]) } if len(parts) >= 6 { cfg.Cmd = parseImageConfigStringList(parts[5]) } if len(parts) >= 7 { labelJson := strings.TrimSpace(parts[6]) if labelJson != "" && labelJson != "null" && labelJson != "{}" { var labels map[string]string if jsonErr := json.Unmarshal([]byte(labelJson), &labels); jsonErr == nil { for k, v := range labels { k = strings.TrimSpace(k) if k != "" { if cfg.Labels == nil { cfg.Labels = make(map[string]string, len(labels)) } cfg.Labels[k] = v } } } } } return cfg } func parseImageConfigStringList(raw string) []string { trimmed := strings.TrimSpace(raw) if trimmed == "" || trimmed == "null" { return nil } var list []string if err := json.Unmarshal([]byte(trimmed), &list); err != nil { return nil } out := make([]string, 0, len(list)) for _, item := range list { clean := strings.TrimSpace(item) if clean != "" { out = append(out, clean) } } return out } func runtimeArgNeedsQuoting(arg string) bool { if arg == "" { return true } for _, r := range arg { switch r { case ' ', '\t', '\n', '\r', '"', '\\': return true } } return false } func quoteRuntimeArg(arg string) string { if !runtimeArgNeedsQuoting(arg) { return arg } var b strings.Builder b.WriteByte('"') for _, r := range arg { if r == '"' || r == '\\' { b.WriteByte('\\') } b.WriteRune(r) } b.WriteByte('"') return b.String() } func runtimeCommandFromArgs(args []string) string { if len(args) == 0 { return "" } encoded := make([]string, 0, len(args)) for _, arg := range args { clean := strings.TrimSpace(arg) if clean == "" { continue } encoded = append(encoded, quoteRuntimeArg(clean)) } return strings.TrimSpace(strings.Join(encoded, " ")) } func trimRuntimeProcessArgs(args []string) []string { out := make([]string, 0, len(args)) for _, arg := range args { clean := strings.TrimSpace(arg) if clean != "" { out = append(out, clean) } } return out } func isRuntimeShellName(value string) bool { switch strings.ToLower(strings.TrimSpace(value)) { case "sh", "bash", "ash", "dash", "zsh", "ksh": return true default: return false } } func shellEntrypointInfo(entrypoint []string) (bool, int) { if len(entrypoint) < 2 { return false, 0 } execIndex := 0 flagIndex := 1 cmdIndex := 2 execName := strings.ToLower(strings.TrimSpace(filepath.Base(entrypoint[execIndex]))) if execName == "env" && len(entrypoint) >= 3 { execIndex = 1 flagIndex = 2 cmdIndex = 3 execName = strings.ToLower(strings.TrimSpace(filepath.Base(entrypoint[execIndex]))) } if !isRuntimeShellName(execName) || len(entrypoint) <= flagIndex { return false, 0 } flags := strings.TrimSpace(entrypoint[flagIndex]) if !strings.HasPrefix(flags, "-") || !strings.Contains(flags, "c") { return false, 0 } return true, cmdIndex } func runtimeCommandFromImageConfig(cfg imageConfig) string { entrypoint := trimRuntimeProcessArgs(cfg.Entrypoint) cmd := trimRuntimeProcessArgs(cfg.Cmd) if isShell, cmdIndex := shellEntrypointInfo(entrypoint); isShell { if len(cmd) > 0 { // Docker treats Cmd as a single shell command string when Entrypoint is a shell wrapper. return strings.TrimSpace(strings.Join(cmd, " ")) } if len(entrypoint) > cmdIndex { return strings.TrimSpace(strings.Join(entrypoint[cmdIndex:], " ")) } return "" } args := make([]string, 0, len(entrypoint)+len(cmd)) args = append(args, entrypoint...) args = append(args, cmd...) return runtimeCommandFromArgs(args) } func getDataPathsFromEnv(env map[string]string) []string { dataKeys := []string{ "SERVER_DIR", "SERVERDIR", "SRV_DIR", "GAME_DIR", "GAMEDIR", "DATA_DIR", "DATADIR", "INSTALL_DIR", "INSTALLDIR", "STEAMAPPDIR", "HOMEDIR", "HOME_DIR", "APP_DIR", "APPDIR", "WORKDIR", "WORK_DIR", } seen := map[string]bool{} var paths []string for _, key := range dataKeys { if val, ok := env[key]; ok { val = strings.TrimSpace(val) if val != "" && val != "/" && strings.HasPrefix(val, "/") && !seen[val] { paths = append(paths, val) seen[val] = true } } } return paths } func (d Docker) getImageVolumePaths(ctx context.Context, ref string) []string { return d.inspectImageConfig(ctx, ref).Volumes } func (a *Agent) recoverMisplacedFiles(name, serverDir string, original dockerContainerInspectForStats) { release := a.lockMisplacedFileRecovery(name, serverDir, original) if release == nil { return } defer release() fmt.Printf("[file-recovery] %s: server directory is EMPTY after 60s — attempting file recovery\n", name) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() diffOut, _, _, diffErr := a.docker.runCollect(ctx, "diff", original.ID) if diffErr != nil || strings.TrimSpace(diffOut) == "" { fmt.Printf("[file-recovery] %s: docker diff returned no changes\n", name) return } dataRoots := map[string]int{} for _, line := range strings.Split(diffOut, "\n") { line = strings.TrimSpace(line) if line == "" { continue } parts := strings.SplitN(line, " ", 2) if len(parts) != 2 { continue } action := parts[0] filePath := parts[1] if action != "A" { continue } skipPrefixes := []string{"/tmp/", "/var/", "/proc/", "/sys/", "/dev/", "/etc/", "/root/", "/run/", "/opt/", "/usr/", "/home/"} skip := false for _, prefix := range skipPrefixes { if strings.HasPrefix(filePath, prefix) { skip = true break } } if skip { continue } clean := filepath.Clean(filePath) segments := strings.Split(strings.TrimPrefix(clean, "/"), "/") if len(segments) == 0 { continue } root := "/" + segments[0] if len(segments) >= 2 { root = "/" + segments[0] + "/" + segments[1] } dataRoots[root]++ } if len(dataRoots) == 0 { fmt.Printf("[file-recovery] %s: no significant file changes found in container\n", name) return } bestRoot := "" bestCount := 0 for root, count := range dataRoots { if count > bestCount { bestRoot = root bestCount = count } } fmt.Printf("[file-recovery] %s: detected data root '%s' with %d new files — copying to server directory\n", name, bestRoot, bestCount) cpCtx, cpCancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cpCancel() srcPath := original.ID + ":" + bestRoot + "/." _, cpErr, cpCode, cpGoErr := a.docker.runCollect(cpCtx, "cp", srcPath, serverDir+"/") if cpGoErr != nil || cpCode != 0 { srcPath = original.ID + ":" + bestRoot _, cpErr, cpCode, cpGoErr = a.docker.runCollect(cpCtx, "cp", srcPath, serverDir+"/") if cpGoErr != nil || cpCode != 0 { fmt.Printf("[file-recovery] %s: docker cp failed: %s\n", name, cpErr) return } } ensureVolumeWritable(serverDir) correctVolume := fmt.Sprintf("%s:%s", serverDir, bestRoot) _ = a.modifyMeta(serverDir, func(meta map[string]any) { runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj == nil { runtimeObj = make(map[string]any) } runtimeObj["volumes"] = []any{correctVolume} meta["runtime"] = runtimeObj if sc, ok := meta["startupCommand"].(string); ok && sc != "" { fmt.Printf("[file-recovery] %s: startup command exists, runtime volumes updated to %s\n", name, correctVolume) } }) fmt.Printf("[file-recovery] %s: recovered %d files from container path '%s' — volume config updated for future starts\n", name, bestCount, bestRoot) newEntries, _ := os.ReadDir(serverDir) newCount := 0 for _, e := range newEntries { if e.Name() != ".adpanel" && e.Name() != ".adpanel_meta" { newCount++ } } fmt.Printf("[file-recovery] %s: server directory now has %d files\n", name, newCount) } func (d Docker) updateRestartNo(ctx context.Context, name string) { _, _, _, _ = d.runCollect(ctx, "update", "--restart=no", name) } func (d Docker) updateRestartPolicy(ctx context.Context, name, policy string) { clean := strings.ToLower(strings.TrimSpace(policy)) switch clean { case "", "no", "always", "unless-stopped", "on-failure": default: clean = "unless-stopped" } if clean == "" { clean = "no" } _, _, _, _ = d.runCollect(ctx, "update", "--restart="+clean, name) } // adpanel:restore-refusal-recovery — inspectRestartPolicy reads the container's // current restart policy through the same runCollect "inspect -f" pattern // inspectRunning uses. Callers about to MUTATE the policy (the restore handler's // `docker update --restart=no` before its stop) capture it here so a // refused/failed exit can put the original policy back. Best-effort by // design: any inspect failure returns "" (unknown) and the caller proceeds // with today's behavior instead of blocking the operation. func (d Docker) inspectRestartPolicy(ctx context.Context, name string) string { out, _, _, err := d.runCollect(ctx, "inspect", "-f", "{{.HostConfig.RestartPolicy.Name}}", name) if err != nil { return "" } return strings.TrimSpace(out) } func (d Docker) getImageDigest(ctx context.Context, imageRef string) string { out, _, code, err := d.runCollect(ctx, "inspect", "--format", "{{.Id}}", imageRef) if err != nil || code != 0 { return "" } return strings.TrimSpace(out) } func (a *Agent) syncNewFilesToServer(ctx context.Context, imageRef, serverDir string, containerPaths []string) error { tmpDir, err := os.MkdirTemp("", "adpanel-sync-*") if err != nil { return fmt.Errorf("failed to create temp dir: %w", err) } defer os.RemoveAll(tmpDir) // One win rule for both loops, mirroring the create-time server-dir // preparation: a cp that exits 0 proves nothing, and a FAILED cp can // leave partial files behind (docker cp extracts incrementally; // extractImageFiles never cleans destDir), so the check is a per-attempt // delta over tmpDir, not an absolute non-empty check. Same per-attempt // budget as the other image-extract flows so one hung attempt cannot eat // the caller's whole context. trySyncExtract := func(containerPath string) bool { before := 0 if entries, err := os.ReadDir(tmpDir); err == nil { before = len(entries) } extractCtx, cancel := context.WithTimeout(ctx, imageExtractAttemptBudget) err := a.docker.extractImageFiles(extractCtx, imageRef, tmpDir, containerPath) cancel() if err != nil { return false } entries, err := os.ReadDir(tmpDir) return err == nil && len(entries) > before } extracted := false for _, containerPath := range containerPaths { if trySyncExtract(containerPath) { extracted = true break } } if !extracted { // The caller's paths were all tried and failed above, so derive the // fallback candidates from the image's own config — the same shared // derivation as every other image-extract flow. for _, cand := range imageExtractCandidates(nil, a.docker.inspectImageConfig(ctx, imageRef)) { if trySyncExtract(cand.Path) { extracted = true break } } } if !extracted { return fmt.Errorf("could not extract files from image") } // adpanel:fs-toctou - parent directories for synced files are created // through the pinned server dirfd (see ensureDirUnderRoot) so a planted // intermediate symlink cannot redirect ensureDir outside the server scope // when the target does not exist yet. serverRoot, rootErr := safeOpenRoot(serverDir) if rootErr != nil { return rootErr } defer serverRoot.Close() newFiles := 0 err = filepath.Walk(tmpDir, func(path string, info os.FileInfo, walkErr error) error { if walkErr != nil || info.IsDir() { return walkErr } if info.Mode()&os.ModeSymlink != 0 { return nil } if !info.Mode().IsRegular() { return nil } rel, err := filepath.Rel(tmpDir, path) if err != nil { return nil } destPath := filepath.Join(serverDir, rel) destParent := filepath.Dir(destPath) if rp, rpErr := filepath.EvalSymlinks(destParent); rpErr == nil && !isUnder(serverDir, rp) { return nil } if di, diErr := os.Lstat(destPath); diErr == nil && di.Mode()&os.ModeSymlink != 0 { return nil } if _, err := os.Stat(destPath); os.IsNotExist(err) { destParentRel, relErr := filepath.Rel(serverRoot.path, filepath.Dir(destPath)) if relErr != nil { return nil } if err := ensureDirUnderRoot(serverRoot, destParentRel, 0o755); err != nil { return nil } data, err := os.ReadFile(path) if err != nil { return nil } if err := writeFileNoFollow(destPath, data, info.Mode()); err == nil { newFiles++ if a.debug { fmt.Printf("[sync] added new file: %s\n", rel) } } } return nil }) if newFiles > 0 { fmt.Printf("[sync] added %d new files from image update\n", newFiles) } return err } func serverDirVisibleFileCount(serverDir string) int { entries, err := os.ReadDir(serverDir) if err != nil { return 0 } count := 0 for _, entry := range entries { name := entry.Name() if name == ".adpanel" || name == ".adpanel_meta" || name == "adpanel.json" || strings.HasPrefix(name, ".adpanel_") { continue } count++ } return count } func appendUniqueContainerPath(paths []string, seen map[string]struct{}, raw string) []string { clean := path.Clean(strings.TrimSpace(raw)) if clean == "" || clean == "." || clean == "/" || !strings.HasPrefix(clean, "/") { return paths } if _, ok := seen[clean]; ok { return paths } seen[clean] = struct{}{} return append(paths, clean) } func commandReferencedContainerPaths(command, workdir, dataDir string) []string { args := parseShellArgs(command) if len(args) == 0 { return nil } paths := []string{} seen := map[string]struct{}{} for _, arg := range args[1:] { token := strings.TrimSpace(arg) if token == "" || strings.HasPrefix(token, "-") { continue } lower := strings.ToLower(token) if strings.HasPrefix(token, "/") { paths = appendUniqueContainerPath(paths, seen, path.Dir(token)) continue } if strings.Contains(token, "/") || strings.HasSuffix(lower, ".sh") || strings.HasSuffix(lower, ".py") || strings.HasSuffix(lower, ".js") { base := strings.TrimSpace(workdir) if base == "" { base = dataDir } if base != "" { paths = appendUniqueContainerPath(paths, seen, path.Dir(path.Join(base, token))) } } } return paths } // --- Image extract candidates --- // // One shared derivation for every "copy data out of a docker image" flow // (create-time server-dir preparation, image update sync), so the call sites // cannot drift apart again: they previously carried separate copies of the // same hardcoded path list. // Where a candidate came from — which derivation tier produced the path // (request manifest, image label, image config, or the curated fallback). const ( extractSourceRequest = "request" // caller-supplied manifest (req.Paths) extractSourceLabel = "label" // image author declared it on the image extractSourceVolume = "image-volume" extractSourceEnv = "image-env" extractSourceWorkdir = "image-workdir" extractSourceCommand = "image-command" extractSourceFallback = "fallback" // curated common-path list, last resort ) // imageExtractLabel is the label an image author can set to declare which // container directories hold the server data, without needing a panel-side // manifest: // // LABEL adpanel.extract="/home/steam/serverdata /opt/fivem" // // Value grammar: absolute container paths separated by commas, semicolons, // or whitespace. const imageExtractLabel = "adpanel.extract" // curatedImageExtractFallbackPaths is the historic common-path list, kept as // the LAST resort for images that declare nothing at all (no label, no // volume, no data-path env, no usable workdir, no command references). It is // the union of the lists the three former per-call-site copies carried; each // entry only wins if extracting it actually lands files (see // imageExtractCandidates), so an early empty hit no longer masks a later // real one. var curatedImageExtractFallbackPaths = []string{ "/ragemp", "/fivem", "/config", "/server", "/gameserver", "/rust", "/ark", "/minecraft", "/csgo", "/valheim", "/app", "/data", "/opt", "/home", "/usr/src/app", "/usr/app", "/var/www", "/srv", } type imageExtractCandidate struct { Path string Source string } // appendExtractCandidate normalizes raw into an absolute container path and // appends it when unseen — the same normalization contract as // appendUniqueContainerPath (clean, absolute, not root), kept as a parallel // helper because candidates carry their provenance source. func appendExtractCandidate(candidates []imageExtractCandidate, seen map[string]struct{}, raw, source string) []imageExtractCandidate { clean := path.Clean(strings.TrimSpace(raw)) if clean == "" || clean == "." || clean == "/" || !strings.HasPrefix(clean, "/") { return candidates } if _, ok := seen[clean]; ok { return candidates } seen[clean] = struct{}{} return append(candidates, imageExtractCandidate{Path: clean, Source: source}) } // labelExtractPaths splits an imageExtractLabel value on commas, // semicolons, and whitespace. func labelExtractPaths(label string) []string { return strings.FieldsFunc(label, func(r rune) bool { switch r { case ',', ';', ' ', '\t', '\n', '\r': return true } return false }) } // imageCommandSystemDirs are container directories that are never game data. // Absolute prefixes, matched on whole path segments. Applied ONLY to paths // derived from the image's Entrypoint/Cmd (where argv leftovers like // /usr/bin/supervisord or /etc/app/supervisord.conf are common false // positives); author-declared sources (manifest, label, volume, env, // workdir) are taken at face value. var imageCommandSystemDirs = []string{ "/bin", "/sbin", "/usr/bin", "/usr/sbin", "/usr/lib", "/usr/libexec", "/usr/local/bin", "/usr/local/sbin", "/usr/local/lib", "/usr/share", "/etc", "/boot", "/proc", "/sys", "/dev", "/run", "/tmp", "/var/lib", "/var/log", "/var/cache", } // looksLikeImageSystemPath reports whether p is or lives under one of // imageCommandSystemDirs. func looksLikeImageSystemPath(p string) bool { for _, dir := range imageCommandSystemDirs { if p == dir || strings.HasPrefix(p, dir+"/") { return true } } return false } // imageExtractAttemptBudget caps ONE docker create+cp attempt in every // image-extract flow. The overall request/update context still bounds the // whole loop, but a single hung or multi-GB attempt must not eat the shared // budget and starve the remaining candidates. const imageExtractAttemptBudget = 90 * time.Second // imageExtractCandidates builds the ordered, de-duplicated candidate list of // container paths to try when pulling server data out of an image. Most // specific source first: // // 1. request manifest — explicit caller paths (the panel or template knows // the layout and outranks everything the image says about itself); // 2. image label — imageExtractLabel, declared by the image author; // 3. image config — Volumes (author-declared data mounts), then data-path // env vars (getDataPathsFromEnv), then WorkingDir, then absolute dirs // referenced by the image's own Entrypoint/Cmd (system dirs filtered); // 4. curated fallback — curatedImageExtractFallbackPaths. // // The list is a SEARCH ORDER, not a verdict: callers verify that an attempt // actually landed files before accepting it, so a higher-priority miss never // masks a lower-priority hit. func imageExtractCandidates(explicit []string, imgCfg imageConfig) []imageExtractCandidate { seen := map[string]struct{}{} var candidates []imageExtractCandidate for _, p := range explicit { candidates = appendExtractCandidate(candidates, seen, p, extractSourceRequest) } for _, p := range labelExtractPaths(imgCfg.Labels[imageExtractLabel]) { candidates = appendExtractCandidate(candidates, seen, p, extractSourceLabel) } for _, p := range imgCfg.Volumes { candidates = appendExtractCandidate(candidates, seen, p, extractSourceVolume) } for _, p := range getDataPathsFromEnv(imgCfg.Env) { candidates = appendExtractCandidate(candidates, seen, p, extractSourceEnv) } candidates = appendExtractCandidate(candidates, seen, imgCfg.Workdir, extractSourceWorkdir) for _, p := range commandReferencedContainerPaths(runtimeCommandFromImageConfig(imgCfg), imgCfg.Workdir, "") { if looksLikeImageSystemPath(p) { continue } candidates = appendExtractCandidate(candidates, seen, p, extractSourceCommand) } for _, p := range curatedImageExtractFallbackPaths { candidates = appendExtractCandidate(candidates, seen, p, extractSourceFallback) } return candidates } func (d Docker) stop(ctx context.Context, name string) error { _, _, _, err := d.runCollect(ctx, "stop", "-t", "15", name) return err } // adpanel:live-wipe-guard - only an explicit stopped state or the absence of // the requested container permits destructive filesystem work. func (d Docker) inspectRunning(ctx context.Context, name string) (bool, error) { out, errText, _, err := d.runCollect(ctx, "inspect", "-f", "{{.State.Running}}", "--type=container", name) if ctx.Err() != nil { return false, ctx.Err() } if err == nil { switch strings.TrimSpace(out) { case "true": return true, nil case "false": return false, nil default: return false, errors.New("docker returned an invalid running state") } } message := strings.ToLower(strings.TrimSpace(errText)) message = strings.TrimPrefix(message, "error response from daemon: ") message = strings.TrimPrefix(message, "error: ") containerName := strings.ToLower(dockerContainerName(name)) if message == "no such container: "+containerName || message == "no such object: "+containerName { return false, nil } return false, err } func (d Docker) clearContainerLogs(ctx context.Context, name string) error { dockerName := d.resolveDockerContainerName(ctx, name) if dockerName == "" { return fmt.Errorf("missing container name") } out, errText, _, err := d.runCollect(ctx, "inspect", "-f", "{{.LogPath}}", dockerName) if err != nil { lower := strings.ToLower(errText) if strings.Contains(lower, "no such object") || strings.Contains(lower, "no such container") || strings.Contains(lower, "not found") { return nil } if strings.TrimSpace(errText) != "" { return errors.New(strings.TrimSpace(errText)) } return err } logPath := strings.TrimSpace(out) if logPath == "" || logPath == "" { return nil } cleanPath := filepath.Clean(logPath) if !filepath.IsAbs(cleanPath) || cleanPath == string(filepath.Separator) { return fmt.Errorf("unsafe docker log path") } info, statErr := os.Lstat(cleanPath) if statErr != nil { if os.IsNotExist(statErr) { return nil } return statErr } if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() { return fmt.Errorf("refusing to truncate non-regular docker log path") } return os.Truncate(cleanPath, 0) } const ( stdinMaxContainers = 100 stdinIdleTimeout = 10 * time.Minute stdinWriteTimeout = 5 * time.Second stdinCommandMaxLen = 4096 stdinBufferSize = 256 consoleCommandDuplicateWindow = 1200 * time.Millisecond consoleCommandRequestIDWindow = 30 * time.Second consoleCommandRequestIDMaxLen = 128 consoleCommandRecentMaxServers = 1000 ) type recentConsoleCommand struct { command string requestID string at time.Time } type stdinConn struct { name string stdin io.WriteCloser cmd *exec.Cmd lastUsed time.Time tty bool transport string mu sync.Mutex closed bool } type stdinManager struct { mu sync.RWMutex conns map[string]*stdinConn docker *Docker debug bool stopCh chan struct{} stopOnce sync.Once } func preferDockerCLIConsoleTransport() bool { override := strings.ToLower(strings.TrimSpace(os.Getenv("ADPANEL_DOCKER_STREAM_TRANSPORT"))) switch override { case "cli", "docker-cli", "docker": return true case "api", "docker-api", "hijack": return false } return false } func isEnterpriseLinuxOSRelease(raw string) bool { osInfo := strings.ToLower(raw) for _, line := range strings.Split(osInfo, "\n") { key, val, ok := strings.Cut(line, "=") if !ok { continue } key = strings.ToLower(strings.TrimSpace(key)) val = strings.Trim(strings.TrimSpace(val), `"'`) if key != "id" && key != "id_like" { continue } for _, distro := range []string{"rocky", "rhel", "centos", "almalinux", "ol", "fedora"} { if val == distro || strings.Contains(val, distro) { return true } } } return false } func preferDockerCLIPTYStdinTransport() bool { override := strings.ToLower(strings.TrimSpace(os.Getenv("ADPANEL_DOCKER_STDIN_TRANSPORT"))) switch override { case "pty", "cli-pty", "docker-pty", "script": return true case "api", "docker-api", "hijack": return false } return true } func containerTTYForHost() bool { return true } func newStdinManager(docker *Docker, debug bool) *stdinManager { sm := &stdinManager{ conns: make(map[string]*stdinConn), docker: docker, debug: debug, stopCh: make(chan struct{}), } go sm.cleanupLoop() return sm } func (sm *stdinManager) cleanupLoop() { ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() for { select { case <-sm.stopCh: return case <-ticker.C: sm.cleanupIdle() } } } // extractTarSafeRouted extracts a routed tar stream: server files into // serverDir, ".adpanel_backups/" into backupsDir, ".adpanel_meta/" into // metaDir (when given). budget is optional (nil = unlimited, old call shape // preserved for unbudgeted callers) and mirrors copyDir's transfer-budget // contract (adpanel:backup-copy-budget): when armed it is consulted // SYNCHRONOUSLY in the walk loop — goroutine-free — after each extracted // regular file with the running byte total, and its error aborts the extract // mid-walk (the errImportExtractBudgetExceeded sentinel). The global // archive-bomb cap below (maxExtractSize, via limitedWriter) is unchanged and // independent: the budget only bounds the quota axis the caller validated. func extractTarSafeRouted(tr *tar.Reader, serverDir string, backupsDir string, budget func(extractedSoFar int64) error, metaDir ...string) error { var budgetFn func(extractedSoFar int64) error if budget != nil { budgetFn = budget } var totalSize int64 var fileCount int const backupsPrefix = transferBackupsDir + "/" const metaPrefix = transferMetadataDir + "/" // adpanel:fs-toctou - archive directory creation runs against dirfds // pinned per dest root (see ensureDirUnderRoot); a planted intermediate // symlink cannot redirect MkdirAll outside the server scope when the // target does not exist yet. pinnedRoots := make(map[string]*safeRoot) pinDestRoot := func(dir string) (*safeRoot, error) { if sr, ok := pinnedRoots[dir]; ok { return sr, nil } if err := ensureDir(dir); err != nil { return nil, err } sr, err := safeOpenRoot(dir) if err != nil { return nil, err } pinnedRoots[dir] = sr return sr, nil } defer func() { for _, sr := range pinnedRoots { _ = sr.Close() } }() for { h, err := tr.Next() if err == io.EOF { return nil } if err != nil { return err } fileCount++ if fileCount > maxExtractFiles { return fmt.Errorf("too many files in tar: %d (max %d)", fileCount, maxExtractFiles) } if h.Size > maxSingleFile { return fmt.Errorf("file too large in tar: %s (%d bytes, max %d)", h.Name, h.Size, maxSingleFile) } cleaned := filepath.Clean(h.Name) cleaned = strings.TrimPrefix(cleaned, "/") if cleaned == "." || cleaned == "" { continue } destRoot := serverDir rel := cleaned if cleaned == transferBackupsDir { continue } if cleaned == transferMetadataDir { continue } if strings.HasPrefix(cleaned, metaPrefix) { if len(metaDir) > 0 && metaDir[0] != "" { destRoot = metaDir[0] rel = strings.TrimPrefix(cleaned, metaPrefix) if rel == "" || rel == "." { continue } } else { continue } } else if strings.HasPrefix(cleaned, backupsPrefix) { destRoot = backupsDir rel = strings.TrimPrefix(cleaned, backupsPrefix) if rel == "" || rel == "." { continue } } target := filepath.Join(destRoot, rel) if !isUnder(destRoot, target) { return fmt.Errorf("tar-slip blocked: %s", h.Name) } baseName := filepath.Base(rel) if baseName == "." || baseName == ".." { continue } switch h.Typeflag { case tar.TypeDir: // adpanel:fs-toctou - created through the pinned dest-root dirfd // (mkdirat on verified parents) so a planted intermediate symlink // can no longer make MkdirAll materialize a directory inside a // sibling directory when the target does not exist yet. sr, pinErr := pinDestRoot(destRoot) if pinErr != nil { return pinErr } targetRel, relErr := filepath.Rel(sr.path, target) if relErr != nil { return relErr } if err := ensureDirUnderRoot(sr, targetRel, 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { return fmt.Errorf("symlink escape blocked during tar extract: %s", h.Name) } return err } case tar.TypeReg, tar.TypeRegA: sr, pinErr := pinDestRoot(destRoot) if pinErr != nil { return pinErr } targetRel, relErr := filepath.Rel(sr.path, target) if relErr != nil { return relErr } if err := ensureDirUnderRoot(sr, filepath.Dir(targetRel), 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { return fmt.Errorf("symlink escape blocked during tar extract: %s", h.Name) } return err } if ei, eiErr := os.Lstat(target); eiErr == nil && ei.Mode()&os.ModeSymlink != 0 { continue } // adpanel:fs-toctou - the target open rides with O_NONBLOCK and an // fstat regular-file gate (see safeOpenWriteAt) so a FIFO planted // at the target cannot wedge the writer inside open(2). out, err := safeOpenWriteAt(sr, targetRel, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|openNoFollow, 0o644) if err != nil { return err } lw := &limitedWriter{w: out, limit: maxExtractSize - totalSize} n, err := io.Copy(lw, tr) out.Close() if err != nil { return err } totalSize += n // adpanel:import-extract-budget — consult the budget synchronously // in the walk loop (per extracted file, one cheap compare against // the caller's captured cap — the same placement as copyDir's // budgetFn): a breach aborts the walk with the sentinel before // more bytes are committed. Granularity is per file (a single // entry can overshoot by its own size — the same accepted skew as // the copy budget). Meta-quarantine entries count too: they can // only over-count the quota axis, never under-count it. if budgetFn != nil { if berr := budgetFn(totalSize); berr != nil { return berr } } case tar.TypeLink: return fmt.Errorf("hardlinks not allowed for security: %s", h.Name) case tar.TypeSymlink: continue default: continue } } } func (sm *stdinManager) cleanupIdle() { sm.mu.Lock() defer sm.mu.Unlock() now := time.Now() for name, conn := range sm.conns { conn.mu.Lock() idle := now.Sub(conn.lastUsed) > stdinIdleTimeout conn.mu.Unlock() if idle { if sm.debug { fmt.Printf("[stdin-manager] closing idle connection for %s\n", name) } conn.close() delete(sm.conns, name) } } } func (sm *stdinManager) stop() { sm.stopOnce.Do(func() { close(sm.stopCh) sm.mu.Lock() defer sm.mu.Unlock() for name, conn := range sm.conns { conn.close() delete(sm.conns, name) } }) } func (sm *stdinManager) getOrCreate(ctx context.Context, containerName string) (*stdinConn, error) { name := dockerContainerName(containerName) if name == "" { return nil, fmt.Errorf("empty container name") } if !sm.docker.containerExists(ctx, name) { return nil, fmt.Errorf("container-not-running") } sm.mu.Lock() defer sm.mu.Unlock() if conn, ok := sm.conns[name]; ok { conn.mu.Lock() if !conn.closed { conn.lastUsed = time.Now() conn.mu.Unlock() return conn, nil } conn.mu.Unlock() delete(sm.conns, name) } if len(sm.conns) >= stdinMaxContainers { var oldestName string var oldestTime time.Time for n, c := range sm.conns { c.mu.Lock() if oldestName == "" || c.lastUsed.Before(oldestTime) { oldestName = n oldestTime = c.lastUsed } c.mu.Unlock() } if oldestName != "" { if sm.debug { fmt.Printf("[stdin-manager] evicting oldest connection %s\n", oldestName) } sm.conns[oldestName].close() delete(sm.conns, oldestName) } } conn, err := sm.createStdinConn(ctx, name) if err != nil { return nil, err } sm.conns[name] = conn return conn, nil } func (sm *stdinManager) createStdinConn(ctx context.Context, name string) (*stdinConn, error) { tty := sm.docker.containerTTY(ctx, name) preferCLI := preferDockerCLIConsoleTransport() && !tty preferCLIPTY := tty && preferDockerCLIPTYStdinTransport() if preferCLIPTY { conn, err := sm.createDockerCLIPTYStdinConn(ctx, name) if err == nil { return conn, nil } if sm.debug { fmt.Printf("[stdin-manager] Docker CLI PTY stdin attach failed for %s: %v\n", name, err) } } if preferCLI { conn, err := sm.createDockerCLIStdinConn(ctx, name) if err == nil { return conn, nil } if sm.debug { fmt.Printf("[stdin-manager] Docker CLI stdin attach failed for %s: %v\n", name, err) } } attachCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() stdin, err := sm.docker.attachContainerAPI(attachCtx, name, dockerAttachOptions{Stdin: true}) if err != nil { if tty && !preferCLIPTY { conn, ptyErr := sm.createDockerCLIPTYStdinConn(ctx, name) if ptyErr == nil { return conn, nil } return nil, fmt.Errorf("failed to attach container stdin: Docker API: %v; Docker CLI PTY: %w", err, ptyErr) } if !preferCLI && !tty { conn, cliErr := sm.createDockerCLIStdinConn(ctx, name) if cliErr == nil { return conn, nil } return nil, fmt.Errorf("failed to attach container stdin: Docker API: %v; Docker CLI: %w", err, cliErr) } return nil, fmt.Errorf("failed to attach container stdin: %w", err) } conn := &stdinConn{ name: name, stdin: stdin, lastUsed: time.Now(), tty: tty, transport: "docker-api", } if sm.debug { fmt.Printf("[stdin-manager] created Docker API stdin connection for %s (tty=%t)\n", name, conn.tty) } return conn, nil } func (sm *stdinManager) createDockerCLIPTYStdinConn(ctx context.Context, name string) (*stdinConn, error) { if err := ctx.Err(); err != nil { return nil, err } if strings.TrimSpace(name) == "" { return nil, fmt.Errorf("empty container name") } cmd := exec.Command("docker", "attach", "--sig-proxy=false", "--detach-keys=ctrl-@", name) ptmx, err := pty.StartWithSize(cmd, &pty.Winsize{Rows: 30, Cols: 120}) if err != nil { return nil, err } conn := &stdinConn{ name: name, stdin: ptmx, cmd: cmd, lastUsed: time.Now(), tty: true, transport: "docker-cli-pty", } go func() { _, _ = io.Copy(io.Discard, ptmx) }() go func() { _ = cmd.Wait() conn.mu.Lock() conn.closed = true conn.mu.Unlock() }() if sm.debug { fmt.Printf("[stdin-manager] created Docker CLI PTY stdin connection for %s\n", name) } return conn, nil } func (sm *stdinManager) createDockerCLIStdinConn(ctx context.Context, name string) (*stdinConn, error) { if err := ctx.Err(); err != nil { return nil, err } if strings.TrimSpace(name) == "" { return nil, fmt.Errorf("empty container name") } cmd := exec.Command("docker", "attach", "--sig-proxy=false", name) stdin, err := cmd.StdinPipe() if err != nil { return nil, err } cmd.Stdout = io.Discard cmd.Stderr = io.Discard if err := cmd.Start(); err != nil { _ = stdin.Close() return nil, err } conn := &stdinConn{ name: name, stdin: stdin, cmd: cmd, lastUsed: time.Now(), tty: sm.docker.containerTTY(ctx, name), transport: "docker-cli", } go func() { _ = cmd.Wait() conn.mu.Lock() conn.closed = true conn.mu.Unlock() }() if sm.debug { fmt.Printf("[stdin-manager] created Docker CLI stdin connection for %s (tty=%t)\n", name, conn.tty) } return conn, nil } func (c *stdinConn) close() { c.mu.Lock() defer c.mu.Unlock() if c.closed { return } c.closed = true if c.stdin != nil { c.stdin.Close() } if c.cmd != nil && c.cmd.Process != nil { _ = c.cmd.Process.Kill() } } func (c *stdinConn) sendCommand(cmd string) error { c.mu.Lock() defer c.mu.Unlock() if c.closed { return fmt.Errorf("connection closed") } c.lastUsed = time.Now() line := strings.TrimRight(cmd, "\r\n") + "\n" if deadlineWriter, ok := c.stdin.(interface{ SetWriteDeadline(time.Time) error }); ok { _ = deadlineWriter.SetWriteDeadline(time.Now().Add(stdinWriteTimeout)) defer deadlineWriter.SetWriteDeadline(time.Time{}) } if _, err := io.WriteString(c.stdin, line); err != nil { c.closed = true if c.stdin != nil { _ = c.stdin.Close() } if c.cmd != nil && c.cmd.Process != nil { _ = c.cmd.Process.Kill() } return fmt.Errorf("stdin write failed: %w", err) } return nil } func (sm *stdinManager) remove(name string) { name = dockerContainerName(name) sm.mu.Lock() defer sm.mu.Unlock() if conn, ok := sm.conns[name]; ok { conn.close() delete(sm.conns, name) } } func exitCodeFromErr(err error) int { if err == nil { return 0 } var ee *exec.ExitError if errors.As(err, &ee) { return ee.ExitCode() } return -1 } func (d Docker) writeToContainerProcessStdin(ctx context.Context, containerName, command string) error { name := dockerContainerName(containerName) cmd := strings.TrimSpace(command) if name == "" || cmd == "" { return fmt.Errorf("missing-params") } shells := []string{"sh", "/bin/sh", "bash", "/bin/bash"} for idx, shellPath := range shells { script := "fd=$(readlink /proc/1/fd/0 2>/dev/null || true); case \"$fd\" in /dev/null*) exit 45 ;; esac; cat > /proc/1/fd/0" pipeCmd := exec.CommandContext(ctx, "docker", "exec", "-i", name, shellPath, "-lc", script) pipeCmd.Stdin = strings.NewReader(cmd + "\n") pipeCmd.Stdout = io.Discard var stderr bytes.Buffer pipeCmd.Stderr = &stderr if err := pipeCmd.Run(); err == nil { return nil } else { exitCode := exitCodeFromErr(err) if exitCode == 45 { return fmt.Errorf("process stdin is not open; restart the server so the container is recreated with interactive stdin") } if isMissingExecShell(stderr.String(), shellPath, exitCode) && idx < len(shells)-1 { continue } detail := strings.TrimSpace(stderr.String()) if detail == "" { detail = err.Error() } return fmt.Errorf("process stdin write failed: %s", detail) } } return fmt.Errorf("process stdin write failed: no supported shell found in container") } func (d Docker) containerTTY(ctx context.Context, containerName string) bool { name := dockerContainerName(containerName) if name == "" { return false } inspectCtx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() out, _, _, err := d.runCollect(inspectCtx, "inspect", "-f", "{{.Config.Tty}}", name) return err == nil && strings.EqualFold(strings.TrimSpace(out), "true") } func (d Docker) containerOpenStdin(ctx context.Context, containerName string) bool { name := dockerContainerName(containerName) if name == "" { return false } inspectCtx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() out, _, _, err := d.runCollect(inspectCtx, "inspect", "-f", "{{.Config.OpenStdin}} {{.Config.AttachStdin}}", name) if err != nil { return false } fields := strings.Fields(strings.ToLower(strings.TrimSpace(out))) return len(fields) >= 1 && fields[0] == "true" } func (d Docker) writeToMinecraftProcessStdin(ctx context.Context, containerName, command string) error { name := dockerContainerName(containerName) cmd := strings.TrimSpace(command) if name == "" || cmd == "" { return fmt.Errorf("missing-params") } script := "pid=$(pgrep -n java || pgrep -n bedrock_server || echo 1); fd=$(readlink \"/proc/$pid/fd/0\" 2>/dev/null || true); case \"$fd\" in /dev/null*) exit 45 ;; esac; cat > \"/proc/$pid/fd/0\"" shells := []string{"sh", "/bin/sh", "bash", "/bin/bash"} for idx, shellPath := range shells { pipeCmd := exec.CommandContext(ctx, "docker", "exec", "-i", name, shellPath, "-lc", script) pipeCmd.Stdin = strings.NewReader(cmd + "\n") pipeCmd.Stdout = io.Discard var stderr bytes.Buffer pipeCmd.Stderr = &stderr if err := pipeCmd.Run(); err == nil { return nil } else { exitCode := exitCodeFromErr(err) if exitCode == 45 { return fmt.Errorf("minecraft stdin is not open; restart the server so the container is recreated with interactive stdin") } if isMissingExecShell(stderr.String(), shellPath, exitCode) && idx < len(shells)-1 { continue } detail := strings.TrimSpace(stderr.String()) if detail == "" { detail = err.Error() } return fmt.Errorf("minecraft stdin write failed: %s", detail) } } return fmt.Errorf("minecraft stdin write failed: no supported shell found in container") } func (d Docker) writeToTargetProcessStdin(ctx context.Context, containerName, command string, targets []string) error { name := dockerContainerName(containerName) cmd := strings.TrimSpace(command) targets = sanitizeConsoleProcessTargets(targets) if name == "" || cmd == "" { return fmt.Errorf("missing-params") } if len(targets) == 0 { return fmt.Errorf("no console target processes configured") } script := strings.Join([]string{ "pid=''", "self=$$", "for pattern in \"$@\"; do", " [ -n \"$pattern\" ] || continue", " pid=$(pgrep -n -x -- \"$pattern\" 2>/dev/null || true)", " if [ -z \"$pid\" ]; then", " for candidate in $(pgrep -f -- \"$pattern\" 2>/dev/null || true); do", " [ \"$candidate\" = \"$self\" ] && continue", " cmdline=$(tr '\\000' ' ' < \"/proc/$candidate/cmdline\" 2>/dev/null || true)", " case \"$cmdline\" in *adpanel-console*) continue ;; esac", " pid=$candidate", " done", " fi", " [ -n \"$pid\" ] && break", "done", "[ -n \"$pid\" ] || exit 44", "fd=$(readlink \"/proc/$pid/fd/0\" 2>/dev/null || true)", "case \"$fd\" in /dev/null*) exit 45 ;; esac", "cat > \"/proc/$pid/fd/0\"", }, "\n") shells := []string{"sh", "/bin/sh", "bash", "/bin/bash"} for idx, shellPath := range shells { args := []string{"exec", "-i", name, shellPath, "-c", script, "adpanel-console"} args = append(args, targets...) pipeCmd := exec.CommandContext(ctx, "docker", args...) pipeCmd.Stdin = strings.NewReader(cmd + "\n") pipeCmd.Stdout = io.Discard var stderr bytes.Buffer pipeCmd.Stderr = &stderr if err := pipeCmd.Run(); err == nil { if d.debug { fmt.Printf("[docker] command sent to target process stdin: %s\n", strings.Join(targets, ",")) } return nil } else { exitCode := exitCodeFromErr(err) if exitCode == 44 { return fmt.Errorf("target process not found: %s", strings.Join(targets, ", ")) } if exitCode == 45 { return fmt.Errorf("target process stdin is not open; restart the server so the container is recreated with interactive stdin") } if isMissingExecShell(stderr.String(), shellPath, exitCode) && idx < len(shells)-1 { continue } detail := strings.TrimSpace(stderr.String()) if detail == "" { detail = err.Error() } return fmt.Errorf("target process stdin write failed: %s", detail) } } return fmt.Errorf("target process stdin write failed: no supported shell found in container") } func (d Docker) sendViaAttachedStdin(ctx context.Context, stdinMgr *stdinManager, containerName, command string) error { name := dockerContainerName(containerName) cmd := strings.TrimSpace(command) if name == "" || cmd == "" { return fmt.Errorf("missing-params") } if stdinMgr == nil { return fmt.Errorf("stdin manager unavailable") } var lastErr error for attempt := 0; attempt < 2; attempt++ { if err := ctx.Err(); err != nil { return err } conn, err := stdinMgr.getOrCreate(ctx, name) if err == nil { if err := conn.sendCommand(cmd); err == nil { if d.debug { fmt.Printf("[docker] command sent via attached container stdin\n") } return nil } else { lastErr = err stdinMgr.remove(name) continue } } lastErr = err stdinMgr.remove(name) } if lastErr == nil { lastErr = fmt.Errorf("stdin channel unavailable") } return lastErr } func (d Docker) sendCommand(ctx context.Context, stdinMgr *stdinManager, containerName, command string, targetProcesses []string) error { name := d.resolveDockerContainerName(ctx, containerName) cmd := strings.TrimSpace(command) if name == "" || cmd == "" { return fmt.Errorf("missing-params") } if len(cmd) > stdinCommandMaxLen { return fmt.Errorf("command too long (max %d)", stdinCommandMaxLen) } if err := validateCommandInput(cmd); err != nil { return err } if state := d.containerState(ctx, name); state != "running" { return fmt.Errorf("container-not-running") } openStdin := d.containerOpenStdin(ctx, name) if !openStdin { if stdinMgr != nil { stdinMgr.remove(name) } return fmt.Errorf("container stdin is not open; restart the server so the container is recreated with interactive stdin") } tty := d.containerTTY(ctx, name) var targetErr error var attachedErr error if stdinMgr != nil { if err := d.sendViaAttachedStdin(ctx, stdinMgr, name, cmd); err == nil { return nil } else { attachedErr = err if d.debug { fmt.Printf("[docker] attached stdin failed for %s: %v\n", name, err) } } } if tty { if attachedErr != nil { return fmt.Errorf("failed-to-send: attached TTY stdin failed: %w", attachedErr) } return fmt.Errorf("failed-to-send: TTY stdin channel unavailable") } if len(targetProcesses) > 0 { if err := d.writeToTargetProcessStdin(ctx, name, cmd, targetProcesses); err == nil { return nil } else { targetErr = err if d.debug { fmt.Printf("[docker] target process stdin failed for %s: %v\n", name, err) } } } if err := d.writeToContainerProcessStdin(ctx, name, cmd); err == nil { if d.debug { fmt.Printf("[docker] command sent via /proc/1/fd/0\n") } return nil } else if err != nil { if attachedErr != nil { if targetErr != nil { return fmt.Errorf("failed-to-send: target process stdin failed: %v; attached stdin failed: %v; process stdin fallback failed: %w", targetErr, attachedErr, err) } return fmt.Errorf("failed-to-send: attached stdin failed: %v; process stdin fallback failed: %w", attachedErr, err) } if targetErr != nil { return fmt.Errorf("failed-to-send: target process stdin failed: %v; process stdin fallback failed: %w", targetErr, err) } return fmt.Errorf("failed-to-send: %w", err) } return fmt.Errorf("failed-to-send: stdin channel unavailable") } func validateCommandInput(cmd string) error { if strings.ContainsRune(cmd, '\x00') { return fmt.Errorf("invalid command: contains null byte") } for _, r := range cmd { if r < 32 && r != '\t' && r != '\n' && r != '\r' { return fmt.Errorf("invalid command: contains control character") } } return nil } // errDownloadQuotaExceeded is returned by a Downloader's quotaCheck hook (see // quotaGuardedDownloader) to abort a download that would push the server past // its storage quota. handleApplyVersion maps it to the shared 507 // disk_limit_exceeded body; every other caller never sets the hook. var errDownloadQuotaExceeded = errors.New("download aborted: server disk limit exceeded") type Downloader struct { headerTimeout time.Duration maxBytes int64 // quotaCheck, when set, is consulted with the running byte total during the // commit copy and aborts it on rejection. Zero value = unquotaed, so every // caller that does not opt in keeps its exact behavior. quotaCheck func(written int64) error } // readerOnly narrows a Reader to just Read so io.Copy cannot take a // WriterTo/ReadFrom shortcut that bypasses per-chunk quota consultation. type readerOnly struct{ io.Reader } // quotaLimitedWriter enforces the Downloader's optional quota hook: after every // successful write it reports the running total and aborts the copy when the // callback rejects it. The hook must be O(1) (the agent wires a precomputed // used+written <= limit comparison, not a rescan — see quotaGuardedDownloader); // a per-chunk rescan here would turn a 10 GiB download into a quadratic walk. type quotaLimitedWriter struct { w io.Writer fn func(written int64) error sum int64 } func (q *quotaLimitedWriter) Write(p []byte) (int, error) { n, err := q.w.Write(p) q.sum += int64(n) if err == nil && q.fn != nil { if qerr := q.fn(q.sum); qerr != nil { return n, qerr } } return n, err } func (dl Downloader) safeURL(raw string) (*url.URL, error) { u, err := url.Parse(strings.TrimSpace(raw)) if err != nil { return nil, err } if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("invalid scheme") } if u.User != nil && u.User.String() != "" { return nil, fmt.Errorf("credentials not allowed") } host := u.Hostname() if host == "" { return nil, fmt.Errorf("missing host") } if isBlockedOutboundHostname(host) { return nil, fmt.Errorf("blocked host") } ips, err := net.LookupIP(host) if err != nil { return nil, fmt.Errorf("dns failed: %w", err) } checkedIP := false for _, ip := range ips { addr, ok := netip.AddrFromSlice(ip) if !ok { continue } checkedIP = true if isBlockedOutboundAddr(addr) { return nil, fmt.Errorf("blocked host ip: %s", addr.String()) } } if !checkedIP { return nil, fmt.Errorf("dns returned no usable ip") } return u, nil } func isBlockedOutboundHostname(host string) bool { h := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(host)), ".") return h == "localhost" || strings.HasSuffix(h, ".localhost") || strings.HasSuffix(h, ".local") } func isBlockedOutboundAddr(addr netip.Addr) bool { if addr.Is4In6() { addr = addr.Unmap() } if !addr.IsGlobalUnicast() || addr.IsPrivate() || addr.IsLoopback() || addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() || addr.IsMulticast() || addr.IsUnspecified() { return true } // netip's classification covers RFC1918/RFC4193, loopback, link-local and // multicast but silently allows the rest of the special-purpose ranges the // panel-side SSRF guards refuse (index.js isPrivateIPv4/isPrivateIPv6, // utils/node-ssrf-guard.js forbiddenIpv4Reason/forbiddenIpv6Reason). The // panel relays user URL uploads to the daemon's /v1/fs/uploadUrl and this // daemon then does the fetching, so a range blocked only panel-side stays // reachable through the relay: the daemon must refuse the same set, most // importantly the carrier-grade NAT range 100.64.0.0/10, where Tailscale // tailnets and some cloud service CIDRs live on node hosts. if addr.Is4() { return isBlockedOutboundIPv4(addr.As4()) } return isBlockedOutboundIPv6(addr.As16()) } // isBlockedOutboundIPv4 classifies the special-purpose IPv4 ranges beyond // netip's IsPrivate/IsGlobalUnicast coverage, mirroring forbiddenIpv4Reason // in node-ssrf-guard.js (byte arithmetic only - no string re-parsing). func isBlockedOutboundIPv4(b [4]byte) bool { a, o1, o2 := int(b[0]), int(b[1]), int(b[2]) switch { case a == 0: // 0.0.0.0/8 "this network" (IsUnspecified covers only 0.0.0.0) return true case a == 100 && o1 >= 64 && o1 <= 127: // 100.64.0.0/10 carrier-grade NAT return true case a == 192 && o1 == 0 && o2 == 2: // 192.0.2.0/24 documentation return true case a == 198 && (o1 == 18 || o1 == 19): // 198.18.0.0/15 benchmarking return true case a == 198 && o1 == 51 && o2 == 100: // 198.51.100.0/24 documentation return true case a == 203 && o1 == 0 && o2 == 113: // 203.0.113.0/24 documentation return true case a >= 240: // 240.0.0.0/4 reserved incl. broadcast (multicast 224/4 already covered) return true } return false } // isBlockedOutboundIPv6 mirrors forbiddenIpv6Reason for the ranges netip // misses (IPv4-mapped and IPv4-compatible tails with a private embedded // address are already refused via the Unmap above): deprecated site-local, // documentation, and the transition prefixes whose only payload is an encoded // IPv4 address. The transition prefixes are refused wholesale — index.js does // that only for NAT64 (startsWith("64:ff9b:")) and node-ssrf-guard.js instead // classifies their embedded IPv4 — because all three are RFC-deprecated ranges // (6to4 RFC 7526, Teredo, ::/96 RFC 4291) that no legitimate DNS answer lands // in anymore, and refusing the whole prefix avoids trusting embedded-IPv4 // classification of attacker-supplied AAAA forms. func isBlockedOutboundIPv6(b [16]byte) bool { switch { case b[0] == 0xfe && (b[1]&0xc0) == 0xc0: // fec0::/10 deprecated site-local return true case b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x0d && b[3] == 0xb8: // 2001:db8::/32 documentation return true case b[0] == 0x20 && b[1] == 0x02: // 2002::/16 6to4 (deprecated, RFC 7526) return true case b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x00 && b[3] == 0x00: // 2001:0::/32 Teredo return true case b[0] == 0x00 && b[1] == 0x64 && b[2] == 0xff && b[3] == 0x9b: // 64:ff9b::/32 NAT64 (well-known /96 + local-use /48) return true case b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 0 && b[4] == 0 && b[5] == 0 && b[6] == 0 && b[7] == 0 && b[8] == 0 && b[9] == 0 && b[10] == 0 && b[11] == 0 && !(b[12] == 0 && b[13] == 0 && b[14] == 0 && b[15] == 0): // deprecated IPv4-compatible ::/96 return true } return false } func isPrivateIP(ip net.IP) bool { addr, ok := netip.AddrFromSlice(ip) if !ok { return true } return isBlockedOutboundAddr(addr) } func (dl Downloader) client() *http.Client { return dl.clientWithProxy(http.ProxyFromEnvironment) } func (dl Downloader) clientNoProxy() *http.Client { return dl.clientWithProxy(nil) } func (dl Downloader) clientWithProxy(proxy func(*http.Request) (*url.URL, error)) *http.Client { safeDialer := &net.Dialer{ Timeout: 10 * time.Second, KeepAlive: 30 * time.Second, } transport := &http.Transport{ Proxy: proxy, DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { host, port, err := net.SplitHostPort(addr) if err != nil { return nil, fmt.Errorf("invalid address: %w", err) } ips, err := net.LookupIP(host) if err != nil { return nil, fmt.Errorf("dns lookup failed: %w", err) } for _, ip := range ips { if isPrivateIP(ip) { continue } dialAddr := net.JoinHostPort(ip.String(), port) return safeDialer.DialContext(ctx, network, dialAddr) } return nil, fmt.Errorf("all resolved IPs are blocked (private/internal)") }, TLSHandshakeTimeout: 10 * time.Second, ResponseHeaderTimeout: dl.headerTimeout, IdleConnTimeout: 60 * time.Second, MaxIdleConns: 50, MaxIdleConnsPerHost: 10, } return &http.Client{ Transport: transport, CheckRedirect: func(req *http.Request, via []*http.Request) error { if len(via) >= 10 { return fmt.Errorf("too many redirects") } _, err := dl.safeURL(req.URL.String()) return err }, } } func (dl Downloader) getJSON(ctx context.Context, raw string, dst any) error { u, err := dl.safeURL(raw) if err != nil { return err } req, _ := http.NewRequestWithContext(ctx, "GET", u.String(), nil) resp, err := dl.client().Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != 200 { io.Copy(io.Discard, resp.Body) return fmt.Errorf("http %d", resp.StatusCode) } body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) if err != nil { return err } return json.Unmarshal(body, dst) } func (dl Downloader) downloadToFile(ctx context.Context, rawURL, destPath string) error { u, err := dl.safeURL(rawURL) if err != nil { return err } req, _ := http.NewRequestWithContext(ctx, "GET", u.String(), nil) resp, err := dl.client().Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != 200 { io.Copy(io.Discard, resp.Body) return fmt.Errorf("http %d", resp.StatusCode) } return dl.writeDownloadToFile(resp.Body, destPath) } // writeDownloadToFile commits an already-validated body to destPath through a // unique temp file + rename. Split from downloadToFile so tests can drive the // commit logic (where the concurrent-apply corruption lived) without the SSRF // host resolution, which refuses the loopback a test HTTP server binds to. func (dl Downloader) writeDownloadToFile(body io.Reader, destPath string) error { if err := ensureDir(filepath.Dir(destPath)); err != nil { return err } // Unique temp file per download. A deterministic destPath+".tmp" was the // only non-unique write name in the codebase: two concurrent applies to // the same destination (double-submitted install, reinstall racing an // apply) shared one temp file, the first rename-by-name moved the second // writer's still-open fd into destPath, both flows could report success, // and the destination was left truncated or interleaved. O_CREATE|O_EXCL // makes the uniqueness guarantee airtight (and never follows a pre-planted // symlink — the open fails with EEXIST instead), preserving the // openNoFollow guarantee of the old open while removing the shared name. dir := filepath.Dir(destPath) var f *os.File var tmp string for attempt := 0; attempt < 5 && f == nil; attempt++ { candidate := filepath.Join(dir, fmt.Sprintf(".%s.tmp-%s", filepath.Base(destPath), randomHex(8))) fh, err := os.OpenFile(candidate, os.O_CREATE|os.O_EXCL|os.O_WRONLY|openNoFollow, 0o644) if err == nil { f, tmp = fh, candidate break } if !errors.Is(err, os.ErrExist) { return err } } if f == nil { return fmt.Errorf("could not create a unique temp file next to %s", destPath) } defer f.Close() var r io.Reader = body if dl.maxBytes > 0 { r = io.LimitReader(body, dl.maxBytes) } // readerOnly hides copy shortcuts (io.WriterTo, e.g. bytes.Reader) behind a // bare Read: such a source would hand io.Copy its whole buffer in ONE // Write, deferring the quota hook until after the full chunk is already on // disk. With the shortcut hidden, io.Copy falls back to its bounded 32 KiB // loop, so the hook's worst-case observation lag is one buffer for every // source, not just streaming response bodies. r = readerOnly{r} // The quota hook wraps the destination (not the reader): it must observe // bytes actually committed to disk, not bytes the source emitted. var dst io.Writer = f if dl.quotaCheck != nil { dst = "aLimitedWriter{w: f, fn: dl.quotaCheck} } if _, err := io.Copy(dst, r); err != nil { _ = os.Remove(tmp) return err } if err := f.Close(); err != nil { _ = os.Remove(tmp) return err } return os.Rename(tmp, destPath) } // writeMinecraftScaffold lays out the default Minecraft server files. It // intentionally does NOT write eula.txt: EULA consent must come from a user // through the console EULA prompt, never pre-accepted by the panel. func writeMinecraftScaffold(serverDir, name, fork, version string) { props := strings.Join([]string{ "motd=" + name, "max-players=20", "enforce-secure-profile=false", "server-port=25565", "server-ip=", "", }, "\n") _ = os.WriteFile(filepath.Join(serverDir, "server.properties"), []byte(props), 0o644) } // normalizeTemplateIdentifier lowercases a stored template/type identifier so // template comparisons are stable across panel versions; blank and "" // entries (Go's fmt.Sprint of a missing map value) are treated as unknown. func normalizeTemplateIdentifier(v any) string { id := strings.ToLower(strings.TrimSpace(fmt.Sprint(v))) if id == "" || id == "" { return "" } return id } // isMinecraftServerMeta reports whether ADPanel positively identifies a server // as a Minecraft server. It only reads identifiers already persisted on the // server when the Minecraft template was applied (meta type/template or the // template's docker runtime signature); template JSON files are never modified. // Anything that cannot be positively identified as Minecraft returns false, so // the EULA gate automatically passes for every other template. func isMinecraftServerMeta(meta map[string]any) bool { if meta == nil { return false } for _, key := range []string{"type", "template"} { if normalizeTemplateIdentifier(meta[key]) == "minecraft" { return true } } runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj == nil { return false } image := normalizeTemplateIdentifier(runtimeObj["image"]) command := normalizeTemplateIdentifier(runtimeObj["command"]) // Signature of the bundled Minecraft template: eclipse-temurin runtime // launching the server jar from the mounted data directory. return image == "eclipse-temurin" && strings.Contains(command, "server.jar") } // minecraftEulaAccepted inspects the server files and reports whether eula.txt // exists and is set to eula=true. Every other state (missing file, empty file, // eula=false, unparseable content) counts as not accepted. // // adpanel:fs-toctou - the read runs against a serverDir pinned by directory fd // (safeOpenRegularAt): a tenant symlink at the stable eula.txt name can no // longer redirect the read into a sibling server, and the O_NONBLOCK open + // regular-file fstat gate mean a planted FIFO cannot wedge the start path // inside open(2)/read(2) - any refusal maps onto the existing error // convention, "not accepted". A normal eula.txt is read byte-identically. func minecraftEulaAccepted(serverDir string) bool { root, err := safeOpenRoot(serverDir) if err != nil { return false } defer root.Close() f, _, err := safeOpenRegularAt(root, "eula.txt", os.O_RDONLY, 0) if err != nil { return false } defer f.Close() data, err := io.ReadAll(f) if err != nil { return false } for _, rawLine := range strings.Split(string(data), "\n") { line := strings.TrimSpace(rawLine) if line == "" || strings.HasPrefix(line, "#") { continue } key, value, found := strings.Cut(line, "=") if !found { continue } if strings.EqualFold(strings.TrimSpace(key), "eula") && strings.EqualFold(strings.TrimSpace(value), "true") { return true } } return false } var errMinecraftEulaRequired = errors.New("minecraft eula not accepted") // adpanel:backup-race - returned by performServerStart when a backup // create/restore/delete holds the server's op lock; handleStart maps it to a // 409 backup_in_progress. var errBackupOpInProgress = errors.New("backup operation in progress") // adpanel:backup-race - returned by performServerStart when a reinstall holds // the server's op lock; handleStart maps it to a 409 reinstall_in_progress. var errReinstallOpInProgress = errors.New("reinstall operation in progress") // adpanel:backup-race - returned by performServerStart when a runtime seed // holds the server's op lock; handleStart maps it to a 409 // runtime_seed_in_progress. var errRuntimeSeedOpInProgress = errors.New("runtime seed operation in progress") // adpanel:backup-race - returned by performServerStart when its bounded // op-lock acquisition expires behind a short holder (see // acquireServerOpLockFailFast); handleStart maps it to a 409 // server_op_in_progress. var errServerOpInProgress = errors.New("server operation already in progress") var errServerStartNotFound = errors.New("not found") var errServerAlreadyRunning = errors.New("server already running") var errServerStartStateUnknown = errors.New("could not verify container state before starting") var errPowerOpRequestEnded = errors.New("power request ended before admission") // adpanel:fs-toctou - the server.properties read-modify-write runs against a // serverDir pinned by directory fd: a tenant symlink at the stable // server.properties name can no longer redirect the daemon's write into a // sibling server, and the O_NONBLOCK open + regular-file gate means a planted // FIFO cannot wedge the start path (refused like any other unreadable // file, same convention as the eula read). Contents, the regex rewrite, the // 0o644 mode and the ignored-error behavior are unchanged; a normal // server.properties round-trips byte-identically. func enforceServerProps(serverDir string) { const propsRel = "server.properties" root, err := safeOpenRoot(serverDir) if err != nil { return } defer root.Close() txt := "" if f, _, rerr := safeOpenRegularAt(root, propsRel, os.O_RDONLY, 0); rerr == nil { if b, derr := io.ReadAll(f); derr == nil { txt = string(b) } f.Close() } if txt == "" { txt = "server-port=25565\nserver-ip=\n" } else { rePort := regexp.MustCompile(`(?m)^server-port=.*$`) reIP := regexp.MustCompile(`(?m)^server-ip=.*$`) if rePort.MatchString(txt) { txt = rePort.ReplaceAllString(txt, "server-port=25565") } else { txt += "\nserver-port=25565\n" } if reIP.MatchString(txt) { txt = reIP.ReplaceAllString(txt, "server-ip=") } else { txt += "server-ip=\n" } } _ = safeWriteAt(root, propsRel, os.O_WRONLY|os.O_CREATE|os.O_TRUNC|openNoFollow, 0o644, []byte(txt)) } func fixedJarUrlFor1218(fork string) string { f := strings.ToLower(strings.TrimSpace(fork)) switch f { case "paper": return "https://fill-data.papermc.io/v1/objects/8de7c52c3b02403503d16fac58003f1efef7dd7a0256786843927fa92ee57f1e/paper-1.21.8-60.jar" case "pufferfish": return "https://ci.pufferfish.host/job/Pufferfish-1.21/33/artifact/pufferfish-server/build/libs/pufferfish-paperclip-1.21.8-R0.1-SNAPSHOT-mojmap.jar" case "vanilla": return "https://piston-data.mojang.com/v1/objects/95495a7f485eedd84ce928cef5e223b757d2f764/server.jar" default: return "https://api.purpurmc.org/v2/purpur/1.21.8/2497/download" } } // adpanel:F8 - mcVersion/mcFork arrive from the panel and are interpolated // into the PaperMC/Purpur API URL paths in getMinecraftJarURL, so they are // pinned to a strict allowlist/grammar at this trust boundary too (the panel // validates first; these helpers make the URL-construction sites safe on // their own). Must stay in sync with utils/minecraft-versions.js. var supportedMinecraftForks = map[string]bool{ "paper": true, "pufferfish": true, "vanilla": true, "purpur": true, } // Mirror of MC_FORK_ALIASES in utils/minecraft-versions.js: legacy names map // onto the maintained successor instead of falling through to an unrelated // fork's download. var minecraftForkAliases = map[string]string{ "spigot": "paper", "bukkit": "paper", } // Mirror of MC_VERSION_PATTERN in utils/minecraft-versions.js: releases // (1.21.8), pre-releases/RCs (1.21.8-pre1) and snapshots (24w14a) only. // Anything else is rejected before it can reach a URL-path interpolation. var minecraftVersionPattern = regexp.MustCompile(`^(?:1\.\d{1,2}(?:\.\d{1,2})?(?:-(?:pre|rc)\d{1,2})?|\d{1,2}w\d{1,2}[a-z])$`) func resolveMinecraftFork(fork string) (string, error) { f := strings.ToLower(strings.TrimSpace(fork)) if f == "" { return "paper", nil } if mapped, ok := minecraftForkAliases[f]; ok { f = mapped } if !supportedMinecraftForks[f] { return "", fmt.Errorf("unsupported minecraft fork %q (supported: paper, pufferfish, vanilla, purpur)", fork) } return f, nil } func resolveMinecraftVersion(version string) (string, error) { v := strings.ToLower(strings.TrimSpace(version)) if v == "" { return "1.21.8", nil } if !minecraftVersionPattern.MatchString(v) { return "", fmt.Errorf("unsupported minecraft version %q (expected e.g. 1.21.8, 1.21.8-pre1, 24w14a)", version) } return v, nil } // paperJarFileName validates the jar file name reported by the PaperMC builds // API before it becomes a URL path segment; the API response is treated as // untrusted input. A malformed name falls back to the conventional // paper--.jar layout. var minecraftJarNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jar$`) func paperJarFileName(apiName, version string, build int) string { name := strings.TrimSpace(apiName) if !strings.Contains(name, "..") && minecraftJarNamePattern.MatchString(name) { return name } return fmt.Sprintf("paper-%s-%d.jar", version, build) } func getMinecraftJarURL(ctx context.Context, dl Downloader, fork, version string, debug bool) (string, error) { f, err := resolveMinecraftFork(fork) if err != nil { return "", err } v, err := resolveMinecraftVersion(version) if err != nil { return "", err } if v == "1.21.8" { return fixedJarUrlFor1218(f), nil } // PathEscape is a no-op for grammar-valid values but keeps the invariant // local to the URL construction so future edits cannot reintroduce raw // interpolation. if f == "purpur" { return fmt.Sprintf("https://api.purpurmc.org/v2/purpur/%s/latest/download", url.PathEscape(v)), nil } if f == "paper" || f == "pufferfish" { var builds struct { Builds []struct { Build int `json:"build"` Downloads struct { Application struct { Name string `json:"name"` } `json:"application"` } `json:"downloads"` } `json:"builds"` } u := fmt.Sprintf("https://api.papermc.io/v2/projects/paper/versions/%s/builds", url.PathEscape(v)) if err := dl.getJSON(ctx, u, &builds); err == nil && len(builds.Builds) > 0 { last := builds.Builds[len(builds.Builds)-1] jarName := paperJarFileName(last.Downloads.Application.Name, v, last.Build) return fmt.Sprintf("https://api.papermc.io/v2/projects/paper/versions/%s/builds/%d/downloads/%s", url.PathEscape(v), last.Build, url.PathEscape(jarName)), nil } } if f == "vanilla" { var manifest struct { Versions []struct { ID string `json:"id"` URL string `json:"url"` } `json:"versions"` } if err := dl.getJSON(ctx, "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json", &manifest); err == nil { for _, ver := range manifest.Versions { if ver.ID == v && ver.URL != "" { var det struct { Downloads struct { Server struct { URL string `json:"url"` } `json:"server"` } `json:"downloads"` } if err := dl.getJSON(ctx, ver.URL, &det); err == nil && det.Downloads.Server.URL != "" { return det.Downloads.Server.URL, nil } } } } } // Historical behavior: when the fork-specific lookup cannot resolve (API // outage, empty build list), fall through to Purpur's versioned download // so setup still produces a working jar. return fmt.Sprintf("https://api.purpurmc.org/v2/purpur/%s/latest/download", url.PathEscape(v)), nil } const legacyPythonMainTemplate = `def greet(name="World"): return f"Hello, {name}!" if __name__ == "__main__": print("--- Starting main.py execution ---") user_name = "ADPanel" message_1 = greet(user_name) print(f"Message 1: {message_1}") message_2 = greet() print(f"Message 2: {message_2}") print("--- Execution finished ---") ` const pythonMainTemplate = `from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import os class Handler(BaseHTTPRequestHandler): def do_GET(self): body = b"ADPanel Python server is running.\n" self.send_response(200) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, fmt, *args): print("%s - %s" % (self.address_string(), fmt % args), flush=True) if __name__ == "__main__": port = int(os.environ.get("PORT", "8000")) server = ThreadingHTTPServer(("0.0.0.0", port), Handler) print(f"ADPanel Python server listening on 0.0.0.0:{port}", flush=True) server.serve_forever() ` func clampPort(p any, fallback int) int { if n, ok := parseStrictPortValue(p); ok { return n } return fallback } func isStrictNumericPortString(s string) bool { if s == "" { return false } if s[0] < '1' || s[0] > '9' { return false } for i := 1; i < len(s); i++ { if s[i] < '0' || s[i] > '9' { return false } } return true } func parseStrictPortValue(v any) (int, bool) { switch x := v.(type) { case int: if x < 1 || x > 65535 { return 0, false } return x, true case int64: if x < 1 || x > 65535 { return 0, false } return int(x), true case float64: if x < 1 || x > 65535 || x != float64(int(x)) { return 0, false } return int(x), true case float32: if x < 1 || x > 65535 || x != float32(int(x)) { return 0, false } return int(x), true case string: s := strings.TrimSpace(x) if !isStrictNumericPortString(s) { return 0, false } n, err := strconv.Atoi(s) if err != nil || n < 1 || n > 65535 { return 0, false } return n, true default: return 0, false } } func normalizePortProtocolName(v any) string { protocol := strings.ToLower(strings.TrimSpace(fmt.Sprint(v))) switch protocol { case "tcp", "udp", "sctp": return protocol default: return "" } } func normalizePortProtocolSlice(v any) []string { var raw []any switch x := v.(type) { case []string: raw = make([]any, 0, len(x)) for _, item := range x { raw = append(raw, item) } case []any: raw = x case string: raw = []any{x} default: return nil } out := make([]string, 0, len(raw)) seen := map[string]struct{}{} for _, item := range raw { protocol := normalizePortProtocolName(item) if protocol == "" { continue } if _, ok := seen[protocol]; ok { continue } seen[protocol] = struct{}{} out = append(out, protocol) } return out } func runtimePortProtocolMap(raw any) map[int][]string { out := map[int][]string{} switch x := raw.(type) { case map[string][]string: for key, protocolsRaw := range x { port, ok := parseStrictPortValue(key) if !ok { continue } protocols := normalizePortProtocolSlice(protocolsRaw) if len(protocols) > 0 { out[port] = protocols } } case map[string]any: for key, protocolsRaw := range x { port, ok := parseStrictPortValue(key) if !ok { continue } protocols := normalizePortProtocolSlice(protocolsRaw) if len(protocols) > 0 { out[port] = protocols } } case map[int][]string: for port, protocolsRaw := range x { if _, ok := parseStrictPortValue(port); !ok { continue } protocols := normalizePortProtocolSlice(protocolsRaw) if len(protocols) > 0 { out[port] = protocols } } } if len(out) == 0 { return nil } return out } func portProtocolsFor(protocolsByPort map[int][]string, port int) []string { if port > 0 { if protocols := protocolsByPort[port]; len(protocols) > 0 { return protocols } } return []string{"tcp"} } func mergePortProtocols(a, b []string) []string { out := make([]string, 0, len(a)+len(b)) seen := map[string]struct{}{} for _, source := range [][]string{a, b} { for _, raw := range source { protocol := normalizePortProtocolName(raw) if protocol == "" { continue } if _, ok := seen[protocol]; ok { continue } seen[protocol] = struct{}{} out = append(out, protocol) } } return out } func sanitizeDockerPortProtocols(raw map[string][]string, ports []int) map[string][]string { if len(raw) == 0 { return nil } allowedPorts := map[int]struct{}{} for _, port := range ports { if _, ok := parseStrictPortValue(port); ok { allowedPorts[port] = struct{}{} } } out := map[string][]string{} for rawPort, protocolsRaw := range raw { port, ok := parseStrictPortValue(rawPort) if !ok { continue } if len(allowedPorts) > 0 { if _, ok := allowedPorts[port]; !ok { continue } } protocols := normalizePortProtocolSlice(protocolsRaw) if len(protocols) > 0 { out[strconv.Itoa(port)] = protocols } } if len(out) == 0 { return nil } return out } func (a *Agent) dockerHostPortOwner(ctx context.Context, port int, excludeName string) string { if a == nil || port <= 0 { return "" } out, _, code, err := a.docker.runCollect(ctx, "ps", "--format", "{{.Names}}\t{{.Ports}}") if err != nil || code != 0 { return "" } needle := ":" + strconv.Itoa(port) + "->" excluded := strings.ToLower(strings.TrimSpace(excludeName)) for _, line := range strings.Split(out, "\n") { line = strings.TrimSpace(line) if line == "" { continue } parts := strings.SplitN(line, "\t", 2) if len(parts) != 2 { continue } name := strings.TrimSpace(parts[0]) if excluded != "" && strings.ToLower(name) == excluded { continue } if strings.Contains(parts[1], needle) { return name } } return "" } func (a *Agent) hostPortAvailability(ctx context.Context, port int, excludeName string) (bool, string, string) { return a.hostPortAvailabilityForProtocols(ctx, port, []string{"tcp"}, excludeName) } func (a *Agent) hostPortAvailabilityForProtocols(ctx context.Context, port int, protocols []string, excludeName string) (bool, string, string) { return a.hostBindingAvailability(ctx, port, protocols, excludeName, "0.0.0.0") } var dockerRunFlagsWithValue = map[string]bool{ "-e": true, "--env": true, "-v": true, "--volume": true, "-p": true, "--publish": true, "-w": true, "--workdir": true, "--name": true, "-m": true, "--memory": true, "--cpus": true, "--memory-swap": true, "--memory-reservation": true, "--cpu-period": true, "--cpu-quota": true, "-u": true, "--user": true, "-h": true, "--hostname": true, "--network": true, "--net": true, "--restart": true, "-l": true, "--label": true, "--entrypoint": true, "--mount": true, "--tmpfs": true, "--device": true, "--pid": true, "--ipc": true, "--userns": true, "--uts": true, "--cgroupns": true, "--shm-size": true, "--ulimit": true, "--dns": true, "--dns-search": true, "--add-host": true, "--log-driver": true, "--log-opt": true, "--stop-signal": true, "--stop-timeout": true, "--health-cmd": true, "--health-interval": true, "--health-retries": true, "--health-timeout": true, "--runtime": true, "--platform": true, "--pull": true, "--ip": true, "--ip6": true, "--mac-address": true, "--expose": true, "--link": true, "--cidfile": true, } var dockerRunSafeStandaloneFlags = map[string]bool{ "-d": true, "--detach": true, "-i": true, "--interactive": true, "-t": true, "--tty": true, "--rm": true, "--init": true, "--read-only": true, } var dockerRunBlockedFlags = map[string]bool{ "--privileged": true, "--cap-add": true, "--cap-drop": true, "--security-opt": true, "--volumes-from": true, "--env-file": true, "--device": true, "--device-cgroup-rule": true, "--sysctl": true, "--oom-kill-disable": true, "--oom-score-adj": true, } var dockerRunHostNamespaceFlags = map[string]bool{ "--network": true, "--net": true, "--pid": true, "--userns": true, "--ipc": true, "--uts": true, "--cgroupns": true, } func isSafeShortDockerFlagCluster(flag string) bool { if len(flag) < 2 || flag[0] != '-' || strings.HasPrefix(flag, "--") { return false } for i := 1; i < len(flag); i++ { switch flag[i] { case 'd', 'D', 'i', 'I', 't', 'T': default: return false } } return true } func parseDockerFlagToken(token string) (string, string) { trimmed := strings.TrimSpace(token) lower := strings.ToLower(trimmed) if eqIdx := strings.Index(lower, "="); eqIdx > 0 { return lower[:eqIdx], strings.TrimSpace(trimmed[eqIdx+1:]) } return lower, "" } func readDockerFlagValue(args []string, index int, inlineValue string) (string, int) { if strings.TrimSpace(inlineValue) != "" { return inlineValue, index } if index+1 >= len(args) { return "", index } return args[index+1], index + 1 } var ansiSGRRE = regexp.MustCompile(`\x1b\[[0-9;:]*m`) var mcHexRE = regexp.MustCompile(`§x(?:§[0-9A-Fa-f]){6}`) var mcRE = regexp.MustCompile(`§[0-9A-FK-ORa-fk-or]`) var promptArtifactRE = regexp.MustCompile(`(?m)^\s*>\.{2,}\s*`) var ttyOnlyLineRE = regexp.MustCompile(`^[\s>.=…-]+$`) func stripDockerStreamFraming(s string) string { buf := []byte(s) if len(buf) < 8 { return s } out := make([]byte, 0, len(buf)) usedFrames := false for i := 0; i < len(buf); { if len(buf)-i >= 8 && buf[i] >= 1 && buf[i] <= 3 && buf[i+1] == 0 && buf[i+2] == 0 && buf[i+3] == 0 { frameLen := int(binary.BigEndian.Uint32(buf[i+4 : i+8])) if frameLen == 0 { usedFrames = true i += 8 continue } if frameLen > 0 && len(buf)-i-8 >= frameLen { out = append(out, buf[i+8:i+8+frameLen]...) i += 8 + frameLen usedFrames = true continue } } out = append(out, buf[i]) i++ } if usedFrames { return string(out) } return s } func consumeAnsiCSISequence(s string, idx int) (next int, keep bool) { i := idx for i < len(s) { c := s[i] if c >= 0x40 && c <= 0x7e { return i + 1, c == 'm' } i++ } return len(s), false } func skipAnsiOSCSequence(s string, idx int) int { i := idx for i < len(s) { if s[i] == 0x07 { return i + 1 } if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '\\' { return i + 2 } i++ } return len(s) } func skipAnsiEscTerminatedSequence(s string, idx int) int { i := idx for i < len(s) { if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '\\' { return i + 2 } i++ } return len(s) } func sanitizeAnsiForConsole(s string) string { if s == "" { return s } var out strings.Builder out.Grow(len(s)) for i := 0; i < len(s); { switch s[i] { case 0x9b: next, keep := consumeAnsiCSISequence(s, i+1) if keep { out.WriteString(s[i:next]) } i = next continue case 0x1b: if i+1 >= len(s) { i++ continue } nextByte := s[i+1] switch nextByte { case '[': next, keep := consumeAnsiCSISequence(s, i+2) if keep { out.WriteString(s[i:next]) } i = next continue case ']': i = skipAnsiOSCSequence(s, i+2) continue case 'P', 'X', '^', '_': i = skipAnsiEscTerminatedSequence(s, i+2) continue default: if nextByte >= 0x40 && nextByte <= 0x5f { i += 2 continue } i++ continue } default: if (s[i] < 32 || s[i] == 127) && s[i] != '\n' && s[i] != '\r' && s[i] != '\t' { i++ continue } out.WriteByte(s[i]) i++ } } return out.String() } func cleanLogLine(s string) string { if s == "" { return s } s = strings.ReplaceAll(s, "\r\n", "\n") s = strings.ReplaceAll(s, "\r", "\n") s = stripDockerStreamFraming(s) s = sanitizeAnsiForConsole(s) s = mcHexRE.ReplaceAllString(s, "") s = mcRE.ReplaceAllString(s, "") s = promptArtifactRE.ReplaceAllString(s, "") lines := strings.Split(s, "\n") out := make([]string, 0, len(lines)) for _, line := range lines { line = strings.ReplaceAll(line, "…", "") line = strings.TrimRight(line, " \t") line = strings.TrimLeft(line, ">=. ") plain := strings.TrimSpace(ansiSGRRE.ReplaceAllString(line, "")) if plain == "" || ttyOnlyLineRE.MatchString(plain) || strings.Contains(plain, "[ADPanel Setup]") { continue } out = append(out, line) } return strings.Join(out, "\n") } func normalizeConsoleMode(raw any) string { switch v := raw.(type) { case string: mode := strings.ToLower(strings.TrimSpace(v)) switch mode { case "stdin", "exec", "exec-shell", "shell": return mode } case map[string]any: if mode := normalizeConsoleMode(v["mode"]); mode != "" { return mode } if mode := normalizeConsoleMode(v["type"]); mode != "" { return mode } } return "" } func consoleProcessTargetsFromRaw(raw any) []string { switch v := raw.(type) { case string: return sanitizeConsoleProcessTargets([]string{v}) case []string: return sanitizeConsoleProcessTargets(v) case []any: out := make([]string, 0, len(v)) for _, item := range v { out = append(out, fmt.Sprint(item)) } return sanitizeConsoleProcessTargets(out) case map[string]any: for _, key := range []string{"targetProcesses", "target_processes", "processes", "processNames", "process_names"} { if targets := consoleProcessTargetsFromRaw(v[key]); len(targets) > 0 { return targets } } for _, key := range []string{"targetProcess", "target_process", "process", "target"} { if targets := consoleProcessTargetsFromRaw(v[key]); len(targets) > 0 { return targets } } } return nil } func sanitizeConsoleProcessTargets(values []string) []string { out := make([]string, 0, len(values)) seen := make(map[string]struct{}, len(values)) for _, value := range values { target := strings.TrimSpace(value) target = strings.Trim(target, "'\"") if target == "" || target == "" || strings.ContainsAny(target, "\x00\r\n") { continue } if len(target) > 120 { target = target[:120] } if _, ok := seen[target]; ok { continue } seen[target] = struct{}{} out = append(out, target) if len(out) >= 12 { break } } return out } func normalizeTemplateID(raw any) string { id := strings.ToLower(strings.TrimSpace(fmt.Sprint(raw))) id = strings.ReplaceAll(id, "_", "-") id = strings.ReplaceAll(id, " ", "-") for strings.Contains(id, "--") { id = strings.ReplaceAll(id, "--", "-") } id = strings.Trim(id, "-") if id == "" { return "" } return id } func isKnownStdinConsoleTemplate(id string) bool { switch normalizeTemplateID(id) { case "7-days-to-die", "7dtd", "sdtd", "ark", "ark-survival-evolved", "assetto-corsa", "csgo", "cs2", "counter-strike-2", "dayz", "fivem", "five-m", "hytale", "minecraft", "palworld", "project-zomboid", "zomboid", "ragemp", "rage-mp", "redm", "rust", "valheim": return true default: return false } } func defaultConsoleProcessTargetsForTemplate(id string) []string { switch normalizeTemplateID(id) { case "7-days-to-die", "7dtd", "sdtd": return []string{"7DaysToDieServer", "7DaysToDieServer.x86_64"} case "ark", "ark-survival-evolved": return []string{"ShooterGameServer"} case "assetto-corsa": return []string{"server-manager", "acServer"} case "csgo", "cs2", "counter-strike-2": return []string{"cs2", "srcds_linux"} case "dayz": return []string{"DayZServer", "DayZServer_x64", "dayzserver"} case "fivem", "five-m": return []string{"FXServer", "fxserver"} case "hytale": return []string{"hytale-server", "java"} case "minecraft": return []string{"java", "bedrock_server"} case "palworld": return []string{"PalServer-Linux-Test", "PalServer"} case "project-zomboid", "zomboid": return []string{"ProjectZomboid64", "ProjectZomboid32", "java"} case "ragemp", "rage-mp": return []string{"ragemp-server", "ragemp"} case "redm": return []string{"FXServer", "fxserver"} case "rust": return []string{"RustDedicated"} case "valheim": return []string{"valheim_server", "valheim_server.x86_64"} default: return nil } } func defaultConsoleProcessTargetsForImage(image string) []string { imageLower := strings.ToLower(strings.TrimSpace(image)) switch { case strings.Contains(imageLower, "hytale"): return defaultConsoleProcessTargetsForTemplate("hytale") case strings.Contains(imageLower, "redm"): return defaultConsoleProcessTargetsForTemplate("redm") case strings.Contains(imageLower, "fivem"): return defaultConsoleProcessTargetsForTemplate("fivem") case strings.Contains(imageLower, "dayz") || strings.Contains(imageLower, "day-z"): return defaultConsoleProcessTargetsForTemplate("dayz") case strings.Contains(imageLower, "zomboid"): return defaultConsoleProcessTargetsForTemplate("project-zomboid") case strings.Contains(imageLower, "palworld"): return defaultConsoleProcessTargetsForTemplate("palworld") case strings.Contains(imageLower, "valheim"): return defaultConsoleProcessTargetsForTemplate("valheim") case strings.Contains(imageLower, "rust"): return defaultConsoleProcessTargetsForTemplate("rust") case strings.Contains(imageLower, "ragemp"): return defaultConsoleProcessTargetsForTemplate("ragemp") case strings.Contains(imageLower, "ark"): return defaultConsoleProcessTargetsForTemplate("ark-survival-evolved") case strings.Contains(imageLower, "7dtd") || strings.Contains(imageLower, "7daystodie") || strings.Contains(imageLower, "7-days-to-die") || strings.Contains(imageLower, "sdtd"): return defaultConsoleProcessTargetsForTemplate("7-days-to-die") case strings.Contains(imageLower, "assetto"): return defaultConsoleProcessTargetsForTemplate("assetto-corsa") case strings.Contains(imageLower, "cs2") || strings.Contains(imageLower, "csgo"): return defaultConsoleProcessTargetsForTemplate("cs2") default: return nil } } func consoleProcessTargetsForServer(meta map[string]any) []string { runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj != nil { if targets := consoleProcessTargetsFromRaw(runtimeObj["console"]); len(targets) > 0 { return targets } } for _, key := range []string{"template", "type"} { if targets := defaultConsoleProcessTargetsForTemplate(fmt.Sprint(meta[key])); len(targets) > 0 { return targets } } if runtimeObj != nil { if targets := defaultConsoleProcessTargetsForTemplate(fmt.Sprint(runtimeObj["providerId"])); len(targets) > 0 { return targets } if targets := defaultConsoleProcessTargetsForImage(fmt.Sprint(runtimeObj["image"])); len(targets) > 0 { return targets } } return nil } func inferredConsoleModeForServer(meta map[string]any) string { runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj != nil { if mode := normalizeConsoleMode(runtimeObj["console"]); mode != "" { return mode } if len(consoleProcessTargetsFromRaw(runtimeObj["console"])) > 0 { return "stdin" } } for _, key := range []string{"template", "type"} { if isKnownStdinConsoleTemplate(fmt.Sprint(meta[key])) { return "stdin" } } if runtimeObj != nil { if isKnownStdinConsoleTemplate(fmt.Sprint(runtimeObj["providerId"])) { return "stdin" } image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) if image != "" && image != "" && isGameServerDockerImage(image) { return "stdin" } startupDisplay := strings.TrimSpace(fmt.Sprint(runtimeObj["startupDisplay"])) if startupDisplay != "" && startupDisplay != "" { return "stdin" } } return "" } const ( maxExtractSize = 10 << 30 maxExtractFiles = 100000 maxSingleFile = 2 << 30 ) type limitedWriter struct { w io.Writer written int64 limit int64 exceeded bool } func (lw *limitedWriter) Write(p []byte) (int, error) { if lw.written+int64(len(p)) > lw.limit { lw.exceeded = true return 0, fmt.Errorf("extraction size limit exceeded (%d bytes)", lw.limit) } n, err := lw.w.Write(p) lw.written += int64(n) return n, err } // adpanel:fs-toctou - sanitizeExtractedTree pins the dest root once and // applies every chmod through dirfds opened beneath it (safeOpenDirAt + // safeChmodFileAt, AT_SYMLINK_NOFOLLOW semantics): the by-name os.Chmod this // replaces could follow a symlink swapped in between the walk's Lstat and the // chmod and move a mode change outside the extraction. The walk stays by-name // for enumeration and the exact "safe" mode derivation and skip rules are // unchanged; per-entry open/chmod failures are skipped silently exactly like // the ignored os.Chmod errors they replace. func sanitizeExtractedTree(dest string) error { root, err := safeOpenRoot(dest) if err != nil { return err } defer root.Close() return filepath.Walk(dest, func(path string, info os.FileInfo, err error) error { if err != nil { return nil } if info.Mode()&os.ModeSymlink != 0 { return nil } if !info.Mode().IsRegular() && !info.IsDir() { return nil } safe := sanitizeFileMode(info.Mode(), info.IsDir()) if info.Mode().Perm() == safe { return nil } rel, relErr := filepath.Rel(root.path, path) if relErr != nil { return nil } rel = filepath.Clean(rel) if rel == "." { // The walk root itself: chmod the pinned dirfd directly, which no // name swap can redirect. _ = root.file.Chmod(safe) return nil } if _, verr := safeRelUnderRoot(rel); verr != nil { return nil } parent, oerr := safeOpenDirAt(root, filepath.Dir(rel)) if oerr != nil { return nil } defer parent.Close() _ = safeChmodFileAt(parent, filepath.Base(rel), safe) return nil }) } // extractBudgetForDir caps how many bytes one extraction may write under // absDir: the smaller of the global archive-bomb cap (maxExtractSize) and the // server's remaining disk quota. Untracked dirs (meta, unserved volumes) get // the global cap only. Quota here counts existing usage including the archive // itself, so a near-full server may need its archive deleted before a large // extraction succeeds — a conservative failure mode by design. func (a *Agent) extractBudgetForDir(absDir string) int64 { budget := int64(maxExtractSize) serverName := a.serverNameFromPath(absDir) if serverName == "" || serverName == ".adpanel_meta" { return budget } serverDir := a.serverDir(serverName) limitBytes := a.getServerDiskLimitBytes(serverDir) if limitBytes <= 0 { return budget } remaining := limitBytes - a.getServerTotalUsage(serverDir) if remaining < 0 { return 0 } if remaining < budget { return remaining } return budget } // extractZipSafe is the by-name entry point for callers without a pinned // archive scope root (daemon-created import/sync temp files). The // handleFSExtract zip branch opens the archive through safeOpenRegularAt and // calls extractZipSafeFrom directly. Daemon-internal import/sync flows keep // conventional overwrite semantics; no-clobber is negotiated only by the // /v1/fs/extract request path. func extractZipSafe(src, dest string, maxTotal int64) error { f, err := os.Open(src) if err != nil { return err } defer f.Close() st, err := f.Stat() if err != nil { return err } _, err = extractZipSafeFrom(f, st.Size(), dest, maxTotal, true) return err } // extractZipSafeAt extracts an already-opened zip archive (size taken from // the opener's fstat) into dest. It returns the number of entries skipped by // no-clobber mode. With overwrite=false an entry whose destination already // exists is skipped — never truncated: the write below opens with O_EXCL // instead of O_TRUNC, so a file present at open time (race included) can // never be opened for writing. This serves the files_create-only extract // path; only callers holding files_write (or system flows) pass true. func extractZipSafeAt(f *os.File, size int64, destRoot *safeRoot, maxTotal int64, overwrite bool) (int, error) { if maxTotal <= 0 { return 0, fmt.Errorf("no extract budget") } dest := destRoot.path // adpanel:zip-cd-dos - zip.NewReader parses the whole central directory (a // File struct plus name/extra/comment strings per entry) before any // post-parse check can run, so a ~1 GB upload can spike daemon heap // hosting every server on this node. Count the real headers ourselves // first, bounded by the same caps, and reject before handing the file to // the stdlib. Fail-open on archives we cannot parse ourselves // (zip.NewReader will produce its authentic error); fail-closed on cap // exceedance. if err := preflightZipCentralDirectoryBounded(f, size); err != nil { return 0, err } r, err := zip.NewReader(f, size) if err != nil { return 0, err } if len(r.File) > maxExtractFiles { return 0, fmt.Errorf("too many files in archive: %d (max %d)", len(r.File), maxExtractFiles) } var totalSize int64 var fileCount int var skipped int for _, f := range r.File { name := f.Name name = filepath.FromSlash(name) target := filepath.Join(dest, name) if !isUnder(dest, target) { return 0, fmt.Errorf("zip-slip blocked: %s", f.Name) } if f.UncompressedSize64 > maxSingleFile { return 0, fmt.Errorf("file too large: %s (%d bytes, max %d)", f.Name, f.UncompressedSize64, maxSingleFile) } baseName := filepath.Base(name) if baseName == "." || baseName == ".." { continue } if f.FileInfo().IsDir() { // adpanel:fs-toctou - created through the pinned dest dirfd // (mkdirat on verified parents) so a planted intermediate symlink // can no longer make MkdirAll materialize a directory inside a // sibling directory when the target does not exist yet. targetRel, relErr := filepath.Rel(destRoot.path, target) if relErr != nil { return 0, relErr } if err := ensureDirUnderRoot(destRoot, targetRel, 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { return 0, fmt.Errorf("symlink escape blocked during zip extract: %s", f.Name) } return 0, err } continue } targetRel, relErr := filepath.Rel(destRoot.path, target) if relErr != nil { return 0, relErr } if err := ensureDirUnderRoot(destRoot, filepath.Dir(targetRel), 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { return 0, fmt.Errorf("symlink escape blocked during zip extract: %s", f.Name) } return 0, err } if ei, eiErr := os.Lstat(target); eiErr == nil && ei.Mode()&os.ModeSymlink != 0 { continue } if err := func() error { rc, err := f.Open() if err != nil { return err } defer rc.Close() // adpanel:fs-toctou - the target open rides with O_NONBLOCK and an // fstat regular-file gate (see safeOpenWriteAt) so a FIFO planted // at the target cannot wedge the writer inside open(2). writeFlags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY | openNoFollow if !overwrite { // adpanel:extract-no-clobber - no-clobber mode swaps O_TRUNC // for O_EXCL, so an existing destination fails the open with // EEXIST and the entry is skipped instead of truncated. The // pre-existing symlink continue above keeps its role; the // EEXIST check is what makes the skip race-free. writeFlags = os.O_CREATE | os.O_EXCL | os.O_WRONLY | openNoFollow } out, err := safeOpenWriteAt(destRoot, targetRel, writeFlags, 0o644) if err != nil { if !overwrite && errors.Is(err, os.ErrExist) { skipped++ return nil } return err } defer out.Close() lw := &limitedWriter{w: out, limit: maxTotal - totalSize} n, err := io.Copy(lw, rc) if err != nil { return err } totalSize += n fileCount++ if fileCount > maxExtractFiles { return fmt.Errorf("too many files extracted: %d (max %d)", fileCount, maxExtractFiles) } if overwrite { return sanitizeExtractedFileMode(out) } return nil }(); err != nil { return 0, err } } return skipped, nil } // extractTarSafeAt extracts a tar stream into dest and returns the number of // entries skipped by no-clobber mode. With overwrite=false an entry whose // destination already exists is skipped — never truncated: the write below // opens with O_EXCL instead of O_TRUNC, so a file present at open time (race // included) can never be opened for writing. This serves the files_create-only // extract path; only callers holding files_write (or system flows) pass true. func extractTarSafeAt(tr *tar.Reader, destRoot *safeRoot, maxTotal int64, overwrite, strict bool) (int, error) { if maxTotal <= 0 { return 0, fmt.Errorf("no extract budget") } dest := destRoot.path var totalSize int64 var fileCount int var skipped int for { h, err := tr.Next() if err == io.EOF { return skipped, nil } if err != nil { return 0, err } fileCount++ if fileCount > maxExtractFiles { return 0, fmt.Errorf("too many files in tar: %d (max %d)", fileCount, maxExtractFiles) } if !strict && h.Size > maxSingleFile { return 0, fmt.Errorf("file too large in tar: %s (%d bytes, max %d)", h.Name, h.Size, maxSingleFile) } name := filepath.Clean(h.Name) baseName := filepath.Base(name) if baseName == "." || baseName == ".." { continue } target := filepath.Join(dest, name) if !isUnder(dest, target) { return 0, fmt.Errorf("tar-slip blocked: %s", h.Name) } switch h.Typeflag { case tar.TypeDir: // adpanel:fs-toctou - created through the pinned dest dirfd // (mkdirat on verified parents) so a planted intermediate symlink // can no longer make MkdirAll materialize a directory inside a // sibling directory when the target does not exist yet. targetRel, relErr := filepath.Rel(destRoot.path, target) if relErr != nil { return 0, relErr } if err := ensureDirUnderRoot(destRoot, targetRel, 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { return 0, fmt.Errorf("symlink escape blocked during tar extract: %s", h.Name) } return 0, err } case tar.TypeReg, tar.TypeRegA: targetRel, relErr := filepath.Rel(destRoot.path, target) if relErr != nil { return 0, relErr } if err := ensureDirUnderRoot(destRoot, filepath.Dir(targetRel), 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { return 0, fmt.Errorf("symlink escape blocked during tar extract: %s", h.Name) } return 0, err } if ei, eiErr := os.Lstat(target); eiErr == nil && ei.Mode()&os.ModeSymlink != 0 { continue } // adpanel:fs-toctou - the target open rides with O_NONBLOCK and an // fstat regular-file gate (see safeOpenWriteAt) so a FIFO planted // at the target cannot wedge the writer inside open(2). writeFlags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY | openNoFollow if !overwrite { // adpanel:extract-no-clobber - no-clobber mode swaps O_TRUNC // for O_EXCL, so an existing destination fails the open with // EEXIST and the entry is skipped instead of truncated. The // pre-existing symlink continue above keeps its role; the // EEXIST check is what makes the skip race-free. writeFlags = os.O_CREATE | os.O_EXCL | os.O_WRONLY | openNoFollow } mode := os.FileMode(0o644) if strict { if h.Size > maxTotal-totalSize { return 0, errReinstallInstallerBudget } mode |= os.FileMode(h.Mode) & 0o111 } out, err := safeOpenWriteAt(destRoot, targetRel, writeFlags, mode) if err != nil { if !overwrite && errors.Is(err, os.ErrExist) { skipped++ continue } return 0, err } lw := &limitedWriter{w: out, limit: maxTotal - totalSize} n, err := io.Copy(lw, tr) if err == nil && overwrite && !strict { err = sanitizeExtractedFileMode(out) } out.Close() if err != nil { return 0, err } totalSize += n case tar.TypeLink: return 0, fmt.Errorf("hardlinks not allowed for security: %s", h.Name) case tar.TypeSymlink: if strict { return 0, fmt.Errorf("links are not supported in staged installer output: %s", h.Name) } default: if strict { return 0, fmt.Errorf("unsupported staged installer output: %s", h.Name) } } } } func detectArchiveType(p string) string { l := strings.ToLower(p) switch { case strings.HasSuffix(l, ".zip"): return "zip" case strings.HasSuffix(l, ".tar"): return "tar" case strings.HasSuffix(l, ".tar.gz") || strings.HasSuffix(l, ".tgz"): return "targz" case strings.HasSuffix(l, ".tar.bz2") || strings.HasSuffix(l, ".tbz2"): return "tarbz2" case strings.HasSuffix(l, ".tar.xz") || strings.HasSuffix(l, ".txz"): return "tarxz" case strings.HasSuffix(l, ".7z"): return "7z" case strings.HasSuffix(l, ".rar"): return "rar" default: return "" } } type AuditLogger struct { enabled bool mu sync.Mutex } func sanitizeLogField(s string) string { return strings.NewReplacer( "\n", "\\n", "\r", "\\r", "\t", "\\t", ).Replace(s) } func (al *AuditLogger) Log(event, clientIP, user, resource, action, result string, details map[string]any) { if !al.enabled { return } al.mu.Lock() defer al.mu.Unlock() entry := map[string]any{ "timestamp": time.Now().UTC().Format(time.RFC3339), "event": sanitizeLogField(event), "clientIP": sanitizeLogField(clientIP), "user": sanitizeLogField(user), "resource": sanitizeLogField(resource), "action": sanitizeLogField(action), "result": sanitizeLogField(result), } if details != nil { entry["details"] = details } b, _ := json.Marshal(entry) fmt.Printf("[AUDIT] %s\n", string(b)) } var auditLog = &AuditLogger{enabled: true} type Agent struct { cfg Config debug bool token string tokenID string oldToken string oldTokenExp time.Time uuid string apiHost string apiPort int uploadLimit int64 dataRoot string volumesDir string cfgPath string tokenMu sync.Mutex fsAnomaly *fsAnomalyTracker // Per-node panel admin signing secret (panel.hmac_secret in config.yml, // or PANEL_HMAC_SECRET env). Rotating it via /v1/panel/hmac-secret keeps // the outgoing secret valid for panelHMACRotationGrace so requests already // in flight still verify. panelHMACMu sync.RWMutex panelHMAC string panelHMACPrev string panelHMACPrevExp time.Time // Replay protection for panel-signed admin requests: nonces from // signature-valid requests are held until they leave the timestamp drift // window, so a captured request cannot be replayed while still valid. panelNonceMu sync.Mutex panelNonceCache map[string]int64 // panelRequireNonce rejects nonce-less (legacy) signed requests. On by // default (every current panel signs nonces); opt out via // PANEL_REQUIRE_NONCE=0 or panel.require_nonce: false for a legacy panel. panelRequireNonce bool stopGrace time.Duration docker Docker dl Downloader logs *logManager stdinMgr *stdinManager resourceStats *serverResourceStatsCache stopMu sync.Mutex stoppingNow map[string]time.Time // killPending is guarded by stopMu; startCancels by startAbortMu. killPending map[string]struct{} startAbortMu sync.Mutex startCancels map[string]context.CancelFunc commandMu sync.Mutex recentCommands map[string]recentConsoleCommand importProgressMu sync.RWMutex importProgress map[string]*ImportProgress importSem chan struct{} wsMu sync.Mutex wsSubscribers map[*wsSubscriber]struct{} metaLocks sync.Map serverOpLocks sync.Map // adpanel:backup-race - names with a long-running operation currently // holding the op lock, mapped to which kind (longOpBackup for backup // create/restore/delete, longOpReinstall for reinstall, // longOpRuntimeSeed for the runtime seed — all hold for // minutes-to-tens-of-minutes). Power ops consult it inside their bounded // acquireServerOpLockFailFast poll, and reinstall/runtime-seed consult it // via writeServerOpConflictResponse: queueing behind such a hold would run // them as phantom actions (their HTTP response dies at the 120s // server-wide WriteTimeout while the op still executes much later), so // they fail fast with a 409 that names the holder instead. longOpBusyNames sync.Map // adpanel:upload-atomicity - per-storage-scope upload serialization, keyed // by scope root (server dir or volume root) like serverOpLocks. The upload // routes hold it across the usage snapshot -> allowance -> transfer -> // commit window, so concurrent uploads to one scope cannot each validate // against the same pre-upload usage snapshot and jointly overshoot the // disk limit, and the temp-file commit of one upload can never interleave // with another upload's write to the same target. uploadScopeLocks sync.Map // adpanel:multidisk:fields (anchor) - per-server disk routing cache. Empty by // default => single-disk behavior preserved. disksMu sync.RWMutex serverDiskCache map[string]string // adpanel:cpu-sampling (anchor) - previous /proc/stat sample backing // delta-based node CPU utilization in handleSystemStats. cpuSampleMu is // held across the whole sample-and-maybe-double-read operation so // concurrent polls serialize into distinct sampling windows instead of // racing on lastCPUSample. cpuSampleMu sync.Mutex lastCPUSample cpuProcSample } const ( serverResourceStatsDefaultTTL = 2500 * time.Millisecond serverResourceStatsDiskTTL = 15 * time.Second serverResourceStatsMaxIdle = 10 * time.Minute ) type serverResourceStatsCache struct { ttl time.Duration diskTTL time.Duration mu sync.Mutex entries map[string]*serverResourceStatsCacheEntry } // deepCopyJSONValue returns a deep copy of a value composed of the dynamic // types produced by JSON-style payloads (map[string]any, []any and scalars). // It is used to hand out cached payloads safely: callers may freely mutate or // JSON-encode the returned value without racing against other goroutines that // share the same cached map. Without this, two concurrent requests for the // same server would mutate/encode the same cached map and trigger the runtime // "fatal error: concurrent map writes". func deepCopyJSONValue(v any) any { switch val := v.(type) { case map[string]any: if val == nil { return map[string]any(nil) } cp := make(map[string]any, len(val)) for k, item := range val { cp[k] = deepCopyJSONValue(item) } return cp case []any: if val == nil { return []any(nil) } cp := make([]any, len(val)) for i, item := range val { cp[i] = deepCopyJSONValue(item) } return cp case map[string]string: cp := make(map[string]string, len(val)) for k, item := range val { cp[k] = item } return cp default: // Scalars (string, numbers, bool, nil) and other immutable values are // safe to share by value. return val } } // deepCopyPayload deep-copies a top-level payload map. Returns nil for a nil // input so callers can preserve the "not found"/empty semantics. func deepCopyPayload(payload map[string]any) map[string]any { if payload == nil { return nil } cp, _ := deepCopyJSONValue(payload).(map[string]any) return cp } type serverResourceStatsCacheEntry struct { mu sync.Mutex payload map[string]any expiresAt time.Time touchedAt time.Time diskBytes int64 diskExpiresAt time.Time // adpanel:backup-storage - backups live in a separate directory outside the // server dir, so they are tracked (and cached) separately and then folded // into the reported/enforced "used" total. backupsBytes int64 backupsExpiresAt time.Time containerID string seenNetwork bool lastRawRx uint64 lastRawTx uint64 totalRx uint64 totalTx uint64 networkWindowStartedAt time.Time networkWindowInterval time.Duration networkWindowRx uint64 networkWindowTx uint64 } func newServerResourceStatsCache(ttl, diskTTL time.Duration) *serverResourceStatsCache { if ttl <= 0 { ttl = serverResourceStatsDefaultTTL } if diskTTL <= 0 { diskTTL = serverResourceStatsDiskTTL } return &serverResourceStatsCache{ ttl: ttl, diskTTL: diskTTL, entries: make(map[string]*serverResourceStatsCacheEntry), } } func (c *serverResourceStatsCache) get(name string) *serverResourceStatsCacheEntry { c.mu.Lock() defer c.mu.Unlock() entry := c.entries[name] if entry == nil { entry = &serverResourceStatsCacheEntry{} c.entries[name] = entry } return entry } func (c *serverResourceStatsCache) reset(name string) { if c == nil { return } c.mu.Lock() entry := c.entries[name] c.mu.Unlock() if entry != nil { entry.mu.Lock() entry.payload = nil entry.expiresAt = time.Time{} entry.mu.Unlock() } } func (c *serverResourceStatsCache) cleanup(maxIdle time.Duration) { if c == nil || maxIdle <= 0 { return } now := time.Now() cutoff := now.Add(-maxIdle) c.mu.Lock() defer c.mu.Unlock() for name, entry := range c.entries { entry.mu.Lock() windowRx, windowTx, _ := entry.currentNetworkWindow(now, entry.networkWindowInterval) idle := !entry.touchedAt.IsZero() && entry.touchedAt.Before(cutoff) && windowRx == 0 && windowTx == 0 entry.mu.Unlock() if idle { delete(c.entries, name) } } } func (e *serverResourceStatsCacheEntry) cachedDiskUsage(a *Agent, serverDir string, now time.Time, ttl time.Duration) int64 { if now.Before(e.diskExpiresAt) { return e.diskBytes } e.diskBytes = a.getServerDiskUsage(serverDir) e.diskExpiresAt = now.Add(ttl) return e.diskBytes } // cachedBackupsUsage returns the cached on-disk size of a server's backups // directory, refreshing it when the TTL elapses. adpanel:backup-storage - kept // on the same TTL as the disk scan so a stats request triggers at most one walk // of each tree. func (e *serverResourceStatsCacheEntry) cachedBackupsUsage(a *Agent, serverName string, now time.Time, ttl time.Duration) int64 { if now.Before(e.backupsExpiresAt) { return e.backupsBytes } e.backupsBytes = a.getServerBackupsUsage(serverName) e.backupsExpiresAt = now.Add(ttl) return e.backupsBytes } func addUint64Saturating(a, b uint64) uint64 { if ^uint64(0)-a < b { return ^uint64(0) } return a + b } func (e *serverResourceStatsCacheEntry) updateNetworkCounters(containerID string, rawRx, rawTx uint64, now time.Time, resetEvery time.Duration) (uint64, uint64, uint64, uint64, time.Time) { if containerID != "" && e.containerID != "" && containerID != e.containerID { e.lastRawRx = 0 e.lastRawTx = 0 e.totalRx = 0 e.totalTx = 0 e.seenNetwork = false } var rxDelta, txDelta uint64 if !e.seenNetwork { e.totalRx = rawRx e.totalTx = rawTx rxDelta = rawRx txDelta = rawTx } else { if rawRx >= e.lastRawRx { rxDelta = rawRx - e.lastRawRx } else { rxDelta = rawRx } if rawTx >= e.lastRawTx { txDelta = rawTx - e.lastRawTx } else { txDelta = rawTx } e.totalRx = rawRx e.totalTx = rawTx } if resetEvery > 0 { _, _, windowStartedAt := e.currentNetworkWindow(now, resetEvery) if windowStartedAt.IsZero() { e.networkWindowStartedAt = now e.networkWindowRx = 0 e.networkWindowTx = 0 } e.networkWindowInterval = resetEvery e.networkWindowRx = addUint64Saturating(e.networkWindowRx, rxDelta) e.networkWindowTx = addUint64Saturating(e.networkWindowTx, txDelta) } e.lastRawRx = rawRx e.lastRawTx = rawTx e.containerID = containerID e.seenNetwork = true return e.totalRx, e.totalTx, e.networkWindowRx, e.networkWindowTx, e.networkWindowStartedAt } type ImportProgress struct { Status string `json:"status"` Percent int `json:"percent"` Downloaded int64 `json:"downloaded"` Total int64 `json:"total"` Error string `json:"error,omitempty"` } func (a *Agent) logf(format string, args ...any) { if a.debug { fmt.Printf(format+"\n", args...) } } func (a *Agent) authOK(r *http.Request) bool { h := r.Header.Get("x-node-token") if h == "" { h = r.Header.Get("authorization") } t := strings.TrimSpace(h) if strings.HasPrefix(strings.ToLower(t), "bearer ") { t = strings.TrimSpace(t[7:]) } if t == "" { return false } a.tokenMu.Lock() currentToken := a.token oldToken := a.oldToken oldTokenExp := a.oldTokenExp tokenID := a.tokenID a.tokenMu.Unlock() if tokenID != "" { if reqTID := strings.TrimSpace(r.Header.Get("x-node-token-id")); reqTID != "" { if !timingSafeEq(reqTID, tokenID) { return false } } } if currentToken != "" && timingSafeEq(t, currentToken) { return true } if oldToken != "" && time.Now().Before(oldTokenExp) && timingSafeEq(t, oldToken) { return true } return false } const ( // panelSignDriftMillis is the lifetime of a panel-signed admin request: // requests whose x-panel-ts differs from local time by more than this are // rejected before the signature is evaluated. panelSignDriftMillis = 5 * 60 * 1000 // adpanel:panel-nonce-ttl - a future-dated signature can first arrive at // the early edge of its drift window and remain valid through the far edge. panelNonceTTL = 2*panelSignDriftMillis + 1 panelNonceMaxLen = 128 panelNonceSweepSize = 1024 // panelHMACRotationGrace keeps the outgoing panel signing secret valid // after /v1/panel/hmac-secret rotates it, so admin requests already in // flight when the rotation response was produced still verify. The panel // switches to the new secret immediately; this only bridges the gap. panelHMACRotationGrace = 60 * time.Second ) // envFlagTriState reads an explicit boolean from the environment. ok is false // when the variable is unset, blank, or not a recognized boolean token, so // callers can distinguish "operator explicitly set this" from "not // configured" — an explicit value always wins over defaults and config keys. func envFlagTriState(name string) (value, ok bool) { switch strings.ToLower(strings.TrimSpace(os.Getenv(name))) { case "1", "true", "yes", "on": return true, true case "0", "false", "no", "off": return false, true default: return false, false } } // resolvePanelRequireNonce computes whether nonce-less (legacy) panel // signatures are rejected. Replay protection is ON by default: every current // panel release signs a fresh single-use nonce into each admin envelope, and // the nonce cache TTL (panelNonceTTL) covers the entire timestamp window // on both sides of the signed time, so requiring one closes the // ~5-minute replay window on plaintext links. Operators still running a panel // that predates nonce support can opt out explicitly: PANEL_REQUIRE_NONCE=0 // (or false/no/off) in the daemon environment, or panel.require_nonce: false // in config.yml. An explicit PANEL_REQUIRE_NONCE value always wins over the // config key. func resolvePanelRequireNonce(cfg Config) bool { if v, ok := envFlagTriState("PANEL_REQUIRE_NONCE"); ok { return v } // The config dialect parses a quoted require_nonce value as a STRING, so a // bare v.(bool) assertion would silently disable enforcement for // require_nonce: "true". Bools pass through, recognized strings map onto // their boolean (case-insensitive), and anything else falls through to the // default-ON below. if v := cfg.Any("panel", "require_nonce"); v != nil { switch t := v.(type) { case bool: return t case string: switch strings.ToLower(t) { case "true", "1": return true case "false", "0", "off": return false } } } return true } // resolveAPIBindHost returns the address the node API listens on. An explicit // operator setting (env API_HOST or config api.host, resolved by the caller // with env first, matching API_TLS_CERT/API_TLS_KEY precedence) always wins // verbatim. Unconfigured listeners default to loopback when serving plaintext // so a hand-written config.yml cannot silently expose the bearer token on // every interface, and to 0.0.0.0 when TLS is enabled (unchanged legacy // behavior — TLS configs were written against the wildcard default). func resolveAPIBindHost(configured string, sslEnabled bool) string { if configured != "" { return configured } if sslEnabled { return DefaultAPIHost } return DefaultAPILoopbackHost } // apiHostIsLoopback reports whether host confines the listener to the // machine's loopback interfaces. Hostnames cannot be proven loopback, and an // empty or wildcard address means every interface, so all of them fail // closed (report as non-loopback). func apiHostIsLoopback(host string) bool { addr, err := netip.ParseAddr(strings.TrimSpace(host)) if err != nil { return false } return addr.Unmap().IsLoopback() } // plaintextNonLoopbackWarningLines returns the actionable warning printed // when the API serves plaintext HTTP on a non-loopback address, or nil when // the listener is loopback-only (plaintext exposure is local by // construction). func plaintextNonLoopbackWarningLines(host string) []string { if apiHostIsLoopback(host) { return nil } return []string{ fmt.Sprintf("[security] WARNING: the node API is serving plaintext HTTP on non-loopback address %s — the bearer token and panel HMAC secret are readable by anyone on the path.", host), "[security] WARNING: bind it to the panel-reachable interface with API_HOST (env) or api.host (config.yml), or enable TLS via api.ssl.enabled with api.ssl.cert/api.ssl.key (env: API_TLS_CERT, API_TLS_KEY).", } } // panelHMACSecrets returns the active panel signing secret plus the outgoing // one while its rotation grace window is still open. Readers snapshot both // under the read lock and verify without holding it (verification is pure // CPU over immutable copies). func (a *Agent) panelHMACSecrets() (current, previous string, previousLive bool) { a.panelHMACMu.RLock() defer a.panelHMACMu.RUnlock() return a.panelHMAC, a.panelHMACPrev, a.panelHMACPrev != "" && time.Now().Before(a.panelHMACPrevExp) } // setPanelHMAC swaps the panel signing secret and keeps the outgoing value // accepted for grace, mirroring the token rotation semantics. func (a *Agent) setPanelHMAC(newSecret string, grace time.Duration) { a.panelHMACMu.Lock() defer a.panelHMACMu.Unlock() a.panelHMACPrev = a.panelHMAC a.panelHMACPrevExp = time.Now().Add(grace) a.panelHMAC = newSecret } // validPanelNonce restricts nonces to alphanumeric values so they cannot // smuggle the "|" field separator or control characters into the signed base // string or logs. func validPanelNonce(nonce string) bool { if len(nonce) < 16 || len(nonce) > panelNonceMaxLen { return false } for i := 0; i < len(nonce); i++ { c := nonce[i] if (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') { continue } return false } return true } // recordPanelNonce marks nonce as seen until now+panelNonceTTL and reports // whether it was fresh. It runs only after the signature verified, so // unauthenticated traffic cannot poison the cache. func (a *Agent) recordPanelNonce(nonce string, now int64) bool { a.panelNonceMu.Lock() defer a.panelNonceMu.Unlock() if a.panelNonceCache == nil { a.panelNonceCache = make(map[string]int64) } if exp, ok := a.panelNonceCache[nonce]; ok && exp > now { return false } if len(a.panelNonceCache) >= panelNonceSweepSize { for k, exp := range a.panelNonceCache { if exp <= now { delete(a.panelNonceCache, k) } } } a.panelNonceCache[nonce] = now + panelNonceTTL return true } func (a *Agent) verifyPanelSignature(r *http.Request, name string, providerId, versionId, u string, bodyTS any) (bool, string) { base := fmt.Sprintf("%s|%s|%s|%s", strings.TrimSpace(name), providerId, versionId, u) return a.verifyPanelSignedEnvelope(r, base) } func (a *Agent) verifyReinstallAdminRequest(r *http.Request, name, template string) (bool, string) { role := strings.ToLower(strings.TrimSpace(r.Header.Get("x-panel-role"))) if role != "admin" { return false, "admin-required" } base := fmt.Sprintf("%s|%s|%s|%s", strings.TrimSpace(name), "reinstall", template, role) return a.verifyPanelSignedEnvelope(r, base) } func (a *Agent) nodeInformationPath() string { return filepath.Join(a.dataRoot, NodeInfoFileName) } func (a *Agent) defaultNodeInformation() NodeInformation { return NodeInformation{ NodeVersion: normalizeNodeVersionTag(NodeVersion), NodeArchitecture: runtime.GOOS + "/" + runtime.GOARCH, NodeAutoUpdate: false, } } func (a *Agent) readNodeInformation() NodeInformation { info := a.defaultNodeInformation() b, err := os.ReadFile(a.nodeInformationPath()) if err != nil || len(bytes.TrimSpace(b)) == 0 { return info } // Version honesty: the running binary's compile-time NodeVersion is the // only source of truth for the version that is actually executing. A // persisted value let a failed or never-activated update claim success — // /v1/update/info reported the new version while the old binary was still // running, so the panel showed the node as "up to date" and auto-update // skipped it forever. Architecture, auto-update preference, updatedAt and // disks are genuine persisted node state and keep being honored. var arr []NodeInformation if err := json.Unmarshal(b, &arr); err == nil && len(arr) > 0 { if arr[0].NodeArchitecture != "" { info.NodeArchitecture = arr[0].NodeArchitecture } info.NodeAutoUpdate = arr[0].NodeAutoUpdate info.UpdatedAt = arr[0].UpdatedAt info.Disks = arr[0].Disks return info } var obj NodeInformation if err := json.Unmarshal(b, &obj); err == nil { if obj.NodeArchitecture != "" { info.NodeArchitecture = obj.NodeArchitecture } info.NodeAutoUpdate = obj.NodeAutoUpdate info.UpdatedAt = obj.UpdatedAt info.Disks = obj.Disks } return info } func (a *Agent) writeNodeInformation(info NodeInformation) error { if err := ensureDir(a.dataRoot); err != nil { return err } if info.NodeVersion == "" { info.NodeVersion = normalizeNodeVersionTag(NodeVersion) } else { info.NodeVersion = normalizeNodeVersionTag(info.NodeVersion) } if info.NodeArchitecture == "" { info.NodeArchitecture = runtime.GOOS + "/" + runtime.GOARCH } info.UpdatedAt = time.Now().UTC().Format(time.RFC3339) b, err := json.MarshalIndent([]NodeInformation{info}, "", " ") if err != nil { return err } b = append(b, '\n') return writeFileNoFollow(a.nodeInformationPath(), b, 0o644) } func (a *Agent) ensureNodeInformationFile() NodeInformation { info := a.readNodeInformation() if _, err := os.Stat(a.nodeInformationPath()); err != nil { if writeErr := a.writeNodeInformation(info); writeErr != nil { fmt.Fprintf(os.Stderr, "[node-update] failed to initialize %s: %v\n", NodeInfoFileName, writeErr) } } return info } func (a *Agent) writeNodeUpdateFile(rel string, data []byte, backupDir string) error { if !allowedNodeUpdateFile(rel) { return fmt.Errorf("file is not allowed: %s", rel) } if err := validateNodeUpdateFileContent(rel, data); err != nil { return err } if err := ensureDir(a.dataRoot); err != nil { return err } target := filepath.Join(a.dataRoot, rel) resolvedRoot, err := filepath.Abs(a.dataRoot) if err != nil { return err } resolvedTarget, err := filepath.Abs(target) if err != nil { return err } if resolvedTarget != resolvedRoot && !strings.HasPrefix(resolvedTarget, resolvedRoot+string(filepath.Separator)) { return fmt.Errorf("refusing path outside node root: %s", rel) } if st, err := os.Lstat(target); err == nil && st.Mode().IsRegular() && backupDir != "" { if err := copyRegularFile(target, filepath.Join(backupDir, rel)); err != nil { return fmt.Errorf("backup failed for %s: %w", rel, err) } } tmp := filepath.Join(a.dataRoot, fmt.Sprintf(".%s.tmp.%d", rel, time.Now().UnixNano())) if err := writeFileNoFollow(tmp, data, 0o644); err != nil { return err } if err := os.Rename(tmp, target); err != nil { _ = os.Remove(tmp) return err } return nil } // goToolchainDir returns the directory holding the shared Go build state used // for update installs (gopath/gocache/gomodcache subdirs) and the staging area // for freshly built binaries. The ADPANEL_NODE_GO_DIR override exists so tests // can redirect the whole toolchain state into a scratch directory and run // hermetically instead of touching /var/lib/gonode. func goToolchainDir() string { if dir := strings.TrimSpace(os.Getenv("ADPANEL_NODE_GO_DIR")); dir != "" { return dir } return "/var/lib/gonode" } // goBinaryPath resolves the go toolchain binary. The systemd unit's PATH now // leads with /usr/local/go/bin, but the OpenRC and SysV units export no PATH // at all, units written by older installers may not include it, and a // gonode-local toolchain must win when present — hence the fallback chain // before giving up. func goBinaryPath() (string, error) { if p, err := exec.LookPath("go"); err == nil { return p, nil } candidates := []string{ "/usr/local/go/bin/go", filepath.Join(goToolchainDir(), "go", "bin", "go"), } for _, c := range candidates { if st, err := os.Stat(c); err == nil && !st.IsDir() { return c, nil } } return "", fmt.Errorf("go toolchain not found (tried PATH lookup, %s)", strings.Join(candidates, ", ")) } // buildAdaemonBinary compiles the sources in a.dataRoot (the pushed update // payload) into a staging file under goToolchainDir, then verifies the // artifact with its --version self-check before it is allowed to replace the // running binary. This supersedes the old `go clean` pre-step: Go's // content-addressed build cache has no staleness hazard, so nothing needs // clearing — the build itself is what produces the new binary. func (a *Agent) buildAdaemonBinary(ctx context.Context, expectedVersion string) (stagingPath string, err error) { goDir := goToolchainDir() if err := os.MkdirAll(goDir, 0o750); err != nil { return "", fmt.Errorf("failed to prepare build staging dir %s: %w", goDir, err) } // Sweep staging artifacts orphaned by daemon generations that died // mid-build: a kill -9/OOM/power loss never reaches the error-path // cleanup below, and without a sweep the ~20MB adnode.update- // files would accumulate unboundedly. A build+verify cycle is bounded // at ~10m15s, so anything older than an hour is definitively stale; // sweeping here — serialized by the install mutex — bounds the // accumulation without ever touching a build that could still be in // flight from a freshly restarted process. if stale, gerr := filepath.Glob(filepath.Join(goDir, "adnode.update-*")); gerr == nil { cutoff := time.Now().Add(-time.Hour) for _, s := range stale { if fi, serr := os.Stat(s); serr == nil && fi.ModTime().Before(cutoff) { _ = os.Remove(s) } } } goBin, err := goBinaryPath() if err != nil { return "", err } staging := filepath.Join(goDir, fmt.Sprintf("adnode.update-%d", os.Getpid())) bctx, cancel := context.WithTimeout(ctx, 10*time.Minute) defer cancel() cmd := exec.CommandContext(bctx, goBin, "build", "-trimpath", "-buildvcs=false", "-ldflags", "-s -w", "-o", staging, ".") cmd.Dir = a.dataRoot // Appended AFTER os.Environ() so these win over any inherited values. env := os.Environ() env = append(env, "GOPATH="+filepath.Join(goDir, "gopath")) env = append(env, "GOCACHE="+filepath.Join(goDir, "gocache")) env = append(env, "GOMODCACHE="+filepath.Join(goDir, "gomodcache")) cmd.Env = env out, err := cmd.CombinedOutput() if bctx.Err() == context.DeadlineExceeded { _ = os.Remove(staging) return "", fmt.Errorf("go build timed out") } if err != nil { _ = os.Remove(staging) msg := strings.TrimSpace(string(out)) if len(msg) > 400 { msg = msg[:400] } if msg == "" { msg = err.Error() } return "", fmt.Errorf("go build failed: %s", msg) } // Verify the artifact: a build that "succeeds" but does not report the // target version must never be swapped in. vctx, vcancel := context.WithTimeout(ctx, 15*time.Second) defer vcancel() vout, verr := exec.CommandContext(vctx, staging, "--version").Output() got := strings.TrimSpace(string(vout)) if verr != nil || vctx.Err() == context.DeadlineExceeded || normalizeNodeVersionTag(got) != normalizeNodeVersionTag(expectedVersion) { _ = os.Remove(staging) return "", fmt.Errorf("built binary does not report the target version (got %q, want %q)", got, normalizeNodeVersionTag(expectedVersion)) } return staging, nil } // activateUpdatedDaemon replaces the running process image with the freshly // installed binary at activePath. It must only be called AFTER the success // response has been written and flushed, so the panel's 200 is already on the // wire before the image changes. syscall.Exec swaps the image in place: same // PID, systemd unit stays active, no privileges required (works under // NoNewPrivileges=true). Exec returns ONLY on failure — at that point the // on-disk binary already IS the new one, so fall back to the systemctl // restart attempt; in hardened deployments that fallback logs its own failure // (User=adaemon, NoNewPrivileges=true, no polkit rule refuse it), which is // expected and non-fatal: any later manual restart or reboot lands the new // binary, and /v1/update/info honestly keeps reporting the still-running old // version so the panel re-offers the update. func (a *Agent) activateUpdatedDaemon(activePath string) { go func() { time.Sleep(900 * time.Millisecond) // drain window, parity with the old restart scheduler if err := syscall.Exec(activePath, os.Args, os.Environ()); err != nil { fmt.Fprintf(os.Stderr, "[node-update] in-place re-exec of %s failed: %v; falling back to systemctl restart adaemon\n", activePath, err) restartAdaemonViaSystemctl() } }() } // restartAdaemonViaSystemctl is the fallback activation path when the // in-place re-exec could not start the new process image. func restartAdaemonViaSystemctl() { cmd := exec.Command("systemctl", "restart", "adaemon") out, err := cmd.CombinedOutput() if err != nil { msg := strings.TrimSpace(string(out)) if len(msg) > 400 { msg = msg[:400] } fmt.Fprintf(os.Stderr, "[node-update] systemctl restart adaemon failed: %v %s\n", err, msg) return } fmt.Println("[node-update] systemctl restart adaemon executed") } func (a *Agent) handleNodeUpdateInfo(w http.ResponseWriter, r *http.Request) { info := a.ensureNodeInformationFile() jsonWrite(w, 200, map[string]any{ "ok": true, "version": info.NodeVersion, "architecture": info.NodeArchitecture, "autoUpdateEnabled": info.NodeAutoUpdate, "nodeId": a.uuid, }) } func (a *Agent) handleNodeUpdateAuto(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, 1024*1024) var payload nodeUpdateAutoRequest if err := json.NewDecoder(r.Body).Decode(&payload); err != nil && !errors.Is(err, io.EOF) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid request body"}) return } subject := "off" if payload.Enabled { subject = "on" } if ok, reason := a.verifyNodeAdminRequest(r, "node-update-auto", subject); !ok { jsonWrite(w, 403, map[string]any{"ok": false, "error": reason}) return } info := a.readNodeInformation() info.NodeAutoUpdate = payload.Enabled if err := a.writeNodeInformation(info); err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to save node information"}) return } jsonWrite(w, 200, map[string]any{"ok": true, "autoUpdateEnabled": payload.Enabled}) } // nodeUpdateInstallMu serializes node update installs: the write + build + // swap section takes minutes and concurrent installs must queue, never // interleave (otherwise one install's swap could race the other's source // writes and build). var nodeUpdateInstallMu sync.Mutex func (a *Agent) handleNodeUpdateInstall(w http.ResponseWriter, r *http.Request) { // The server-wide WriteTimeout is 120s and is armed once per request, but // everything this handler does before the response can outlive it: the // body decode reads up to a 20MB payload, nodeUpdateInstallMu can queue // behind a concurrent install's minutes-long build, the source-file write // loop hits disk, and the build+verify itself can run for up to ~10m15s. // Arm THIS connection's extension at the top so the deadline spans all of // it (ignored on writers without deadline support, e.g. // httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(12 * time.Minute)) r.Body = http.MaxBytesReader(w, r.Body, NodeUpdateMaxBody) var payload nodeUpdateInstallRequest if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid request body"}) return } version := normalizeNodeVersionTag(payload.Version) if !validNodeUpdateVersion(version) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid version"}) return } if ok, reason := a.verifyNodeAdminRequest(r, "node-update-install", version); !ok { jsonWrite(w, 403, map[string]any{"ok": false, "error": reason}) return } if len(payload.Files) == 0 || len(payload.Files) > 32 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid update file set"}) return } seenMain := false totalBytes := 0 decoded := make(map[string][]byte, len(payload.Files)) for _, file := range payload.Files { rel := strings.TrimSpace(file.Path) if !allowedNodeUpdateFile(rel) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "update contains an unsupported file"}) return } if _, exists := decoded[rel]; exists { jsonWrite(w, 400, map[string]any{"ok": false, "error": "duplicate update file"}) return } data, err := base64.StdEncoding.DecodeString(strings.TrimSpace(file.ContentBase64)) if err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid update file encoding"}) return } if err := validateNodeUpdateFileContent(rel, data); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": err.Error()}) return } totalBytes += len(data) if totalBytes > NodeUpdateMaxBody { jsonWrite(w, 413, map[string]any{"ok": false, "error": "update payload too large"}) return } if rel == "main.go" { seenMain = true } decoded[rel] = data } if !seenMain { jsonWrite(w, 400, map[string]any{"ok": false, "error": "main.go is required"}) return } // Serialize the write + build + swap section: builds take minutes and // concurrent installs must queue, never interleave. nodeUpdateInstallMu.Lock() defer nodeUpdateInstallMu.Unlock() backupDir := filepath.Join(a.dataRoot, ".update-backups", time.Now().UTC().Format("20060102-150405")) filesUpdated := 0 for rel, data := range decoded { if err := a.writeNodeUpdateFile(rel, data, backupDir); err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write update file", "filesUpdated": filesUpdated}) return } filesUpdated++ } // Resolve the active binary path BEFORE building: this is where the // verified artifact will be swapped in. For a deleted-but-running binary // /proc/self/exe reports the old path with a " (deleted)" suffix. activePath, err := os.Readlink("/proc/self/exe") if err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": fmt.Sprintf("failed to resolve the running binary path: %v", err), "filesUpdated": filesUpdated}) return } activePath = strings.TrimSuffix(activePath, " (deleted)") // Build + verify the new binary from the just-written sources. Deliberately // not tied to r.Context(): a build takes minutes and must not be aborted by // an impatient or disconnected HTTP client — the swap is the operation that // matters and response delivery is best-effort. staging, err := a.buildAdaemonBinary(context.Background(), version) if err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": err.Error(), "filesUpdated": filesUpdated}) return } // Swap the verified binary in. Rename over a running binary is legal on // Linux (atomic replace; the old inode stays open). If the rename or chmod // fails (EPERM/EROFS/EXDEV — e.g. a legacy layout where the unit still // executes the root-owned /usr/local/bin/adnode and this daemon is // unprivileged), fail closed: nothing is activated, the old binary keeps // running and /v1/update/info keeps honestly reporting it. if err := os.Rename(staging, activePath); err != nil { jsonWrite(w, 500, map[string]any{ "ok": false, "error": fmt.Sprintf("failed to replace the running binary %s: %v; the verified new binary remains at %s — re-run install-daemon.sh to migrate this deployment to the self-update layout", activePath, err, staging), "filesUpdated": filesUpdated, }) return } if err := os.Chmod(activePath, 0o755); err != nil { jsonWrite(w, 500, map[string]any{ "ok": false, "error": fmt.Sprintf("failed to set executable permissions on the replaced binary %s: %v — re-run install-daemon.sh to migrate this deployment to the self-update layout", activePath, err), "filesUpdated": filesUpdated, }) return } jsonWrite(w, 200, map[string]any{ "ok": true, "version": version, "filesUpdated": filesUpdated, "restartCommand": "systemctl restart adaemon", "message": "Node update installed: sources written, binary rebuilt from them and verified at " + version + ", activated in place. The daemon re-executes momentarily; no manual restart needed.", }) // The success response must be on the wire before the process image changes. _ = http.NewResponseController(w).Flush() a.activateUpdatedDaemon(activePath) } const ( wsMaxSubscribers = 5 wsStatusIntervalSec = 10 wsWriteTimeout = 5 * time.Second wsReadTimeout = 60 * time.Second ) type wsSubscriber struct { msgs chan []byte done chan struct{} } // isRestoreStagingName reports whether name matches the exact sibling // staging-directory format the wipe-restore creates under the volumes root: // .restore-staging- (adpanel:restore-staging — a // crash may leave a staged or previous tree behind, but it must not appear // in enumerateServerNames). The suffix after the LAST ".restore-staging-" marker // must be a non-empty decimal run parseable as int64 — exactly what // time.Now().UnixMilli() formats. // // Collision note: sanitizeName keeps dots, so a DELIBERATELY crafted server // name ending in ".restore-staging-" would match and be hidden from // enumeration. That is the accepted reservation of the marker — the same // trade isArchiveTempName makes for archive temps — and it requires an // admin-chosen name shaped like an internal staging path, not any dot-bearing // name. func isRestoreStagingName(name string) bool { const marker = ".restore-staging-" i := strings.LastIndex(name, marker) if i <= 0 { return false } digits := name[i+len(marker):] if digits == "" { return false } for j := 0; j < len(digits); j++ { if digits[j] < '0' || digits[j] > '9' { return false } } _, err := strconv.ParseInt(digits, 10, 64) return err == nil } // enumerateServerNames returns the unique set of server directory names across // every registered disk's volumes root (primary first), preserving discovery // order. adpanel:multidisk - this is the single source of truth for "which // servers exist on this node". Reading only a.volumesDir would silently drop // every server that lives on a secondary disk, which is why status/stats and the // server listing previously reported secondary-disk servers as missing (no live // metrics, power state stuck at "idle"/unknown). func (a *Agent) enumerateServerNames() []string { var names []string seen := map[string]struct{}{} for _, root := range a.allDiskVolumeRoots() { entries, err := os.ReadDir(root) if err != nil { // A secondary disk may be temporarily unmounted/unreadable. Skip it // rather than failing the whole enumeration so the remaining disks // (including the primary) still report correctly. continue } for _, e := range entries { if !e.IsDir() || strings.HasPrefix(e.Name(), ".") { continue } // adpanel:restore-staging - skip leftover wipe-restore staging // siblings so a mid-swap failure or crash does not leave a phantom // server entry in status/stats and the server listing. if isRestoreStagingName(e.Name()) { continue } name := e.Name() if _, dup := seen[name]; dup { continue } seen[name] = struct{}{} names = append(names, name) } } return names } // panelManagedContainerNames returns the set of Docker container names the // panel owns: dockerContainerName applied to every server discovered by // enumerateServerNames. Host-wide container enumerations (the memory // monitor's `docker ps` sweep) must filter against this set so co-hosted // containers the panel does not manage are never stopped or killed. func (a *Agent) panelManagedContainerNames() map[string]struct{} { owned := make(map[string]struct{}) if a == nil { return owned } for _, name := range a.enumerateServerNames() { owned[dockerContainerName(name)] = struct{}{} } return owned } func (a *Agent) collectServerStatuses() map[string]any { names := a.enumerateServerNames() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() var servers []ServerStatus for _, name := range names { serverDir := a.serverDir(name) ss := ServerStatus{Name: name, Status: "stopped"} meta := a.loadMeta(serverDir) cpuCoresConfig := metaCpuCores(meta) _, cpuLimit := computeCpuLimit(cpuCoresConfig) ss.CpuLimit = &cpuLimit if a.docker.containerExists(ctx, name) { out, _, _, err := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.Running}}", name) if err == nil && strings.TrimSpace(out) == "true" { ss.Status = "running" startedAt, _, _, startErr := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.StartedAt}}", name) if startErr == nil && strings.TrimSpace(startedAt) != "" { startTime, parseErr := time.Parse(time.RFC3339Nano, strings.TrimSpace(startedAt)) if parseErr == nil { uptime := int64(time.Since(startTime).Seconds()) ss.Uptime = &uptime } } statsOut, _, _, statsErr := a.docker.runCollect(ctx, "stats", "--no-stream", "--format", "{{.CPUPerc}}|{{.MemUsage}}", name) if statsErr == nil && strings.TrimSpace(statsOut) != "" { parts := strings.Split(strings.TrimSpace(statsOut), "|") if len(parts) >= 2 { cpuStr := strings.TrimSuffix(strings.TrimSpace(parts[0]), "%") if cpu, err := strconv.ParseFloat(cpuStr, 64); err == nil { if cpu > cpuLimit { cpu = cpuLimit } ss.CPU = &cpu } memParts := strings.Split(parts[1], "/") if len(memParts) >= 1 { memMb := parseMemoryString(strings.TrimSpace(memParts[0])) if memMb > 0 { ss.Memory = &memMb } } } } } } diskBytes := a.getServerTotalUsage(serverDir) if diskBytes > 0 { diskMb := float64(diskBytes) / (1024 * 1024) ss.Disk = &diskMb } servers = append(servers, ss) } return map[string]any{ "type": "status", "ok": true, "nodeId": a.uuid, "timestamp": time.Now().UnixMilli(), "servers": servers, "resources": map[string]any{ "cpuCount": runtime.NumCPU(), }, } } func (a *Agent) handleWebSocket(w http.ResponseWriter, r *http.Request) { conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{}) if err != nil { if a.debug { fmt.Printf("[ws] accept error: %v\n", err) } return } sub := &wsSubscriber{ msgs: make(chan []byte, 4), done: make(chan struct{}), } a.wsMu.Lock() if a.wsSubscribers == nil { a.wsSubscribers = make(map[*wsSubscriber]struct{}) } if len(a.wsSubscribers) >= wsMaxSubscribers { a.wsMu.Unlock() conn.Close(websocket.StatusTryAgainLater, "too many connections") return } a.wsSubscribers[sub] = struct{}{} a.wsMu.Unlock() defer func() { conn.Close(websocket.StatusNormalClosure, "closing") a.wsMu.Lock() delete(a.wsSubscribers, sub) a.wsMu.Unlock() close(sub.done) }() fmt.Printf("[ws] panel connected (subscribers: %d)\n", func() int { a.wsMu.Lock() defer a.wsMu.Unlock() return len(a.wsSubscribers) }()) snapshot := a.collectServerStatuses() ctx, cancel := context.WithTimeout(r.Context(), wsWriteTimeout) _ = wsjson.Write(ctx, conn, snapshot) cancel() go func() { for { _, _, err := conn.Read(r.Context()) if err != nil { return } } }() ticker := time.NewTicker(wsStatusIntervalSec * time.Second) defer ticker.Stop() for { select { case <-r.Context().Done(): fmt.Printf("[ws] panel disconnected\n") return case <-ticker.C: status := a.collectServerStatuses() data, err := json.Marshal(status) if err != nil { continue } writeCtx, writeCancel := context.WithTimeout(r.Context(), wsWriteTimeout) err = conn.Write(writeCtx, websocket.MessageText, data) writeCancel() if err != nil { if a.debug { fmt.Printf("[ws] write error: %v\n", err) } return } case msg := <-sub.msgs: writeCtx, writeCancel := context.WithTimeout(r.Context(), wsWriteTimeout) err := conn.Write(writeCtx, websocket.MessageText, msg) writeCancel() if err != nil { if a.debug { fmt.Printf("[ws] write error: %v\n", err) } return } } } } func (a *Agent) broadcastContainerEvent(name, status string) { a.broadcastContainerEventWithMeta(name, status, nil) } func (a *Agent) broadcastContainerEventWithMeta(name, status string, extras map[string]any) { a.wsMu.Lock() subs := make([]*wsSubscriber, 0, len(a.wsSubscribers)) for s := range a.wsSubscribers { subs = append(subs, s) } a.wsMu.Unlock() if len(subs) == 0 { return } evt := map[string]any{ "type": "event", "nodeId": a.uuid, "timestamp": time.Now().UnixMilli(), "server": name, "status": status, } for k, v := range extras { evt[k] = v } data, err := json.Marshal(evt) if err != nil { return } for _, s := range subs { select { case s.msgs <- data: default: } } } func statUIDGID(p string) (uid, gid int) { uid, gid = 1000, 1000 st, err := os.Stat(p) if err != nil { return } sys, ok := st.Sys().(*syscall.Stat_t) if !ok { return } return int(sys.Uid), int(sys.Gid) } const ( cpuPeriod = 100000 defaultPidsLimit = 512 minIoWeight = 10 maxIoWeight = 1000 minCpuWeight = 1 maxCpuWeight = 1000 minPidsLimit = 64 maxPidsLimit = 4096 minFileLimit = 1024 maxFileLimit = 1048576 minNetworkLimitMb int64 = 1 maxNetworkLimitMb int64 = 1073741824 defaultNetworkResetMins = 1440 minNetworkResetMins = 1 maxNetworkResetMins = 43200 ) func dockerCpuSharesFromWeight(weight int) int64 { if weight <= 0 { return 0 } if weight < minCpuWeight { weight = minCpuWeight } if weight > maxCpuWeight { weight = maxCpuWeight } shares := int64((weight * 2048) / maxCpuWeight) if shares < 2 { return 2 } return shares } func runtimeNeedsHighFileLimit(tpl, imageRef string) bool { tpl = strings.ToLower(strings.TrimSpace(tpl)) imageRef = strings.ToLower(strings.TrimSpace(imageRef)) if tpl == "rust" { return true } return strings.Contains(imageRef, "pterodactyl/games:rust") || strings.Contains(imageRef, "parkervcp/games:rust") || strings.Contains(imageRef, "didstopia/rust-server") } func withRuntimeDefaultFileLimit(resources *resourceLimits, tpl, imageRef string) *resourceLimits { if !runtimeNeedsHighFileLimit(tpl, imageRef) { return resources } if resources != nil && resources.FileLimit != nil { return resources } limit := maxFileLimit if resources == nil { return &resourceLimits{FileLimit: &limit} } copy := *resources copy.FileLimit = &limit return © } const rustPterodactylStartup = `./RustDedicated -batchmode -nographics -logfile "{{LOG_FILE}}" +server.ip 0.0.0.0 +server.port {{SERVER_PORT}} +server.queryport {{QUERY_PORT}} +server.identity "{{SERVER_IDENTITY}}" +server.level "{{SERVER_LEVEL}}" +server.seed {{SERVER_SEED}} +server.worldsize {{WORLD_SIZE}} +server.hostname "{{SERVER_NAME}}" +server.description "{{SERVER_DESCRIPTION}}" +server.maxplayers {{MAX_PLAYERS}} +server.secure {{SERVER_SECURE}} +rcon.ip 0.0.0.0 +rcon.web {{RCON_WEB}} +rcon.port {{RCON_PORT}} +rcon.password "{{RCON_PASS}}" +app.port {{RUST_PLUS_PORT}} +server.saveinterval {{SAVE_INTERVAL}} {{ADDITIONAL_ARGS}}` func normalizeRustRuntimeForPterodactyl(meta map[string]any) bool { if meta == nil { return false } template := normalizeTemplateIdentifier(meta["template"]) if template == "" { template = normalizeTemplateIdentifier(meta["type"]) } if template != "" && template != "rust" { return false } runtimeObj, _ := meta["runtime"].(map[string]any) image := "" tag := "" if runtimeObj != nil { image = strings.ToLower(strings.TrimSpace(fmt.Sprint(runtimeObj["image"]))) tag = strings.ToLower(strings.TrimSpace(fmt.Sprint(runtimeObj["tag"]))) } imageRef := image + ":" + tag isRust := template == "rust" || strings.Contains(imageRef, "didstopia/rust-server") || strings.Contains(imageRef, "pterodactyl/games:rust") || strings.Contains(imageRef, "parkervcp/games:rust") if !isRust { return false } if runtimeObj == nil { runtimeObj = map[string]any{} } changed := false set := func(key string, value any) { if !reflect.DeepEqual(runtimeObj[key], value) { runtimeObj[key] = value changed = true } } set("image", "ghcr.io/pterodactyl/games") set("tag", "rust") set("volumes", []any{"{BOT_DIR}:/home/container"}) set("workdir", "/home/container") set("command", "") set("adpanelStartup", "") set("startupDisplay", "/bin/bash /entrypoint.sh") set("ports", []any{28015, 28016, 28082}) set("portProtocols", map[string]any{ "28015": []any{"udp"}, "28016": []any{"tcp", "udp"}, "28082": []any{"tcp", "udp"}, }) set("console", map[string]any{ "type": "stdin", "targetProcesses": []any{"RustDedicated"}, }) env := runtimeEnvMap(runtimeObj["env"]) if env == nil { env = map[string]string{} } copyEnv := func(dst, src string) { if strings.TrimSpace(env[dst]) == "" && strings.TrimSpace(env[src]) != "" { env[dst] = env[src] changed = true } } copyEnv("SERVER_IDENTITY", "RUST_SERVER_IDENTITY") copyEnv("SERVER_PORT", "RUST_SERVER_PORT") copyEnv("QUERY_PORT", "RUST_SERVER_QUERYPORT") copyEnv("SERVER_SEED", "RUST_SERVER_SEED") copyEnv("WORLD_SIZE", "RUST_SERVER_WORLDSIZE") copyEnv("SERVER_NAME", "RUST_SERVER_NAME") copyEnv("SERVER_DESCRIPTION", "RUST_SERVER_DESCRIPTION") copyEnv("MAX_PLAYERS", "RUST_SERVER_MAXPLAYERS") copyEnv("RCON_PORT", "RUST_RCON_PORT") copyEnv("RCON_PASS", "RUST_RCON_PASSWORD") copyEnv("RUST_PLUS_PORT", "RUST_APP_PORT") envDefaults := map[string]string{ "STARTUP": rustPterodactylStartup, "AUTO_UPDATE": "0", "FRAMEWORK": "", "OXIDE": "0", "LD_LIBRARY_PATH": "/home/container/RustDedicated_Data/Plugins/x86_64:/home/container", "LOG_FILE": "/home/container/logs/rust.log", "SERVER_PORT": "28015", "QUERY_PORT": "28016", "RCON_PORT": "28016", "RUST_PLUS_PORT": "28082", "SERVER_IDENTITY": "adpanel", "SERVER_LEVEL": "Procedural Map", "SERVER_SEED": "12345", "WORLD_SIZE": "3500", "SERVER_NAME": "ADPanel Rust Server", "SERVER_DESCRIPTION": "Rust server hosted with ADPanel", "MAX_PLAYERS": "100", "SERVER_SECURE": "1", "RCON_WEB": "true", "RCON_PASS": "change-me", "RCON_PASSWORD": "change-me", "RCON_IP": "127.0.0.1", "SAVE_INTERVAL": "300", "ADDITIONAL_ARGS": "", "TZ": "Etc/UTC", } for key, value := range envDefaults { if _, ok := env[key]; !ok { env[key] = value changed = true } } if env["RCON_PASSWORD"] != env["RCON_PASS"] { env["RCON_PASSWORD"] = env["RCON_PASS"] changed = true } if !reflect.DeepEqual(runtimeObj["env"], env) { runtimeObj["env"] = env changed = true } if meta["type"] != "rust" { meta["type"] = "rust" changed = true } if meta["template"] != "rust" { meta["template"] = "rust" changed = true } if !reflect.DeepEqual(meta["runtime"], runtimeObj) { meta["runtime"] = runtimeObj changed = true } return changed } func computeCpuLimit(allocatedCores float64) (effectiveCores, maxPercent float64) { hostCores := float64(runtime.NumCPU()) if hostCores <= 0 { hostCores = 1 } effectiveCores = hostCores if allocatedCores > 0 { effectiveCores = allocatedCores if effectiveCores > hostCores { effectiveCores = hostCores } } maxPercent = effectiveCores * 100 return } func metaCpuCores(meta map[string]any) float64 { if meta == nil { return 0 } res, ok := meta["resources"].(map[string]any) if !ok { return 0 } switch v := res["cpuCores"].(type) { case float64: return v case int: return float64(v) case int64: return float64(v) } return 0 } const ( defaultMinecraftProcessImage = "eclipse-temurin" defaultMinecraftProcessTag = "21-jre" defaultMinecraftProcessCommand = "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui" maxRuntimeCommandLen = 4000 ) var ( fallbackMinecraftJavaVersions = []string{"8", "11", "17", "21", "22", "23", "24", "25", "26"} minecraftJavaVersionsCache []string minecraftJavaVersionsCacheExpireAt time.Time minecraftJavaVersionsMu sync.Mutex ) const ( minecraftJavaMinVersion = 8 minecraftJavaMaxVersion = 99 minecraftJavaDiscoveryURL = "https://hub.docker.com/v2/repositories/library/eclipse-temurin/tags?page_size=100&name=-jre" minecraftJavaDiscoveryTimeout = 4500 * time.Millisecond minecraftJavaDiscoveryTTL = 6 * time.Hour minecraftJavaDiscoveryFailTTL = 5 * time.Minute ) type dockerHubTagsResponse struct { Next string `json:"next"` Results []struct { Name string `json:"name"` } `json:"results"` } func normalizeMinecraftJavaVersion(raw any) string { value := strings.TrimSpace(strings.ToLower(fmt.Sprint(raw))) if value == "" || value == "" { return "" } var digits strings.Builder for _, r := range value { if r < '0' || r > '9' { break } digits.WriteRune(r) } version := digits.String() if version == "" { return "" } parsed, err := strconv.Atoi(version) if err != nil || parsed < minecraftJavaMinVersion || parsed > minecraftJavaMaxVersion { return "" } return fmt.Sprint(parsed) } func minecraftJavaTag(version any) string { clean := normalizeMinecraftJavaVersion(version) if clean == "" { return defaultMinecraftProcessTag } return clean + "-jre" } func minecraftJavaVersionFromTag(raw any) string { tag := strings.TrimSpace(strings.ToLower(fmt.Sprint(raw))) if tag == "" || tag == "" { return "" } if idx := strings.LastIndex(tag, ":"); idx >= 0 && idx+1 < len(tag) { tag = tag[idx+1:] } return normalizeMinecraftJavaVersion(tag) } func cloneStringSlice(values []string) []string { if len(values) == 0 { return nil } out := make([]string, len(values)) copy(out, values) return out } func mergeMinecraftJavaVersions(discovered []string) []string { seen := make(map[int]struct{}) for _, raw := range fallbackMinecraftJavaVersions { if clean := normalizeMinecraftJavaVersion(raw); clean != "" { if n, err := strconv.Atoi(clean); err == nil { seen[n] = struct{}{} } } } for _, raw := range discovered { if clean := normalizeMinecraftJavaVersion(raw); clean != "" { if n, err := strconv.Atoi(clean); err == nil { seen[n] = struct{}{} } } } nums := make([]int, 0, len(seen)) for n := range seen { nums = append(nums, n) } sort.Ints(nums) out := make([]string, 0, len(nums)) for _, n := range nums { out = append(out, fmt.Sprint(n)) } return out } func extractMinecraftJavaVersionsFromDockerHubPayload(payload dockerHubTagsResponse) []string { versions := []string{} for _, result := range payload.Results { name := strings.TrimSpace(strings.ToLower(result.Name)) if !strings.HasSuffix(name, "-jre") { continue } prefix := strings.TrimSuffix(name, "-jre") if prefix == "" || strings.ContainsAny(prefix, ".-_") { continue } if version := normalizeMinecraftJavaVersion(prefix); version != "" { versions = append(versions, version) } } return versions } func discoverMinecraftJavaVersions(ctx context.Context) ([]string, bool) { discovered := []string{} nextURL := minecraftJavaDiscoveryURL client := &http.Client{Timeout: minecraftJavaDiscoveryTimeout} ok := false for page := 0; page < 5 && nextURL != ""; page++ { req, err := http.NewRequestWithContext(ctx, http.MethodGet, nextURL, nil) if err != nil { break } req.Header.Set("Accept", "application/json") resp, err := client.Do(req) if err != nil { break } func() { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { nextURL = "" return } ok = true var payload dockerHubTagsResponse if err := json.NewDecoder(io.LimitReader(resp.Body, 2*1024*1024)).Decode(&payload); err != nil { nextURL = "" return } discovered = append(discovered, extractMinecraftJavaVersionsFromDockerHubPayload(payload)...) next := strings.TrimSpace(payload.Next) if next == "" || !strings.HasPrefix(next, "https://hub.docker.com/v2/repositories/library/eclipse-temurin/tags") { nextURL = "" return } nextURL = next }() } return mergeMinecraftJavaVersions(discovered), ok } func minecraftJavaVersions() []string { now := time.Now() minecraftJavaVersionsMu.Lock() if len(minecraftJavaVersionsCache) > 0 && now.Before(minecraftJavaVersionsCacheExpireAt) { cached := cloneStringSlice(minecraftJavaVersionsCache) minecraftJavaVersionsMu.Unlock() return cached } minecraftJavaVersionsMu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), minecraftJavaDiscoveryTimeout) discovered, ok := discoverMinecraftJavaVersions(ctx) cancel() if len(discovered) == 0 { discovered = mergeMinecraftJavaVersions(nil) } minecraftJavaVersionsMu.Lock() minecraftJavaVersionsCache = cloneStringSlice(discovered) if ok { minecraftJavaVersionsCacheExpireAt = time.Now().Add(minecraftJavaDiscoveryTTL) } else { minecraftJavaVersionsCacheExpireAt = time.Now().Add(minecraftJavaDiscoveryFailTTL) } out := cloneStringSlice(minecraftJavaVersionsCache) minecraftJavaVersionsMu.Unlock() return out } func minecraftJavaOptionsPayload(selected string) map[string]any { selected = normalizeMinecraftJavaVersion(selected) if selected == "" { selected = minecraftJavaVersionFromTag(defaultMinecraftProcessTag) } if selected == "" { selected = "21" } versions := minecraftJavaVersions() hasSelected := false for _, version := range versions { if version == selected { hasSelected = true break } } if !hasSelected { versions = mergeMinecraftJavaVersions(append(versions, selected)) } options := make([]map[string]string, 0, len(versions)) for _, version := range versions { options = append(options, map[string]string{ "version": version, "tag": minecraftJavaTag(version), "label": "Java " + version, }) } return map[string]any{ "selected": selected, "image": defaultMinecraftProcessImage, "tag": minecraftJavaTag(selected), "options": options, } } func sanitizeRuntimeCommand(raw any) string { s := strings.ReplaceAll(fmt.Sprint(raw), "\r\n", "\n") s = strings.ReplaceAll(s, "\r", "\n") s = strings.TrimSpace(s) if len(s) > maxRuntimeCommandLen { s = s[:maxRuntimeCommandLen] } if s == "" { return "" } return s } func stripLegacyStartupCommandFields(meta map[string]any) bool { if meta == nil { return false } changed := false if _, ok := meta["startupCommand"]; ok { delete(meta, "startupCommand") changed = true } if runtimeObj, ok := meta["runtime"].(map[string]any); ok { if _, ok := runtimeObj["startupCommand"]; ok { delete(runtimeObj, "startupCommand") meta["runtime"] = runtimeObj changed = true } } return changed } func defaultStartFileForType(tpl string) string { switch strings.ToLower(strings.TrimSpace(tpl)) { case "minecraft": return "server.jar" case "python": return "main.py" case "nodejs", "discord-bot": return "index.js" default: return "" } } func defaultDataDirForType(tpl string) string { switch strings.ToLower(strings.TrimSpace(tpl)) { case "python", "nodejs", "discord-bot", "runtime": return "/app" case "fivem", "five-m", "redm": return cfxRuntimeServerDir default: return "/data" } } func hasManagedRuntimeDefaults(tpl string) bool { switch strings.ToLower(strings.TrimSpace(tpl)) { case "minecraft", "python", "nodejs", "discord-bot", "runtime": return true default: return false } } func isManagedProcessRuntime(tpl string) bool { switch strings.ToLower(strings.TrimSpace(tpl)) { case "python", "nodejs", "discord-bot", "runtime": return true default: return false } } func defaultRuntimeCommandForType(tpl, startFile, dataDir string) string { switch strings.ToLower(strings.TrimSpace(tpl)) { case "minecraft": return defaultMinecraftProcessCommand case "python": if startFile == "" { startFile = "main.py" } return fmt.Sprintf("python %s/%s", strings.TrimRight(dataDir, "/"), startFile) case "nodejs", "discord-bot": if startFile == "" { startFile = "index.js" } return fmt.Sprintf("node %s/%s", strings.TrimRight(dataDir, "/"), startFile) default: return "" } } func (a *Agent) inferRuntimeProcessCommandFromImage(ctx context.Context, tpl, imageRef, startFile, dataDir, fallbackCommand string) (string, string, imageConfig, error) { cleanTemplate := strings.ToLower(strings.TrimSpace(tpl)) cleanImageRef := strings.TrimSpace(imageRef) cleanStartFile := strings.TrimSpace(startFile) providedDataDir := strings.TrimSpace(dataDir) != "" cleanDataDir := strings.TrimSpace(dataDir) if cleanStartFile == "" { cleanStartFile = defaultStartFileForType(cleanTemplate) } if cleanDataDir == "" { cleanDataDir = defaultDataDirForType(cleanTemplate) } fallback := sanitizeRuntimeCommand(fallbackCommand) if fallback == "" { fallback = defaultRuntimeCommandForType(cleanTemplate, cleanStartFile, cleanDataDir) } inspected := imageConfig{Env: map[string]string{}} if cleanImageRef != "" { if !a.docker.imageExistsLocally(ctx, cleanImageRef) { a.docker.pull(ctx, cleanImageRef) } imgCfg := a.docker.inspectImageConfig(ctx, cleanImageRef) inspected = imgCfg if !providedDataDir { if wd := strings.TrimSpace(imgCfg.Workdir); wd != "" { cleanDataDir = wd } } candidate := runtimeCommandFromImageConfig(imgCfg) if candidate != "" { candidate = normalizeLegacyRuntimeProcessCommand(cleanTemplate, candidate, cleanStartFile, cleanDataDir) if shouldPreferImageDefaultRuntimeCommand(candidate, imgCfg) { return candidate, "image-default", inspected, nil } if reason := validateRuntimeProcessCommand(candidate); reason == "" { return candidate, "image-inspect", inspected, nil } } } fallback = normalizeLegacyRuntimeProcessCommand(cleanTemplate, fallback, cleanStartFile, cleanDataDir) if reason := validateRuntimeProcessCommand(fallback); reason != "" { return "", "", inspected, fmt.Errorf("%s", reason) } if fallback != "" { return fallback, "template-default", inspected, nil } return "", "", inspected, fmt.Errorf("no startup command could be inferred") } func metaIntValue(meta map[string]any, key string, fallback int) int { if meta == nil { return fallback } resources, _ := meta["resources"].(map[string]any) if resources == nil { return fallback } switch v := resources[key].(type) { case float64: return int(v) case int: return v case int64: return int(v) case string: if parsed, err := strconv.Atoi(strings.TrimSpace(v)); err == nil { return parsed } } return fallback } func metaFloatValue(meta map[string]any, key string, fallback float64) float64 { if meta == nil { return fallback } resources, _ := meta["resources"].(map[string]any) if resources == nil { return fallback } switch v := resources[key].(type) { case float64: return v case int: return float64(v) case int64: return float64(v) case string: if parsed, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil { return parsed } } return fallback } func effectiveRamMb(resources *resourceLimits, meta map[string]any, fallback int) int { if resources != nil && resources.RamMb != nil && *resources.RamMb > 0 { return *resources.RamMb } return metaIntValue(meta, "ramMb", fallback) } func effectiveCpuCores(resources *resourceLimits, meta map[string]any, fallback float64) float64 { if resources != nil && resources.CpuCores != nil && *resources.CpuCores > 0 { return *resources.CpuCores } return metaFloatValue(meta, "cpuCores", fallback) } func resourceLimitsFromMeta(meta map[string]any) *resourceLimits { rm, ok := meta["resources"].(map[string]any) if !ok || rm == nil { return nil } resources := &resourceLimits{} if v := anyToInt(rm["ramMb"]); v > 0 { i := v resources.RamMb = &i } if v := anyToFloat64(rm["cpuCores"]); v > 0 { resources.CpuCores = &v } if v := anyToInt(rm["storageMb"]); v > 0 { i := v resources.StorageMb = &i } else if v := anyToInt(rm["storageGb"]); v > 0 { i := v * 1024 resources.StorageMb = &i } if _, ok := rm["swapMb"]; ok { i := anyToInt(rm["swapMb"]) resources.SwapMb = &i } if v := anyToInt(rm["backupsMax"]); v > 0 { i := v resources.BackupsMax = &i } if v := anyToInt(rm["maxSchedules"]); v > 0 { i := v resources.MaxSchedules = &i } if v := anyToInt(rm["ioWeight"]); v > 0 { i := v resources.IoWeight = &i } if v := anyToInt(rm["cpuWeight"]); v > 0 { i := v resources.CpuWeight = &i } if v := anyToInt(rm["pidsLimit"]); v > 0 { i := v resources.PidsLimit = &i } if v := anyToInt(rm["fileLimit"]); v > 0 { i := v resources.FileLimit = &i } if v := anyToInt64(rm["networkInboundLimitMb"]); v > 0 { i := v resources.NetworkInboundLimitMb = &i } if v := anyToInt64(rm["networkOutboundLimitMb"]); v > 0 { i := v resources.NetworkOutboundLimitMb = &i } if v := anyToInt(rm["networkResetMinutes"]); v > 0 { i := v resources.NetworkResetMinutes = &i } return resources } func renderRuntimeCommandTemplate(command, dataDir, startFile, imageRef string, hostPort int, resources *resourceLimits, meta map[string]any, resolvedEnv ...map[string]string) string { cmd := sanitizeRuntimeCommand(command) if cmd == "" { return "" } ramMb := effectiveRamMb(resources, meta, 2048) cpuCores := effectiveCpuCores(resources, meta, 1) values := map[string]string{ "PORT": fmt.Sprint(hostPort), "SERVER_PORT": fmt.Sprint(hostPort), "DATA_DIR": dataDir, "START_FILE": startFile, "RAM_MB": fmt.Sprint(ramMb), "SERVER_MEMORY": fmt.Sprint(ramMb), "CPU_CORES": strconv.FormatFloat(cpuCores, 'f', -1, 64), "IMAGE": imageRef, } var env map[string]string if len(resolvedEnv) != 0 { env = resolvedEnv[0] } else if runtimeObj, ok := meta["runtime"].(map[string]any); ok { env = runtimeEnvMap(runtimeObj["env"]) } for key, value := range env { values[key] = value } placeholder := regexp.MustCompile(`\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}|\{(PORT|SERVER_PORT|DATA_DIR|START_FILE|RAM_MB|SERVER_MEMORY|CPU_CORES|IMAGE)\}`) rendered := placeholder.ReplaceAllStringFunc(cmd, func(token string) string { match := placeholder.FindStringSubmatch(token) key := match[1] if key == "" { key = match[2] } if key == "server.build.default.port" { if hostPort > 0 { return fmt.Sprint(hostPort) } return token } if strings.HasPrefix(key, "env.") { key = strings.TrimPrefix(key, "env.") } if value, ok := values[key]; ok { return value } return token }) return strings.TrimSpace(rendered) } func isPythonRuntimeExecutable(execName string) bool { execName = strings.ToLower(strings.TrimSpace(execName)) return execName == "python" || strings.HasPrefix(execName, "python3") || strings.HasPrefix(execName, "python2") } func isNodeRuntimeExecutable(execName string) bool { execName = strings.ToLower(strings.TrimSpace(execName)) return execName == "node" || execName == "nodejs" } func firstRuntimeCommandFileTarget(args []string, startIndex int, extensions map[string]bool) string { for i := startIndex + 1; i < len(args); i++ { token := strings.TrimSpace(args[i]) if token == "" || token == "--" { continue } if strings.HasPrefix(token, "-") { continue } ext := strings.ToLower(path.Ext(strings.SplitN(token, "?", 2)[0])) if extensions[ext] { return token } } return "" } func containerPathToServerPath(serverDir, dataDir, workdir, rawPath string) string { clean := strings.TrimSpace(rawPath) if clean == "" || strings.Contains(clean, "\x00") { return "" } clean = strings.ReplaceAll(clean, "\\", "/") var rel string if path.IsAbs(clean) { for _, root := range []string{dataDir, workdir} { root = path.Clean(strings.TrimSpace(root)) if root == "" || root == "." || root == "/" { continue } if clean == root { return "" } prefix := strings.TrimRight(root, "/") + "/" if strings.HasPrefix(clean, prefix) { rel = strings.TrimPrefix(clean, prefix) break } } if rel == "" { return "" } } else { rel = clean } rel = path.Clean("/" + rel) rel = strings.TrimPrefix(rel, "/") if rel == "" || rel == "." || rel == ".." || strings.HasPrefix(rel, "../") { return "" } return filepath.Join(serverDir, filepath.FromSlash(rel)) } func parseVolumeSpecContainerPath(spec string) string { parts := strings.Split(spec, ":") if len(parts) < 2 { return "" } containerPath := strings.TrimSpace(parts[1]) if idx := strings.LastIndex(containerPath, ":"); idx > 0 { containerPath = containerPath[:idx] } return strings.TrimSpace(containerPath) } func replaceVolumeSpecContainerPath(spec, containerPath string) string { cleanTarget := strings.TrimSpace(containerPath) if cleanTarget == "" { return spec } parts := strings.Split(spec, ":") if len(parts) < 2 { return spec } parts[1] = cleanTarget return strings.Join(parts, ":") } func imageConfigHasRuntimeDefault(cfg imageConfig) bool { return len(trimRuntimeProcessArgs(cfg.Entrypoint)) > 0 || len(trimRuntimeProcessArgs(cfg.Cmd)) > 0 } func imageConfigDeclaresVolume(cfg imageConfig, containerPath string) bool { cleanPath := path.Clean(strings.TrimSpace(containerPath)) if cleanPath == "." || cleanPath == "/" || cleanPath == "" { return false } for _, volumePath := range cfg.Volumes { if path.Clean(strings.TrimSpace(volumePath)) == cleanPath { return true } } return false } func imageUsesPterodactylContainerWorkdir(imageRef string, imgCfg imageConfig) bool { workdir := path.Clean(strings.TrimSpace(imgCfg.Workdir)) if workdir != "/home/container" { return false } imageLower := strings.ToLower(strings.TrimSpace(imageRef)) return strings.Contains(imageLower, "ghcr.io/pterodactyl/") || strings.Contains(imageLower, "ghcr.io/ptero-eggs/") || strings.Contains(imageLower, "ghcr.io/parkervcp/") || strings.Contains(imageLower, "pterodactyl/") } func (a *Agent) inspectRuntimeImageConfig(ctx context.Context, imageRef string) imageConfig { cleanImageRef := strings.TrimSpace(imageRef) if cleanImageRef == "" { return imageConfig{Env: map[string]string{}} } if !a.docker.imageExistsLocally(ctx, cleanImageRef) { a.docker.pull(ctx, cleanImageRef) } return a.docker.inspectImageConfig(ctx, cleanImageRef) } func sanitizeCustomImageDefaultBinds(imageRef string, imgCfg imageConfig, binds []string, dataDir string) ([]string, string) { workdir := path.Clean(strings.TrimSpace(imgCfg.Workdir)) if workdir == "" || workdir == "." || workdir == "/" || !imageConfigHasRuntimeDefault(imgCfg) || imageConfigDeclaresVolume(imgCfg, workdir) { return binds, dataDir } if imageUsesPterodactylContainerWorkdir(imageRef, imgCfg) { return binds, dataDir } gameDataPath := "" if isGameServerDockerImage(imageRef) { gameDataPath = path.Clean(getGameServerDataPath(imageRef)) } if gameDataPath == workdir { return binds, dataDir } if gameDataPath == "." || gameDataPath == "/" { gameDataPath = "" } changed := false out := make([]string, 0, len(binds)) for _, bind := range binds { containerPath := path.Clean(parseVolumeSpecContainerPath(bind)) if containerPath == workdir { if gameDataPath != "" { out = append(out, replaceVolumeSpecContainerPath(bind, gameDataPath)) if path.Clean(strings.TrimSpace(dataDir)) == workdir { dataDir = gameDataPath } changed = true fmt.Printf("[docker] remapped volume away from image workdir for %s: %s -> %s\n", imageRef, workdir, gameDataPath) continue } changed = true fmt.Printf("[docker] skipped volume that would hide image workdir for %s: %s\n", imageRef, bind) continue } out = append(out, bind) } if !changed { return binds, dataDir } if len(out) == 0 { return nil, "" } return out, dataDir } func runtimeStringSlice(raw any) []string { switch v := raw.(type) { case []string: out := make([]string, 0, len(v)) for _, entry := range v { clean := strings.TrimSpace(entry) if clean != "" && clean != "" { out = append(out, clean) } } return out case []any: out := make([]string, 0, len(v)) for _, entry := range v { clean := strings.TrimSpace(fmt.Sprint(entry)) if clean != "" && clean != "" { out = append(out, clean) } } return out default: return nil } } func runtimeIntSlice(raw any) []int { switch v := raw.(type) { case []int: out := make([]int, 0, len(v)) for _, entry := range v { if port, ok := parseStrictPortValue(entry); ok { out = append(out, port) } } return out case []float64: out := make([]int, 0, len(v)) for _, entry := range v { if port, ok := parseStrictPortValue(entry); ok { out = append(out, port) } } return out case []string: out := make([]int, 0, len(v)) for _, entry := range v { if port, ok := parseStrictPortValue(entry); ok { out = append(out, port) } } return out case []any: out := make([]int, 0, len(v)) for _, entry := range v { if port, ok := parseStrictPortValue(entry); ok { out = append(out, port) } } return out default: return nil } } func runtimeBool(raw any) bool { switch v := raw.(type) { case bool: return v case string: clean := strings.ToLower(strings.TrimSpace(v)) return clean == "1" || clean == "true" || clean == "yes" || clean == "on" case float64: return v != 0 case int: return v != 0 default: return false } } // Environment payloads originate from untrusted template JSON and reach // container processes through two sinks: the Docker Engine API "KEY=VALUE" // Env list (envMapToList) and `docker run -e KEY=VALUE` argv for installers // (dockerEnvArgs). Both split on the first "=", so the key inside the map // must BE the name the container sees: a key containing "=" would silently // rename the variable and could carry a different name past any key-based // allowlist/denylist. Whitespace, NUL and control characters break // "KEY=VALUE" / argv / env-file framing the same way. Keys are restricted to // [A-Za-z0-9_][A-Za-z0-9_.-]* — the same charset startupTemplateTokenRE // accepts, so every surviving key stays referenceable from {{KEY}} tokens // (non-identifier keys like "my-key" remain supported via the quoted splice // path in renderADPanelStartupTemplate). Values stay opaque single strings: // NUL cannot survive execve (runc rejects the whole container start), while // newlines remain legal (PEM/JSON blobs) because values travel as expansion // data or quoted shell data, never as code. The invariants are enforced at // the parse boundary (runtimeEnvMap) AND at every sink, so safety never // depends on an individual caller remembering to filter. const ( envKeyMaxLen = 128 envValueMaxLen = 32768 envMaxEntries = 128 ) var envKeyRE = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]*$`) func validEnvKey(key string) bool { return len(key) <= envKeyMaxLen && envKeyRE.MatchString(key) } // sanitizeEnvValue strips NUL, the only character that cannot survive execve. func sanitizeEnvValue(value string) string { return strings.ReplaceAll(value, "\x00", "") } // normalizeEnvEntry validates one key/value pair against the environment // invariants and returns the trimmed key and NUL-stripped value. func normalizeEnvEntry(key, value string) (string, string, bool) { trimmed := strings.TrimSpace(key) if !validEnvKey(trimmed) { return "", "", false } cleaned := sanitizeEnvValue(value) if len(cleaned) > envValueMaxLen { return "", "", false } return trimmed, cleaned, true } // sanitizeEnvMap returns a copy of env keeping only entries that satisfy the // environment invariants. Iteration is over sorted keys so the entry cap is // deterministic. func sanitizeEnvMap(env map[string]string) map[string]string { if len(env) == 0 { return nil } keys := make([]string, 0, len(env)) for key := range env { keys = append(keys, key) } sort.Strings(keys) out := make(map[string]string, len(keys)) for _, key := range keys { if len(out) >= envMaxEntries { break } cleanKey, cleanValue, ok := normalizeEnvEntry(key, env[key]) if !ok { continue } out[cleanKey] = cleanValue } if len(out) == 0 { return nil } return out } // dockerEnvArgs renders an env map as `docker run -e KEY=VALUE` argument // pairs for exec.CommandContext (argv, never a shell). Only entries that // satisfy the environment invariants are emitted, independent of what // upstream merging produced; pair order is sorted for reproducible installs. func dockerEnvArgs(env map[string]string) []string { clean := sanitizeEnvMap(env) if len(clean) == 0 { return nil } keys := make([]string, 0, len(clean)) for key := range clean { keys = append(keys, key) } sort.Strings(keys) args := make([]string, 0, 2*len(keys)) for _, key := range keys { args = append(args, "-e", key+"="+clean[key]) } return args } func runtimeEnvMap(raw any) map[string]string { out := map[string]string{} switch v := raw.(type) { case map[string]string: for key, value := range v { out[key] = value } case map[string]any: for key, value := range v { out[key] = fmt.Sprint(value) } } return sanitizeEnvMap(out) } func primaryPortEnvKeysForTemplate(tpl string) []string { switch strings.ToLower(strings.TrimSpace(tpl)) { case "ark-survival-evolved", "ark": return []string{"GAME_CLIENT_PORT"} case "cs2", "dayz", "rust", "valheim": return []string{"SERVER_PORT"} case "fivem", "redm": return []string{"SERVER_PORT", "PORT", "ADPANEL_GAME_PORT"} case "palworld": return []string{"PORT"} case "project-zomboid": return []string{"DEFAULT_PORT"} case "ragemp": return []string{"RAGEMP_PORT"} default: return nil } } func applyRuntimeHostPortEnv(tpl string, env map[string]string, hostPort int) { if env == nil || hostPort <= 0 { return } portValue := fmt.Sprint(hostPort) env["PORT"] = portValue env["SERVER_PORT"] = portValue for _, key := range primaryPortEnvKeysForTemplate(tpl) { env[key] = portValue } } func renderRuntimeEnvTemplates(tpl string, env map[string]string, hostPort int) { if env == nil { return } for key, value := range env { if !strings.Contains(value, "{{") && !strings.Contains(value, "{PORT}") && !strings.Contains(value, "{SERVER_PORT}") { continue } rendered := renderTemplateValueTextual(value, env, hostPort) if hostPort > 0 { rendered = strings.ReplaceAll(rendered, "{SERVER_PORT}", fmt.Sprint(hostPort)) rendered = strings.ReplaceAll(rendered, "{PORT}", fmt.Sprint(hostPort)) } env[key] = rendered } } func runtimeUsesHostPortInsideContainer(tpl, startup string, env map[string]string) bool { normalized := strings.ToLower(strings.TrimSpace(tpl)) switch normalized { case "ark-survival-evolved", "ark", "cs2", "dayz", "fivem", "redm", "palworld", "project-zomboid", "ragemp", "rust", "valheim": return true } for _, key := range primaryPortEnvKeysForTemplate(normalized) { if _, ok := env[key]; ok { return true } } if startup == "" { startup = strings.TrimSpace(env["STARTUP"]) } return strings.Contains(startup, "{{SERVER_PORT}}") || strings.Contains(startup, "{{PORT}}") || strings.Contains(startup, "{SERVER_PORT}") || strings.Contains(startup, "{PORT}") } const cfxRuntimeServerDir = "/serverdata/serverfiles" func isCfxTemplate(tpl string) bool { switch strings.ToLower(strings.TrimSpace(tpl)) { case "fivem", "five-m", "redm": return true default: return false } } func normalizeCfxRuntimeLayout(tpl string, runtimeObj map[string]any, serverDir string) bool { if runtimeObj == nil || !isCfxTemplate(tpl) { return false } changed := false migrateNestedCfxServerFiles(serverDir) desiredVolume := "{BOT_DIR}:" + cfxRuntimeServerDir volumes := runtimeStringSlice(runtimeObj["volumes"]) if len(volumes) != 1 || strings.TrimSpace(volumes[0]) != desiredVolume { runtimeObj["volumes"] = []any{desiredVolume} changed = true } if normalizeContainerWorkdir(runtimeObj["workdir"]) != cfxRuntimeServerDir { runtimeObj["workdir"] = cfxRuntimeServerDir changed = true } env := runtimeEnvMap(runtimeObj["env"]) if env == nil { env = map[string]string{} } for key, value := range map[string]string{ "DATA_DIR": cfxRuntimeServerDir, "SERVER_DIR": cfxRuntimeServerDir, "GAME_CONFIG": "server.cfg", "HOME": cfxRuntimeServerDir, "DATA_PERM": "777", } { if env[key] != value { env[key] = value changed = true } } runtimeObj["env"] = env if runtimeObj["runAsRoot"] != true && templateRootAllowed() { runtimeObj["runAsRoot"] = true changed = true } if rawInstall, ok := runtimeObj["install"]; ok && rawInstall != nil { switch install := rawInstall.(type) { case map[string]any: if normalizeContainerWorkdir(install["runtimePath"]) != cfxRuntimeServerDir { install["runtimePath"] = cfxRuntimeServerDir changed = true } if normalizeContainerWorkdir(install["mountPath"]) == "" && normalizeContainerWorkdir(install["containerPath"]) == "" { install["mountPath"] = "/mnt/server" changed = true } case *templateInstallConfig: if normalizeContainerWorkdir(install.RuntimePath) != cfxRuntimeServerDir { install.RuntimePath = cfxRuntimeServerDir changed = true } if normalizeContainerWorkdir(install.MountPath) == "" && normalizeContainerWorkdir(install.ContainerPath) == "" { install.MountPath = "/mnt/server" changed = true } } } return changed } func resolveHostBindIP(hostIP string) string { clean := strings.TrimSpace(hostIP) if clean == "" || clean == "" || clean == "0.0.0.0" { return "0.0.0.0" } if parsed := net.ParseIP(clean); parsed != nil { return parsed.String() } if ips, err := net.LookupIP(clean); err == nil && len(ips) > 0 { for _, ip := range ips { if ip4 := ip.To4(); ip4 != nil { return ip4.String() } } return ips[0].String() } return clean } func addPortBindingWithIP(portBindings map[string][]dockerPortBinding, exposed map[string]struct{}, hostPort, containerPort int, protocols []string, hostIP string) { if hostPort <= 0 || containerPort <= 0 { return } cleanHostIP := resolveHostBindIP(hostIP) cleanProtocols := normalizePortProtocolSlice(protocols) if len(cleanProtocols) == 0 { cleanProtocols = []string{"tcp"} } for _, protocol := range cleanProtocols { key := fmt.Sprintf("%d/%s", containerPort, protocol) exposed[key] = struct{}{} duplicate := false for _, binding := range portBindings[key] { if binding.HostPort == fmt.Sprint(hostPort) && binding.HostIP == cleanHostIP { duplicate = true break } } if duplicate { continue } portBindings[key] = append(portBindings[key], dockerPortBinding{ HostIP: cleanHostIP, HostPort: fmt.Sprint(hostPort), }) } } func addPortBinding(portBindings map[string][]dockerPortBinding, exposed map[string]struct{}, hostPort, containerPort int, protocols []string) { addPortBindingWithIP(portBindings, exposed, hostPort, containerPort, protocols, "0.0.0.0") } func (a *Agent) buildStructuredPortBindings(serverDir string, meta map[string]any, hostPort, mainContainerPort int) (map[string][]dockerPortBinding, map[string]struct{}) { portBindings := make(map[string][]dockerPortBinding) exposed := make(map[string]struct{}) runtimeObj, _ := meta["runtime"].(map[string]any) protocolsByPort := runtimePortProtocolMap(runtimeObj["portProtocols"]) isMinecraft := strings.EqualFold(strings.TrimSpace(fmt.Sprint(meta["type"])), "minecraft") if !isMinecraft && runtimeObj != nil { isMinecraft = strings.EqualFold(strings.TrimSpace(fmt.Sprint(runtimeObj["providerId"])), "minecraft") || strings.EqualFold(strings.TrimSpace(fmt.Sprint(runtimeObj["id"])), "minecraft") } resolveProtocols := func(port int) []string { if protocols := protocolsByPort[port]; len(protocols) > 0 { return protocols } if isMinecraft { return []string{"tcp", "udp"} } return []string{"tcp"} } hostIP := serverHostBindIP(meta) allocMap := serverPortAllocationIPs(meta) mainPortIP := hostIP if customIP, found := allocMap[hostPort]; found && customIP != "" { mainPortIP = customIP } addPortBindingWithIP(portBindings, exposed, hostPort, mainContainerPort, resolveProtocols(mainContainerPort), mainPortIP) if metaRes, ok := meta["resources"].(map[string]any); ok { for _, ap := range runtimeIntSlice(metaRes["ports"]) { if ap > 0 && ap != hostPort { portIP := hostIP if customIP, found := allocMap[ap]; found && customIP != "" { portIP = customIP } addPortBindingWithIP(portBindings, exposed, ap, ap, resolveProtocols(ap), portIP) fmt.Printf("[port-manage] exposing additional port %d:%d (ip: %s, protocols: %v)\n", ap, ap, portIP, resolveProtocols(ap)) } } } return portBindings, exposed } func dockerRestartPolicyFromName(name string) dockerRestartPolicy { clean := strings.ToLower(strings.TrimSpace(name)) switch clean { case "no", "": return dockerRestartPolicy{Name: "no"} case "always": return dockerRestartPolicy{Name: "always"} case "on-failure": return dockerRestartPolicy{Name: "on-failure"} default: return dockerRestartPolicy{Name: "unless-stopped"} } } func isDangerousCapability(capName string) bool { switch strings.ToUpper(strings.TrimSpace(capName)) { case "NET_RAW", "DAC_OVERRIDE", "SYS_CHROOT", "AUDIT_WRITE", "MKNOD", "SETFCAP", "SETPCAP", "SYS_ADMIN", "SYS_RAWIO", "SYS_MODULE", "SYS_PTRACE": return true default: return false } } func stringSliceContains(slice []string, val string) bool { for _, item := range slice { if strings.EqualFold(item, val) { return true } } return false } func buildStructuredHostConfig(binds []string, portBindings map[string][]dockerPortBinding, resources *resourceLimits, restart string, readOnly bool) dockerHostConfig { return buildStructuredHostConfigWithRuntime(binds, portBindings, resources, restart, readOnly, nil) } func buildStructuredHostConfigWithRuntime(binds []string, portBindings map[string][]dockerPortBinding, resources *resourceLimits, restart string, readOnly bool, runtimeObj map[string]any) dockerHostConfig { pidsLimit := int64(defaultPidsLimit) if resources != nil && resources.PidsLimit != nil && *resources.PidsLimit >= minPidsLimit && *resources.PidsLimit <= maxPidsLimit { pidsLimit = int64(*resources.PidsLimit) } isRoot := templateMayRunAsRoot(runtimeObj) capAdd := []string{"KILL", "NET_BIND_SERVICE"} if isRoot { capAdd = append(capAdd, "CHOWN", "FOWNER", "SETUID", "SETGID") } if runtimeObj != nil { if customCapAdd, ok := runtimeObj["capAdd"].([]any); ok && len(customCapAdd) > 0 { for _, c := range customCapAdd { cStr := strings.ToUpper(strings.TrimSpace(fmt.Sprint(c))) if cStr != "" && !isDangerousCapability(cStr) && !stringSliceContains(capAdd, cStr) { capAdd = append(capAdd, cStr) } } } else if customCapAdd, ok := runtimeObj["cap_add"].([]any); ok && len(customCapAdd) > 0 { for _, c := range customCapAdd { cStr := strings.ToUpper(strings.TrimSpace(fmt.Sprint(c))) if cStr != "" && !isDangerousCapability(cStr) && !stringSliceContains(capAdd, cStr) { capAdd = append(capAdd, cStr) } } } } capDrop := []string{"ALL"} if runtimeObj != nil { if customCapDrop, ok := runtimeObj["capDrop"].([]any); ok && len(customCapDrop) > 0 { for _, c := range customCapDrop { cStr := strings.ToUpper(strings.TrimSpace(fmt.Sprint(c))) if cStr != "" && !stringSliceContains(capDrop, cStr) { capDrop = append(capDrop, cStr) } } } else if customCapDrop, ok := runtimeObj["cap_drop"].([]any); ok && len(customCapDrop) > 0 { for _, c := range customCapDrop { cStr := strings.ToUpper(strings.TrimSpace(fmt.Sprint(c))) if cStr != "" && !stringSliceContains(capDrop, cStr) { capDrop = append(capDrop, cStr) } } } } networkMode := "adpanel_nw" if runtimeObj != nil { if customNet := strings.TrimSpace(fmt.Sprint(runtimeObj["networkMode"])); customNet != "" && customNet != "" { networkMode = customNet } else if customNet := strings.TrimSpace(fmt.Sprint(runtimeObj["network"])); customNet != "" && customNet != "" { networkMode = customNet } } tmpfsMap := map[string]string{ "/tmp": "rw,exec,nosuid,size=256m", } if readOnly { tmpfsMap["/var/tmp"] = "rw,noexec,nosuid,size=64m" tmpfsMap["/run"] = "rw,noexec,nosuid,size=32m" } hostConfig := dockerHostConfig{ Binds: binds, PortBindings: portBindings, RestartPolicy: dockerRestartPolicyFromName(restart), CapDrop: capDrop, CapAdd: capAdd, SecurityOpt: []string{"no-new-privileges"}, PidsLimit: pidsLimit, ReadonlyRootfs: readOnly, Tmpfs: tmpfsMap, LogConfig: &dockerLogConfig{ Type: "local", Config: map[string]string{ "max-size": "10m", "max-file": "3", "mode": "non-blocking", }, }, NetworkMode: networkMode, } if resources != nil { if resources.RamMb != nil && *resources.RamMb > 0 { hostConfig.Memory = int64(*resources.RamMb) * 1024 * 1024 hostConfig.MemoryReservation = int64(min(*resources.RamMb, max(minDockerMemoryMb, *resources.RamMb*90/100))) * 1024 * 1024 if resources.SwapMb == nil { hostConfig.MemorySwap = int64(*resources.RamMb) * 1024 * 1024 } else { swapVal := *resources.SwapMb if swapVal == -1 { hostConfig.MemorySwap = int64(*resources.RamMb) * 1024 * 1024 } else if swapVal == 0 { hostConfig.MemorySwap = -1 } else { hostConfig.MemorySwap = int64(*resources.RamMb+swapVal) * 1024 * 1024 } } } if resources.CpuCores != nil && *resources.CpuCores > 0 { effCores, _ := computeCpuLimit(*resources.CpuCores) hostConfig.CpuPeriod = cpuPeriod hostConfig.CpuQuota = int64(float64(cpuPeriod) * effCores) } if resources.CpuWeight != nil && *resources.CpuWeight >= minCpuWeight && *resources.CpuWeight <= maxCpuWeight { hostConfig.CpuShares = dockerCpuSharesFromWeight(*resources.CpuWeight) } if resources.IoWeight != nil && *resources.IoWeight >= minIoWeight && *resources.IoWeight <= maxIoWeight { hostConfig.BlkioWeight = int64(*resources.IoWeight) } if resources.FileLimit != nil && *resources.FileLimit >= minFileLimit && *resources.FileLimit <= maxFileLimit { limit := int64(*resources.FileLimit) hostConfig.Ulimits = append(hostConfig.Ulimits, dockerUlimit{Name: "nofile", Soft: limit, Hard: limit}) } } return hostConfig } // envMapToList renders an env map for the Docker Engine API Env list. The // Engine (and every OCI runtime below it) splits each entry on the first "=", // so only entries satisfying the environment invariants are emitted — a key // containing "=" must never survive to here, or the container would see a // different variable name than the panel's maps do. Pair order is sorted for // deterministic container configs. func envMapToList(env map[string]string) []string { if len(env) == 0 { return nil } keys := make([]string, 0, len(env)) for k := range env { keys = append(keys, k) } sort.Strings(keys) out := make([]string, 0, len(keys)) for _, k := range keys { cleanKey, cleanValue, ok := normalizeEnvEntry(k, env[k]) if !ok { continue } out = append(out, cleanKey+"="+cleanValue) } if len(out) == 0 { return nil } return out } func isBlockedRuntimeShellExecutable(arg string) bool { switch runtimeProcessBaseExecutable(arg) { case "sh", "bash", "ash", "dash", "zsh", "ksh": return true default: return false } } func isRuntimeShellWrapperArgs(args []string, execIndex int) bool { if execIndex < 0 || execIndex >= len(args) { return false } if !isBlockedRuntimeShellExecutable(args[execIndex]) { return false } if execIndex+1 >= len(args) { return false } flags := strings.ToLower(strings.TrimSpace(args[execIndex+1])) return strings.HasPrefix(flags, "-") && strings.Contains(flags, "c") } func isBlockedRuntimeShellToken(arg string) bool { switch strings.TrimSpace(arg) { case "&&", "||", "|", ";", "&", ">", ">>", "<", "<<", "2>", "2>>", "2>&1", "|&": return true default: return false } } // findUnquotedRuntimeShellOperator mirrors parseShellArgs quote and escape // handling and reports the first operator character a shell would interpret // outside quotes. parseShellArgs keeps embedded operators as literal argv // data (execution is argv-based), so this backs the validator's contract // that the command carries no shell syntax at all, not just no standalone // operator tokens. Quoted operators are literal data and stay allowed. func findUnquotedRuntimeShellOperator(command string) byte { quote := byte(0) escape := false for i := 0; i < len(command); i++ { ch := command[i] if escape { escape = false continue } if ch == '\\' { escape = true continue } if quote != 0 { if ch == quote { quote = 0 } continue } if ch == '"' || ch == '\'' { quote = ch continue } if ch == ';' || ch == '&' || ch == '|' || ch == '<' || ch == '>' { return ch } } return 0 } func runtimeProcessBaseExecutable(arg string) string { clean := strings.TrimSpace(arg) if clean == "" { return "" } if strings.IndexFunc(clean, func(r rune) bool { return r == ' ' || r == '\t' || r == '\n' || r == '\r' }) >= 0 { if nested := parseShellArgs(clean); len(nested) > 0 { clean = strings.TrimSpace(nested[0]) } } clean = strings.ToLower(strings.ReplaceAll(clean, "\\", "/")) if slash := strings.LastIndex(clean, "/"); slash >= 0 && slash+1 < len(clean) { return clean[slash+1:] } return clean } func isRuntimeEnvAssignmentToken(arg string) bool { token := strings.TrimSpace(arg) if token == "" || strings.HasPrefix(token, "-") { return false } eqIdx := strings.Index(token, "=") if eqIdx <= 0 { return false } key := token[:eqIdx] for i, r := range key { isLetter := (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') isDigit := r >= '0' && r <= '9' if i == 0 { if r != '_' && !isLetter { return false } continue } if r != '_' && !isLetter && !isDigit { return false } } return true } func resolveRuntimeProcessExecutable(args []string) (string, int) { if len(args) == 0 { return "", -1 } for index := 0; index < len(args); index++ { token := strings.TrimSpace(args[index]) if token == "" { continue } execName := runtimeProcessBaseExecutable(token) if execName == "env" { index++ for index < len(args) { envToken := strings.TrimSpace(args[index]) if envToken == "" { index++ continue } if envToken == "--" { index++ break } if strings.HasPrefix(envToken, "-") || isRuntimeEnvAssignmentToken(envToken) { index++ continue } break } index-- continue } return execName, index } return "", -1 } func isBlockedContainerRuntimeExecutable(arg string) bool { switch strings.TrimSpace(arg) { case "docker", "docker-compose", "podman", "podman-compose", "nerdctl", "ctr": return true default: return false } } func unwrapRuntimeShellWrapper(cmd string) (string, bool) { args := parseShellArgs(cmd) if len(args) < 3 { return "", false } if !isBlockedRuntimeShellExecutable(args[0]) { return "", false } flags := strings.TrimSpace(args[1]) if !strings.HasPrefix(flags, "-") || !strings.Contains(flags, "c") { return "", false } inner := sanitizeRuntimeCommand(args[2]) if inner == "" { return "", false } return inner, true } func normalizeLegacyRuntimeProcessCommand(tpl, command, startFile, dataDir string) string { clean := sanitizeRuntimeCommand(command) if clean == "" { return "" } for i := 0; i < 2; i++ { inner, ok := unwrapRuntimeShellWrapper(clean) if !ok { break } clean = sanitizeRuntimeCommand(inner) } switch strings.ToLower(strings.TrimSpace(tpl)) { case "nodejs", "discord-bot": lower := strings.ToLower(clean) nodeIdx := strings.LastIndex(lower, "node ") if nodeIdx >= 0 && (strings.Contains(lower, "&&") || strings.HasPrefix(lower, "npm ") || strings.HasPrefix(lower, "cd ")) { clean = sanitizeRuntimeCommand(clean[nodeIdx:]) } } return clean } func looksLikePathOnlyScriptRuntimeCommand(command string) bool { args := parseShellArgs(command) if len(args) != 1 { return false } token := strings.ToLower(strings.TrimSpace(args[0])) if !strings.HasPrefix(token, "/") { return false } return strings.Contains(token, "entrypoint") || strings.HasSuffix(token, ".sh") || strings.HasSuffix(token, ".bash") } func looksLikeImageDefaultWrapperRuntimeCommand(command string, imgCfg imageConfig) bool { clean := strings.ToLower(strings.TrimSpace(command)) if clean == "" { return false } if looksLikePathOnlyScriptRuntimeCommand(command) { return true } entrypoint := trimRuntimeProcessArgs(imgCfg.Entrypoint) cmd := trimRuntimeProcessArgs(imgCfg.Cmd) if len(entrypoint) == 2 && isRuntimeShellName(entrypoint[0]) { script := strings.ToLower(strings.TrimSpace(entrypoint[1])) if strings.HasPrefix(script, "/") && (strings.Contains(script, "entrypoint") || strings.HasSuffix(script, ".sh") || strings.HasSuffix(script, ".bash")) { return true } } if len(cmd) == 1 { script := strings.ToLower(strings.TrimSpace(cmd[0])) if strings.HasPrefix(script, "/") && (strings.Contains(script, "entrypoint") || strings.HasSuffix(script, ".sh") || strings.HasSuffix(script, ".bash")) { return true } } if strings.Contains(clean, "entrypoint") && strings.Contains(clean, "/") { return true } return false } func shouldPreferImageDefaultRuntimeCommand(command string, imgCfg imageConfig) bool { if !imageConfigHasRuntimeDefault(imgCfg) { return false } return looksLikeImageDefaultWrapperRuntimeCommand(command, imgCfg) } func validateRuntimeProcessCommand(command string) string { clean := sanitizeRuntimeCommand(command) if clean == "" { return "" } if len(clean) > 4000 { return "process command is too long" } if strings.Contains(clean, "\n") { return "process command must be a single line" } if strings.Contains(clean, "`") || strings.Contains(clean, "$(") { return "shell expansions are not allowed in process commands" } args := parseShellArgs(clean) if len(args) == 0 { return "process command is empty" } execName, execIndex := resolveRuntimeProcessExecutable(args) if isBlockedContainerRuntimeExecutable(execName) { return `container runtime CLI commands like "docker run" are not allowed; configure image, ports, volumes, env, and the in-container process separately` } if isBlockedRuntimeShellExecutable(execName) && isRuntimeShellWrapperArgs(args, execIndex) { return "shell wrappers like sh -c or bash -lc are not allowed; provide the executable and arguments directly" } for _, arg := range args { if isBlockedRuntimeShellToken(arg) { return fmt.Sprintf("shell control operator %q is not allowed in process commands", strings.TrimSpace(arg)) } } if op := findUnquotedRuntimeShellOperator(clean); op != 0 { return fmt.Sprintf("shell control operator %q is not allowed in unquoted process command arguments; quote the argument to pass it literally", string(op)) } return "" } func buildProcessCommandArgs(command string) ([]string, error) { clean := sanitizeRuntimeCommand(command) if clean == "" { return nil, nil } if reason := validateRuntimeProcessCommand(clean); reason != "" { return nil, fmt.Errorf("%s", reason) } args := parseShellArgs(clean) if len(args) == 0 { return nil, fmt.Errorf("process command is empty") } return args, nil } func normalizeContainerWorkdir(value any) string { workdir := strings.TrimSpace(fmt.Sprint(value)) if workdir == "" || workdir == "" { return "" } workdir = strings.ReplaceAll(workdir, "\\", "/") if !strings.HasPrefix(workdir, "/") { return "" } workdir = path.Clean(workdir) if workdir == "" || workdir == "." { return "" } if !strings.HasPrefix(workdir, "/") { workdir = "/" + workdir } return workdir } func buildRenderedRuntimeProcessArgs(tpl, command, dataDir, startFile, imageRef string, hostPort int, resources *resourceLimits, meta map[string]any, env ...map[string]string) ([]string, error) { rendered := renderRuntimeCommandTemplate(command, dataDir, startFile, imageRef, hostPort, resources, meta, env...) rendered = normalizeLegacyRuntimeProcessCommand(tpl, rendered, startFile, dataDir) return buildProcessCommandArgs(rendered) } func (a *Agent) recentContainerLogs(ctx context.Context, name string, tail int) string { tailN := tail if tailN <= 0 { tailN = 50 } out, _ := collectDockerLogTail(ctx, name, tailN, false) return out } func isImmediateStartupPermissionIssue(logs string) bool { lower := strings.ToLower(strings.TrimSpace(logs)) if lower == "" { return false } hasPermissionFailure := strings.Contains(lower, "permission denied") || strings.Contains(lower, "operation not permitted") || strings.Contains(lower, "cannot execute") if !hasPermissionFailure { return false } startupHints := []string{ "start.sh", "entrypoint", "docker-entrypoint", "/opt/", "/bin/bash", "/bin/sh", "/usr/local/bin", "exec /", } for _, hint := range startupHints { if strings.Contains(lower, hint) { return true } } return true } func isMissingRuntimeExecutableStartError(err error) bool { if err == nil { return false } lower := strings.ToLower(err.Error()) if !strings.Contains(lower, "exec:") { return false } return strings.Contains(lower, "no such file or directory") || strings.Contains(lower, "executable file not found") || strings.Contains(lower, "stat ") || strings.Contains(lower, "not found") } func (a *Agent) preferredStructuredContainerUser(ctx context.Context, imageRef string, uid, gid int) string { cleanImageRef := strings.TrimSpace(imageRef) if cleanImageRef != "" { imgCfg := a.inspectRuntimeLaunchImage(ctx, cleanImageRef) if strings.TrimSpace(imgCfg.User) != "" { if a.debug { fmt.Printf("[docker] honoring image-defined user %q for %s\n", imgCfg.User, cleanImageRef) } return "" } } if uid <= 0 || gid <= 0 { return "1000:1000" } return fmt.Sprintf("%d:%d", uid, gid) } func runtimeRequestsRootUser(runtimeObj map[string]any) bool { if runtimeObj == nil { return false } return runtimeBool(runtimeObj["runAsRoot"]) || runtimeBool(runtimeObj["run_as_root"]) } // templateRootAllowed is the node-level opt-in for template/server-declared // root containers. Templates can no longer request root (stripped at panel // ingestion, removed from shipped templates); this flag exists only so an // operator can temporarily keep legacy workloads running on a node that // genuinely needs it. Default is deny. func templateRootAllowed() bool { return os.Getenv("ADPANEL_ALLOW_TEMPLATE_ROOT") == "1" } // templateMayRunAsRoot combines a stored root request with the node-level // opt-in. Every container-user and capability decision must go through this // function instead of runtimeRequestsRootUser. func templateMayRunAsRoot(runtimeObj map[string]any) bool { if !templateRootAllowed() { return false } return runtimeRequestsRootUser(runtimeObj) } func (a *Agent) structuredContainerUser(ctx context.Context, imageRef string, uid, gid int, runtimeObj map[string]any) string { if templateMayRunAsRoot(runtimeObj) { if a.debug { fmt.Printf("[docker] template requested root entrypoint for %s\n", imageRef) } return "" } if runtimeRequestsRootUser(runtimeObj) { fmt.Printf("[security] denying runAsRoot request for %s (set ADPANEL_ALLOW_TEMPLATE_ROOT=1 on the node to allow)\n", imageRef) } return a.preferredStructuredContainerUser(ctx, imageRef, uid, gid) } func hostConfigMemoryLimitMb(cfg dockerHostConfig) float64 { if cfg.Memory <= 0 { return 0 } return float64(cfg.Memory) / (1024 * 1024) } func hostConfigCpuLimitPercent(cfg dockerHostConfig) float64 { if cfg.CpuPeriod <= 0 || cfg.CpuQuota <= 0 { return 0 } return (float64(cfg.CpuQuota) / float64(cfg.CpuPeriod)) * 100 } func almostEqualFloat64(a, b, tolerance float64) bool { diff := a - b if diff < 0 { diff = -diff } return diff <= tolerance } func (a *Agent) inspectContainerHostConfig(ctx context.Context, name string) (dockerHostConfig, error) { inspected, err := a.docker.inspectContainerAPI(ctx, dockerContainerName(name)) if err != nil { return dockerHostConfig{}, err } return inspected.HostConfig, nil } func (a *Agent) inspectContainerAppliedLimits(ctx context.Context, name string) (memoryLimitMb float64, cpuLimitPercent float64, err error) { hostConfig, err := a.inspectContainerHostConfig(ctx, name) if err != nil { return 0, 0, err } return hostConfigMemoryLimitMb(hostConfig), hostConfigCpuLimitPercent(hostConfig), nil } type dockerStatsCPUUsage struct { TotalUsage uint64 `json:"total_usage"` PercpuUsage []uint64 `json:"percpu_usage"` } type dockerStatsCPU struct { CPUUsage dockerStatsCPUUsage `json:"cpu_usage"` SystemCPUUsage uint64 `json:"system_cpu_usage"` OnlineCPUs uint32 `json:"online_cpus"` } type dockerStatsMemory struct { Usage uint64 `json:"usage"` Limit uint64 `json:"limit"` Stats map[string]uint64 `json:"stats"` } type dockerStatsNetwork struct { RxBytes uint64 `json:"rx_bytes"` TxBytes uint64 `json:"tx_bytes"` } type dockerContainerStatsResponse struct { CPUStats dockerStatsCPU `json:"cpu_stats"` PreCPUStats dockerStatsCPU `json:"precpu_stats"` MemoryStats dockerStatsMemory `json:"memory_stats"` Networks map[string]dockerStatsNetwork `json:"networks"` } func (d Docker) resolveDockerContainerName(ctx context.Context, name string) string { dockerName := dockerContainerName(name) if d.containerExists(ctx, dockerName) { return dockerName } // The raw and sanitized fallbacks may resolve to a foreign container that // merely shares the name, so they require the ownership label to match. // If the label probe errors or is inconclusive, keep the canonical name. clean := strings.TrimSpace(name) if clean != "" && d.containerExists(ctx, clean) && d.containerHasServerLabel(ctx, clean, name) { return clean } safe := sanitizeName(clean) if safe != "" && d.containerExists(ctx, safe) && d.containerHasServerLabel(ctx, safe, name) { return safe } return dockerName } func (a *Agent) resolveDockerContainerName(ctx context.Context, name string) string { if a == nil { return dockerContainerName(name) } return a.docker.resolveDockerContainerName(ctx, name) } func (a *Agent) inspectContainerForStats(ctx context.Context, name string) (dockerContainerInspectForStats, string, bool, error) { dockerName := a.resolveDockerContainerName(ctx, name) body, status, err := a.docker.engineRequest(ctx, http.MethodGet, "/containers/"+url.PathEscape(dockerName)+"/json", nil, nil) if err != nil { return dockerContainerInspectForStats{}, "", false, err } if status == http.StatusNotFound { return dockerContainerInspectForStats{}, "", false, nil } if status < 200 || status >= 300 { return dockerContainerInspectForStats{}, "", false, fmt.Errorf("failed to inspect container %s: %s", name, decodeDockerAPIError(body)) } var payload dockerContainerInspectForStats if err := json.Unmarshal(body, &payload); err != nil { return dockerContainerInspectForStats{}, "", false, err } label, hasLabel := dockerServerLabel(payload.Labels, payload.Config) if hasLabel { if label != name { return dockerContainerInspectForStats{}, "", false, fmt.Errorf("container belongs to another server") } } else if actualName := strings.TrimPrefix(payload.Name, "/"); actualName != dockerName && actualName != name && actualName != sanitizeName(name) { // Unlabeled containers predate the ownership label, so they keep the // weaker name-based guard. return dockerContainerInspectForStats{}, "", false, fmt.Errorf("container name mismatch") } return payload, dockerName, true, nil } func (a *Agent) readContainerStatsForServer(ctx context.Context, name string) (dockerContainerStatsResponse, error) { _, dockerName, exists, err := a.inspectContainerForStats(ctx, name) if err != nil { return dockerContainerStatsResponse{}, err } if !exists { return dockerContainerStatsResponse{}, fmt.Errorf("container %s not found", name) } query := url.Values{} query.Set("stream", "false") body, status, err := a.docker.engineRequest(ctx, http.MethodGet, "/containers/"+url.PathEscape(dockerName)+"/stats", query, nil) if err != nil { return dockerContainerStatsResponse{}, err } if status < 200 || status >= 300 { return dockerContainerStatsResponse{}, fmt.Errorf("failed to read container stats %s: %s", name, decodeDockerAPIError(body)) } var payload dockerContainerStatsResponse if err := json.Unmarshal(body, &payload); err != nil { return dockerContainerStatsResponse{}, err } return payload, nil } func dockerCPUPercent(stats dockerContainerStatsResponse) float64 { cpuTotal := stats.CPUStats.CPUUsage.TotalUsage preCPUTime := stats.PreCPUStats.CPUUsage.TotalUsage systemTotal := stats.CPUStats.SystemCPUUsage preSystemTotal := stats.PreCPUStats.SystemCPUUsage if cpuTotal <= preCPUTime || systemTotal <= preSystemTotal { return 0 } cpuDelta := float64(cpuTotal - preCPUTime) systemDelta := float64(systemTotal - preSystemTotal) if cpuDelta <= 0 || systemDelta <= 0 { return 0 } onlineCPUs := float64(stats.CPUStats.OnlineCPUs) if onlineCPUs <= 0 { onlineCPUs = float64(len(stats.CPUStats.CPUUsage.PercpuUsage)) } if onlineCPUs <= 0 { onlineCPUs = 1 } return (cpuDelta / systemDelta) * onlineCPUs * 100 } func dockerMemoryUsedBytes(mem dockerStatsMemory) uint64 { usage := mem.Usage if usage == 0 { return 0 } if inactiveFile, ok := mem.Stats["inactive_file"]; ok && inactiveFile < usage { return usage - inactiveFile } if cache, ok := mem.Stats["cache"]; ok && cache < usage { return usage - cache } return usage } func sumDockerNetworkBytes(networks map[string]dockerStatsNetwork) (uint64, uint64) { var rx, tx uint64 for _, counters := range networks { rx = addUint64Saturating(rx, counters.RxBytes) tx = addUint64Saturating(tx, counters.TxBytes) } return rx, tx } func (a *Agent) verifyContainerResourceLimitsApplied(ctx context.Context, name string, expected dockerHostConfig) error { actual, err := a.inspectContainerHostConfig(ctx, name) if err != nil { return fmt.Errorf("failed to verify container resource limits: %w", err) } if expected.Memory > 0 && actual.Memory != expected.Memory { return fmt.Errorf( "container memory limit mismatch: expected %d MB, got %.0f MB", expected.Memory/(1024*1024), hostConfigMemoryLimitMb(actual), ) } if expected.CpuPeriod > 0 && expected.CpuQuota > 0 { expectedPercent := hostConfigCpuLimitPercent(expected) actualPercent := hostConfigCpuLimitPercent(actual) if !almostEqualFloat64(actualPercent, expectedPercent, 0.05) { return fmt.Errorf( "container cpu limit mismatch: expected %.2f cores, got %.2f cores", expectedPercent/100.0, actualPercent/100.0, ) } } return nil } func customBootstrapFailureReason(logs string) string { lower := strings.ToLower(strings.TrimSpace(logs)) if lower == "" { return "" } if strings.Contains(lower, "state is 0x202 after update job") && (strings.Contains(lower, "srcds_run: no such file or directory") || strings.Contains(lower, "tar:") || strings.Contains(lower, "server.cfg: no such file or directory")) { return "SteamCMD/app install failed and the expected server files are missing" } fatalPatterns := []string{ "executable file not found", "error during container init", "stat ", "no such file or directory", "permission denied", "error is not recoverable", "cannot open: no such file or directory", "is not a directory", "srcds_run: no such file or directory", "server.cfg: no such file or directory", } score := 0 primary := "" for _, line := range strings.Split(lower, "\n") { line = strings.TrimSpace(line) if line == "" { continue } for _, pattern := range fatalPatterns { if strings.Contains(line, pattern) { score++ if primary == "" { primary = strings.TrimSpace(line) } break } } } if score >= 4 { if primary != "" { return primary } return "repeated fatal startup errors detected" } return "" } func logsSuggestBootstrapInProgress(logs string) bool { lower := strings.ToLower(strings.TrimSpace(logs)) if lower == "" { return false } patterns := []string{ "downloading update", "installing update", "extracting package", "steam console client", "steamcmd", "app_update", "installing", "extracting", "downloading", "npm install", "pip install", "apt-get", "apk add", "composer install", } for _, pattern := range patterns { if strings.Contains(lower, pattern) { return true } } return false } func summarizeStartupLogs(logs string, maxLen int) string { clean := strings.TrimSpace(logs) if clean == "" { return "" } if maxLen <= 0 { maxLen = 1800 } if len(clean) > maxLen { clean = clean[len(clean)-maxLen:] } return clean } type boundedLogWriter struct { mu sync.Mutex buf []byte max int truncated bool } func newBoundedLogWriter(max int) *boundedLogWriter { if max <= 0 { max = 64 * 1024 } return &boundedLogWriter{max: max} } func (w *boundedLogWriter) Write(p []byte) (int, error) { w.mu.Lock() defer w.mu.Unlock() if len(p) >= w.max { w.truncated = w.truncated || len(w.buf)+len(p) > w.max w.buf = append(w.buf[:0], p[len(p)-w.max:]...) return len(p), nil } if excess := len(w.buf) + len(p) - w.max; excess > 0 { w.truncated = true copy(w.buf, w.buf[excess:]) w.buf = w.buf[:len(w.buf)-excess] } w.buf = append(w.buf, p...) return len(p), nil } func (w *boundedLogWriter) String() string { w.mu.Lock() defer w.mu.Unlock() return string(append([]byte(nil), w.buf...)) } type setupConsoleWriter struct { agent *Agent name string prefix string mu sync.Mutex partial string } func newSetupConsoleWriter(agent *Agent, name, prefix string) *setupConsoleWriter { prefix = strings.TrimSuffix(strings.TrimSpace(prefix), ":") if prefix != "stderr" { prefix = "stdout" } return &setupConsoleWriter{agent: agent, name: name, prefix: prefix} } func (w *setupConsoleWriter) Write(p []byte) (int, error) { if w == nil || w.agent == nil || w.name == "" { return len(p), nil } w.mu.Lock() defer w.mu.Unlock() data := w.partial + string(p) data = strings.ReplaceAll(data, "\r\n", "\n") data = strings.ReplaceAll(data, "\r", "\n") parts := strings.Split(data, "\n") if strings.HasSuffix(data, "\n") { w.partial = "" } else { w.partial = parts[len(parts)-1] parts = parts[:len(parts)-1] } for _, line := range parts { w.agent.emitSetupLog(w.name, w.prefix, line) } return len(p), nil } func (w *setupConsoleWriter) Flush() { if w == nil || w.agent == nil || w.name == "" { return } w.mu.Lock() line := w.partial w.partial = "" w.mu.Unlock() if strings.TrimSpace(line) != "" { w.agent.emitSetupLog(w.name, w.prefix, line) } } func normalizeTemplateInstallConfig(raw *templateInstallConfig) *templateInstallConfig { if raw == nil { return nil } script := strings.TrimSpace(strings.ReplaceAll(raw.Script, "\r\n", "\n")) script = strings.ReplaceAll(script, "\r", "\n") if script == "" { return nil } if len(script) > 262144 { script = script[:262144] } image := strings.TrimSpace(raw.Image) if image == "" { image = strings.TrimSpace(raw.Container) } if image == "" { image = "ghcr.io/pterodactyl/installers:debian" } if strings.ContainsAny(image, " \t\r\n\x00") { return nil } mountPath := normalizeContainerWorkdir(raw.MountPath) if mountPath == "" { mountPath = normalizeContainerWorkdir(raw.ContainerPath) } if mountPath == "" { mountPath = "/mnt/server" } runtimePath := normalizeContainerWorkdir(raw.RuntimePath) if runtimePath == "" { runtimePath = "/home/container" } minimumStorageMb := raw.MinimumStorageMb if minimumStorageMb < 0 { minimumStorageMb = 0 } timeoutSeconds := raw.TimeoutSeconds if timeoutSeconds <= 0 { timeoutSeconds = 1800 } if timeoutSeconds < 60 { timeoutSeconds = 60 } if timeoutSeconds > 7200 { timeoutSeconds = 7200 } env := map[string]string{} for key, value := range raw.Env { if envKey, envValue, ok := normalizeEnvEntry(key, value); ok { env[envKey] = envValue } } clean := &templateInstallConfig{ Image: image, Script: script, MountPath: mountPath, RuntimePath: runtimePath, TimeoutSeconds: timeoutSeconds, MinimumStorageMb: minimumStorageMb, AllowEmpty: raw.AllowEmpty || raw.AllowEmptyResult, } if len(env) > 0 { clean.Env = env } return clean } func dockerTemplateInstall(cfg *dockerTemplateConfig) *templateInstallConfig { if cfg == nil { return nil } if install := normalizeTemplateInstallConfig(cfg.Install); install != nil { return install } return normalizeTemplateInstallConfig(cfg.Installation) } func installConfigFromRuntime(runtimeObj map[string]any) *templateInstallConfig { if runtimeObj == nil { return nil } raw, ok := runtimeObj["install"] if !ok || raw == nil { return nil } if install, ok := raw.(*templateInstallConfig); ok { return normalizeTemplateInstallConfig(install) } b, err := json.Marshal(raw) if err != nil { return nil } var install templateInstallConfig if err := json.Unmarshal(b, &install); err != nil { return nil } return normalizeTemplateInstallConfig(&install) } func runtimeImageRef(runtimeObj map[string]any) string { if runtimeObj == nil { return "" } image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) if image == "" || image == "" { return "" } tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) if tag == "" || tag == "" { tag = "latest" } return image + ":" + tag } func safeInstallerContainerName(serverName string) string { base := sanitizeName(serverName) if base == "" { base = "server" } const prefix = "adpanel-install-" suffix := "-" + strconv.FormatInt(time.Now().UnixNano(), 36) return prefix + base[:min(len(base), 120-len(prefix)-len(suffix))] + suffix } func adpanelStartupDefaultEnv(name string, hostPort int, resources *resourceLimits, startup string) map[string]string { env := map[string]string{ "TZ": "Etc/UTC", "SERVER_IP": "0.0.0.0", "P_SERVER_LOCATION": "ADPanel", "P_SERVER_ALLOCATION_LIMIT": "0", "P_SERVER_UUID": name, "P_SERVER_UUID_SHORT": name, } if hostPort > 0 { env["SERVER_PORT"] = fmt.Sprint(hostPort) env["PORT"] = fmt.Sprint(hostPort) } if resources != nil && resources.RamMb != nil && *resources.RamMb > 0 { env["SERVER_MEMORY"] = fmt.Sprint(*resources.RamMb) } if strings.TrimSpace(startup) != "" { env["STARTUP"] = startup } return env } func mergeStringEnv(dst map[string]string, src map[string]string) map[string]string { if dst == nil { dst = map[string]string{} } for key, value := range src { envKey, envValue, ok := normalizeEnvEntry(key, value) if !ok { continue } dst[envKey] = envValue } return dst } func startupTemplateFromRuntime(runtimeObj map[string]any) string { if runtimeObj == nil { return "" } for _, key := range []string{"adpanelStartup", "adpanel_startup", "pterodactylStartup", "pterodactyl_startup"} { value := strings.TrimSpace(fmt.Sprint(runtimeObj[key])) if value != "" && value != "" { return value } } return "" } func startupTemplateFromDockerConfig(cfg *dockerTemplateConfig) string { if cfg == nil { return "" } if startup := strings.TrimSpace(cfg.ADPanelStartup); startup != "" { return startup } if startup := strings.TrimSpace(cfg.ADPanelStartupSnake); startup != "" { return startup } if startup := strings.TrimSpace(cfg.LegacyStartup); startup != "" { return startup } return strings.TrimSpace(cfg.LegacyStartupSnake) } func startupDisplayFromDockerConfig(cfg *dockerTemplateConfig) string { if cfg == nil { return "" } for _, value := range []string{ cfg.StartupDisplay, cfg.StartupDisplaySnake, cfg.StartupPreview, cfg.StartupPreviewSnake, cfg.ImageDefaultStartup, cfg.ImageDefaultStartupSnake, } { if display := strings.TrimSpace(value); display != "" { return display } } return "" } func javaVersionFromDockerConfig(cfg *dockerTemplateConfig) string { if cfg == nil { return "" } if version := strings.TrimSpace(cfg.JavaVersion); version != "" { return version } return strings.TrimSpace(cfg.Java) } func freeDiskMb(path string) int64 { var stat syscall.Statfs_t if err := syscall.Statfs(path, &stat); err != nil { return 0 } return int64(stat.Bavail) * int64(stat.Bsize) / (1024 * 1024) } var startupTemplateTokenRE = regexp.MustCompile(`\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}`) func isShellIdentifierKey(key string) bool { if key == "" { return false } for i, r := range key { switch { case r == '_' || (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z'): case i > 0 && r >= '0' && r <= '9': default: return false } } return true } // escapeSingleQuotedSplice renders a value for splicing inside a single-quoted // shell region: embedded quotes close and reopen the region ('\” idiom) so // the value always stays shell data, never code. func escapeSingleQuotedSplice(value string) string { return strings.ReplaceAll(value, "'", `'\''`) } // renderADPanelStartupTemplate prepares a managed startup script for // execution via `sh -lc`. // // Environment values are NOT spliced into the script text: splicing raw // values let shell metacharacters inside a value execute as code (template // injection). Instead, {{KEY}} tokens are rewritten to ${KEY} shell // references and the values travel through the container environment, where // variable expansion is data-only and never re-parsed as code. // // Context handling (tracked with a small shell state machine): // - unquoted and double-quoted tokens -> ${KEY}; expansion inside double // quotes performs no word splitting, globbing, or command substitution // - tokens inside single quotes cannot be expressed as ${KEY} (single // quotes suppress all expansion), so the value is spliced using the // '\” idiom, which keeps it data; the rendered result is identical to // the legacy splice for values that contain no single quotes // - non-identifier keys (e.g. "my-key") cannot be referenced as ${KEY}; // their values are spliced as a fully quoted single word // - keys with no value in the environment keep their literal {{KEY}} token // // Every rewritten ${KEY} is guaranteed to exist in env: missing keys are // backfilled so the shell resolves an empty value instead of an unbound // variable. func renderADPanelStartupTemplate(startup string, env map[string]string, hostPort int) string { rendered := strings.TrimSpace(startup) if rendered == "" { return "" } values := map[string]string{} for key, value := range env { values[strings.TrimSpace(key)] = value } if hostPort > 0 { values["SERVER_PORT"] = fmt.Sprint(hostPort) values["PORT"] = fmt.Sprint(hostPort) } var out strings.Builder out.Grow(len(rendered)) quote := 0 // 0 = unquoted, 1 = single, 2 = double escaped := false resolveKey := func(rawKey string) (string, string, bool) { key := strings.TrimSpace(rawKey) if key == "server.build.default.port" { if hostPort > 0 { return "SERVER_PORT", values["SERVER_PORT"], true } return key, "", false } key = strings.TrimPrefix(key, "env.") if value, ok := values[key]; ok { return key, value, true } return key, "", false } for i := 0; i < len(rendered); { if !escaped && rendered[i] == '{' && i+1 < len(rendered) && rendered[i+1] == '{' { if loc := startupTemplateTokenRE.FindStringSubmatchIndex(rendered[i:]); loc != nil && loc[0] == 0 { token := rendered[i : i+loc[1]] key, value, found := resolveKey(rendered[i+loc[2] : i+loc[3]]) switch { case !found: out.WriteString(token) case quote == 1: out.WriteString(escapeSingleQuotedSplice(value)) case isShellIdentifierKey(key): out.WriteString("${" + key + "}") if env != nil { if _, exists := env[key]; !exists { env[key] = value } } default: out.WriteString("'" + escapeSingleQuotedSplice(value) + "'") } i += loc[1] continue } } ch := rendered[i] switch { case escaped: escaped = false case quote == 1: if ch == '\'' { quote = 0 } case ch == '\\': escaped = true case ch == '\'' && quote != 2: quote = 1 case ch == '"' && quote == 0: quote = 2 case ch == '"' && quote == 2: quote = 0 } out.WriteByte(ch) i++ } return out.String() } // renderTemplateValueTextual splices {{KEY}} values into an env VALUE. // Env values are literal strings (the Docker API does not shell-expand // them), so the historical textual splice is safe here as long as the // result never becomes shell code; the managed startup script path must // use renderADPanelStartupTemplate instead. func renderTemplateValueTextual(value string, env map[string]string, hostPort int) string { rendered := strings.TrimSpace(value) if rendered == "" { return "" } values := map[string]string{} for key, envValue := range env { values[strings.TrimSpace(key)] = envValue } if hostPort > 0 { values["SERVER_PORT"] = fmt.Sprint(hostPort) values["PORT"] = fmt.Sprint(hostPort) } rendered = startupTemplateTokenRE.ReplaceAllStringFunc(rendered, func(token string) string { match := startupTemplateTokenRE.FindStringSubmatch(token) if len(match) != 2 { return token } key := strings.TrimSpace(match[1]) if key == "server.build.default.port" { if hostPort > 0 { return fmt.Sprint(hostPort) } return token } key = strings.TrimPrefix(key, "env.") if value, ok := values[key]; ok { return value } return token }) return rendered } // validateADPanelStartupScript rejects the highest-value host-escape // primitives in managed startup scripts. The script is by design arbitrary // shell inside the container; this check keeps it from reaching past the // container boundary (container runtime sockets/CLIs, namespace tools, // host PID namespace) at every ingestion point. It is defense in depth: // structured containers already run with cap-drop-all, no-new-privileges, // and a bind allowlist. func validateADPanelStartupScript(script string) string { clean := strings.TrimSpace(script) if clean == "" { return "" } if len(clean) > 32768 { return "managed startup script is too long (max 32768 bytes)" } lower := strings.ToLower(clean) for _, pattern := range []string{ "docker.sock", "podman.sock", "containerd.sock", "--privileged", "--pid=host", "--network=host", "--net=host", "/proc/1/root", } { if strings.Contains(lower, pattern) { return fmt.Sprintf("managed startup scripts cannot reference %q", pattern) } } for _, re := range []*regexp.Regexp{ regexp.MustCompile(`\bdocker\s+(run|exec|build|create|cp|save|load|export|import|kill|stop|restart|rm|rmi|volume|network|node|swarm|system|container|image|plugin|secret|service|stack|stats|update)\b`), regexp.MustCompile(`\b(podman|nerdctl|nsenter|unshare)\b`), } { if match := re.FindString(lower); match != "" { return fmt.Sprintf("managed startup scripts cannot reference %q", strings.TrimSpace(match)) } } return "" } // validateTemplateInstallScript is the node agent's mirror of the panel's // validateTemplateInstallScriptInput (utils/server-template-payload.js): the // same boundary patterns as validateADPanelStartupScript above, plus // whole-word container-runtime tool rejection — the installer image is // attacker-chosen and networked, so a runtime reference inside an install // script can only be an escape attempt. Enforced at the create endpoint (400) // and in checkTemplateInstallPreflight (fails the install job) so stored // legacy content is stopped at the sink too. var installScriptBlockedPatterns = []string{ "docker.sock", "podman.sock", "containerd.sock", "--privileged", "--pid=host", "--network=host", "--net=host", "/proc/1/root", } var installScriptRuntimeToolRE = regexp.MustCompile(`\b(docker|podman|nerdctl|ctr|nsenter|unshare)\b`) func validateTemplateInstallScript(script string) string { clean := strings.TrimSpace(script) if clean == "" { return "" } lower := strings.ToLower(clean) for _, pattern := range installScriptBlockedPatterns { if strings.Contains(lower, pattern) { return fmt.Sprintf("install scripts cannot reference %q — the installer container must not reach the container runtime or host namespaces", pattern) } } if match := installScriptRuntimeToolRE.FindString(lower); match != "" { return fmt.Sprintf("install scripts cannot reference %q — the installer cannot manage containers; configure the image, ports, volumes and env via the template instead", match) } return "" } func (a *Agent) emitSetupLog(name, prefix, message string) { name = sanitizeName(name) if name == "" { return } prefix = strings.TrimSuffix(strings.TrimSpace(prefix), ":") if prefix != "stderr" { prefix = "stdout" } message = strings.ReplaceAll(message, "\r\n", "\n") message = strings.ReplaceAll(message, "\r", "\n") for _, line := range strings.Split(message, "\n") { line = strings.TrimRight(line, " \t") plain := strings.TrimSpace(ansiSGRRE.ReplaceAllString(line, "")) if plain == "" { continue } if a != nil && a.debug { fmt.Printf("[setup][%s] %s: %s\n", name, prefix, plain) } } } func (a *Agent) checkTemplateInstallPreflight(name, serverDir string, install *templateInstallConfig) error { install = normalizeTemplateInstallConfig(install) if install == nil { return nil } if reason := validateTemplateInstallScript(install.Script); reason != "" { return fmt.Errorf("template install script rejected: %s — update the template's install script and reinstall", reason) } // Sink-side registry allowlist: stored legacy templates predate the panel's // ingestion check, so the image the installer pulls is verified here too. if reason := validateTemplateImageRef(install.Image); reason != "" { return fmt.Errorf("template installer image rejected: %s — update the template's installer image and reinstall", reason) } if err := ensureDir(serverDir); err != nil { return err } ensureVolumeWritable(serverDir) if install.MinimumStorageMb > 0 { freeMb := freeDiskMb(serverDir) if freeMb > 0 && freeMb < int64(install.MinimumStorageMb) { return fmt.Errorf("not enough free disk for installer: template requires at least %d MB, host has %d MB free", install.MinimumStorageMb, freeMb) } } return nil } func (a *Agent) pullSetupImage(name, serverDir, imageRef, label string, timeout time.Duration) error { imageRef = strings.TrimSpace(imageRef) if imageRef == "" { return nil } label = strings.TrimSpace(label) if label == "" { label = "Docker" } if timeout <= 0 { timeout = 10 * time.Minute } a.updateSetupState(name, serverDir, "pulling", fmt.Sprintf("Pulling %s image %s", label, imageRef)) ctx, cancel := context.WithTimeout(context.Background(), timeout) err := a.docker.ensureImageAvailableAPI(ctx, imageRef) cancel() if err != nil { return fmt.Errorf("%s image pull failed: %w", label, err) } a.emitSetupLog(name, "stdout", fmt.Sprintf("%s image ready: %s", label, imageRef)) return nil } func installerScriptPreferredShell(script string) string { clean := strings.TrimSpace(strings.ReplaceAll(script, "\r\n", "\n")) if clean == "" { return "sh" } if strings.HasPrefix(clean, "#!") { firstLine := strings.TrimSpace(strings.SplitN(clean, "\n", 2)[0]) firstLine = strings.TrimSpace(strings.TrimPrefix(firstLine, "#!")) for _, token := range strings.Fields(firstLine) { base := strings.ToLower(path.Base(strings.TrimSpace(token))) switch base { case "bash", "zsh", "ksh": return base case "sh", "ash", "dash": return "sh" } } } lower := strings.ToLower(clean) if strings.Contains(lower, "[[") || strings.Contains(lower, "function ") || strings.Contains(lower, "source ") || strings.Contains(lower, "set -o pipefail") { return "bash" } return "sh" } func installerShellCommandFlag(shell string) string { switch strings.ToLower(path.Base(strings.TrimSpace(shell))) { case "bash", "zsh", "ksh": return "-lc" default: return "-c" } } func installerDefaultCommandArgs(entrypoint []string, script string) []string { ep := trimRuntimeProcessArgs(entrypoint) if len(ep) == 0 { shell := installerScriptPreferredShell(script) return []string{shell, installerShellCommandFlag(shell), script} } execIndex := 0 if strings.EqualFold(path.Base(ep[0]), "env") && len(ep) > 1 { execIndex = 1 } base := strings.ToLower(path.Base(ep[execIndex])) if base == "bash" || base == "zsh" || base == "ksh" || base == "sh" || base == "ash" || base == "dash" { if len(ep) > execIndex+1 && strings.HasPrefix(ep[execIndex+1], "-") && strings.Contains(ep[execIndex+1], "c") { return []string{script} } return []string{installerShellCommandFlag(base), script} } return []string{script} } func (a *Agent) updateSetupState(name, serverDir, status, message string) { meta := a.loadMeta(serverDir) if meta == nil { meta = map[string]any{} } status = strings.TrimSpace(status) message = strings.TrimSpace(message) if status == "" { delete(meta, "setupStatus") } else { meta["setupStatus"] = status } if message == "" { delete(meta, "setupMessage") } else { meta["setupMessage"] = message } meta["setupUpdatedAt"] = time.Now().UnixMilli() if err := a.saveMeta(serverDir, meta); err != nil { fmt.Printf("[setup] failed to update setup state for %s: %v\n", name, err) } if status != "" { line := status if message != "" { line += ": " + message } prefix := "stdout" if strings.EqualFold(status, "failed") { prefix = "stderr" } a.emitSetupLog(name, prefix, line) } } func (a *Agent) prepareMinecraftCreateSetup(req createReq, name, serverDir string, meta map[string]any) bool { runtimeObj, _ := meta["runtime"].(map[string]any) imageRef := runtimeImageRef(runtimeObj) if imageRef != "" { if err := a.pullSetupImage(name, serverDir, imageRef, "runtime", 10*time.Minute); err != nil { a.updateSetupState(name, serverDir, "failed", err.Error()) fmt.Printf("[setup] Minecraft runtime image pull failed for %s: %v\n", name, err) return false } } a.updateSetupState(name, serverDir, "queued", "Docker image ready; Minecraft setup will continue in the background") return true } func (a *Agent) prepareCustomCreateSetup(req createReq, name, serverDir string, meta map[string]any) bool { runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj == nil { runtimeObj = map[string]any{} } a.updateSetupState(name, serverDir, "preparing", "Preparing Docker template") if install := installConfigFromRuntime(runtimeObj); install != nil { if err := a.checkTemplateInstallPreflight(name, serverDir, install); err != nil { a.updateSetupState(name, serverDir, "failed", err.Error()) fmt.Printf("[setup] Template preflight failed for %s: %v\n", name, err) return false } if err := a.pullSetupImage(name, serverDir, install.Image, "installer", 10*time.Minute); err != nil { a.updateSetupState(name, serverDir, "failed", err.Error()) fmt.Printf("[setup] Template installer image pull failed for %s: %v\n", name, err) return false } } if imageRef := runtimeImageRef(runtimeObj); imageRef != "" { if err := a.pullSetupImage(name, serverDir, imageRef, "runtime", 10*time.Minute); err != nil { a.updateSetupState(name, serverDir, "failed", err.Error()) fmt.Printf("[setup] Runtime image pull failed for %s: %v\n", name, err) return false } } a.updateSetupState(name, serverDir, "queued", "Docker images ready; setup will continue in the background") return true } func (a *Agent) finishMinecraftCreateSetup(req createReq, name, serverDir string, meta map[string]any, hostPort int) { // adpanel:F8 - re-validate here: this runs as a background continuation // and must never build download URLs from unvalidated request fields, // even if a future caller skips handler-level checks. fork, forkErr := resolveMinecraftFork(req.MCFork) if forkErr != nil { a.updateSetupState(name, serverDir, "failed", forkErr.Error()) fmt.Printf("[setup] Minecraft setup failed for %s: %v\n", name, forkErr) return } ver, verErr := resolveMinecraftVersion(req.MCVersion) if verErr != nil { a.updateSetupState(name, serverDir, "failed", verErr.Error()) fmt.Printf("[setup] Minecraft setup failed for %s: %v\n", name, verErr) return } a.updateSetupState(name, serverDir, "downloading", "Downloading Minecraft server files") ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) jarURL, jarErr := getMinecraftJarURL(ctx, a.dl, fork, ver, a.debug) cancel() if jarErr != nil { a.updateSetupState(name, serverDir, "failed", jarErr.Error()) fmt.Printf("[setup] Minecraft download failed for %s: %v\n", name, jarErr) return } ctxD, cancelD := context.WithTimeout(context.Background(), 30*time.Minute) if err := a.dl.downloadToFile(ctxD, jarURL, filepath.Join(serverDir, "server.jar")); err != nil { cancelD() a.updateSetupState(name, serverDir, "failed", err.Error()) fmt.Printf("[setup] Minecraft download failed for %s: %v\n", name, err) return } cancelD() enforceServerProps(serverDir) if req.ImportUrl != "" { a.updateSetupState(name, serverDir, "importing", "Importing archive") if err := a.downloadAndExtractArchiveSync(name, serverDir, req.ImportUrl); err != nil { a.updateSetupState(name, serverDir, "failed", "archive import failed: "+err.Error()) fmt.Printf("[setup] Minecraft archive import failed for %s: %v\n", name, err) return } } if req.AutoStart { a.updateSetupState(name, serverDir, "starting", "Starting container") ctxStart, cancelStart := context.WithTimeout(context.Background(), 240*time.Second) err := a.startMinecraftContainer(ctxStart, name, serverDir, hostPort, req.Resources, nil, false) cancelStart() if err != nil { if errors.Is(err, errMinecraftEulaRequired) { // Setup itself finished; the EULA prompt in the console gates the // first start, so this is a normal ready state, not a failure. a.updateSetupState(name, serverDir, "ready", "Setup complete — accept the Minecraft EULA in the console to start the server") a.broadcastContainerEventWithMeta(name, "stopped", map[string]any{"eulaRequired": true}) auditLog.Log("server_setup", "127.0.0.1", "", name, "setup", "success", map[string]any{"template": req.Template, "eulaRequired": true}) return } a.updateSetupState(name, serverDir, "failed", err.Error()) fmt.Printf("[setup] Minecraft startup failed for %s: %v\n", name, err) return } a.ensureLiveLogs(name) } a.updateSetupState(name, serverDir, "ready", "Server setup complete") auditLog.Log("server_setup", "127.0.0.1", "", name, "setup", "success", map[string]any{"template": req.Template}) } func (a *Agent) finishCustomCreateSetup(req createReq, name, serverDir string, meta map[string]any, hostPort int) { runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj == nil { runtimeObj = map[string]any{} } if install := installConfigFromRuntime(runtimeObj); install != nil { a.updateSetupState(name, serverDir, "installing", "Installing server files") if err := a.runTemplateInstall(context.Background(), name, serverDir, install, runtimeObj, hostPort, req.Resources, 0); err != nil { a.updateSetupState(name, serverDir, "failed", err.Error()) fmt.Printf("[setup] Template install failed for %s: %v\n", name, err) return } } if req.ImportUrl != "" { a.updateSetupState(name, serverDir, "importing", "Importing archive") if err := a.downloadAndExtractArchiveSync(name, serverDir, req.ImportUrl); err != nil { a.updateSetupState(name, serverDir, "failed", "archive import failed: "+err.Error()) fmt.Printf("[setup] Archive import failed for %s: %v\n", name, err) return } } template := strings.ToLower(strings.TrimSpace(req.Template)) switch template { case "python": scaffoldPython(serverDir, defaultStartFileForType(template)) case "nodejs", "discord-bot": scaffoldNode(serverDir, filepath.Base(serverDir), defaultStartFileForType(template), hostPort) } runtimeImg := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) if runtimeImg == "" || runtimeImg == "" { if req.Docker != nil { runtimeImg = strings.TrimSpace(req.Docker.Image) } } canStart := req.AutoStart && (runtimeImg != "" || isManagedProcessRuntime(template)) if canStart { a.updateSetupState(name, serverDir, "starting", "Starting container") ctxStart, cancelStart := context.WithTimeout(context.Background(), 240*time.Second) var err error if isManagedProcessRuntime(template) { err = a.startRuntimeContainer(ctxStart, name, serverDir, meta, hostPort, req.Resources, nil) } else { err = a.startCustomDockerContainer(ctxStart, name, serverDir, meta, hostPort, req.Resources) } cancelStart() if err != nil { a.updateSetupState(name, serverDir, "failed", err.Error()) fmt.Printf("[setup] Container startup failed for %s: %v\n", name, err) return } a.ensureLiveLogs(name) } a.updateSetupState(name, serverDir, "ready", "Server setup complete") auditLog.Log("server_setup", "127.0.0.1", "", name, "setup", "success", map[string]any{"template": req.Template}) } func (a *Agent) monitorCustomContainerBootstrap(ctx context.Context, name, imageRef string) error { started := time.Now() defaultWindow := 18 * time.Second bootstrapWindow := 115 * time.Second if isGameServerDockerImage(imageRef) { bootstrapWindow = 150 * time.Second } seenBootstrap := false ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): logCtx, cancel := context.WithTimeout(context.Background(), 6*time.Second) logsOut := a.recentContainerLogs(logCtx, name, 160) cancel() return fmt.Errorf("container bootstrap did not become stable before timeout; last logs: %s", summarizeStartupLogs(logsOut, 1800)) case <-ticker.C: } statusOut, _, _, _ := a.docker.runCollect(ctx, "inspect", "--format", "{{.State.Status}} {{.State.ExitCode}}", name) statusParts := strings.Fields(strings.TrimSpace(statusOut)) status := "" exitStr := "0" if len(statusParts) > 0 { status = statusParts[0] } if len(statusParts) > 1 { exitStr = statusParts[1] } logsOut := a.recentContainerLogs(ctx, name, 160) if logsSuggestBootstrapInProgress(logsOut) { seenBootstrap = true } if reason := customBootstrapFailureReason(logsOut); reason != "" { return fmt.Errorf("container bootstrap failed: %s; last logs: %s", reason, summarizeStartupLogs(logsOut, 1800)) } switch status { case "restarting": if time.Since(started) >= defaultWindow { fmt.Printf("[docker] %s is restarting during bootstrap; not blocking startup.\n", name) return nil } continue case "exited", "dead": if status == "" { status = "unknown" } return fmt.Errorf("container stopped during bootstrap (%s, exit code %s); last logs: %s", status, exitStr, summarizeStartupLogs(logsOut, 1800)) case "running": elapsed := time.Since(started) if seenBootstrap { if elapsed >= bootstrapWindow { return nil } continue } if elapsed >= defaultWindow { return nil } case "created", "": if time.Since(started) > defaultWindow { return nil } default: if time.Since(started) > defaultWindow { return nil } } } } func (a *Agent) startMinecraftContainer(ctx context.Context, name, serverDir string, hostPort int, resources *resourceLimits, extraEnv map[string]string, directStart bool) error { meta := a.loadMeta(serverDir) // adpanel:minecraft-eula - single choke point for every Minecraft container // start (console start, restart, create/reinstall autostart, jar apply). // EULA consent must exist in eula.txt before the container can boot; the // rmForce also stops a crash-looping container the restart policy keeps // respawning without an accepted EULA. if isMinecraftServerMeta(meta) && !minecraftEulaAccepted(serverDir) { if !directStart { a.stopContainerBeforeStart(ctx, name) } a.broadcastDaemonLog(name, "Minecraft EULA is not accepted yet (eula.txt is missing or eula=false).") a.broadcastDaemonLog(name, "Accept the Minecraft EULA in the console to allow this server to start.") return errMinecraftEulaRequired } // adpanel:eula-console-history - a direct Start confirmed the container // was inactive, but must still preserve its logs until consent is verified. if directStart { a.prepareServerConsoleStart(name) a.broadcastDaemonLog(name, fmt.Sprintf("Allocating network port bindings (: %d)...", hostPort)) enforceServerProps(serverDir) } if err := a.prepareServerResourceStart(name, meta); err != nil { return err } a.stopContainerBeforeStart(ctx, name) runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj == nil { runtimeObj = make(map[string]any) } ensureVolumeWritable(serverDir) uid, gid := statUIDGID(serverDir) commandTemplate := sanitizeRuntimeCommand(runtimeObj["command"]) image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) rawJavaVersion := strings.TrimSpace(fmt.Sprint(runtimeObj["javaVersion"])) selectedJavaVersion := normalizeMinecraftJavaVersion(rawJavaVersion) if rawJavaVersion != "" && rawJavaVersion != "" && selectedJavaVersion == "" { return fmt.Errorf("unsupported minecraft java version: %s", rawJavaVersion) } if selectedJavaVersion != "" { image = defaultMinecraftProcessImage tag = minecraftJavaTag(selectedJavaVersion) runtimeObj["image"] = image runtimeObj["tag"] = tag runtimeObj["javaVersion"] = selectedJavaVersion } useLegacyImageMode := false if image == "" || image == "" { if commandTemplate == "" { image = "itzg/minecraft-server" tag = "latest" useLegacyImageMode = true } else { image = defaultMinecraftProcessImage tag = defaultMinecraftProcessTag } } if tag == "" || tag == "" { if strings.EqualFold(image, "itzg/minecraft-server") && commandTemplate == "" { tag = "latest" useLegacyImageMode = true } else { tag = defaultMinecraftProcessTag } } if strings.EqualFold(image, "itzg/minecraft-server") && commandTemplate == "" { useLegacyImageMode = true } imageRef := image + ":" + tag binds, dataDir := a.resolveStructuredBinds("minecraft", runtimeObj, serverDir) workdir := normalizeContainerWorkdir(runtimeObj["workdir"]) if workdir == "" { workdir = dataDir } startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) if startFile == "" || startFile == "" { startFile = "server.jar" } env := runtimeEnvMap(runtimeObj["env"]) if env == nil { env = map[string]string{} } for k, v := range extraEnv { env[strings.TrimSpace(k)] = v } req := dockerContainerCreateRequest{ Image: imageRef, Tty: containerTTYForHost(), OpenStdin: true, AttachStdin: true, AttachStdout: true, AttachStderr: true, WorkingDir: workdir, } if useLegacyImageMode { // No EULA env here: the itzg image validates the mounted /data/eula.txt, // which the EULA start gate guarantees is accepted before this container // can start. Injecting EULA=TRUE would silently accept it for the user. if _, ok := env["TYPE"]; !ok { env["TYPE"] = "CUSTOM" } if _, ok := env["CUSTOM_SERVER"]; !ok { env["CUSTOM_SERVER"] = "/data/server.jar" } if _, ok := env["ENABLE_RCON"]; !ok { env["ENABLE_RCON"] = "false" } if _, ok := env["CREATE_CONSOLE_IN_PIPE"]; !ok { env["CREATE_CONSOLE_IN_PIPE"] = "true" } effUID := uid effGID := gid if effUID <= 0 || effGID <= 0 { effUID = 1000 effGID = 1000 } if _, ok := env["UID"]; !ok { env["UID"] = fmt.Sprint(effUID) } if _, ok := env["GID"]; !ok { env["GID"] = fmt.Sprint(effGID) } } else { if commandTemplate == "" { commandTemplate = defaultRuntimeCommandForType("minecraft", startFile, dataDir) } cmdArgs, err := buildRenderedRuntimeProcessArgs("minecraft", commandTemplate, dataDir, startFile, imageRef, hostPort, resources, meta) if err != nil { return err } req.User = a.structuredContainerUser(ctx, imageRef, uid, gid, runtimeObj) req.Cmd = cmdArgs } mcReadOnly := !useLegacyImageMode && structuredRuntimeReadOnly(runtimeObj, true) portBindings, exposedPorts := a.buildStructuredPortBindings(serverDir, meta, hostPort, 25565) req.ExposedPorts = exposedPorts req.HostConfig = buildStructuredHostConfigWithRuntime( binds, portBindings, resources, strings.TrimSpace(fmt.Sprint(runtimeObj["restart"])), mcReadOnly, runtimeObj, ) req.Env = envMapToList(env) a.broadcastDaemonLog(name, "Provisioning container process with allocated resource limits...") if err := a.runStructuredContainerWithCompatUser(ctx, name, req); err != nil { return err } return nil } func (a *Agent) startRuntimeContainer(ctx context.Context, name, serverDir string, meta map[string]any, hostPort int, resources *resourceLimits, extraEnv map[string]string) error { if err := a.prepareServerResourceStart(name, meta); err != nil { return err } a.stopContainerBeforeStart(ctx, name) runtimeObj, _ := meta["runtime"].(map[string]any) tpl := strings.ToLower(fmt.Sprint(meta["type"])) if tpl == "" { tpl = strings.ToLower(fmt.Sprint(runtimeObj["providerId"])) } image, tag := managedRuntimeImage(tpl, runtimeObj) imageRef := image if tag != "" { imageRef = image + ":" + tag } ensureVolumeWritable(serverDir) effectivePort := 0 if hostPort > 0 { effectivePort = hostPort } binds, dataDir := a.resolveStructuredBinds(tpl, runtimeObj, serverDir) workdir := normalizeContainerWorkdir(runtimeObj["workdir"]) if workdir == "" { workdir = dataDir } env := runtimeEnvMap(runtimeObj["env"]) if env == nil { env = map[string]string{} } for k, v := range extraEnv { env[strings.TrimSpace(k)] = v } if effectivePort > 0 { applyRuntimeHostPortEnv(tpl, env, effectivePort) renderRuntimeEnvTemplates(tpl, env, effectivePort) } startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) if startFile == "" || startFile == "" { startFile = defaultStartFileForType(tpl) } commandTemplate := sanitizeRuntimeCommand(runtimeObj["command"]) if commandTemplate == "" { commandTemplate = defaultRuntimeCommandForType(tpl, startFile, dataDir) } ensureRuntimeEntrypointScaffold(ctx, serverDir, tpl, commandTemplate, dataDir, workdir, startFile, effectivePort) cmdArgs, err := buildRenderedRuntimeProcessArgs(tpl, commandTemplate, dataDir, startFile, imageRef, effectivePort, resources, meta) if err != nil { return err } uid, gid := statUIDGID(serverDir) req := dockerContainerCreateRequest{ Image: imageRef, Env: envMapToList(env), Cmd: cmdArgs, WorkingDir: workdir, User: a.structuredContainerUser(ctx, imageRef, uid, gid, runtimeObj), Tty: containerTTYForHost(), OpenStdin: true, AttachStdin: true, AttachStdout: true, AttachStderr: true, } portBindings, exposedPorts := a.buildStructuredPortBindings(serverDir, meta, effectivePort, effectivePort) req.ExposedPorts = exposedPorts req.HostConfig = buildStructuredHostConfigWithRuntime( binds, portBindings, resources, strings.TrimSpace(fmt.Sprint(runtimeObj["restart"])), structuredRuntimeReadOnly(runtimeObj, true), runtimeObj, ) a.broadcastDaemonLog(name, "Provisioning container process with allocated resource limits...") if err := a.runStructuredContainerWithCompatUser(ctx, name, req); err != nil { return err } return nil } func matchesBlockedFlag(flag string, denylist map[string]bool) (bool, string) { if !strings.HasPrefix(flag, "--") || len(flag) <= 2 { return false, "" } for blocked := range denylist { if strings.HasPrefix(blocked, flag) { return true, blocked } } return false, "" } func parseShellArgs(s string) []string { var args []string var current strings.Builder inQuote := rune(0) escape := false for _, r := range s { if escape { if r == '\n' || r == '\r' { escape = false continue } current.WriteRune(r) escape = false continue } if r == '\\' { escape = true continue } if inQuote != 0 { if r == inQuote { inQuote = 0 } else { current.WriteRune(r) } continue } if r == '"' || r == '\'' { inQuote = r continue } if r == ' ' || r == '\t' || r == '\n' || r == '\r' { if current.Len() > 0 { args = append(args, current.String()) current.Reset() } continue } current.WriteRune(r) } if current.Len() > 0 { args = append(args, current.String()) } return args } func (a *Agent) startCustomDockerContainer(ctx context.Context, name, serverDir string, meta map[string]any, hostPort int, resources *resourceLimits) error { if err := a.prepareServerResourceStart(name, meta); err != nil { return err } a.stopContainerBeforeStart(ctx, name) runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj == nil { runtimeObj = make(map[string]any) } if a.debug { fmt.Printf("[docker] startCustomDockerContainer for %s\n", name) } image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) if image == "" || image == "" { return fmt.Errorf("no docker image specified") } if tag == "" || tag == "" { tag = "latest" } imageRef := image + ":" + tag // Sink-side registry allowlist (mirrors the panel's ingestion check): a // start must never pull and run a template image from a registry the node // does not allow, even for content stored before that check existed. if reason := validateTemplateImageRef(imageRef); reason != "" { return fmt.Errorf("runtime image rejected: %s", reason) } imgCfg := a.inspectRuntimeLaunchImage(ctx, imageRef) ensureVolumeWritable(serverDir) tpl := strings.ToLower(fmt.Sprint(meta["type"])) if tpl == "" || tpl == "" { tpl = strings.ToLower(fmt.Sprint(runtimeObj["providerId"])) } if normalizeCfxRuntimeLayout(tpl, runtimeObj, serverDir) { meta["runtime"] = runtimeObj _ = a.saveMeta(serverDir, meta) } explicitCommandTemplate := sanitizeRuntimeCommand(runtimeObj["command"]) adpanelStartup := startupTemplateFromRuntime(runtimeObj) if reason := validateADPanelStartupScript(adpanelStartup); reason != "" { // Stored pre-existing scripts are not rejected at start time (that // would break servers on upgrade), but node operators get a signal. fmt.Printf("[security] WARNING: stored managed startup for %s: %s\n", name, reason) } binds, dataDir, workdir := a.resolveCustomRuntimeLayout(tpl, runtimeObj, serverDir, serverDir, imageRef, imgCfg) preparedPath, err := a.prepareCustomRuntimeImage(ctx, imageRef, serverDir, imgCfg, binds, dataDir, workdir, explicitCommandTemplate) if err != nil { return err } if preparedPath != "" && len(binds) == 0 && !hasManagedRuntimeDefaults(tpl) { binds, dataDir, workdir = customRuntimeImageSeedLayout(serverDir, preparedPath, workdir) fmt.Printf("[docker] mounted prepared image path for %s: %s -> %s\n", imageRef, serverDir, dataDir) } env, mainContainerPort := customRuntimeEnvironmentAndPort(name, tpl, adpanelStartup, runtimeObj, hostPort, resources) startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) if startFile == "" || startFile == "" { startFile = defaultStartFileForType(tpl) } commandTemplate := explicitCommandTemplate if adpanelStartup != "" { commandTemplate = "" } else if commandTemplate == "" { commandTemplate = defaultRuntimeCommandForType(tpl, startFile, dataDir) } if commandTemplate == "" && !imageConfigHasRuntimeDefault(imgCfg) { if adpanelStartup != "" && strings.TrimSpace(env["STARTUP"]) != "" { commandTemplate = "" } else if isManagedProcessRuntime(tpl) { // runtime types have no meaningful idle mode; failing loudly beats // reporting an online server whose PID 1 is "sleep infinity" return fmt.Errorf("no startup command for server %q: configure a startup command or start file, or use an image with a default entrypoint/cmd", name) } else { commandTemplate = "sleep infinity" } } if commandTemplate != "" && shouldPreferImageDefaultRuntimeCommand(commandTemplate, imgCfg) { fmt.Printf("[docker] ignoring path-only template command for %s and using image default entrypoint/cmd: %s\n", imageRef, commandTemplate) commandTemplate = "" if imageWorkdir := normalizeContainerWorkdir(imgCfg.Workdir); imageWorkdir != "" { workdir = imageWorkdir } } var cmdArgs []string if adpanelStartup != "" && len(trimRuntimeProcessArgs(imgCfg.Entrypoint)) == 0 && strings.TrimSpace(env["STARTUP"]) != "" { cmdArgs = []string{"sh", "-lc", env["STARTUP"]} } else if commandTemplate != "" { ensureRuntimeEntrypointScaffold(ctx, serverDir, tpl, commandTemplate, dataDir, workdir, startFile, mainContainerPort) var err error cmdArgs, err = buildRenderedRuntimeProcessArgs(tpl, commandTemplate, dataDir, startFile, imageRef, mainContainerPort, resources, meta, env) if err != nil { return err } } uid, gid := statUIDGID(serverDir) req := dockerContainerCreateRequest{ Image: imageRef, Env: envMapToList(env), Cmd: cmdArgs, WorkingDir: workdir, User: a.structuredContainerUser(ctx, imageRef, uid, gid, runtimeObj), Tty: containerTTYForHost(), OpenStdin: true, AttachStdin: true, AttachStdout: true, AttachStderr: true, } portBindings, exposedPorts := a.buildStructuredPortBindings(serverDir, meta, hostPort, mainContainerPort) req.ExposedPorts = exposedPorts desiredRestart := strings.TrimSpace(fmt.Sprint(runtimeObj["restart"])) if desiredRestart == "" { desiredRestart = "" } resources = withRuntimeDefaultFileLimit(resources, tpl, imageRef) req.HostConfig = buildStructuredHostConfigWithRuntime( binds, portBindings, resources, "no", structuredRuntimeReadOnly(runtimeObj, false), runtimeObj, ) a.broadcastDaemonLog(name, "Provisioning container process with allocated resource limits...") if err := a.runStructuredContainerWithCompatUser(ctx, name, req); err != nil { return err } if err := a.monitorCustomContainerBootstrap(ctx, name, imageRef); err != nil { return err } if desiredRestart != "" && strings.ToLower(desiredRestart) != "no" { a.docker.updateRestartPolicy(ctx, name, desiredRestart) } a.scheduleMisplacedFileRecovery(ctx, name, serverDir) return nil } func isGameServerDockerImage(image string) bool { imageLower := strings.ToLower(image) gameServerPatterns := []string{ "csgo", "cs2", "counterstrike", "minecraft", "paper", "spigot", "bukkit", "forge", "fabric", "hytale", "hytale-docker", "rxmarin/hytale", "valheim", "rust", "ark", "terraria", "assetto", "dayz", "zomboid", "fivem", "redm", "ragemp", "gtav", "gta5", "factorio", "satisfactory", "teamspeak", "ts3", "mumble", "starbound", "unturned", "7daystodie", "7dtd", "conan", "empyrion", "hurtworld", "mordhau", "squad", "insurgency", "garrysmod", "gmod", "srcds", "avorion", "astroneer", "barotrauma", "palworld", "enshrouded", "soulmask", "ptero-eggs", "cm2network", "gameservermanagers", "linuxgsm", "steamcmd", "itzg/minecraft", "ich777", } for _, pattern := range gameServerPatterns { if strings.Contains(imageLower, pattern) { return true } } return false } func getGameServerDataPath(image string) string { imageLower := strings.ToLower(image) if strings.Contains(imageLower, "cm2network/csgo") || strings.Contains(imageLower, "csgo") { return "/home/steam/csgo-dedicated" } if strings.Contains(imageLower, "cm2network/cs2") || strings.Contains(imageLower, "cs2") { return "/home/steam/cs2-dedicated" } if strings.Contains(imageLower, "cm2network/tf2") { return "/home/steam/tf2-dedicated" } if strings.Contains(imageLower, "fivem") || strings.Contains(imageLower, "cfx") { return "/config" } if strings.Contains(imageLower, "ragemp") { return "/ragemp" } if strings.Contains(imageLower, "valheim") { return "/config" } if strings.Contains(imageLower, "rust") && !strings.Contains(imageLower, "rustlang") { return "/steamcmd/rust" } if strings.Contains(imageLower, "ark") { return "/ark" } if strings.Contains(imageLower, "itzg/minecraft") { return "/data" } if strings.Contains(imageLower, "terraria") { return "/config" } if strings.Contains(imageLower, "factorio") { return "/factorio" } if strings.Contains(imageLower, "satisfactory") { return "/config" } if strings.Contains(imageLower, "teamspeak") || strings.Contains(imageLower, "ts3") { return "/var/ts3server" } if strings.Contains(imageLower, "7daystodie") || strings.Contains(imageLower, "7dtd") { return "/steamcmd/7dtd" } if strings.Contains(imageLower, "garrysmod") || strings.Contains(imageLower, "gmod") { return "/home/steam/gmod-dedicated" } if strings.Contains(imageLower, "palworld") { return "/palworld" } if strings.Contains(imageLower, "enshrouded") { return "/config" } if strings.Contains(imageLower, "linuxgsm") || strings.Contains(imageLower, "gameservermanagers") { return "/home/linuxgsm" } if strings.Contains(imageLower, "ich777") { return "/serverdata" } return "/data" } func getGameServerUID(image string) int { imageLower := strings.ToLower(image) if strings.Contains(imageLower, "cm2network") { return 1000 } if strings.Contains(imageLower, "itzg/minecraft") { return 1000 } if strings.Contains(imageLower, "linuxgsm") || strings.Contains(imageLower, "gameservermanagers") { return 1000 } if strings.Contains(imageLower, "ich777") { return 99 } return 1000 } func fixGameServerVolumePermissions(serverDir string, image string) error { uid := getGameServerUID(image) gid := uid fmt.Printf("[docker] Setting volume permissions for game server: chown -R %d:%d %s\n", uid, gid, serverDir) resolvedServerDir, resolveErr := filepath.EvalSymlinks(serverDir) if resolveErr != nil { return fmt.Errorf("cannot resolve server directory path: %v", resolveErr) } if resolvedServerDir != filepath.Clean(serverDir) { fmt.Printf("[security] serverDir is a symlink: %s -> %s, using resolved path\n", serverDir, resolvedServerDir) serverDir = resolvedServerDir } cmd := exec.Command("chown", "-Rh", fmt.Sprintf("%d:%d", uid, gid), serverDir) if output, err := cmd.CombinedOutput(); err != nil { fmt.Printf("[docker] Warning: chown failed: %v, output: %s\n", err, string(output)) if err2 := os.Chown(serverDir, uid, gid); err2 != nil { return fmt.Errorf("failed to set volume permissions: %v", err2) } } if err := os.Chmod(serverDir, 0755); err != nil { fmt.Printf("[docker] Warning: failed to chmod %s: %v\n", serverDir, err) } fmt.Printf("[docker] Volume permissions set successfully for %s\n", serverDir) return nil } func guessStartupCommand(serverDir string, image string) string { imageLower := strings.ToLower(image) if _, err := os.Stat(filepath.Join(serverDir, "package.json")); err == nil { return "cd /app && npm install --production && npm start" } if _, err := os.Stat(filepath.Join(serverDir, "requirements.txt")); err == nil { if _, err := os.Stat(filepath.Join(serverDir, "main.py")); err == nil { return "cd /app && pip install -r requirements.txt && python main.py" } if _, err := os.Stat(filepath.Join(serverDir, "app.py")); err == nil { return "cd /app && pip install -r requirements.txt && python app.py" } if _, err := os.Stat(filepath.Join(serverDir, "run.py")); err == nil { return "cd /app && pip install -r requirements.txt && python run.py" } return "cd /app && pip install -r requirements.txt && python main.py" } if strings.Contains(imageLower, "python") { if _, err := os.Stat(filepath.Join(serverDir, "main.py")); err == nil { return "python /app/main.py" } if _, err := os.Stat(filepath.Join(serverDir, "app.py")); err == nil { return "python /app/app.py" } return "python /app/main.py" } if strings.Contains(imageLower, "node") { if _, err := os.Stat(filepath.Join(serverDir, "index.js")); err == nil { return "node /app/index.js" } if _, err := os.Stat(filepath.Join(serverDir, "app.js")); err == nil { return "node /app/app.js" } return "node /app/index.js" } if strings.Contains(imageLower, "go") || strings.Contains(imageLower, "golang") { if _, err := os.Stat(filepath.Join(serverDir, "main.go")); err == nil { return "cd /app && go run main.go" } return "cd /app && go run ." } if strings.Contains(imageLower, "java") || strings.Contains(imageLower, "openjdk") { files, _ := filepath.Glob(filepath.Join(serverDir, "*.jar")) if len(files) > 0 { jarName := filepath.Base(files[0]) return fmt.Sprintf("java -jar /app/%s", jarName) } return "java -jar /app/app.jar" } if strings.Contains(imageLower, "ruby") { if _, err := os.Stat(filepath.Join(serverDir, "Gemfile")); err == nil { return "cd /app && bundle install && bundle exec ruby main.rb" } return "ruby /app/main.rb" } if strings.Contains(imageLower, "php") { return "php -S 0.0.0.0:${PORT:-8080} -t /app" } if strings.Contains(imageLower, "nginx") { return "" } if strings.Contains(imageLower, "redis") { return "" } if strings.Contains(imageLower, "postgres") || strings.Contains(imageLower, "mysql") || strings.Contains(imageLower, "mariadb") { return "" } return "" } type logTail struct { name string closed bool dockerSnapshotPrimed bool mu sync.Mutex writeMu sync.Mutex clients map[chan string]struct{} recent []string recentN int suppressEchoes []commandEchoSuppressEntry knownEchoDupes map[string]struct{} // Persistent on-disk console log (Pterodactyl/Wings-style). Every line that // enters the ring buffer is also appended here so a refresh can be served // from a durable source that does NOT get recycled like the in-memory ring. // The file is truncated whenever the container (re)starts. persistMu sync.Mutex persistPath string persistLines int persistLineTotal int64 // snapshotEpochMs is a STABLE time anchor (UnixMilli) used to assign // synthetic, strictly-increasing timestamps to persisted snapshot lines that // have no real per-line timestamp. It is set once (lazily, on first use) and // reset on a genuine container (re)start. Because it does not change between // refreshes, the same on-disk line is always served with the SAME synthetic // ts, so the panel's client-side dedup (keyed on ts:source:line) stays // stable and stops re-appending boot lines on every refresh. snapshotEpochMs int64 // runStartMs is the wall-clock anchor (UnixMilli) for the CURRENT persisted // run. It is captured the moment the persisted log is (re)scoped to a run // (genuine container restart, or first seed when the node attaches to an // already-running container). Synthetic snapshot timestamps are assigned // FORWARD from this anchor (runStartMs + position*step), never backward from // "now". // // Why this matters: the panel marks a console "reset" at server-start time // (wall clock) and then drops any history line whose ts < resetAt. The old // scheme anchored the synthetic window at (now - count*step) and stepped // forward to end at "now", so the EARLIEST boot lines received timestamps // far in the past — well before the start/reset boundary — and the panel // filtered them out, leaving only the last few lines after a refresh. By // anchoring forward from the actual run start (which is ~= the panel's // resetAt) every snapshot line is guaranteed to be >= resetAt, so the full // boot log survives a refresh. It is reset (to 0) on a genuine restart so a // new run re-anchors. runStartMs int64 stopCh chan struct{} cmd *exec.Cmd conn io.ReadWriteCloser } type commandEchoSuppressEntry struct { command string expiresAt time.Time remaining int } type logSnapshotCall struct { done chan struct{} entries []logSnapshotEntry } type logSnapshotEntry struct { line string ts int64 } const ( logTailRecentMaxLines = 1200 consoleCommandEchoSuppressTTL = 8 * time.Second // Maximum number of lines kept in the persistent on-disk console log per // server. When exceeded, the oldest lines are trimmed (rotated) so the file // stays bounded, exactly like Pterodactyl/Wings cap their console buffer. consolePersistMaxLines = 5000 // Marker prefix used to embed a user-issued console command as a single, // in-order line inside the very same log stream as its output. This makes // the node's log buffer the one and only source of truth for console // ordering (Pterodactyl/Wings-style), so commands and their output never // need to be re-interleaved from two clocks on the panel side. The prefix // is plain ASCII (no leading ">=. " or control chars) so it survives // cleanLogLine untouched. The panel/client recognise this prefix and render // it as a "[HH:MM:SS CMD] " line. consoleCommandMarkerPrefix = "ADPANELCMD>> " consoleDaemonMarkerPrefix = "ADAEMON>> " ) type logManager struct { mu sync.Mutex tails map[string]*logTail d Docker debug bool // logsDir is the directory where per-server persistent console logs are // stored. Set by the agent after construction; if empty, persistence is // disabled (in-memory only) and behaviour falls back to the ring buffer. logsDir string snapshotMu sync.Mutex snapshotInFlight map[string]*logSnapshotCall } func newLogManager(d Docker, debug bool) *logManager { return &logManager{ tails: map[string]*logTail{}, d: d, debug: debug, snapshotInFlight: map[string]*logSnapshotCall{}, } } func normalizeStreamedLogLine(raw string) string { line := strings.TrimRight(raw, "\r\n") if strings.HasPrefix(line, "stdout:") { line = strings.TrimPrefix(line, "stdout:") } else if strings.HasPrefix(line, "stderr:") { line = strings.TrimPrefix(line, "stderr:") } return cleanLogLine(line) } func (t *logTail) appendRecentLocked(line string) { if line == "" { return } limit := t.recentN if limit <= 0 { limit = logTailRecentMaxLines } for _, part := range strings.Split(line, "\n") { part = strings.TrimRight(part, "\r") if part == "" { continue } t.recent = append(t.recent, part) } if overflow := len(t.recent) - limit; overflow > 0 { copy(t.recent, t.recent[overflow:]) t.recent = t.recent[:limit] } } func (t *logTail) appendRecentBatch(lines []string) { if len(lines) == 0 { return } t.mu.Lock() for _, line := range lines { t.appendRecentLocked(cleanLogLine(line)) } t.mu.Unlock() } func (t *logTail) snapshotRecent(tail int) []string { if tail <= 0 { return nil } t.mu.Lock() defer t.mu.Unlock() if len(t.recent) == 0 { return nil } if tail > len(t.recent) { tail = len(t.recent) } out := make([]string, tail) copy(out, t.recent[len(t.recent)-tail:]) return out } // --- Persistent on-disk console log (Pterodactyl/Wings-style) -------------- // // Rationale: the in-memory ring buffer (`recent`, capped at // logTailRecentMaxLines) is recycled. A bulky burst of output (e.g. a Minecraft // `/help` dump) or a few minutes of activity evicts older output while the tiny // command-marker lines persist longer, so a refresh after ~5-10 min showed only // "> cmd" markers plus the last command's output. Wings/Pterodactyl avoid this // by streaming every line to a durable file and serving the console from it. // // We mirror that: every line written to the ring buffer is also appended to a // per-server file. The file is truncated when the container (re)starts so it is // always scoped to the current run, and it is line-capped so it stays bounded. func (lm *logManager) persistDirReady() string { if lm == nil || strings.TrimSpace(lm.logsDir) == "" { return "" } if err := ensureDir(lm.logsDir); err != nil { return "" } return lm.logsDir } func (lm *logManager) persistPathFor(name string) string { dir := lm.persistDirReady() if dir == "" { return "" } safe := sanitizeName(name) if safe == "" { safe = "unknown" } return filepath.Join(dir, safe+".log") } // bindPersistPath wires the on-disk log path for a tail and seeds its current // line count so rotation works immediately after a restart. func (lm *logManager) bindPersistPath(t *logTail) { if lm == nil || t == nil { return } path := lm.persistPathFor(t.name) if path == "" { return } t.persistMu.Lock() if t.persistPath == "" { t.persistPath = path if fi, err := os.Stat(path); err == nil && fi.Size() > 0 { if fi.Size() > consolePersistMaxBytes { t.rotatePersistedLogLocked(true) } else { t.persistLines = countFileLines(path) } t.persistLineTotal = int64(t.persistLines) t.mu.Lock() if t.runStartMs == 0 { t.runStartMs = fi.ModTime().UnixMilli() } t.mu.Unlock() } } t.persistMu.Unlock() } // truncatePersistedLog clears the on-disk console log. Called when the // container (re)starts so the persisted console always reflects the current // run only (matches "delete on each re-run of the container"). func (t *logTail) truncatePersistedLog() { t.persistMu.Lock() defer t.persistMu.Unlock() if t.persistPath == "" { return } if f, err := os.OpenFile(t.persistPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600); err == nil { _ = f.Close() } t.persistLines = 0 t.persistLineTotal = 0 // New run => the synthetic-timestamp anchors must be re-based so the next // snapshot reflects the fresh run. runStartMs captures the wall-clock moment // this run's persisted log begins; synthetic snapshot timestamps are // assigned forward from it so they always land at/after the panel's // start-time reset marker (and therefore survive the panel's resetAt filter). t.mu.Lock() t.snapshotEpochMs = 0 t.runStartMs = time.Now().UnixMilli() t.mu.Unlock() } // markRunStartIfUnset records the run-start anchor when it has not been set yet // (e.g. the node attaches to an already-running container and seeds the empty // persisted log from docker logs without a preceding truncate). Using the // earliest available anchor keeps synthetic snapshot timestamps monotonic and // at/after the panel's reset boundary. func (t *logTail) markRunStartIfUnset() { t.persistMu.Lock() path := t.persistPath t.persistMu.Unlock() t.mu.Lock() if t.runStartMs == 0 { if path != "" { if fi, err := os.Stat(path); err == nil { t.runStartMs = fi.ModTime().UnixMilli() } } if t.runStartMs == 0 { t.runStartMs = time.Now().UnixMilli() } } t.mu.Unlock() } func (t *logTail) runStartAnchor() int64 { t.mu.Lock() defer t.mu.Unlock() return t.runStartMs } // snapshotEpoch returns a STABLE base UnixMilli timestamp used as the anchor for // assigning synthetic timestamps to persisted snapshot lines that carry no real // per-line timestamp. It is computed once and cached on the tail so every // refresh serves the same on-disk line with the same synthetic ts (keeping the // panel's client-side dedup stable). // // The anchor is the CURRENT run's start time (runStartMs), so synthetic // timestamps are assigned FORWARD from the run start: ts(pos) = base + // pos*stepMs. This guarantees every line is >= the run start, which is ~= the // panel's start-time reset marker, so the panel never filters boot lines out as // "before reset" (the bug where only the last few lines survived a refresh). // // `count` is unused for the anchor itself but retained for signature // compatibility; the forward anchoring no longer needs to shift the window into // the past. If runStartMs is somehow unset we fall back to a conservative // recent anchor that still keeps lines close to "now". func (t *logTail) snapshotEpoch(count int, stepMs int64) int64 { t.mu.Lock() defer t.mu.Unlock() if t.snapshotEpochMs == 0 { if t.runStartMs > 0 { t.snapshotEpochMs = t.runStartMs } else { if count < 0 { count = 0 } t.snapshotEpochMs = time.Now().UnixMilli() - int64(count)*stepMs } } return t.snapshotEpochMs } func (t *logTail) persistedLinePosition() int64 { t.persistMu.Lock() defer t.persistMu.Unlock() return t.persistLineTotal } func countFileLines(path string) int { f, err := os.Open(path) if err != nil { return 0 } defer f.Close() count := 0 buf := make([]byte, 64*1024) for { n, err := f.Read(buf) for i := 0; i < n; i++ { if buf[i] == '\n' { count++ } } if err != nil { break } } return count } func normalizeCommandEchoText(value string) string { text := ansiSGRRE.ReplaceAllString(value, "") text = strings.ReplaceAll(text, "\r\n", "\n") text = strings.ReplaceAll(text, "\r", "\n") text = strings.ReplaceAll(text, "\n", " ") text = strings.Join(strings.Fields(strings.TrimSpace(text)), " ") if len(text) >= 2 { if (strings.HasPrefix(text, `"`) && strings.HasSuffix(text, `"`)) || (strings.HasPrefix(text, `'`) && strings.HasSuffix(text, `'`)) { text = strings.TrimSpace(text[1 : len(text)-1]) } } return text } func duplicatedFirstRuneCommandEcho(command string) string { if command == "" { return "" } r, size := utf8.DecodeRuneInString(command) if r == utf8.RuneError && size == 0 { return "" } return string(r) + command } func isPrefixedCommandEchoArtifact(text, command string) bool { if text == "" || command == "" || text == command { return false } if !strings.HasSuffix(text, command) { return false } prefix := strings.TrimSpace(strings.TrimSuffix(text, command)) return prefix != "" && strings.HasPrefix(command, prefix) } func isLikelyCommandEchoArtifact(line, command string) bool { text := normalizeCommandEchoText(line) cmd := normalizeCommandEchoText(command) if text == "" || cmd == "" { return false } if text == cmd || text == "$ "+cmd || text == "> "+cmd { return true } if text == duplicatedFirstRuneCommandEcho(cmd) { return true } if isPrefixedCommandEchoArtifact(text, cmd) { return true } runes := []rune(cmd) if len(runes) > 0 && len([]rune(text)) >= len(runes) { first := string(runes[0]) for n := 2; n <= 5; n++ { if text == strings.Repeat(first, n)+string(runes[1:]) || text == strings.Repeat(first, n)+cmd { return true } } } return false } func (t *logTail) addCommandEchoSuppress(command string) { cmd := normalizeCommandEchoText(command) if cmd == "" { return } now := time.Now() t.mu.Lock() defer t.mu.Unlock() kept := t.suppressEchoes[:0] for _, entry := range t.suppressEchoes { if entry.remaining > 0 && now.Before(entry.expiresAt) { kept = append(kept, entry) } } t.suppressEchoes = append(kept, commandEchoSuppressEntry{ command: cmd, expiresAt: now.Add(consoleCommandEchoSuppressTTL), remaining: 10, }) dupe := duplicatedFirstRuneCommandEcho(cmd) if dupe != "" { if t.knownEchoDupes == nil { t.knownEchoDupes = make(map[string]struct{}) } t.knownEchoDupes[dupe] = struct{}{} } if len(t.suppressEchoes) > 24 { t.suppressEchoes = t.suppressEchoes[len(t.suppressEchoes)-24:] } } func (t *logTail) shouldSuppressCommandEcho(line string) bool { if line == "" { return false } now := time.Now() t.mu.Lock() defer t.mu.Unlock() text := normalizeCommandEchoText(line) if text != "" && t.knownEchoDupes != nil { if _, ok := t.knownEchoDupes[text]; ok { return true } } if len(t.suppressEchoes) == 0 { return false } suppressed := false kept := t.suppressEchoes[:0] for _, entry := range t.suppressEchoes { if entry.remaining <= 0 || !now.Before(entry.expiresAt) { continue } if !suppressed && isLikelyCommandEchoArtifact(line, entry.command) { entry.remaining-- suppressed = true } if entry.remaining > 0 { kept = append(kept, entry) } } t.suppressEchoes = kept return suppressed } func (t *logTail) markDockerSnapshotPrimed() bool { t.mu.Lock() defer t.mu.Unlock() if t.dockerSnapshotPrimed { return false } t.dockerSnapshotPrimed = true return true } func splitDockerLogTimestamp(raw string) (string, int64) { line := strings.TrimRight(raw, "\r") token, rest, ok := strings.Cut(line, " ") if !ok || token == "" || rest == "" { return line, 0 } if t, err := time.Parse(time.RFC3339Nano, token); err == nil { return strings.TrimLeft(rest, " \t"), t.UnixMilli() } return line, 0 } func parseDockerLogSnapshotEntries(raw string, tail int) []logSnapshotEntry { if raw == "" { return nil } raw = stripDockerStreamFraming(raw) raw = strings.ReplaceAll(raw, "\r\n", "\n") raw = strings.ReplaceAll(raw, "\r", "\n") parts := strings.Split(raw, "\n") entries := make([]logSnapshotEntry, 0, len(parts)) for _, part := range parts { part = strings.TrimRight(part, "\r") if strings.TrimSpace(part) == "" { continue } linePart, ts := splitDockerLogTimestamp(part) cleaned := cleanLogLine(linePart) if cleaned == "" { continue } for _, line := range strings.Split(cleaned, "\n") { line = strings.TrimRight(line, "\r") if line == "" { continue } entries = append(entries, logSnapshotEntry{line: line, ts: ts}) } } if tail > 0 && len(entries) > tail { entries = entries[len(entries)-tail:] } return entries } func parseDockerLogSnapshot(raw string, tail int) []string { entries := parseDockerLogSnapshotEntries(raw, tail) lines := make([]string, 0, len(entries)) for _, entry := range entries { lines = append(lines, entry.line) } return lines } func (lm *logManager) fetchTailSnapshotSingleflight(name string, tail int, fetch func() []logSnapshotEntry) []logSnapshotEntry { if tail <= 0 || fetch == nil { return nil } key := fmt.Sprintf("%s:%d", name, tail) lm.snapshotMu.Lock() if call, ok := lm.snapshotInFlight[key]; ok { lm.snapshotMu.Unlock() <-call.done return append([]logSnapshotEntry(nil), call.entries...) } call := &logSnapshotCall{done: make(chan struct{})} lm.snapshotInFlight[key] = call lm.snapshotMu.Unlock() entries := fetch() lm.snapshotMu.Lock() call.entries = append([]logSnapshotEntry(nil), entries...) close(call.done) delete(lm.snapshotInFlight, key) lm.snapshotMu.Unlock() return append([]logSnapshotEntry(nil), entries...) } func (lm *logManager) getOrCreate(name string) *logTail { lm.mu.Lock() defer lm.mu.Unlock() if t, ok := lm.tails[name]; ok { return t } t := &logTail{ name: name, clients: map[chan string]struct{}{}, recentN: logTailRecentMaxLines, stopCh: make(chan struct{}), } lm.tails[name] = t lm.bindPersistPath(t) go lm.followLoop(t) return t } func (lm *logManager) removeIfEmpty(t *logTail) { lm.mu.Lock() defer lm.mu.Unlock() t.mu.Lock() clientCount := len(t.clients) alreadyClosed := t.closed t.mu.Unlock() if clientCount == 0 && !alreadyClosed { t.mu.Lock() if t.closed { t.mu.Unlock() return } t.closed = true cmd := t.cmd conn := t.conn t.mu.Unlock() close(t.stopCh) if cmd != nil && cmd.Process != nil { _ = cmd.Process.Kill() } if conn != nil { _ = conn.Close() } delete(lm.tails, t.name) } } func (lm *logManager) primeDockerLogSnapshot(t *logTail, tail int) { if t == nil || tail <= 0 || !t.markDockerSnapshotPrimed() { return } ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) stdout, stderr := collectDockerLogTail(ctx, t.name, tail, true) cancel() entries := parseDockerLogSnapshotEntries(stdout, tail) for _, entry := range parseDockerLogSnapshotEntries(stderr, tail) { lower := strings.ToLower(entry.line) if strings.Contains(lower, "no such container") || strings.Contains(lower, "can not get logs from container which is dead") { continue } entries = append(entries, entry) } sort.SliceStable(entries, func(i, j int) bool { left := entries[i].ts right := entries[j].ts if left == 0 || right == 0 { return false } return left < right }) if len(entries) > tail { entries = entries[len(entries)-tail:] } lines := make([]string, 0, len(entries)) for _, entry := range entries { lines = append(lines, entry.line) } t.appendRecentBatch(lines) } // seedPersistedLogFromDocker writes the current docker-logs tail into an empty // persistent console file. Used only when the node process (re)starts against a // container that was already running, so prior output survives a panel/node // restart without being duplicated by the live stream (which only carries new // lines from attach time onward). func (lm *logManager) seedPersistedLogFromDocker(t *logTail, tail int) { if t == nil || tail <= 0 { return } ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) stdout, stderr := collectDockerLogTail(ctx, t.name, tail, true) cancel() entries := parseDockerLogSnapshotEntries(stdout, tail) for _, entry := range parseDockerLogSnapshotEntries(stderr, tail) { lower := strings.ToLower(entry.line) if strings.Contains(lower, "no such container") || strings.Contains(lower, "can not get logs from container which is dead") { continue } entries = append(entries, entry) } sort.SliceStable(entries, func(i, j int) bool { left := entries[i].ts right := entries[j].ts if left == 0 || right == 0 { return false } return left < right }) if len(entries) > tail { entries = entries[len(entries)-tail:] } lines := make([]string, 0, len(entries)) for _, entry := range entries { if entry.line != "" { lines = append(lines, entry.line) } } t.appendPersistedLines(lines) // Broadcast the seeded lines to any clients already connected (e.g. the // panel page was open when the physical host rebooted and the node brought // servers back up). Without this the live console stays blank until the // user manually refreshes, because seedPersistedLog only fills the // on-disk log — it does not push to SSE channels. We send to the live // channel the same way sendToClients does, but skip re-appending to the // ring buffer (primeDockerLogSnapshot, called right after, will do that). if len(lines) > 0 { t.mu.Lock() for _, line := range lines { for ch := range t.clients { select { case ch <- line: default: } } } t.mu.Unlock() } } func (lm *logManager) broadcastLiveLogLine(t *logTail, prefix, raw string) { line := cleanLogLine(raw) if line == "" { return } if t.shouldSuppressCommandEcho(line) { return } lower := strings.ToLower(line) if strings.Contains(lower, "no such container") { return } if strings.Contains(lower, "can not get logs from container which is dead") { return } lm.sendToClients(t, prefix+line) } func (lm *logManager) suppressCommandEcho(name, command string) { if lm == nil { return } t := lm.getOrCreate(name) if t == nil { return } t.addCommandEchoSuppress(command) } // recordCommandLine embeds a user-issued command into the live log stream as a // single marker line, both broadcasting it to connected clients and appending // it to the recent ring buffer. Because it is inserted at the exact moment the // command is accepted, it lands in correct chronological position relative to // surrounding output, and it survives a refresh via the normal log snapshot. // This is the single source of truth for command ordering; the panel no longer // merges a separate command list. func (lm *logManager) recordCommandLine(name, command string) { if lm == nil { return } cmd := normalizeCommandEchoText(command) if strings.TrimSpace(name) == "" || cmd == "" { return } // Use getOrCreate so the marker is ALWAYS persisted into the recent ring // buffer, even if no SSE client is currently attached (otherwise the command // would be silently dropped and never appear after a refresh). The SSE // handler registers its tail under the raw server name, so create/lookup the // tail under that same key to guarantee a single shared buffer. t := lm.getOrCreate(name) if t == nil { return } // Ensure the boot/log snapshot is primed before we record the marker, so the // command lands in correct chronological position. If the user sends a // command right after start (before the live stream has filled the buffer), // priming pulls the existing docker logs first; the marker is then appended // after them rather than being pinned at the very top on refresh. lm.primeDockerLogSnapshot(t, 200) marker := consoleCommandMarkerPrefix + cmd // Persist the marker into the ring buffer AND broadcast it live, in a single // locked operation so live clients and the persisted record are identical and // in the same order. The ring buffer is the single authoritative source the // panel replays on refresh, so the marker must always be recorded here at the // exact moment the command is accepted; this places it in correct // chronological position relative to surrounding output (Wings-style: the // command line lives inline in the one log stream). t.mu.Lock() t.appendRecentLocked(marker) for ch := range t.clients { select { case ch <- marker: default: } } t.mu.Unlock() // Persist the command marker to the durable on-disk log too, so it survives // a refresh in correct chronological position alongside output. t.appendPersistedLines([]string{marker}) } func (lm *logManager) appendDaemonMessage(name, message string) { if lm == nil || strings.TrimSpace(name) == "" || strings.TrimSpace(message) == "" { return } t := lm.getOrCreate(name) if t == nil { return } t.markRunStartIfUnset() marker := consoleDaemonMarkerPrefix + strings.TrimSpace(message) t.mu.Lock() t.appendRecentLocked(marker) for ch := range t.clients { select { case ch <- marker: default: } } t.mu.Unlock() t.appendPersistedLines([]string{marker}) } func (a *Agent) broadcastDaemonLog(name, message string) { if a == nil || a.logs == nil || strings.TrimSpace(name) == "" || strings.TrimSpace(message) == "" { return } a.logs.appendDaemonMessage(name, message) } func (lm *logManager) followDockerLogsCLI(t *logTail) error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() cmd := exec.CommandContext(ctx, "docker", "logs", "-f", "--tail", "0", t.name) stdout, err := cmd.StdoutPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } t.mu.Lock() t.cmd = cmd t.conn = nil t.mu.Unlock() done := make(chan struct{}) go func() { select { case <-t.stopCh: cancel() case <-done: } }() var wg sync.WaitGroup scan := func(r io.Reader, prefix string) { defer wg.Done() sc := bufio.NewScanner(r) buf := make([]byte, 0, 64*1024) sc.Buffer(buf, 2*1024*1024) for sc.Scan() { lm.broadcastLiveLogLine(t, prefix, sc.Text()) } } wg.Add(2) go scan(stdout, "stdout:") go scan(stderr, "stderr:") err = cmd.Wait() close(done) wg.Wait() t.mu.Lock() if t.cmd == cmd { t.cmd = nil } t.mu.Unlock() if ctx.Err() != nil { return ctx.Err() } return err } func (lm *logManager) followLoop(t *logTail) { backoff := 1 * time.Second lastState := "" fmt.Printf("[logs] starting follow loop for container: %s\n", t.name) for { select { case <-t.stopCh: fmt.Printf("[logs] stop signal received for: %s\n", t.name) return default: } ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) state := lm.d.containerState(ctx, t.name) cancel() if state == "" { if lastState != "" && lastState != "missing" { fmt.Printf("[logs] container %s no longer exists, waiting...\n", t.name) } lastState = "missing" time.Sleep(backoff) if backoff < 5*time.Second { backoff += 500 * time.Millisecond } continue } if state != "running" { if state != lastState { fmt.Printf("[logs] container %s is %s, waiting for running state before attaching logs\n", t.name, state) } lastState = state time.Sleep(backoff) if backoff < 5*time.Second { backoff += 500 * time.Millisecond } continue } if lastState != "running" { fmt.Printf("[logs] container %s running, attaching to live logs\n", t.name) t.markRunStartIfUnset() } lastState = "running" backoff = 1 * time.Second if preferDockerCLIConsoleTransport() { if err := lm.followDockerLogsCLI(t); err != nil { if lm.debug { fmt.Printf("[logs] Docker CLI log stream ended for %s: %v\n", t.name, err) } } select { case <-t.stopCh: return default: time.Sleep(500 * time.Millisecond) continue } } openStdin := false if !preferDockerCLIPTYStdinTransport() { openStdinCtx, openStdinCancel := context.WithTimeout(context.Background(), 3*time.Second) openStdin = lm.d.containerOpenStdin(openStdinCtx, t.name) openStdinCancel() } attachCtx, attachCancel := context.WithTimeout(context.Background(), 10*time.Second) stream, err := lm.d.attachContainerAPI(attachCtx, t.name, dockerAttachOptions{Stdin: openStdin, Stdout: true, Stderr: true}) attachCancel() if err != nil { fmt.Printf("[logs] failed to attach live stream for %s: %v\n", t.name, err) if cliErr := lm.followDockerLogsCLI(t); cliErr != nil && lm.debug { fmt.Printf("[logs] Docker CLI log fallback ended for %s: %v\n", t.name, cliErr) } select { case <-t.stopCh: return default: time.Sleep(1 * time.Second) continue } } select { case <-t.stopCh: _ = stream.Close() return default: } t.mu.Lock() t.conn = stream t.mu.Unlock() broadcast := func(r io.Reader) { sc := bufio.NewScanner(r) buf := make([]byte, 0, 64*1024) sc.Buffer(buf, 2*1024*1024) for sc.Scan() { lm.broadcastLiveLogLine(t, "stdout:", sc.Text()) } } broadcast(stream) _ = stream.Close() t.mu.Lock() t.conn = nil t.mu.Unlock() select { case <-t.stopCh: return default: time.Sleep(500 * time.Millisecond) } } } func (lm *logManager) sendToClients(t *logTail, s string) { cleaned := normalizeStreamedLogLine(s) t.mu.Lock() t.appendRecentLocked(cleaned) for ch := range t.clients { select { case ch <- s: default: } } t.mu.Unlock() // Mirror every streamed line into the durable on-disk log so a refresh is // served from a source that is not recycled like the in-memory ring. if cleaned != "" { t.appendPersistedLines([]string{cleaned}) } } func (lm *logManager) writeCommand(name, command string) error { if lm == nil { return fmt.Errorf("log manager unavailable") } dockerName := dockerContainerName(name) cmd := strings.TrimSpace(command) if dockerName == "" || cmd == "" { return fmt.Errorf("missing-params") } lm.mu.Lock() t := lm.tails[dockerName] if t == nil && dockerName != name { t = lm.tails[name] } lm.mu.Unlock() if t == nil { return fmt.Errorf("live console stream unavailable") } t.mu.Lock() conn := t.conn closed := t.closed t.mu.Unlock() if closed || conn == nil { return fmt.Errorf("live console stream unavailable") } line := strings.TrimRight(cmd, "\r\n") + "\n" t.writeMu.Lock() defer t.writeMu.Unlock() if deadlineWriter, ok := conn.(interface{ SetWriteDeadline(time.Time) error }); ok { _ = deadlineWriter.SetWriteDeadline(time.Now().Add(stdinWriteTimeout)) defer deadlineWriter.SetWriteDeadline(time.Time{}) } if _, err := io.WriteString(conn, line); err != nil { _ = conn.Close() t.mu.Lock() if t.conn == conn { t.conn = nil } t.mu.Unlock() return fmt.Errorf("live console stdin write failed: %w", err) } return nil } func (lm *logManager) resetRecent(name string) { lm.mu.Lock() t, ok := lm.tails[name] if !ok { dockerName := dockerContainerName(name) if dockerName != name { t, ok = lm.tails[dockerName] } } lm.mu.Unlock() if !ok || t == nil { return } t.mu.Lock() t.recent = nil t.suppressEchoes = nil t.knownEchoDupes = nil t.dockerSnapshotPrimed = false t.mu.Unlock() // Also clear the durable on-disk console log so a manual console reset wipes // persisted history, matching the in-memory reset. t.truncatePersistedLog() } func (a *Agent) resetConsoleLogs(name string) { cleanName := strings.TrimSpace(name) if cleanName == "" { return } // Truncate the durable on-disk console log up front, by PATH, so it is wiped // even when no in-memory tail currently exists (e.g. the previous tail was // killed on stop/restart). This is what guarantees old logs disappear on a // container re-run, matching Pterodactyl/Wings. if a.logs != nil { a.logs.truncatePersistedLogByName(cleanName) a.logs.resetRecent(cleanName) } ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) defer cancel() if err := a.docker.clearContainerLogs(ctx, cleanName); err != nil && a.debug { fmt.Printf("[logs] failed to clear docker logs for %s: %v\n", cleanName, err) } if a.logs != nil { a.logs.truncatePersistedLogByName(cleanName) a.logs.resetRecent(cleanName) } } // truncatePersistedLogByName clears the persistent console log file for a server // regardless of whether an in-memory tail exists. It resolves the same path used // by tails (both the raw name and the docker container name) so a reset always // hits the right file. func (lm *logManager) truncatePersistedLogByName(name string) { if lm == nil { return } candidates := map[string]struct{}{} if p := lm.persistPathFor(name); p != "" { candidates[p] = struct{}{} } if dockerName := dockerContainerName(name); dockerName != "" && dockerName != name { if p := lm.persistPathFor(dockerName); p != "" { candidates[p] = struct{}{} } } for path := range candidates { if f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600); err == nil { _ = f.Close() } } // Also reset the in-memory line counter on any live tail so rotation stays // consistent after the wipe. lm.mu.Lock() for _, key := range []string{name, dockerContainerName(name)} { if t, ok := lm.tails[key]; ok && t != nil { t.persistMu.Lock() t.persistLines = 0 t.persistLineTotal = 0 t.persistMu.Unlock() } } lm.mu.Unlock() } func (lm *logManager) killTail(name string) { lm.mu.Lock() defer lm.mu.Unlock() t, ok := lm.tails[name] if !ok || t == nil { return } t.mu.Lock() alreadyClosed := t.closed if !alreadyClosed { t.closed = true } cmd := t.cmd conn := t.conn t.mu.Unlock() if cmd != nil && cmd.Process != nil { _ = cmd.Process.Kill() } if conn != nil { _ = conn.Close() } if !alreadyClosed { close(t.stopCh) } delete(lm.tails, name) } func (a *Agent) ensureLiveLogs(name string) { if a == nil || a.logs == nil || strings.TrimSpace(name) == "" { return } a.logs.getOrCreate(name) } // getDirSizeBytes returns the PHYSICAL on-disk size of dir: `du -sb` counts a // hardlinked inode once no matter how many names point at it, which is the // honest measure of what the tree occupies on disk. Consumers that want that // physical number (the disk monitor, quota guards via getServerDiskUsage / // getServerTotalUsage, the per-disk capacity scans, status reporting) bind // this; the backup projection must NOT (see getDirSizeBytesPerName). func getDirSizeBytes(dir string) (int64, error) { return getDirSizeBytesWithDuFlags("-sb", dir) } // adpanel:backup-du-hardlinks — getDirSizeBytesPerName returns the size dir // costs when copyDir WRITES it: one full copy per walked NAME. The backup // projection must cost what copyDir writes, not what the tree physically // shares (hardlinked inodes counted once by `du -sb`), or a hardlink farm of // N names over one S-byte file makes N×S backup bytes pass an S-sized // projection. The -l flag (GNU du --count-links; the -sb fast path is already // a GNU-coreutils assumption, and any du rejecting the flags falls back to // the Go walk below, which Lstats every name) charges each hardlink name // separately, so every path through here measures per name. The restore-side // projection deliberately keeps getDirSizeBytes: it sizes a tree copyDir // WROTE (per-name full copies, never hardlinks), where both measures agree. func getDirSizeBytesPerName(dir string) (int64, error) { return getDirSizeBytesWithDuFlags("-sbl", dir) } func getDirSizeBytesWithDuFlags(duFlags, dir string) (int64, error) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() cmd := exec.CommandContext(ctx, "du", duFlags, dir) out, err := cmd.Output() if err != nil { return getDirSizeBytesGo(dir) } parts := strings.Fields(string(out)) if len(parts) < 1 { return getDirSizeBytesGo(dir) } size, err := strconv.ParseInt(parts[0], 10, 64) if err != nil { return getDirSizeBytesGo(dir) } return size, nil } func getDirSizeBytesGo(dir string) (int64, error) { var size int64 err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return nil } if !info.IsDir() { size += info.Size() } return nil }) return size, err } type diskMonitor struct { agent *Agent interval time.Duration stopCh chan struct{} debug bool } func newDiskMonitor(agent *Agent, interval time.Duration, debug bool) *diskMonitor { if interval <= 0 { interval = 60 * time.Second } // Allow operators to tighten the enforcement window without rebuilding. A // shorter interval reduces how far a container can overshoot its quota before // being stopped. Clamped to a sane range so it can never become a busy-loop // that pins CPU with repeated `du` scans. if v := os.Getenv("DISK_MONITOR_MS"); v != "" { if n, err := strconv.Atoi(v); err == nil && n >= 2000 && n <= 600000 { interval = time.Duration(n) * time.Millisecond } } return &diskMonitor{ agent: agent, interval: interval, stopCh: make(chan struct{}), debug: debug, } } func (dm *diskMonitor) start() { go dm.monitorLoop() } func (dm *diskMonitor) stop() { close(dm.stopCh) } func (dm *diskMonitor) monitorLoop() { time.Sleep(10 * time.Second) ticker := time.NewTicker(dm.interval) defer ticker.Stop() for { select { case <-dm.stopCh: return case <-ticker.C: dm.checkAllServers() } } } func (dm *diskMonitor) checkAllServers() { // adpanel:multidisk - check servers on EVERY disk, not just the primary // volumes dir. Secondary-disk servers were never inspected, so their // over-limit usage (e.g. a container downloading a jar larger than its quota) // was never enforced. names := dm.agent.enumerateServerNames() for _, serverName := range names { serverDir := dm.agent.serverDir(serverName) limitBytes := dm.agent.getServerDiskLimitBytes(serverDir) if limitBytes <= 0 { continue } // Optimization: only a *running* container can grow its volume. Skipping // stopped servers avoids a `du -sb` scan per idle server every cycle, which // is what keeps CPU/RAM flat even with a short interval and many servers on // both primary and secondary disks. A stopped over-limit server is already // stopped, so re-stopping it would be a no-op anyway. checkCtx, checkCancel := context.WithTimeout(context.Background(), 4*time.Second) container, _, exists, err := dm.agent.inspectContainerForStats(checkCtx, serverName) checkCancel() if err != nil || !exists || !container.State.Running { continue } usedBytes := dm.agent.getServerTotalUsage(serverDir) if dm.debug { usedGb := float64(usedBytes) / (1024 * 1024 * 1024) limitGb := float64(limitBytes) / (1024 * 1024 * 1024) fmt.Printf("[disk-monitor] %s: %.2f GB / %.2f GB\n", serverName, usedGb, limitGb) } if usedBytes > limitBytes { reason := fmt.Sprintf("disk limit exceeded (%d / %d bytes)", usedBytes, limitBytes) if err := dm.agent.stopServerForPolicy(serverName, "disk-monitor", reason, container, func() bool { currentLimit := dm.agent.getServerDiskLimitBytes(serverDir) return currentLimit > 0 && usedBytes > currentLimit }); err != nil { fmt.Fprintf(os.Stderr, "[disk-monitor] stop %s failed: %v\n", serverName, err) } } } } type networkAbuseMonitor struct { agent *Agent interval time.Duration workers int stopCh chan struct{} debug bool } func newNetworkAbuseMonitor(agent *Agent, interval time.Duration, debug bool) *networkAbuseMonitor { if interval <= 0 { interval = 5 * time.Second } if v := os.Getenv("NETWORK_ABUSE_MONITOR_MS"); v != "" { if n, err := strconv.Atoi(v); err == nil && n >= 1000 && n <= 60000 { interval = time.Duration(n) * time.Millisecond } } workers := runtime.NumCPU() * 2 if workers < 4 { workers = 4 } if workers > 16 { workers = 16 } if v := os.Getenv("NETWORK_ABUSE_MONITOR_WORKERS"); v != "" { if n, err := strconv.Atoi(v); err == nil && n >= 1 && n <= 64 { workers = n } } return &networkAbuseMonitor{ agent: agent, interval: interval, workers: workers, stopCh: make(chan struct{}), debug: debug, } } func (nm *networkAbuseMonitor) start() { go nm.monitorLoop() } func (nm *networkAbuseMonitor) stop() { close(nm.stopCh) } func (nm *networkAbuseMonitor) monitorLoop() { time.Sleep(12 * time.Second) ticker := time.NewTicker(nm.interval) defer ticker.Stop() for { select { case <-nm.stopCh: return default: nm.checkAllServers() } select { case <-nm.stopCh: return case <-ticker.C: } } } func (nm *networkAbuseMonitor) checkAllServers() { // adpanel:multidisk - enumerate across every disk so network anti-abuse rules // (inbound/outbound caps + reset window) are enforced for secondary-disk // servers too, not only those on the primary volumes dir. names := nm.agent.enumerateServerNames() if len(names) == 0 { return } workers := nm.workers if workers > len(names) { workers = len(names) } jobs := make(chan string) var wg sync.WaitGroup for i := 0; i < workers; i++ { wg.Add(1) go func() { defer wg.Done() for name := range jobs { nm.checkServer(name) } }() } for _, name := range names { select { case <-nm.stopCh: close(jobs) wg.Wait() return case jobs <- name: } } close(jobs) wg.Wait() } func (nm *networkAbuseMonitor) checkServer(serverName string) { if !isValidContainerName(serverName) || nm.agent == nil { return } serverDir := nm.agent.serverDir(serverName) meta := nm.agent.loadMeta(serverDir) rule := networkAntiAbuseRuleFromMeta(meta) if !rule.enabled { return } inspectCtx, inspectCancel := context.WithTimeout(context.Background(), 3500*time.Millisecond) inspected, _, exists, err := nm.agent.inspectContainerForStats(inspectCtx, serverName) inspectCancel() if err != nil || !exists || !inspected.State.Running { if nm.debug && err != nil { fmt.Fprintf(os.Stderr, "[network-abuse] inspect %s failed: %v\n", serverName, err) } return } statsCtx, statsCancel := context.WithTimeout(context.Background(), 3500*time.Millisecond) stats, err := nm.agent.readContainerStatsForServer(statsCtx, serverName) statsCancel() if err != nil { if nm.debug { fmt.Fprintf(os.Stderr, "[network-abuse] stats %s failed: %v\n", serverName, err) } return } if len(stats.Networks) == 0 { return } rawRx, rawTx := sumDockerNetworkBytes(stats.Networks) if nm.agent.resourceStats == nil { return } entry := nm.agent.resourceStats.get(serverName) now := time.Now() entry.mu.Lock() entry.touchedAt = now _, _, windowRx, windowTx, _ := entry.updateNetworkCounters(inspected.ID, rawRx, rawTx, now, rule.resetEvery) entry.mu.Unlock() inboundExceeded, outboundExceeded := rule.exceeded(windowRx, windowTx) if !inboundExceeded && !outboundExceeded { return } reason := "network limit reached" if inboundExceeded && outboundExceeded { reason = "inbound and outbound network limits reached" } else if inboundExceeded { reason = "inbound network limit reached" } else if outboundExceeded { reason = "outbound network limit reached" } if nm.debug { fmt.Printf("[network-abuse] %s exceeded limit: inbound=%d/%d outbound=%d/%d\n", serverName, windowRx, rule.inboundLimitBytes, windowTx, rule.outboundLimitBytes) } if err := nm.agent.stopServerForPolicy(serverName, "network-abuse", reason, inspected, func() bool { return nm.agent.verifyServerNetworkQuota(serverName, nm.agent.loadMeta(serverDir), time.Now()) != nil }); err != nil && nm.debug { fmt.Fprintf(os.Stderr, "[network-abuse] stop %s failed: %v\n", serverName, err) } } func (a *Agent) stopServerForPolicy(name, policy, reason string, original dockerContainerInspectForStats, stillExceeded func() bool) error { if !isValidContainerName(name) { return fmt.Errorf("invalid container name") } opMu := a.tryLockServerOp(name) if opMu == nil { return nil } defer opMu.Unlock() if a.serverStopPending(name) { return nil } a.stopMu.Lock() a.stoppingNow[name] = time.Now() a.stopMu.Unlock() defer a.clearPendingServerStop(name) inspectCtx, inspectCancel := context.WithTimeout(context.Background(), 5*time.Second) inspected, _, exists, err := a.inspectContainerForStats(inspectCtx, name) inspectCancel() if err != nil { return err } if !exists || !inspected.State.Running || !sameDockerContainerRun(original, inspected) { return nil } // adpanel:policy-stop-current-limit - a settings write can land while usage is being sampled. if !stillExceeded() { return nil } updateCtx, updateCancel := context.WithTimeout(context.Background(), 5*time.Second) a.docker.updateRestartNo(updateCtx, original.ID) updateCancel() if a.stdinMgr != nil { a.stdinMgr.remove(name) } serverDir := a.serverDir(name) meta := a.loadMeta(serverDir) serverType := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) templateType := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) isMinecraft := serverType == "" || serverType == "minecraft" || templateType == "minecraft" if isMinecraft { commandCtx, commandCancel := context.WithTimeout(context.Background(), 5*time.Second) _ = a.docker.sendCommand(commandCtx, a.stdinMgr, name, "stop", nil) commandCancel() } a.broadcastContainerEvent(name, "stopping") time.Sleep(a.stopGrace) if err := a.finishServerStop(name, original.ID); err != nil { return err } fmt.Printf("[%s] Container %s stopped safely: %s\n", policy, name, reason) auditLog.Log("server_stop", "node-agent", "", name, policy+"-stop", "success", map[string]any{"reason": reason}) return nil } func (a *Agent) getServerDiskUsage(serverDir string) int64 { size, err := getDirSizeBytes(serverDir) if err != nil { return 0 } return size } // getServerDiskUsagePerName is the backup-projection variant of // getServerDiskUsage (same error->0 contract): it measures the server dir the // way copyDir writes it — per NAME, hardlinks charged per name — so the // backup create projection validates the bytes the copy will actually commit. // adpanel:backup-du-hardlinks — see getDirSizeBytesPerName. func (a *Agent) getServerDiskUsagePerName(serverDir string) int64 { size, err := getDirSizeBytesPerName(serverDir) if err != nil { return 0 } return size } // getServerBackupsUsage returns the total on-disk size of a server's backups // directory. adpanel:backup-storage - backups are stored under serverBackupsDir, // which lives OUTSIDE the server's volume dir, so getServerDiskUsage never sees // them. We surface this so the panel can show "server files + backups" and so the // disk-limit guard treats backups as occupied space. func (a *Agent) getServerBackupsUsage(serverName string) int64 { backupsDir := a.serverBackupsDir(serverName) if st, err := os.Stat(backupsDir); err != nil || !st.IsDir() { return 0 } size, err := getDirSizeBytes(backupsDir) if err != nil { return 0 } return size } // getServerTotalUsage returns the combined occupied storage for a server: // its files plus all of its backups. adpanel:backup-storage - this is the value // that must be compared against the storage limit, because a backup is a full // copy of the server and counts toward the quota. func (a *Agent) getServerTotalUsage(serverDir string) int64 { used := a.getServerDiskUsage(serverDir) if name := filepath.Base(serverDir); name != "" && name != "." && name != ".adpanel_meta" { used += a.getServerBackupsUsage(name) } return used } func (a *Agent) getServerDiskLimitBytes(serverDir string) int64 { meta := a.loadMeta(serverDir) resources, ok := meta["resources"].(map[string]any) if !ok { return 0 } if val, ok := resources["storageMb"]; ok { var limitMb int64 switch v := val.(type) { case float64: limitMb = int64(v) case int: limitMb = int64(v) case int64: limitMb = v } if limitMb > 0 { return limitMb * 1024 * 1024 } } if val, ok := resources["storageGb"]; ok { var limitGb int64 switch v := val.(type) { case float64: limitGb = int64(v) case int: limitGb = int64(v) case int64: limitGb = v } if limitGb > 0 { return limitGb * 1024 * 1024 * 1024 } } return 0 } func (a *Agent) checkDiskLimit(serverDir string, extraBytes int64) map[string]any { limitBytes := a.getServerDiskLimitBytes(serverDir) if limitBytes <= 0 { return nil } // adpanel:backup-storage - count server files AND backups against the quota. usedBytes := a.getServerTotalUsage(serverDir) if usedBytes+extraBytes > limitBytes { return diskLimitExceededBody(usedBytes, limitBytes, fmt.Sprintf("This server has exceeded its disk space limit. Used: %.1f MB / %.1f MB", float64(usedBytes)/(1024*1024), float64(limitBytes)/(1024*1024))) } return nil } // diskLimitExceededBody is the ONE home of the 507 body shape for the // per-server storage-limit quota (error code "disk_limit_exceeded"): the // panel's settled pass-through whitelist keys on that error code and relays // the remaining fields verbatim, so every writer of this class — checkDiskLimit // above and the backup-copy budget abort (adpanel:backup-copy-budget) — builds // its body here instead of inlining a drifting copy. func diskLimitExceededBody(usedBytes, limitBytes int64, message string) map[string]any { usedMb := float64(usedBytes) / (1024 * 1024) limitMb := float64(limitBytes) / (1024 * 1024) return map[string]any{ "error": "disk_limit_exceeded", "message": message, "usedBytes": usedBytes, "limitBytes": limitBytes, "usedMb": usedMb, "limitMb": limitMb, } } // quotaGuardedDownloader returns the agent's downloader with a quota guard // bound to this server: the commit copy aborts with errDownloadQuotaExceeded // the moment usedBefore+written crosses the server's storage limit. // // Usage is sampled once, before the download's temp file exists, and the temp // file lives inside the server dir — so usedBefore+written is exactly what a // directory rescan would report at that point in the copy, without rescanning // per chunk. A download can now overshoot its quota by at most one write // buffer plus concurrent writers, instead of the downloader's full maxBytes // ceiling (10 GiB by default) allowed by the pre-download-only check. // // The snapshot is a plain read of current usage, so it is only a snapshot: // both callers (the two handleApplyVersion download branches) construct the // downloader while holding the destination scope's upload lock // (lockUploadScope) and keep it across the whole downloadToFile call, so no // other quota-accounted writer can commit bytes between usedBefore and the // rename commit (see the lockUploadScope contract comment). func (a *Agent) quotaGuardedDownloader(serverDir string) Downloader { dl := a.dl limitBytes := a.getServerDiskLimitBytes(serverDir) if limitBytes <= 0 { return dl } usedBefore := a.getServerTotalUsage(serverDir) dl.quotaCheck = func(written int64) error { if usedBefore+written > limitBytes { return errDownloadQuotaExceeded } return nil } return dl } func (a *Agent) serverNameFromPath(absPath string) string { // adpanel:multidisk - reverse-map a path to its server name across every // registered disk's volumes root. Falls back to primary-only behavior when no // additional disks are present. c := filepath.Clean(absPath) for _, root := range a.allDiskVolumeRoots() { rel, err := filepath.Rel(root, c) if err != nil { continue } parts := strings.SplitN(filepath.ToSlash(rel), "/", 2) if len(parts) == 0 || parts[0] == "" || parts[0] == "." || parts[0] == ".." { continue } return parts[0] } return "" } func (a *Agent) checkDiskLimitForPath(absPath string, extraBytes int64) map[string]any { serverName := a.serverNameFromPath(absPath) if serverName == "" || serverName == ".adpanel_meta" { return nil } serverDir := a.serverDir(serverName) if diskErr := a.checkDiskLimit(serverDir, extraBytes); diskErr != nil { return diskErr } // adpanel:multidisk - also enforce the per-disk capacity ceiling. No-op for the // primary disk and for disks without a limit, so single-disk behavior is unchanged. return a.checkDiskCapacityForPath(absPath, extraBytes) } func (a *Agent) checkDiskLimitForPathAfterReplacing(absPath string, replacedBytes int64) map[string]any { serverName := a.serverNameFromPath(absPath) if serverName == "" || serverName == ".adpanel_meta" { return nil } serverDir := a.serverDir(serverName) limitBytes := a.getServerDiskLimitBytes(serverDir) if limitBytes <= 0 { return nil } // adpanel:backup-storage - backups occupy quota too, so they must be part of // the post-replacement total when validating an in-place overwrite. usedBytes := a.getServerTotalUsage(serverDir) finalUsedBytes := usedBytes - replacedBytes if finalUsedBytes < 0 { finalUsedBytes = 0 } if finalUsedBytes > limitBytes { return diskLimitExceededBody(finalUsedBytes, limitBytes, fmt.Sprintf("This server has exceeded its disk space limit. Used: %.1f MB / %.1f MB", float64(finalUsedBytes)/(1024*1024), float64(limitBytes)/(1024*1024))) } return nil } func diskLimitUploadPayload(usedBytes, limitBytes, incomingBytes int64) map[string]any { if usedBytes < 0 { usedBytes = 0 } if incomingBytes < 0 { incomingBytes = 0 } remainingBytes := limitBytes - usedBytes if remainingBytes < 0 { remainingBytes = 0 } usedMb := float64(usedBytes) / (1024 * 1024) limitMb := float64(limitBytes) / (1024 * 1024) return map[string]any{ "error": "disk_limit_exceeded", "message": fmt.Sprintf("Upload would exceed this server's disk space limit. Used: %.1f MB / %.1f MB", usedMb, limitMb), "usedBytes": usedBytes, "limitBytes": limitBytes, "remainingBytes": remainingBytes, "incomingBytes": incomingBytes, "usedMb": usedMb, "limitMb": limitMb, } } // diskCapacityUploadPayload mirrors diskLimitUploadPayload for the per-disk // capacity ceiling: same response shape, "disk_capacity_exceeded" error code // and GB units like checkDiskCapacity. func diskCapacityUploadPayload(usedBytes, limitBytes, incomingBytes int64) map[string]any { if usedBytes < 0 { usedBytes = 0 } if incomingBytes < 0 { incomingBytes = 0 } remainingBytes := limitBytes - usedBytes if remainingBytes < 0 { remainingBytes = 0 } return map[string]any{ "error": "disk_capacity_exceeded", "message": fmt.Sprintf("Upload would exceed the target disk's capacity. Used: %.1f GB / %.1f GB", float64(usedBytes)/(1024*1024*1024), float64(limitBytes)/(1024*1024*1024)), "usedBytes": usedBytes, "limitBytes": limitBytes, "remainingBytes": remainingBytes, "incomingBytes": incomingBytes, } } // uploadDiskAllowanceForPath computes how many bytes an upload may still // write into a server-scoped path: the disk limit minus everything already // occupying the server (files + backups) minus the bytes the upload will // replace. The usage number is a filesystem walk, so it is only a snapshot: // CALLERS MUST hold the destination scope's upload lock // (a.lockUploadScope(a.fsScopeRootFor(server, absDir))) across the whole // snapshot -> transfer -> commit window. Without that lock N concurrent // uploads each validate against the same pre-upload snapshot and jointly // overshoot the limit by up to N-1 upload sizes. // // This covers the per-server quota only. The per-disk capacity ceiling // (LimitGb) is a separate snapshot via diskCapacityAllowanceForPath; routes // that stream a body of unknown length must fold both snapshots into the // transfer cap by taking the min of the two allowances. func (a *Agent) uploadDiskAllowanceForPath(absPath string, replacedBytes int64) (allowedBytes, baseUsedBytes, limitBytes int64, limited bool, diskErr map[string]any) { serverName := a.serverNameFromPath(absPath) if serverName == "" || serverName == ".adpanel_meta" { return 0, 0, 0, false, nil } serverDir := a.serverDir(serverName) limitBytes = a.getServerDiskLimitBytes(serverDir) if limitBytes <= 0 { return 0, 0, 0, false, nil } // adpanel:backup-storage - the remaining upload allowance is the limit minus // EVERYTHING already occupying it (server files + backups), so uploads are // blocked once backups have saturated the quota even if the files are small. usedBytes := a.getServerTotalUsage(serverDir) baseUsedBytes = usedBytes - replacedBytes if baseUsedBytes < 0 { baseUsedBytes = 0 } if baseUsedBytes > limitBytes { return 0, baseUsedBytes, limitBytes, true, diskLimitUploadPayload(baseUsedBytes, limitBytes, 0) } return limitBytes - baseUsedBytes, baseUsedBytes, limitBytes, true, nil } func copyUploadWithLimits(dst io.Writer, src io.Reader, maxBytes int64, diskAllowedBytes int64) (int64, string, error) { const maxInt64 = int64(^uint64(0) >> 1) if maxBytes <= 0 { maxBytes = maxInt64 } buf := make([]byte, 64*1024) var written int64 for { n, readErr := src.Read(buf) if n > 0 { next := written + int64(n) if next > maxBytes { return written, "upload", nil } if diskAllowedBytes >= 0 && next > diskAllowedBytes { return written, "disk", nil } if _, writeErr := dst.Write(buf[:n]); writeErr != nil { return written, "", writeErr } written = next } if readErr == io.EOF { return written, "", nil } if readErr != nil { return written, "", readErr } } } // uploadBodyIdleTimeout is the idle window the upload routes arm on the // connection while a request body is streaming. The server-wide ReadTimeout // is one absolute deadline armed at request start and would otherwise cap // every upload at that fixed duration no matter how fast the client actually // sends, so while the body is being read each successful read pushes the // connection's read deadline one window forward: an active transfer is // bounded by progress instead of wall clock, and a client that stops sending // for the whole window fails its next read with os.ErrDeadlineExceeded — the // handler cleans up its temp file and the previous destination stays intact. // Overridable in tests. var uploadBodyIdleTimeout = 120 * time.Second // uploadIdleBody wraps a request body with the per-read deadline re-arming // described on uploadBodyIdleTimeout. Deadline support is best-effort and // ignored on writers without it (e.g. httptest.ResponseRecorder), matching // the SetWriteDeadline extensions the long-running routes use. type uploadIdleBody struct { rc *http.ResponseController src io.ReadCloser rearmBefore time.Time } func newUploadIdleBody(w http.ResponseWriter, src io.ReadCloser) *uploadIdleBody { b := &uploadIdleBody{rc: http.NewResponseController(w), src: src} // Arm before the first byte so a client that sends headers and then // stalls is bounded by the window, not by the server-wide backstop. _ = b.rc.SetReadDeadline(time.Now().Add(uploadBodyIdleTimeout)) return b } func (b *uploadIdleBody) Read(p []byte) (int, error) { n, err := b.src.Read(p) if n > 0 { now := time.Now() // Re-arm at most every window/4 so a multi-GB transfer at 64 KiB // read chunks does not churn a runtime timer on every read. if now.After(b.rearmBefore) { b.rearmBefore = now.Add(uploadBodyIdleTimeout / 4) _ = b.rc.SetReadDeadline(now.Add(uploadBodyIdleTimeout)) } } return n, err } func (b *uploadIdleBody) Close() error { return b.src.Close() } func protectNodeProcess() { pid := os.Getpid() path := fmt.Sprintf("/proc/%d/oom_score_adj", pid) err := os.WriteFile(path, []byte("-1000"), 0o644) if err != nil { fmt.Fprintf(os.Stderr, "[oom-protect] WARNING: could not set oom_score_adj to -1000: %v\n", err) fmt.Fprintln(os.Stderr, "[oom-protect] The node process may be killed by Linux OOM killer under memory pressure.") fmt.Fprintln(os.Stderr, "[oom-protect] Ensure this process runs as root or has CAP_SYS_RESOURCE.") } else { fmt.Printf("[oom-protect] Node process (PID %d) protected with oom_score_adj=-1000\n", pid) } } type containerMemState struct { state string since time.Time lastPct float64 } type memoryMonitor struct { agent *Agent interval time.Duration stopCh chan struct{} debug bool recentKills map[string]time.Time recentKillsMu sync.Mutex containerStates map[string]*containerMemState statesMu sync.Mutex } func newMemoryMonitor(agent *Agent, interval time.Duration, debug bool) *memoryMonitor { return &memoryMonitor{ agent: agent, interval: interval, stopCh: make(chan struct{}), debug: debug, recentKills: make(map[string]time.Time), containerStates: make(map[string]*containerMemState), } } func (mm *memoryMonitor) start() { go mm.monitorLoop() } func (mm *memoryMonitor) stop() { close(mm.stopCh) } func (mm *memoryMonitor) monitorLoop() { time.Sleep(15 * time.Second) ticker := time.NewTicker(mm.interval) defer ticker.Stop() for { select { case <-mm.stopCh: return case <-ticker.C: mm.tick() } } } func (mm *memoryMonitor) tick() { totalKB, availKB, err := readSystemMemory() if err != nil { if mm.debug { fmt.Fprintf(os.Stderr, "[mem-monitor] error reading /proc/meminfo: %v\n", err) } return } if totalKB == 0 { return } usedPercent := float64(totalKB-availKB) / float64(totalKB) * 100.0 if mm.debug { fmt.Printf("[mem-monitor] System memory: %.1f%% used (%d MB / %d MB)\n", usedPercent, (totalKB-availKB)/1024, totalKB/1024) } hostTotalBytes := int64(totalKB) * 1024 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() out, _, _, err := mm.agent.docker.runCollect(ctx, "ps", "--no-trunc", "--format", "{{.ID}}|{{.Names}}") if err != nil { if mm.debug { fmt.Fprintf(os.Stderr, "[mem-monitor] docker ps error: %v\n", err) } return } lines := strings.Split(strings.TrimSpace(out), "\n") if len(lines) == 0 || (len(lines) == 1 && lines[0] == "") { return } mm.pruneRecentKills() // docker ps lists every container on the host; only panel-managed ones may // be stopped/killed by the OOM guard. managedNames := mm.agent.panelManagedContainerNames() activeIDs := make(map[string]struct{}, len(lines)) for _, line := range lines { parts := strings.SplitN(strings.TrimSpace(line), "|", 2) if len(parts) != 2 || parts[0] == "" { continue } containerID := parts[0] containerName := parts[1] if _, managed := managedNames[containerName]; !managed { if mm.debug { fmt.Printf("[mem-monitor] Container %s not panel-managed, skipping\n", containerName) } continue } activeIDs[containerID] = struct{}{} mm.recentKillsMu.Lock() if _, killed := mm.recentKills[containerID]; killed { mm.recentKillsMu.Unlock() continue } mm.recentKillsMu.Unlock() usageBytes, limitBytes := mm.readContainerCgroupMemory(containerID) if usageBytes < 0 { continue } effectiveLimit := limitBytes isUnlimited := false if limitBytes <= 0 || limitBytes >= hostTotalBytes { effectiveLimit = hostTotalBytes isUnlimited = true } containerUsedPct := float64(usageBytes) / float64(effectiveLimit) * 100.0 if mm.debug && containerUsedPct > 75.0 { limitLabel := fmt.Sprintf("%d MB", effectiveLimit/(1024*1024)) if isUnlimited { limitLabel = fmt.Sprintf("%d MB (host RAM)", effectiveLimit/(1024*1024)) } fmt.Printf("[mem-monitor] Container %s: %.1f%% memory (%d MB / %s)\n", containerName, containerUsedPct, usageBytes/(1024*1024), limitLabel) } if containerUsedPct >= 99.0 { idShort := containerID if len(idShort) > 12 { idShort = idShort[:12] } limitDesc := fmt.Sprintf("%d MB", effectiveLimit/(1024*1024)) if isUnlimited { limitDesc = fmt.Sprintf("%d MB (host RAM, unlimited server)", effectiveLimit/(1024*1024)) } fmt.Printf("[mem-monitor] Container %s (%s) at %.1f%% of memory limit (%d MB / %s) — FORCE KILLING\n", containerName, idShort, containerUsedPct, usageBytes/(1024*1024), limitDesc) mm.killContainer(containerID, containerName) mm.setContainerState(containerID, "normal") continue } if containerUsedPct >= 96.0 { state := mm.getContainerState(containerID) if state == nil || state.state != "stopping" { idShort := containerID if len(idShort) > 12 { idShort = idShort[:12] } limitDesc := fmt.Sprintf("%d MB", effectiveLimit/(1024*1024)) if isUnlimited { limitDesc = fmt.Sprintf("%d MB (host RAM, unlimited server)", effectiveLimit/(1024*1024)) } fmt.Printf("[mem-monitor] Container %s (%s) at %.1f%% of memory limit (%d MB / %s) — graceful stop\n", containerName, idShort, containerUsedPct, usageBytes/(1024*1024), limitDesc) mm.gracefulStopContainer(containerID, containerName) mm.setContainerState(containerID, "stopping") } else if mm.debug { fmt.Printf("[mem-monitor] Container %s still at %.1f%% — graceful stop already issued, waiting for 99%% to force kill\n", containerName, containerUsedPct) } mm.updateContainerPct(containerID, containerUsedPct) continue } if containerUsedPct < 90.0 { state := mm.getContainerState(containerID) if state != nil && state.state != "normal" { if mm.debug { fmt.Printf("[mem-monitor] Container %s recovered to %.1f%% — clearing warning state\n", containerName, containerUsedPct) } mm.setContainerState(containerID, "normal") } } } mm.pruneContainerStates(activeIDs) } func readSystemMemory() (totalKB, availKB int64, err error) { data, err := os.ReadFile("/proc/meminfo") if err != nil { return 0, 0, err } var memTotal, memAvailable, memFree, buffers, cached int64 for _, line := range strings.Split(string(data), "\n") { fields := strings.Fields(line) if len(fields) < 2 { continue } val, _ := strconv.ParseInt(fields[1], 10, 64) switch fields[0] { case "MemTotal:": memTotal = val case "MemAvailable:": memAvailable = val case "MemFree:": memFree = val case "Buffers:": buffers = val case "Cached:": cached = val } } if memAvailable > 0 { return memTotal, memAvailable, nil } return memTotal, memFree + buffers + cached, nil } func (mm *memoryMonitor) readContainerCgroupMemory(containerID string) (usageBytes, limitBytes int64) { cgroupV2Base := fmt.Sprintf("/sys/fs/cgroup/system.slice/docker-%s.scope", containerID) usage := readInt64File(cgroupV2Base + "/memory.current") limit := readInt64File(cgroupV2Base + "/memory.max") if usage >= 0 && limit > 0 { return usage, limit } cgroupV2Alt := fmt.Sprintf("/sys/fs/cgroup/docker/%s", containerID) usage = readInt64File(cgroupV2Alt + "/memory.current") limit = readInt64File(cgroupV2Alt + "/memory.max") if usage >= 0 && limit > 0 { return usage, limit } cgroupV1Base := fmt.Sprintf("/sys/fs/cgroup/memory/docker/%s", containerID) usage = readInt64File(cgroupV1Base + "/memory.usage_in_bytes") limit = readInt64File(cgroupV1Base + "/memory.limit_in_bytes") if usage >= 0 && limit > 0 { return usage, limit } cgroupV1Sys := fmt.Sprintf("/sys/fs/cgroup/memory/system.slice/docker-%s.scope", containerID) usage = readInt64File(cgroupV1Sys + "/memory.usage_in_bytes") limit = readInt64File(cgroupV1Sys + "/memory.limit_in_bytes") if usage >= 0 && limit > 0 { return usage, limit } return -1, -1 } func readInt64File(path string) int64 { data, err := os.ReadFile(path) if err != nil { return -1 } s := strings.TrimSpace(string(data)) if s == "max" || s == "" { return -1 } val, err := strconv.ParseInt(s, 10, 64) if err != nil { return -1 } return val } func (mm *memoryMonitor) gracefulStopContainer(containerID, containerName string) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() idShort := containerID if len(idShort) > 12 { idShort = idShort[:12] } _, errStr, _, err := mm.agent.docker.runCollect(ctx, "stop", "-t", "15", containerID) if err != nil { fmt.Fprintf(os.Stderr, "[mem-monitor] failed to gracefully stop container %s (%s): %v — %s\n", containerName, idShort, err, strings.TrimSpace(errStr)) return } fmt.Printf("[mem-monitor] Gracefully stopped container %s (%s) due to high memory usage\n", containerName, idShort) mm.recentKillsMu.Lock() mm.recentKills[containerID] = time.Now() mm.recentKillsMu.Unlock() } func (mm *memoryMonitor) killContainer(containerID, containerName string) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() idShort := containerID if len(idShort) > 12 { idShort = idShort[:12] } _, errStr, _, err := mm.agent.docker.runCollect(ctx, "kill", containerID) if err != nil { fmt.Fprintf(os.Stderr, "[mem-monitor] failed to kill container %s (%s): %v — %s\n", containerName, idShort, err, strings.TrimSpace(errStr)) return } fmt.Printf("[mem-monitor] Force killed container %s (%s) due to critical memory overuse\n", containerName, idShort) mm.recentKillsMu.Lock() mm.recentKills[containerID] = time.Now() mm.recentKillsMu.Unlock() } func (mm *memoryMonitor) getContainerState(containerID string) *containerMemState { mm.statesMu.Lock() defer mm.statesMu.Unlock() return mm.containerStates[containerID] } func (mm *memoryMonitor) setContainerState(containerID, state string) { mm.statesMu.Lock() defer mm.statesMu.Unlock() mm.containerStates[containerID] = &containerMemState{ state: state, since: time.Now(), } } func (mm *memoryMonitor) updateContainerPct(containerID string, pct float64) { mm.statesMu.Lock() defer mm.statesMu.Unlock() if s, ok := mm.containerStates[containerID]; ok { s.lastPct = pct } } func (mm *memoryMonitor) pruneContainerStates(activeIDs map[string]struct{}) { mm.statesMu.Lock() defer mm.statesMu.Unlock() for id := range mm.containerStates { if _, active := activeIDs[id]; !active { delete(mm.containerStates, id) } } } func (mm *memoryMonitor) pruneRecentKills() { mm.recentKillsMu.Lock() defer mm.recentKillsMu.Unlock() cutoff := time.Now().Add(-60 * time.Second) for id, t := range mm.recentKills { if t.Before(cutoff) { delete(mm.recentKills, id) } } } type rateLimiter struct { mu sync.Mutex attempts map[string]*rateLimitEntry limit int window time.Duration maxSize int } type rateLimitEntry struct { count int resetAt time.Time } var trustProxyHeaders = false var authRateLimiter = &rateLimiter{ attempts: make(map[string]*rateLimitEntry), limit: 100, window: 5 * time.Minute, maxSize: 50000, } func (rl *rateLimiter) allow(ip string) bool { rl.mu.Lock() defer rl.mu.Unlock() now := time.Now() if len(rl.attempts) >= rl.maxSize { for k, v := range rl.attempts { if now.After(v.resetAt) { delete(rl.attempts, k) } } if len(rl.attempts) >= rl.maxSize { var oldestKey string var oldestTime time.Time first := true for k, v := range rl.attempts { if first || v.resetAt.Before(oldestTime) { oldestKey = k oldestTime = v.resetAt first = false } } if oldestKey != "" { delete(rl.attempts, oldestKey) } } } entry, exists := rl.attempts[ip] if !exists || now.After(entry.resetAt) { rl.attempts[ip] = &rateLimitEntry{count: 1, resetAt: now.Add(rl.window)} return true } entry.count++ if entry.count > rl.limit { return false } return true } var rateLimitCleanupOnce sync.Once func startRateLimitCleanup() { rateLimitCleanupOnce.Do(func() { go func() { for { time.Sleep(time.Minute) authRateLimiter.mu.Lock() now := time.Now() for ip, entry := range authRateLimiter.attempts { if now.After(entry.resetAt) { delete(authRateLimiter.attempts, ip) } } authRateLimiter.mu.Unlock() } }() }) } func getClientIP(r *http.Request) string { if trustProxyHeaders { if xff := r.Header.Get("X-Forwarded-For"); xff != "" { parts := strings.Split(xff, ",") if len(parts) > 0 { return strings.TrimSpace(parts[0]) } } } host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return r.RemoteAddr } return host } func (a *Agent) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Frame-Options", "DENY") w.Header().Set("X-XSS-Protection", "1; mode=block") w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") w.Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()") w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate") w.Header().Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'") if r.TLS != nil { w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") } path := r.URL.Path method := r.Method if method == "HEAD" && path == "/ping" { w.WriteHeader(204) return } if method == "GET" && path == "/health" { jsonWrite(w, 200, map[string]any{ "ok": true, "version": NodeVersion, "tls": r.TLS != nil, "time": time.Now().UnixMilli(), }) return } if strings.HasPrefix(path, "/v1/servers/") { rest := strings.TrimPrefix(path, "/v1/servers/") parts := strings.Split(rest, "/") if len(parts) >= 2 { name := sanitizeName(parts[0]) action := parts[1] if name == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid name"}) return } if method == "POST" && action == "apply-version" { a.handleApplyVersion(w, r, name) return } } } clientIP := getClientIP(r) if !a.authOK(r) { if !authRateLimiter.allow(clientIP) { auditLog.Log("rate_limit", clientIP, "", path, method, "blocked", nil) jsonWrite(w, 429, map[string]any{"error": "too many requests"}) return } auditLog.Log("auth_failure", clientIP, "", path, method, "denied", nil) jsonWrite(w, 401, map[string]any{"error": "unauthorized"}) return } if strings.HasPrefix(path, "/v1/fs/") { reqBytes := r.ContentLength if reqBytes < 0 { reqBytes = 0 } a.recordFSAccess(clientIP, path, method, reqBytes) } switch { case method == "GET" && path == "/api/system/stats": a.handleSystemStats(w, r) return case method == "GET" && path == "/v1/info": probeOK, proof, probeWhy := a.verifyPanelProbe(r, "info") if !probeOK { jsonWrite(w, 401, map[string]any{"ok": false, "error": probeWhy}) return } info := map[string]any{ "ok": true, "node": map[string]any{ "uuid": a.uuid, "version": NodeVersion, "autoUpdate": a.readNodeInformation().NodeAutoUpdate, "dataRoot": a.dataRoot, "volumesDir": a.volumesDir, }, } proof.addTo(info) jsonWrite(w, 200, info) return case method == "GET" && path == "/v1/ports/check": a.handlePortCheck(w, r) return case method == "GET" && path == "/v1/update/info": a.handleNodeUpdateInfo(w, r) return case method == "POST" && path == "/v1/update/auto": a.handleNodeUpdateAuto(w, r) return case method == "POST" && path == "/v1/update/install": a.handleNodeUpdateInstall(w, r) return case method == "GET" && path == "/v1/disks": a.handleDiskList(w, r) return case method == "POST" && path == "/v1/token/rotate": a.handleTokenRotate(w, r) return case method == "POST" && path == "/v1/panel/hmac-secret": a.handlePanelHMACSet(w, r) return case method == "POST" && path == "/v1/disks": a.handleDiskAdd(w, r) return case method == "DELETE" && path == "/v1/disks": a.handleDiskDelete(w, r) return case method == "GET" && path == "/v1/ws": a.handleWebSocket(w, r) return case method == "GET" && path == "/v1/servers": a.handleListServers(w, r) return case method == "POST" && (path == "/v1/servers" || path == "/v1/servers/create"): a.handleCreateServer(w, r) return case method == "POST" && path == "/v1/runtime/startup-command": a.handleTemplateStartupCommand(w, r) return case method == "POST" && path == "/v1/fs/list": a.handleFSList(w, r) return case method == "POST" && path == "/v1/fs/read": a.handleFSRead(w, r) return case method == "POST" && path == "/v1/fs/download": a.handleFSDownload(w, r) return case method == "POST" && path == "/v1/fs/write": a.handleFSWrite(w, r) return case method == "POST" && path == "/v1/fs/delete": a.handleFSDelete(w, r) return case method == "POST" && path == "/v1/fs/delete-batch": a.handleFSDeleteBatch(w, r) return case method == "POST" && path == "/v1/fs/rename": a.handleFSRename(w, r) return case (method == "POST" || method == http.MethodPut) && path == "/v1/fs/extract": a.handleFSExtract(w, r) return case method == "POST" && path == "/v1/fs/uploadRaw": a.handleFSUploadRaw(w, r) return case (method == "POST" || method == http.MethodPut) && path == "/v1/fs/upload": a.handleFSUploadStream(w, r) return case (method == "POST" || method == http.MethodPut) && path == "/v1/fs/uploadUrl": a.handleFSUploadURL(w, r) return case method == "POST" && path == "/v1/server/command": a.handleServerCommandBody(w, r) return } if strings.HasPrefix(path, "/v1/servers/") { rest := strings.TrimPrefix(path, "/v1/servers/") parts := strings.Split(rest, "/") // adpanel:multidisk - GET /v1/servers/ must return BOTH the resolved // per-server baseDir (so the panel can route to the correct disk root) and the // live resource stats. handleServerInfo now merges the disk-routing fields into // the stats payload, so a single-name GET falls through to it below instead of // being answered by a stats-less early return (which made the panel show "—"). if len(parts) >= 2 { name := sanitizeName(parts[0]) action := parts[1] if name == "" { jsonWrite(w, 400, map[string]any{"error": "invalid name"}) return } if action != "" && action != "logs" && action != "resources" && action != "delete-status" && action != "delete" && action != "eula" && action != "eula-accept" && action != "reinstall" { if a.isServerInstalling(name) { writeServerInstallingConflict(w) return } } switch action { case "": case "runtime": if method == "POST" { a.handleRuntime(w, r, name) return } case "start": if method == "POST" { a.handleStart(w, r, name) return } case "eula-accept": if method == "POST" || method == "PUT" { a.handleEulaAccept(w, r, name) return } case "eula": if method == "GET" { a.handleEulaStatus(w, r, name) return } case "stop": if method == "POST" { a.handleStop(w, r, name) return } case "restart": if method == "POST" { a.handleRestart(w, r, name) return } case "command": if method == "POST" { a.handleCommand(w, r, name) return } case "logs": if method == "GET" && len(parts) == 2 { if r.URL.Query().Get("format") == "json" { a.handleLogsSnapshot(w, r, name) return } a.handleLogsSSE(w, r, name) return } if method == "GET" && len(parts) == 3 && (parts[2] == "snapshot" || parts[2] == "history") { a.handleLogsSnapshot(w, r, name) return } if method == "POST" && len(parts) == 3 && parts[2] == "reset" { a.handleResetLogs(w, r, name) return } case "kill": if method == "POST" { a.handleKill(w, r, name) return } case "delete-status": if method == "GET" { a.handleDeleteStatus(w, r, name) return } case "files": if len(parts) >= 3 { sub := parts[2] switch sub { case "list": if method == "GET" { a.handleFilesList(w, r, name) return } case "read": if method == "GET" { a.handleFilesRead(w, r, name) return } case "write": if method == "PUT" { a.handleFilesWrite(w, r, name) return } case "delete": if method == "DELETE" { a.handleFilesDelete(w, r, name) return } case "upload": if method == "POST" { a.handleFilesUpload(w, r, name) return } case "archive": if method == "POST" { a.handleFilesArchive(w, r, name) return } } } case "backups": if len(parts) == 2 { if method == "GET" { a.handleBackupsList(w, r, name) return } if method == "POST" { a.handleBackupsCreate(w, r, name) return } } else if len(parts) >= 3 { backupId := parts[2] if len(parts) == 3 { if method == "DELETE" { a.handleBackupsDelete(w, r, name, backupId) return } } else if len(parts) == 4 && parts[3] == "restore" { if method == "POST" { a.handleBackupsRestore(w, r, name, backupId) return } } } case "resources": if method == "GET" { a.handleGetResources(w, r, name) return } if method == "PATCH" { a.handleUpdateResources(w, r, name) return } case "import-archive": if method == "POST" && len(parts) == 2 { a.handleImportArchive(w, r, name) return } if method == "GET" && len(parts) == 3 && parts[2] == "progress" { a.handleImportArchiveProgress(w, r, name) return } case "export": if method == "GET" && len(parts) == 2 { a.handleExportServer(w, r, name) return } if method == "DELETE" && len(parts) == 2 { a.handleFinishTransferExport(w, r, name) return } case "import-tar": if method == "POST" || (method == "PUT" && len(parts) == 2) { a.handleImportTar(w, r, name) return } if method == "DELETE" && len(parts) == 2 { a.handleDeleteTransferImport(w, r, name) return } case "reinstall": if method == "POST" && len(parts) == 2 { a.handleReinstallServer(w, r, name) return } case "reinstall-result": if method == "GET" && len(parts) == 2 { a.handleReinstallResult(w, r, name) return } default: if method == "GET" && len(parts) == 2 { a.handleServerInfo(w, r, name) return } } } else if method == "GET" && len(parts) == 1 { name := sanitizeName(parts[0]) a.handleServerInfo(w, r, name) return } if method == "DELETE" && len(parts) == 1 { name := sanitizeName(parts[0]) a.handleDeleteServer(w, r, name) return } } jsonWrite(w, 404, map[string]any{"error": "not found"}) } func (a *Agent) handlePortCheck(w http.ResponseWriter, r *http.Request) { port, ok := parseStrictPortValue(r.URL.Query().Get("port")) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid port"}) return } exclude := sanitizeName(r.URL.Query().Get("exclude")) rawProtocols := strings.TrimSpace(r.URL.Query().Get("protocols")) if rawProtocols == "" { rawProtocols = strings.TrimSpace(r.URL.Query().Get("protocol")) } protocols := []string{"tcp"} if rawProtocols != "" { protocols = nil for _, part := range strings.Split(rawProtocols, ",") { if protocol := normalizePortProtocolName(part); protocol != "" { protocols = append(protocols, protocol) } } if len(protocols) == 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid protocol"}) return } } ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) available, owner, reason := a.hostPortAvailabilityForProtocols(ctx, port, protocols, exclude) cancel() payload := map[string]any{ "ok": true, "port": port, "protocols": protocols, "available": available, } if owner != "" { payload["owner"] = owner } if reason != "" { payload["reason"] = reason } jsonWrite(w, 200, payload) } // adpanel:cpu-sampling - instantaneous node CPU utilization. A single // /proc/stat read yields cumulative counters since boot, so dividing them // reports the boot-to-now average: on a long-uptime node that number is // effectively frozen (a busy node shows a low historical average and the // panel's ">90% CPU" warning can never fire). The same delta-sampling // technique dockerCPUPercent uses for containers is applied here: keep the // previous sample per agent and report the change since the last poll. type cpuProcSample struct { total uint64 idle uint64 // idle + iowait at time.Time } const ( // Deltas over windows shorter than this are too noisy to trust, so the // caller falls back to a fresh double-read instead. cpuDeltaMinWindow = 50 * time.Millisecond // A previous sample older than this no longer represents "current" // usage (nobody polled for a while), so it is discarded. cpuDeltaMaxWindow = 2 * time.Minute // In-handler double-read spacing used when no usable previous sample // exists (first poll after start, stale sample, or counter reset). Kept // short so the first stats request only pays a fraction of a second. cpuFallbackSampleDelay = 250 * time.Millisecond ) // readProcStatCPUTotals parses the aggregate "cpu " line of /proc/stat. The // kernel folds guest time into user, so the total deliberately stops at steal // (fields: user nice system idle iowait irq softirq steal) to avoid // double-counting guest. func readProcStatCPUTotals() (cpuProcSample, bool) { stat, err := os.ReadFile("/proc/stat") if err != nil { return cpuProcSample{}, false } for _, line := range strings.Split(string(stat), "\n") { if !strings.HasPrefix(line, "cpu ") { continue } fields := strings.Fields(line) if len(fields) < 5 { return cpuProcSample{}, false } var vals [8]uint64 n := len(fields) - 1 if n > len(vals) { n = len(vals) } for i := 0; i < n; i++ { v, err := strconv.ParseUint(fields[i+1], 10, 64) if err != nil { return cpuProcSample{}, false } vals[i] = v } var total, idle uint64 for i := 0; i < n; i++ { total += vals[i] } if n > 3 { idle += vals[3] // idle } if n > 4 { idle += vals[4] // iowait } return cpuProcSample{total: total, idle: idle, at: time.Now()}, true } return cpuProcSample{}, false } // cpuPercentFromSamples converts two /proc/stat samples into a busy // percentage. usable=false means the pair cannot be trusted (counters went // backwards, e.g. after a reboot) and the caller must resample. func cpuPercentFromSamples(prev, cur cpuProcSample) (float64, bool) { if cur.total <= prev.total { return 0, false } totalDelta := cur.total - prev.total idleDelta := uint64(0) if cur.idle > prev.idle { idleDelta = cur.idle - prev.idle } pct := (1 - float64(idleDelta)/float64(totalDelta)) * 100 if pct < 0 { pct = 0 } if pct > 100 { pct = 100 } return pct, true } // currentCPUPercent reports current node CPU utilization as a percentage. // It deltas against the previous poll when that poll is recent enough; on // the first call after start (or after a long quiet period) it takes a // short in-handler double-read so this response still carries a current // reading instead of the boot-to-now average. On read failure it returns 0, // matching the previous behavior of this endpoint. func (a *Agent) currentCPUPercent() float64 { if a == nil { return 0 } cur, ok := readProcStatCPUTotals() if !ok { return 0 } a.cpuSampleMu.Lock() defer a.cpuSampleMu.Unlock() prev := a.lastCPUSample elapsed := cur.at.Sub(prev.at) if prev.at.IsZero() || elapsed < cpuDeltaMinWindow || elapsed > cpuDeltaMaxWindow { time.Sleep(cpuFallbackSampleDelay) next, ok2 := readProcStatCPUTotals() if ok2 { if pct, usable := cpuPercentFromSamples(cur, next); usable { a.lastCPUSample = next return pct } } a.lastCPUSample = cur return 0 } a.lastCPUSample = cur if pct, usable := cpuPercentFromSamples(prev, cur); usable { return pct } return 0 } func (a *Agent) handleSystemStats(w http.ResponseWriter, r *http.Request) { // Panel-signed probe: the panel challenges this endpoint with a fresh // nonce when it needs proof that the responder holds the per-node signing // secret (link-node setup gate). Unsigned requests keep the legacy // bearer-only behavior so older panels are unaffected. probeOK, proof, probeWhy := a.verifyPanelProbe(r, "stats") if !probeOK { jsonWrite(w, 401, map[string]any{"ok": false, "error": probeWhy}) return } var memStats runtime.MemStats runtime.ReadMemStats(&memStats) var ramTotalMb, ramUsedMb, ramFreeMb float64 if memInfo, err := os.ReadFile("/proc/meminfo"); err == nil { lines := strings.Split(string(memInfo), "\n") var memTotal, memAvailable, memFree, buffers, cached int64 for _, line := range lines { fields := strings.Fields(line) if len(fields) < 2 { continue } val, _ := strconv.ParseInt(fields[1], 10, 64) switch fields[0] { case "MemTotal:": memTotal = val case "MemAvailable:": memAvailable = val case "MemFree:": memFree = val case "Buffers:": buffers = val case "Cached:": cached = val } } ramTotalMb = float64(memTotal) / 1024 if memAvailable > 0 { ramFreeMb = float64(memAvailable) / 1024 } else { ramFreeMb = float64(memFree+buffers+cached) / 1024 } ramUsedMb = ramTotalMb - ramFreeMb } // Delta-sampled current utilization, not the boot-to-now average: see // the adpanel:cpu-sampling block above. cpuPercent := a.currentCPUPercent() var diskTotalGb, diskUsedGb, diskFreeGb float64 if stat, err := os.Stat(a.dataRoot); err == nil && stat.IsDir() { var statfs syscall.Statfs_t if syscall.Statfs(a.dataRoot, &statfs) == nil { diskTotalGb = float64(statfs.Blocks*uint64(statfs.Bsize)) / (1024 * 1024 * 1024) diskFreeGb = float64(statfs.Bavail*uint64(statfs.Bsize)) / (1024 * 1024 * 1024) diskUsedGb = diskTotalGb - diskFreeGb } } var uptimeSeconds float64 if uptime, err := os.ReadFile("/proc/uptime"); err == nil { fields := strings.Fields(string(uptime)) if len(fields) >= 1 { uptimeSeconds, _ = strconv.ParseFloat(fields[0], 64) } } hostname, _ := os.Hostname() resp := map[string]any{ "ok": true, "cpu_percent": cpuPercent, "cpu_cores": runtime.NumCPU(), "ram_used_mb": ramUsedMb, "ram_total_mb": ramTotalMb, "ram_free_mb": ramFreeMb, "disk_used_gb": diskUsedGb, "disk_total_gb": diskTotalGb, "disk_free_gb": diskFreeGb, "uptime": int64(uptimeSeconds), "hostname": hostname, "os": runtime.GOOS, "arch": runtime.GOARCH, "go_version": runtime.Version(), "node_version": NodeVersion, } proof.addTo(resp) jsonWrite(w, 200, resp) } func (a *Agent) serverDir(name string) string { // adpanel:multidisk - route to the server's assigned disk. Defaults to the // primary volumes root when the server has no disk assignment (back-compat). disk := a.diskForServer(name) if disk.Primary || disk.ID == primaryDiskID { return filepath.Join(a.volumesDir, name) } return filepath.Join(a.diskLayoutVolumes(disk.MountPath), name) } func (a *Agent) metaDir() string { return filepath.Join(a.volumesDir, ".adpanel_meta") } func (a *Agent) metaPath(name string) string { safe := sanitizeName(name) if safe == "" { safe = "unknown" } return filepath.Join(a.metaDir(), safe+".json") } func (a *Agent) getMetaLock(serverDir string) *sync.Mutex { key := filepath.Clean(serverDir) val, _ := a.metaLocks.LoadOrStore(key, &sync.Mutex{}) return val.(*sync.Mutex) } func (a *Agent) modifyMeta(serverDir string, fn func(meta map[string]any)) error { mu := a.getMetaLock(serverDir) mu.Lock() defer mu.Unlock() meta := a.loadMeta(serverDir) fn(meta) return a.saveMeta(serverDir, meta) } func (a *Agent) getServerOpLock(name string) *sync.RWMutex { val, _ := a.serverOpLocks.LoadOrStore(name, &sync.RWMutex{}) return val.(*sync.RWMutex) } // adpanel:backup-race - tryLockServerOp is the fail-fast variant of // getServerOpLock for the long mutating handlers (backup create/restore/delete // and reinstall). Backups are snapshot-then-transfer operations like uploads // (see the lockUploadScope contract below): two creates validated against the // same usage snapshot jointly overshoot the disk limit and the backupsMax // count, and two restores interleave copyDir writers into serverDir. Reinstall // is the same class of writer: its RemoveAll of serverDir plus template // rebuild raced a concurrent create (torn, status:"complete" backup of a // half-wiped tree) and a concurrent restore (two interleaved copyDir writers, // silently mixed files). All of them therefore serialize on the same per-server // op lock as start/stop/restart/kill, create/delete-server, import-tar and the // policy stopper - but acquire it non-blocking: the panel relay times out on // long copies, and the retry must never stack a second concurrent operation // behind the first. Returns the held mutex, or nil when another op already // holds it; callers must 409 immediately and release via defer on every path. // Power ops use acquireServerOpLockFailFast (bounded polling on this lock // plus the long-op marker) so they never queue behind a long op's hold. func (a *Agent) tryLockServerOp(name string) *sync.RWMutex { mu := a.getServerOpLock(name) if !mu.TryLock() { return nil } return mu } // Long-op kinds recorded in longOpBusyNames while the op holds the per-server // op lock. Backups (create/restore/delete), reinstall and the runtime seed all // hold for minutes-to-tens-of-minutes - far beyond any relay timeout - so // short ops must fail fast rather than queue behind them (see longOpConflict). const ( longOpBackup = "backup" longOpReinstall = "reinstall" longOpRuntimeSeed = "runtime_seed" ) // beginLongOp registers kind as the long op currently holding name's op lock. // Callers must already hold the lock and must defer endLongOp(name) BEFORE // deferring the Unlock: deferred calls run LIFO, so the marker is withdrawn // while the lock is still held and can never be observed stale, nor can a // queued waiter's acquisition race a lingering marker. func (a *Agent) beginLongOp(name, kind string) { a.longOpBusyNames.Store(name, kind) } // endLongOp withdraws the long-op marker registered by beginLongOp. func (a *Agent) endLongOp(name string) { a.longOpBusyNames.Delete(name) } // longOpKind reports which long op currently holds name's op lock // (longOpBackup / longOpReinstall), or "" when none does. func (a *Agent) longOpKind(name string) string { v, ok := a.longOpBusyNames.Load(name) if !ok { return "" } kind, _ := v.(string) return kind } // serverOpConflicts is the single vocabulary for every per-server op-lock // refusal: longOpConflict, acquireServerOpLockFailFast and the power-op // handlers all build their refusal bodies from this table, so codes, messages and // details can never drift apart. var serverOpConflicts = map[string]struct{ message, detail string }{ "backup_in_progress": {"backup operation in progress", "A backup create/restore/delete is running on this server; retry after it completes."}, "reinstall_in_progress": {"reinstall operation in progress", "A reinstall is running on this server; retry after it completes."}, "runtime_seed_in_progress": {"runtime seed operation in progress", "A runtime seed is running on this server; retry after it completes."}, "server_op_in_progress": {"server operation already in progress", "Another server operation is running on this server; retry in a moment."}, serverStopInProgress: {"server is stopping", "Wait for the server to finish stopping before retrying this operation."}, powerOpRequestEnded: {"power request ended", "The request ended before the server operation could start."}, } // serverOpConflictBody builds the body for an op-lock refusal code; an // unknown code degrades to the generic short-holder body. func serverOpConflictBody(code string) map[string]any { c, ok := serverOpConflicts[code] if !ok { code = "server_op_in_progress" c = serverOpConflicts[code] } return map[string]any{"ok": false, "error": c.message, "code": code, "detail": c.detail} } // longOpConflict describes the long operation currently holding name's op // lock, for the fail-fast 409s of power ops and reinstall. busy=false means // no long op is registered - the holder is a short op (start/stop/restart/ // kill/delete/import) and the caller should advertise a quick retry instead. func (a *Agent) longOpConflict(name string) (code, message, detail string, busy bool) { switch a.longOpKind(name) { case longOpBackup: c := serverOpConflicts["backup_in_progress"] return "backup_in_progress", c.message, c.detail, true case longOpReinstall: c := serverOpConflicts["reinstall_in_progress"] return "reinstall_in_progress", c.message, c.detail, true case longOpRuntimeSeed: c := serverOpConflicts["runtime_seed_in_progress"] return "runtime_seed_in_progress", c.message, c.detail, true } return "", "", "", false } // writeServerOpConflictResponse replies 409 on behalf of a failed // tryLockServerOp: it names the registered long op when there is one (backup / // reinstall / runtime seed) and otherwise advertises a quick retry, since the // holder is then a short op that clears within moments. It returns the refusal // code so callers can audit it. Call it only after the TryLock failed. func (a *Agent) writeServerOpConflictResponse(w http.ResponseWriter, name string) string { if code, _, _, long := a.longOpConflict(name); long { jsonWrite(w, 409, serverOpConflictBody(code)) return code } jsonWrite(w, 409, serverOpConflictBody("server_op_in_progress")) return "server_op_in_progress" } // backupOpConflictBody builds the backup handlers' 409 body for a failed // tryLockServerOp. It keeps the exact legacy body for a backup holder and for // unregistered short holders (the pre-existing combinations, whose consumers // match on the error text), and names the actual holder for the long ops the // op-lock sharing made reachable (reinstall, runtime seed). func backupOpConflictBody(a *Agent, name string) map[string]any { switch a.longOpKind(name) { case longOpReinstall: return map[string]any{ "ok": false, "error": "reinstall operation already in progress", "code": "reinstall_in_progress", "detail": "A reinstall is running on this server; retry after it completes.", } case longOpRuntimeSeed: return map[string]any{ "ok": false, "error": "runtime seed operation already in progress", "code": "runtime_seed_in_progress", "detail": "A runtime seed is running on this server; retry after it completes.", } } return map[string]any{"ok": false, "error": "backup operation already in progress"} } type ServerStatus struct { Name string `json:"name"` Status string `json:"status"` CPU *float64 `json:"cpu,omitempty"` CpuLimit *float64 `json:"cpuLimit,omitempty"` Memory *float64 `json:"memory,omitempty"` Disk *float64 `json:"disk,omitempty"` Uptime *int64 `json:"uptime,omitempty"` } func (a *Agent) handleListServers(w http.ResponseWriter, r *http.Request) { // adpanel:multidisk - enumerate servers across every disk root, not just the // primary volumes dir, so secondary-disk servers are listed with live data. names := a.enumerateServerNames() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() var servers []ServerStatus for _, name := range names { serverDir := a.serverDir(name) ss := ServerStatus{ Name: name, Status: "stopped", } meta := a.loadMeta(serverDir) cpuCoresConfig := metaCpuCores(meta) _, cpuLimit := computeCpuLimit(cpuCoresConfig) ss.CpuLimit = &cpuLimit if a.docker.containerExists(ctx, name) { out, _, _, err := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.Running}}", name) if err == nil && strings.TrimSpace(out) == "true" { ss.Status = "running" startedAt, _, _, startErr := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.StartedAt}}", name) if startErr == nil && strings.TrimSpace(startedAt) != "" { startTime, parseErr := time.Parse(time.RFC3339Nano, strings.TrimSpace(startedAt)) if parseErr == nil { uptime := int64(time.Since(startTime).Seconds()) ss.Uptime = &uptime } } statsOut, _, _, statsErr := a.docker.runCollect(ctx, "stats", "--no-stream", "--format", "{{.CPUPerc}}|{{.MemUsage}}", name) if statsErr == nil && strings.TrimSpace(statsOut) != "" { parts := strings.Split(strings.TrimSpace(statsOut), "|") if len(parts) >= 2 { cpuStr := strings.TrimSuffix(strings.TrimSpace(parts[0]), "%") if cpu, err := strconv.ParseFloat(cpuStr, 64); err == nil { if cpu > cpuLimit { cpu = cpuLimit } ss.CPU = &cpu } memParts := strings.Split(parts[1], "/") if len(memParts) >= 1 { memMb := parseMemoryString(strings.TrimSpace(memParts[0])) if memMb > 0 { ss.Memory = &memMb } } } } } } diskBytes := a.getServerTotalUsage(serverDir) if diskBytes > 0 { diskMb := float64(diskBytes) / (1024 * 1024) ss.Disk = &diskMb } servers = append(servers, ss) } resources := map[string]any{ "totalMemory": runtime.MemStats{}.Sys, "cpuCount": runtime.NumCPU(), } jsonWrite(w, 200, map[string]any{ "ok": true, "servers": servers, "resources": resources, }) } type resourceLimits struct { RamMb *int `json:"ramMb"` CpuCores *float64 `json:"cpuCores"` StorageMb *int `json:"storageMb"` StorageGb *int `json:"storageGb"` SwapMb *int `json:"swapMb"` BackupsMax *int `json:"backupsMax"` MaxSchedules *int `json:"maxSchedules"` IoWeight *int `json:"ioWeight"` CpuWeight *int `json:"cpuWeight"` PidsLimit *int `json:"pidsLimit"` FileLimit *int `json:"fileLimit"` NetworkInboundLimitMb *int64 `json:"networkInboundLimitMb"` NetworkOutboundLimitMb *int64 `json:"networkOutboundLimitMb"` NetworkResetMinutes *int `json:"networkResetMinutes"` } type dockerTemplateConfig struct { Image string `json:"image"` Tag string `json:"tag"` Command string `json:"command"` ADPanelStartup string `json:"adpanelStartup"` ADPanelStartupSnake string `json:"adpanel_startup"` LegacyStartup string `json:"pterodactylStartup"` LegacyStartupSnake string `json:"pterodactyl_startup"` StartupDisplay string `json:"startupDisplay"` StartupDisplaySnake string `json:"startup_display"` StartupPreview string `json:"startupPreview"` StartupPreviewSnake string `json:"startup_preview"` ImageDefaultStartup string `json:"imageDefaultStartup"` ImageDefaultStartupSnake string `json:"image_default_startup"` JavaVersion string `json:"javaVersion"` Java string `json:"java"` Ports []int `json:"ports"` PortProtocols map[string][]string `json:"portProtocols"` Volumes []string `json:"volumes"` Workdir string `json:"workdir"` WorkingDir string `json:"workingDir"` Env map[string]string `json:"env"` Restart string `json:"restart"` RestartPolicy string `json:"restartPolicy"` RunAsRoot bool `json:"runAsRoot"` RunAsRootSnake bool `json:"run_as_root"` BindIP string `json:"bind_ip"` HostIP string `json:"host_ip"` StartupCommand string `json:"startupCommand"` Install *templateInstallConfig `json:"install"` Installation *templateInstallConfig `json:"installation"` Console any `json:"console"` } type templateInstallConfig struct { Image string `json:"image"` Container string `json:"container"` Script string `json:"script"` Entrypoint string `json:"entrypoint"` MountPath string `json:"mountPath"` ContainerPath string `json:"containerPath"` RuntimePath string `json:"runtimePath"` TimeoutSeconds int `json:"timeoutSeconds"` Timeout int `json:"timeout"` MinimumStorageMb int `json:"minimumStorageMb"` AllowEmpty bool `json:"allowEmpty"` AllowEmptyResult bool `json:"allowEmptyResult"` Env map[string]string `json:"env"` } type templateStartupCommandReq struct { TemplateId string `json:"templateId"` Image string `json:"image"` Tag string `json:"tag"` StartFile string `json:"startFile"` DataDir string `json:"dataDir"` FallbackCommand string `json:"fallbackCommand"` } func (a *Agent) handleTemplateStartupCommand(w http.ResponseWriter, r *http.Request) { var req templateStartupCommandReq if err := readJSON(w, r, 1<<20, &req); err != nil { jsonWrite(w, 400, map[string]any{"error": "invalid request body"}) return } templateType := strings.ToLower(strings.TrimSpace(req.TemplateId)) image := strings.TrimSpace(req.Image) tag := strings.TrimSpace(req.Tag) if image == "" { jsonWrite(w, 400, map[string]any{"error": "missing image"}) return } if strings.ContainsAny(image, " \t\r\n") { jsonWrite(w, 400, map[string]any{"error": "invalid image"}) return } if tag == "" { tag = "latest" } if strings.ContainsAny(tag, " \t\r\n") { jsonWrite(w, 400, map[string]any{"error": "invalid tag"}) return } startFile := strings.TrimSpace(req.StartFile) if startFile == "" { startFile = defaultStartFileForType(templateType) } dataDir := strings.TrimSpace(req.DataDir) if dataDir == "" { dataDir = defaultDataDirForType(templateType) } imageRef := image + ":" + tag if reason := validateTemplateImageRef(imageRef); reason != "" { jsonWrite(w, 400, map[string]any{"error": reason}) return } ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) defer cancel() command, source, inspected, err := a.inferRuntimeProcessCommandFromImage(ctx, templateType, imageRef, startFile, dataDir, req.FallbackCommand) if err != nil { jsonWrite(w, 502, map[string]any{"ok": false, "error": "failed to infer startup command", "detail": err.Error()}) return } workingDir := strings.TrimSpace(inspected.Workdir) if workingDir == "" { workingDir = "/" } jsonWrite(w, 200, map[string]any{ "ok": true, "command": command, "source": source, "imageRef": imageRef, "entrypoint": inspected.Entrypoint, "cmd": inspected.Cmd, "workingDir": workingDir, "env": inspected.Env, }) } type createReq struct { Name string `json:"name"` Template string `json:"templateId"` MCFork string `json:"mcFork"` MCVersion string `json:"mcVersion"` HostPort int `json:"hostPort"` BindIP string `json:"bind_ip"` HostIP string `json:"host_ip"` AutoStart bool `json:"autoStart"` AsyncSetup bool `json:"asyncSetup"` Resources *resourceLimits `json:"resources"` Docker *dockerTemplateConfig `json:"docker"` StartupCommand string `json:"startupCommand"` JavaVersion string `json:"javaVersion"` ImportUrl string `json:"importUrl"` DiskID string `json:"diskId"` } // createCallerWaitBudget covers the response-blocking work that precedes the // create response: on the asyncSetup path (both panel create flows) the // per-server op-lock wait plus the synchronous prepare phase — preflight and // up to two docker image pulls (installer and runtime), each under its own // 10-minute context; on the synchronous direct-API path the full create chain // (minecraft jar download under a 30-minute context, or a template install // under its 30-minute default context, plus the container start). A cold // first pull used to lose the response to the stock 120s WriteTimeout while // the create kept running: the panel's recovery poll then committed the row // without the daemon's meta, so it never carried the installing marker while // the daemon 409-gated actions with server_installing. Callers with shorter // budgets (the nodes.js relay waits 120s) still surface timeouts for creates // that outlive THEM — raising those is a product decision, same as the delete // budget. The 7200s installer timeoutSeconds clamp and a multi-GB synchronous // archive import can still outlive this arm. const createCallerWaitBudget = 35 * time.Minute func (a *Agent) handleCreateServer(w http.ResponseWriter, r *http.Request) { var req createReq if err := readJSON(w, r, a.uploadLimit, &req); err != nil { jsonWrite(w, 400, map[string]any{"error": "bad json", "detail": err.Error()}) return } if a.debug { fmt.Printf("[createServer] Received request - Name: %s, Template: %s\n", req.Name, req.Template) } name := sanitizeName(req.Name) if name == "" { jsonWrite(w, 400, map[string]any{"error": "invalid name"}) return } if strings.TrimSpace(req.Template) == "" { jsonWrite(w, 400, map[string]any{"error": "missing templateId"}) return } if req.HostPort != 0 { if _, ok := parseStrictPortValue(req.HostPort); !ok { jsonWrite(w, 400, map[string]any{"error": "invalid hostPort"}) return } } if req.Docker != nil { for _, p := range req.Docker.Ports { if _, ok := parseStrictPortValue(p); !ok { jsonWrite(w, 400, map[string]any{"error": fmt.Sprintf("invalid docker port: %d", p)}) return } } if cleanPortProtocols := sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports); len(req.Docker.PortProtocols) > 0 && len(cleanPortProtocols) == 0 { jsonWrite(w, 400, map[string]any{"error": "invalid docker port protocols"}) return } // Registry allowlist at the create boundary (mirrors the panel's // ingestion check): both the runtime image and the installer image are // execution content the node will pull, so neither may come from a // registry the operator has not allowed. if req.Docker.Image != "" { tag := strings.TrimSpace(req.Docker.Tag) if tag == "" { tag = "latest" } if reason := validateTemplateImageRef(strings.TrimSpace(req.Docker.Image) + ":" + tag); reason != "" { jsonWrite(w, 400, map[string]any{"error": reason}) return } } if install := dockerTemplateInstall(req.Docker); install != nil { if reason := validateTemplateImageRef(install.Image); reason != "" { jsonWrite(w, 400, map[string]any{"error": "installer image: " + reason}) return } } } if strings.TrimSpace(req.StartupCommand) != "" || (req.Docker != nil && strings.TrimSpace(req.Docker.StartupCommand) != "") { jsonWrite(w, 400, map[string]any{"error": "raw docker startup commands are no longer supported"}) return } if reason := validateResourcePerformanceLimits(req.Resources); reason != "" { jsonWrite(w, 400, map[string]any{"error": reason}) return } templateForPort := strings.ToLower(strings.TrimSpace(req.Template)) hostPortForCheck := req.HostPort if hostPortForCheck == 0 { if templateForPort == "minecraft" { hostPortForCheck = 25565 } else if req.Docker != nil && len(req.Docker.Ports) > 0 && req.Docker.Ports[0] > 0 { hostPortForCheck = req.Docker.Ports[0] } else { hostPortForCheck = 8080 } } protocolsForMainPort := []string{"tcp"} if req.Docker != nil { portProtocols := runtimePortProtocolMap(sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports)) if len(req.Docker.Ports) > 0 { protocolsForMainPort = portProtocolsFor(portProtocols, req.Docker.Ports[0]) } } if hostPortForCheck > 0 { ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) available, owner, reason := a.hostPortAvailabilityForProtocols(ctx, hostPortForCheck, protocolsForMainPort, "") cancel() if !available { msg := fmt.Sprintf("port %d is already in use", hostPortForCheck) if owner != "" { msg = fmt.Sprintf("port %d is already used by container %s", hostPortForCheck, owner) } else if reason != "" { msg = fmt.Sprintf("port %d is unavailable (%s)", hostPortForCheck, reason) } jsonWrite(w, 409, map[string]any{"error": msg, "code": "port_in_use", "port": hostPortForCheck, "owner": owner}) return } } // Long op: the response lands only after the per-server op-lock wait plus // the synchronous prepare phase (up to two image pulls under 10-minute // contexts) on the asyncSetup path, or the full create chain on the // synchronous direct-API path — see createCallerWaitBudget (ignored on // writers without deadline support, e.g. httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(createCallerWaitBudget)) opMu := a.getServerOpLock(name) opMu.Lock() setupOwnsLock := false defer func() { if !setupOwnsLock { opMu.Unlock() } }() // adpanel:multidisk - resolve and validate the target disk before any path is // computed. Unknown/empty diskId => primary (back-compat). The routing cache is // primed now so serverDir(name) and serverBackupsDir(name) route correctly for // the rest of this handler; __diskId is persisted into meta further below. targetDisk, diskOK := a.diskByID(req.DiskID) if !diskOK { jsonWrite(w, 400, map[string]any{"error": "invalid diskId"}) return } a.setServerDiskMapping(name, targetDisk.ID) if capErr := a.checkDiskCapacity(targetDisk, 0); capErr != nil { a.invalidateServerDiskCache(name) jsonWrite(w, 507, capErr) return } serverDir := a.serverDir(name) if _, err := os.Stat(serverDir); err == nil { extMetaExists := false if _, metaErr := os.Stat(a.metaPath(name)); metaErr == nil { extMetaExists = true } legacyPath := filepath.Join(serverDir, "adpanel.json") legacyExists := false if _, metaErr := os.Stat(legacyPath); metaErr == nil { legacyExists = true } if extMetaExists || legacyExists { jsonWrite(w, 400, map[string]any{"error": "server already exists"}) return } fmt.Printf("[createServer] Found stale server directory without meta, cleaning up: %s\n", serverDir) if err := os.RemoveAll(serverDir); err != nil { fmt.Printf("[createServer] Warning: failed to clean stale directory: %v\n", err) } } _ = ensureDir(serverDir) template := strings.ToLower(strings.TrimSpace(req.Template)) meta := map[string]any{} // adpanel:multidisk - persist the assigned disk so serverDir/serverBackupsDir // route correctly across restarts. Omitted for primary to keep meta unchanged // for the common single-disk case. if !(targetDisk.Primary || targetDisk.ID == primaryDiskID) { meta["__diskId"] = targetDisk.ID } if template != "minecraft" { if req.Docker == nil || strings.TrimSpace(req.Docker.Image) == "" { _ = os.RemoveAll(serverDir) jsonWrite(w, 400, map[string]any{"error": "no docker image specified", "detail": "Template payload must include docker.image"}) return } } resourcesMeta := map[string]any{} if req.Resources != nil { if req.Resources.RamMb != nil && *req.Resources.RamMb > 0 { resourcesMeta["ramMb"] = *req.Resources.RamMb } if req.Resources.CpuCores != nil && *req.Resources.CpuCores > 0 { resourcesMeta["cpuCores"] = *req.Resources.CpuCores } if req.Resources.StorageMb != nil && *req.Resources.StorageMb > 0 { resourcesMeta["storageMb"] = *req.Resources.StorageMb } else if req.Resources.StorageGb != nil && *req.Resources.StorageGb > 0 { resourcesMeta["storageGb"] = *req.Resources.StorageGb } if req.Resources.SwapMb != nil { resourcesMeta["swapMb"] = *req.Resources.SwapMb } if req.Resources.BackupsMax != nil { resourcesMeta["backupsMax"] = *req.Resources.BackupsMax } if req.Resources.MaxSchedules != nil { resourcesMeta["maxSchedules"] = *req.Resources.MaxSchedules } if req.Resources.IoWeight != nil { resourcesMeta["ioWeight"] = *req.Resources.IoWeight } if req.Resources.CpuWeight != nil { resourcesMeta["cpuWeight"] = *req.Resources.CpuWeight } if req.Resources.PidsLimit != nil { resourcesMeta["pidsLimit"] = *req.Resources.PidsLimit } if req.Resources.FileLimit != nil { resourcesMeta["fileLimit"] = *req.Resources.FileLimit } if req.Resources.NetworkInboundLimitMb != nil && *req.Resources.NetworkInboundLimitMb > 0 { resourcesMeta["networkInboundLimitMb"] = *req.Resources.NetworkInboundLimitMb } if req.Resources.NetworkOutboundLimitMb != nil && *req.Resources.NetworkOutboundLimitMb > 0 { resourcesMeta["networkOutboundLimitMb"] = *req.Resources.NetworkOutboundLimitMb } if req.Resources.NetworkResetMinutes != nil && *req.Resources.NetworkResetMinutes > 0 { resourcesMeta["networkResetMinutes"] = *req.Resources.NetworkResetMinutes } } if template == "minecraft" { // adpanel:F8 - reject bad fork/version values at the node's trust // boundary, before they reach writeMinecraftScaffold or the // PaperMC/Purpur URL construction further down. fork, forkErr := resolveMinecraftFork(req.MCFork) if forkErr != nil { jsonWrite(w, 400, map[string]any{"error": forkErr.Error()}) return } ver, verErr := resolveMinecraftVersion(req.MCVersion) if verErr != nil { jsonWrite(w, 400, map[string]any{"error": verErr.Error()}) return } hostPort := req.HostPort if hostPort == 0 { hostPort = 25565 } writeMinecraftScaffold(serverDir, name, fork, ver) mcImage := defaultMinecraftProcessImage mcTag := defaultMinecraftProcessTag mcCommand := defaultMinecraftProcessCommand mcWorkdir := "/data" rawJavaVersion := strings.TrimSpace(req.JavaVersion) if rawJavaVersion == "" && req.Docker != nil { rawJavaVersion = javaVersionFromDockerConfig(req.Docker) } mcJavaVersion := normalizeMinecraftJavaVersion(rawJavaVersion) if strings.TrimSpace(rawJavaVersion) != "" && mcJavaVersion == "" { jsonWrite(w, 400, map[string]any{"error": "unsupported minecraft java version"}) return } if req.Docker != nil && req.Docker.Image != "" { mcImage = req.Docker.Image if req.Docker.Tag != "" { mcTag = req.Docker.Tag } reqWorkdir := strings.TrimSpace(req.Docker.Workdir) if reqWorkdir == "" { reqWorkdir = strings.TrimSpace(req.Docker.WorkingDir) } if reqWorkdir != "" { cleanWorkdir := normalizeContainerWorkdir(reqWorkdir) if cleanWorkdir == "" { jsonWrite(w, 400, map[string]any{"error": "invalid workdir (must be an absolute path like /data)"}) return } mcWorkdir = cleanWorkdir } if cmd := sanitizeRuntimeCommand(req.Docker.Command); cmd != "" { mcCommand = normalizeLegacyRuntimeProcessCommand("minecraft", cmd, "server.jar", "/data") if reason := validateRuntimeProcessCommand(mcCommand); reason != "" { jsonWrite(w, 400, map[string]any{"error": reason}) return } } } if mcJavaVersion == "" { mcJavaVersion = minecraftJavaVersionFromTag(mcTag) } if mcJavaVersion != "" { mcImage = defaultMinecraftProcessImage mcTag = minecraftJavaTag(mcJavaVersion) } meta = map[string]any{ "type": "minecraft", "fork": fork, "version": ver, "start": "server.jar", "hostPort": hostPort, "runtime": map[string]any{ "image": mcImage, "tag": mcTag, "command": mcCommand, "workdir": mcWorkdir, "javaVersion": func() any { if mcJavaVersion != "" { return mcJavaVersion } return nil }(), }, } bindIP := strings.TrimSpace(req.BindIP) if bindIP == "" { bindIP = strings.TrimSpace(req.HostIP) } if bindIP == "" && req.Docker != nil { if req.Docker.BindIP != "" { bindIP = strings.TrimSpace(req.Docker.BindIP) } else if req.Docker.HostIP != "" { bindIP = strings.TrimSpace(req.Docker.HostIP) } } if bindIP != "" && bindIP != "" { meta["bind_ip"] = bindIP meta["host_ip"] = bindIP if runtimeObj, ok := meta["runtime"].(map[string]any); ok { runtimeObj["bind_ip"] = bindIP runtimeObj["host_ip"] = bindIP } } if len(resourcesMeta) > 0 { meta["resources"] = resourcesMeta } if startupDisplay := startupDisplayFromDockerConfig(req.Docker); startupDisplay != "" { if runtimeObj, ok := meta["runtime"].(map[string]any); ok { runtimeObj["startupDisplay"] = startupDisplay } } if req.Docker != nil { if runtimeObj, ok := meta["runtime"].(map[string]any); ok { if portProtocols := sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports); len(portProtocols) > 0 { runtimeObj["portProtocols"] = portProtocols } if restart := strings.TrimSpace(req.Docker.Restart); restart != "" { runtimeObj["restart"] = restart } else if restartPolicy := strings.TrimSpace(req.Docker.RestartPolicy); restartPolicy != "" { runtimeObj["restart"] = restartPolicy } if req.Docker.Console != nil { runtimeObj["console"] = req.Docker.Console } } } if req.AsyncSetup { meta["setupStatus"] = "queued" meta["setupMessage"] = "Server setup queued" meta["setupUpdatedAt"] = time.Now().UnixMilli() } _ = a.saveMeta(serverDir, meta) if req.AsyncSetup { setupOwnsLock = a.acceptAsyncCreateSetup(w, r, req, name, serverDir, meta, hostPort, opMu.Unlock, true) return } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) jarURL, jarErr := getMinecraftJarURL(ctx, a.dl, fork, ver, a.debug) cancel() if jarErr != nil { jsonWrite(w, 400, map[string]any{"error": "jar resolution failed", "detail": jarErr.Error()}) return } ctxD, cancelD := context.WithTimeout(context.Background(), 30*time.Minute) if err := a.dl.downloadToFile(ctxD, jarURL, filepath.Join(serverDir, "server.jar")); err != nil { cancelD() jsonWrite(w, 500, map[string]any{"error": "download failed", "detail": err.Error()}) return } cancelD() enforceServerProps(serverDir) if req.ImportUrl != "" { fmt.Printf("[createServer] Importing archive from URL for Minecraft server: %s\n", req.ImportUrl) if err := a.downloadAndExtractArchiveSync(name, serverDir, req.ImportUrl); err != nil { fmt.Printf("[createServer] Warning: archive import failed: %v\n", err) } } if req.AutoStart { ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) err := a.startMinecraftContainer(ctx, name, serverDir, hostPort, req.Resources, nil, false) cancel() if err != nil { if errors.Is(err, errMinecraftEulaRequired) { // The server files are valid; the EULA prompt in the console // will gate the first start. Keep the server. auditLog.Log("server_create", getClientIP(r), "", name, "create", "success", map[string]any{"template": req.Template, "eulaRequired": true}) jsonWrite(w, 200, map[string]any{"ok": true, "name": name, "meta": meta, "eulaRequired": true}) return } fmt.Printf("[createServer] Container startup failed, cleaning up: %s - %v\n", name, err) _ = os.RemoveAll(serverDir) _ = os.Remove(a.metaPath(name)) jsonWrite(w, 500, map[string]any{"error": "failed to start server", "detail": err.Error()}) return } a.ensureLiveLogs(name) } } else { hostPort := req.HostPort if hostPort == 0 { if req.Docker != nil && len(req.Docker.Ports) > 0 && req.Docker.Ports[0] > 0 { hostPort = req.Docker.Ports[0] } else { hostPort = 8080 } } runtimeConfig := map[string]any{} if req.Docker != nil { if req.Docker.Image != "" { runtimeConfig["image"] = req.Docker.Image } if req.Docker.Tag != "" { runtimeConfig["tag"] = req.Docker.Tag } if cmd := sanitizeRuntimeCommand(req.Docker.Command); cmd != "" { cleanCmd := normalizeLegacyRuntimeProcessCommand(template, cmd, defaultStartFileForType(template), defaultDataDirForType(template)) if reason := validateRuntimeProcessCommand(cleanCmd); reason != "" { jsonWrite(w, 400, map[string]any{"error": reason}) return } runtimeConfig["command"] = cleanCmd } if len(req.Docker.Ports) > 0 { runtimeConfig["ports"] = req.Docker.Ports } if portProtocols := sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports); len(portProtocols) > 0 { runtimeConfig["portProtocols"] = portProtocols } if len(req.Docker.Volumes) > 0 { runtimeConfig["volumes"] = req.Docker.Volumes } if len(req.Docker.Env) > 0 { runtimeConfig["env"] = req.Docker.Env } if startup := startupTemplateFromDockerConfig(req.Docker); startup != "" { if reason := validateADPanelStartupScript(startup); reason != "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": reason}) return } runtimeConfig["adpanelStartup"] = startup delete(runtimeConfig, "command") } if startupDisplay := startupDisplayFromDockerConfig(req.Docker); startupDisplay != "" { runtimeConfig["startupDisplay"] = startupDisplay } if install := dockerTemplateInstall(req.Docker); install != nil { if reason := validateTemplateInstallScript(install.Script); reason != "" { jsonWrite(w, 400, map[string]any{"error": reason}) return } runtimeConfig["install"] = install } reqWorkdir := strings.TrimSpace(req.Docker.Workdir) if reqWorkdir == "" { reqWorkdir = strings.TrimSpace(req.Docker.WorkingDir) } if reqWorkdir != "" { cleanWorkdir := normalizeContainerWorkdir(reqWorkdir) if cleanWorkdir == "" { jsonWrite(w, 400, map[string]any{"error": "invalid workdir (must be an absolute path like /app)"}) return } runtimeConfig["workdir"] = cleanWorkdir } if restart := strings.TrimSpace(req.Docker.Restart); restart != "" { runtimeConfig["restart"] = restart } else if restartPolicy := strings.TrimSpace(req.Docker.RestartPolicy); restartPolicy != "" { runtimeConfig["restart"] = restartPolicy } if templateRootAllowed() && (req.Docker.RunAsRoot || req.Docker.RunAsRootSnake) { runtimeConfig["runAsRoot"] = true } if req.Docker.Console != nil { runtimeConfig["console"] = req.Docker.Console } runtimeConfig["providerId"] = "custom" } if _, ok := runtimeConfig["command"]; !ok { if defaultCmd := defaultRuntimeCommandForType(template, defaultStartFileForType(template), defaultDataDirForType(template)); defaultCmd != "" { runtimeConfig["command"] = defaultCmd } } if _, ok := runtimeConfig["workdir"]; !ok && hasManagedRuntimeDefaults(template) { runtimeConfig["workdir"] = defaultDataDirForType(template) } meta = map[string]any{ "type": template, "template": template, "hostPort": hostPort, "createdAt": time.Now().UnixMilli(), } bindIP := strings.TrimSpace(req.BindIP) if bindIP == "" { bindIP = strings.TrimSpace(req.HostIP) } if bindIP == "" && req.Docker != nil { if req.Docker.BindIP != "" { bindIP = strings.TrimSpace(req.Docker.BindIP) } else if req.Docker.HostIP != "" { bindIP = strings.TrimSpace(req.Docker.HostIP) } } if bindIP != "" && bindIP != "" { meta["bind_ip"] = bindIP meta["host_ip"] = bindIP if len(runtimeConfig) > 0 { runtimeConfig["bind_ip"] = bindIP runtimeConfig["host_ip"] = bindIP } } if len(runtimeConfig) > 0 { meta["runtime"] = runtimeConfig } if len(resourcesMeta) > 0 { meta["resources"] = resourcesMeta } if req.AsyncSetup { meta["setupStatus"] = "queued" meta["setupMessage"] = "Server setup queued" meta["setupUpdatedAt"] = time.Now().UnixMilli() } fmt.Printf("[createServer] Final meta to save: %+v\n", meta) _ = a.saveMeta(serverDir, meta) if req.AsyncSetup { setupOwnsLock = a.acceptAsyncCreateSetup(w, r, req, name, serverDir, meta, hostPort, opMu.Unlock, false) return } if install := installConfigFromRuntime(runtimeConfig); install != nil { if err := a.runTemplateInstall(context.Background(), name, serverDir, install, runtimeConfig, hostPort, req.Resources, 0); err != nil { fmt.Printf("[createServer] Template install failed, cleaning up: %s - %v\n", name, err) _ = os.RemoveAll(serverDir) _ = os.Remove(a.metaPath(name)) jsonWrite(w, 500, map[string]any{"error": "failed to install server", "detail": err.Error()}) return } } if req.ImportUrl != "" { fmt.Printf("[createServer] Importing archive from URL: %s\n", req.ImportUrl) if err := a.downloadAndExtractArchiveSync(name, serverDir, req.ImportUrl); err != nil { fmt.Printf("[createServer] Warning: archive import failed: %v\n", err) } } switch template { case "python": scaffoldPython(serverDir, defaultStartFileForType(template)) case "nodejs", "discord-bot": scaffoldNode(serverDir, filepath.Base(serverDir), defaultStartFileForType(template), hostPort) } hasImage := req.Docker != nil && req.Docker.Image != "" if req.AutoStart && hasImage { ctx, cancel := context.WithTimeout(context.Background(), 240*time.Second) var err error if isManagedProcessRuntime(template) { err = a.startRuntimeContainer(ctx, name, serverDir, meta, hostPort, req.Resources, nil) } else { err = a.startCustomDockerContainer(ctx, name, serverDir, meta, hostPort, req.Resources) } cancel() if err != nil { fmt.Printf("[createServer] Container startup failed, cleaning up: %s - %v\n", name, err) _ = os.RemoveAll(serverDir) _ = os.Remove(a.metaPath(name)) jsonWrite(w, 500, map[string]any{"error": "failed to start server", "detail": err.Error()}) return } a.ensureLiveLogs(name) } } auditLog.Log("server_create", getClientIP(r), "", name, "create", "success", map[string]any{"template": req.Template}) jsonWrite(w, 200, map[string]any{"ok": true, "name": name, "meta": meta}) } func resourceRamLimitMbFromMeta(meta map[string]any) float64 { resources, _ := meta["resources"].(map[string]any) if resources == nil { return 0 } return anyToFloat64(resources["ramMb"]) } func resourceStorageLimitMbFromMeta(meta map[string]any) float64 { resources, _ := meta["resources"].(map[string]any) if resources == nil { return 0 } if v := anyToFloat64(resources["storageMb"]); v > 0 { return v } if v := anyToFloat64(resources["storageGb"]); v > 0 { return v * 1024 } return 0 } func buildNetworkStatsPayload(inboundBytes, outboundBytes uint64) map[string]any { return map[string]any{ "inboundBytes": inboundBytes, "outboundBytes": outboundBytes, "rxBytes": inboundBytes, "txBytes": outboundBytes, } } type networkAntiAbuseRule struct { inboundLimitBytes uint64 outboundLimitBytes uint64 resetEvery time.Duration enabled bool } func networkLimitMbToBytes(mb int64) uint64 { if mb <= 0 { return 0 } maxMb := int64(^uint64(0) / (1024 * 1024)) if mb > maxMb { return ^uint64(0) } return uint64(mb) * 1024 * 1024 } func networkAntiAbuseRuleFromMeta(meta map[string]any) networkAntiAbuseRule { resources, _ := meta["resources"].(map[string]any) if resources == nil { return networkAntiAbuseRule{} } inboundMb := anyToInt64(resources["networkInboundLimitMb"]) outboundMb := anyToInt64(resources["networkOutboundLimitMb"]) if inboundMb <= 0 && outboundMb <= 0 { return networkAntiAbuseRule{} } resetMinutes := anyToInt(resources["networkResetMinutes"]) if resetMinutes <= 0 { resetMinutes = defaultNetworkResetMins } if resetMinutes < minNetworkResetMins || resetMinutes > maxNetworkResetMins { resetMinutes = defaultNetworkResetMins } return networkAntiAbuseRule{ inboundLimitBytes: networkLimitMbToBytes(inboundMb), outboundLimitBytes: networkLimitMbToBytes(outboundMb), resetEvery: time.Duration(resetMinutes) * time.Minute, enabled: inboundMb > 0 || outboundMb > 0, } } func uint64Remaining(limit, used uint64) uint64 { if limit == 0 || used >= limit { return 0 } return limit - used } func attachNetworkAntiAbusePayload(payload map[string]any, rule networkAntiAbuseRule, windowRx, windowTx uint64, windowStartedAt time.Time) { if payload == nil || !rule.enabled { return } payload["windowInboundBytes"] = windowRx payload["windowOutboundBytes"] = windowTx payload["inboundLimitBytes"] = rule.inboundLimitBytes payload["outboundLimitBytes"] = rule.outboundLimitBytes payload["inboundRemainingBytes"] = uint64Remaining(rule.inboundLimitBytes, windowRx) payload["outboundRemainingBytes"] = uint64Remaining(rule.outboundLimitBytes, windowTx) payload["resetEveryMinutes"] = int(rule.resetEvery / time.Minute) if !windowStartedAt.IsZero() && rule.resetEvery > 0 { payload["windowStartedAt"] = windowStartedAt.UTC().Format(time.RFC3339) payload["windowResetsAt"] = windowStartedAt.Add(rule.resetEvery).UTC().Format(time.RFC3339) } } func normalizeDockerContainerStatus(status string) string { switch strings.ToLower(strings.TrimSpace(status)) { case "running": return "running" case "created", "exited", "dead", "removing", "paused": return "stopped" case "": return "stopped" default: return strings.ToLower(strings.TrimSpace(status)) } } func (a *Agent) getServerResourcePayload(ctx context.Context, name string) (map[string]any, error) { serverDir := a.serverDir(name) if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { return nil, os.ErrNotExist } if a.resourceStats == nil { return a.collectServerResourcePayload(ctx, name, serverDir, nil), nil } entry := a.resourceStats.get(name) entry.mu.Lock() defer entry.mu.Unlock() now := time.Now() entry.touchedAt = now if entry.payload != nil && now.Before(entry.expiresAt) { // Return a deep copy: the cached map is shared across concurrent // requests for the same server. Callers mutate (e.g. add baseDir) and // JSON-encode the result outside of this lock, so handing out the // cached map directly causes "concurrent map writes". return deepCopyPayload(entry.payload), nil } payload := a.collectServerResourcePayload(ctx, name, serverDir, entry) entry.payload = payload entry.expiresAt = now.Add(a.resourceStats.ttl) // Hand the caller its own copy and keep the cache copy private. return deepCopyPayload(payload), nil } func (a *Agent) collectServerResourcePayload(ctx context.Context, name, serverDir string, entry *serverResourceStatsCacheEntry) map[string]any { meta := a.loadMeta(serverDir) status := "stopped" now := time.Now() memoryUsedMb := float64(0) memoryLimitMb := resourceRamLimitMbFromMeta(meta) memoryPercent := float64(0) uptimeSeconds := int64(0) cpuEffCores, cpuMaxPercent := computeCpuLimit(metaCpuCores(meta)) cpuPercent := float64(0) networkRule := networkAntiAbuseRuleFromMeta(meta) var networkPayload map[string]any setupStatus, _ := meta["setupStatus"].(string) isSetupActive := setupStatus != "" && setupStatus != "ready" && setupStatus != "failed" inspected, _, exists, inspectErr := a.inspectContainerForStats(ctx, name) if isSetupActive { status = "installing" } else if inspectErr != nil { status = "unknown" } else if exists { status = normalizeDockerContainerStatus(inspected.State.Status) if inspected.State.Running { status = "running" if appliedMemoryMb := hostConfigMemoryLimitMb(inspected.HostConfig); appliedMemoryMb > 0 { memoryLimitMb = appliedMemoryMb } if appliedCPULimit := hostConfigCpuLimitPercent(inspected.HostConfig); appliedCPULimit > 0 { cpuMaxPercent = appliedCPULimit cpuEffCores = appliedCPULimit / 100.0 } if strings.TrimSpace(inspected.State.StartedAt) != "" { if startTime, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(inspected.State.StartedAt)); err == nil { uptimeSeconds = int64(time.Since(startTime).Seconds()) } } if stats, err := a.readContainerStatsForServer(ctx, name); err == nil { cpuPercent = dockerCPUPercent(stats) if cpuMaxPercent > 0 && cpuPercent > cpuMaxPercent { cpuPercent = cpuMaxPercent } memoryUsedMb = float64(dockerMemoryUsedBytes(stats.MemoryStats)) / (1024 * 1024) if memoryLimitMb > 0 { memoryPercent = (memoryUsedMb / memoryLimitMb) * 100 } if len(stats.Networks) > 0 && entry != nil { rawRx, rawTx := sumDockerNetworkBytes(stats.Networks) totalRx, totalTx, windowRx, windowTx, windowStartedAt := entry.updateNetworkCounters(inspected.ID, rawRx, rawTx, now, networkRule.resetEvery) networkPayload = buildNetworkStatsPayload(totalRx, totalTx) attachNetworkAntiAbusePayload(networkPayload, networkRule, windowRx, windowTx, windowStartedAt) } } } } if networkPayload == nil { networkPayload = buildNetworkStatsPayload(0, 0) if entry != nil { windowRx, windowTx, windowStartedAt := entry.currentNetworkWindow(now, networkRule.resetEvery) attachNetworkAntiAbusePayload(networkPayload, networkRule, windowRx, windowTx, windowStartedAt) } } var serverBytes int64 if entry != nil { serverBytes = entry.cachedDiskUsage(a, serverDir, now, a.resourceStats.diskTTL) } else { serverBytes = a.getServerDiskUsage(serverDir) } // adpanel:backup-storage - backups live outside serverDir, so add them on top // of the server-file usage. The combined value is what the panel shows and // what the disk-limit guard enforces, so "server occupied storage + backups" // is a single, consistent number everywhere. var backupsBytes int64 if entry != nil { backupsBytes = entry.cachedBackupsUsage(a, name, now, a.resourceStats.diskTTL) } else { backupsBytes = a.getServerBackupsUsage(name) } diskUsageBytes := serverBytes + backupsBytes diskUsageMb := float64(diskUsageBytes) / (1024 * 1024) diskUsageGb := float64(diskUsageBytes) / (1024 * 1024 * 1024) serverUsageMb := float64(serverBytes) / (1024 * 1024) backupsUsageMb := float64(backupsBytes) / (1024 * 1024) storageLimitMb := resourceStorageLimitMbFromMeta(meta) diskInfo := map[string]any{ "usedBytes": diskUsageBytes, "usedMb": diskUsageMb, "usedGb": diskUsageGb, // Breakdown so the UI can render "server files + backups". "serverBytes": serverBytes, "serverMb": serverUsageMb, "backupsBytes": backupsBytes, "backupsMb": backupsUsageMb, } diskPercent := float64(0) if storageLimitMb > 0 { limitBytes := int64(storageLimitMb) * 1024 * 1024 diskInfo["limitBytes"] = limitBytes diskInfo["limitGb"] = storageLimitMb / 1024 diskInfo["limitMb"] = storageLimitMb if limitBytes > 0 { diskPercent = (float64(diskUsageBytes) / float64(limitBytes)) * 100 } diskInfo["percentUsed"] = diskPercent } stats := map[string]any{ "cpu": map[string]any{ "percent": cpuPercent, "cores": cpuEffCores, "limit": cpuMaxPercent, }, "memory": map[string]any{ "usedMb": memoryUsedMb, "limitMb": memoryLimitMb, "percent": memoryPercent, }, "disk": map[string]any{ "usedMb": diskUsageMb, "limitMb": storageLimitMb, "percent": diskPercent, "serverMb": serverUsageMb, "backupsMb": backupsUsageMb, }, } if networkPayload != nil { stats["network"] = networkPayload } minecraft := isMinecraftServerMeta(meta) eulaAccepted := !minecraft || minecraftEulaAccepted(serverDir) payload := map[string]any{ "ok": true, "name": name, "status": status, "meta": meta, "disk": diskInfo, "stats": stats, "uptime": uptimeSeconds, "setupStatus": setupStatus, "setupMessage": meta["setupMessage"], "isInstalling": isSetupActive, "minecraft": minecraft, "eulaRequired": minecraft && !eulaAccepted, } if networkPayload != nil { payload["network"] = networkPayload } return payload } func (a *Agent) handleServerInfo(w http.ResponseWriter, r *http.Request, name string) { ctx, cancel := context.WithTimeout(r.Context(), 3500*time.Millisecond) defer cancel() payload, err := a.getServerResourcePayload(ctx, name) if errors.Is(err, os.ErrNotExist) { jsonWrite(w, 404, map[string]any{"error": "not found"}) return } if err != nil { jsonWrite(w, 500, map[string]any{"error": "failed to collect resource stats"}) return } // adpanel:multidisk - expose the resolved per-server baseDir / disk routing on the // SAME GET /v1/servers/ response that carries live stats. Previously a // dedicated early-return handler answered this route with only the baseDir fields // and no stats/uptime/network, which made the panel render "—" for every metric of // servers it resolved through this endpoint (notably secondary-disk servers). Merge // both concerns into one payload so the panel gets disk routing *and* live stats. if payload != nil { disk := a.diskForServer(name) payload["baseDir"] = a.serverDir(name) payload["diskId"] = disk.ID payload["diskRoot"] = a.diskLayoutVolumes(disk.MountPath) payload["primary"] = disk.Primary || disk.ID == primaryDiskID } jsonWrite(w, 200, payload) } func (a *Agent) handleGetResources(w http.ResponseWriter, r *http.Request, name string) { serverDir := a.serverDir(name) if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { jsonWrite(w, 404, map[string]any{"error": "not found"}) return } meta := a.loadMeta(serverDir) resources, _ := meta["resources"].(map[string]any) if resources == nil { resources = make(map[string]any) } if _, hasMb := resources["storageMb"]; !hasMb { if gb, hasGb := resources["storageGb"]; hasGb { var gbVal float64 switch v := gb.(type) { case float64: gbVal = v case int: gbVal = float64(v) case int64: gbVal = float64(v) } if gbVal > 0 { resources["storageMb"] = int(gbVal * 1024) } } } configuredCommand := "" command := "" commandSource := "" imageDefaultCommand := "" imageRef := "" templateType := "" javaVersion := "" if t, ok := meta["template"].(string); ok { templateType = t } else if t, ok := meta["type"].(string); ok { templateType = t } startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj != nil { configuredCommand = normalizeLegacyRuntimeProcessCommand(templateType, fmt.Sprint(runtimeObj["command"]), startFile, defaultDataDirForType(templateType)) adpanelStartup := startupTemplateFromRuntime(runtimeObj) if adpanelStartup != "" { configuredCommand = "" command = adpanelStartup commandSource = "adpanel-startup" } image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) if image != "" && image != "" { if tag == "" || tag == "" { tag = "latest" } imageRef = image + ":" + tag javaVersion = normalizeMinecraftJavaVersion(runtimeObj["javaVersion"]) if javaVersion == "" { javaVersion = minecraftJavaVersionFromTag(tag) } } } if command == "" && configuredCommand != "" { command = configuredCommand commandSource = "configured" } if command == "" { command = defaultRuntimeCommandForType( templateType, startFile, defaultDataDirForType(templateType), ) if command != "" { commandSource = "template-default" } } if command == "" && imageRef != "" { inspectCtx, inspectCancel := context.WithTimeout(context.Background(), 8*time.Second) imgCfg := a.inspectRuntimeImageConfig(inspectCtx, imageRef) inspectCancel() imageDefaultCommand = normalizeLegacyRuntimeProcessCommand( templateType, runtimeCommandFromImageConfig(imgCfg), startFile, defaultDataDirForType(templateType), ) if imageDefaultCommand != "" && validateRuntimeProcessCommand(imageDefaultCommand) == "" { command = imageDefaultCommand commandSource = "image-default" } } if command == "" && imageRef != "" { command = "sleep infinity" commandSource = "fallback" } template := templateType var memoryUsedMb, memoryLimitMb float64 if res, ok := resources["ramMb"]; ok { switch v := res.(type) { case float64: memoryLimitMb = v case int: memoryLimitMb = float64(v) case int64: memoryLimitMb = float64(v) } } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if a.docker.containerExists(ctx, name) { out, _, _, err := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.Running}}", name) if err == nil && strings.TrimSpace(out) == "true" { if inspectedMemoryLimitMb, _, inspectErr := a.inspectContainerAppliedLimits(ctx, name); inspectErr == nil && inspectedMemoryLimitMb > 0 { memoryLimitMb = inspectedMemoryLimitMb } statsOut, _, _, statsErr := a.docker.runCollect(ctx, "stats", "--no-stream", "--format", "{{.MemUsage}}", name) if statsErr == nil && strings.TrimSpace(statsOut) != "" { memParts := strings.Split(strings.TrimSpace(statsOut), "/") if len(memParts) >= 2 { memoryUsedMb = parseMemoryString(strings.TrimSpace(memParts[0])) } } } } stats := map[string]any{ "memory": map[string]any{ "usedMb": memoryUsedMb, "limitMb": memoryLimitMb, }, } var hostPort int if port, ok := parseStrictPortValue(meta["hostPort"]); ok { hostPort = port } payload := map[string]any{ "ok": true, "resources": resources, "command": command, "configuredCommand": configuredCommand, "effectiveCommand": command, "commandSource": commandSource, "imageDefaultCommand": imageDefaultCommand, "imageRef": imageRef, "template": template, "stats": stats, "hostPort": hostPort, } if strings.EqualFold(strings.TrimSpace(templateType), "minecraft") { payload["javaVersion"] = javaVersion payload["minecraftJava"] = minecraftJavaOptionsPayload(javaVersion) } jsonWrite(w, 200, payload) } func (a *Agent) handleImportArchive(w http.ResponseWriter, r *http.Request, name string) { srvDir := a.serverDir(name) if st, err := os.Stat(srvDir); err != nil || !st.IsDir() { jsonWrite(w, 404, map[string]any{"error": "server not found", "detail": "Server directory does not exist"}) return } if diskErr := a.checkDiskLimit(srvDir, 0); diskErr != nil { jsonWrite(w, 507, diskErr) return } var req struct { ArchiveUrl string `json:"archiveUrl"` } if err := readJSON(w, r, 1<<20, &req); err != nil { jsonWrite(w, 400, map[string]any{"error": "invalid request body"}) return } archiveUrl := strings.TrimSpace(req.ArchiveUrl) if archiveUrl == "" { jsonWrite(w, 400, map[string]any{"error": "archiveUrl is required"}) return } parsedUrl, err := url.Parse(archiveUrl) if err != nil || (parsedUrl.Scheme != "http" && parsedUrl.Scheme != "https") { jsonWrite(w, 400, map[string]any{"error": "invalid URL - must be http or https"}) return } pathname := strings.ToLower(parsedUrl.Path) validExt := false allowedExts := []string{".zip", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".7z", ".rar"} for _, ext := range allowedExts { if strings.HasSuffix(pathname, ext) { validExt = true break } } if !validExt { jsonWrite(w, 400, map[string]any{"error": "invalid archive format. Supported: .zip, .tar.gz, .tgz, .tar.bz2, .tbz2, .7z, .rar"}) return } a.importProgressMu.Lock() a.importProgress[name] = &ImportProgress{ Status: "downloading", Percent: 0, Downloaded: 0, Total: 0, } a.importProgressMu.Unlock() go a.downloadAndExtractArchive(name, srvDir, archiveUrl) jsonWrite(w, 200, map[string]any{"ok": true, "message": "Import started"}) } // purgeServerCopiesOnAllDisks removes any existing copy of a server's volumes and // backups directories from EVERY disk this node owns (primary + registered). // adpanel:multidisk - used before an import/transfer extraction so the server is // placed cleanly on exactly one target disk. Without this, a re-transfer that // changes the destination disk (e.g. secondary -> primary) would leave the old // copy behind; the back-compat scan in diskForServer would then re-adopt the // stale secondary directory and orphan the freshly imported files. Removing all // copies up front makes placement deterministic regardless of prior history. func (a *Agent) purgeServerCopiesOnAllDisks(name string) { safe := sanitizeName(name) if safe == "" { return } volumes, backups := a.serverStoragePaths(safe) for _, path := range append(volumes, backups...) { _ = os.RemoveAll(path) } } func (a *Agent) handleImportTar(w http.ResponseWriter, r *http.Request, name string) { if name == "" { jsonWrite(w, 400, map[string]any{"error": "invalid name"}) return } // adpanel:multidisk - a transfer lands the server on a disk OWNED BY THIS // (the destination) node. The incoming tar carries the SOURCE node's meta, // whose __diskId references a disk that only exists on the source. Adopting // that ID verbatim would mis-route the server (or, if this node happens to // own a disk with the same ID, point it at the wrong/empty location) and // orphan the extracted files. We therefore: // 1. resolve the destination disk from an optional ?diskId= (default // primary), priming the routing cache BEFORE computing any path so files // extract onto the correct disk, and // 2. extract the source meta into a temp dir (never verbatim into metaDir), // strip its stale __diskId, re-stamp the destination disk's __diskId // (omitted for primary, exactly like createServer), and persist it. // This guarantees the panel/node always resolve a secondary-disk server to // "/adpanel/volumes/" with backups at // "/adpanel/backups/", and a primary-disk server to the // default roots, across restarts and cold caches. transferID := "" if r.Method == http.MethodPut { transferID = r.URL.Query().Get("transferId") if !validReinstallOperationID(transferID) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid transfer ID"}) return } } opMu := a.getServerOpLock(name) if transferID == "" { opMu.Lock() } else if !opMu.TryLock() { a.writeServerOpConflictResponse(w, name) return } defer opMu.Unlock() if err := a.checkTransferSourceWritable(name); err != nil { status, body := fileMutationAdmissionFailure(err) jsonWrite(w, status, body) return } if transferID != "" { if status, err := a.checkTransferDestinationVacant(r.Context(), name); err != nil { jsonWrite(w, status, map[string]any{"ok": false, "error": err.Error()}) return } } targetDisk, diskOK := a.diskByID(strings.TrimSpace(r.URL.Query().Get("diskId"))) if !diskOK { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid diskId"}) return } a.setServerDiskMapping(name, targetDisk.ID) serverDir := a.serverDir(name) // adpanel:import-quota-lock — the import's quota checks and its streaming // extract commit quota-accounted bytes into this scope, so they serialize // under the same upload-scope lock as every other quota-accounted writer; // nested inside the op lock above like the backup flows (same direction, // no cycle). Held for the whole tar stream by design (HOL, see // lockUploadScope's doc): a usage snapshot is only meaningful if no other // writer can commit before the extract lands. importCtx := context.Background() if transferID != "" { importCtx = r.Context() } unlockImportScope, lockErr := a.acquireUploadScope(importCtx, serverDir) if lockErr != nil { a.invalidateServerDiskCache(name) jsonWrite(w, http.StatusRequestTimeout, uploadScopeRequestEnded()) return } defer unlockImportScope() if diskErr := a.checkDiskLimit(serverDir, 0); diskErr != nil { a.invalidateServerDiskCache(name) jsonWrite(w, 507, diskErr) return } if capErr := a.checkDiskCapacity(targetDisk, 0); capErr != nil { a.invalidateServerDiskCache(name) jsonWrite(w, 507, capErr) return } // adpanel:import-extract-budget — the two caps the pre-checks above just // validated against, captured here so the backstop enforces exactly that // basis (nothing between the pre-checks and this capture mutates meta). // The per-server limit also survives the purge below: it lives in the // registry meta volumesRoot/.adpanel_meta/.json, a sibling of the // per-server volumes/backups trees the purge RemoveAlls, and loadMeta // reads the external file first (the pre-check's own loadMeta call has // already migrated any legacy-only meta there), so a post-wipe re-read // returns the identical value. The capture is kept because it is still // the more robust read in one corner: if loadMeta's legacy-migration // write fails it deletes the legacy file anyway, where a post-wipe // re-read would silently return 0 and disarm the per-server axis the // pre-check had just enforced. The per-disk ceiling rides on targetDisk // itself. The pre-checks stay byte-identical and first — what follows is // only their mid-write backstop. importLimitBytes := a.getServerDiskLimitBytes(serverDir) importDiskCeiling := diskCapacityCeilingBytes(targetDisk) backupsDir := a.serverBackupsDir(name) if transferID == "" { a.purgeServerCopiesOnAllDisks(name) _ = os.RemoveAll(serverDir) _ = os.RemoveAll(backupsDir) } else if r.Context().Err() != nil { a.invalidateServerDiskCache(name) jsonWrite(w, http.StatusRequestTimeout, uploadScopeRequestEnded()) return } else if err := a.reserveTransferImport(serverDir, targetDisk, transferID); err != nil { a.invalidateServerDiskCache(name) jsonWrite(w, 500, map[string]any{"ok": false, "error": "could not reserve destination storage"}) return } _ = ensureDir(serverDir) _ = ensureDir(backupsDir) // adpanel:import-extract-budget — the extract below is a long // quota-accounted write; the pre-checks validated a projection the // extract must not outgrow — per-entry bound mirrors the copyBudget // contract for the same reason a chatty server can outgrow a validated // projection mid-write. The tar arrives as an undeclared stream (no // total size exists before the walk), so the cap is derived honestly // from what the pre-checks actually validated: both axes passed against // the then-current usage, and the purge above then frees this server's // counted bytes on BOTH axes, so the honest start is the post-wipe // snapshot (sampled here with the same sizing helpers the pre-checks // use — the pre-wipe numbers would under-count the freed headroom and // false-abort legitimate imports) and the extract may commit at most the // tighter of the armed axes' remaining allowances. Armed exactly once, // when EITHER cap exists (per-server limit OR per-disk LimitGb ceiling — // the backup-copy-budget arming rule); a server with neither bound keeps // its unlimited extract (documented pre-existing posture). Under the // upload-scope lock held for the whole tar stream, no other daemon writer // can commit into THIS scope between the snapshot and the extract; the // disk-axis walk sees the whole disk, so its allowance is the honest // bound for the shared physical disk. Slack matches the copy budget's: // it absorbs snapshot skew, never a meaningful overshoot. var importExtractBudget func(extractedSoFar int64) error if importLimitBytes > 0 || importDiskCeiling > 0 { budgetCap := int64(-1) if importLimitBytes > 0 { budgetCap = importLimitBytes - a.getServerTotalUsage(serverDir) } if importDiskCeiling > 0 { // The per-disk allowance home (same sizing checkDiskCapacity // enforces). A snapshot already at/over the ceiling post-purge // (another server on this disk grew between the pre-check and // here) refuses before any extract byte, like the stream-upload // route's fold does. if capAllowed, _, _, capLimited, capErr := a.diskCapacityAllowanceForPath(serverDir); capErr != nil { a.invalidateServerDiskCache(name) jsonWrite(w, 507, capErr) return } else if capLimited && (budgetCap < 0 || capAllowed < budgetCap) { budgetCap = capAllowed } } if budgetCap < 0 { budgetCap = 0 } budgetCap += backupCopyBudgetSlack importExtractBudget = func(extractedSoFar int64) error { if extractedSoFar > budgetCap { return errImportExtractBudgetExceeded } return nil } } // Extract the incoming meta into a quarantine dir so the source's __diskId is // never written into our metaDir as-is. We normalize and persist it below. tmpMetaDir, mkErr := os.MkdirTemp("", "adpanel-import-meta-") if mkErr != nil { a.invalidateServerDiskCache(name) jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed", "detail": "temp meta dir"}) return } defer os.RemoveAll(tmpMetaDir) _ = ensureDir(a.metaDir()) tr := tar.NewReader(r.Body) if err := extractTarSafeRouted(tr, serverDir, backupsDir, importExtractBudget, tmpMetaDir); err != nil { if errors.Is(err, errImportExtractBudgetExceeded) { // adpanel:import-extract-budget — the extract blew past the // validated allowance + slack. Mirror the backup copy's budget // abort (adpanel:backup-copy-budget): the partial extract is // removed — the import already wiped the previous state // (documented import semantics), so a clean empty scope is the // honest failure state, never a half-written server — and the // response is the SAME 507 disk_limit_exceeded body shape the // sibling budget paths use (shared diskLimitExceededBody helper, // so the settled panel pass-through surfaces it as quota), with // the message naming the cause. usedBytes is re-walked AFTER the // cleanup so it reports the post-cleanup usage, exactly what // checkDiskLimit reports for the surviving tree; limitBytes stays // keyed to the per-server axis (0 when only the disk ceiling // armed the budget — the settled whitelist keys on the error // code, as documented for the backup copy's abort). _ = os.RemoveAll(serverDir) _ = os.RemoveAll(backupsDir) usedBytes := a.getServerTotalUsage(serverDir) jsonWrite(w, 507, diskLimitExceededBody(usedBytes, importLimitBytes, fmt.Sprintf("Import extract aborted: the archive would exceed the server's disk allowance. Used: %.1f MB / %.1f MB (limit %.1f MB).", float64(usedBytes)/(1024*1024), float64(importLimitBytes)/(1024*1024), float64(importLimitBytes)/(1024*1024)))) return } a.invalidateServerDiskCache(name) jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed", "detail": err.Error()}) return } // Normalize and persist the destination-correct meta. meta := map[string]any{} importedMetaPath := filepath.Join(tmpMetaDir, sanitizeName(name)+".json") if b, err := os.ReadFile(importedMetaPath); err == nil { var m map[string]any if json.Unmarshal(b, &m) == nil && m != nil { meta = m } } stampTransferImportMetadata(meta, targetDisk, transferID) if err := a.saveMeta(serverDir, meta); err != nil { a.invalidateServerDiskCache(name) jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed", "detail": "persist meta: " + err.Error()}) return } // Reload routing from the authoritative, just-written meta. a.invalidateServerDiskCache(name) a.setServerDiskMapping(name, targetDisk.ID) result := map[string]any{"ok": true, "diskId": targetDisk.ID} if transferID != "" { result["transferId"] = transferID } jsonWrite(w, 200, result) } func (a *Agent) downloadAndExtractArchive(name, serverDir, archiveUrl string) { a.importSem <- struct{}{} defer func() { <-a.importSem }() defer func() { if r := recover(); r != nil { fmt.Fprintf(os.Stderr, "[import-archive] panic recovered for %s: %v\n", name, r) a.importProgressMu.Lock() a.importProgress[name] = &ImportProgress{ Status: "error", Error: "internal error", } a.importProgressMu.Unlock() } time.AfterFunc(5*time.Minute, func() { a.importProgressMu.Lock() delete(a.importProgress, name) a.importProgressMu.Unlock() }) }() updateProgress := func(status string, percent int, downloaded, total int64, errMsg string) { a.importProgressMu.Lock() a.importProgress[name] = &ImportProgress{ Status: status, Percent: percent, Downloaded: downloaded, Total: total, Error: errMsg, } a.importProgressMu.Unlock() } if _, err := a.dl.safeURL(archiveUrl); err != nil { updateProgress("error", 0, 0, 0, fmt.Sprintf("invalid URL: blocked by security policy")) if a.debug { fmt.Printf("[import-archive] SSRF blocked for %s: %v\n", name, err) } return } if a.debug { fmt.Printf("[import-archive] Starting download for server %s from %s\n", name, archiveUrl) } dlCtx, dlCancel := context.WithTimeout(context.Background(), 30*time.Minute) defer dlCancel() req, err := http.NewRequestWithContext(dlCtx, "GET", archiveUrl, nil) if err != nil { if a.debug { fmt.Printf("[import-archive] Request creation error for %s: %v\n", name, err) } updateProgress("error", 0, 0, 0, "download failed") return } resp, err := a.dl.client().Do(req) if err != nil { if a.debug { fmt.Printf("[import-archive] Download error for %s: %v\n", name, err) } updateProgress("error", 0, 0, 0, "download failed") return } defer resp.Body.Close() if resp.StatusCode != 200 { if a.debug { fmt.Printf("[import-archive] HTTP error for %s: %d\n", name, resp.StatusCode) } updateProgress("error", 0, 0, 0, fmt.Sprintf("HTTP error: %d", resp.StatusCode)) return } totalSize := resp.ContentLength if totalSize <= 0 { totalSize = 0 } tmpFile, err := os.CreateTemp("", "import-archive-*") if err != nil { updateProgress("error", 0, 0, 0, "failed to create temp file") return } tmpPath := tmpFile.Name() defer os.Remove(tmpPath) // adpanel:upload-scope-lock — the headroom snapshot below is a usage walk, // so like every quota-accounted write it must run under the destination // scope's upload lock: without it, two imports to one server (or an import // racing an upload, editor save or version apply) each validate against // the same pre-import snapshot and jointly overshoot the disk limit, and // the extraction commits can interleave. The remote fetch above stays // OUTSIDE the lock (it only fills the daemon temp file); the snapshot -> // download-loop enforcement -> extraction window is one hold, and every // path below returns from this goroutine, so a single defer releases the // lock on the error and completion paths alike — it also unwinds before // the panic-recover defer registered at the top of the function (deferred // calls run LIFO), so a panic cannot leak the hold (see the // lockUploadScope contract comment). unlock, lockErr := a.acquireFileMutationScope(context.Background(), a.fsScopeRootFor(name, serverDir)) if lockErr != nil { updateProgress("error", 0, 0, 0, "server files cannot be modified right now") return } defer unlock() // adpanel:multidisk - enforce the per-server storage quota during import so a // download (and subsequent extraction) can never push the server over its // limit, regardless of which disk the server lives on. headroom is computed // from the server's OWNING disk via serverDir (already disk-routed). limitBytes := a.getServerDiskLimitBytes(serverDir) var headroom int64 = -1 // -1 => unlimited if limitBytes > 0 { // adpanel:backup-storage - existing backups occupy quota, so subtract the // combined (files + backups) usage when computing import headroom. used := a.getServerTotalUsage(serverDir) headroom = limitBytes - used if headroom < 0 { headroom = 0 } } var downloaded int64 = 0 buf := make([]byte, 32*1024) for { n, readErr := resp.Body.Read(buf) if n > 0 { downloaded += int64(n) // Reject as soon as the import would exceed the server's quota. The // archive's on-disk size is a lower bound on what extraction will add, // so this is a safe, exploit-proof ceiling. if headroom >= 0 && downloaded > headroom { tmpFile.Close() limitMb := float64(limitBytes) / (1024 * 1024) updateProgress("error", 0, downloaded, totalSize, fmt.Sprintf("disk limit exceeded: import would exceed the server's %.0f MB storage limit", limitMb)) return } _, writeErr := tmpFile.Write(buf[:n]) if writeErr != nil { tmpFile.Close() updateProgress("error", 0, downloaded, totalSize, "failed to write temp file") return } var percent int if totalSize > 0 { percent = int((downloaded * 100) / totalSize) } else { percent = 0 } updateProgress("downloading", percent, downloaded, totalSize, "") } if readErr == io.EOF { break } if readErr != nil { tmpFile.Close() updateProgress("error", 0, downloaded, totalSize, fmt.Sprintf("download error: %v", readErr)) return } } tmpFile.Close() fmt.Printf("[import-archive] Download complete for %s: %d bytes\n", name, downloaded) updateProgress("extracting", 100, downloaded, totalSize, "") pathname := strings.ToLower(archiveUrl) var extractErr error importBudget := a.extractBudgetForDir(serverDir) if strings.HasSuffix(pathname, ".zip") { extractErr = extractZipSafe(tmpPath, serverDir, importBudget) } else if strings.HasSuffix(pathname, ".tar.gz") || strings.HasSuffix(pathname, ".tgz") { extractErr = a.extractTarGzSafe(tmpPath, serverDir, importBudget) } else if strings.HasSuffix(pathname, ".tar.bz2") || strings.HasSuffix(pathname, ".tbz2") { extractErr = a.extractTarBz2Safe(tmpPath, serverDir, importBudget) } else if strings.HasSuffix(pathname, ".tar.xz") || strings.HasSuffix(pathname, ".txz") { extractErr = a.extractTarXzSafe(tmpPath, serverDir, importBudget) } else if strings.HasSuffix(pathname, ".7z") { // adpanel:fs-toctou - the external-tool branches move entries through // a scope root pinned once here; serverDir is the scope root itself. scope, serr := safeOpenRoot(serverDir) if serr != nil { extractErr = serr } else { _, extractErr = a.extract7z(tmpPath, serverDir, importBudget, scope, true) scope.Close() } } else if strings.HasSuffix(pathname, ".rar") { scope, serr := safeOpenRoot(serverDir) if serr != nil { extractErr = serr } else { _, extractErr = a.extractRar(tmpPath, serverDir, importBudget, scope, true) scope.Close() } } else { extractErr = fmt.Errorf("unsupported archive format") } if extractErr != nil { if a.debug { fmt.Printf("[import-archive] Extract error for %s: %v\n", name, extractErr) } updateProgress("error", 100, downloaded, totalSize, fmt.Sprintf("extraction failed: %v", extractErr)) return } _ = sanitizeExtractedTree(serverDir) if a.debug { fmt.Printf("[import-archive] Extraction complete for %s\n", name) } updateProgress("complete", 100, downloaded, totalSize, "") } func (a *Agent) extractTarGzSafe(archivePath, destDir string, maxTotal int64) error { f, err := os.Open(archivePath) if err != nil { return err } defer f.Close() gzr, err := gzip.NewReader(f) if err != nil { return err } defer gzr.Close() tr := tar.NewReader(gzr) // Daemon-internal import flow: conventional overwrite semantics (see // extractZipSafe for the no-clobber note). _, err = extractTarSafe(tr, destDir, maxTotal, true) return err } func (a *Agent) extractTarBz2Safe(archivePath, destDir string, maxTotal int64) error { f, err := os.Open(archivePath) if err != nil { return err } defer f.Close() bzr := bzip2.NewReader(f) tr := tar.NewReader(bzr) // Daemon-internal import flow: conventional overwrite semantics (see // extractZipSafe for the no-clobber note). _, err = extractTarSafe(tr, destDir, maxTotal, true) return err } // extractTarXzSafe is the by-name entry point for callers without a pinned // archive scope root (daemon-created import/sync temp files). The open is // FIFO-hardened like safeOpenRegularAt: O_NONBLOCK so a planted FIFO cannot // wedge open(2), an fstat gate rejecting non-regular targets, and O_NONBLOCK // cleared again so regular-file reads keep blocking semantics. The // handleFSExtract tarxz branch opens the archive through safeOpenRegularAt // and calls extractTarXzSafeAt directly. func (a *Agent) extractTarXzSafe(archivePath, destDir string, maxTotal int64) error { f, err := os.OpenFile(archivePath, os.O_RDONLY|syscall.O_NONBLOCK, 0) if err != nil { return err } defer f.Close() st, err := f.Stat() if err != nil { return err } if !st.Mode().IsRegular() { return fmt.Errorf("%w: %s", errSafeNotRegular, archivePath) } if err := syscall.SetNonblock(int(f.Fd()), false); err != nil { return err } // Daemon-internal import flow: conventional overwrite semantics (see // extractZipSafe for the no-clobber note). destRoot, err := openExtractRoot(destDir, maxTotal) if err != nil { return err } defer destRoot.Close() _, err = extractTarXzSafeAt(f, destRoot, maxTotal, true) return err } // extractTarXzSafeAt runs the xz tar extraction from an already-opened, // regular-file archive fd. It returns the number of entries skipped by // no-clobber mode (see extractTarSafe for the overwrite contract). func extractTarXzSafeAt(f *os.File, destRoot *safeRoot, maxTotal int64, overwrite bool) (int, error) { xzr, err := xz.NewReader(f) if err != nil { return 0, err } tr := tar.NewReader(xzr) return extractTarSafeAt(tr, destRoot, maxTotal, overwrite, false) } func (a *Agent) extract7z(archivePath, destDir string, maxTotal int64, scope *safeRoot, overwrite bool) (int, error) { return a.extractWithExternalTool("7z", archivePath, destDir, maxTotal, overwrite, scope) } func (a *Agent) extractRar(archivePath, destDir string, maxTotal int64, scope *safeRoot, overwrite bool) (int, error) { return a.extractWithExternalTool("unrar", archivePath, destDir, maxTotal, overwrite, scope) } // extractWithExternalTool runs 7z/unrar into a scratch directory placed inside // destDir's own filesystem. The previous /tmp scratch sat on a different // device (os.Rename would fail with EXDEV) and outside every containment and // quota boundary; entries are only moved into place after a full pre-scan // against the size/count budget. // // The external tool writes without going through limitedWriter, so the budget // is enforced around it: a pre-flight listing rejects archives whose // uncompressed payload already exceeds maxTotal before anything is written // (preflightExternalExtraction), a runtime watchdog polls the scratch dir // while the child runs and kills it the moment growth passes maxTotal, and // the post-extraction scan in validateAndMoveExtracted still audits whatever // landed. It returns the number of entries skipped by no-clobber mode (see // validateAndMoveExtracted): the tool itself always overwrites, but it only // writes into the fresh scratch dir - the destination is touched solely by // the move phase, where the overwrite flag is enforced. func (a *Agent) extractWithExternalTool(bin, archivePath, destDir string, maxTotal int64, overwrite bool, scope *safeRoot) (int, error) { if maxTotal <= 0 { return 0, fmt.Errorf("no extract budget") } // The external tools open the archive by name, so reject non-regular // files up front: a planted FIFO would otherwise hang the request inside // the tool's own listing (`7z l`) instead of failing here. (A full // path-free conversion of the external tools is out of scope.) if info, lerr := os.Lstat(archivePath); lerr != nil { return 0, fmt.Errorf("%s extraction failed: %v", bin, lerr) } else if !info.Mode().IsRegular() { return 0, fmt.Errorf("%s extraction failed: not a regular file: %s", bin, archivePath) } // adpanel:fs-toctou - the destination chain and the scratch dir are // created through the scope root the caller pinned (fsScopeRootFor / the // server dir), and the post-extraction moves resolve through the same // pinned root, so no by-name walk between check and rename can land an // entry outside the server scope. destDirRel, relErr := filepath.Rel(scope.path, destDir) if relErr != nil { return 0, fmt.Errorf("symlink escape blocked during extract") } if _, verr := safeRelUnderRoot(destDirRel); verr != nil { return 0, fmt.Errorf("symlink escape blocked during extract") } if err := ensureDirUnderRoot(scope, destDirRel, 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { return 0, fmt.Errorf("symlink escape blocked during extract") } return 0, err } if err := preflightExternalExtraction(bin, archivePath, maxTotal); err != nil { return 0, err } tmpDir, err := createExtractScratchDirAt(scope, destDirRel, ".adpanel-extract-*") if err != nil { return 0, err } defer os.RemoveAll(tmpDir) var args []string switch bin { case "7z": args = []string{"x", "-y", "-o" + tmpDir, archivePath} case "unrar": args = []string{"x", "-y", archivePath, tmpDir + "/"} default: return 0, fmt.Errorf("unknown extractor %q", bin) } ctx, cancel := context.WithCancel(context.Background()) defer cancel() cmd := exec.CommandContext(ctx, bin, args...) var output bytes.Buffer cmd.Stdout = &output cmd.Stderr = &output // Run the tool in its own process group and kill the whole group on // cancellation: a bare Process.Kill can leave forked helpers behind, and // any of them holding the output pipe open would keep Wait() blocked (and // the scratch dir occupied) long after the tool itself died. WaitDelay is // a further backstop bounding Wait on stuck pipes. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Cancel = func() error { err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) if err == syscall.ESRCH { return os.ErrProcessDone } return err } cmd.WaitDelay = 5 * time.Second if err := cmd.Start(); err != nil { return 0, fmt.Errorf("%s extraction failed: %v - %s", bin, err, output.String()) } // Watchdog: probe the scratch dir every extractWatchdogInterval and kill // the tool as soon as it outgrows the budget, mirroring the limitedWriter // cap on the in-process zip/tar paths. watchCh is buffered so the poller // never blocks on its verdict, and it sends exactly once on every exit // path, so the receive below cannot leak the goroutine. // // The pre-flight listing is not a complete cap for rar: real-world // `unrar vt` label drift makes the parser succeed with zero/understated // sizes rather than error, so the pre-flight can silently UNDERSTATE the // true payload and this watchdog is the cap in that case. watchCh := make(chan error, 1) go func() { ticker := time.NewTicker(extractWatchdogInterval) defer ticker.Stop() for { select { case <-ctx.Done(): watchCh <- nil return case <-ticker.C: used, err := dirDiskUsage(tmpDir) if err != nil { continue // tree is being written concurrently; retry next tick } if used > maxTotal { watchCh <- fmt.Errorf("extraction size limit exceeded (%d bytes)", maxTotal) cancel() return } } } }() waitErr := cmd.Wait() cancel() if watchErr := <-watchCh; watchErr != nil { return 0, watchErr } if waitErr != nil { return 0, fmt.Errorf("%s extraction failed: %v - %s", bin, waitErr, output.String()) } return validateAndMoveExtracted(scope, tmpDir, destDir, maxTotal, overwrite) } // extractWatchdogInterval is how often the external-tool watchdog re-probes // the scratch directory while an extraction runs. const extractWatchdogInterval = 500 * time.Millisecond // externalListingStats aggregates a pre-flight archive listing: entry count, // the sum of uncompressed sizes, and the largest single entry. type externalListingStats struct { totalSize int64 fileCount int maxFileSize int64 maxFileName string } // preflightListingTimeout bounds each pre-flight listing command: a crafted // pathological archive can otherwise stall the listing (and the request) // indefinitely, since the extraction watchdog only covers the extraction // phase. A var so tests can tighten it. var preflightListingTimeout = 60 * time.Second // preflightMaxListingBytes caps how much listing output the pre-flight // buffers per request - `7z l -slt` on a pathological archive can otherwise // OOM the daemon. The per-request cap matches the zip central-directory // preflight (maxZipCentralDirBytes = 64 << 20); a listing for any archive // within maxExtractFiles fits well below it (each listing entry is a few // hundred bytes). A var so tests can tighten it. var preflightMaxListingBytes int64 = 64 << 20 // errPreflightListingTooLarge is returned by preflightListWriter once the cap // is hit, failing the command's stdout copy (and with it cmd.Run). var errPreflightListingTooLarge = errors.New("preflight listing output exceeds cap") // preflightListWriter buffers listing output up to the cap, then fails the // write instead of buffering an unbounded listing. type preflightListWriter struct { buf bytes.Buffer limit int64 capped bool } func (w *preflightListWriter) Write(p []byte) (int, error) { if int64(w.buf.Len())+int64(len(p)) > w.limit { w.capped = true return 0, errPreflightListingTooLarge } return w.buf.Write(p) } func (w *preflightListWriter) String() string { return w.buf.String() } // preflightExternalExtraction consults the tool's own listing so an archive // whose uncompressed payload already exceeds the budget is rejected before a // single byte is written. The listing runs under a hard timeout with a capped // output buffer, so a pathological archive can neither stall the listing // indefinitely nor OOM the daemon while buffering it. 7z -slt output is // stable, so a listing that cannot be produced or parsed fails closed there; // unrar vt output has drifted across unrar majors, so listing trouble (a // non-zero exit, a timeout, an over-cap listing, an unparseable listing) only // skips the pre-flight for rar and leaves the runtime watchdog plus the // post-extraction scan as the cap. func preflightExternalExtraction(bin, archivePath string, maxTotal int64) error { switch bin { case "7z": ctx, cancel := context.WithTimeout(context.Background(), preflightListingTimeout) defer cancel() var out preflightListWriter out.limit = preflightMaxListingBytes cmd := exec.CommandContext(ctx, "7z", "l", "-slt", archivePath) cmd.Stdout = &out cmd.Stderr = &out cmd.WaitDelay = 5 * time.Second if err := cmd.Run(); err != nil { excerpt := out.String() if len(excerpt) > 8192 { excerpt = excerpt[:8192] + "...(truncated)" } return fmt.Errorf("7z pre-flight listing failed: %v - %s", err, excerpt) } stats, err := parse7zSltSizes(out.String()) if err != nil { return fmt.Errorf("7z pre-flight listing failed: %v", err) } return checkExternalListingBudget(stats, maxTotal) case "unrar": ctx, cancel := context.WithTimeout(context.Background(), preflightListingTimeout) defer cancel() var out preflightListWriter out.limit = preflightMaxListingBytes cmd := exec.CommandContext(ctx, "unrar", "vt", archivePath) cmd.Stdout = &out cmd.Stderr = &out cmd.WaitDelay = 5 * time.Second if err := cmd.Run(); err != nil { return nil } stats, err := parseUnrarVtSizes(out.String()) if err != nil { return nil } return checkExternalListingBudget(stats, maxTotal) } return nil } // checkExternalListingBudget applies the extract budget to pre-flight stats // with the same checks and messages as the post-extraction scan in // validateAndMoveExtracted. func checkExternalListingBudget(stats externalListingStats, maxTotal int64) error { if stats.fileCount > maxExtractFiles { return fmt.Errorf("too many files in archive: %d (max %d)", stats.fileCount, maxExtractFiles) } if stats.maxFileSize > maxSingleFile { return fmt.Errorf("file too large: %s (%d bytes, max %d)", stats.maxFileName, stats.maxFileSize, maxSingleFile) } if stats.totalSize > maxTotal { return fmt.Errorf("extraction size limit exceeded (%d bytes)", maxTotal) } return nil } // parse7zSltSizes parses `7z l -slt` output. The archive-header block only // emits "Physical Size = " / "Headers Size = " lines, which the exact // "Size =" prefix ignores. func parse7zSltSizes(output string) (externalListingStats, error) { return parseExternalListing(output, "Path = ", "Size =") } // parseUnrarVtSizes parses `unrar vt` output. Labels are right-aligned to a // shared width, so lines are trimmed first; "Packed size:" deliberately does // not match the "Size:" prefix. func parseUnrarVtSizes(output string) (externalListingStats, error) { return parseExternalListing(output, "Name:", "Size:") } // parseExternalListing sums per-entry uncompressed sizes out of an extractor's // listing output: namePrefix marks an entry line, sizePrefix its size line. // Only entries that actually carry a size line are counted, so the 7z listing's // own header block (whose "Path = " line has no "Size =" line) no // longer inflates the entry count - an archive with exactly maxExtractFiles // entries passes the pre-flight exactly like the in-process zip path. Every // real 7z -slt / unrar vt entry block carries a size line, so this never // counts fewer than the true entries. func parseExternalListing(output, namePrefix, sizePrefix string) (externalListingStats, error) { var stats externalListingStats var currentName string pendingName := false for _, line := range strings.Split(output, "\n") { line = strings.TrimSpace(line) if strings.HasPrefix(line, namePrefix) { currentName = strings.TrimSpace(strings.TrimPrefix(line, namePrefix)) pendingName = true continue } if !strings.HasPrefix(line, sizePrefix) { continue } size, err := parseListingSize(strings.TrimPrefix(line, sizePrefix)) if err != nil { return externalListingStats{}, err } if pendingName { stats.fileCount++ pendingName = false } stats.totalSize += size if size > stats.maxFileSize { stats.maxFileSize = size stats.maxFileName = currentName } } return stats, nil } // parseListingSize parses one listing size value. Directory entries can carry // an empty size; anything else must be a plain non-negative decimal. func parseListingSize(value string) (int64, error) { value = strings.TrimSpace(value) if value == "" { return 0, nil } size, err := strconv.ParseInt(value, 10, 64) if err != nil || size < 0 { return 0, fmt.Errorf("cannot parse listing size %q", value) } return size, nil } // dirDiskUsage sums the byte size of everything currently under dir, counting // the same entries as the post-extraction scan in validateAndMoveExtracted: // directories and symlinks add nothing. func dirDiskUsage(dir string) (int64, error) { var total int64 err := filepath.Walk(dir, func(_ string, info os.FileInfo, err error) error { if err != nil { return err } if info.Mode()&os.ModeSymlink != 0 || info.IsDir() { return nil } total += info.Size() return nil }) return total, err } // validateAndMoveExtracted moves the scratch-dir payload of an external-tool // extraction into destDir after the full pre-scan budget check. scope is the // server scope root pinned once by the caller (fsScopeRootFor discipline; // destDir and tmpDir are both beneath it - tmpDir is the scratch dir created // inside destDir). It returns the number of entries skipped by no-clobber // mode: with overwrite=false a file entry whose destination already exists is // left byte-identical (see the move below), mirroring the O_EXCL skip of the // in-process zip/tar extractors. This serves the files_create-only extract // path; only callers holding files_write (or system flows) pass true. func validateAndMoveExtracted(scope *safeRoot, tmpDir, destDir string, maxTotal int64, overwrite bool) (int, error) { if maxTotal <= 0 { return 0, fmt.Errorf("no extract budget") } // Pre-scan before moving anything so an oversized or bomb-style payload is // rejected wholesale instead of half-copied into the destination. Symlinks // (checked via Lstat in Walk) never leave tmpDir; the deferred RemoveAll in // the caller disposes of them. var totalCount int var totalSize int64 scanErr := filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.Mode()&os.ModeSymlink != 0 { return nil } if info.IsDir() { return nil } // adpanel:extract-hardlinks - the external-tool branch must impose the // same rule the tar extractors enforce (`hardlinks not allowed for // security`): a fresh scratch dir can only contain an Nlink>1 regular // file if the extractor created a link, and the move would otherwise // relocate a shared inode - potentially one pointing outside the server // scope - into the server's tree. Checked in this pre-scan so the error // rejects the extraction wholesale, before anything is moved. // Directories are skipped above because they always carry Nlink > 1 on // Linux. Walk Lstats, so a hardlink is otherwise indistinguishable from // a regular file here. if st, ok := info.Sys().(*syscall.Stat_t); ok && st.Nlink > 1 { return fmt.Errorf("hardlinks not allowed for security: %s", path) } totalCount++ if totalCount > maxExtractFiles { return fmt.Errorf("too many files extracted: %d (max %d)", totalCount, maxExtractFiles) } if info.Size() > maxSingleFile { return fmt.Errorf("file too large extracted: %s (%d bytes, max %d)", path, info.Size(), maxSingleFile) } totalSize += info.Size() if totalSize > maxTotal { return fmt.Errorf("extraction size limit exceeded (%d bytes)", maxTotal) } return nil }) if scanErr != nil { return 0, scanErr } // adpanel:fs-toctou - both sides of every move must already live beneath // the pinned scope root; a rel escaping it means the scratch or the // destination is not where the caller validated it, so fail closed. destDirRel, relErr := filepath.Rel(scope.path, destDir) if relErr != nil { return 0, fmt.Errorf("symlink escape blocked during extract") } if _, verr := safeRelUnderRoot(destDirRel); verr != nil { return 0, fmt.Errorf("symlink escape blocked during extract") } tmpDirRel, relErr := filepath.Rel(scope.path, tmpDir) if relErr != nil { return 0, fmt.Errorf("symlink escape blocked during extract") } if _, verr := safeRelUnderRoot(tmpDirRel); verr != nil { return 0, fmt.Errorf("symlink escape blocked during extract") } var skipped int moveErr := filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } rel, err := filepath.Rel(tmpDir, path) if err != nil { return fmt.Errorf("cannot compute relative path: %v", err) } if rel == "." { return nil } if info.Mode()&os.ModeSymlink != 0 { return nil } dest := filepath.Join(destDir, rel) if !isUnder(destDir, dest) { return fmt.Errorf("zip-slip blocked: %s escapes destination", rel) } destRel := filepath.Join(destDirRel, rel) // adpanel:fs-toctou - directory creation and the move below resolve // through the pinned scope dirfd (ensureDirUnderRoot + renameat on // dirfds), so a tenant swapping the destination parent between the // checks and the move cannot land the file outside the server scope. // In-root symlinks keep resolving; escapes are refused here. if info.IsDir() { if err := ensureDirUnderRoot(scope, destRel, sanitizeFileMode(info.Mode(), true)); err != nil { if errors.Is(err, errSafeScopeEscape) { return fmt.Errorf("symlink escape blocked during extract: %s", rel) } return err } return nil } if err := ensureDirUnderRoot(scope, filepath.Dir(destRel), 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { return fmt.Errorf("symlink escape blocked during extract: %s", rel) } return err } tmpRel := filepath.Join(tmpDirRel, rel) srcParent, oerr := safeOpenDirAt(scope, filepath.Dir(tmpRel)) if oerr != nil { return oerr } defer srcParent.Close() dstParent, oerr := safeOpenDirAt(scope, filepath.Dir(destRel)) if oerr != nil { return oerr } defer dstParent.Close() // adpanel:extract-no-clobber - no-clobber mode swaps the plain rename // for RENAME_NOREPLACE, so an entry whose destination already exists // (regular file or symlink, mirroring the O_EXCL skip of the in-process // extractors) is skipped instead of replaced; the scratch copy is // disposed of by the caller's deferred RemoveAll. The existing // destination keeps its bytes AND its mode: the chmod below only runs // on the successful-move path. if overwrite { if err := safeRenameFileAcrossDirs(srcParent, dstParent, filepath.Base(tmpRel), filepath.Base(destRel)); err != nil { return err } } else { if err := safeRenameFileAcrossDirsNoReplace(srcParent, dstParent, filepath.Base(tmpRel), filepath.Base(destRel)); err != nil { if errors.Is(err, errSafeDestExists) { skipped++ return nil } return err } } return safeChmodFileAt(dstParent, filepath.Base(destRel), sanitizeFileMode(info.Mode(), false)) }) if moveErr != nil { return 0, moveErr } return skipped, nil } func (a *Agent) downloadAndExtractArchiveSync(name, serverDir, archiveUrl string) error { if _, err := a.dl.safeURL(archiveUrl); err != nil { if a.debug { fmt.Printf("[import-archive] SSRF blocked for %s: %v\n", name, err) } return fmt.Errorf("invalid URL: blocked by security policy") } parsedUrl, _ := url.Parse(archiveUrl) pathname := strings.ToLower(parsedUrl.Path) validExt := false allowedExts := []string{".zip", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".7z", ".rar"} for _, ext := range allowedExts { if strings.HasSuffix(pathname, ext) { validExt = true break } } if !validExt { return fmt.Errorf("unsupported archive format (supported: .zip, .tar.gz, .tgz, .tar.bz2, .tbz2, .tar.xz, .txz, .7z, .rar)") } if a.debug { fmt.Printf("[import-archive] Starting download for server %s from %s\n", name, archiveUrl) } resp, err := a.dl.client().Get(archiveUrl) if err != nil { return fmt.Errorf("download failed") } defer resp.Body.Close() if resp.StatusCode != 200 { return fmt.Errorf("HTTP error: %d", resp.StatusCode) } const maxImportSize int64 = 10 << 30 if resp.ContentLength > maxImportSize { return fmt.Errorf("archive too large (max 10GB)") } tmpFile, err := os.CreateTemp("", "import-archive-*") if err != nil { return fmt.Errorf("failed to create temp file") } tmpPath := tmpFile.Name() defer os.Remove(tmpPath) limitedReader := io.LimitReader(resp.Body, maxImportSize) downloaded, err := io.Copy(tmpFile, limitedReader) tmpFile.Close() if err != nil { return fmt.Errorf("download error") } if a.debug { fmt.Printf("[import-archive] Download complete for %s: %d bytes\n", name, downloaded) } // adpanel:upload-scope-lock — the extraction budget below is a usage // snapshot (extractBudgetForDir walks current usage), so the snapshot -> // extraction -> sanitize window must run under the destination scope's // upload lock like the async import and every other quota-accounted // write: without it a create-time import can jointly overshoot the disk // limit with a concurrent upload, editor save, extract or version apply // on the same scope. The remote fetch above stays OUTSIDE the lock (it // only fills the daemon temp file); every path below returns from this // function, so a single defer releases the lock on the success and error // paths alike (see the lockUploadScope contract comment). unlock := a.lockUploadScope(a.fsScopeRootFor(name, serverDir)) defer unlock() archivePathLower := strings.ToLower(archiveUrl) var extractErr error syncImportBudget := a.extractBudgetForDir(serverDir) if strings.HasSuffix(archivePathLower, ".zip") { extractErr = extractZipSafe(tmpPath, serverDir, syncImportBudget) } else if strings.HasSuffix(archivePathLower, ".tar.gz") || strings.HasSuffix(archivePathLower, ".tgz") { extractErr = a.extractTarGzSafe(tmpPath, serverDir, syncImportBudget) } else if strings.HasSuffix(archivePathLower, ".tar.bz2") || strings.HasSuffix(archivePathLower, ".tbz2") { extractErr = a.extractTarBz2Safe(tmpPath, serverDir, syncImportBudget) } else if strings.HasSuffix(archivePathLower, ".tar.xz") || strings.HasSuffix(archivePathLower, ".txz") { extractErr = a.extractTarXzSafe(tmpPath, serverDir, syncImportBudget) } else if strings.HasSuffix(archivePathLower, ".7z") { // adpanel:fs-toctou - the external-tool branches move entries through // a scope root pinned once here; serverDir is the scope root itself. scope, serr := safeOpenRoot(serverDir) if serr != nil { extractErr = serr } else { _, extractErr = a.extract7z(tmpPath, serverDir, syncImportBudget, scope, true) scope.Close() } } else if strings.HasSuffix(archivePathLower, ".rar") { scope, serr := safeOpenRoot(serverDir) if serr != nil { extractErr = serr } else { _, extractErr = a.extractRar(tmpPath, serverDir, syncImportBudget, scope, true) scope.Close() } } else { extractErr = fmt.Errorf("unsupported archive format") } if extractErr != nil { return fmt.Errorf("extraction failed: %v", extractErr) } _ = sanitizeExtractedTree(serverDir) if a.debug { fmt.Printf("[import-archive] Extraction complete for %s\n", name) } return nil } func (a *Agent) handleImportArchiveProgress(w http.ResponseWriter, r *http.Request, name string) { a.importProgressMu.RLock() progress, exists := a.importProgress[name] a.importProgressMu.RUnlock() if !exists { jsonWrite(w, 200, map[string]any{ "status": "not_found", "percent": 0, "downloaded": 0, "total": 0, }) return } jsonWrite(w, 200, map[string]any{ "status": progress.Status, "percent": progress.Percent, "downloaded": progress.Downloaded, "total": progress.Total, "error": progress.Error, }) } func parseMemoryString(s string) float64 { s = strings.TrimSpace(s) s = strings.ToUpper(s) var multiplier float64 = 1 var numStr string if strings.HasSuffix(s, "GIB") { multiplier = 1024 numStr = strings.TrimSuffix(s, "GIB") } else if strings.HasSuffix(s, "GB") { multiplier = 1024 numStr = strings.TrimSuffix(s, "GB") } else if strings.HasSuffix(s, "MIB") { multiplier = 1 numStr = strings.TrimSuffix(s, "MIB") } else if strings.HasSuffix(s, "MB") { multiplier = 1 numStr = strings.TrimSuffix(s, "MB") } else if strings.HasSuffix(s, "KIB") { multiplier = 1.0 / 1024 numStr = strings.TrimSuffix(s, "KIB") } else if strings.HasSuffix(s, "KB") { multiplier = 1.0 / 1024 numStr = strings.TrimSuffix(s, "KB") } else { numStr = s } val, err := strconv.ParseFloat(strings.TrimSpace(numStr), 64) if err != nil { return 0 } return val * multiplier } type applyReq struct { URL string `json:"url"` NodeID string `json:"nodeId"` DestPath string `json:"destPath"` ProviderID string `json:"providerId"` VersionID string `json:"versionId"` } func (a *Agent) handleApplyVersion(w http.ResponseWriter, r *http.Request, name string) { var req applyReq if err := readJSON(w, r, 1<<20, &req); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad-json", "detail": err.Error()}) return } if name == "" || strings.TrimSpace(req.URL) == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing-fields"}) return } // The quota pre-check runs only after the cheap gates AND the signature: // checkDiskLimit walks the whole server tree (spawning du), and this // endpoint is routed before bearer-token auth — an unauthenticated prober // must not be able to buy a directory walk per request with a bare POST. if !strings.HasPrefix(strings.ToLower(req.URL), "http://") && !strings.HasPrefix(strings.ToLower(req.URL), "https://") { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid-url"}) return } if req.NodeID != "" && a.uuid != "" && req.NodeID != a.uuid { jsonWrite(w, 401, map[string]any{"ok": false, "error": "unauthorized"}) return } ok, why := a.verifyPanelSignature(r, name, req.ProviderID, req.VersionID, req.URL, nil) if !ok { jsonWrite(w, 403, map[string]any{"ok": false, "error": why}) return } destRel := strings.TrimSpace(req.DestPath) if destRel == "" { destRel = "server.jar" } if destRel == "server.jar" { // adpanel:reinstall-apply-order - lock before stopping Docker, not just before writing the jar. opMu := a.tryLockServerOp(name) if opMu == nil { a.writeServerOpConflictResponse(w, name) return } defer opMu.Unlock() } serverDir := a.serverDir(name) if diskErr := a.checkDiskLimit(serverDir, 0); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } baseDir := serverDir st, err := os.Stat(baseDir) if err != nil || !st.IsDir() { jsonWrite(w, 404, map[string]any{"ok": false, "error": "server-dir-not-found"}) return } target, pathOk := safeJoin(baseDir, destRel) if !pathOk { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid-destPath"}) return } // adpanel:fs-scope - resolve the target's parent against the server dir // (not the disk root) so a symlink planted inside the server dir cannot // point at a sibling server. Re-checked after ensureDir to validate the // newly created directories and narrow the race window. if rp, err := filepath.EvalSymlinks(filepath.Dir(target)); err == nil && !isUnder(baseDir, rp) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } // adpanel:fs-toctou - missing parents are created through the pinned // server dirfd (see ensureDirUnderRoot); unlike MkdirAll this cannot // follow a planted intermediate symlink outside the server scope when the // target does not exist yet. The EvalSymlinks checks remain as friendly // pre/post error reporting. baseRoot, rootErr := safeOpenRoot(baseDir) if rootErr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to create destination"}) return } defer baseRoot.Close() targetDirRel, targetRelErr := filepath.Rel(baseRoot.path, filepath.Dir(target)) if targetRelErr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to create destination"}) return } if err := ensureDirUnderRoot(baseRoot, targetDirRel, 0o755); err != nil && errors.Is(err, errSafeScopeEscape) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } if rp, err := filepath.EvalSymlinks(filepath.Dir(target)); err == nil && !isUnder(baseDir, rp) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } // adpanel:fs-scope - same rule as the upload handler: never follow a // symlinked final component when replacing the file. if li, lerr := os.Lstat(target); lerr == nil && li.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot overwrite symlink"}) return } if destRel == "server.jar" { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) a.docker.stop(ctx, name) cancel() ctxD, cancelD := context.WithTimeout(context.Background(), 30*time.Minute) // adpanel:upload-scope-lock — the guarded downloader samples its // enforcing usage snapshot (usedBefore) when it is constructed in the // call below, so that snapshot -> transfer -> temp-file rename commit // window must run under the destination scope's upload lock like every // other quota-accounted write: without it an apply racing an upload, // editor save, extract or a second apply on the same server validates // against the same pre-write snapshot and the writers jointly overshoot // the disk limit. The checkDiskLimit pre-check above stays outside the // lock deliberately — it is only the early 407; the enforcing snapshot // lives inside quotaGuardedDownloader under this hold. The hold extends // across the container restart that follows via defer: the restart // writes no quota-accounted bytes, but no upload should interleave with // the server.jar swap (see the lockUploadScope contract comment). unlock := a.lockUploadScope(a.fsScopeRootFor(name, baseDir)) defer unlock() // adpanel:apply-quota - the pre-check above runs with extraBytes=0, so // without a mid-copy guard the download could write up to the // downloader's maxBytes ceiling past the server's quota. The guarded // copy aborts instead, and the failure maps to the same 507 body the // quota pre-check emits. if err := a.quotaGuardedDownloader(baseDir).downloadToFile(ctxD, req.URL, target); err != nil { cancelD() if errors.Is(err, errDownloadQuotaExceeded) { if diskErr := a.checkDiskLimit(serverDir, 0); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } jsonWrite(w, 507, map[string]any{"ok": false, "error": "disk_limit_exceeded"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "download failed", "detail": err.Error()}) return } cancelD() hostPort := 25565 meta := a.loadMeta(baseDir) if v, ok := meta["hostPort"]; ok { switch vv := v.(type) { case float64: hostPort = int(vv) case int: hostPort = vv } } enforceServerProps(baseDir) ctx2, cancel2 := context.WithTimeout(context.Background(), 15*time.Second) a.docker.rmForce(ctx2, name) cancel2() resources := resourceLimitsFromMeta(meta) ctx3, cancel3 := context.WithTimeout(context.Background(), 60*time.Second) if err := a.startMinecraftContainer(ctx3, name, baseDir, hostPort, resources, nil, false); err != nil { cancel3() if errors.Is(err, errMinecraftEulaRequired) { jsonWrite(w, 409, map[string]any{ "ok": false, "error": "minecraft_eula_required", "code": "minecraft_eula_required", "detail": "The Minecraft EULA (eula.txt) must be accepted before this server can start.", }) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "restart failed", "detail": err.Error()}) return } cancel3() jsonWrite(w, 200, map[string]any{ "ok": true, "msg": "applied", "server": name, "hostPort": hostPort, "path": target, }) return } ctxD, cancelD := context.WithTimeout(context.Background(), 30*time.Minute) // Same quota-guarded copy as the server.jar branch above: plugins/mods // installs count against the server's quota too. // adpanel:upload-scope-lock — the enforcing usage snapshot inside // quotaGuardedDownloader is taken under the destination scope's upload // lock, held across the transfer and the rename commit, so this download // cannot jointly overshoot the limit with a concurrent upload, editor // save, extract or second apply on the same scope (see the // lockUploadScope contract comment; the handler ends right after the // response below, so the defer releases the lock on every path). unlock := a.lockUploadScope(a.fsScopeRootFor(name, baseDir)) defer unlock() if err := a.quotaGuardedDownloader(baseDir).downloadToFile(ctxD, req.URL, target); err != nil { cancelD() if errors.Is(err, errDownloadQuotaExceeded) { if diskErr := a.checkDiskLimit(serverDir, 0); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } jsonWrite(w, 507, map[string]any{"ok": false, "error": "disk_limit_exceeded"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "download failed", "detail": err.Error()}) return } cancelD() jsonWrite(w, 200, map[string]any{ "ok": true, "msg": "downloaded", "server": name, "path": target, "destPath": destRel, }) } // runtimeSeedCallerWaitBudget bounds the /runtime seed handler's response // window. Its slowest leg is the image pull's 2-minute context; the legacy- // migration wipe is unbounded on pathological storage (the accepted exposure // class reinstall's 60-minute budget documents), so the budget is generous // against both. The panel's relays wait 60s (version-apply) and 120s // (seedRuntimeOnNode, which best-effort-ignores the response), so a generous // daemon-side budget keeps the handler able to answer past the server-wide // 120s WriteTimeout. const runtimeSeedCallerWaitBudget = 15 * time.Minute // runtimeSeedNeedsPull reports whether the seed's image pre-warm pull must // run: only when the effective image:tag differs from what the server's // persisted meta already carries. The panel re-seeds on EVERY start of a // nodejs/python/discord-bot server (seedRuntimeOnNode), and pulling each time // made the routine seed regularly outlive the panel's 120s relay - surfacing // as a transient runtime_seed_in_progress 409 on the immediately following // start - for a pull the start path would redo anyway. First seed and // version changes (new tag) still pull. func runtimeSeedNeedsPull(existingMeta map[string]any, img, tag string) bool { if existingMeta == nil { return true } rt, ok := existingMeta["runtime"].(map[string]any) if !ok || rt == nil { return true } curImg := strings.TrimSpace(fmt.Sprint(rt["image"])) curTag := strings.TrimSpace(fmt.Sprint(rt["tag"])) if curImg == "" || curImg == "" || curTag == "" || curTag == "" { return true } return curImg != img || curTag != tag } type runtimeReq struct { Runtime map[string]any `json:"runtime"` Template string `json:"template"` Start string `json:"start"` Port any `json:"port"` NodeID string `json:"nodeId"` } func (a *Agent) handleRuntime(w http.ResponseWriter, r *http.Request, name string) { var req runtimeReq if err := readJSON(w, r, a.uploadLimit, &req); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad-json", "detail": err.Error()}) return } if name == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing-name"}) return } if req.Runtime == nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing-runtime"}) return } if rawStartup, exists := req.Runtime["startupCommand"]; exists && strings.TrimSpace(fmt.Sprint(rawStartup)) != "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "raw docker startup commands are no longer supported"}) return } if req.NodeID != "" && a.uuid != "" && req.NodeID != a.uuid { jsonWrite(w, 401, map[string]any{"ok": false, "error": "unauthorized"}) return } // adpanel:backup-race - the runtime seed joins the per-server op-lock // discipline. For a server whose meta has no structured runtime yet (the // legacy-migration case) this handler RemoveAll's serverDir and re- // scaffolds it, then saves meta and pulls an image - exactly the // wipe/rebuild writer class that raced backup create (torn, status: // "complete" backup of the half-wiped tree) and restore (two interleaved // copyDir writers) before reinstall was fixed, and reachable on every // start of a legacy nodejs/python/discord-bot server via the panel's // seedRuntimeOnNode. Acquire non-blocking like the backup handlers and // reinstall: this handler holds for minutes (wipe + scaffold + the // 2-minute pull context), so a queued second op would only run as a // phantom action after its relay gave up. The panel treats seeding as // best-effort (seedRuntimeOnNode swallows errors), so a 409 here costs // one skipped re-seed, not a broken start. opMu := a.tryLockServerOp(name) if opMu == nil { a.writeServerOpConflictResponse(w, name) return } defer opMu.Unlock() if a.serverStopPending(name) { writePowerOpRefusal(w, serverStopInProgress) return } // Mark busy before any work: power ops 409 instead of queueing behind // the seed's minutes-long hold (see longOpBusyNames). The deferred // endLongOp runs before the Unlock defer above (LIFO), so the marker // never outlives the lock. a.beginLongOp(name, longOpRuntimeSeed) defer a.endLongOp(name) // Long op: the legacy wipe, the scaffold and the pull (2-minute context) // run before the first response byte (ignored on writers without // deadline support, e.g. httptest.ResponseRecorder). Generous against // the panel's 60-120s seeding relays, which best-effort-ignore or // surface the error text. _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(runtimeSeedCallerWaitBudget)) serverDir := a.serverDir(name) existingMeta := a.loadMeta(serverDir) if existingMeta[reinstallPendingStartupKey] == true { writeReinstallStartupPending(w) return } stripLegacyStartupCommandFields(existingMeta) hasStructuredRuntime := false if existingMeta != nil { if rt, ok := existingMeta["runtime"].(map[string]any); ok && len(rt) > 0 { hasStructuredRuntime = true } } if !hasStructuredRuntime { _ = os.RemoveAll(serverDir) } _ = ensureDir(serverDir) kind := strings.ToLower(strings.TrimSpace(req.Template)) if kind == "" { kind = strings.ToLower(fmt.Sprint(req.Runtime["providerId"])) } finalStart := strings.TrimSpace(req.Start) if finalStart == "" { if kind == "python" { finalStart = "main.py" } else if kind == "nodejs" || kind == "discord-bot" { finalStart = "index.js" } } if finalStart != "" { finalStart = filepath.Base(finalStart) if finalStart == "." || finalStart == ".." { finalStart = "" } } hostPort := 0 if req.Port != nil { parsedPort, ok := parseStrictPortValue(req.Port) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid-port"}) return } hostPort = parsedPort } cleanRuntime := make(map[string]any) for _, key := range []string{"providerId", "versionId", "image", "tag", "restart"} { if raw, ok := req.Runtime[key]; ok { clean := strings.TrimSpace(fmt.Sprint(raw)) if clean != "" && clean != "" { cleanRuntime[key] = clean } } } if rawCommand, ok := req.Runtime["command"]; ok { if clean := normalizeLegacyRuntimeProcessCommand(kind, fmt.Sprint(rawCommand), finalStart, defaultDataDirForType(kind)); clean != "" { if reason := validateRuntimeProcessCommand(clean); reason != "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": reason}) return } cleanRuntime["command"] = clean } } if rawEnv, ok := req.Runtime["env"].(map[string]any); ok && len(rawEnv) > 0 { cleanEnv := make(map[string]any) for key, value := range rawEnv { envKey := strings.TrimSpace(key) if envKey == "" { continue } envValue := strings.TrimSpace(fmt.Sprint(value)) if envValue == "" { envValue = "" } cleanEnv[envKey] = envValue } if len(cleanEnv) > 0 { cleanRuntime["env"] = cleanEnv } } if rawVolumes, ok := req.Runtime["volumes"].([]any); ok && len(rawVolumes) > 0 { cleanVolumes := make([]any, 0, len(rawVolumes)) for _, entry := range rawVolumes { spec := strings.TrimSpace(fmt.Sprint(entry)) if spec == "" || spec == "" { continue } if strings.ContainsAny(spec, "\x00\r\n") { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid-volume-spec"}) return } cleanVolumes = append(cleanVolumes, spec) } if len(cleanVolumes) > 0 { cleanRuntime["volumes"] = cleanVolumes } } if rawPorts, ok := req.Runtime["ports"].([]any); ok && len(rawPorts) > 0 { cleanPorts := make([]any, 0, len(rawPorts)) seenPorts := make(map[int]struct{}, len(rawPorts)) for _, entry := range rawPorts { port, ok := parseStrictPortValue(entry) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid-runtime-port"}) return } if _, seen := seenPorts[port]; seen { continue } seenPorts[port] = struct{}{} cleanPorts = append(cleanPorts, port) } if len(cleanPorts) > 0 { cleanRuntime["ports"] = cleanPorts } } switch kind { case "python": scaffoldPython(serverDir, finalStart) case "nodejs", "discord-bot": p := hostPort if p == 0 { p = 3001 } scaffoldNode(serverDir, filepath.Base(serverDir), finalStart, p) default: if finalStart != "" { _ = os.WriteFile(filepath.Join(serverDir, finalStart), []byte(""), 0o644) } } meta := map[string]any{ "type": func() string { if kind != "" { return kind } return "runtime" }(), "runtime": cleanRuntime, "start": func() any { if finalStart != "" { return finalStart } return nil }(), "hostPort": func() any { if hostPort > 0 { return hostPort } return nil }(), "updatedAt": time.Now().UnixMilli(), } preserveRuntimeSeedMetadata(meta, existingMeta) _ = a.saveMeta(serverDir, meta) img := strings.TrimSpace(fmt.Sprint(req.Runtime["image"])) tag := strings.TrimSpace(fmt.Sprint(req.Runtime["tag"])) if img == "" { if kind == "python" { img = "python" if tag == "" { tag = "3.12-slim" } } else { img = "node" if tag == "" { tag = "20-alpine" } } } ref := img if tag != "" { ref = img + ":" + tag } // Pre-warm only when the image actually changed (see runtimeSeedNeedsPull): // routine re-seeds of an identical runtime stay sub-second, well inside the // panel relays' budgets, instead of stretching the op-lock hold by a // pull the start path would redo anyway. if runtimeSeedNeedsPull(existingMeta, img, tag) { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) _ = a.docker.pullImageAPI(ctx, ref) cancel() } jsonWrite(w, 200, map[string]any{"ok": true, "type": meta["type"], "start": meta["start"], "hostPort": meta["hostPort"]}) } func (a *Agent) performServerStart(requestCtx context.Context, name string, customHostPort int, customEnv map[string]string) (string, error) { // adpanel:backup-race - bounded fail-fast acquisition instead of a // marker-check + blocking Lock (see acquireServerOpLockFailFast): a start // either runs while current or refuses with the sentinel handleStart maps // to the matching 409; it can never queue behind a long op's hold and // execute minutes later as a phantom action after the relay gave up. opMu, refused := a.acquireServerOpLockFailFast(requestCtx, name) if refused != "" { switch refused { case powerOpRequestEnded: return "", errPowerOpRequestEnded case "reinstall_in_progress": return "", errReinstallOpInProgress case "runtime_seed_in_progress": return "", errRuntimeSeedOpInProgress case "backup_in_progress": return "", errBackupOpInProgress } return "", errServerOpInProgress } defer opMu.Unlock() if a.serverStopPending(name) { return "", errServerStopInProgress } if err := a.checkTransferSourceWritable(name); err != nil { return "", err } // register before the killPending check so a kill landing between the two // still pops this cancel and aborts the start ctx, cancel := context.WithTimeout(context.Background(), 240*time.Second) ctx = context.WithValue(ctx, confirmDockerStartKey{}, true) a.startAbortMu.Lock() if a.startCancels == nil { a.startCancels = make(map[string]context.CancelFunc) } a.startCancels[name] = cancel a.startAbortMu.Unlock() defer func() { a.startAbortMu.Lock() delete(a.startCancels, name) a.startAbortMu.Unlock() cancel() }() a.stopMu.Lock() if _, pending := a.killPending[name]; pending { a.stopMu.Unlock() return "", fmt.Errorf("start aborted: kill requested") } a.stopMu.Unlock() serverDir := a.serverDir(name) if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { return "", errServerStartNotFound } meta := a.loadMeta(serverDir) if meta[reinstallPendingStartupKey] == true { return "", errReinstallStartupPending } // adpanel:start-permission - Start must never remove an active container; // only the separate Restart operation is allowed to replace a running one. inspectCtx, inspectCancel := context.WithTimeout(requestCtx, 5*time.Second) container, _, exists, inspectErr := a.inspectContainerForStats(inspectCtx, name) inspectCancel() if requestCtx.Err() != nil { return "", errPowerOpRequestEnded } if inspectErr != nil { return "", errServerStartStateUnknown } if exists { if container.State.Running { return "", errServerAlreadyRunning } switch container.State.Status { case "running", "paused", "restarting": return "", errServerAlreadyRunning case "created", "exited", "dead": default: return "", errServerStartStateUnknown } } if stripLegacyStartupCommandFields(meta) { _ = a.saveMeta(serverDir, meta) } if normalizeRustRuntimeForPterodactyl(meta) { _ = a.saveMeta(serverDir, meta) } typ := strings.ToLower(fmt.Sprint(meta["type"])) if a.debug { fmt.Printf("[handleStart] Server: %s, type: %s\n", name, typ) } resolveStartPort := func(defaultPort int) int { if customHostPort > 0 { return customHostPort } if storedPort, ok := parseStrictPortValue(meta["hostPort"]); ok { return storedPort } return defaultPort } resources := resourceLimitsFromMeta(meta) if typ == "minecraft" { hp := resolveStartPort(25565) if err := a.startMinecraftContainer(ctx, name, serverDir, hp, resources, customEnv, true); err != nil { a.broadcastDaemonLog(name, fmt.Sprintf("Failed to initialize container: %v", err)) return typ, err } a.broadcastDaemonLog(name, "Server instance active, attached to live console output.") a.ensureLiveLogs(name) a.broadcastContainerEvent(name, "running") return typ, nil } a.prepareServerConsoleStart(name) if meta["runtime"] != nil && (typ == "python" || typ == "nodejs" || typ == "discord-bot" || typ == "runtime") { hp := resolveStartPort(0) if hp > 0 { a.broadcastDaemonLog(name, fmt.Sprintf("Allocating network port bindings (: %d)...", hp)) } if err := a.startRuntimeContainer(ctx, name, serverDir, meta, hp, resources, customEnv); err != nil { a.broadcastDaemonLog(name, fmt.Sprintf("Failed to initialize container: %v", err)) return typ, err } a.broadcastDaemonLog(name, "Server instance active, attached to live console output.") a.ensureLiveLogs(name) a.broadcastContainerEvent(name, "running") return typ, nil } hp := resolveStartPort(8080) a.broadcastDaemonLog(name, fmt.Sprintf("Allocating network port bindings (: %d)...", hp)) if meta["runtime"] == nil { meta["runtime"] = make(map[string]any) } if err := a.startCustomDockerContainer(ctx, name, serverDir, meta, hp, resources); err != nil { a.broadcastDaemonLog(name, fmt.Sprintf("Failed to initialize container: %v", err)) return typ, err } a.broadcastDaemonLog(name, "Server instance active, attached to live console output.") a.ensureLiveLogs(name) a.broadcastContainerEvent(name, "running") return typ, nil } // handleEulaStatus reports whether the server is a Minecraft server that still // needs EULA consent, so the console can show the prompt without waiting for a // blocked start attempt. func (a *Agent) handleEulaStatus(w http.ResponseWriter, r *http.Request, name string) { if !isValidContainerName(name) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid container name"}) return } serverDir := a.serverDir(name) meta := a.loadMeta(serverDir) minecraft := isMinecraftServerMeta(meta) accepted := minecraftEulaAccepted(serverDir) jsonWrite(w, 200, map[string]any{ "ok": true, "minecraft": minecraft, "accepted": accepted, "required": minecraft && !accepted, }) } func (a *Agent) handleStop(w http.ResponseWriter, r *http.Request, name string) { if !isValidContainerName(name) { jsonWrite(w, 400, map[string]any{"error": "invalid container name"}) return } waitMode := r.URL.Query().Get("wait") == "true" // adpanel:backup-race - bounded fail-fast acquisition (see // acquireServerOpLockFailFast) instead of a marker-check + blocking Lock: // the stop either runs while current or 409s naming why; it can never // queue behind a long op's hold and execute later as a phantom action // after the panel relay (10s) gave up. opMu, refused := a.acquireServerOpLockFailFast(r.Context(), name) if refused != "" { writePowerOpRefusal(w, refused) return } if !waitMode && a.serverStopPending(name) { opMu.Unlock() jsonWrite(w, 200, map[string]any{"ok": true, "stopping": true, "note": "already stopping"}) return } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() original, _, exists, err := a.inspectContainerForStats(ctx, name) if err != nil || (exists && !validDockerContainerID(original.ID)) { opMu.Unlock() jsonWrite(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "error": "could not verify the container to stop"}) return } if !exists { opMu.Unlock() jsonWrite(w, 200, map[string]any{"ok": true, "note": "not running"}) return } requestedAt := time.Now() a.stopMu.Lock() a.stoppingNow[name] = requestedAt a.stopMu.Unlock() a.docker.updateRestartNo(ctx, original.ID) if a.stdinMgr != nil { a.stdinMgr.remove(name) } serverDir := a.serverDir(name) meta := a.loadMeta(serverDir) serverType := strings.ToLower(fmt.Sprint(meta["type"])) isMinecraft := serverType == "" || serverType == "minecraft" a.broadcastDaemonLog(name, "Sending graceful shutdown signal to server process...") if isMinecraft { _ = a.docker.sendCommand(ctx, a.stdinMgr, name, "stop", nil) } if waitMode { time.Sleep(a.stopGrace) stopErr := a.finishServerStop(name, original.ID) a.clearPendingServerStop(name) opMu.Unlock() if stopErr != nil { auditLog.Log("server_stop", getClientIP(r), "", name, "stop", "failure", nil) jsonWrite(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "error": "could not confirm server container stopped"}) return } jsonWrite(w, 200, map[string]any{"ok": true, "stopped": true}) auditLog.Log("server_stop", getClientIP(r), "", name, "stop", "success", nil) return } a.broadcastContainerEvent(name, "stopping") opMu.Unlock() go a.completeDeferredServerStop(name, original, requestedAt) jsonWrite(w, 200, map[string]any{"ok": true, "stopping": true}) auditLog.Log("server_stop", getClientIP(r), "", name, "stop", "success", nil) } func shouldRecreateContainerOnRestart(meta map[string]any) bool { if meta == nil { return false } template := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) if template == "" || template == "" { template = strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) } if template == "rust" { return true } runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj == nil { return false } image := strings.ToLower(strings.TrimSpace(fmt.Sprint(runtimeObj["image"]))) tag := strings.ToLower(strings.TrimSpace(fmt.Sprint(runtimeObj["tag"]))) imageRef := image + ":" + tag return strings.Contains(imageRef, "pterodactyl/games:rust") || strings.Contains(imageRef, "parkervcp/games:rust") || strings.Contains(imageRef, "didstopia/rust-server") } func (a *Agent) handleRestart(w http.ResponseWriter, r *http.Request, name string) { if !isValidContainerName(name) { jsonWrite(w, 400, map[string]any{"error": "invalid container name"}) return } // adpanel:backup-race - bounded fail-fast acquisition (see // acquireServerOpLockFailFast) instead of a marker-check + blocking Lock: // the restart either runs while current or 409s naming why; it can never // queue behind a long op's hold and execute later as a phantom action // after the panel relay (10s) gave up. opMu, refused := a.acquireServerOpLockFailFast(r.Context(), name) if refused != "" { writePowerOpRefusal(w, refused) return } defer opMu.Unlock() if a.serverStopPending(name) { writePowerOpRefusal(w, serverStopInProgress) return } if err := a.checkTransferSourceWritable(name); err != nil { status, body := fileMutationAdmissionFailure(err) jsonWrite(w, status, body) return } serverDir := a.serverDir(name) meta := a.loadMeta(serverDir) if meta[reinstallPendingStartupKey] == true { writeReinstallStartupPending(w) return } if a.verifyServerNetworkQuota(name, meta, time.Now()) != nil { writeServerNetworkQuotaExceeded(w) return } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if !a.docker.containerExists(ctx, name) { jsonWrite(w, 400, map[string]any{"error": "not running"}) return } if normalizeRustRuntimeForPterodactyl(meta) { _ = a.saveMeta(serverDir, meta) } // adpanel:minecraft-eula - a restart boots the server again, so consent must // exist in eula.txt (covers both the recreate and plain docker restart paths). if isMinecraftServerMeta(meta) && !minecraftEulaAccepted(serverDir) { jsonWrite(w, 409, map[string]any{ "ok": false, "error": "minecraft_eula_required", "code": "minecraft_eula_required", "detail": "The Minecraft EULA (eula.txt) must be accepted before this server can start.", }) return } consoleMode := inferredConsoleModeForServer(meta) recreateForConsoleStdin := consoleMode == "stdin" && (!a.docker.containerOpenStdin(ctx, name) || !a.docker.containerTTY(ctx, name)) if shouldRecreateContainerOnRestart(meta) || recreateForConsoleStdin { if a.stdinMgr != nil { a.stdinMgr.remove(name) } if a.logs != nil { a.logs.resetRecent(name) } startCtx, startCancel := context.WithTimeout(context.Background(), 240*time.Second) defer startCancel() resources := resourceLimitsFromMeta(meta) resolveStoredPort := func(defaultPort int) int { if storedPort, ok := parseStrictPortValue(meta["hostPort"]); ok { return storedPort } if runtimeObj, ok := meta["runtime"].(map[string]any); ok { if ports := runtimeIntSlice(runtimeObj["ports"]); len(ports) > 0 && ports[0] > 0 { return ports[0] } } return defaultPort } typ := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) if typ == "" || typ == "" { typ = strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) } var startErr error switch { case typ == "minecraft": hostPort := resolveStoredPort(25565) enforceServerProps(serverDir) startErr = a.startMinecraftContainer(startCtx, name, serverDir, hostPort, resources, nil, false) case meta["runtime"] != nil && (typ == "python" || typ == "nodejs" || typ == "discord-bot" || typ == "runtime"): hostPort := resolveStoredPort(0) startErr = a.startRuntimeContainer(startCtx, name, serverDir, meta, hostPort, resources, nil) default: hostPort := resolveStoredPort(8080) startErr = a.startCustomDockerContainer(startCtx, name, serverDir, meta, hostPort, resources) } if startErr != nil { jsonWrite(w, 500, map[string]any{"error": "container recreate failed", "detail": startErr.Error()}) return } a.ensureLiveLogs(name) a.broadcastContainerEvent(name, "running") jsonWrite(w, 200, map[string]any{"ok": true, "recreated": true, "reason": func() string { if recreateForConsoleStdin { return "stdin" } return "runtime" }()}) return } if a.stdinMgr != nil { a.stdinMgr.remove(name) } if a.logs != nil { a.logs.resetRecent(name) } _, errStr, _, err := a.docker.runCollect(ctx, "restart", name) if err != nil { if a.debug { fmt.Printf("[docker] restart error for %s: %s\n", name, strings.TrimSpace(errStr)) } jsonWrite(w, 500, map[string]any{"error": "container restart failed"}) return } a.ensureLiveLogs(name) a.broadcastContainerEvent(name, "running") jsonWrite(w, 200, map[string]any{"ok": true}) } func sanitizeCommandRequestID(raw string) string { id := strings.TrimSpace(raw) if id == "" { return "" } if len(id) > consoleCommandRequestIDMaxLen { id = id[:consoleCommandRequestIDMaxLen] } for _, r := range id { if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == ':' || r == '.' { continue } return "" } return id } func (a *Agent) claimConsoleCommand(name, command, requestID string) (bool, string) { now := time.Now() a.commandMu.Lock() defer a.commandMu.Unlock() if a.recentCommands == nil { a.recentCommands = make(map[string]recentConsoleCommand) } for key, entry := range a.recentCommands { if now.Sub(entry.at) > consoleCommandRequestIDWindow { delete(a.recentCommands, key) } } if len(a.recentCommands) >= consoleCommandRecentMaxServers { var oldestKey string var oldestAt time.Time for key, entry := range a.recentCommands { if oldestKey == "" || entry.at.Before(oldestAt) { oldestKey = key oldestAt = entry.at } } if oldestKey != "" { delete(a.recentCommands, oldestKey) } } if entry, ok := a.recentCommands[name]; ok { if requestID != "" && entry.requestID == requestID && now.Sub(entry.at) <= consoleCommandRequestIDWindow { return false, "request_id" } // Rapid-duplicate guard: collapse the same command fired twice in a very // short window ONLY when we cannot distinguish the two submissions by // request id (i.e. no request id, or the same one). When the client sends // a fresh, distinct request id, the repeat is a deliberate separate // command and MUST be recorded as its own marker — otherwise sending // "pl" twice dropped the second marker while its output still appeared, // making outputs pile up with no "> pl" line between them. sameOrNoRequestID := requestID == "" || entry.requestID == "" || entry.requestID == requestID if sameOrNoRequestID && entry.command == command && now.Sub(entry.at) <= consoleCommandDuplicateWindow { return false, "rapid_duplicate" } } a.recentCommands[name] = recentConsoleCommand{ command: command, requestID: requestID, at: now, } return true, "" } func (a *Agent) isServerInstalling(name string) bool { if a == nil || strings.TrimSpace(name) == "" { return false } return serverSetupInProgress(a.loadMeta(a.serverDir(name))) } func (a *Agent) handleServerCommandBody(w http.ResponseWriter, r *http.Request) { var body struct { Name string `json:"name"` Command string `json:"command"` RequestID string `json:"requestId"` } if err := readJSON(w, r, 16*1024, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } name := sanitizeName(body.Name) if name == "" || strings.TrimSpace(body.Command) == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing params"}) return } r2 := *r r2.URL = &url.URL{Path: "/v1/servers/" + name + "/command"} commandBody, _ := json.Marshal(map[string]string{ "command": body.Command, "requestId": body.RequestID, }) r2.Body = io.NopCloser(bytes.NewReader(commandBody)) r2.ContentLength = int64(len(commandBody)) a.handleCommand(w, &r2, name) } func (a *Agent) handleLogsSSE(w http.ResponseWriter, r *http.Request, name string) { if !isValidContainerName(name) { jsonWrite(w, 400, map[string]any{"error": "invalid container name"}) return } rc := http.NewResponseController(w) _ = rc.SetWriteDeadline(time.Time{}) flusher, ok := w.(http.Flusher) if !ok { jsonWrite(w, 500, map[string]any{"error": "streaming not supported"}) return } tailN := 200 const maxLogTail = 10000 if q := r.URL.Query().Get("tail"); q != "" { if n, err := strconv.Atoi(q); err == nil && n >= 0 { tailN = n if tailN > maxLogTail { tailN = maxLogTail } } } w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache, no-transform") w.Header().Set("Connection", "keep-alive") sendEvent := func(ev string, data any) { b, _ := json.Marshal(data) fmt.Fprintf(w, "event: %s\ndata: %s\n\n", ev, string(b)) flusher.Flush() } sendLine := func(line string, ts int64) { var cleaned string if strings.HasPrefix(line, consoleDaemonMarkerPrefix) || strings.HasPrefix(line, consoleCommandMarkerPrefix) { cleaned = strings.TrimSpace(line) } else { cleaned = cleanLogLine(line) } if cleaned == "" { return } payload := map[string]any{"line": cleaned} if ts > 0 { payload["ts"] = ts } b, _ := json.Marshal(payload) fmt.Fprintf(w, "data: %s\n\n", string(b)) flusher.Flush() } sendEvent("hello", map[string]any{"server": name, "ts": time.Now().UnixMilli(), "tail": tailN}) t := a.logs.getOrCreate(name) t.markRunStartIfUnset() if tailN > 0 { snapshot := a.getLogSnapshotEntries(name, tailN) for _, entry := range snapshot { sendLine(entry.line, entry.ts) } } ch := make(chan string, 256) t.mu.Lock() if t.closed { t.mu.Unlock() return } t.clients[ch] = struct{}{} t.mu.Unlock() defer func() { t.mu.Lock() delete(t.clients, ch) t.mu.Unlock() a.logs.removeIfEmpty(t) }() hb := time.NewTicker(15 * time.Second) defer hb.Stop() notify := r.Context().Done() for { select { case <-notify: return case <-t.stopCh: return case line := <-ch: line = normalizeStreamedLogLine(line) sendLine(line, time.Now().UnixMilli()) case <-hb.C: sendEvent("keepalive", map[string]any{"ts": time.Now().UnixMilli()}) } } } func (a *Agent) getLogSnapshotEntries(name string, tailN int) []logSnapshotEntry { if tailN <= 0 { return nil } t := a.logs.getOrCreate(name) t.markRunStartIfUnset() snapshot := []logSnapshotEntry{} snapshotFromDockerLogs := false persisted, persistedEnd := t.readPersistedSnapshot(tailN) if len(persisted) > 0 { for _, line := range persisted { if strings.Contains(line, "[ADPanel Setup]") { continue } snapshot = append(snapshot, logSnapshotEntry{line: line}) } } if len(snapshot) == 0 && !preferDockerCLIConsoleTransport() { recentSnapshot := t.snapshotRecent(tailN) for _, line := range recentSnapshot { if strings.Contains(line, "[ADPanel Setup]") { continue } snapshot = append(snapshot, logSnapshotEntry{line: line}) } } if len(snapshot) == 0 { snapshotFromDockerLogs = true shouldReadDockerLogs := true stateCtx, stateCancel := context.WithTimeout(context.Background(), 2*time.Second) state := a.docker.containerState(stateCtx, name) stateCancel() if state != "" && state != "running" { shouldReadDockerLogs = false } if shouldReadDockerLogs { snapshot = a.logs.fetchTailSnapshotSingleflight(name, tailN, func() []logSnapshotEntry { ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) out, errOut := collectDockerLogTail(ctx, name, tailN, true) cancel() entries := append(parseDockerLogSnapshotEntries(out, tailN), parseDockerLogSnapshotEntries(errOut, tailN)...) sort.SliceStable(entries, func(i, j int) bool { left := entries[i].ts right := entries[j].ts if left == 0 || right == 0 { return false } return left < right }) if len(entries) > tailN { entries = entries[len(entries)-tailN:] } return entries }) } } if snapshotFromDockerLogs && len(snapshot) > 0 { lines := make([]string, 0, len(snapshot)) for _, entry := range snapshot { lines = append(lines, entry.line) } t.appendRecentBatch(lines) t.markDockerSnapshotPrimed() if existing, _ := t.readPersistedSnapshot(1); len(existing) == 0 { t.appendPersistedLines(lines) persistedEnd = t.persistedLinePosition() } } const snapshotSyntheticStepMs int64 = 3000 if n := len(snapshot); n > 0 { base := t.snapshotEpoch(n, snapshotSyntheticStepMs) absStart := max(0, persistedEnd-int64(n)) for i := range snapshot { if snapshot[i].ts <= 0 { snapshot[i].ts = base + (absStart+int64(i))*snapshotSyntheticStepMs } } } return snapshot } func (a *Agent) handleLogsSnapshot(w http.ResponseWriter, r *http.Request, name string) { if !isValidContainerName(name) { jsonWrite(w, 400, map[string]any{"error": "invalid container name"}) return } tailN := 200 const maxLogTail = 10000 if q := r.URL.Query().Get("tail"); q != "" { if n, err := strconv.Atoi(q); err == nil && n >= 0 { tailN = n if tailN > maxLogTail { tailN = maxLogTail } } } snapshot := a.getLogSnapshotEntries(name, tailN) type logLineOut struct { Line string `json:"line"` Ts int64 `json:"ts,omitempty"` } lines := make([]logLineOut, 0, len(snapshot)) for _, entry := range snapshot { var cleaned string if strings.HasPrefix(entry.line, consoleDaemonMarkerPrefix) || strings.HasPrefix(entry.line, consoleCommandMarkerPrefix) { cleaned = strings.TrimSpace(entry.line) } else { cleaned = cleanLogLine(entry.line) } if cleaned == "" { continue } lines = append(lines, logLineOut{Line: cleaned, Ts: entry.ts}) } jsonWrite(w, 200, map[string]any{ "ok": true, "server": name, "total": len(lines), "lines": lines, }) } func (a *Agent) handleResetLogs(w http.ResponseWriter, r *http.Request, name string) { if !isValidContainerName(name) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid container name"}) return } serverDir := a.serverDir(name) if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { jsonWrite(w, 404, map[string]any{"ok": false, "error": "not found"}) return } a.resetConsoleLogs(name) jsonWrite(w, 200, map[string]any{"ok": true}) } func (a *Agent) handleKill(w http.ResponseWriter, r *http.Request, name string) { if !isValidContainerName(name) { jsonWrite(w, 400, map[string]any{"error": "invalid container name"}) return } if r.Context().Err() != nil { writePowerOpRefusal(w, powerOpRequestEnded) return } // adpanel:backup-race - the abort markers are armed BEFORE the acquisition // (they are what aborts an in-flight start while the kill waits), but the // acquisition itself is bounded fail-fast (see acquireServerOpLockFailFast): // a kill either runs while current or refuses. On refusal the markers are // withdrawn - a lingering killPending would abort later starts as a // phantom side effect of a kill that never ran. a.stopMu.Lock() if a.killPending == nil { a.killPending = make(map[string]struct{}) } a.killPending[name] = struct{}{} a.stopMu.Unlock() a.startAbortMu.Lock() startCancel := a.startCancels[name] delete(a.startCancels, name) a.startAbortMu.Unlock() if startCancel != nil { startCancel() } opMu, refused := a.acquireServerOpLockFailFast(r.Context(), name) if refused != "" { a.stopMu.Lock() delete(a.killPending, name) a.stopMu.Unlock() writePowerOpRefusal(w, refused) return } defer opMu.Unlock() a.stopMu.Lock() delete(a.killPending, name) a.stopMu.Unlock() a.broadcastDaemonLog(name, "Sending immediate termination signal to container...") a.broadcastDaemonLog(name, "Terminating process threads and releasing allocated resources...") a.logs.killTail(name) if a.stdinMgr != nil { a.stdinMgr.remove(name) } ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) defer cancel() if err := a.removeServerContainerWithRetry(ctx, name); err != nil { fmt.Printf("[kill] force removal warning for %s: %v\n", name, err) jsonWrite(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "error": "could not confirm server container removal"}) return } a.broadcastDaemonLog(name, "Server container terminated forcefully.") a.broadcastContainerEvent(name, "stopped") jsonWrite(w, 200, map[string]any{"ok": true}) } func (a *Agent) handleDeleteServer(w http.ResponseWriter, r *http.Request, name string) { if name == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid name"}) return } filesOnly := r.URL.Query().Get("files_only") == "true" opMu := a.tryLockServerOp(name) if opMu == nil { a.writeServerOpConflictResponse(w, name) return } if r.URL.Query().Get("async") == "true" { serverDir := a.serverDir(name) // adpanel:multidisk - validate against the server's OWNING volumes root, // not the primary one, so secondary-disk servers pass the guard. volRoot := a.serverVolumesRoot(name) if filepath.Clean(serverDir) == volRoot { opMu.Unlock() jsonWrite(w, 400, map[string]any{"ok": false, "error": "refusing to delete volumes root"}) return } if !isUnder(volRoot, serverDir) { opMu.Unlock() jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } clientIP := getClientIP(r) go func() { defer opMu.Unlock() if _, err := a.deleteServerLocked(name, filesOnly, clientIP); err != nil { fmt.Printf("[delete] async delete failed for %s: %v\n", name, err) auditLog.Log("server_delete", clientIP, "", name, "delete", "failure", map[string]any{"error": err.Error()}) } }() jsonWrite(w, http.StatusAccepted, map[string]any{"ok": true, "name": name, "deleting": true}) return } defer opMu.Unlock() result, err := a.deleteServerLocked(name, filesOnly, getClientIP(r)) if err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to queue server delete", "detail": err.Error()}) return } jsonWrite(w, 200, map[string]any{"ok": true, "name": name, "deleting": result.ServerQueued || result.BackupQueued}) } type deleteServerResult struct { ServerQueued bool BackupQueued bool } func (a *Agent) deleteServerLocked(name string, filesOnly bool, clientIP string) (deleteServerResult, error) { var result deleteServerResult a.logs.killTail(name) a.logs.resetRecent(name) if a.stdinMgr != nil { a.stdinMgr.remove(name) } if !filesOnly { ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) err := a.removeServerContainerWithRetry(ctx, name) cancel() if err != nil { return result, fmt.Errorf("could not confirm server container removal: %w", err) } a.logs.resetRecent(name) } serverDir := a.serverDir(name) backupsDir := a.serverBackupsDir(name) // adpanel:multidisk - resolve the OWNING roots for this server so all guards // and detach operations target the correct disk. Using the hardcoded primary // roots here previously rejected secondary-disk deletes ("invalid path") and // left their volume + backups behind. volRoot := a.serverVolumesRoot(name) bkRoot := a.serverBackupsRoot(name) fmt.Printf("[delete] attempting to detach server directory: %s\n", serverDir) if filepath.Clean(serverDir) == volRoot { return result, fmt.Errorf("refusing to delete volumes root") } if !isUnder(volRoot, serverDir) || !isUnder(bkRoot, backupsDir) || filepath.Clean(backupsDir) == bkRoot { return result, fmt.Errorf("invalid path") } detachedServer, serverExists, err := a.detachPathForAsyncDelete(volRoot, serverDir, "server", name) if err != nil { fmt.Printf("[delete] error detaching %s: %v\n", serverDir, err) return result, err } if serverExists { result.ServerQueued = true removeDetachedPathAsync("server", detachedServer) } detachedBackup, backupExists, err := a.detachPathForAsyncDelete(bkRoot, backupsDir, "backups", name) if err != nil { return result, fmt.Errorf("could not detach server backups: %w", err) } if backupExists { result.BackupQueued = true removeDetachedPathAsync("backups", detachedBackup) } // adpanel:delete-storage-routing - a partial delete must keep its original disk mapping for retry. if err := os.Remove(a.metaPath(name)); err != nil && !os.IsNotExist(err) { return result, fmt.Errorf("could not remove server metadata: %w", err) } a.resourceStats.forget(name) // adpanel:multidisk - drop the cached server->disk mapping now that the server // is gone, so a future server reusing this name resolves its disk freshly. a.invalidateServerDiskCache(name) fmt.Printf("[delete] queued async cleanup for %s (serverQueued=%v backupsQueued=%v)\n", name, result.ServerQueued, result.BackupQueued) auditLog.Log("server_delete", clientIP, "", name, "delete", "success", nil) return result, nil } func (a *Agent) handleReinstallServer(w http.ResponseWriter, r *http.Request, name string) { if name == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid name"}) return } req, decoded := readReinstallRequest(w, r, a.uploadLimit) if !decoded { return } if strings.TrimSpace(req.StartupCommand) != "" || (req.Docker != nil && strings.TrimSpace(req.Docker.StartupCommand) != "") { jsonWrite(w, 400, map[string]any{"ok": false, "error": "raw docker startup commands are no longer supported"}) return } template := strings.ToLower(strings.TrimSpace(req.TemplateId)) if template == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing templateId"}) return } if req.HostPort != 0 { if _, ok := parseStrictPortValue(req.HostPort); !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid hostPort"}) return } } if req.Docker != nil { for _, p := range req.Docker.Ports { if _, ok := parseStrictPortValue(p); !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": fmt.Sprintf("invalid docker port: %d", p)}) return } } if cleanPortProtocols := sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports); len(req.Docker.PortProtocols) > 0 && len(cleanPortProtocols) == 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid docker port protocols"}) return } } if ok, why := a.verifyReinstallAdminRequest(r, name, template); !ok { auditLog.Log("server_reinstall", getClientIP(r), "", name, "reinstall", "denied", map[string]any{"reason": why}) jsonWrite(w, 403, map[string]any{"ok": false, "error": why}) return } // adpanel:backup-race - hold the same per-server lock as backup and // restore; never queue a wipe that could run after its relay gives up. opMu := a.tryLockServerOp(name) if opMu == nil { reason := a.writeServerOpConflictResponse(w, name) auditLog.Log("server_reinstall", getClientIP(r), "", name, "reinstall", "refused", map[string]any{"reason": reason}) return } defer opMu.Unlock() if a.serverStopPending(name) { writePowerOpRefusal(w, serverStopInProgress) auditLog.Log("server_reinstall", getClientIP(r), "", name, "reinstall", "refused", map[string]any{"reason": serverStopInProgress}) return } if req.OperationId != "" || req.AcceptUntil != 0 { now := time.Now() if !validReinstallOperationID(req.OperationId) || req.AcceptUntil < now.UnixMilli() || req.AcceptUntil > now.Add(10*time.Minute).UnixMilli() { jsonWrite(w, http.StatusBadRequest, map[string]any{"ok": false, "error": "invalid or expired reinstall operation"}) return } } // Register as a long op before any work: power ops check this and 409 // instead of queueing behind the reinstall's potentially // tens-of-minutes hold (see longOpBusyNames). The deferred endLongOp // runs before the Unlock defer above (LIFO), so the marker never // outlives the lock. a.beginLongOp(name, longOpReinstall) defer a.endLongOp(name) // Long op: installation can take up to two hours before image pull and // container start; the server-wide write deadline is too short - see // reinstallCallerWaitBudget (ignored on writers without deadline support, // e.g. httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(reinstallCallerWaitBudget)) fmt.Printf("[reinstall] Starting reinstall for server %s with template %s\n", name, template) serverDir := a.serverDir(name) // adpanel:multidisk - guard against the server's OWNING volumes root so // secondary-disk servers are not wrongly rejected as "invalid path". volRoot := a.serverVolumesRoot(name) if filepath.Clean(serverDir) == volRoot { jsonWrite(w, 400, map[string]any{"ok": false, "error": "refusing to operate on volumes root"}) return } if !isUnder(volRoot, serverDir) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } oldMeta, metaError := a.loadMetaChecked(serverDir, true) if metaError != nil { fmt.Printf("[reinstall] Failed to read metadata for %s: %v\n", name, metaError) jsonWrite(w, http.StatusInternalServerError, map[string]any{ "ok": false, "code": "reinstall_meta_read_failed", "error": "server metadata could not be verified; no files were replaced; contact an administrator before retrying", }) return } if serverSetupInProgress(oldMeta) { writeServerInstallingConflict(w) return } if oldMeta[reinstallPendingStartupKey] == true { writeReinstallStartupPending(w) return } if req.OperationId != "" && oldMeta[reinstallOperationMetadataKey] == req.OperationId { jsonWrite(w, http.StatusConflict, map[string]any{"ok": false, "code": "reinstall_operation_recorded", "error": "This reinstall operation has already finished."}) return } stripLegacyStartupCommandFields(oldMeta) oldRuntime := reinstallStoredRuntime(template, oldMeta, req.ReplaceRuntime) hostPort := req.HostPort if hostPort == 0 { if existingPort, ok := parseStrictPortValue(oldMeta["hostPort"]); ok { hostPort = existingPort } else if req.Docker != nil && len(req.Docker.Ports) > 0 { hostPort = req.Docker.Ports[0] } else if template == "minecraft" { hostPort = 25565 } else { hostPort = 8080 } } runtimeConfig := map[string]any{} rawJavaVersion := strings.TrimSpace(req.JavaVersion) if rawJavaVersion == "" && req.Docker != nil { rawJavaVersion = javaVersionFromDockerConfig(&req.Docker.dockerTemplateConfig) } if cleanJavaVersion := normalizeMinecraftJavaVersion(rawJavaVersion); strings.TrimSpace(rawJavaVersion) != "" { if cleanJavaVersion == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "unsupported minecraft java version"}) return } if template != "minecraft" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "java version selection is only available for minecraft"}) return } runtimeConfig["javaVersion"] = cleanJavaVersion } if req.Docker != nil { if req.Docker.ReadonlyRootfs { runtimeConfig["readonlyRootfs"] = true } if req.Docker.Image != "" { runtimeConfig["image"] = req.Docker.Image } if req.Docker.Tag != "" { runtimeConfig["tag"] = req.Docker.Tag } if cmd := sanitizeRuntimeCommand(req.Docker.Command); cmd != "" { startFile := defaultStartFileForType(template) dataDir := defaultDataDirForType(template) cleanCmd := normalizeLegacyRuntimeProcessCommand(template, cmd, startFile, dataDir) if reason := validateRuntimeProcessCommand(cleanCmd); reason != "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": reason}) return } runtimeConfig["command"] = cleanCmd } if req.Docker.Ports != nil { runtimeConfig["ports"] = req.Docker.Ports } if portProtocols := sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports); len(portProtocols) > 0 { runtimeConfig["portProtocols"] = portProtocols } if req.Docker.Volumes != nil { runtimeConfig["volumes"] = req.Docker.Volumes } if req.Docker.Env != nil { runtimeConfig["env"] = req.Docker.Env } if startup := startupTemplateFromDockerConfig(&req.Docker.dockerTemplateConfig); startup != "" { if reason := validateADPanelStartupScript(startup); reason != "" { jsonWrite(w, 400, map[string]any{"error": reason}) return } runtimeConfig["adpanelStartup"] = startup delete(runtimeConfig, "command") } if startupDisplay := startupDisplayFromDockerConfig(&req.Docker.dockerTemplateConfig); startupDisplay != "" { runtimeConfig["startupDisplay"] = startupDisplay } if install := dockerTemplateInstall(&req.Docker.dockerTemplateConfig); install != nil { runtimeConfig["install"] = install } reqWorkdir := strings.TrimSpace(req.Docker.Workdir) if reqWorkdir == "" { reqWorkdir = strings.TrimSpace(req.Docker.WorkingDir) } if reqWorkdir != "" { cleanWorkdir := normalizeContainerWorkdir(reqWorkdir) if cleanWorkdir == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid workdir (must be an absolute path like /app)"}) return } runtimeConfig["workdir"] = cleanWorkdir } if restart := strings.TrimSpace(req.Docker.Restart); restart != "" { runtimeConfig["restart"] = restart } else if restartPolicy := strings.TrimSpace(req.Docker.RestartPolicy); restartPolicy != "" { runtimeConfig["restart"] = restartPolicy } if templateRootAllowed() && (req.Docker.RunAsRoot || req.Docker.RunAsRootSnake) { runtimeConfig["runAsRoot"] = true } if req.Docker.Console != nil { runtimeConfig["console"] = req.Docker.Console } runtimeConfig["providerId"] = "custom" } if oldRuntime != nil { for _, key := range []string{"providerId", "versionId", "image", "tag", "javaVersion", "restart", "adpanelStartup", "install", "portProtocols", "runAsRoot"} { if _, exists := runtimeConfig[key]; exists { continue } if key == "portProtocols" { if protocols := runtimePortProtocolMap(oldRuntime[key]); len(protocols) > 0 { clean := map[string][]string{} for port, values := range protocols { clean[strconv.Itoa(port)] = values } runtimeConfig[key] = clean } continue } if key == "install" { if install := installConfigFromRuntime(oldRuntime); install != nil { runtimeConfig[key] = install } continue } if key == "runAsRoot" { if templateRootAllowed() && runtimeBool(oldRuntime[key]) { runtimeConfig[key] = true } continue } value := strings.TrimSpace(fmt.Sprint(oldRuntime[key])) if key == "adpanelStartup" && (value == "" || value == "") { value = startupTemplateFromRuntime(oldRuntime) } if value != "" && value != "" { runtimeConfig[key] = value } } if _, exists := runtimeConfig["command"]; !exists { if cmd := sanitizeRuntimeCommand(oldRuntime["command"]); cmd != "" { startFile := defaultStartFileForType(template) dataDir := defaultDataDirForType(template) cleanCmd := normalizeLegacyRuntimeProcessCommand(template, cmd, startFile, dataDir) if validateRuntimeProcessCommand(cleanCmd) == "" { runtimeConfig["command"] = cleanCmd } } } if _, exists := runtimeConfig["ports"]; !exists { if rawPorts, ok := oldRuntime["ports"].([]any); ok && len(rawPorts) > 0 { cleanPorts := make([]any, 0, len(rawPorts)) seenPorts := make(map[int]struct{}, len(rawPorts)) for _, entry := range rawPorts { port, ok := parseStrictPortValue(entry) if !ok { continue } if _, seen := seenPorts[port]; seen { continue } seenPorts[port] = struct{}{} cleanPorts = append(cleanPorts, port) } if len(cleanPorts) > 0 { runtimeConfig["ports"] = cleanPorts } } } if _, exists := runtimeConfig["volumes"]; !exists { if rawVolumes, ok := oldRuntime["volumes"].([]any); ok && len(rawVolumes) > 0 { cleanVolumes := make([]any, 0, len(rawVolumes)) for _, entry := range rawVolumes { spec := strings.TrimSpace(fmt.Sprint(entry)) if spec == "" || spec == "" || strings.ContainsAny(spec, "\x00\r\n") { continue } cleanVolumes = append(cleanVolumes, spec) } if len(cleanVolumes) > 0 { runtimeConfig["volumes"] = cleanVolumes } } } if _, exists := runtimeConfig["env"]; !exists { if rawEnv, ok := oldRuntime["env"].(map[string]any); ok && len(rawEnv) > 0 { cleanEnv := make(map[string]any) for key, value := range rawEnv { envKey := strings.TrimSpace(key) if envKey == "" { continue } envValue := strings.TrimSpace(fmt.Sprint(value)) if envValue == "" { envValue = "" } cleanEnv[envKey] = envValue } if len(cleanEnv) > 0 { runtimeConfig["env"] = cleanEnv } } } if _, exists := runtimeConfig["workdir"]; !exists { oldWorkdir := strings.TrimSpace(fmt.Sprint(oldRuntime["workdir"])) if oldWorkdir == "" || oldWorkdir == "" { oldWorkdir = strings.TrimSpace(fmt.Sprint(oldRuntime["workingDir"])) } if cleanWorkdir := normalizeContainerWorkdir(oldWorkdir); cleanWorkdir != "" { runtimeConfig["workdir"] = cleanWorkdir } } if _, exists := runtimeConfig["console"]; !exists { if rawConsole, ok := oldRuntime["console"]; ok && rawConsole != nil { runtimeConfig["console"] = rawConsole } } } a.rebuildReinstallServer(w, r, name, serverDir, template, hostPort, oldMeta, oldRuntime, runtimeConfig, req.OperationId, req.ReplaceRuntime, Downloader.downloadToFile) } func (a *Agent) handleFilesList(w http.ResponseWriter, r *http.Request, name string) { root := a.serverDir(name) if st, err := os.Stat(root); err != nil || !st.IsDir() { jsonWrite(w, 404, map[string]any{"error": "server not found"}) return } rel := r.URL.Query().Get("path") dir, ok := safeJoin(root, rel) if !ok { jsonWrite(w, 400, map[string]any{"error": "invalid path"}) return } st, err := os.Lstat(dir) if err != nil || !st.IsDir() { jsonWrite(w, 400, map[string]any{"error": "not a directory"}) return } if err := ensureResolvedUnder(root, dir); err != nil { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } // adpanel:fs-toctou - the listing is read from a dirfd pinned under the // server root (openat2/RESOLVE_BENEATH); the checks above only produce // friendly errors and no longer gate the actual read. rootHandle, herr := safeOpenRoot(root) if herr != nil { jsonWrite(w, 404, map[string]any{"error": "server not found"}) return } defer rootHandle.Close() dirRel, rerr := filepath.Rel(rootHandle.path, dir) if rerr != nil { jsonWrite(w, 400, map[string]any{"error": "invalid path"}) return } dirFd, oerr := safeOpenDirAt(rootHandle, dirRel) if oerr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to read directory"}) return } defer dirFd.Close() ents, truncated, err := readDirEntriesBounded(dirFd, maxDirListEntries) if err != nil { if a.debug { fmt.Printf("[files] list error for %s: %v\n", dir, err) } jsonWrite(w, 500, map[string]any{"error": "failed to read directory"}) return } out := make([]map[string]any, 0, len(ents)) for _, e := range ents { item := map[string]any{"name": e.Name(), "type": "file"} // Metadata comes from the pinned dirfd (Lstat equivalent), not from a // by-name walk that a swapped intermediate could redirect. if info, serr := safeStatAt(dirFd, e.Name()); serr == nil { typ := "file" if info.IsDir() { typ = "dir" } item["type"] = typ item["mtime"] = info.ModTime().Unix() if !info.IsDir() { item["size"] = info.Size() } } else if e.IsDir() { item["type"] = "dir" } out = append(out, item) } jsonWrite(w, 200, map[string]any{"ok": true, "entries": out, "path": rel, "truncated": truncated}) } // maxEditorRead caps the editor read routes (handleFilesRead, handleFSRead): // larger files must go through download, not an in-memory read into a JSON // response (which would copy the bytes three more times into the response). const maxEditorRead = 10 << 20 // errEditorReadTooLarge reports that the source still had data after // maxEditorRead bytes — either the file outgrew its pre-open size check (the // Lstat snapshot is stale the moment it returns) or it grew while being read. var errEditorReadTooLarge = errors.New("editor read exceeded the size cap") // readEditorCapped bounds an editor read no matter what the source does after // the caller's size check: it buffers at most maxBytes+1 bytes (the +1 // detects residual data without reading the rest of the file) and returns // errEditorReadTooLarge instead of serving a truncated view the user could // then save back over the real file. // // adpanel:fs-read-cap - the os.Lstat size checks in the callers are advisory // (friendly errors only); this reader is the enforced bound. A plain // io.ReadAll after a pre-open size check reads a concurrently-appending file // (a tenant-controlled log) into memory in full, however large it has become // by the time the open lands. func readEditorCapped(r io.Reader, maxBytes int64) ([]byte, error) { b, err := io.ReadAll(io.LimitReader(r, maxBytes+1)) if err != nil { return nil, err } if int64(len(b)) > maxBytes { return nil, errEditorReadTooLarge } return b, nil } func (a *Agent) handleFilesRead(w http.ResponseWriter, r *http.Request, name string) { root := a.serverDir(name) rel := r.URL.Query().Get("path") file, ok := safeJoin(root, rel) if !ok { jsonWrite(w, 400, map[string]any{"error": "invalid path"}) return } info, err := os.Lstat(file) if err != nil { jsonWrite(w, 404, map[string]any{"error": "file not found"}) return } if info.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"error": "cannot read symlink"}) return } if err := ensureResolvedUnder(root, file); err != nil { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } if info.IsDir() { jsonWrite(w, 400, map[string]any{"error": "path is a directory"}) return } if info.Size() > maxEditorRead { jsonWrite(w, 400, map[string]any{"error": "file too large (max 10MB)"}) return } // adpanel:fs-toctou - the file is opened through the pinned server-root // dirfd (openat2/RESOLVE_BENEATH); the Lstat/ensureResolvedUnder checks // above only produce friendly errors now. safeOpenRegularAt adds the // regular-file gate so a planted FIFO cannot wedge the open. rootHandle, herr := safeOpenRoot(root) if herr != nil { jsonWrite(w, 404, map[string]any{"error": "file not found"}) return } defer rootHandle.Close() fileRel, rerr := filepath.Rel(rootHandle.path, file) if rerr != nil { jsonWrite(w, 400, map[string]any{"error": "invalid path"}) return } rf, _, err := safeOpenRegularAt(rootHandle, fileRel, os.O_RDONLY|openNoFollow, 0) if err != nil { if errors.Is(err, errSafeNotRegular) { jsonWrite(w, 400, map[string]any{"error": "not a regular file"}) return } if a.debug { fmt.Printf("[files] read error for %s: %v\n", file, err) } jsonWrite(w, 500, map[string]any{"error": "failed to read file"}) return } defer rf.Close() b, rerr := readEditorCapped(rf, maxEditorRead) if rerr != nil { if errors.Is(rerr, errEditorReadTooLarge) { // Same message as the Lstat pre-check above so clients see one // shape whether the size was over the cap up front or the file // grew past it between the check and the read. jsonWrite(w, 400, map[string]any{"error": "file too large (max 10MB)"}) return } if a.debug { fmt.Printf("[files] read error for %s: %v\n", file, rerr) } jsonWrite(w, 500, map[string]any{"error": "failed to read file"}) return } jsonWrite(w, 200, map[string]any{"ok": true, "path": rel, "content": string(b)}) } func (a *Agent) handleFilesWrite(w http.ResponseWriter, r *http.Request, name string) { root := a.serverDir(name) var body struct { Path string `json:"path"` Content string `json:"content"` } if err := readJSON(w, r, 10<<20, &body); err != nil { // Split the old combined "bad json or content too large" message so a // malformed body is not misreported as exceeding the editor limit. if errors.Is(err, errBodyTooLarge) { jsonWrite(w, 400, map[string]any{"error": "content too large (max 10MB)"}) } else { jsonWrite(w, 400, map[string]any{"error": "invalid JSON body"}) } return } // adpanel:upload-atomicity - editor saves share the server scope's upload // lock with the upload routes (same contract as handleFSWrite): the quota // check and the write below form one serialized section per scope. unlock := a.lockRequestUploadScope(w, r, a.fsScopeRootFor(name, root)) if unlock == nil { return } defer unlock() file, ok := safeJoin(root, body.Path) if !ok { jsonWrite(w, 400, map[string]any{"error": "invalid path"}) return } // adpanel:fs-toctou - the parent-directory creation and the write target // are both resolved through the pinned server-root dirfd // (openat2/RESOLVE_BENEATH); missing parents are created with // ensureDirUnderRoot so a planted intermediate symlink cannot redirect // the creation outside the server scope when the target does not exist // yet. The EvalSymlinks checks below remain as friendly error reporting. rootHandle, herr := safeOpenRoot(root) if herr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } defer rootHandle.Close() fileRel, rerr := filepath.Rel(rootHandle.path, file) if rerr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } if err := ensureDirUnderRoot(rootHandle, filepath.Dir(fileRel), 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } parentDir := filepath.Dir(file) if parentDir != root { resolvedParent, err := filepath.EvalSymlinks(parentDir) if err == nil && !isUnder(root, resolvedParent) { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } } if rp, err := filepath.EvalSymlinks(filepath.Dir(file)); err == nil && !isUnder(root, rp) { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } if info, err := os.Lstat(file); err == nil { if info.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"error": "cannot write to symlink"}) return } } // adpanel:upload-atomicity - replaced-size credit before the quota check, // matching handleFSWrite: a save of an existing file near the limit used // to be billed as old file + new content and falsely 507'd. Content is a // utf8 string here, so len(body.Content) is the exact write size. var replacedBytes int64 if info, err := os.Lstat(file); err == nil && info.Mode().IsRegular() { replacedBytes = info.Size() } extraBytes := int64(len(body.Content)) - replacedBytes if extraBytes < 0 { extraBytes = 0 } if diskErr := a.checkDiskLimitForPath(root, extraBytes); diskErr != nil { jsonWrite(w, 507, diskErr) return } if err := safeWriteAt(rootHandle, fileRel, os.O_WRONLY|os.O_CREATE|os.O_TRUNC|openNoFollow, 0o644, []byte(body.Content)); err != nil { jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } jsonWrite(w, 200, map[string]any{"ok": true}) } func (a *Agent) handleFilesDelete(w http.ResponseWriter, r *http.Request, name string) { root := a.serverDir(name) var body struct { Path string `json:"path"` IsDir bool `json:"isDir"` } if err := readJSON(w, r, a.uploadLimit, &body); err != nil { jsonWrite(w, 400, map[string]any{"error": "bad json"}) return } p, ok := safeJoin(root, body.Path) if !ok { jsonWrite(w, 400, map[string]any{"error": "invalid path"}) return } if filepath.Clean(p) == filepath.Clean(root) { jsonWrite(w, 400, map[string]any{"error": "refusing to delete server root"}) return } unlock := a.lockRequestUploadScope(w, r, root) if unlock == nil { return } defer unlock() if _, err := os.Lstat(p); err != nil { jsonWrite(w, 200, map[string]any{"ok": true, "note": "already missing"}) return } if err := ensureResolvedUnder(root, p); err != nil { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } parentDir := filepath.Dir(p) if parentDir != root { resolvedParent, rpErr := filepath.EvalSymlinks(parentDir) if rpErr == nil && !isUnder(root, resolvedParent) { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } } // adpanel:fs-toctou - removal runs against dirfds pinned under the server // root (unlinkat/renameat-family on the opened parent); the checks above // only produce friendly errors now. rootHandle, herr := safeOpenRoot(root) if herr != nil { // The legacy path treated a missing server root as "already missing"; // any other root-open failure is a real error, like handleFSDelete. if os.IsNotExist(herr) { jsonWrite(w, 200, map[string]any{"ok": true, "note": "already missing"}) return } jsonWrite(w, 500, map[string]any{"error": "delete operation failed"}) return } defer rootHandle.Close() pRel, rerr := filepath.Rel(rootHandle.path, p) if rerr != nil { jsonWrite(w, 400, map[string]any{"error": "invalid path"}) return } if err := safeDeleteUnderRoot(rootHandle, pRel, body.IsDir); err != nil { jsonWrite(w, 500, map[string]any{"error": "delete operation failed"}) return } jsonWrite(w, 200, map[string]any{"ok": true}) } func (a *Agent) handleFilesUpload(w http.ResponseWriter, r *http.Request, name string) { root := a.serverDir(name) var body struct { DestDir string `json:"destDir"` Filename string `json:"filename"` Content string `json:"content"` } if err := readJSON(w, r, a.uploadLimit, &body); err != nil { jsonWrite(w, 400, map[string]any{"error": "bad json"}) return } // adpanel:upload-atomicity - the quota check and the write below run // under the server scope's upload lock, shared with the streaming upload // routes, so a base64 upload cannot interleave with another upload's // transfer/commit to the same server or validate its quota against a // snapshot another upload is about to invalidate. unlock := a.lockRequestUploadScope(w, r, a.fsScopeRootFor(name, root)) if unlock == nil { return } defer unlock() if strings.TrimSpace(body.Filename) == "" { jsonWrite(w, 400, map[string]any{"error": "missing filename"}) return } destDir, ok := safeJoin(root, body.DestDir) if !ok { jsonWrite(w, 400, map[string]any{"error": "invalid path"}) return } // adpanel:fs-toctou - the destination directory is created through the // pinned server-root dirfd (see ensureDirUnderRoot); unlike MkdirAll this // cannot follow a planted intermediate symlink outside the server scope // when the destination does not exist yet. rootHandle, herr := safeOpenRoot(root) if herr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } defer rootHandle.Close() destDirRel, dirRelErr := filepath.Rel(rootHandle.path, destDir) if dirRelErr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } if err := ensureDirUnderRoot(rootHandle, destDirRel, 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } if err := ensureResolvedUnder(root, destDir); err != nil { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } fn := sanitizeUploadFilename(body.Filename) if fn == "" { jsonWrite(w, 400, map[string]any{"error": "invalid filename"}) return } destFile := filepath.Join(destDir, fn) if !isUnder(destDir, destFile) { jsonWrite(w, 400, map[string]any{"error": "invalid filename"}) return } b64 := body.Content if strings.HasPrefix(b64, "data:") { if i := strings.Index(b64, ","); i >= 0 { b64 = b64[i+1:] } } const maxBase64Upload = 25 << 20 if base64.StdEncoding.DecodedLen(len(b64)) > maxBase64Upload { jsonWrite(w, 400, map[string]any{"error": "file too large for base64 upload; use stream upload"}) return } data, err := base64.StdEncoding.DecodeString(b64) if err != nil { jsonWrite(w, 400, map[string]any{"error": "invalid base64"}) return } // adpanel:upload-atomicity - credit the bytes an overwrite frees and bill // the DECODED size before validating the quota: the old check ran on the // raw base64 string (a ~33% over-bill) on top of counting the replaced // file as fresh bytes, so a near-quota overwrite that actually fit was // rejected with a false 507. checkDiskLimitForPath (not checkDiskLimit) // keeps the per-disk capacity ceiling the other upload routes enforce. // A symlink or directory at the destination is refused here instead of // failing later at write time. var replacedBytes int64 var existingMode os.FileMode destWasRegular := false if info, err := os.Lstat(destFile); err == nil { if info.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"error": "cannot write to symlink"}) return } if info.IsDir() { jsonWrite(w, 400, map[string]any{"error": "destination is a directory"}) return } replacedBytes = info.Size() if info.Mode().IsRegular() { existingMode = info.Mode() destWasRegular = true } } extraBytes := int64(len(data)) - replacedBytes if extraBytes < 0 { extraBytes = 0 } if diskErr := a.checkDiskLimitForPath(root, extraBytes); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } // adpanel:upload-atomicity - like the stream route, the transfer lands in // a unique temp file and is committed with an atomic same-directory // rename, so a failed write cannot leave a pre-existing target truncated // the way the old in-place O_TRUNC write did; failure cleanups unlink // only the temp. out, tmpRel, terr := openUploadTempFileAt(rootHandle, destDirRel, fn) if terr != nil { if a.debug { fmt.Printf("[files] upload create error for %s: %v\n", destFile, terr) } jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } if destWasRegular { // the staged commit replaces the inode, so the temp must inherit the replaced file's mode (see storeStreamUploadPart) if cerr := out.Chmod(existingMode); cerr != nil { _ = out.Close() removeUploadTemp(rootHandle, tmpRel) jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } } if _, werr := out.Write(data); werr != nil { _ = out.Close() removeUploadTemp(rootHandle, tmpRel) jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } // Crash-durability: the data must be on disk before the commit rename, or // a power loss after it surfaces an empty/truncated file under the final // name with the replaced version already gone. syncErr := out.Sync() if cerr := out.Close(); cerr != nil { removeUploadTemp(rootHandle, tmpRel) jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } if syncErr != nil { removeUploadTemp(rootHandle, tmpRel) jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } if rerr := safeRenameUnderRoot(rootHandle, tmpRel, fn); rerr != nil { removeUploadTemp(rootHandle, tmpRel) if a.debug { fmt.Printf("[files] upload commit error for %s: %v\n", destFile, rerr) } jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) return } // Best-effort: persist the commit rename itself; a crash that rolls it // back leaves the previous file intact, so the error is ignored. if parentFd, perr := safeOpenDirAt(rootHandle, destDirRel); perr == nil { _ = parentFd.Sync() _ = parentFd.Close() } rel, _ := filepath.Rel(root, destFile) jsonWrite(w, 200, map[string]any{"ok": true, "path": rel}) } // adpanel:archive-self-exclusion - in-flight archive temp files are created in // the destination directory with this pattern so the archive walk can exclude // them by name, including strays left behind by interrupted runs. const archiveTempPattern = ".archive-*.tmp" func isArchiveTempName(name string) bool { return strings.HasPrefix(name, ".archive-") && strings.HasSuffix(name, ".tmp") } // archiveDestinationNames returns the ordered commit candidates for one // archive run: the second-resolution timestamped name plus bounded -N // fallbacks, so a same-second collision (two concurrent archives in one // directory, or a user file that already carries the exact name) resolves to // a fresh name instead of an overwrite. The bound caps the commit retry loop // and any trivial name-squatting exhaustion of the endpoint in one directory. func archiveDestinationNames(now time.Time) []string { stem := "archive-" + now.Format("20060102-150405") names := make([]string, 0, 101) names = append(names, stem+".tar.gz") for i := 1; i <= 100; i++ { names = append(names, fmt.Sprintf("%s-%d.tar.gz", stem, i)) } return names } // pickArchiveDestinationName returns the first candidate that does not // currently exist beneath the pinned root at dirRel (checked with // safeStatAt on a dirfd pinned under the scope root). Purely advisory - the // commit rename in handleFilesArchive is still RENAME_NOREPLACE - it only // makes the walk-time self-exclusion track the name that will actually be // written. Every candidate existing surfaces as errSafeDestExists before any // temp file is created. func pickArchiveDestinationName(root *safeRoot, dirRel string, candidates []string) (string, error) { parentFd, err := safeOpenDirAt(root, dirRel) if err != nil { return "", err } defer parentFd.Close() for _, name := range candidates { _, statErr := safeStatAt(parentFd, name) if errors.Is(statErr, fs.ErrNotExist) { return name, nil } if statErr != nil { return "", statErr } } return "", fmt.Errorf("%w: %s", errSafeDestExists, candidates[0]) } // commitArchiveNoReplace renames the fully-written archive temp file onto its // final name without ever replacing an existing destination: // safeRenameNoReplaceUnderRoot (RENAME_NOREPLACE, with the pathsafe lstat // fallback on kernels/filesystems without the flag) turns a mid-walk // collision - the pre-picked name taken by a concurrent archive or a file // created meanwhile - into an errSafeDestExists for the next -N candidate // rather than a silent destroy. Returns the committed name. func commitArchiveNoReplace(root *safeRoot, tempRel string, candidates []string, picked string) (string, error) { start := 0 for i, name := range candidates { if name == picked { start = i break } } for _, name := range candidates[start:] { err := safeRenameNoReplaceUnderRoot(root, tempRel, name) if err == nil { return name, nil } if errors.Is(err, errSafeDestExists) { continue } return "", err } return "", fmt.Errorf("%w: %s", errSafeDestExists, picked) } // archiveCallerWaitBudget matches what every files-archive caller waits for a // response (nodes.js archive relay and index.js direct: 300s). The tar+gzip // walk below is disk/CPU-bound with only a byte budget, so archiving a large // tree legitimately outlasts the server-wide 120s WriteTimeout. const archiveCallerWaitBudget = 5 * time.Minute func (a *Agent) handleFilesArchive(w http.ResponseWriter, r *http.Request, name string) { root := a.serverDir(name) var body struct { Paths []string `json:"paths"` DestDir string `json:"destDir"` } if err := readJSON(w, r, a.uploadLimit, &body); err != nil { jsonWrite(w, 400, map[string]any{"error": "bad json"}) return } if len(body.Paths) == 0 { jsonWrite(w, 400, map[string]any{"error": "no paths specified"}) return } // adpanel:upload-scope-lock — the disk check and the budget snapshot below // must serialize with uploads and other extracts/archives on the same // scope, or the quota check is taken against stale usage; the lock is // deliberately held across the whole operation (see the lockUploadScope // contract comment). unlock := a.lockRequestUploadScope(w, r, a.fsScopeRootFor(name, root)) if unlock == nil { return } defer unlock() if diskErr := a.checkDiskLimit(root, 0); diskErr != nil { jsonWrite(w, 507, diskErr) return } destDir, ok := safeJoin(root, body.DestDir) if !ok { jsonWrite(w, 400, map[string]any{"error": "invalid destination path"}) return } // adpanel:fs-toctou - the destination directory is created through the // pinned server-root dirfd (see ensureDirUnderRoot); unlike MkdirAll this // cannot follow a planted intermediate symlink outside the server scope // when the destination does not exist yet. rootHandle, herr := safeOpenRoot(root) if herr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to create archive"}) return } defer rootHandle.Close() destDirRel, dirRelErr := filepath.Rel(rootHandle.path, destDir) if dirRelErr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to create archive"}) return } if err := ensureDirUnderRoot(rootHandle, destDirRel, 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } jsonWrite(w, 500, map[string]any{"error": "failed to create archive"}) return } resolvedDest, rdErr := filepath.EvalSymlinks(destDir) if rdErr == nil && !isUnder(root, resolvedDest) { jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) return } // adpanel:archive-no-clobber - the destination name is server-generated, // so unlike the upload flows (whose filename is the user's explicit choice // and whose commit may replace that file, with replaced-bytes quota // accounting and a symlink refusal) the archive must never overwrite // anything. Pick the first candidate that does not currently exist // (advisory, so the walk below excludes the name that will actually be // written while a pre-existing file at the primary name keeps getting // archived like any other file) and commit through RENAME_NOREPLACE: two // archives made in the same directory within one second, or a user file // that happens to carry the exact timestamped name, resolve to // deterministic -N fallbacks instead of a silent destroy. archiveCandidates := archiveDestinationNames(time.Now()) archiveName, pickErr := pickArchiveDestinationName(rootHandle, destDirRel, archiveCandidates) if pickErr != nil { if errors.Is(pickErr, errSafeDestExists) { jsonWrite(w, 409, map[string]any{"error": "archive name already exists"}) } else { jsonWrite(w, 500, map[string]any{"error": "failed to create archive"}) } return } archivePath := filepath.Join(destDir, archiveName) // adpanel:archive-self-exclusion - write the tar into a unique temp file in // the destination directory instead of the final name. Archiving a source // directory that contains the destination used to let the walk read the // growing output back into the tar stream, silently corrupting it. The temp // file is created through the pinned server root (O_CREAT|O_EXCL, mode 0644 // so the umask still applies), fsynced and renamed to the final // archive-.tar.gz name only after the stream is fully written, so a // half-written archive never sits at a walkable path. outFile, tempArchiveRel, terr := openArchiveTempFileAt(rootHandle, destDirRel) if terr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to create archive"}) return } tempArchivePath := filepath.Join(rootHandle.path, tempArchiveRel) archiveRel := filepath.Join(destDirRel, archiveName) defer func() { outFile.Close() _ = safeDeleteUnderRoot(rootHandle, tempArchiveRel, false) // no-op after a successful rename }() // Same lost-response shape as extract: the walk+compress below commits // the archive (fsync + no-replace rename) before the first response byte, // so a >120s archive used to finish and then lose the response to the // server-wide WriteTimeout — the caller answers 502 and a retry dies on // the no-clobber commit even though the archive exists. Extend THIS // connection's write deadline to the full caller budget; beyond it no // caller is listening anyway (ignored on writers without deadline // support, e.g. httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(archiveCallerWaitBudget)) // adpanel:archive-budget - the outgoing tar/gzip stream is bounded by the // same budget that bounds one extraction (extractBudgetForDir: the global // archive-bomb cap or the server's remaining disk quota), so archiving "." // on a near-quota server cannot approach ~2x usage by reading everything // back out into a second copy. Under-budget archives stream through the // wrapper byte-identically; a capped stream surfaces as the endpoint's // existing 507 quota shape below, with the temp removed by the deferred // cleanup and no final archive file renamed into place. archiveLW := &limitedWriter{w: outFile, limit: a.extractBudgetForDir(root)} gw := gzip.NewWriter(archiveLW) defer gw.Close() tw := tar.NewWriter(gw) defer tw.Close() // The walked source may contain the destination at any depth (e.g. archiving // "." with a destination inside the root), so the archive's own output - the // final name and the in-flight temp file - must be skipped in absolute and // root-relative spellings as well as in both symlink-resolved spellings. resolvedArchivePath := "" resolvedTempPath := "" if rdErr == nil { resolvedArchivePath = filepath.Join(resolvedDest, archiveName) resolvedTempPath = filepath.Join(resolvedDest, filepath.Base(tempArchivePath)) } skipArchiveOutput := func(path, resolved string) bool { c := filepath.Clean(path) if c == archivePath || c == tempArchivePath { return true } if rel, relErr := filepath.Rel(rootHandle.path, c); relErr == nil && (rel == archiveRel || rel == tempArchiveRel) { return true } if resolved != "" && (resolved == resolvedArchivePath || resolved == resolvedTempPath) { return true } return filepath.Dir(c) == destDir && isArchiveTempName(filepath.Base(c)) } archiveErr := writeArchiveSources(tw, rootHandle, root, body.Paths, skipArchiveOutput) twErr := tw.Close() gwErr := gw.Close() if archiveLW.exceeded { // The stream hit the extract budget (during the walk or while // flushing the tar/gzip trailers): answer with the same quota shape // the endpoint's checkDiskLimit failures use. The temp is removed by // the deferred cleanup above and the final rename never happens. diskErr := a.checkDiskLimit(root, archiveLW.written+1) if diskErr == nil { usedBytes := a.getServerTotalUsage(root) if usedBytes < archiveLW.written { usedBytes = archiveLW.written } limitBytes := a.getServerDiskLimitBytes(root) if limitBytes <= 0 { limitBytes = archiveLW.limit } usedMb := float64(usedBytes) / (1024 * 1024) limitMb := float64(limitBytes) / (1024 * 1024) diskErr = map[string]any{ "error": "disk_limit_exceeded", "message": fmt.Sprintf("This server has exceeded its disk space limit. Used: %.1f MB / %.1f MB", usedMb, limitMb), "usedBytes": usedBytes, "limitBytes": limitBytes, "usedMb": usedMb, "limitMb": limitMb, } } jsonWrite(w, 507, diskErr) return } if errors.Is(archiveErr, errArchiveSourceUnavailable) { jsonWrite(w, http.StatusConflict, map[string]any{"error": errArchiveSourceUnavailable.Error()}) return } if archiveErr != nil { jsonWrite(w, http.StatusInternalServerError, map[string]any{"error": "failed to create archive"}) return } if twErr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to finalize archive"}) return } if gwErr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to finalize archive"}) return } if err := outFile.Sync(); err != nil { jsonWrite(w, 500, map[string]any{"error": "failed to finalize archive"}) return } if err := outFile.Close(); err != nil { jsonWrite(w, 500, map[string]any{"error": "failed to finalize archive"}) return } // Same-parent rename through the pinned root: both sides stay beneath the // server scope no matter what was swapped into destDir mid-request. The // commit is create-only (adpanel:archive-no-clobber): a name that was free // at pick time but taken by a concurrent archive or a new file by now is // answered with the next -N candidate, never an overwrite. finalName, commitErr := commitArchiveNoReplace(rootHandle, tempArchiveRel, archiveCandidates, archiveName) if commitErr != nil { if errors.Is(commitErr, errSafeDestExists) { jsonWrite(w, 409, map[string]any{"error": "archive name already exists"}) } else { jsonWrite(w, 500, map[string]any{"error": "failed to finalize archive"}) } return } archiveName = finalName archivePath = filepath.Join(destDir, archiveName) relPath, _ := filepath.Rel(root, archivePath) jsonWrite(w, 200, map[string]any{"ok": true, "path": relPath, "name": archiveName}) } func (a *Agent) backupsDir() string { return filepath.Join(a.dataRoot, "backups") } func (a *Agent) serverBackupsDir(serverName string) string { // adpanel:multidisk - backups live on the same disk as the server. Defaults // to the primary backups root for unassigned servers (back-compat). disk := a.diskForServer(serverName) if disk.Primary || disk.ID == primaryDiskID { return filepath.Join(a.backupsDir(), sanitizeName(serverName)) } return filepath.Join(a.diskLayoutBackups(disk.MountPath), sanitizeName(serverName)) } // serverVolumesRoot returns the volumes root that owns the given server's files. // adpanel:multidisk - this is the parent under which the server directory lives, // which is the primary volumes dir for unassigned servers and the disk-specific // volumes root otherwise. Delete/detach guards must validate against THIS root, // not a.volumesDir, or secondary-disk servers are wrongly rejected as "invalid // path" and their files/backups are never removed. func (a *Agent) serverVolumesRoot(serverName string) string { disk := a.diskForServer(serverName) if disk.Primary || disk.ID == primaryDiskID { return filepath.Clean(a.volumesDir) } return filepath.Clean(a.diskLayoutVolumes(disk.MountPath)) } // serverBackupsRoot returns the backups root that owns the given server's backups // (the parent of serverBackupsDir). Used as the detach parentRoot for backups. func (a *Agent) serverBackupsRoot(serverName string) string { disk := a.diskForServer(serverName) if disk.Primary || disk.ID == primaryDiskID { return filepath.Clean(a.backupsDir()) } return filepath.Clean(a.diskLayoutBackups(disk.MountPath)) } func deletionTrashDir(parent string) string { return filepath.Join(parent, ".adpanel_deleting") } func deletionTombstoneName(label, name string) string { safe := sanitizeName(name) if safe == "" { safe = "unknown" } label = sanitizeName(label) if label == "" { label = "path" } return fmt.Sprintf("%s-%s-%d", label, safe, time.Now().UnixNano()) } func deleteTrashPrefix(label, name string) string { safe := sanitizeName(name) if safe == "" { safe = "unknown" } label = sanitizeName(label) if label == "" { label = "path" } return fmt.Sprintf("%s-%s-", label, safe) } func pathExists(path string) bool { _, err := os.Lstat(path) return err == nil } func deleteTrashEntryExists(parentRoot, label, name string) bool { entries, err := os.ReadDir(deletionTrashDir(parentRoot)) if err != nil { return false } prefix := deleteTrashPrefix(label, name) for _, entry := range entries { if strings.HasPrefix(entry.Name(), prefix) { return true } } return false } func (a *Agent) containerExistsKnown(ctx context.Context, name string) (bool, bool) { if exists, err := a.docker.containerExistsAPI(ctx, name); err == nil { return exists, true } if ctx.Err() != nil { return false, false } _, errText, _, err := a.docker.runCollect(ctx, "inspect", name) if err == nil { return true, true } if ctx.Err() != nil { return false, false } msg := strings.ToLower(errText) if strings.Contains(msg, "no such object") || strings.Contains(msg, "no such container") || strings.Contains(msg, "not found") { return false, true } return false, false } func (a *Agent) deleteStatus(ctx context.Context, name string) map[string]any { containerExists, containerCheckOk := a.containerExistsKnown(ctx, name) volumes, backups := a.serverStoragePaths(name) serverDirExists, serverErr := anyServerStoragePathExists(volumes) metaExists, metaErr := anyServerStoragePathExists([]string{a.metaPath(name)}) backupsDirExists, backupsErr := anyServerStoragePathExists(backups) storageCheckOk := serverErr == nil && metaErr == nil && backupsErr == nil bkRoot := a.serverBackupsRoot(name) volRoot := a.serverVolumesRoot(name) serverTrashExists := deleteTrashEntryExists(volRoot, "server", name) backupTrashExists := deleteTrashEntryExists(bkRoot, "backups", name) deleted := containerCheckOk && storageCheckOk && !containerExists && !serverDirExists && !metaExists && !backupsDirExists return map[string]any{ "ok": true, "deleteStatus": true, "name": name, "deleted": deleted, "containerExists": containerExists, "containerCheckOk": containerCheckOk, "storageCheckOk": storageCheckOk, "serverDirExists": serverDirExists, "metaExists": metaExists, "backupsDirExists": backupsDirExists, "serverTrashExists": serverTrashExists, "backupTrashExists": backupTrashExists, } } func (a *Agent) handleDeleteStatus(w http.ResponseWriter, r *http.Request, name string) { ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() jsonWrite(w, 200, a.deleteStatus(ctx, name)) } func (a *Agent) detachPathForAsyncDelete(parentRoot, target, label, name string) (string, bool, error) { parentRoot = filepath.Clean(parentRoot) target = filepath.Clean(target) if parentRoot == "" || target == "" || target == "." || target == string(os.PathSeparator) { return "", false, fmt.Errorf("invalid delete path") } if filepath.Clean(parentRoot) == target { return "", false, fmt.Errorf("refusing to delete root") } if !isUnder(parentRoot, target) { return "", false, fmt.Errorf("delete path escapes root") } if _, err := os.Lstat(target); err != nil { if os.IsNotExist(err) { return "", false, nil } return "", false, err } trashRoot := deletionTrashDir(parentRoot) if err := ensureDir(trashRoot); err != nil { return "", true, err } var lastErr error for i := 0; i < 10; i++ { dst := filepath.Join(trashRoot, deletionTombstoneName(label, name)) if i > 0 { dst = fmt.Sprintf("%s-%d", dst, i) } if err := os.Rename(target, dst); err == nil { return dst, true, nil } else { if os.IsNotExist(err) { return "", false, nil } lastErr = err time.Sleep(25 * time.Millisecond) } } return "", true, lastErr } func removeDetachedPathAsync(label, root string) { root = filepath.Clean(root) if root == "" || root == "." || root == string(os.PathSeparator) { return } go func() { started := time.Now() if err := removeAllWritable(root); err != nil { fmt.Printf("[delete] async cleanup failed for %s %s after %s: %v\n", label, root, time.Since(started).Round(time.Millisecond), err) return } fmt.Printf("[delete] async cleanup completed for %s %s in %s\n", label, root, time.Since(started).Round(time.Millisecond)) }() } func (a *Agent) cleanupPendingDeletes() { // adpanel:multidisk - sweep the deletion trash on EVERY disk (primary + // secondaries), not just the primary roots. Detached tombstones for // secondary-disk servers/backups live under each disk's own volumes/backups // trash dir and would otherwise leak on restart. roots := []string{deletionTrashDir(a.volumesDir), deletionTrashDir(a.backupsDir())} for _, d := range a.registeredDisks() { roots = append(roots, deletionTrashDir(a.diskLayoutVolumes(d.MountPath)), deletionTrashDir(a.diskLayoutBackups(d.MountPath)), ) } seen := map[string]struct{}{} for _, root := range roots { root = filepath.Clean(root) if _, dup := seen[root]; dup { continue } seen[root] = struct{}{} entries, err := os.ReadDir(root) if err != nil { continue } for _, entry := range entries { removeDetachedPathAsync("startup-trash", filepath.Join(root, entry.Name())) } } } type BackupMeta struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` ServerName string `json:"serverName"` CreatedAt int64 `json:"createdAt"` Size int64 `json:"size"` Status string `json:"status"` // adpanel:backup-live-copy-mark — a backup is a HOT copy: the container may // still be running while its tree is walked and copied (databases, logs and // player data can be mid-write). The panel warns about possible inconsistency. Live bool `json:"live,omitempty"` } // maxBackupMetaBytes caps the backup.json read in loadBackupMeta: the file is // written by saveBackupMeta with daemon-clamped fields, so anything larger is // corrupt or foreign and is treated like an unmarshal failure, not loaded // whole into memory. const maxBackupMetaBytes = 64 << 10 func (a *Agent) loadBackupMeta(backupDir string) *BackupMeta { metaPath := filepath.Join(backupDir, "backup.json") f, err := os.Open(metaPath) if err != nil { return nil } defer f.Close() data, err := io.ReadAll(io.LimitReader(f, maxBackupMetaBytes+1)) if err != nil { return nil } if len(data) > maxBackupMetaBytes { return nil } var meta BackupMeta if err := json.Unmarshal(data, &meta); err != nil { return nil } return &meta } func (a *Agent) saveBackupMeta(backupDir string, meta *BackupMeta) error { data, err := json.MarshalIndent(meta, "", " ") if err != nil { return err } return writeFileNoFollow(filepath.Join(backupDir, "backup.json"), data, 0644) } func getDirSize(path string) int64 { var size int64 filepath.Walk(path, func(_ string, info os.FileInfo, err error) error { if err == nil && !info.IsDir() { size += info.Size() } return nil }) return size } // adpanel:backup-orphan-janitor — a crash can leave a stale backup directory // without backup.json. It counts against quota but cannot be managed in the // panel. The sweep reclaims it only when the metadata file is absent; an // unreadable or corrupt file is not evidence that its payload is incomplete. const backupOrphanAgeThreshold = time.Hour // adpanel:restore-staging-gc — a crash or failed cleanup can leave a staging // sibling outside the per-server quota and listings. Reclaim stale siblings // for this server under its operation lock, but never a live volume. const restoreStagingAgeThreshold = 2 * time.Hour // dirHasServerMeta reports whether dir carries a server meta in either form // the daemon recognises as "this directory is a live server": the external // registry file .adpanel_meta/.json on the primary // volumes root (what createServer writes via saveMeta), or the legacy in-dir // adpanel.json loadMeta still migrates from. This is the SAME liveness test // createServer's duplicate detection applies (dir exists + either meta => // "server already exists"), kept as pure os.Stat calls on purpose: // adpanel:restore-staging-gc — the staging sweep refuses to RemoveAll any // candidate carrying either mark (sanitizeName keeps dots, so a live server // may legitimately be named like a staging sibling), and loadMeta itself is // NOT usable here because its legacy migration would WRITE a registry file // as a side effect for a name the GC arm merely suspects. func (a *Agent) dirHasServerMeta(dir string) bool { if _, err := os.Stat(a.metaPath(filepath.Base(dir))); err == nil { return true } _, err := os.Stat(filepath.Join(dir, "adpanel.json")) return err == nil } // sweepOrphanBackups is the backup janitor, one non-blocking locked sweep // with two independent arms: (1) stale meta-less backup dirs in backupsDir // (see the adpanel:backup-orphan-janitor comment above) and (2) stale // restore-staging siblings in the volumes root (see // adpanel:restore-staging-gc above). // // Race posture: the sweep takes the per-server op lock non-blocking and skips // the WHOLE sweep — both arms — when it is busy: the same lock a create and a // restore each hold for their whole duration, so an in-flight create can // never be swept even if its copy runs past the age threshold (a huge server // copying for hours) and an in-flight restore's staging dir can never be // swept mid-copy or mid-swap. The staging arm is scoped per server ON // PURPOSE: it matches only entries carrying THIS server's base name, so a // crash leftover from a DIFFERENT server is cleaned when THAT server's list // runs — the per-server op lock that guards this arm is exactly the lock // that server's restore holds, which a global sweep could not claim (its // removals would race restores of other servers it holds no lock for; the // scoped form needs no cross-server coupling). func (a *Agent) sweepOrphanBackups(serverName, backupsDir string) { opMu := a.tryLockServerOp(serverName) if opMu == nil { // A create/restore/delete/power op holds the lock: nothing in here may // be an orphan yet. The next list sweeps. return } defer opMu.Unlock() // Arm 1: meta-less backup dirs (adpanel:backup-orphan-janitor). entries, err := os.ReadDir(backupsDir) if err == nil { cutoff := time.Now().Add(-backupOrphanAgeThreshold) for _, entry := range entries { if !entry.IsDir() { continue } info, err := entry.Info() if err != nil { continue } if info.ModTime().After(cutoff) { continue } backupDir := filepath.Join(backupsDir, entry.Name()) if _, err := os.Lstat(filepath.Join(backupDir, "backup.json")); !errors.Is(err, os.ErrNotExist) { continue } if err := removeAllWritable(backupDir); err != nil { a.logf("Backup orphan janitor: failed to remove meta-less backup dir %s: %v", backupDir, err) continue } a.logf("Backup orphan janitor: removed meta-less backup dir %s (mtime %s older than %s)", backupDir, info.ModTime().Format(time.RFC3339), backupOrphanAgeThreshold) } } // Arm 2: stale restore-staging siblings (adpanel:restore-staging-gc). // Scoped to THIS server's staging prefix, with or without the leading // dot used by new staging directories; a non-directory entry (or a planted // symlink — DirEntry.IsDir is lstat-shaped) is never touched. // adpanel:restore-staging-gc — the entry-shape and age checks alone are // NOT the data-safety bound: sanitizeName keeps dots, so a LIVE server // can be named .restore-staging- (deliberately or by // accident) while its top-level mtime trails subdirectory writes past // the threshold; a bare RemoveAll here would destroy that server's whole // tree with no trash and no tombstone. Every candidate therefore passes // dirHasServerMeta first (external registry meta, or the legacy in-dir // adpanel.json — the same liveness test createServer's duplicate // detection uses); a candidate carrying either mark is a live server by // the daemon's own definition and is SKIPPED with a warning, never // removed. A staging directory containing legacy metadata is also left // for manual cleanup, since that case cannot be distinguished safely. serverDir := a.serverDir(serverName) volumesRoot := filepath.Dir(serverDir) stagingPrefix := filepath.Base(serverDir) + ".restore-staging-" rootEntries, err := os.ReadDir(volumesRoot) if err != nil { return } stagingCutoff := time.Now().Add(-restoreStagingAgeThreshold) for _, entry := range rootEntries { name := entry.Name() if !entry.IsDir() || !strings.HasPrefix(strings.TrimPrefix(name, "."), stagingPrefix) || !isRestoreStagingName(name) { continue } info, err := entry.Info() if err != nil { continue } if info.ModTime().After(stagingCutoff) { continue } stagingDir := filepath.Join(volumesRoot, name) // adpanel:restore-staging-gc - never RemoveAll a candidate that is // (or looks like) a live server: skip it loudly for the operator. if a.dirHasServerMeta(stagingDir) { a.logf("Backup orphan janitor: skipped stale restore-staging dir %s: it carries a server meta file and may be a LIVE server named like a staging sibling, not removing", stagingDir) continue } if err := removeAllWritable(stagingDir); err != nil { a.logf("Backup orphan janitor: failed to remove stale restore-staging dir %s: %v", stagingDir, err) continue } a.logf("Backup orphan janitor: removed stale restore-staging dir %s (mtime %s older than %s)", stagingDir, info.ModTime().Format(time.RFC3339), restoreStagingAgeThreshold) } } func (a *Agent) handleBackupsList(w http.ResponseWriter, r *http.Request, serverName string) { backupsDir := a.serverBackupsDir(serverName) // adpanel:backup-orphan-janitor - sweep before listing: this handler runs // on every panel list, so the sweep is cheap and the crash-orphans the // listing below would silently drop (while backupsMax and the du quotas // still count them) are finally reclaimed. a.sweepOrphanBackups(serverName, backupsDir) entries, err := os.ReadDir(backupsDir) if err != nil { if os.IsNotExist(err) { jsonWrite(w, 200, map[string]any{"ok": true, "backups": []any{}}) return } jsonWrite(w, 500, map[string]any{"error": err.Error()}) return } // adpanel:backup-list-cap - bound the per-request work like every other // bulk operation (maxDirListEntries). ReadDir order is filesystem // dependent, so sort by name before truncating to keep the cap // deterministic; backup ids start with unixmilli, so name order is // chronological. if len(entries) > maxDirListEntries { sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() }) entries = entries[:maxDirListEntries] } var backups []BackupMeta for _, entry := range entries { if !entry.IsDir() { continue } backupDir := filepath.Join(backupsDir, entry.Name()) meta := a.loadBackupMeta(backupDir) if meta != nil { backups = append(backups, *meta) } } // Newest first, same order as the previous bubble sort. sort.Slice(backups, func(i, j int) bool { return backups[i].CreatedAt > backups[j].CreatedAt }) jsonWrite(w, 200, map[string]any{"ok": true, "backups": backups}) } // backupCreateCallerWaitBudget matches the panel's backup-create relay // (nodes.js performPanelCreateBackup: 630000ms — 30s slack over // backupCreateCallerWaitBudget so a copy completing just past the daemon // boundary still receives its response). // The create snapshots the server's disk usage and then copyDirs the whole // server dir — disk-bound with only a quota check — so a large server // legitimately outlasts the server-wide 120s WriteTimeout. const backupCreateCallerWaitBudget = 10 * time.Minute func (a *Agent) handleBackupsCreate(w http.ResponseWriter, r *http.Request, serverName string) { serverDir := a.serverDir(serverName) if _, err := os.Stat(serverDir); err != nil { jsonWrite(w, 404, map[string]any{"error": "server not found"}) return } // adpanel:backup-race - hold the per-server op lock (same one as // start/stop/restart/kill, create/delete-server, import-tar and reinstall) // across the usage snapshot, the backupsMax count, // and the copy, so concurrent creates cannot validate against the same // snapshot and jointly overshoot. Fail fast with 409 instead of queueing: // the panel relay times out on long copies and the retry must never stack // a second concurrent backup behind this one. opMu := a.tryLockServerOp(serverName) if opMu == nil { jsonWrite(w, 409, backupOpConflictBody(a, serverName)) return } defer opMu.Unlock() // adpanel:backup-quota-lock - the usage snapshot below is only meaningful // if no other quota-accounted write (upload, editor save, extract, // apply-version, import) commits bytes into this scope before the copyDir // lands: backups count toward the same quota, so hold the per-scope // upload lock across the whole snapshot->count->copy window (see the // lockUploadScope contract). unlock := a.lockRequestUploadScope(w, r, serverDir) if unlock == nil { return } defer unlock() // Mark busy before any work: power ops and reinstall check this and 409 // instead of queueing behind the long hold. Deferred deletes run LIFO, // i.e. before the Unlock defer above, so the marker never outlives the // lock. a.beginLongOp(serverName, longOpBackup) defer a.endLongOp(serverName) // Long op: the usage walk, the backupsMax count, and the full copyDir of // the server dir below all run before the first response byte — see // backupCreateCallerWaitBudget (ignored on writers without deadline // support, e.g. httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(backupCreateCallerWaitBudget)) // adpanel:backup-storage - a backup is a full copy of the server's files, so // it consumes roughly the current server-file size on top of the already // occupied storage (files + existing backups). Reject up front when that // projected total would exceed the storage limit, so we never start an // expensive copy that would blow past the quota. // adpanel:backup-du-hardlinks — the projection must cost what copyDir // WRITES (per-name full copies), not what the tree physically shares // (hardlinked inodes counted once by du -sb): a hardlink farm of N names // over one S-byte file measured at S lets N×S backup bytes through the // pre-checks to abort mid-copy on limited servers (or overshoot until the // physical disk fills on limit-free ones). checkDiskLimit, // checkDiskCapacity and the copy budget below all consume THIS number. projectedBackupBytes := a.getServerDiskUsagePerName(serverDir) if diskErr := a.checkDiskLimit(serverDir, projectedBackupBytes); diskErr != nil { jsonWrite(w, 507, diskErr) return } // adpanel:multidisk - create previously enforced only the opt-in per-server // limit above, skipping the secondary-disk LimitGb ceiling that restore and // every fs write enforce; mirror restore's check here (no-op on primary // disks). backupDisk is kept for the copy-budget arming below: it is the // SAME disk resolution that ceiling check just validated against. backupDisk := a.diskForServer(serverName) if capErr := a.checkDiskCapacity(backupDisk, projectedBackupBytes); capErr != nil { jsonWrite(w, 507, capErr) return } // adpanel:backup-copy-budget - the pre-checks above validated the // projection (server files + existing backups + projected backup) against // the caps, but the copy below runs while the container keeps running (the // op/upload locks only stop daemon writers), so a chatty server can // outgrow the validated projection mid-copy and nothing detected it. Arm a // mid-copy budget of projection + slack whenever the projection was // validated against ANY cap — the opt-in per-server limit (checkDiskLimit // above) OR the per-disk LimitGb ceiling (checkDiskCapacity above, // adpanel:multidisk) — so a mid-copy grower cannot blow past a validated // ceiling on either axis. The cap is deliberately relative to the // validated projection rather than the limit itself, which is what lets // one budget serve both axes: each pre-check owns its own axis, and this // budget bounds growth beyond what they validated. With neither bound, // the copy remains unlimited. backupLimitBytes := a.getServerDiskLimitBytes(serverDir) var copyBudget []int64 if backupLimitBytes > 0 || diskCapacityCeilingBytes(backupDisk) > 0 { copyBudget = []int64{projectedBackupBytes + backupCopyBudgetSlack} } // adpanel:backup-cap-fallback — resolve the count ceiling: meta's // resources.backupsMax (written on server create and on a resources // PATCH) wins unchanged when present and positive; ONLY when meta carries // no positive backupsMax does the request-supplied fallback apply, read // from the X-ADPanel-Backups-Max request header (naming precedent: // X-ADPanel-Server-Bytes). The fallback travels as a header, NOT a JSON // body field: readJSON decodes with DisallowUnknownFields and this // handler ignores its error, so a new body field would fail the whole // decode on an older daemon (Name/Description would stay empty and the // create would break) — unknown headers are ignored entirely, so the // header is backward-compatible in BOTH rolling-upgrade directions (new // panel → old daemon, old panel → new daemon). Atoi accepts only plain // positive integers: empty/whitespace/garbage parse to no fallback. // Without this fallback the gate below enforced nothing for a pre-feature // server (no resources edit ever transmitted backupsMax into meta), so // two creates serialized by the per-server op lock still landed at 51+ — // the panel and scheduler relays now transmit their cap on every create. // Direct daemon callers that omit the header keep today's behavior // exactly: effectiveBackupsMax stays 0 and the gate is off (unlimited). meta := a.loadMeta(serverDir) effectiveBackupsMax := 0 if resources, ok := meta["resources"].(map[string]any); ok { if backupsMaxRaw, ok := resources["backupsMax"]; ok { var metaBackupsMax int switch v := backupsMaxRaw.(type) { case float64: metaBackupsMax = int(v) case int: metaBackupsMax = v case int64: metaBackupsMax = int(v) } if metaBackupsMax > 0 { effectiveBackupsMax = metaBackupsMax } } } if effectiveBackupsMax == 0 { if headerBackupsMax, err := strconv.Atoi(r.Header.Get("X-ADPanel-Backups-Max")); err == nil && headerBackupsMax > 0 { effectiveBackupsMax = headerBackupsMax } } if effectiveBackupsMax > 0 { backupsDir := a.serverBackupsDir(serverName) entries, err := os.ReadDir(backupsDir) trashName := filepath.Base(deletionTrashDir(backupsDir)) currentCount := 0 if err == nil { for _, e := range entries { if e.IsDir() && e.Name() != trashName { currentCount++ } } } if currentCount >= effectiveBackupsMax { jsonWrite(w, 403, map[string]any{ "error": "backup_limit_reached", "message": fmt.Sprintf("Maximum backup limit reached (%d/%d). Delete old backups to create new ones.", currentCount, effectiveBackupsMax), "current": currentCount, "max": effectiveBackupsMax, }) return } } var body struct { Name string `json:"name"` Description string `json:"description"` } _ = readJSON(w, r, 1024*1024, &body) backupId := fmt.Sprintf("%d_%s", time.Now().UnixMilli(), randomHex(6)) backupDir := filepath.Join(a.serverBackupsDir(serverName), backupId) if err := ensureDir(backupDir); err != nil { jsonWrite(w, 500, map[string]any{"error": "failed to create backup directory"}) return } dataDir := filepath.Join(backupDir, "data") if err := ensureDir(dataDir); err != nil { jsonWrite(w, 500, map[string]any{"error": "failed to create data directory"}) return } // adpanel:backup-live-copy-mark - one fast inspect before the copy (a // single docker inspect on a short ctx, mirroring the restore's // live-wipe-guard usage; placed after the quota checks and before the // copyDir so it cannot eat into the caller-wait budget materially). A // container that is up makes this a HOT copy: files may be mid-write and // the result torn. An ambiguous Docker state is conservatively // marked hot. The mark flows into backup.json and every list response via // BackupMeta.Live; Status/UI/pruning are untouched. hotCtx, hotCancel := context.WithTimeout(context.Background(), 10*time.Second) running, stateErr := a.docker.inspectRunning(hotCtx, serverName) hotCancel() hotCopy := running || stateErr != nil if hotCopy { a.logf("Backup %s for server %s: container may be running, hot copy may be torn", backupId, serverName) } if err := copyDir(serverDir, dataDir, true, copyBudget...); err != nil { _ = removeAllWritable(backupDir) if errors.Is(err, errCopyBudgetExceeded) { // adpanel:backup-copy-budget - the copy blew past the validated // projection + slack (server files grew during the copy). The // partial backup is removed above; surface the SAME 507 // disk_limit_exceeded body shape checkDiskLimit writes (built by // the shared diskLimitExceededBody helper so the settled panel // pass-through surfaces it as quota, never as a masked generic), // with the message naming the actual cause. usedBytes is re-walked // AFTER the RemoveAll cleanup above, so it reports the // post-cleanup usage — exactly what checkDiskLimit reports for // the surviving tree (the server may still be UNDER its limit; // the abort was caused by the growth, hence the growth-specific // message below — the settled panel whitelist keys only on the // error code, so the message override is safe). usedBytes := a.getServerTotalUsage(serverDir) jsonWrite(w, 507, diskLimitExceededBody(usedBytes, backupLimitBytes, fmt.Sprintf("Backup copy aborted: server files grew during the copy. Used: %.1f MB / %.1f MB (limit %.1f MB).", float64(usedBytes)/(1024*1024), float64(backupLimitBytes)/(1024*1024), float64(backupLimitBytes)/(1024*1024)))) return } jsonWrite(w, 500, map[string]any{"error": "failed to copy server files: " + err.Error()}) return } size := getDirSize(dataDir) backupName := strings.TrimSpace(body.Name) if backupName == "" { backupName = fmt.Sprintf("Backup %s", time.Now().Format("2006-01-02 15:04")) } // adpanel:backup-field-cap - the panel clamps name to 120 and description // to 500 chars; clamp by runes here too so an oversized payload (up to the // 1MB readJSON cap) can't be stored verbatim into backup.json and echoed // back in list responses. The default name above is far below the cap. if runes := []rune(backupName); len(runes) > 120 { backupName = string(runes[:120]) } backupDescription := strings.TrimSpace(body.Description) if runes := []rune(backupDescription); len(runes) > 500 { backupDescription = string(runes[:500]) } backupMeta := &BackupMeta{ ID: backupId, Name: backupName, Description: backupDescription, ServerName: serverName, CreatedAt: time.Now().UnixMilli(), Size: size, Status: "complete", Live: hotCopy, } if err := a.saveBackupMeta(backupDir, backupMeta); err != nil { _ = removeAllWritable(backupDir) jsonWrite(w, 500, map[string]any{"error": "failed to save backup metadata"}) return } a.logf("Created backup %s for server %s (size: %d bytes)", backupId, serverName, size) jsonWrite(w, 200, map[string]any{"ok": true, "backup": backupMeta}) } // backupRestoreCallerWaitBudget matches the panel's backup-restore relay // (nodes.js performPanelRestoreBackup: 1830000ms = this budget plus the same // 30s slack the create relay keeps). A restore optionally wipes the server dir // and copies the whole backup back — the longest copy the panel relays — so it // legitimately outlasts the server-wide 120s WriteTimeout. const backupRestoreCallerWaitBudget = 30 * time.Minute func (a *Agent) handleBackupsRestore(w http.ResponseWriter, r *http.Request, serverName, backupId string) { if !validateBackupId(backupId) { jsonWrite(w, 400, map[string]any{"error": "invalid backup id format"}) return } backupDir := filepath.Join(a.serverBackupsDir(serverName), backupId) dataDir := filepath.Join(backupDir, "data") if _, err := os.Stat(dataDir); err != nil { jsonWrite(w, 404, map[string]any{"error": "backup not found"}) return } var body struct { DeleteOldFiles bool `json:"deleteOldFiles"` } _ = readJSON(w, r, 1024, &body) serverDir := a.serverDir(serverName) // adpanel:backup-race - hold the per-server op lock (same one as // start/stop/restart/kill, create/delete-server, import-tar and reinstall) // across the usage checks, the stop, the optional // wipe, and the copy, so concurrent restores cannot interleave two copyDir // writers into serverDir and a wipe cannot race a concurrent create's // snapshot. Fail fast with 409 instead of queueing: the panel relay times // out on long copies and the retry must never stack a second concurrent // operation behind this one. opMu := a.tryLockServerOp(serverName) if opMu == nil { jsonWrite(w, 409, backupOpConflictBody(a, serverName)) return } defer opMu.Unlock() // adpanel:backup-race - re-check under the op lock: the pre-lock stat // above races a concurrent delete (handleBackupsDelete serializes on // this same lock), so a backup removed between the stat and the // acquisition would otherwise pass validation, stop the container and // wipe serverDir (deleteOldFiles) before copyDir fails - leaving a // stopped, emptied server. 404 while nothing has been touched yet. if _, err := os.Stat(dataDir); err != nil { jsonWrite(w, 404, map[string]any{"error": "backup not found"}) return } // Mark busy before any work (see handleBackupsCreate): power ops and // reinstall 409 instead of queueing behind this restore's long hold; the // deferred delete runs before the Unlock defer above (LIFO). a.beginLongOp(serverName, longOpBackup) defer a.endLongOp(serverName) // adpanel:backup-quota-lock - the usage snapshot in the quota checks below // and the copy that commits the restore are only meaningful if no other // quota-accounted write (upload, editor save, extract, apply-version, // import) commits bytes into the server scope in between, so hold the // per-scope upload lock across the checks->stop->stage->wipe->swap window // (see the lockUploadScope contract; every restore now runs the quota // checks — adpanel:restore-quota — and every restore commits/moves // quota-accounted bytes, so the lock is unconditional). unlock := a.lockRequestUploadScope(w, r, serverDir) if unlock == nil { return } defer unlock() // Long op: the backup-size walk, the quota checks, the docker stop, the // staging copy, the optional wipe and the swap (or the merge copyDir) all // run before the first response byte — see backupRestoreCallerWaitBudget // (ignored on writers without deadline support, e.g. // httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(backupRestoreCallerWaitBudget)) // adpanel:restore-quota - EVERY restore runs both quota checks, projected // on backupSize = getDirSizeBytes(dataDir). For a merge-restore that is the // current+backupSize projection, exactly as before. For a wipe-restore the // honest conservative projection while the old content still exists is // ALSO current+backupSize: the pre-wipe peak holds the old server files // AND the staged copy on the same disk at the same time (backups constant), // so checking the same extra size BEFORE anything destructive runs refuses // an over-quota restore with the untouched 507 shapes instead of // discovering the overshoot after a wipe. A restore that would only fit // AFTER the wipe is refused — that is the deliberate price of refusing // before touching anything. backupSize, _ := getDirSizeBytes(dataDir) if diskErr := a.checkDiskLimit(serverDir, backupSize); diskErr != nil { jsonWrite(w, 507, diskErr) return } // adpanel:multidisk - backups live on the server's disk; enforce per-disk // capacity (no-op on primary / unlimited disks). if capErr := a.checkDiskCapacity(a.diskForServer(serverName), backupSize); capErr != nil { jsonWrite(w, 507, capErr) return } // adpanel:restore-refusal-recovery — the two mutations below (`docker // update --restart=no` + `docker stop`) run BEFORE the live-wipe-guard // verification and before every staging/swap/merge failure exit, so a // refused or failed restore would leave the container with its restart // policy mangled to "no" (and stopped) until someone recreates or // reconfigures the server — a refused restore must not silently take a // busy server offline. Capture the pre-restore policy and running state // (best-effort: an unknown capture leaves recovery inert), then on every // exit that does not complete the restore, put the container back the // way it was found: re-apply the captured policy and, when it was // running pre-restore and is not running at recovery time, start it // again. Recovery is best-effort — a recovery failure is logged loudly // and never masks the original 409/failure response — and runs under the // same op/upload serialization (the defer below executes LIFO ahead of // the lock-releasing defers). The success path is excluded: // restoreSucceeded is set only on the 200, and container recreation // re-applies the desired policy (updateRestartPolicy's caller in the // provisioning flow). capCtx, capCancel := context.WithTimeout(context.Background(), 10*time.Second) capturedPolicy := a.docker.inspectRestartPolicy(capCtx, serverName) wasRunning, stateErr := a.docker.inspectRunning(capCtx, serverName) capCancel() if stateErr != nil { jsonWrite(w, 409, map[string]any{"error": "could not confirm container state before restore"}) return } recoverRefusedRestore := func() { recCtx, recCancel := context.WithTimeout(context.Background(), 10*time.Second) defer recCancel() if capturedPolicy != "" { a.docker.updateRestartPolicy(recCtx, serverName, capturedPolicy) } if !wasRunning { return } running, inspectErr := a.docker.inspectRunning(recCtx, serverName) if inspectErr != nil { a.logf("Restore of backup %s for server %s: could not verify running state during recovery: %v - check the server status", backupId, serverName, inspectErr) return } if running { return } startCtx, startCancel := context.WithTimeout(context.Background(), 15*time.Second) _, _, _, startErr := a.docker.runCollect(startCtx, "start", dockerContainerName(serverName)) startCancel() if startErr != nil { a.logf("Restore of backup %s for server %s: refused/failed after stopping the container and recovery could not restart it (was running pre-restore, restart policy %q): %v - start it manually", backupId, serverName, capturedPolicy, startErr) return } a.logf("Restore of backup %s for server %s: refused/failed after stopping the container; recovered it to its pre-restore state (running, restart policy %q)", backupId, serverName, capturedPolicy) } // The recovery defer gates on mutatedContainer so the pre-mutation exits // (quota 507s, 404s, op-lock 409) never trigger it, and on // !restoreSucceeded so the success path is untouched. mutatedContainer := false restoreSucceeded := false defer func() { if mutatedContainer && !restoreSucceeded { recoverRefusedRestore() } }() mutatedContainer = true ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) a.docker.updateRestartNo(ctx, serverName) a.docker.stop(ctx, serverName) cancel() // adpanel:live-wipe-guard - confirm the stop on a fresh context before // staging or writing any server files. An unconfirmed stop is not safe. checkCtx, checkCancel := context.WithTimeout(context.Background(), 10*time.Second) stillRunning, stateErr := a.docker.inspectRunning(checkCtx, serverName) checkCancel() if stateErr != nil { jsonWrite(w, 409, map[string]any{"error": "could not confirm the container stopped; no server files were changed"}) return } if stillRunning { jsonWrite(w, 409, map[string]any{"error": "container is still running; aborting restore to avoid wiping a live server"}) return } if body.DeleteOldFiles { // adpanel:restore-staging — stage beside the live tree so the whole // replacement can be committed without deleting any live entry first. stagingDir, err := createServerStagingDir(serverDir) if err != nil { jsonWrite(w, 500, map[string]any{"error": "failed to create restore staging directory"}) return } if sameDev, devErr := sameDevice(serverDir, stagingDir); devErr != nil || !sameDev { _ = removeAllWritable(stagingDir) jsonWrite(w, 500, map[string]any{"error": "failed to restore backup: staging directory is not on the server directory's filesystem"}) return } // adpanel:backup-copy-budget - the staging copy carries the same // mid-transfer budget discipline as backup create: the measured // backupSize plus slack is the projection, growth beyond it aborts // the copy (the backup's data dir is static, so a breach means the // measurement or the copy went wrong — either way, do not proceed). stagingBudgetCap := backupSize + backupCopyBudgetSlack if err := copyDir(dataDir, stagingDir, true, stagingBudgetCap); err != nil { _ = removeAllWritable(stagingDir) jsonWrite(w, 500, map[string]any{"error": "failed to stage backup for restore: " + err.Error()}) return } if err := swapStagedRestore(stagingDir, serverDir); err != nil { _ = removeAllWritable(stagingDir) a.logf("Restore of backup %s for server %s: atomic exchange refused: %v", backupId, serverName, err) jsonWrite(w, 500, map[string]any{"error": "could not atomically replace server files; existing files were not changed"}) return } if err := removeAllWritable(stagingDir); err != nil { a.logf("Restored backup %s for server %s, but could not remove previous files at %s: %v", backupId, serverName, stagingDir, err) } } else { // Merge-restore: unchanged in-place copy semantics — an additive merge // has no wipe to protect (a copy failure leaves the old files mixed // with some restored files, as before), and staging a merge would need // directory merging that rename(2) refuses (ENOTEMPTY on dir-over-dir) // — out of scope here. if err := copyDir(dataDir, serverDir, false); err != nil { jsonWrite(w, 500, map[string]any{"error": "failed to restore backup: " + err.Error()}) return } } a.logf("Restored backup %s for server %s (deleteOldFiles=%v)", backupId, serverName, body.DeleteOldFiles) restoreSucceeded = true jsonWrite(w, 200, map[string]any{"ok": true}) } // backupDeleteCallerWaitBudget matches the panel's backup-delete relay // (nodes.js performPanelDeleteBackup: 330000ms = this budget plus the same // 30s slack the create relay keeps). The os.RemoveAll of a large backup tree // is disk-bound and can outlast the server-wide 120s WriteTimeout. const backupDeleteCallerWaitBudget = 5 * time.Minute func (a *Agent) handleBackupsDelete(w http.ResponseWriter, r *http.Request, serverName, backupId string) { if !validateBackupId(backupId) { jsonWrite(w, 400, map[string]any{"error": "invalid backup id format"}) return } backupDir := filepath.Join(a.serverBackupsDir(serverName), backupId) if _, err := os.Stat(backupDir); err != nil { jsonWrite(w, 404, map[string]any{"error": "backup not found"}) return } // adpanel:backup-race - serialize with create/restore on the per-server op // lock so a delete cannot remove a backup directory out from under an // in-flight create/restore copy. Fail fast with 409 instead of queueing so // a relay retry can never stack a second concurrent operation. opMu := a.tryLockServerOp(serverName) if opMu == nil { jsonWrite(w, 409, backupOpConflictBody(a, serverName)) return } defer opMu.Unlock() // Mark busy before any work (see handleBackupsCreate): power ops and // reinstall 409 instead of queueing behind a large RemoveAll; the deferred // delete runs before the Unlock defer above (LIFO). a.beginLongOp(serverName, longOpBackup) defer a.endLongOp(serverName) // Long op: the os.RemoveAll of the backup tree is disk-bound and can // outlive the server-wide WriteTimeout — see backupDeleteCallerWaitBudget // (ignored on writers without deadline support, e.g. // httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(backupDeleteCallerWaitBudget)) if err := a.deleteBackupTree(backupDir); err != nil { a.logf("Could not detach backup %s for server %s: %v", backupId, serverName, err) jsonWrite(w, 500, map[string]any{"error": "failed to delete backup"}) return } a.logf("Deleted backup %s for server %s", backupId, serverName) jsonWrite(w, 200, map[string]any{"ok": true}) } func randomHex(n int) string { b := make([]byte, n) _, _ = rand.Read(b) return hex.EncodeToString(b) } func validateBackupId(id string) bool { if id == "" || len(id) > 64 { return false } for _, c := range id { if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') { return false } } return true } // adpanel:backup-copy-budget — errCopyBudgetExceeded aborts a budgeted copyDir // before a write can exceed its byte allowance. An absent budget is unlimited. var errCopyBudgetExceeded = errors.New("copy budget exceeded") // adpanel:backup-copy-budget — slack a mid-copy budget tolerates over the // validated projection. The pre-check (checkDiskLimit / checkDiskCapacity) // validated used + projection against the cap before the copy started, so // growth of the SOURCE beyond projection + slack is what the budget aborts on: // large enough to absorb the du-vs-walk skew of a quiet server, far below any // meaningful overshoot of a chatty one. const backupCopyBudgetSlack = 16 << 20 // adpanel:import-extract-budget — errImportExtractBudgetExceeded aborts a // budgeted extractTarSafeRouted mid-walk, mirroring errCopyBudgetExceeded's // contract for copyDir: the import-tar handler arms the budget when the quota // pre-checks validated a cap (per-server limit OR per-disk ceiling), matches // the sentinel with errors.Is and maps it to the shared 507 // disk_limit_exceeded body plus the partial-extract cleanup. A nil budget // means unlimited and behaves exactly as before. var errImportExtractBudgetExceeded = errors.New("import extract budget exceeded") // sameDevice reports whether two existing paths live on the same filesystem, // so an os.Rename between them is atomic instead of failing EXDEV. func sameDevice(aPath, bPath string) (bool, error) { var sta, stb syscall.Stat_t if err := syscall.Stat(aPath, &sta); err != nil { return false, err } if err := syscall.Stat(bPath, &stb); err != nil { return false, err } return sta.Dev == stb.Dev, nil } // --- adpanel:multidisk:registry (anchor) --- // // Disk registry, layout helpers, per-server routing, capacity checks and the // admin API. All of this is dormant until an additional disk is registered: with // only the primary disk, every helper resolves to the existing a.volumesDir / // a.backupsDir() paths, so behavior is identical to single-disk and no migration // is required. const primaryDiskID = "primary" // diskLayoutVolumes returns the volumes root for a given mount path. // For the primary mount (a.dataRoot) this equals a.volumesDir exactly. func (a *Agent) diskLayoutVolumes(mountPath string) string { if filepath.Clean(mountPath) == filepath.Clean(a.dataRoot) { return a.volumesDir } return filepath.Join(filepath.Clean(mountPath), "adpanel", "volumes") } // diskLayoutBackups returns the backups root for a given mount path. // For the primary mount this equals a.backupsDir() exactly. func (a *Agent) diskLayoutBackups(mountPath string) string { if filepath.Clean(mountPath) == filepath.Clean(a.dataRoot) { return a.backupsDir() } return filepath.Join(filepath.Clean(mountPath), "adpanel", "backups") } // primaryDisk returns the synthetic primary disk descriptor. func (a *Agent) primaryDisk() NodeDisk { return NodeDisk{ID: primaryDiskID, MountPath: filepath.Clean(a.dataRoot), Primary: true} } // registeredDisks returns the persisted additional disks (never the primary). func (a *Agent) registeredDisks() []NodeDisk { info := a.readNodeInformation() out := make([]NodeDisk, 0, len(info.Disks)) for _, d := range info.Disks { if strings.TrimSpace(d.ID) == "" || d.Primary || d.ID == primaryDiskID { continue } if strings.TrimSpace(d.MountPath) == "" { continue } out = append(out, d) } return out } // allDisks returns the primary disk first, then all registered additional disks. func (a *Agent) allDisks() []NodeDisk { disks := []NodeDisk{a.primaryDisk()} disks = append(disks, a.registeredDisks()...) return disks } // diskByID resolves a disk descriptor by its ID. Empty or "primary" => primary. func (a *Agent) diskByID(id string) (NodeDisk, bool) { id = strings.TrimSpace(id) if id == "" || id == primaryDiskID { return a.primaryDisk(), true } for _, d := range a.registeredDisks() { if d.ID == id { return d, true } } return NodeDisk{}, false } // diskForServer returns the disk that owns a server, based on its persisted meta. // Absent/unknown diskId defaults to the primary disk (back-compat). Results are // cached to avoid a meta read on every FS request. func (a *Agent) diskForServer(name string) NodeDisk { name = sanitizeName(name) if name == "" { return a.primaryDisk() } a.disksMu.RLock() if a.serverDiskCache != nil { if id, ok := a.serverDiskCache[name]; ok { a.disksMu.RUnlock() if d, ok := a.diskByID(id); ok { return d } return a.primaryDisk() } } a.disksMu.RUnlock() // Meta always lives on the primary disk's .adpanel_meta, independent of where // the server files reside, so this read is disk-location agnostic. id := primaryDiskID hasExplicitDiskID := false metaPath := a.metaPath(name) if b, err := os.ReadFile(metaPath); err == nil { var m map[string]any if json.Unmarshal(b, &m) == nil { if v, ok := m["__diskId"].(string); ok && strings.TrimSpace(v) != "" { id = strings.TrimSpace(v) hasExplicitDiskID = true } } } // adpanel:multidisk - legacy/back-compat recovery. Servers created before // __diskId was persisted (or whose meta lost it) have no disk assignment in // meta, so they would default to the primary disk even when their files // physically live on a secondary disk. That mis-routing made delete/reinstall // target the (empty) primary path, report success, and ORPHAN the real files // + backups on the secondary disk. When meta carries no explicit __diskId, // locate the server by scanning each registered disk's volumes root for its // directory and adopt the owning disk. This is only hit on a cold cache for // unassigned servers, so the cost is bounded. if !hasExplicitDiskID { if disk, found := a.locateServerDiskByScan(name); found { id = disk.ID } } a.disksMu.Lock() if a.serverDiskCache == nil { a.serverDiskCache = map[string]string{} } a.serverDiskCache[name] = id a.disksMu.Unlock() if d, ok := a.diskByID(id); ok { return d } return a.primaryDisk() } // locateServerDiskByScan finds which registered disk physically holds a server's // directory. It is used as a back-compat fallback for servers whose meta has no // persisted __diskId (created before multidisk routing). Secondary disks are // checked first so a real secondary-disk server is correctly adopted; if the // directory only exists on the primary disk (or nowhere), it reports not-found // and the caller keeps the primary default. The first match wins. func (a *Agent) locateServerDiskByScan(name string) (NodeDisk, bool) { safe := sanitizeName(name) if safe == "" { return NodeDisk{}, false } for _, d := range a.registeredDisks() { candidate := filepath.Join(a.diskLayoutVolumes(d.MountPath), safe) if st, err := os.Stat(candidate); err == nil && st.IsDir() { return d, true } } return NodeDisk{}, false } // invalidateServerDiskCache drops a cached server->disk mapping (after create/delete). func (a *Agent) invalidateServerDiskCache(name string) { name = sanitizeName(name) a.disksMu.Lock() if a.serverDiskCache != nil { delete(a.serverDiskCache, name) } a.disksMu.Unlock() } // setServerDiskMapping records a server's disk assignment in the routing cache. func (a *Agent) setServerDiskMapping(name, diskID string) { name = sanitizeName(name) if name == "" { return } if strings.TrimSpace(diskID) == "" { diskID = primaryDiskID } a.disksMu.Lock() if a.serverDiskCache == nil { a.serverDiskCache = map[string]string{} } a.serverDiskCache[name] = diskID a.disksMu.Unlock() } // diskCapacityCeilingBytes resolves the per-disk capacity ceiling (LimitGb) a // disk carries, in bytes, with the SAME rule checkDiskCapacity (below) // enforces: the primary disk and disks with LimitGb<=0 are unlimited (0). // checkDiskCapacity itself must walk the disk's usage to decide a breach, so // it cannot cheaply answer "was a ceiling in force at all"; callers that just // validated a projection through checkDiskCapacity (e.g. handleBackupsCreate's // adpanel:multidisk pre-check, arming the adpanel:backup-copy-budget) use this // to re-arm enforcement for the SAME ceiling without a second walk. The no-op // cases and the GiB conversion MUST stay in exact lockstep with // checkDiskCapacity — the ceiling it enforces is exactly the non-zero value // this returns. func diskCapacityCeilingBytes(disk NodeDisk) int64 { if disk.Primary || disk.ID == primaryDiskID || disk.LimitGb <= 0 { return 0 } return disk.LimitGb * 1024 * 1024 * 1024 } // checkDiskCapacity enforces a per-disk capacity ceiling (LimitGb). It is a no-op // for the primary disk and for disks with LimitGb<=0. used = volumes + backups. func (a *Agent) checkDiskCapacity(disk NodeDisk, extraBytes int64) map[string]any { if disk.Primary || disk.ID == primaryDiskID || disk.LimitGb <= 0 { return nil } limitBytes := disk.LimitGb * 1024 * 1024 * 1024 volBytes, _ := getDirSizeBytes(a.diskLayoutVolumes(disk.MountPath)) bkBytes, _ := getDirSizeBytes(a.diskLayoutBackups(disk.MountPath)) used := volBytes + bkBytes if used+extraBytes > limitBytes { return map[string]any{ "error": "disk_capacity_exceeded", "message": fmt.Sprintf("Target disk is full. Used: %.1f GB / %d GB", float64(used)/(1024*1024*1024), disk.LimitGb), "usedBytes": used, "limitBytes": limitBytes, } } return nil } // checkDiskCapacityForPath finds the owning disk of abs and enforces its capacity. func (a *Agent) checkDiskCapacityForPath(abs string, extraBytes int64) map[string]any { root := a.volumeRootFor(abs) for _, d := range a.allDisks() { if filepath.Clean(a.diskLayoutVolumes(d.MountPath)) == root { return a.checkDiskCapacity(d, extraBytes) } } return nil } // diskCapacityAllowanceForPath returns how many more bytes the disk owning abs // accepts before hitting its configured per-disk capacity ceiling (LimitGb). // It mirrors checkDiskCapacity's no-op cases: the primary disk, disks without // a limit and paths on no known disk are unlimited (limited=false), so the // quota snapshot is only taken where a ceiling actually exists. The usage // number is a filesystem walk, so like uploadDiskAllowanceForPath it is only // a snapshot: CALLERS MUST hold the destination scope's upload lock // (a.lockUploadScope(...)) across the snapshot -> transfer -> commit window. func (a *Agent) diskCapacityAllowanceForPath(abs string) (allowedBytes, usedBytes, limitBytes int64, limited bool, diskErr map[string]any) { root := a.volumeRootFor(abs) for _, d := range a.allDisks() { if filepath.Clean(a.diskLayoutVolumes(d.MountPath)) != root { continue } if d.Primary || d.ID == primaryDiskID || d.LimitGb <= 0 { return 0, 0, 0, false, nil } limitBytes = d.LimitGb * 1024 * 1024 * 1024 volBytes, _ := getDirSizeBytes(a.diskLayoutVolumes(d.MountPath)) bkBytes, _ := getDirSizeBytes(a.diskLayoutBackups(d.MountPath)) usedBytes = volBytes + bkBytes if usedBytes >= limitBytes { return 0, usedBytes, limitBytes, true, a.checkDiskCapacity(d, 0) } return limitBytes - usedBytes, usedBytes, limitBytes, true, nil } return 0, 0, 0, false, nil } // pathAllowedForDisk rejects dangerous mount paths for new disks. func pathAllowedForDisk(p string) (string, error) { s := strings.TrimSpace(p) if s == "" { return "", fmt.Errorf("mount path required") } if !filepath.IsAbs(s) { return "", fmt.Errorf("mount path must be absolute") } c := filepath.Clean(s) if c != s { return "", fmt.Errorf("mount path must be clean (no '.', '..', or trailing slash)") } // Mirrors utils/disk-mount-validation.js on the panel — keep in sync. // /var/lib covers the daemon's own /var/lib/node tree; /run and /var/run // are the same tmpfs. denied := []string{"/", "/var/lib", "/var/log", "/var/run", "/run", "/srv", "/opt", "/tmp", "/home", "/etc", "/proc", "/sys", "/dev", "/boot", "/root", "/bin", "/sbin", "/usr", "/lib", "/lib64"} // Plain prefix comparison (not isUnder): isUnder("/", c) is true for every // absolute path, which would reject all mounts. On already-clean paths the // prefix form is exact and matches the panel's startsWith(d + "/") check. for _, d := range denied { if c == d || strings.HasPrefix(c, d+"/") { return "", fmt.Errorf("mount path %q is not allowed", c) } } return c, nil } func (a *Agent) handleDiskList(w http.ResponseWriter, r *http.Request) { out := make([]map[string]any, 0) for _, d := range a.allDisks() { volBytes, _ := getDirSizeBytes(a.diskLayoutVolumes(d.MountPath)) bkBytes, _ := getDirSizeBytes(a.diskLayoutBackups(d.MountPath)) usedGb := float64(volBytes+bkBytes) / (1024 * 1024 * 1024) entry := map[string]any{ "id": d.ID, "mountPath": d.MountPath, "limitGb": d.LimitGb, "usedGb": usedGb, "primary": d.Primary || d.ID == primaryDiskID, "freeMb": freeDiskMb(d.MountPath), } out = append(out, entry) } jsonWrite(w, 200, map[string]any{"ok": true, "disks": out}) } func (a *Agent) handleDiskAdd(w http.ResponseWriter, r *http.Request) { var body struct { MountPath string `json:"mountPath"` LimitGb int64 `json:"limitGb"` } if err := readJSON(w, r, 64*1024, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } mount, err := pathAllowedForDisk(body.MountPath) if err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": err.Error()}) return } if ok, reason := a.verifyNodeAdminRequest(r, "disk-add", mount); !ok { jsonWrite(w, statusForAdminReason(reason), map[string]any{"ok": false, "error": reason}) return } if body.LimitGb <= 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "limitGb must be > 0"}) return } // EvalSymlinks re-check: the real path must also pass the allowlist. if resolved, rErr := filepath.EvalSymlinks(mount); rErr == nil { if _, vErr := pathAllowedForDisk(resolved); vErr != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "resolved mount path not allowed"}) return } } // Capacity sanity: limit cannot exceed currently free space on the mount. freeGb := freeDiskMb(mount) / 1024 if freeGb > 0 && body.LimitGb > freeGb { jsonWrite(w, 400, map[string]any{"ok": false, "error": fmt.Sprintf("limitGb %d exceeds free space %d GB", body.LimitGb, freeGb)}) return } volRoot := a.diskLayoutVolumes(mount) bkRoot := a.diskLayoutBackups(mount) if err := os.MkdirAll(volRoot, 0o750); err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to create volumes dir"}) return } if err := os.MkdirAll(bkRoot, 0o750); err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to create backups dir"}) return } // Real write-probe under /adpanel. probe := filepath.Join(filepath.Clean(mount), "adpanel", ".adpanel_write_probe") if err := os.WriteFile(probe, []byte("ok"), 0o600); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "mount path is not writable"}) return } _ = os.Remove(probe) a.disksMu.Lock() defer a.disksMu.Unlock() info := a.readNodeInformation() for _, d := range info.Disks { if filepath.Clean(d.MountPath) == mount { jsonWrite(w, 409, map[string]any{"ok": false, "error": "disk already registered"}) return } } disk := NodeDisk{ ID: "disk-" + randomHex(8), MountPath: mount, LimitGb: body.LimitGb, CreatedAt: time.Now().UTC().Format(time.RFC3339), } info.Disks = append(info.Disks, disk) if err := a.writeNodeInformation(info); err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to persist disk"}) return } jsonWrite(w, 200, map[string]any{"ok": true, "disk": map[string]any{ "id": disk.ID, "mountPath": disk.MountPath, "limitGb": disk.LimitGb, "primary": false, }}) } func (a *Agent) handleDiskDelete(w http.ResponseWriter, r *http.Request) { var body struct { ID string `json:"id"` } if err := readJSON(w, r, 64*1024, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } id := strings.TrimSpace(body.ID) if id == "" || id == primaryDiskID { jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot remove primary disk"}) return } if ok, reason := a.verifyNodeAdminRequest(r, "disk-remove", id); !ok { jsonWrite(w, statusForAdminReason(reason), map[string]any{"ok": false, "error": reason}) return } disk, found := a.diskByID(id) if !found || disk.Primary { jsonWrite(w, 404, map[string]any{"ok": false, "error": "disk not found"}) return } volRoot := a.diskLayoutVolumes(disk.MountPath) a.disksMu.Lock() defer a.disksMu.Unlock() // adpanel:disk-removal - an unavailable or unreadable disk is not an empty disk. entries, err := os.ReadDir(volRoot) if err != nil { jsonWrite(w, 409, map[string]any{"ok": false, "error": "cannot verify that the disk is empty; check the node mount"}) return } for _, entry := range entries { if entry.Name() != ".adpanel_meta" && entry.Name() != ".adpanel_deleting" { jsonWrite(w, 409, map[string]any{"ok": false, "error": "disk is in use by one or more servers"}) return } } info := a.readNodeInformation() kept := make([]NodeDisk, 0, len(info.Disks)) removed := false for _, d := range info.Disks { if d.ID == id { removed = true continue } kept = append(kept, d) } if !removed { jsonWrite(w, 404, map[string]any{"ok": false, "error": "disk not found"}) return } info.Disks = kept if err := a.writeNodeInformation(info); err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to persist"}) return } jsonWrite(w, 200, map[string]any{"ok": true}) } func updateConfigTokensInYAML(src, newToken string) string { lines := strings.Split(strings.ReplaceAll(src, "\r\n", "\n"), "\n") replaced := false for i, line := range lines { trimmed := strings.TrimSpace(line) if trimmed == "" || strings.HasPrefix(trimmed, "#") { continue } if strings.HasPrefix(trimmed, "token:") || strings.HasPrefix(trimmed, "token :") { indentLen := len(line) - len(strings.TrimLeft(line, " \t")) indent := line[:indentLen] lines[i] = indent + "token: " + newToken replaced = true } } if !replaced { if len(lines) > 0 && lines[len(lines)-1] == "" { lines[len(lines)-1] = "token: " + newToken lines = append(lines, "") } else { lines = append(lines, "token: "+newToken) } } res := strings.Join(lines, "\n") if !strings.HasSuffix(res, "\n") { res += "\n" } return res } func (a *Agent) persistNewTokenToConfig(cfgPath, newToken string) error { if strings.TrimSpace(cfgPath) == "" { return fmt.Errorf("config path is empty") } realPath := cfgPath if resolved, err := filepath.EvalSymlinks(cfgPath); err == nil { realPath = resolved } raw, err := os.ReadFile(realPath) if err != nil { return fmt.Errorf("read config file: %w", err) } updated := updateConfigTokensInYAML(string(raw), newToken) if _, err := parseYAMLSubset(updated); err != nil { return fmt.Errorf("updated config failed validation: %w", err) } dir := filepath.Dir(realPath) tmpFile, err := os.CreateTemp(dir, "config-*.tmp") if err != nil { return fmt.Errorf("create temp file: %w", err) } tmpName := tmpFile.Name() defer func() { _ = os.Remove(tmpName) }() if err := tmpFile.Chmod(0o600); err != nil { _ = tmpFile.Close() return fmt.Errorf("chmod temp file: %w", err) } if _, err := tmpFile.Write([]byte(updated)); err != nil { _ = tmpFile.Close() return fmt.Errorf("write temp file: %w", err) } if err := tmpFile.Sync(); err != nil { _ = tmpFile.Close() return fmt.Errorf("sync temp file: %w", err) } if err := tmpFile.Close(); err != nil { return fmt.Errorf("close temp file: %w", err) } if err := os.Rename(tmpName, realPath); err != nil { return fmt.Errorf("rename temp file to config: %w", err) } _ = os.Chmod(realPath, 0o600) return nil } func (a *Agent) handleTokenRotate(w http.ResponseWriter, r *http.Request) { var body struct { Token string `json:"token"` } if err := readJSON(w, r, 64*1024, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid request body"}) return } newToken := strings.TrimSpace(body.Token) if newToken == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "token is required"}) return } if len(newToken) < 32 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "token too short (minimum 32 characters)"}) return } if !strings.HasPrefix(newToken, "adpnt_") { jsonWrite(w, 400, map[string]any{"ok": false, "error": "token must start with adpnt_ prefix"}) return } cfgPath := a.cfgPath if cfgPath == "" { cfgPath = os.Getenv("ADPANEL_NODE_CONFIG") if cfgPath == "" { cfgPath = DefaultConfigPath } } // Persist to config.yml before swapping in-memory token if err := a.persistNewTokenToConfig(cfgPath, newToken); err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": fmt.Sprintf("failed to persist token: %v", err)}) return } const tokenGraceDuration = 10 * time.Minute a.tokenMu.Lock() a.oldToken = a.token a.oldTokenExp = time.Now().Add(tokenGraceDuration) a.token = newToken a.tokenMu.Unlock() clientIP := getClientIP(r) auditLog.Log("token_rotate", clientIP, "", "agent", "rotate", "success", map[string]any{ "grace_seconds": int(tokenGraceDuration.Seconds()), }) jsonWrite(w, 200, map[string]any{ "ok": true, "graceSeconds": int(tokenGraceDuration.Seconds()), }) } // validPanelHMACSecret restricts rotation payloads to the shapes the panel // actually derives and writes: 32..256 characters of [0-9a-zA-Z]. This // excludes the "|" envelope separator, whitespace, YAML control characters // and shell metacharacters, so the secret cannot smuggle structural meaning // into the signed base string, config.yml, or logs. func validPanelHMACSecret(s string) bool { if len(s) < 32 || len(s) > 256 { return false } for i := 0; i < len(s); i++ { c := s[i] if (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') { continue } return false } return true } // updateConfigHMACInYAML rewrites the panel.hmac_secret entry of a config // document. It replaces an existing entry in place (preserving its // indentation), inserts one directly under the panel: section when the // section exists, and appends a panel: block otherwise. Indentation is // measured exactly like parseYAMLSubset (tabs count as two spaces) so the // updated document always parses the way this function reasoned about it. // The result must still pass parseYAMLSubset before it is persisted. func updateConfigHMACInYAML(src, newSecret string) string { lines := strings.Split(strings.ReplaceAll(src, "\r\n", "\n"), "\n") entry := "hmac_secret: \"" + newSecret + "\"" yamlIndent := func(line string) int { line = strings.ReplaceAll(line, "\t", " ") return len(line) - len(strings.TrimLeft(line, " ")) } // mappingKey splits a line into its key, value remainder and reports // whether the line is a "key:" mapping-section opener (empty value). mappingKey := func(line string) (key, rest string, ok bool) { trimmed := strings.TrimSpace(line) if trimmed == "" || strings.HasPrefix(trimmed, "#") { return "", "", false } colon := strings.Index(trimmed, ":") if colon < 0 { return "", "", false } return strings.TrimSpace(trimmed[:colon]), strings.TrimSpace(trimmed[colon+1:]), true } isPanelKey := func(key string) bool { return key == "panel" } panelIdx := -1 panelIndent := 0 secretIdx := -1 secretIndent := "" for i := 0; i < len(lines); i++ { key, rest, ok := mappingKey(lines[i]) if !ok { continue } indent := yamlIndent(lines[i]) if panelIdx >= 0 && indent <= panelIndent { panelIdx = -1 // a key at parent depth closes the panel block } if panelIdx < 0 { if isPanelKey(key) && (rest == "" || strings.HasPrefix(rest, "#")) { panelIdx = i panelIndent = indent } continue } if key == "hmac_secret" { secretIdx = i // Re-emit the indent as spaces: parseYAMLSubset already treats a // tab as two spaces, so this preserves the mapping depth exactly. secretIndent = strings.Repeat(" ", yamlIndent(lines[i])) } } if secretIdx >= 0 { lines[secretIdx] = secretIndent + entry } else if panelIdx >= 0 { insertAt := panelIdx + 1 lines = append(lines[:insertAt], append([]string{strings.Repeat(" ", panelIndent+2) + entry}, lines[insertAt:]...)...) } else { for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" { lines = lines[:len(lines)-1] } lines = append(lines, "panel:", " "+entry, "") } res := strings.Join(lines, "\n") if !strings.HasSuffix(res, "\n") { res += "\n" } return res } // panelHMACEnvOverride reports whether the process environment pins the panel // signing secret. The env var wins over config.yml at startup, so while it is // set a rotated config secret would be ignored on the next daemon restart. func panelHMACEnvOverride() bool { return strings.TrimSpace(os.Getenv("PANEL_HMAC_SECRET")) != "" } // handlePanelHMACSet rotates the per-node panel admin signing secret // (POST /v1/panel/hmac-secret). Authentication mirrors the other admin // endpoints, with one hardening twist: the signed subject is the SHA-256 // fingerprint of the new secret, so the signature covers the request body — // an attacker who captures the request cannot swap in a different secret. // // The new secret is persisted to config.yml before the in-memory value // changes, and the outgoing secret stays valid for panelHMACRotationGrace so // admin requests already in flight still verify. The panel never receives or // stores fleet-wide material here: it sends each node exactly the secret that // node will hold. func (a *Agent) handlePanelHMACSet(w http.ResponseWriter, r *http.Request) { var body struct { Secret string `json:"secret"` } if err := readJSON(w, r, 4*1024, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid request body"}) return } newSecret := strings.TrimSpace(body.Secret) if newSecret == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "secret is required"}) return } if !validPanelHMACSecret(newSecret) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid secret format"}) return } // The signed subject must fingerprint the secret actually being installed. fingerprint := sha256.Sum256([]byte(newSecret)) if ok, reason := a.verifyNodeAdminRequest(r, "panel-hmac-set", hex.EncodeToString(fingerprint[:])); !ok { jsonWrite(w, 403, map[string]any{"ok": false, "error": reason}) return } if panelHMACEnvOverride() { // Fail safe: persisting would have no effect on the next restart and // would silently diverge config from runtime. Tell the panel so it can // warn the operator; the current env-provided secret keeps working. jsonWrite(w, 200, map[string]any{"ok": true, "envOverride": true}) return } current, _, _ := a.panelHMACSecrets() if current == newSecret { jsonWrite(w, 403, map[string]any{"ok": false, "error": "unchanged-secret"}) return } cfgPath := a.cfgPath if cfgPath == "" { cfgPath = os.Getenv("ADPANEL_NODE_CONFIG") if cfgPath == "" { cfgPath = DefaultConfigPath } } if err := a.persistPanelHMACToConfig(cfgPath, newSecret); err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": fmt.Sprintf("failed to persist secret: %v", err)}) return } a.setPanelHMAC(newSecret, panelHMACRotationGrace) auditLog.Log("panel_hmac_rotate", getClientIP(r), "", "agent", "rotate", "success", map[string]any{ "grace_seconds": int(panelHMACRotationGrace.Seconds()), }) jsonWrite(w, 200, map[string]any{ "ok": true, "graceSeconds": int(panelHMACRotationGrace.Seconds()), }) } // persistPanelHMACToConfig rewrites panel.hmac_secret in config.yml atomically // (temp file + rename, symlink-resolved), mirroring the token rotation // persistence path. The updated document must pass parseYAMLSubset before it // touches disk. func (a *Agent) persistPanelHMACToConfig(cfgPath, newSecret string) error { if strings.TrimSpace(cfgPath) == "" { return fmt.Errorf("config path is empty") } realPath := cfgPath if resolved, err := filepath.EvalSymlinks(cfgPath); err == nil { realPath = resolved } raw, err := os.ReadFile(realPath) if err != nil { return fmt.Errorf("read config file: %w", err) } updated := updateConfigHMACInYAML(string(raw), newSecret) if _, err := parseYAMLSubset(updated); err != nil { return fmt.Errorf("updated config failed validation: %w", err) } dir := filepath.Dir(realPath) tmpFile, err := os.CreateTemp(dir, "config-*.tmp") if err != nil { return fmt.Errorf("create temp file: %w", err) } tmpName := tmpFile.Name() defer func() { _ = os.Remove(tmpName) }() if err := tmpFile.Chmod(0o600); err != nil { _ = tmpFile.Close() return fmt.Errorf("chmod temp file: %w", err) } if _, err := tmpFile.Write([]byte(updated)); err != nil { _ = tmpFile.Close() return fmt.Errorf("write temp file: %w", err) } if err := tmpFile.Sync(); err != nil { _ = tmpFile.Close() return fmt.Errorf("sync temp file: %w", err) } if err := tmpFile.Close(); err != nil { return fmt.Errorf("close temp file: %w", err) } if err := os.Rename(tmpName, realPath); err != nil { return fmt.Errorf("rename temp file to config: %w", err) } _ = os.Chmod(realPath, 0o600) return nil } type fsAnomalyTracker struct { mu sync.Mutex window time.Duration threshold int records map[string]*fsAnomalyRecord } type fsAnomalyRecord struct { windowStart time.Time ops int bytes int64 alerted bool } var defaultFSAnomalyTracker = newFSAnomalyTracker(time.Minute, 200) func newFSAnomalyTracker(window time.Duration, threshold int) *fsAnomalyTracker { if window <= 0 { window = time.Minute } if threshold <= 0 { threshold = 200 } if v := os.Getenv("FS_ANOMALY_THRESHOLD"); v != "" { if n, err := strconv.Atoi(v); err == nil && n > 0 { threshold = n } } return &fsAnomalyTracker{ window: window, threshold: threshold, records: make(map[string]*fsAnomalyRecord), } } func (t *fsAnomalyTracker) record(clientIP, path, method string, reqBytes int64) bool { t.mu.Lock() defer t.mu.Unlock() now := time.Now() rec, exists := t.records[clientIP] if !exists || now.Sub(rec.windowStart) >= t.window { t.records[clientIP] = &fsAnomalyRecord{ windowStart: now, ops: 1, bytes: reqBytes, alerted: false, } if len(t.records) > 10000 { for k, v := range t.records { if now.Sub(v.windowStart) >= t.window*2 { delete(t.records, k) } } } return false } rec.ops++ if reqBytes > 0 { rec.bytes += reqBytes } if rec.ops > t.threshold && !rec.alerted { rec.alerted = true ops := rec.ops totalBytes := rec.bytes thresh := t.threshold auditLog.Log("fs_anomaly", clientIP, "", path, method, "alert", map[string]any{ "ops": ops, "bytes": totalBytes, "threshold": thresh, }) fmt.Fprintf(os.Stderr, "[SECURITY] Anomalous FS API volume detected from %s: %d ops/min (threshold %d, bytes: %d)\n", clientIP, ops, thresh, totalBytes) return true } return false } func (a *Agent) recordFSAccess(clientIP, path, method string, reqBytes int64) bool { tracker := a.fsAnomaly if tracker == nil { tracker = defaultFSAnomalyTracker } return tracker.record(clientIP, path, method, reqBytes) } func statusForAdminReason(reason string) int { switch reason { case "admin-required": return 403 default: return 401 } } // allDiskVolumeRoots returns every registered disk's volumes root, primary first. // When no additional disks are registered it returns exactly []string{a.volumesDir}, // so all path-validation logic below behaves byte-for-byte identically to the // single-disk implementation. This is the single source of truth for "which roots // are valid"; every FS guard derives its root from these helpers. func (a *Agent) allDiskVolumeRoots() []string { roots := []string{filepath.Clean(a.volumesDir)} for _, d := range a.additionalDiskVolumeRoots() { c := filepath.Clean(strings.TrimSpace(d)) if c == "" || c == "." { continue } dup := false for _, existing := range roots { if existing == c { dup = true break } } if !dup { roots = append(roots, c) } } return roots } // additionalDiskVolumeRoots returns the volumes roots of non-primary disks. // Until the disk registry is populated this returns nil, guaranteeing the // primary-only fast path. Kept separate so registry wiring is a one-line change // with no risk to the validation logic. func (a *Agent) additionalDiskVolumeRoots() []string { disks := a.registeredDisks() if len(disks) == 0 { return nil } out := make([]string, 0, len(disks)) for _, d := range disks { out = append(out, a.diskLayoutVolumes(d.MountPath)) } return out } // volumeRootFor returns the registered disk root that owns abs. abs is expected // to already be an absolute, cleaned path that passed safeUnderVolumes. If no // registered root owns it (should not happen for validated paths), it falls back // to a.volumesDir, which preserves the original single-disk behavior exactly. func (a *Agent) volumeRootFor(abs string) string { c := filepath.Clean(abs) for _, root := range a.allDiskVolumeRoots() { if c == root || isUnder(root, c) { return root } } return filepath.Clean(a.volumesDir) } func (a *Agent) safeUnderVolumes(p string) (string, bool) { // adpanel:fs-path-identity - whitespace in a selected path is part of its name. s := p if strings.TrimSpace(s) == "" { return "", false } if !filepath.IsAbs(s) { // Relative paths remain anchored to the primary volumes root, exactly as // before. Absolute paths may target any registered disk root. s = filepath.Join(a.volumesDir, s) } s = filepath.Clean(s) for _, root := range a.allDiskVolumeRoots() { if isUnder(root, s) || root == s { return s, true } } return "", false } // adpanel:fs-scope - safeUnderServerOrVolumes is the hardened replacement used by // every /v1/fs/* handler. When the panel supplies a serverName, the resolved path // must live under that single server's directory (…//) and never // the server root itself for write/delete style operations is decided by callers. // This is defense-in-depth on top of safeUnderVolumes: even if a future caller // forgets to prefix the panel baseDir, the node refuses to touch another server's // files on the same disk. When serverName is empty the behaviour is identical to // safeUnderVolumes (back-compat for any legacy caller). func (a *Agent) safeUnderServerOrVolumes(server, p string) (string, bool) { abs, ok := a.safeUnderVolumes(p) if !ok { return "", false } name := sanitizeName(server) if name == "" { // No server scope requested: fall back to disk-root containment only. return abs, true } root := filepath.Clean(a.serverDir(name)) if abs == root || isUnder(root, abs) { return abs, true } return "", false } // adpanel:fs-scope - fsScopeRootFor returns the containment root that // resolved-path (symlink) checks must use for a request scoped to server. It // must be identical to the root safeUnderServerOrVolumes used for the string // containment check, so a symlink inside the server directory cannot resolve // to a sibling server's directory on the same disk (cross-tenant read/write). // When server is empty the behaviour is identical to volumeRootFor // (back-compat for older panels that do not send the server field). func (a *Agent) fsScopeRootFor(server, abs string) string { if name := sanitizeName(server); name != "" { return filepath.Clean(a.serverDir(name)) } return a.volumeRootFor(abs) } func (a *Agent) handleFSList(w http.ResponseWriter, r *http.Request) { var body struct { Path string `json:"path"` Server string `json:"server"` Depth int `json:"depth"` } if err := readJSON(w, r, a.uploadLimit, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } st, err := os.Lstat(abs) if err != nil || !st.IsDir() { jsonWrite(w, 400, map[string]any{"ok": false, "error": "not a directory"}) return } // adpanel:fs-scope - resolve against the server scope root (not the disk // root) so a symlink inside the server dir cannot point at a sibling server. if err := ensureResolvedUnder(a.fsScopeRootFor(body.Server, abs), abs); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } // adpanel:fs-toctou - the listing is read from a dirfd pinned under the // server scope root (openat2/RESOLVE_BENEATH); the checks above only // produce friendly errors and no longer gate the actual read. scopeHandle, herr := safeOpenRoot(a.fsScopeRootFor(body.Server, abs)) if herr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to read directory"}) return } defer scopeHandle.Close() absRel, rerr := filepath.Rel(scopeHandle.path, abs) if rerr != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } dirFd, oerr := safeOpenDirAt(scopeHandle, absRel) if oerr != nil { if a.debug { fmt.Printf("[fs] list error for %s: %v\n", abs, oerr) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to read directory"}) return } defer dirFd.Close() ents, truncated, err := readDirEntriesBounded(dirFd, maxDirListEntries) if err != nil { if a.debug { fmt.Printf("[fs] list error for %s: %v\n", abs, err) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to read directory"}) return } out := make([]map[string]any, 0, len(ents)) for _, e := range ents { // Metadata comes from the pinned dirfd (Lstat equivalent), not from a // by-name walk that a swapped intermediate could redirect. linfo, lErr := safeStatAt(dirFd, e.Name()) if lErr != nil { continue } if linfo.Mode()&os.ModeSymlink != 0 { out = append(out, map[string]any{"name": e.Name(), "type": "symlink", "mtime": linfo.ModTime().Unix()}) continue } typ := "file" if linfo.IsDir() { typ = "dir" } entry := map[string]any{"name": e.Name(), "type": typ, "mtime": linfo.ModTime().Unix()} if !linfo.IsDir() { entry["size"] = linfo.Size() } out = append(out, entry) } jsonWrite(w, 200, map[string]any{"ok": true, "entries": out, "depth": body.Depth, "truncated": truncated}) } func (a *Agent) handleFSRead(w http.ResponseWriter, r *http.Request) { var body struct { Path string `json:"path"` Server string `json:"server"` Encoding string `json:"encoding"` } if err := readJSON(w, r, 1<<20, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } info, err := os.Lstat(abs) if err != nil { jsonWrite(w, 404, map[string]any{"ok": false, "error": "file not found"}) return } if info.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot read symlink"}) return } // adpanel:fs-scope - resolve against the server scope root (not the disk // root) so a symlink inside the server dir cannot point at a sibling server. if err := ensureResolvedUnder(a.fsScopeRootFor(body.Server, abs), abs); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } if info.IsDir() { jsonWrite(w, 400, map[string]any{"ok": false, "error": "path is a directory"}) return } if info.Size() > maxEditorRead { jsonWrite(w, 400, map[string]any{"ok": false, "error": "file too large (max 10MB)"}) return } // adpanel:fs-toctou - the file is opened through the pinned server scope // root dirfd (openat2/RESOLVE_BENEATH); the checks above only produce // friendly errors now. safeOpenRegularAt adds the regular-file gate so a // planted FIFO cannot wedge the open. scopeHandle, herr := safeOpenRoot(a.fsScopeRootFor(body.Server, abs)) if herr != nil { jsonWrite(w, 404, map[string]any{"ok": false, "error": "file not found"}) return } defer scopeHandle.Close() absRel, rerr := filepath.Rel(scopeHandle.path, abs) if rerr != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } rf, _, rfErr := safeOpenRegularAt(scopeHandle, absRel, os.O_RDONLY|openNoFollow, 0) if rfErr != nil { if errors.Is(rfErr, syscall.ELOOP) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot read symlink"}) return } if errors.Is(rfErr, errSafeNotRegular) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "not a regular file"}) return } if a.debug { fmt.Printf("[fs] read error for %s: %v\n", abs, rfErr) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to read file"}) return } defer rf.Close() // adpanel:fs-read-cap - the plain LimitReader(maxEditorRead) this used to // read through silently truncated a file that grew past the cap between // the Lstat check and the open, serving a partial view as if it were the // whole file (which a subsequent editor save would then write back). // readEditorCapped turns residual growth into an honest 400 instead. b, rerr := readEditorCapped(rf, maxEditorRead) if rerr != nil { if errors.Is(rerr, errEditorReadTooLarge) { // Same message as the Lstat pre-check above so clients see one // shape whether the size was over the cap up front or the file // grew past it between the check and the read. jsonWrite(w, 400, map[string]any{"ok": false, "error": "file too large (max 10MB)"}) return } if a.debug { fmt.Printf("[fs] read error for %s: %v\n", abs, rerr) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to read file"}) return } enc := strings.ToLower(strings.TrimSpace(body.Encoding)) if enc == "" { enc = "utf8" } content := "" if enc == "utf8" { content = string(b) } else { content = base64.StdEncoding.EncodeToString(b) } jsonWrite(w, 200, map[string]any{"ok": true, "content": content, "encoding": enc}) } func (a *Agent) handleFSDownload(w http.ResponseWriter, r *http.Request) { var body struct { Path string `json:"path"` Server string `json:"server"` } if err := readJSON(w, r, 1<<20, &body); err != nil { http.Error(w, "bad json", 400) return } abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) if !ok { http.Error(w, "invalid path", 400) return } info, err := os.Lstat(abs) if err != nil { http.Error(w, "file not found", 404) return } if info.Mode()&os.ModeSymlink != 0 { http.Error(w, "cannot download symlink", 400) return } // adpanel:fs-scope - resolve against the server scope root (not the disk // root) so a symlink inside the server dir cannot point at a sibling server. if err := ensureResolvedUnder(a.fsScopeRootFor(body.Server, abs), abs); err != nil { http.Error(w, "symlink escape blocked", 400) return } if info.IsDir() { http.Error(w, "path is a directory", 400) return } // adpanel:fs-toctou - the file is opened through the pinned server scope // root dirfd (openat2/RESOLVE_BENEATH); the checks above only produce // friendly errors now. safeOpenRegularAt adds the regular-file gate so a // planted FIFO cannot wedge the open. scopeHandle, herr := safeOpenRoot(a.fsScopeRootFor(body.Server, abs)) if herr != nil { http.Error(w, "file not found", 404) return } defer scopeHandle.Close() absRel, rerr := filepath.Rel(scopeHandle.path, abs) if rerr != nil { http.Error(w, "invalid path", 400) return } f, fStat, err := safeOpenRegularAt(scopeHandle, absRel, os.O_RDONLY|openNoFollow, 0) if err != nil { if errors.Is(err, syscall.ELOOP) { http.Error(w, "cannot download symlink", 400) return } if errors.Is(err, errSafeNotRegular) { http.Error(w, "not a regular file", 400) return } http.Error(w, "failed to open file", 500) return } defer f.Close() w.Header().Set("Content-Type", "application/octet-stream") cdName := strings.Map(func(r rune) rune { if r == '"' || r == '\\' || r < 0x20 || r == 0x7f { return '_' } return r }, filepath.Base(abs)) w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, cdName)) w.Header().Set("Content-Length", fmt.Sprintf("%d", fStat.Size())) // The server-wide WriteTimeout (120s) is an absolute deadline armed once // per request, so a transfer that outlived it used to be truncated // mid-body (io.Copy swallows the failed write; the client sees a short // body against Content-Length). This response is client-paced — the // transfer rate is the caller's, not ours — so like handleExportServer, // clear the write deadline for the stream (ignored on writers without // deadline support, e.g. httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Time{}) io.Copy(w, f) } func (a *Agent) handleFSWrite(w http.ResponseWriter, r *http.Request) { var body fsWriteRequest if err := readJSON(w, r, 10<<20, &body); err != nil { // Split the old combined "bad json or content too large" message so a // malformed body is not misreported as exceeding the editor limit; the // panel still maps the too-large wording to its friendly 413. if errors.Is(err, errBodyTooLarge) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "content too large (max 10MB)"}) } else { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid JSON body"}) } return } abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } // adpanel:upload-atomicity - editor saves share the destination scope's // upload lock with the upload routes: the quota check and the write below // form one serialized section per scope, so a save cannot validate its // quota against a snapshot an in-flight upload is about to invalidate // (and uploads cannot race the save's commit the other way round). unlock := a.lockRequestUploadScope(w, r, a.fsScopeRootFor(body.Server, abs)) if unlock == nil { return } defer unlock() mode := strings.ToLower(strings.TrimSpace(body.Mode)) expectedHash, hashLimit := body.expectedFileHash() if mode == "" && body.EditorBaseHash != "" { mode = "update" } existedBefore := false if _, statErr := os.Lstat(abs); statErr == nil { existedBefore = true } if mode == "create" && existedBefore { jsonWrite(w, 409, map[string]any{"ok": false, "error": "file already exists", "existed": true}) return } if mode == "update" && !existedBefore { if expectedHash != "" { refuseChangedReviewedFile(w) return } jsonWrite(w, 404, map[string]any{"ok": false, "error": "file not found", "existed": false}) return } // adpanel:fs-toctou - the parent-directory creation and the write target // are both resolved through the pinned scope-root dirfd // (openat2/RESOLVE_BENEATH); missing parents are created with // ensureDirUnderRoot so a planted intermediate symlink cannot redirect // the creation outside the server scope when the target does not exist // yet. The EvalSymlinks checks below remain as friendly error reporting. scopeHandle, herr := safeOpenRoot(a.fsScopeRootFor(body.Server, abs)) if herr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } defer scopeHandle.Close() absRel, relErr := filepath.Rel(scopeHandle.path, abs) if relErr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } if err := ensureDirUnderRoot(scopeHandle, filepath.Dir(absRel), 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } parentDir := filepath.Dir(abs) resolvedParent, err := filepath.EvalSymlinks(parentDir) // adpanel:fs-scope - resolve against the server scope root (not the disk // root) so a symlink inside the server dir cannot point at a sibling server. if err == nil && !isUnder(a.fsScopeRootFor(body.Server, abs), resolvedParent) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } if rp, err := filepath.EvalSymlinks(filepath.Dir(abs)); err == nil && !isUnder(a.fsScopeRootFor(body.Server, abs), rp) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } enc := strings.ToLower(strings.TrimSpace(body.Encoding)) if enc == "" { enc = "utf8" } var data []byte if enc == "utf8" { data = []byte(body.Content) } else { b, err := base64.StdEncoding.DecodeString(body.Content) if err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid base64"}) return } data = b } if info, err := os.Lstat(abs); err == nil { if info.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot write to symlink"}) return } } // adpanel:upload-atomicity - credit the bytes this write replaces before // validating the quota: without the replaced-size subtraction, saving an // existing file near the limit was billed as a fresh upload (the old file // AND the new content counted together) and a save that actually fit was // rejected with a false 507. Create mode never replaces anything - the // O_EXCL open below enforces non-existence atomically. Content is sized // post-decode so base64 saves are no longer over-billed by the encoding. var replacedBytes int64 var existingMode os.FileMode destWasRegular := false if mode != "create" { if info, err := os.Lstat(abs); err == nil && info.Mode().IsRegular() { replacedBytes = info.Size() existingMode = info.Mode() destWasRegular = true } } extraBytes := int64(len(data)) - replacedBytes if extraBytes < 0 { extraBytes = 0 } if diskErr := a.checkDiskLimitForPath(abs, extraBytes); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } // The Lstat pre-checks above only narrow the race window; the open flags // below are what actually enforce the mode atomically: // create -> O_EXCL: EEXIST here means the file appeared after the // pre-check, so answer with the same 409 shape. A failure // here can never destroy a pre-existing file (there is // none), so the direct write stays. // update/"" -> the transfer lands in a unique temp file and is // committed with an atomic same-directory rename, so a // failed save (ENOSPC mid-write, crash after open) cannot // leave the target truncated the way the old in-place // O_TRUNC write did; failure cleanups unlink only the temp // (same staging the upload routes use). // adpanel:fs-toctou - every open below goes through the pinned server // scope root dirfd (openat2/RESOLVE_BENEATH), so containment is enforced // by the kernel at open time; the Lstat/EvalSymlinks pre-checks above // only produce friendly errors now. if expectedHash != "" && (mode != "update" || !matchFileHash(scopeHandle, absRel, expectedHash, hashLimit)) { refuseChangedReviewedFile(w) return } if mode == "create" { writeErr := safeWriteAt(scopeHandle, absRel, os.O_WRONLY|os.O_CREATE|os.O_TRUNC|openNoFollow|os.O_EXCL, 0o644, data) if writeErr != nil { if a.debug { fmt.Printf("[fs] write error for %s: %v\n", abs, writeErr) } if errors.Is(writeErr, os.ErrExist) { jsonWrite(w, 409, map[string]any{"ok": false, "error": "file already exists", "existed": true}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } jsonWrite(w, 200, map[string]any{"ok": true, "existed": existedBefore}) return } // update mode keeps its "target must exist" contract: a file that // vanished after the early pre-check answers the same 404 shape. If it // vanishes between this check and the commit rename below, the save // re-creates it with the editor content instead of 404 — a benign drift // for an editor save, and the rename replaces a symlink planted at the // target as a link, never writing through it. if mode == "update" { if _, statErr := os.Lstat(abs); statErr != nil { jsonWrite(w, 404, map[string]any{"ok": false, "error": "file not found", "existed": false}) return } } out, tmpRel, terr := openUploadTempFileAt(scopeHandle, filepath.Dir(absRel), filepath.Base(absRel)) if terr != nil { if a.debug { fmt.Printf("[fs] write temp create error for %s: %v\n", abs, terr) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } if destWasRegular { // the staged commit replaces the inode, so the temp must inherit the replaced file's mode (see storeStreamUploadPart) if cerr := out.Chmod(existingMode); cerr != nil { _ = out.Close() removeUploadTemp(scopeHandle, tmpRel) jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } } if _, werr := out.Write(data); werr != nil { _ = out.Close() removeUploadTemp(scopeHandle, tmpRel) jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } // Crash-durability: the data must be on disk before the commit rename, or // a power loss after it surfaces an empty/truncated file under the final // name with the replaced version already gone. syncErr := out.Sync() if cerr := out.Close(); cerr != nil { removeUploadTemp(scopeHandle, tmpRel) jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } if syncErr != nil { removeUploadTemp(scopeHandle, tmpRel) jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } if expectedHash != "" && !matchFileHash(scopeHandle, absRel, expectedHash, hashLimit) { removeUploadTemp(scopeHandle, tmpRel) refuseChangedReviewedFile(w) return } if rerr := safeRenameUnderRoot(scopeHandle, tmpRel, filepath.Base(absRel)); rerr != nil { removeUploadTemp(scopeHandle, tmpRel) if a.debug { fmt.Printf("[fs] write commit error for %s: %v\n", abs, rerr) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } // Best-effort: persist the commit rename itself; a crash that rolls it // back leaves the previous file intact, so the error is ignored. if parentFd, perr := safeOpenDirAt(scopeHandle, filepath.Dir(absRel)); perr == nil { _ = parentFd.Sync() _ = parentFd.Close() } jsonWrite(w, 200, map[string]any{"ok": true, "existed": existedBefore}) } // deleteCallerWaitBudget bounds how long a delete connection stays writable. // Caller budgets are heterogeneous: the FiveM artifact cleanup waits 60s-180s // (the nodeDeletePathIfPresent call sites in index.js), the nodes.js delete // relays and the remaining index.js sites wait 120s. Arming 3m here closes // the one live lost-response window a caller can actually hit: the FiveM // 180s alpine cleanup used to have its response dropped by the stock 120s // WriteTimeout for a 120-180s delete, which aborted the whole artifact // install with fivem-artifact-delete-failed even though the delete had // completed. Callers with shorter budgets still surface 502s for deletes // that outlive THEM — raising those is a product decision (how long the UI // should hang). Retries stay benign either way: both delete routes answer // "already missing" for re-runs. const deleteCallerWaitBudget = 3 * time.Minute func (a *Agent) handleFSDelete(w http.ResponseWriter, r *http.Request) { var body fsDeleteRequest if err := readJSON(w, r, 64*1024, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } if filepath.Clean(abs) == a.volumeRootFor(abs) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "refusing to delete volumes root"}) return } unlock := a.lockRequestUploadScope(w, r, a.fsScopeRootFor(body.Server, abs)) if unlock == nil { return } defer unlock() info, err := os.Lstat(abs) if err != nil { if os.IsNotExist(err) { if body.ExpectedSHA256 != "" { refuseChangedReviewedFile(w) return } jsonWrite(w, 200, map[string]any{"ok": true, "note": "already missing"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to access path"}) return } if info.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot delete symlinks"}) return } // adpanel:fs-scope - resolve against the server scope root (not the disk // root) so a symlink inside the server dir cannot point at a sibling server. if err := ensureResolvedUnder(a.fsScopeRootFor(body.Server, abs), abs); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } // adpanel:fs-toctou - removal runs against dirfds pinned under the server // scope root (unlinkat on the opened parent); the checks above only // produce friendly errors now. scopeHandle, herr := safeOpenRoot(a.fsScopeRootFor(body.Server, abs)) if herr != nil { if os.IsNotExist(herr) { jsonWrite(w, 200, map[string]any{"ok": true, "note": "already missing"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to access path"}) return } defer scopeHandle.Close() absRel, relErr := filepath.Rel(scopeHandle.path, abs) if relErr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to access path"}) return } // rel == "." addresses the server scope root itself: removing it would // delete the whole server directory, which is reserved for the dedicated // admin server-delete/reinstall flows, never the files API. if absRel == "." { jsonWrite(w, 400, map[string]any{"ok": false, "error": "refusing to delete server root"}) return } if body.ExpectedSHA256 != "" && (body.IsDir || !matchReviewedFile(scopeHandle, absRel, body.ExpectedSHA256)) { refuseChangedReviewedFile(w) return } // Long op: a tree delete is disk-bound and can outlive the server-wide // WriteTimeout — see deleteCallerWaitBudget (ignored on writers without // deadline support, e.g. httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(deleteCallerWaitBudget)) if delErr := safeDeleteUnderRoot(scopeHandle, absRel, body.IsDir); delErr != nil { if a.debug { fmt.Printf("[fs] delete error for %s: %v\n", abs, delErr) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "delete operation failed"}) return } jsonWrite(w, 200, map[string]any{"ok": true}) } func (a *Agent) handleFSDeleteBatch(w http.ResponseWriter, r *http.Request) { var body struct { Server string `json:"server"` Items []struct { Path string `json:"path"` IsDir bool `json:"isDir"` } `json:"items"` } if err := readJSON(w, r, a.uploadLimit, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } if len(body.Items) == 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "no items to delete"}) return } if len(body.Items) > 500 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "too many items (max 500)"}) return } if name := sanitizeName(body.Server); name != "" { unlock := a.lockRequestUploadScope(w, r, a.serverDir(name)) if unlock == nil { return } defer unlock() } results := make([]map[string]any, 0, len(body.Items)) successCount := 0 failCount := 0 // Long op: up to 500 deletions, each potentially a tree — see // deleteCallerWaitBudget (ignored on writers without deadline support). _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(deleteCallerWaitBudget)) for _, item := range body.Items { abs, ok := a.safeUnderServerOrVolumes(body.Server, item.Path) if !ok { results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "invalid path"}) failCount++ continue } if filepath.Clean(abs) == a.volumeRootFor(abs) { results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "refusing to delete volumes root"}) failCount++ continue } linfo, err := os.Lstat(abs) if err == nil && linfo.Mode()&os.ModeSymlink == 0 { // adpanel:fs-scope - resolve against the server scope root, not the disk root. if err := ensureResolvedUnder(a.fsScopeRootFor(body.Server, abs), abs); err != nil { results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "symlink escape blocked"}) failCount++ continue } linfo, err = os.Lstat(abs) } if err != nil { if os.IsNotExist(err) { results = append(results, map[string]any{"path": item.Path, "ok": true, "note": "already missing"}) successCount++ } else { results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "failed to access path"}) failCount++ } continue } if linfo.Mode()&os.ModeSymlink != 0 { results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "cannot delete symlinks"}) failCount++ continue } // adpanel:fs-toctou - removal runs against dirfds pinned under the // server scope root (unlinkat on the opened parent); the checks above // only produce friendly errors now. The scope root is resolved per item // because legacy (server-less) requests can span registered disks. scopeHandle, herr := safeOpenRoot(a.fsScopeRootFor(body.Server, abs)) if herr != nil { results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "delete failed"}) failCount++ continue } absRel, relErr := filepath.Rel(scopeHandle.path, abs) if relErr != nil { scopeHandle.Close() results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "delete failed"}) failCount++ continue } // rel == "." addresses the server scope root itself (the whole server // directory); like the volumes-root refusal above it is rejected // per-item while the rest of the batch is processed normally. if absRel == "." { scopeHandle.Close() results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "refusing to delete server root"}) failCount++ continue } delErr := safeDeleteUnderRoot(scopeHandle, absRel, item.IsDir) scopeHandle.Close() if delErr != nil { if a.debug { fmt.Printf("[fs] batch delete error for %s: %v\n", item.Path, delErr) } results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "delete failed"}) failCount++ } else { results = append(results, map[string]any{"path": item.Path, "ok": true}) successCount++ } } jsonWrite(w, 200, map[string]any{ "ok": failCount == 0, "results": results, "success": successCount, "failed": failCount, }) } func (a *Agent) handleFSRename(w http.ResponseWriter, r *http.Request) { var body struct { Path string `json:"path"` Server string `json:"server"` NewName string `json:"newName"` } if err := readJSON(w, r, a.uploadLimit, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } newName := sanitizeUploadFilename(body.NewName) if newName == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid newName"}) return } abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } // adpanel:fs-scope - contain both sides of the rename inside the server // scope root (not the disk root) so a symlink inside the server dir cannot // resolve to, or rename over, a sibling server's files. renameRoot := a.fsScopeRootFor(body.Server, abs) unlock := a.lockRequestUploadScope(w, r, renameRoot) if unlock == nil { return } defer unlock() // rel == "." addresses the server scope root itself: renaming it would // move/replace the whole server directory, which is reserved for the // dedicated admin server-delete/reinstall flows, never the files API. // Checked before the target containment below, whose generic "invalid // target" would otherwise shadow this friendlier refusal. if absRel, relErr := filepath.Rel(renameRoot, abs); relErr == nil && absRel == "." { jsonWrite(w, 400, map[string]any{"ok": false, "error": "refusing to rename server root"}) return } // A missing source answers 404 (the resolved-under check below would // otherwise misreport it as "symlink escape blocked"). if _, lErr := os.Lstat(abs); lErr != nil { if os.IsNotExist(lErr) { jsonWrite(w, 404, map[string]any{"ok": false, "error": "source_not_found"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to access path"}) return } if err := ensureResolvedUnder(renameRoot, abs); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } parent := filepath.Dir(abs) target := filepath.Join(parent, newName) if !isUnder(renameRoot, target) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid target"}) return } resolvedParent, rpErr := filepath.EvalSymlinks(parent) if rpErr == nil && !isUnder(renameRoot, resolvedParent) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } if li, lErr := os.Lstat(abs); lErr == nil && li.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot rename symlinks"}) return } // adpanel:fs-toctou - both sides of the rename are pinned to the same // parent dirfd under the server scope root (renameat2), so the by-name // walk above cannot be raced into a sibling server's directory. scopeHandle, herr := safeOpenRoot(renameRoot) if herr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "rename operation failed"}) return } defer scopeHandle.Close() absRel, relErr := filepath.Rel(scopeHandle.path, abs) if relErr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "rename operation failed"}) return } if err := safeRenameNoReplaceUnderRoot(scopeHandle, absRel, newName); err != nil { if a.debug { fmt.Printf("[fs] rename error for %s: %v\n", abs, err) } // Distinguish the recoverable shapes so the panel can answer 409/404 // instead of collapsing every failure into a generic 500/502. if errors.Is(err, errSafeDestExists) { jsonWrite(w, 409, map[string]any{"ok": false, "error": "destination_exists"}) return } if os.IsNotExist(err) { jsonWrite(w, 404, map[string]any{"ok": false, "error": "source_not_found"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "rename operation failed"}) return } jsonWrite(w, 200, map[string]any{"ok": true}) } // extractCallerWaitBudget matches what every /v1/fs/extract caller waits for // a response (the nodes.js extract relay and all three index.js direct flows: // 600s). The extraction branches below are disk-bound with only a byte // budget, so a large archive legitimately outlasts the server-wide 120s // WriteTimeout. const extractCallerWaitBudget = 10 * time.Minute func (a *Agent) handleFSExtract(w http.ResponseWriter, r *http.Request) { body, err := readFSExtractRequest(w, r, a.uploadLimit) if err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } if diskErr := a.checkDiskLimitForPath(abs, 0); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } // adpanel:fs-scope - resolve against the server scope root (not the disk // root) so a symlink inside the server dir cannot make the archive itself // or the extraction destination resolve into a sibling server's directory. if err := ensureResolvedUnder(a.fsScopeRootFor(body.Server, abs), abs); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } resolvedDir, rdErr := filepath.EvalSymlinks(filepath.Dir(abs)) if rdErr == nil && !isUnder(a.fsScopeRootFor(body.Server, abs), resolvedDir) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } st, err := os.Stat(abs) if err != nil || st.IsDir() { jsonWrite(w, 404, map[string]any{"ok": false, "error": "file not found"}) return } dir := filepath.Dir(abs) typ := detectArchiveType(abs) if typ == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "unsupported archive type"}) return } // adpanel:upload-scope-lock — the budget snapshot below must serialize with // uploads and other extracts/archives on the same scope, or the quota check // is taken against stale usage; the lock is deliberately held across the // whole operation (see the lockUploadScope contract comment). unlock := a.lockRequestUploadScope(w, r, a.fsScopeRootFor(body.Server, abs)) if unlock == nil { return } defer unlock() // Quota-aware extraction budget: global bomb cap clamped down to the // server's remaining disk space (see extractBudgetForDir). budget := a.extractBudgetForDir(dir) // adpanel:fs-toctou - every branch below opens the archive through the // pinned scope root with the regular-file gate, so a planted FIFO cannot // wedge the handler inside open(2); the external-tool branches reject // non-regular archives up front in extractWithExternalTool. extractScope, herr := safeOpenRoot(a.fsScopeRootFor(body.Server, abs)) if herr != nil { jsonWrite(w, 404, map[string]any{"ok": false, "error": "file not found"}) return } defer extractScope.Close() extractRel, relErr := filepath.Rel(extractScope.path, abs) if relErr != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) return } var destRoot *safeRoot if typ != "7z" && typ != "rar" { destRoot, err = openScopedExtractRoot(extractScope, filepath.Dir(extractRel)) if err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid extract destination"}) return } defer destRoot.Close() } // The server-wide WriteTimeout (120s) is armed once when the request // starts being read, but every branch below runs the whole extraction // before its first response byte, disk-bound with only a byte budget. // A large archive used to commit its whole extracted tree and then lose // the response to the 120s deadline — which the relay reports as // node_extract_failed and the user "retries" by re-executing the entire // extraction. Extend THIS connection's write deadline to the full caller // budget; beyond it no caller is listening anyway (ignored on writers // without deadline support, e.g. httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(extractCallerWaitBudget)) var skipped int switch typ { case "zip": af, ainfo, err := safeOpenRegularAt(extractScope, extractRel, os.O_RDONLY, 0) if err != nil { if errors.Is(err, errSafeNotRegular) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "not a regular file"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to open archive"}) return } defer af.Close() skipped, err = extractZipSafeAt(af, ainfo.Size(), destRoot, budget, body.Overwrite) if err != nil { if a.debug { fmt.Printf("[fs] extract zip error for %s: %v\n", abs, err) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) return } case "tar": f, _, err := safeOpenRegularAt(extractScope, extractRel, os.O_RDONLY, 0) if err != nil { if errors.Is(err, errSafeNotRegular) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "not a regular file"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to open archive"}) return } defer f.Close() tr := tar.NewReader(f) skipped, err = extractTarSafeAt(tr, destRoot, budget, body.Overwrite, false) if err != nil { if a.debug { fmt.Printf("[fs] extract tar error for %s: %v\n", abs, err) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) return } case "targz": f, _, err := safeOpenRegularAt(extractScope, extractRel, os.O_RDONLY, 0) if err != nil { if errors.Is(err, errSafeNotRegular) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "not a regular file"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to open archive"}) return } defer f.Close() gz, err := gzip.NewReader(f) if err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "invalid gzip archive"}) return } defer gz.Close() tr := tar.NewReader(gz) skipped, err = extractTarSafeAt(tr, destRoot, budget, body.Overwrite, false) if err != nil { if a.debug { fmt.Printf("[fs] extract targz error for %s: %v\n", abs, err) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) return } case "tarbz2": f, _, err := safeOpenRegularAt(extractScope, extractRel, os.O_RDONLY, 0) if err != nil { if errors.Is(err, errSafeNotRegular) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "not a regular file"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to open archive"}) return } defer f.Close() br := bzip2.NewReader(f) tr := tar.NewReader(br) skipped, err = extractTarSafeAt(tr, destRoot, budget, body.Overwrite, false) if err != nil { if a.debug { fmt.Printf("[fs] extract tarbz2 error for %s: %v\n", abs, err) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) return } case "tarxz": af, _, err := safeOpenRegularAt(extractScope, extractRel, os.O_RDONLY, 0) if err != nil { if errors.Is(err, errSafeNotRegular) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "not a regular file"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to open archive"}) return } defer af.Close() skipped, err = extractTarXzSafeAt(af, destRoot, budget, body.Overwrite) if err != nil { if a.debug { fmt.Printf("[fs] extract tarxz error for %s: %v\n", abs, err) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) return } case "7z": n, err := a.extract7z(abs, dir, budget, extractScope, body.Overwrite) if err != nil { if a.debug { fmt.Printf("[fs] extract 7z error for %s: %v\n", abs, err) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) return } skipped = n case "rar": n, err := a.extractRar(abs, dir, budget, extractScope, body.Overwrite) if err != nil { if a.debug { fmt.Printf("[fs] extract rar error for %s: %v\n", abs, err) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) return } skipped = n } jsonWrite(w, 200, map[string]any{"ok": true, "msg": "extracted", "skipped": skipped}) } func (a *Agent) handleFSUploadRaw(w http.ResponseWriter, r *http.Request) { var body struct { Dir string `json:"dir"` Server string `json:"server"` Filename string `json:"filename"` DataB64 string `json:"data_b64"` } if err := readJSON(w, r, a.uploadLimit, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } if strings.TrimSpace(body.Filename) == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing filename"}) return } absDir, ok := a.safeUnderServerOrVolumes(body.Server, body.Dir) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) return } // adpanel:upload-atomicity - the quota check and the write below run // under the destination scope's upload lock, shared with the streaming // upload routes, so a base64 upload cannot interleave with another // upload's transfer/commit to the same scope or validate its quota // against a snapshot another upload is about to invalidate. unlock := a.lockRequestUploadScope(w, r, a.fsScopeRootFor(body.Server, absDir)) if unlock == nil { return } defer unlock() // adpanel:fs-scope - resolve against the server scope root (not the disk // root) so a symlink inside the server dir cannot point at a sibling // server. This runs before any Lstat below so the replaced-size lookup can // never stat through an escaping symlink. if err := ensureResolvedUnder(a.fsScopeRootFor(body.Server, absDir), absDir); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } fn := sanitizeUploadFilename(body.Filename) if fn == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid filename"}) return } dest := filepath.Join(absDir, fn) if !isUnder(absDir, dest) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid filename"}) return } const maxBase64Upload = 25 << 20 if base64.StdEncoding.DecodedLen(len(body.DataB64)) > maxBase64Upload { jsonWrite(w, 400, map[string]any{"ok": false, "error": "file too large for base64 upload; use stream upload"}) return } data, err := base64.StdEncoding.DecodeString(body.DataB64) if err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid base64"}) return } // adpanel:upload-atomicity - credit the bytes an overwrite frees before // validating the quota, the same way the stream and URL routes do: without // the replaced-size subtraction a near-quota overwrite that actually fits // was billed as a fresh upload (old file AND new content counted together) // and rejected with a false 507. A symlink or directory at the destination // is refused here instead of failing later at write time. var replacedBytes int64 var existingMode os.FileMode destWasRegular := false if info, err := os.Lstat(dest); err == nil { if info.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot write to symlink"}) return } if info.IsDir() { jsonWrite(w, 400, map[string]any{"ok": false, "error": "destination is a directory"}) return } replacedBytes = info.Size() if info.Mode().IsRegular() { existingMode = info.Mode() destWasRegular = true } } extraBytes := int64(len(data)) - replacedBytes if extraBytes < 0 { extraBytes = 0 } if diskErr := a.checkDiskLimitForPath(absDir, extraBytes); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } // adpanel:fs-toctou - the destination directory is created through the // pinned scope-root dirfd (see ensureDirUnderRoot); unlike MkdirAll this // cannot follow a planted intermediate symlink outside the server scope // when the destination does not exist yet. scopeHandle, herr := safeOpenRoot(a.fsScopeRootFor(body.Server, absDir)) if herr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } defer scopeHandle.Close() absDirRel, dirRelErr := filepath.Rel(scopeHandle.path, absDir) if dirRelErr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } if err := ensureDirUnderRoot(scopeHandle, absDirRel, 0o755); err != nil { if errors.Is(err, errSafeScopeEscape) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } // adpanel:upload-atomicity - like the stream route, the transfer lands in // a unique temp file and is committed with an atomic same-directory // rename, so a failed write (ENOSPC mid-write, crash after open) cannot // leave a pre-existing target truncated the way the old in-place // O_TRUNC write did; failure cleanups unlink only the temp. out, tmpRel, terr := openUploadTempFileAt(scopeHandle, absDirRel, fn) if terr != nil { if a.debug { fmt.Printf("[fs] upload raw create error: %v\n", terr) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } if destWasRegular { // the staged commit replaces the inode, so the temp must inherit the replaced file's mode (see storeStreamUploadPart) if cerr := out.Chmod(existingMode); cerr != nil { _ = out.Close() removeUploadTemp(scopeHandle, tmpRel) jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } } if _, werr := out.Write(data); werr != nil { _ = out.Close() removeUploadTemp(scopeHandle, tmpRel) jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } // Crash-durability: the data must be on disk before the commit rename, or // a power loss after it surfaces an empty/truncated file under the final // name with the replaced version already gone. syncErr := out.Sync() if cerr := out.Close(); cerr != nil { removeUploadTemp(scopeHandle, tmpRel) jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } if syncErr != nil { removeUploadTemp(scopeHandle, tmpRel) jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } if rerr := safeRenameUnderRoot(scopeHandle, tmpRel, fn); rerr != nil { removeUploadTemp(scopeHandle, tmpRel) if a.debug { fmt.Printf("[fs] upload raw commit error for %s: %v\n", dest, rerr) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) return } // Best-effort: persist the commit rename itself; a crash that rolls it // back leaves the previous file intact, so the error is ignored. if parentFd, perr := safeOpenDirAt(scopeHandle, absDirRel); perr == nil { _ = parentFd.Sync() _ = parentFd.Close() } jsonWrite(w, 200, map[string]any{"ok": true, "path": dest}) } func (a *Agent) handleFSUploadStream(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, a.uploadLimit) // The body below is paced by the client, so its read deadline advances // with progress (see uploadIdleBody) instead of the server-wide absolute // cap that would abort any transfer outlasting it. r.Body = newUploadIdleBody(w, r.Body) // The server-wide WriteTimeout (120s) is armed once when the request // headers are read, but the first response byte only becomes writable // after the whole transfer below finishes. Without clearing this // connection's write deadline, every upload over ~120s committed the file // and then lost the response — the panel relay answers 502 and the user // re-runs an upload that already landed. Same clearance the download and // extract routes use (ignored on writers without deadline support, e.g. // httptest.ResponseRecorder). _ = http.NewResponseController(w).SetWriteDeadline(time.Time{}) mr, err := r.MultipartReader() if err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad multipart"}) return } var absDir string var destPath string var uploaded bool var written int64 var serverScope string var scopeHandle *safeRoot var absDirRel string for { part, err := mr.NextPart() if errors.Is(err, io.EOF) { break } if err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad multipart"}) return } formName := part.FormName() fileName := part.FileName() if formName == "server" { b, readErr := io.ReadAll(io.LimitReader(part, 4<<10)) _ = part.Close() if readErr != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid server"}) return } serverScope = strings.TrimSpace(string(b)) continue } if formName == "dir" { b, readErr := io.ReadAll(io.LimitReader(part, 64<<10)) if readErr != nil { _ = part.Close() jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) return } _ = part.Close() if len(b) >= 64<<10 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) return } parsedDir, ok := a.safeUnderServerOrVolumes(serverScope, string(b)) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) return } // adpanel:fs-scope - resolve against the server scope root (not the // disk root) so a symlink inside the server dir cannot point at a // sibling server. if err := ensureResolvedUnder(a.fsScopeRootFor(serverScope, parsedDir), parsedDir); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } absDir = parsedDir // adpanel:fs-toctou - pin the server scope root for the rest of the // request so every upload open is resolved against a dirfd // (openat2/RESOLVE_BENEATH), not re-walked by name. if scopeHandle != nil { _ = scopeHandle.Close() scopeHandle = nil } sh, herr := safeOpenRoot(a.fsScopeRootFor(serverScope, absDir)) if herr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "file create failed"}) return } scopeHandle = sh defer func() { _ = scopeHandle.Close() }() rel, relErr := filepath.Rel(scopeHandle.path, absDir) if relErr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "file create failed"}) return } absDirRel = rel continue } if formName != "file" || fileName == "" { _, _ = io.Copy(io.Discard, part) _ = part.Close() continue } if uploaded { _, _ = io.Copy(io.Discard, part) _ = part.Close() jsonWrite(w, 400, map[string]any{"ok": false, "error": "too many files"}) return } if absDir == "" { _, _ = io.Copy(io.Discard, part) _ = part.Close() jsonWrite(w, 400, map[string]any{"ok": false, "error": "dir field must be sent before file"}) return } // Shared sanitizer, replaced-size pre-check, quota snapshot, transfer // and commit all live in storeStreamUploadPart; see there for the // adpanel:upload-atomicity race notes. var status int var resp map[string]any destPath, written, status, resp = a.storeStreamUploadPart(r.Context(), scopeHandle, absDir, absDirRel, part, r.Method == http.MethodPut) if status != 0 { jsonWrite(w, status, resp) return } uploaded = true } if !uploaded { jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing file field"}) return } jsonWrite(w, 200, map[string]any{"ok": true, "path": destPath, "bytes": written}) } // storeStreamUploadPart validates, transfers and commits one multipart file // part. It runs entirely under the destination scope's upload lock // (lockUploadScope), which closes the two races the previous in-place write // had: // // - quota: the replaced-size pre-check, the usage snapshot and the commit // are one serialized section per scope, so a second upload sees the // first's committed bytes instead of both validating against the same // pre-upload snapshot and jointly overshooting the disk limit by up to // N-1 upload sizes; // - same-target writes: Lstat-then-open(O_CREATE|O_TRUNC) let two // concurrent uploads to one target interleave their writes into a // corrupt file while both reported success. The transfer now lands in a // unique temp file inside the destination directory and is committed // with an atomic same-directory rename (last commit wins, the target is // never observable mid-write), and a failed transfer unlinks only its // temp file instead of destroying a pre-existing target that the old // in-place O_TRUNC had already truncated. // // The caller must have validated the destination already (absDir under the // scope, absDirRel relative to the pinned scope root). It returns the // destination path and the bytes written; when status != 0 the request is // finished and resp is the body to send. func (a *Agent) storeStreamUploadPart(ctx context.Context, scopeHandle *safeRoot, absDir, absDirRel string, part *multipart.Part, createOnly bool) (string, int64, int, map[string]any) { // Shared sanitizer: keeps .env-style dotfiles and non-ASCII names the // same way the base64 upload routes do, and refuses unusable names // with the base64 routes' 400 shape instead of silently renaming the // upload to "upload.bin". safeName := sanitizeUploadFilename(part.FileName()) if safeName == "" { _ = part.Close() return "", 0, 400, map[string]any{"ok": false, "error": "invalid filename"} } defer func() { _ = part.Close() }() // adpanel:upload-atomicity - the pre-check, quota snapshot and commit // below form one serialized section per storage scope; see // uploadScopeLocks and the contract comment on uploadDiskAllowanceForPath. unlock, err := a.acquireFileMutationScope(ctx, scopeHandle.path) if err != nil { status, body := fileMutationAdmissionFailure(err) return "", 0, status, body } defer unlock() if !fileMutationRootIsCurrent(scopeHandle) { return "", 0, http.StatusConflict, map[string]any{"ok": false, "error": "The server directory changed while the upload was waiting. Retry the upload."} } destPath := filepath.Join(absDir, safeName) // adpanel:fs-toctou - the destination directory is created through // the pinned scope-root dirfd (see ensureDirUnderRoot); unlike // MkdirAll this cannot follow a planted intermediate symlink outside // the server scope when the destination does not exist yet. On // refusal the safeOpenDirAt below surfaces the failure with the // handler's regular shape instead of creating dirs outside the root. _ = ensureDirUnderRoot(scopeHandle, absDirRel, 0o755) var replacedBytes int64 var existingMode os.FileMode destWasRegular := false if info, err := os.Lstat(destPath); err == nil { if createOnly { return "", 0, http.StatusConflict, uploadDestinationExists() } if info.Mode()&os.ModeSymlink != 0 { return "", 0, 400, map[string]any{"ok": false, "error": "cannot overwrite symlink"} } if info.IsDir() { return "", 0, 400, map[string]any{"ok": false, "error": "destination is a directory"} } replacedBytes = info.Size() if info.Mode().IsRegular() { existingMode = info.Mode() destWasRegular = true } } allowedBytes, baseUsedBytes, limitBytes, diskLimited, diskErr := a.uploadDiskAllowanceForPath(absDir, replacedBytes) if diskErr != nil { diskErr["ok"] = false return "", 0, 507, diskErr } // adpanel:multidisk - fold in the per-disk capacity ceiling so the // transfer cap is the tighter of the per-server quota and the owning // disk's LimitGb: the base64 routes already enforce capacity through // checkDiskLimitForPath, so the stream route must not be the one path // that can push a secondary disk past its limit. capacityBinds records // which ceiling the mid-transfer 507 payload below must report. capacityBinds := false var capUsedBytes, capLimitBytes int64 if capAllowed, capUsed, capLimit, capLimited, capErr := a.diskCapacityAllowanceForPath(absDir); capErr != nil { capErr["ok"] = false return "", 0, 507, capErr } else if capLimited { capUsedBytes, capLimitBytes = capUsed, capLimit if !diskLimited || capAllowed < allowedBytes { allowedBytes = capAllowed capacityBinds = true } diskLimited = true } // adpanel:fs-toctou - the temp file and the commit rename are resolved // against dirfds pinned under the server scope root // (openat2/RESOLVE_BENEATH); no by-name walk can redirect either step // outside the scope. Failure cleanups unlink the temp through the same // pinned parent instead of re-walking by name. out, tmpRel, terr := openUploadTempFileAt(scopeHandle, absDirRel, safeName) if terr != nil { if a.debug { fmt.Printf("[fs] upload stream create error: %v\n", terr) } return "", 0, 500, map[string]any{"ok": false, "error": "file create failed"} } removeTemp := func() { if parentFd, perr := safeOpenDirAt(scopeHandle, absDirRel); perr == nil { _ = safeRemoveAt(parentFd, filepath.Base(tmpRel)) parentFd.Close() } } // adpanel:upload-atomicity - the commit rename below swaps in the temp's // inode, so an overwrite must carry the replaced file's mode on the temp // first: the old in-place O_TRUNC write kept the inode and thus its mode, // while the staged commit reset an executable overwritten through the // panel to the temp's 0644&~umask and silently dropped +x. Ownership and // xattrs are not preserved, and hardlinks to the old inode keep pointing // at the old content - accepted consequences of atomic staging. A chmod // failure is a commit failure, same shape as the sync failure below; new // destinations keep the temp's default 0644&~umask. if destWasRegular { if cerr := out.Chmod(existingMode); cerr != nil { _ = out.Close() removeTemp() return "", 0, 500, map[string]any{"ok": false, "error": "chmod failed"} } } diskAllowedBytes := int64(-1) if diskLimited { diskAllowedBytes = allowedBytes } written, limitKind, err := copyUploadWithLimits(out, part, a.uploadLimit, diskAllowedBytes) // Crash-durability: the temp's data must be on disk BEFORE the commit // rename below — otherwise a power loss after the rename surfaces an // empty or truncated file under the final name with the replaced version // already gone. A sync failure is a commit failure, same shape as the // close failure; skipped when the copy already failed a limit, since // that temp is about to be discarded. var syncErr error if err == nil && limitKind == "" { syncErr = out.Sync() } closeErr := out.Close() if err != nil { removeTemp() // A MaxBytesReader abort is the operator's size cap, not a server // fault — surface the same 413 shape as the payload-limit branch // below instead of a 500. The reader counts multipart framing too, // so it fires first for parts just over the limit. var maxBytesErr *http.MaxBytesError if errors.As(err, &maxBytesErr) { return "", 0, 413, map[string]any{ "ok": false, "error": "file too large", "limit_mb": a.uploadLimit / (1024 * 1024), } } if a.debug { fmt.Printf("[fs] upload stream write error: %v\n", err) } return "", 0, 500, map[string]any{"ok": false, "error": "write failed"} } if closeErr != nil { removeTemp() return "", 0, 500, map[string]any{"ok": false, "error": "close failed"} } if syncErr != nil { removeTemp() return "", 0, 500, map[string]any{"ok": false, "error": "sync failed"} } if limitKind == "upload" { removeTemp() return "", 0, 413, map[string]any{ "ok": false, "error": "file too large", "limit_mb": a.uploadLimit / (1024 * 1024), } } if limitKind == "disk" { removeTemp() var payload map[string]any if capacityBinds { payload = diskCapacityUploadPayload(capUsedBytes, capLimitBytes, written+1) } else { payload = diskLimitUploadPayload(baseUsedBytes, limitBytes, written+1) } payload["ok"] = false return "", 0, 507, payload } if rerr := commitStagedUpload(scopeHandle, tmpRel, safeName, createOnly); rerr != nil { removeTemp() if errors.Is(rerr, errSafeDestExists) { return "", 0, http.StatusConflict, uploadDestinationExists() } if a.debug { fmt.Printf("[fs] upload stream commit error: %v\n", rerr) } return "", 0, 500, map[string]any{"ok": false, "error": "rename failed"} } // Best-effort: persist the commit rename itself. A crash that rolls the // rename back leaves the previous file intact, which is a safe outcome, // so the error is intentionally ignored. if parentFd, perr := safeOpenDirAt(scopeHandle, absDirRel); perr == nil { _ = parentFd.Sync() _ = parentFd.Close() } return destPath, written, 0, nil } func uploadURLAllowsAnyPort() bool { // Trim like the panel's JS parser (index.js) so one .env value cannot // enable any-port fetches on the panel while staying blocked here. return strings.TrimSpace(os.Getenv("ADPANEL_NODE_FETCH_ALLOW_ANY_PORT")) == "1" || strings.TrimSpace(os.Getenv("REMOTE_FETCH_ALLOW_ANY_PORT")) == "1" } // F9: trust-configuration escape hatch. Strict "1" parsing fails safe (a // careless "true"/"yes" leaves the 80/443 allowlist enforced); both the // enabled and the set-but-ignored states are announced at startup. func warnIfAnyPortEscapeHatchSet() { mainV := strings.TrimSpace(os.Getenv("REMOTE_FETCH_ALLOW_ANY_PORT")) aliasV := strings.TrimSpace(os.Getenv("ADPANEL_NODE_FETCH_ALLOW_ANY_PORT")) if mainV == "" && aliasV == "" { return } if uploadURLAllowsAnyPort() { fmt.Printf("[security] warning: any-port remote fetches are ENABLED (REMOTE_FETCH_ALLOW_ANY_PORT/ADPANEL_NODE_FETCH_ALLOW_ANY_PORT=1): the 80/443 port allowlist for URL uploads is disabled. Every non-standard-port fetch is logged; unset this in production unless required.\n") return } fmt.Printf("[security] warning: REMOTE_FETCH_ALLOW_ANY_PORT/ADPANEL_NODE_FETCH_ALLOW_ANY_PORT is set to an unrecognized value (%q/%q) and is IGNORED — only exactly \"1\" enables any-port fetches; the 80/443 allowlist stays enforced.\n", mainV, aliasV) } var uploadURLAnyPortAudit = struct { sync.Mutex last map[string]time.Time }{last: map[string]time.Time{}} // Audit trail for the escape hatch: keep each non-standard-port fetch visible // (throttled per host:port so chatty mirrors cannot flood the log). func logUploadURLAnyPortUse(u *url.URL) { if !uploadURLAllowsAnyPort() { return } port := u.Port() if port == "" || port == "80" || port == "443" { return } key := u.Hostname() + ":" + port now := time.Now() uploadURLAnyPortAudit.Lock() defer uploadURLAnyPortAudit.Unlock() if t, ok := uploadURLAnyPortAudit.last[key]; ok && now.Sub(t) < 10*time.Minute { return } if len(uploadURLAnyPortAudit.last) >= 256 { uploadURLAnyPortAudit.last = map[string]time.Time{} } uploadURLAnyPortAudit.last[key] = now fmt.Printf("[security] URL upload accepted on non-standard port %s via REMOTE_FETCH_ALLOW_ANY_PORT=1 — verify this is intended\n", key) } func uploadURLPortAllowed(u *url.URL) bool { if uploadURLAllowsAnyPort() { logUploadURLAnyPortUse(u) return true } port := u.Port() return port == "" || port == "80" || port == "443" } func sanitizeUploadFilenameForURL(name string) string { s := strings.TrimSpace(name) if s == "" { return "" } if decoded, err := url.PathUnescape(s); err == nil { s = decoded } s = strings.NewReplacer("\x00", "_", "\r", "_", "\n", "_", "\\", "/").Replace(s) s = path.Base(s) if s == "." || s == ".." || s == "/" || s == "" { return "" } var b strings.Builder for _, r := range s { switch { case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '.', r == '-', r == '_', r == ' ': b.WriteRune(r) default: b.WriteByte('_') } } out := strings.TrimSpace(strings.TrimLeft(b.String(), ".")) if out == "" || out == "." || out == ".." { return "" } if len(out) > 200 { out = out[len(out)-200:] out = strings.TrimLeft(out, ". ") } if out == "" || out == "." || out == ".." { return "" } return out } func filenameFromContentDisposition(cd string) string { if strings.TrimSpace(cd) == "" { return "" } _, params, err := mime.ParseMediaType(cd) if err != nil { return "" } return params["filename"] } // explicitUploadFilename validates a relay-supplied explicit stored name for // the URL upload route: it must survive sanitizeUploadFilename unchanged (a // fixed point), which is guaranteed for the panel-sanitized name the relay // sends because utils/upload-filename.js is the canonical JS mirror of that // sanitizer. Unusable names ("" sanitize result) and non-fixed-point values // that would be silently transformed (traversal like "../x" basenamed to "x", // control characters, names over the 200-byte cap) are refused so the daemon // never stores a different name than the one the relay's extension policy // approved. func explicitUploadFilename(raw string) (string, bool) { if raw == "" { return "", false } name := sanitizeUploadFilename(raw) if name == "" || name != raw { return "", false } return name, true } // uploadURLStoredName resolves the stored filename for a URL upload. An // explicit relay-approved name (already fixed-point verified by // explicitUploadFilename) wins; otherwise the legacy derivation applies // unchanged: Content-Disposition first, URL-path fallback, then download.bin. func uploadURLStoredName(explicit, contentDisposition, urlPath string) string { if explicit != "" { return explicit } filename := sanitizeUploadFilenameForURL(filenameFromContentDisposition(contentDisposition)) if filename == "" && urlPath != "" { filename = sanitizeUploadFilenameForURL(path.Base(urlPath)) } if filename == "" { filename = "download.bin" } return filename } func openURLUploadTempFile(dir, filename string) (*os.File, string, error) { prefix := "." + sanitizeUploadFilenameForURL(filename) if prefix == "." { prefix = ".download" } for i := 0; i < 16; i++ { tmpPath := filepath.Join(dir, fmt.Sprintf("%s.%s.urlupload.tmp", prefix, randomHex(8))) if !isUnder(dir, tmpPath) { return nil, "", fmt.Errorf("invalid temp path") } f, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY|openNoFollow, 0o644) if err == nil { return f, tmpPath, nil } if os.IsExist(err) { continue } return nil, "", err } return nil, "", fmt.Errorf("could not allocate temp file") } const ( // uploadURLFetchTimeout bounds one /v1/fs/uploadUrl remote download: it // is the request context the fetch and its copy-to-temp-file run under. uploadURLFetchTimeout = 30 * time.Minute // uploadURLResponseHeadroom covers the post-download work before the // response is written (scope-lock wait, quota checks, commit rename, // response encoding) on top of the fetch budget. uploadURLResponseHeadroom = 2 * time.Minute ) func (a *Agent) handleFSUploadURL(w http.ResponseWriter, r *http.Request) { createOnly := r.Method == http.MethodPut var body struct { Dir string `json:"dir"` Server string `json:"server"` URL string `json:"url"` Filename *string `json:"filename"` } if err := readJSON(w, r, 16<<10, &body); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) return } // adpanel:upload-policy - optional relay-approved stored name. The relay // policy-checks a name derived from the URL path before it calls this // route, but the daemon derived the stored name from the response's // Content-Disposition first, so a remote server answering // `Content-Disposition: attachment; filename="evil.bat"` could store a // blocklisted extension the relay never approved. When the relay sends // "filename" it is the exact name whose extension was policy-approved, so // it is used verbatim as the stored name (the Content-Disposition and // URL-path derivations are skipped) after a fixed-point check: // sanitizeUploadFilename must return it unchanged. The panel's sanitizer // (utils/upload-filename.js) is the canonical JS mirror of that function, // so relay-sent names are always fixed points; a non-fixed-point value // (traversal like "../x", control characters, >200 bytes) would mean the // daemon was about to store a DIFFERENT name than the one the relay // approved, so it is refused with the route's existing invalid-filename // shape. A present-but-empty name is also refused (fail closed) instead of // silently falling back to the server-controlled name. When the field is // absent (nil) the legacy derivation applies unchanged for any other // caller. Checked before any network work so a bad name fails fast. requestedName := "" if body.Filename != nil { name, ok := explicitUploadFilename(*body.Filename) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid filename"}) return } requestedName = name } rawURL := strings.TrimSpace(body.URL) if rawURL == "" { jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing url"}) return } if len(rawURL) > 2048 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "url too long"}) return } parsedURL, err := a.dl.safeURL(rawURL) if err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid url", "detail": err.Error()}) return } if !uploadURLPortAllowed(parsedURL) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid url", "detail": "only ports 80/443 are allowed"}) return } absDir, ok := a.safeUnderServerOrVolumes(body.Server, body.Dir) if !ok { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) return } dirInfo, err := os.Lstat(absDir) if err != nil || !dirInfo.IsDir() { jsonWrite(w, 400, map[string]any{"ok": false, "error": "target dir not found"}) return } if dirInfo.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot upload into symlink"}) return } // adpanel:fs-scope - resolve against the server scope root (not the disk // root) so a symlink inside the server dir cannot point at a sibling server. if err := ensureResolvedUnder(a.fsScopeRootFor(body.Server, absDir), absDir); err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) return } if diskErr := a.checkDiskLimitForPath(absDir, 0); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } maxBytes := a.uploadLimit if maxBytes <= 0 { maxBytes = 1024 * 1024 * 1024 } ctx, cancel := context.WithTimeout(r.Context(), uploadURLFetchTimeout) defer cancel() // The server-wide WriteTimeout (120s) is armed once when the request // starts being read, but this handler's first response byte only becomes // writable after the full remote download below, which the fetch context // bounds at uploadURLFetchTimeout. Without extending this connection's // deadline, every download over ~120s committed the file and then lost // the response — the panel relay answered 502 and the user re-ran an // upload that had already succeeded. Derive the extension from the fetch // context's own deadline instead of accumulating wall-clock time: the // post-fetch copy runs inside the scope lock below but stays bounded by // this same context, so a SUCCESS response always lands before this // deadline. Two bounded exceptions can still land past it — an error // response after an extreme scope-lock wait (the mutex wait itself is // not context-bounded) and the quota tree-walks on a huge quota-limited // tree — and on those paths nothing commits, so a lost error cannot // duplicate an upload (ignored on writers without deadline support, // e.g. httptest.ResponseRecorder). if ctxDeadline, ok := ctx.Deadline(); ok { _ = http.NewResponseController(w).SetWriteDeadline(ctxDeadline.Add(uploadURLResponseHeadroom)) } req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsedURL.String(), nil) if err != nil { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid url"}) return } req.Header.Set("User-Agent", "ADPanel-Node/"+NodeVersion) req.Header.Set("Accept", "*/*") client := a.dl.clientNoProxy() client.CheckRedirect = func(req *http.Request, via []*http.Request) error { if len(via) >= 10 { return fmt.Errorf("too many redirects") } nextURL, err := a.dl.safeURL(req.URL.String()) if err != nil { return err } if !uploadURLPortAllowed(nextURL) { return fmt.Errorf("only ports 80/443 are allowed") } return nil } resp, err := client.Do(req) if err != nil { if a.debug { fmt.Printf("[fs] uploadUrl request error: %v\n", err) } jsonWrite(w, 502, map[string]any{"ok": false, "error": "fetch failed", "detail": "remote request failed"}) return } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10)) jsonWrite(w, 502, map[string]any{"ok": false, "error": "fetch failed", "detail": fmt.Sprintf("remote http %d", resp.StatusCode)}) return } if resp.ContentLength > maxBytes { jsonWrite(w, 413, map[string]any{ "ok": false, "error": "file too large", "limit_mb": maxBytes / (1024 * 1024), }) return } filename := uploadURLStoredName(requestedName, resp.Header.Get("Content-Disposition"), parsedURL.Path) destPath := filepath.Join(absDir, filename) if !isUnder(absDir, destPath) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid filename"}) return } // adpanel:upload-atomicity - the replaced-size pre-check, the quota // checks and the commit rename below run under the destination scope's // upload lock, shared with the multipart stream route, so concurrent // uploads to one scope cannot jointly overshoot the disk limit (each // validates against a snapshot that already includes the previous // upload's committed bytes) and two commits cannot race each other. // The remote fetch above deliberately stays OUTSIDE the lock. unlock := a.lockRequestUploadScope(w, r, a.fsScopeRootFor(body.Server, absDir)) if unlock == nil { return } defer unlock() var replacedBytes int64 var existingMode os.FileMode destWasRegular := false if info, err := os.Lstat(destPath); err == nil { if createOnly { jsonWrite(w, http.StatusConflict, uploadDestinationExists()) return } if info.Mode()&os.ModeSymlink != 0 { jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot overwrite symlink"}) return } if info.IsDir() { jsonWrite(w, 400, map[string]any{"ok": false, "error": "destination is a directory"}) return } replacedBytes = info.Size() if info.Mode().IsRegular() { existingMode = info.Mode() destWasRegular = true } } if resp.ContentLength > 0 { extraBytes := resp.ContentLength - replacedBytes if extraBytes < 0 { extraBytes = 0 } if diskErr := a.checkDiskLimitForPath(absDir, extraBytes); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } } allowedBytes, baseUsedBytes, limitBytes, diskLimited, diskErr := a.uploadDiskAllowanceForPath(absDir, replacedBytes) if diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } // adpanel:multidisk - fold in the per-disk capacity ceiling (same contract // as the stream route): the ContentLength pre-check above covers known // sizes, this fold also caps chunked responses whose length is unknown // until the copy runs. capacityBinds records which ceiling the 507 // payloads below must report. capacityBinds := false var capUsedBytes, capLimitBytes int64 if capAllowed, capUsed, capLimit, capLimited, capErr := a.diskCapacityAllowanceForPath(absDir); capErr != nil { capErr["ok"] = false jsonWrite(w, 507, capErr) return } else if capLimited { capUsedBytes, capLimitBytes = capUsed, capLimit if !diskLimited || capAllowed < allowedBytes { allowedBytes = capAllowed capacityBinds = true } diskLimited = true } if resp.ContentLength > 0 && diskLimited && resp.ContentLength > allowedBytes { var out map[string]any if capacityBinds { out = diskCapacityUploadPayload(capUsedBytes, capLimitBytes, resp.ContentLength) } else { out = diskLimitUploadPayload(baseUsedBytes, limitBytes, resp.ContentLength) } out["ok"] = false jsonWrite(w, 507, out) return } // adpanel:fs-toctou - temp file creation, the commit rename and the cleanup // all run against dirfds pinned under the server scope root // (openat2/RESOLVE_BENEATH); the checks above only produce friendly errors. scopeHandle, herr := safeOpenRoot(a.fsScopeRootFor(body.Server, absDir)) if herr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "file create failed"}) return } defer scopeHandle.Close() dirRel, relErr := filepath.Rel(scopeHandle.path, absDir) if relErr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "file create failed"}) return } out, tmpRel, err := openUploadTempFileAt(scopeHandle, dirRel, filename) if err != nil { if a.debug { fmt.Printf("[fs] uploadUrl create error: %v\n", err) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "file create failed"}) return } committed := false defer func() { if !committed && tmpRel != "" { if parentFd, perr := safeOpenDirAt(scopeHandle, filepath.Dir(tmpRel)); perr == nil { _ = safeRemoveAt(parentFd, filepath.Base(tmpRel)) parentFd.Close() } } }() if destWasRegular { // the staged commit replaces the inode, so the temp must inherit the replaced file's mode (see storeStreamUploadPart) if cerr := out.Chmod(existingMode); cerr != nil { _ = out.Close() jsonWrite(w, 500, map[string]any{"ok": false, "error": "chmod failed"}) return } } diskAllowedBytes := int64(-1) if diskLimited { diskAllowedBytes = allowedBytes } written, limitKind, copyErr := copyUploadWithLimits(out, resp.Body, maxBytes, diskAllowedBytes) // Crash-durability: the temp's data must be on disk BEFORE the commit // rename below (see the stream route). Skipped when the copy already // failed a limit, since that temp is about to be discarded. var syncErr error if copyErr == nil && limitKind == "" { syncErr = out.Sync() } closeErr := out.Close() if copyErr != nil { if a.debug { fmt.Printf("[fs] uploadUrl write error: %v\n", copyErr) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "write failed"}) return } if closeErr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "close failed"}) return } if syncErr != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "sync failed"}) return } if limitKind == "upload" { jsonWrite(w, 413, map[string]any{ "ok": false, "error": "file too large", "limit_mb": maxBytes / (1024 * 1024), }) return } if limitKind == "disk" { var out map[string]any if capacityBinds { out = diskCapacityUploadPayload(capUsedBytes, capLimitBytes, written+1) } else { out = diskLimitUploadPayload(baseUsedBytes, limitBytes, written+1) } out["ok"] = false jsonWrite(w, 507, out) return } if diskErr := a.checkDiskLimitForPathAfterReplacing(absDir, replacedBytes); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } if err := commitStagedUpload(scopeHandle, tmpRel, filename, createOnly); err != nil { if errors.Is(err, errSafeDestExists) { jsonWrite(w, http.StatusConflict, uploadDestinationExists()) return } if a.debug { fmt.Printf("[fs] uploadUrl rename error: %v\n", err) } jsonWrite(w, 500, map[string]any{"ok": false, "error": "rename failed"}) return } committed = true // Best-effort: persist the commit rename itself; a crash that rolls it // back leaves the previous file intact, so the error is ignored. if parentFd, perr := safeOpenDirAt(scopeHandle, dirRel); perr == nil { _ = parentFd.Sync() _ = parentFd.Close() } jsonWrite(w, 200, map[string]any{ "ok": true, "path": destPath, "filename": filename, "bytes": written, "msg": fmt.Sprintf("Downloaded %s (%d bytes)", filename, written), }) } func main() { // Self-check for the update pipeline: a freshly built binary is exec'd with // --version before it may replace the running daemon, so this must answer // before any config is loaded. if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "-version" || os.Args[1] == "version") { fmt.Println(normalizeNodeVersionTag(NodeVersion)) return } cfgPath := os.Getenv("ADPANEL_NODE_CONFIG") if strings.TrimSpace(cfgPath) == "" { cfgPath = DefaultConfigPath } if _, err := os.Stat(cfgPath); err != nil { fmt.Fprintf(os.Stderr, "[config] Missing config.yml at: %s\n", cfgPath) fmt.Fprintln(os.Stderr, "[config] This agent does NOT generate a config file.") os.Exit(1) } raw := string(mustReadFile(cfgPath)) m, err := parseYAMLSubset(raw) if err != nil { fmt.Fprintf(os.Stderr, "[config] Failed to parse YAML: %v\n", err) os.Exit(1) } cfg := Config{Raw: m} warnIfAnyPortEscapeHatchSet() debug := cfg.Bool("debug") token := cfg.String("token") if token == "" { token = cfg.String("auth", "token") } tokenID := cfg.String("token_id") if tokenID == "" { tokenID = cfg.String("auth", "token_id") } uuid := cfg.String("uuid") // TLS settings are resolved before the bind address because the plaintext // fallback default is loopback-only (see resolveAPIBindHost). Env overrides // win over config.yml, mirroring API_TLS_CERT/API_TLS_KEY precedence. sslEnabled := cfg.Bool("api", "ssl", "enabled") cert := cfg.String("api", "ssl", "cert") key := cfg.String("api", "ssl", "key") if envCert := os.Getenv("API_TLS_CERT"); envCert != "" { cert = envCert } if envKey := os.Getenv("API_TLS_KEY"); envKey != "" { key = envKey } apiHost := os.Getenv("API_HOST") if apiHost == "" { apiHost = cfg.String("api", "host") } apiHost = resolveAPIBindHost(apiHost, sslEnabled) apiPort := cfg.Int("api", "port") if apiPort == 0 { apiPort = DefaultAPIPort } uploadMB := cfg.Int("api", "upload_limit") if uploadMB == 0 { uploadMB = 1024 } uploadLimit := int64(uploadMB) * 1024 * 1024 dataRoot := cfg.String("system", "data") if dataRoot == "" { dataRoot = DefaultDataRoot } oldVolumesDir := filepath.Join(dataRoot, "volumes") volumesDir := filepath.Join(dataRoot, "servers") if _, err := os.Stat(oldVolumesDir); err == nil { if _, err := os.Stat(volumesDir); os.IsNotExist(err) { fmt.Printf("[migration] Moving server data from %s to %s\n", oldVolumesDir, volumesDir) if err := os.Rename(oldVolumesDir, volumesDir); err != nil { fmt.Printf("[migration] Warning: could not migrate volumes: %v\n", err) volumesDir = oldVolumesDir } else { fmt.Printf("[migration] Successfully migrated server data\n") } } } _ = ensureDir(volumesDir) stopGraceMS := 1500 if v := os.Getenv("STOP_GRACE_MS"); v != "" { if n, err := strconv.Atoi(v); err == nil && n >= 500 && n <= 30000 { stopGraceMS = n } } headerTimeoutMS := 30000 if v := os.Getenv("HTTP_TIMEOUT_MS"); v != "" { if n, err := strconv.Atoi(v); err == nil && n >= 1000 { headerTimeoutMS = n } } downloadMax := int64(10) << 30 if v := os.Getenv("DOWNLOAD_MAX_BYTES"); v != "" { if n, err := strconv.ParseInt(v, 10, 64); err == nil && n > 0 { downloadMax = n } } resourceStatsTTL := serverResourceStatsDefaultTTL if v := os.Getenv("RESOURCE_STATS_CACHE_MS"); v != "" { if n, err := strconv.Atoi(v); err == nil && n >= 500 && n <= 30000 { resourceStatsTTL = time.Duration(n) * time.Millisecond } } resourceStatsDiskTTL := serverResourceStatsDiskTTL if v := os.Getenv("RESOURCE_STATS_DISK_CACHE_MS"); v != "" { if n, err := strconv.Atoi(v); err == nil && n >= 1000 && n <= 300000 { resourceStatsDiskTTL = time.Duration(n) * time.Millisecond } } panelHMAC := strings.TrimSpace(os.Getenv("PANEL_HMAC_SECRET")) if panelHMAC == "" { panelHMAC = strings.TrimSpace(cfg.String("panel", "hmac_secret")) } panelRequireNonce := resolvePanelRequireNonce(cfg) agent := &Agent{ cfg: cfg, cfgPath: cfgPath, debug: debug, token: token, tokenID: tokenID, uuid: uuid, apiHost: apiHost, apiPort: apiPort, uploadLimit: uploadLimit, dataRoot: dataRoot, volumesDir: volumesDir, panelHMAC: panelHMAC, panelRequireNonce: panelRequireNonce, fsAnomaly: defaultFSAnomalyTracker, stopGrace: time.Duration(stopGraceMS) * time.Millisecond, docker: Docker{debug: debug}, dl: Downloader{ headerTimeout: time.Duration(headerTimeoutMS) * time.Millisecond, maxBytes: downloadMax, }, resourceStats: newServerResourceStatsCache(resourceStatsTTL, resourceStatsDiskTTL), stoppingNow: make(map[string]time.Time), killPending: make(map[string]struct{}), startCancels: make(map[string]context.CancelFunc), recentCommands: make(map[string]recentConsoleCommand), importProgress: make(map[string]*ImportProgress), importSem: make(chan struct{}, 3), } agent.ensureNodeInformationFile() agent.recoverInterruptedServerOperations() agent.logs = newLogManager(agent.docker, debug) agent.logs.logsDir = filepath.Join(agent.metaDir(), "console-logs") agent.stdinMgr = newStdinManager(&agent.docker, debug) agent.syncBootContainers() protectNodeProcess() startRateLimitCleanup() diskMon := newDiskMonitor(agent, 60*time.Second, debug) diskMon.start() memMon := newMemoryMonitor(agent, 10*time.Second, debug) memMon.start() networkAbuseMon := newNetworkAbuseMonitor(agent, 5*time.Second, debug) networkAbuseMon.start() statsCacheStop := make(chan struct{}) go func() { ticker := time.NewTicker(60 * time.Second) defer ticker.Stop() for { select { case <-ticker.C: agent.resourceStats.cleanup(serverResourceStatsMaxIdle) case <-statsCacheStop: return } } }() httpSrv := &http.Server{ Addr: net.JoinHostPort(agent.apiHost, fmt.Sprintf("%d", agent.apiPort)), Handler: agent, // ReadTimeout is one absolute deadline armed once at request start and // covers the whole body, so a small value here is an upload cap: at // 60s a 2 GB transfer over a 100 Mbps link died mid-body long before // the configured upload_limit could ever be reached. Only the // multipart stream upload route re-arms its body deadline per read // (see uploadBodyIdleTimeout), which bounds stalled clients by // progress instead of wall clock; the raw/files/URL upload routes // keep this figure as their absolute backstop, as does every handler // that never opts in. ReadHeaderTimeout remains the slowloris bound // for the header phase. ReadTimeout: 30 * time.Minute, ReadHeaderTimeout: 10 * time.Second, WriteTimeout: 120 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 1 << 20, } sig := make(chan os.Signal, 2) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) go func() { <-sig fmt.Println("[node] shutting down...") memMon.stop() diskMon.stop() networkAbuseMon.stop() close(statsCacheStop) if agent.stdinMgr != nil { agent.stdinMgr.stop() } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() _ = httpSrv.Shutdown(ctx) }() if sslEnabled { // Fail closed: TLS was explicitly requested, so unusable certificate // material must abort startup. Downgrading to plaintext HTTP would put // the bearer token and panel HMAC secret on the wire in the clear. if cert == "" || key == "" { fmt.Fprintln(os.Stderr, "[ssl] FATAL: api.ssl.enabled is true but cert/key paths are missing — refusing to start.") fmt.Fprintf(os.Stderr, "[ssl] FATAL: set api.ssl.cert and api.ssl.key in %s (or API_TLS_CERT/API_TLS_KEY env vars)\n", cfgPath) os.Exit(1) } if _, err := os.Stat(cert); err != nil { fmt.Fprintf(os.Stderr, "[ssl] FATAL: certificate file not readable: %s: %v — refusing to start.\n", cert, err) os.Exit(1) } if _, err := os.Stat(key); err != nil { fmt.Fprintf(os.Stderr, "[ssl] FATAL: key file not readable: %s: %v — refusing to start.\n", key, err) os.Exit(1) } if _, err := tls.LoadX509KeyPair(cert, key); err != nil { fmt.Fprintf(os.Stderr, "[ssl] FATAL: TLS keypair failed to load (cert=%s key=%s): %v — refusing to start.\n", cert, key, err) os.Exit(1) } } else { fmt.Fprintln(os.Stderr, "[ssl] WARNING: api.ssl.enabled is false — node API is serving over plaintext HTTP.") fmt.Fprintln(os.Stderr, "[ssl] WARNING: bearer tokens and the panel HMAC secret transit unencrypted. Set api.ssl.cert/api.ssl.key to enable TLS. /health reports \"tls\": false while degraded.") for _, line := range plaintextNonLoopbackWarningLines(agent.apiHost) { fmt.Fprintln(os.Stderr, line) } } fmt.Printf("[node] API listening on %s://%s:%d\n", func() string { if sslEnabled { return "https" } return "http" }(), agent.apiHost, agent.apiPort) if sslEnabled { fmt.Printf("[node] Starting HTTPS with cert=%s key=%s\n", cert, key) if err := httpSrv.ListenAndServeTLS(cert, key); err != nil && !errors.Is(err, http.ErrServerClosed) { fmt.Fprintf(os.Stderr, "[https] error: %v\n", err) os.Exit(1) } } else { if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { fmt.Fprintf(os.Stderr, "[http] error: %v\n", err) os.Exit(1) } } } func (a *Agent) syncBootContainers() { if a == nil || a.volumesDir == "" { return } files, err := os.ReadDir(a.volumesDir) if err != nil { return } for _, f := range files { if !f.IsDir() || strings.HasPrefix(f.Name(), ".") { continue } name := f.Name() if !isValidContainerName(name) { continue } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) exists := a.docker.containerExists(ctx, name) cancel() if exists { a.ensureLiveLogs(name) } } }