package main import ( "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "os" "path/filepath" "strconv" "strings" "time" ) // lockUploadScope serializes quota-accounted writes, backups, restores, and // reinstalls on the same cleaned storage scope. Hold it from the quota check // through commit; if also using the server operation lock, acquire that first. func (a *Agent) lockUploadScope(scopeRoot string) func() { unlock, _ := a.acquireUploadScope(context.Background(), scopeRoot) return unlock } // adpanel:reinstall-file-admission - a request canceled while waiting for // storage must never wake up and mutate a replacement server tree. func (a *Agent) acquireUploadScope(ctx context.Context, scopeRoot string) (func(), error) { value, _ := a.uploadScopeLocks.LoadOrStore(filepath.Clean(scopeRoot), make(chan struct{}, 1)) gate := value.(chan struct{}) select { case gate <- struct{}{}: if err := ctx.Err(); err != nil { <-gate return nil, err } return func() { <-gate }, nil case <-ctx.Done(): return nil, ctx.Err() } } func (a *Agent) lockRequestUploadScope(w http.ResponseWriter, r *http.Request, scopeRoot string) func() { unlock, err := a.acquireFileMutationScope(r.Context(), scopeRoot) if err != nil { status, body := fileMutationAdmissionFailure(err) jsonWrite(w, status, body) } return unlock } func fileMutationAdmissionFailure(err error) (int, map[string]any) { switch { case errors.Is(err, errReinstallStartupPending): return http.StatusServiceUnavailable, reinstallStartupPendingBody() case errors.Is(err, errTransferExportInProgress): return http.StatusConflict, map[string]any{"ok": false, "code": "transfer_in_progress", "error": errTransferExportInProgress.Error()} case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): return http.StatusRequestTimeout, uploadScopeRequestEnded() default: return http.StatusServiceUnavailable, map[string]any{"ok": false, "error": "could not verify server file operation state"} } } // adpanel:reinstall-pending-writes - never acknowledge writes on a tree that may still be rolled back. func (a *Agent) acquireFileMutationScope(ctx context.Context, scopeRoot string) (func(), error) { unlock, err := a.acquireUploadScope(ctx, scopeRoot) if err != nil { return nil, err } if filepath.Dir(filepath.Clean(scopeRoot)) == a.volumeRootFor(scopeRoot) { var meta struct { Pending bool `json:"__reinstallPendingStartup"` } name := filepath.Base(scopeRoot) if err := a.checkTransferSourceWritable(name); err != nil { unlock() return nil, err } data, err := os.ReadFile(a.metaPath(name)) if err == nil && json.Unmarshal(data, &meta) == nil && meta.Pending { unlock() return nil, errReinstallStartupPending } } return unlock, nil } func fileMutationRootIsCurrent(root *safeRoot) bool { pinned, err := root.file.Stat() if err != nil { return false } current, err := os.Lstat(root.path) return err == nil && os.SameFile(pinned, current) } func uploadScopeRequestEnded() map[string]any { return map[string]any{"ok": false, "error": "file operation request ended before acquiring the storage lock"} } func safeChmodFileAt(parent *os.File, name string, mode os.FileMode) error { file, _, err := safeOpenChildNoFollow(parent, name) if err != nil { return err } defer file.Close() return safeChmodPinnedFile(file, mode) } // adpanel:volume-permissions - installer and runtime trees can contain // untrusted links; only change modes on entries opened below a pinned parent. func ensureVolumeWritable(serverDir string) { chmodVolumeTree(serverDir, false) } func chmodVolumeTree(serverDir string, forRemoval bool) { serverDir = filepath.Clean(serverDir) parent, err := safeOpenRoot(filepath.Dir(serverDir)) if err != nil { return } defer parent.Close() directory, info, err := safeOpenChildNoFollow(parent.file, filepath.Base(serverDir)) if err != nil { return } defer directory.Close() if info.IsDir() { chmodVolumeDirectory(directory, forRemoval) } } func chmodVolumeDirectory(directory *os.File, forRemoval bool) { mode := os.FileMode(0o777) if forRemoval { mode = 0o700 } _ = safeChmodPinnedFile(directory, mode) reader, err := safeOpenPinnedDirReader(directory) if err != nil { return } if reader != directory { defer reader.Close() } for { entries, readErr := reader.ReadDir(128) for _, entry := range entries { if !entry.IsDir() && (forRemoval || !entry.Type().IsRegular()) { continue } child, info, err := safeOpenChildNoFollow(directory, entry.Name()) if err != nil { continue } if info.IsDir() { chmodVolumeDirectory(child, forRemoval) } else if !forRemoval { mode := os.FileMode(0o666) if info.Mode().Perm()&0o111 != 0 { mode = 0o777 } _ = safeChmodPinnedFile(child, mode) } child.Close() } if readErr != nil { return } } } // adpanel:backup-directory-modes - unlinking a preserved read-only tree needs // writable directories, not writable files. Never chmod a linked file. func removeAllWritable(root string) error { root = filepath.Clean(root) if root == "." || root == string(os.PathSeparator) { return fmt.Errorf("refusing to remove unsafe path") } err := os.RemoveAll(root) if !errors.Is(err, os.ErrPermission) { return err } chmodVolumeTree(root, true) if retryErr := os.RemoveAll(root); retryErr != nil { return fmt.Errorf("%v; retry after chmod failed: %w", err, retryErr) } return nil } // adpanel:runtime-bind-scope - a rebuild may reuse stored mounts, but host // binds must stay inside this server's own directory on its assigned disk. func (a *Agent) resolveStructuredBinds(tpl string, runtimeObj map[string]any, serverDir string, stagedDir ...string) ([]string, string) { filesDir := serverDir if len(stagedDir) > 0 { filesDir = stagedDir[0] } binds, primaryDir, _ := resolveStructuredBindsChecked(tpl, runtimeObj, serverDir, filesDir) return binds, primaryDir } func resolveStructuredBindsChecked(tpl string, runtimeObj map[string]any, serverDir, filesDir string) ([]string, string, bool) { defaultDir := defaultDataDirForType(tpl) binds := []string{} primaryDir := defaultDir rejected := false for _, spec := range runtimeStringSlice(runtimeObj["volumes"]) { spec = strings.ReplaceAll(spec, "{BOT_DIR}", serverDir) spec = strings.ReplaceAll(spec, "{SERVER_DIR}", serverDir) spec = strings.ReplaceAll(spec, "{DATA_DIR}", serverDir) if source, _, found := strings.Cut(spec, ":"); found { hostPath := filepath.Clean(source) rel, err := filepath.Rel(serverDir, hostPath) if err != nil || !isUnder(serverDir, hostPath) { rejected = true fmt.Printf("[security] blocked volume mount outside server directory: %s\n", spec) continue } if ensureResolvedUnder(filesDir, filepath.Join(filesDir, rel)) != nil { rejected = true fmt.Printf("[security] blocked volume mount outside server directory: %s\n", spec) continue } containerPath := parseVolumeSpecContainerPath(spec) if containerPath != "" && primaryDir == defaultDir { primaryDir = containerPath } } binds = append(binds, spec) } if len(binds) == 0 { binds = []string{fmt.Sprintf("%s:%s", serverDir, defaultDir)} } return binds, primaryDir, rejected } const runtimeImageSeedPathKey = "__imageSeedPath" func customRuntimeImageSeedLayout(serverDir, seedPath, workdir string) ([]string, string, string) { dataDir := normalizeContainerWorkdir(seedPath) if dataDir == "" || dataDir == "/" { return nil, "", workdir } if workdir == "" { workdir = dataDir } return []string{fmt.Sprintf("%s:%s", serverDir, dataDir)}, dataDir, workdir } func (a *Agent) resolveCustomRuntimeLayout(template string, runtimeConfig map[string]any, serverDir, filesDir, imageRef string, imgCfg imageConfig) (binds []string, dataDir, workdir string) { explicitCommand := sanitizeRuntimeCommand(runtimeConfig["command"]) binds, dataDir = a.resolveStructuredBinds(template, runtimeConfig, serverDir, filesDir) workdir = normalizeContainerWorkdir(runtimeConfig["workdir"]) seedPath, _ := runtimeConfig[runtimeImageSeedPathKey].(string) if len(runtimeStringSlice(runtimeConfig["volumes"])) > 0 { if startupTemplateFromRuntime(runtimeConfig) == "" && (explicitCommand == "" || shouldPreferImageDefaultRuntimeCommand(explicitCommand, imgCfg)) { binds, dataDir = sanitizeCustomImageDefaultBinds(imageRef, imgCfg, binds, dataDir) } if len(binds) == 0 && seedPath != "" { return customRuntimeImageSeedLayout(serverDir, seedPath, workdir) } return } runtimeInstallPath := "" if install := installConfigFromRuntime(runtimeConfig); install != nil { runtimeInstallPath = normalizeContainerWorkdir(install.RuntimePath) } if runtimeInstallPath == "" && startupTemplateFromRuntime(runtimeConfig) != "" { runtimeInstallPath = "/home/container" } envPaths := getDataPathsFromEnv(imgCfg.Env) switch { case runtimeInstallPath != "": dataDir = runtimeInstallPath if workdir == "" { workdir = dataDir } case len(imgCfg.Volumes) > 0: dataDir = imgCfg.Volumes[0] case len(envPaths) > 0: dataDir = envPaths[0] case imgCfg.Workdir != "" && imgCfg.Workdir != "/" && (explicitCommand != "" || hasManagedRuntimeDefaults(template)): dataDir = imgCfg.Workdir if workdir == "" { workdir = dataDir } default: if explicitCommand == "" && !hasManagedRuntimeDefaults(template) { return customRuntimeImageSeedLayout(serverDir, seedPath, workdir) } return } return []string{fmt.Sprintf("%s:%s", serverDir, dataDir)}, dataDir, workdir } func structuredRuntimeReadOnly(runtime map[string]any, byDefault bool) bool { if value, exists := runtime["readonlyRootfs"]; exists { return runtimeBool(value) } if value, exists := runtime["readOnly"]; exists { return runtimeBool(value) } return byDefault } func serverHostBindIP(meta map[string]any) string { hostIP := "0.0.0.0" for _, field := range []string{"bind_ip", "host_ip", "ip"} { if value := strings.TrimSpace(fmt.Sprint(meta[field])); value != "" && value != "" { hostIP = value break } } if runtimeConfig, ok := meta["runtime"].(map[string]any); ok && hostIP == "0.0.0.0" { for _, field := range []string{"bind_ip", "ip"} { if value := strings.TrimSpace(fmt.Sprint(runtimeConfig[field])); value != "" && value != "" { hostIP = value break } } } return hostIP } func serverPortAllocationIPs(meta map[string]any) map[int]string { allocationsByPort := make(map[int]string) resources, _ := meta["resources"].(map[string]any) for _, source := range []any{resources["portAllocations"], meta["portAllocations"]} { allocations, _ := source.([]any) for _, item := range allocations { allocation, ok := item.(map[string]any) if !ok { continue } port, valid := parseStrictPortValue(allocation["port"]) if !valid { continue } if hostIP := strings.TrimSpace(fmt.Sprint(allocation["ip"])); hostIP != "" && hostIP != "" { allocationsByPort[port] = hostIP } } } return allocationsByPort } func (a *Agent) hostBindingAvailability(ctx context.Context, port int, protocols []string, excludeName, hostIP string) (bool, string, string) { if port <= 0 { return true, "", "" } if owner := a.dockerHostPortOwner(ctx, port, excludeName); owner != "" { return false, owner, "docker" } address := net.JoinHostPort(hostIP, strconv.Itoa(port)) cleanProtocols := normalizePortProtocolSlice(protocols) if len(cleanProtocols) == 0 { cleanProtocols = []string{"tcp"} } listen := net.ListenConfig{} for _, protocol := range cleanProtocols { var socket io.Closer var err error if protocol == "udp" { socket, err = listen.ListenPacket(ctx, "udp", address) } else { socket, err = listen.Listen(ctx, "tcp", address) } if err != nil { return false, "", "socket" } _ = socket.Close() } return true, "", "" } func customRuntimeEnvironmentAndPort(name, template, startup string, runtimeConfig map[string]any, hostPort int, resources *resourceLimits) (map[string]string, int) { env := runtimeEnvMap(runtimeConfig["env"]) if env == nil { env = map[string]string{} } containerPort := hostPort if !runtimeUsesHostPortInsideContainer(template, startup, env) || hostPort <= 0 { if ports := runtimeIntSlice(runtimeConfig["ports"]); len(ports) > 0 && ports[0] > 0 { containerPort = ports[0] } } applyRuntimeHostPortEnv(template, env, containerPort) renderRuntimeEnvTemplates(template, env, containerPort) if startup != "" { for key, value := range adpanelStartupDefaultEnv(name, containerPort, resources, startup) { if _, exists := env[key]; !exists { env[key] = value } } env["STARTUP"] = renderADPanelStartupTemplate(startup, env, containerPort) } return env, containerPort } func serverPrimaryContainerPort(name, template string, runtimeConfig map[string]any, hostPort int, resources *resourceLimits) int { if template == "minecraft" { return 25565 } if isManagedProcessRuntime(template) { return hostPort } _, containerPort := customRuntimeEnvironmentAndPort(name, template, startupTemplateFromRuntime(runtimeConfig), runtimeConfig, hostPort, resources) return containerPort } func preserveServerRuntimePolicy(runtimeConfig, oldRuntime map[string]any) { for _, key := range []string{"readonlyRootfs", "readOnly", "bind_ip", "host_ip", "ip"} { if value, exists := oldRuntime[key]; exists && value != nil { if _, configured := runtimeConfig[key]; !configured { runtimeConfig[key] = value } } } } func preserveServerMetadataPolicy(meta, oldMeta map[string]any) { for _, key := range []string{"createdAt", "resources", "bind_ip", "host_ip", "ip", "portAllocations"} { if value, exists := oldMeta[key]; exists && value != nil { meta[key] = value } } if hostIP := serverHostBindIP(oldMeta); hostIP != "0.0.0.0" { meta["bind_ip"] = hostIP } if diskID, ok := oldMeta["__diskId"].(string); ok && strings.TrimSpace(diskID) != "" { meta["__diskId"] = strings.TrimSpace(diskID) } } // adpanel:runtime-seed-policy - the next managed start must not erase a // rebuild's interface/protocol restrictions, read-only filesystem or disk. func preserveRuntimeSeedMetadata(meta, existingMeta map[string]any) { preserveServerMetadataPolicy(meta, existingMeta) for _, key := range []string{"template", "lastImageDigest", reinstallOperationMetadataKey, reinstallOutcomeMetadataKey} { if value, exists := existingMeta[key]; exists { meta[key] = value } } oldRuntime, _ := existingMeta["runtime"].(map[string]any) newRuntime, _ := meta["runtime"].(map[string]any) if newRuntime == nil { newRuntime = make(map[string]any) } preserveServerRuntimePolicy(newRuntime, oldRuntime) for _, key := range []string{"image", "tag", "portProtocols"} { if value, exists := oldRuntime[key]; exists && newRuntime[key] == nil { newRuntime[key] = value } } meta["runtime"] = newRuntime } func (a *Agent) loadMeta(serverDir string) map[string]any { meta, err := a.loadMetaChecked(serverDir, false) if err != nil { return map[string]any{} } return meta } func serverSetupInProgress(meta map[string]any) bool { setupStatus, _ := meta["setupStatus"].(string) return setupStatus != "" && setupStatus != "ready" && setupStatus != "failed" } func (a *Agent) acceptAsyncCreateSetup(w http.ResponseWriter, r *http.Request, req createReq, name, serverDir string, meta map[string]any, hostPort int, unlock func(), minecraft bool) bool { prepare, finish := a.prepareCustomCreateSetup, a.finishCustomCreateSetup if minecraft { prepare, finish = a.prepareMinecraftCreateSetup, a.finishMinecraftCreateSetup } auditLog.Log("server_create", getClientIP(r), "", name, "create", "accepted", map[string]any{"template": req.Template, "asyncSetup": true}) ready := prepare(req, name, serverDir, meta) if latest := a.loadMeta(serverDir); latest != nil { meta = latest } jsonWrite(w, 200, map[string]any{"ok": true, "name": name, "meta": meta, "asyncSetup": true}) if ready { continueCreateSetup(unlock, func() { finish(req, name, serverDir, meta, hostPort) }) } return ready } // adpanel:create-setup-ownership - a delete must not detach files that a queued setup can recreate. func continueCreateSetup(unlock, finish func()) { go func() { defer unlock() finish() }() } func writeServerInstallingConflict(w http.ResponseWriter) { jsonWrite(w, http.StatusConflict, map[string]any{ "error": "server is currently installing", "code": "server_installing", "detail": "Server setup is currently in progress. Operations other than logs, resource reads, EULA, and server deletion are locked.", }) } const maxLegacyServerMetaBytes = 16 << 20 // adpanel:reinstall-meta-write - publish only a complete metadata record so // a failed rebuild can restore its files without losing their existing policy. func (a *Agent) saveMeta(serverDir string, meta map[string]any) error { data, err := json.MarshalIndent(meta, "", " ") if err != nil { return err } return writeServerMetadata(a.metaPath(filepath.Base(serverDir)), data) } func writeServerMetadata(path string, data []byte) error { if err := ensureDir(filepath.Dir(path)); err != nil { return err } if info, err := os.Lstat(path); err == nil { if !info.Mode().IsRegular() { return fmt.Errorf("server metadata path is not a regular file") } } else if !os.IsNotExist(err) { return err } temporary, err := os.CreateTemp(filepath.Dir(path), ".server-metadata-*") if err != nil { return err } defer os.Remove(temporary.Name()) if _, err = temporary.Write(data); err == nil { err = temporary.Sync() } if closeErr := temporary.Close(); err == nil { err = closeErr } if err != nil { return err } return os.Rename(temporary.Name(), path) } // adpanel:reinstall-meta-read - destructive rebuilds need authoritative // policy; legacy files inside the server volume must be regular, bounded // files, and must not resolve through a symlink. func (a *Agent) loadMetaChecked(serverDir string, strict bool) (map[string]any, error) { serverName := filepath.Base(serverDir) extPath := a.metaPath(serverName) metadataBytes, err := os.ReadFile(extPath) const legacyName = "adpanel.json" var legacyRoot *safeRoot if err != nil { if strict && !os.IsNotExist(err) { return nil, fmt.Errorf("read server metadata: %w", err) } legacyRoot, err = safeOpenRoot(serverDir) if err != nil { return nil, fmt.Errorf("open legacy metadata directory: %w", err) } defer legacyRoot.Close() file, info, err := safeOpenRegularAt(legacyRoot, legacyName, os.O_RDONLY|openNoFollow, 0) if err != nil { return nil, fmt.Errorf("open legacy server metadata: %w", err) } defer file.Close() if info.Size() > maxLegacyServerMetaBytes { return nil, fmt.Errorf("legacy server metadata is too large") } metadataBytes, err = io.ReadAll(io.LimitReader(file, maxLegacyServerMetaBytes+1)) if err != nil { return nil, fmt.Errorf("read legacy server metadata: %w", err) } if len(metadataBytes) > maxLegacyServerMetaBytes { return nil, fmt.Errorf("legacy server metadata is too large") } } var meta map[string]any if err := json.Unmarshal(metadataBytes, &meta); err != nil { return nil, fmt.Errorf("decode server metadata: %w", err) } if strict && len(meta) == 0 { return nil, fmt.Errorf("server metadata is empty") } if legacyRoot != nil { if err := a.saveMeta(serverDir, meta); err != nil { if strict { return nil, fmt.Errorf("persist metadata migration: %w", err) } return meta, nil } _ = safeDeleteUnderRoot(legacyRoot, legacyName, false) } return meta, nil } var errNetworkQuotaExceeded = errors.New("Network quota exhausted. Wait for the reset interval before starting the server.") func (rule networkAntiAbuseRule) exceeded(received, sent uint64) (bool, bool) { return rule.inboundLimitBytes > 0 && received >= rule.inboundLimitBytes, rule.outboundLimitBytes > 0 && sent >= rule.outboundLimitBytes } func (entry *serverResourceStatsCacheEntry) currentNetworkWindow(now time.Time, interval time.Duration) (uint64, uint64, time.Time) { started := entry.networkWindowStartedAt if interval <= 0 || started.IsZero() || now.Before(started) || now.Sub(started) >= interval { return 0, 0, time.Time{} } return entry.networkWindowRx, entry.networkWindowTx, started } func (cache *serverResourceStatsCache) forget(name string) { if cache == nil { return } cache.mu.Lock() defer cache.mu.Unlock() delete(cache.entries, name) } // adpanel:network-quota-window - a container restart must not renew a server's traffic allowance. func (a *Agent) verifyServerNetworkQuota(name string, meta map[string]any, now time.Time) error { cache := a.resourceStats rule := networkAntiAbuseRuleFromMeta(meta) if cache == nil || !rule.enabled { return nil } cache.mu.Lock() entry := cache.entries[name] cache.mu.Unlock() if entry == nil { return nil } entry.mu.Lock() defer entry.mu.Unlock() received, sent, _ := entry.currentNetworkWindow(now, rule.resetEvery) inbound, outbound := rule.exceeded(received, sent) if inbound || outbound { return errNetworkQuotaExceeded } return nil } func (a *Agent) prepareServerResourceStart(name string, meta map[string]any) error { if err := a.verifyServerNetworkQuota(name, meta, time.Now()); err != nil { return err } a.resourceStats.reset(name) return nil } func writeServerNetworkQuotaExceeded(w http.ResponseWriter) { jsonWrite(w, http.StatusConflict, map[string]any{ "ok": false, "error": "network_quota_exceeded", "code": "network_quota_exceeded", "detail": errNetworkQuotaExceeded.Error(), }) } const minDockerMemoryMb = 6 // adpanel:resource-docker-minimum - reject unstartable limits before saving container policy. func validateResourcePerformanceLimits(resources *resourceLimits) string { if resources == nil { return "" } if resources.RamMb != nil && *resources.RamMb != 0 && *resources.RamMb < minDockerMemoryMb { return fmt.Sprintf("RAM limit must be at least %d MB.", minDockerMemoryMb) } const minDockerCpuCores = 1000.0 / cpuPeriod if resources.CpuCores != nil && *resources.CpuCores != 0 && *resources.CpuCores < minDockerCpuCores { return fmt.Sprintf("CPU cores must be at least %g.", minDockerCpuCores) } if resources.IoWeight != nil && (*resources.IoWeight < minIoWeight || *resources.IoWeight > maxIoWeight) { return fmt.Sprintf("I/O Priority must be between %d and %d.", minIoWeight, maxIoWeight) } if resources.CpuWeight != nil && (*resources.CpuWeight < minCpuWeight || *resources.CpuWeight > maxCpuWeight) { return fmt.Sprintf("CPU Priority must be between %d and %d.", minCpuWeight, maxCpuWeight) } if resources.PidsLimit != nil && (*resources.PidsLimit < minPidsLimit || *resources.PidsLimit > maxPidsLimit) { return fmt.Sprintf("Process Limit must be between %d and %d.", minPidsLimit, maxPidsLimit) } if resources.FileLimit != nil && (*resources.FileLimit < minFileLimit || *resources.FileLimit > maxFileLimit) { return fmt.Sprintf("File Limit must be between %d and %d.", minFileLimit, maxFileLimit) } if resources.NetworkInboundLimitMb != nil && *resources.NetworkInboundLimitMb != 0 && (*resources.NetworkInboundLimitMb < minNetworkLimitMb || *resources.NetworkInboundLimitMb > maxNetworkLimitMb) { return fmt.Sprintf("Inbound Limit must be between %d and %d.", minNetworkLimitMb, maxNetworkLimitMb) } if resources.NetworkOutboundLimitMb != nil && *resources.NetworkOutboundLimitMb != 0 && (*resources.NetworkOutboundLimitMb < minNetworkLimitMb || *resources.NetworkOutboundLimitMb > maxNetworkLimitMb) { return fmt.Sprintf("Outbound Limit must be between %d and %d.", minNetworkLimitMb, maxNetworkLimitMb) } if resources.NetworkResetMinutes != nil && *resources.NetworkResetMinutes != 0 && (*resources.NetworkResetMinutes < minNetworkResetMins || *resources.NetworkResetMinutes > maxNetworkResetMins) { return fmt.Sprintf("Reset Time must be between %d and %d.", minNetworkResetMins, maxNetworkResetMins) } return "" } // adpanel:reinstall-policy-lock - metadata updates must not overwrite a // rebuild's authoritative runtime, resource limits or disk assignment. func (a *Agent) handleUpdateResources(w http.ResponseWriter, r *http.Request, name string) { opMu := a.tryLockServerOp(name) if opMu == nil { a.writeServerOpConflictResponse(w, name) return } defer opMu.Unlock() serverDir := a.serverDir(name) if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { jsonWrite(w, 404, map[string]any{"error": "not found"}) return } var req struct { Resources 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"` Ports []int `json:"ports"` PortAllocations []map[string]any `json:"portAllocations"` Command *string `json:"command"` StartupCommand *string `json:"startupCommand"` JavaVersion *string `json:"javaVersion"` } `json:"resources"` Command *string `json:"command"` MainPort *int `json:"mainPort"` StartupCommand *string `json:"startupCommand"` JavaVersion *string `json:"javaVersion"` IP *string `json:"ip"` BindIP *string `json:"bind_ip"` PortAllocations []map[string]any `json:"portAllocations"` } if err := readJSON(w, r, 1<<20, &req); err != nil { jsonWrite(w, 400, map[string]any{"error": "invalid request body"}) return } if (req.StartupCommand != nil && strings.TrimSpace(*req.StartupCommand) != "") || (req.Resources.StartupCommand != nil && strings.TrimSpace(*req.Resources.StartupCommand) != "") { jsonWrite(w, 400, map[string]any{"error": "raw docker startup commands are no longer supported"}) return } if req.MainPort != nil { if _, ok := parseStrictPortValue(*req.MainPort); !ok { jsonWrite(w, 400, map[string]any{"error": "invalid mainPort"}) return } } if reason := validateResourcePerformanceLimits(&resourceLimits{ RamMb: req.Resources.RamMb, CpuCores: req.Resources.CpuCores, IoWeight: req.Resources.IoWeight, CpuWeight: req.Resources.CpuWeight, PidsLimit: req.Resources.PidsLimit, FileLimit: req.Resources.FileLimit, NetworkInboundLimitMb: req.Resources.NetworkInboundLimitMb, NetworkOutboundLimitMb: req.Resources.NetworkOutboundLimitMb, NetworkResetMinutes: req.Resources.NetworkResetMinutes, }); reason != "" { jsonWrite(w, 400, map[string]any{"error": reason}) return } metaMu := a.getMetaLock(serverDir) metaMu.Lock() defer metaMu.Unlock() // adpanel:resource-meta-integrity - a partial settings update must not replace unreadable server policy. meta, err := a.loadMetaChecked(serverDir, true) if err != nil { a.logf("[resources] metadata read failed for %q: %v", name, err) jsonWrite(w, 500, map[string]any{"error": "could not read existing server metadata"}) return } // adpanel:resource-setup-lock - setup still starts with its original ports and limits until it settles. if serverSetupInProgress(meta) { writeServerInstallingConflict(w) return } stripLegacyStartupCommandFields(meta) resources, ok := meta["resources"].(map[string]any) if !ok { resources = make(map[string]any) } if req.Resources.RamMb != nil { resources["ramMb"] = *req.Resources.RamMb } if req.Resources.CpuCores != nil { resources["cpuCores"] = *req.Resources.CpuCores } if req.Resources.StorageMb != nil { resources["storageMb"] = *req.Resources.StorageMb delete(resources, "storageGb") } else if req.Resources.StorageGb != nil { resources["storageGb"] = *req.Resources.StorageGb delete(resources, "storageMb") } if req.Resources.SwapMb != nil { resources["swapMb"] = *req.Resources.SwapMb } if req.Resources.BackupsMax != nil { resources["backupsMax"] = *req.Resources.BackupsMax } if req.Resources.MaxSchedules != nil { resources["maxSchedules"] = *req.Resources.MaxSchedules } if req.Resources.IoWeight != nil { resources["ioWeight"] = *req.Resources.IoWeight } if req.Resources.CpuWeight != nil { resources["cpuWeight"] = *req.Resources.CpuWeight } if req.Resources.PidsLimit != nil { resources["pidsLimit"] = *req.Resources.PidsLimit } if req.Resources.FileLimit != nil { resources["fileLimit"] = *req.Resources.FileLimit } if req.Resources.NetworkInboundLimitMb != nil { if *req.Resources.NetworkInboundLimitMb > 0 { resources["networkInboundLimitMb"] = *req.Resources.NetworkInboundLimitMb } else { delete(resources, "networkInboundLimitMb") } } if req.Resources.NetworkOutboundLimitMb != nil { if *req.Resources.NetworkOutboundLimitMb > 0 { resources["networkOutboundLimitMb"] = *req.Resources.NetworkOutboundLimitMb } else { delete(resources, "networkOutboundLimitMb") } } if req.Resources.NetworkResetMinutes != nil { if *req.Resources.NetworkResetMinutes > 0 { resources["networkResetMinutes"] = *req.Resources.NetworkResetMinutes } else { delete(resources, "networkResetMinutes") } } if req.Resources.Ports != nil { validPorts := make([]int, 0, len(req.Resources.Ports)) seenPorts := make(map[int]bool, len(req.Resources.Ports)) for _, p := range req.Resources.Ports { if _, ok := parseStrictPortValue(p); !ok { jsonWrite(w, 400, map[string]any{"error": fmt.Sprintf("invalid port: %d", p)}) return } if seenPorts[p] { continue } seenPorts[p] = true validPorts = append(validPorts, p) } resources["ports"] = validPorts } if req.Resources.PortAllocations != nil { resources["portAllocations"] = req.Resources.PortAllocations meta["portAllocations"] = req.Resources.PortAllocations } else if req.PortAllocations != nil { resources["portAllocations"] = req.PortAllocations meta["portAllocations"] = req.PortAllocations } if req.IP != nil && strings.TrimSpace(*req.IP) != "" { meta["ip"] = strings.TrimSpace(*req.IP) } if req.BindIP != nil && strings.TrimSpace(*req.BindIP) != "" { meta["bind_ip"] = strings.TrimSpace(*req.BindIP) } meta["resources"] = resources if req.MainPort != nil { meta["hostPort"] = *req.MainPort } javaVersionProvided := req.JavaVersion != nil || req.Resources.JavaVersion != nil if javaVersionProvided { rawJavaVersion := "" if req.JavaVersion != nil { rawJavaVersion = *req.JavaVersion } else if req.Resources.JavaVersion != nil { rawJavaVersion = *req.Resources.JavaVersion } cleanJavaVersion := normalizeMinecraftJavaVersion(rawJavaVersion) if cleanJavaVersion == "" { jsonWrite(w, 400, map[string]any{"error": "unsupported minecraft java version"}) return } templateType := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) if templateType == "" { templateType = strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) } runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj == nil { runtimeObj = make(map[string]any) } commandLooksMinecraft := strings.Contains(strings.ToLower(sanitizeRuntimeCommand(runtimeObj["command"])), "server.jar") if templateType != "minecraft" && !strings.Contains(templateType, "minecraft") && !commandLooksMinecraft { jsonWrite(w, 400, map[string]any{"error": "java version selection is only available for minecraft"}) return } runtimeObj["image"] = defaultMinecraftProcessImage runtimeObj["tag"] = minecraftJavaTag(cleanJavaVersion) runtimeObj["javaVersion"] = cleanJavaVersion if sanitizeRuntimeCommand(runtimeObj["command"]) == "" { runtimeObj["command"] = defaultMinecraftProcessCommand } if normalizeContainerWorkdir(runtimeObj["workdir"]) == "" { runtimeObj["workdir"] = defaultDataDirForType("minecraft") } meta["runtime"] = runtimeObj } commandProvided := req.Command != nil || req.Resources.Command != nil if commandProvided { rawCommand := "" if req.Command != nil { rawCommand = *req.Command } else if req.Resources.Command != nil { rawCommand = *req.Resources.Command } runtimeObj, _ := meta["runtime"].(map[string]any) if runtimeObj == nil { runtimeObj = make(map[string]any) } templateType := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) if templateType == "" { templateType = strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) } startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) cleanCommand := normalizeLegacyRuntimeProcessCommand(templateType, rawCommand, startFile, defaultDataDirForType(templateType)) if cleanCommand != "" { if reason := validateRuntimeProcessCommand(cleanCommand); reason != "" { jsonWrite(w, 400, map[string]any{"error": reason}) return } } if cleanCommand == "" { delete(runtimeObj, "command") } else { runtimeObj["command"] = cleanCommand } meta["runtime"] = runtimeObj } // adpanel:resource-port-preflight - check the actual Docker protocols and addresses before saving a binding. if req.MainPort != nil || req.Resources.Ports != nil || req.Resources.PortAllocations != nil || req.PortAllocations != nil || req.IP != nil || req.BindIP != nil { hostPort, _ := parseStrictPortValue(meta["hostPort"]) runtimeConfig, _ := meta["runtime"].(map[string]any) template, _ := meta["type"].(string) template = strings.ToLower(strings.TrimSpace(template)) if template == "" { template, _ = runtimeConfig["providerId"].(string) } if hostPort == 0 { if template == "minecraft" { hostPort = 25565 } else if !isManagedProcessRuntime(template) { hostPort = 8080 } } containerPort := serverPrimaryContainerPort(name, template, runtimeConfig, hostPort, resourceLimitsFromMeta(meta)) bindings, _ := a.buildStructuredPortBindings(serverDir, meta, hostPort, containerPort) if len(bindings) > 0 { ctx, cancel := context.WithTimeout(r.Context(), 6*time.Second) container, containerName, exists, inspectErr := a.inspectContainerForStats(ctx, name) if inspectErr != nil || ctx.Err() != nil { cancel() jsonWrite(w, http.StatusServiceUnavailable, map[string]any{"error": "existing container ports could not be verified"}) return } var ownedBindings map[string][]dockerPortBinding if exists && container.State.Running { ownedBindings = container.HostConfig.PortBindings } status, reason := a.checkServerPortBindings(ctx, bindings, containerName, ownedBindings) cancel() if reason != "" { code := "port_check_failed" if status == http.StatusConflict { code = "port_in_use" } jsonWrite(w, status, map[string]any{"error": reason, "code": code}) return } } } if err := a.saveMeta(serverDir, meta); err != nil { jsonWrite(w, 500, map[string]any{"error": "failed to save meta"}) return } if a.debug { a.logf("[resources] Updated resources for %s: %+v", name, resources) } jsonWrite(w, 200, map[string]any{ "ok": true, "resources": resources, "command": func() string { if runtimeObj, ok := meta["runtime"].(map[string]any); ok { return sanitizeRuntimeCommand(runtimeObj["command"]) } return "" }(), "javaVersion": func() string { if runtimeObj, ok := meta["runtime"].(map[string]any); ok { return normalizeMinecraftJavaVersion(runtimeObj["javaVersion"]) } return "" }(), "hostPort": meta["hostPort"], }) } // adpanel:reinstall-eula-lock - consent must apply to a settled Minecraft // tree, never a directory that a concurrent reinstall is replacing. func (a *Agent) handleEulaAccept(w http.ResponseWriter, r *http.Request, name string) { if !isValidContainerName(name) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid container name"}) return } opMu := a.tryLockServerOp(name) if opMu == nil { a.writeServerOpConflictResponse(w, name) return } defer opMu.Unlock() 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 } meta := a.loadMeta(serverDir) if !isMinecraftServerMeta(meta) { jsonWrite(w, 400, map[string]any{ "ok": false, "error": "not_minecraft", "detail": "EULA acceptance is only available for Minecraft servers.", }) return } var consent struct { AutoStart *bool `json:"autostart"` Mode string `json:"mode"` } if r.Body != nil { if err := readJSON(w, r, 4096, &consent); err != nil && !errors.Is(err, io.EOF) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid EULA consent body"}) return } } shouldAutoStart := r.Method == http.MethodPost && (consent.AutoStart == nil || *consent.AutoStart) flags := os.O_WRONLY | os.O_TRUNC | openNoFollow // adpanel:eula-write-mode - check existence in the same open that writes. switch consent.Mode { case "create": flags |= os.O_CREATE | os.O_EXCL case "update": case "": if r.Method == http.MethodPut { jsonWrite(w, 400, map[string]any{"ok": false, "error": "EULA write mode is required"}) return } flags |= os.O_CREATE default: jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid EULA write mode"}) return } releaseStorage := a.lockRequestUploadScope(w, r, a.fsScopeRootFor(name, serverDir)) if releaseStorage == nil { return } defer releaseStorage() root, err := safeOpenRoot(serverDir) if err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to open server directory"}) return } defer root.Close() const filename = "eula.txt" contents := []byte("eula=true\n") eulaPath := filepath.Join(serverDir, filename) extraBytes := int64(len(contents)) if info, statErr := os.Lstat(eulaPath); statErr == nil && info.Mode().IsRegular() { extraBytes = max(0, extraBytes-info.Size()) } if diskErr := a.checkDiskLimitForPath(eulaPath, extraBytes); diskErr != nil { diskErr["ok"] = false jsonWrite(w, 507, diskErr) return } if err := safeWriteAt(root, filename, flags, 0o644, contents); err != nil { switch { case consent.Mode == "create" && errors.Is(err, os.ErrExist): jsonWrite(w, 409, map[string]any{"ok": false, "error": "eula_file_exists"}) case consent.Mode == "update" && errors.Is(err, os.ErrNotExist): jsonWrite(w, 404, map[string]any{"ok": false, "error": "eula_file_missing"}) default: jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write eula.txt"}) } return } auditLog.Log("minecraft_eula_accept", getClientIP(r), "", name, "eula-accept", "success", nil) if shouldAutoStart { go func() { time.Sleep(100 * time.Millisecond) if _, err := a.performServerStart(context.Background(), name, 0, nil); err != nil { fmt.Printf("[eula] Autostart for %s after EULA acceptance: %v\n", name, err) } }() } jsonWrite(w, 200, map[string]any{"ok": true, "accepted": true, "starting": shouldAutoStart}) }