package main import ( "context" "encoding/json" "errors" "fmt" "io" "os" "path" "path/filepath" "strings" ) const maxLegacyRuntimeScaffoldBytes = 64 << 10 // adpanel:cfx-layout - the installer and runtime can write the legacy tree; // migrate only from a pinned child directory in the assigned server volume. func migrateNestedCfxServerFiles(serverDir string) { const nestedName = "serverfiles" root, err := safeOpenRoot(serverDir) if err != nil { return } defer root.Close() nested, info, err := safeOpenChildNoFollow(root.file, nestedName) if err != nil { return } defer nested.Close() if !info.IsDir() { return } reader, err := safeOpenPinnedDirReader(nested) if err != nil { return } if reader != nested { defer reader.Close() } entries, err := reader.Readdirnames(-1) if err != nil { return } for _, name := range entries { if err := safeRenameFileAcrossDirsNoReplace(nested, root.file, name, name); err != nil && !errors.Is(err, errSafeDestExists) { fmt.Printf("[cfx-layout] could not migrate %s under %s: %v\n", name, serverDir, err) } } current, currentInfo, err := safeOpenChildNoFollow(root.file, nestedName) if err == nil { defer current.Close() if os.SameFile(info, currentInfo) { _ = safeRemoveAt(root.file, nestedName) } } } func buildNodeIndexTemplate(port int) string { p := port if p < 1 || p > 65535 { p = 3001 } return fmt.Sprintf(`const http = require("http"); const PORT = Number(process.env.PORT || %d); const server = http.createServer((req, res) => { const body = "ADPanel Node.js server is running.\n"; res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8", "Content-Length": Buffer.byteLength(body) }); res.end(body); }); server.listen(PORT, "0.0.0.0", () => { console.log(`+"`"+`ADPanel Node.js server listening on 0.0.0.0:${PORT}`+"`"+`); }); `, p) } // adpanel:fs-toctou - keep scaffold writes beneath a pinned server root, // rejecting non-regular files and never creating through a planted symlink. func writeGeneratedRuntimeFile(serverDir, path string, content []byte, isReplaceableLegacy func([]byte) bool) error { if strings.TrimSpace(path) == "" || strings.TrimSpace(serverDir) == "" { return errors.New("missing runtime scaffold path") } root, err := safeOpenRoot(serverDir) if err != nil { return err } defer root.Close() rel, err := filepath.Rel(root.path, path) if err != nil { return err } file, info, err := safeOpenRegularAt(root, rel, os.O_RDONLY, 0) if err == nil { // adpanel:runtime-scaffold-budget - generated stubs are small; leave // installer output intact without buffering an arbitrarily large file. if isReplaceableLegacy == nil || info.Size() > maxLegacyRuntimeScaffoldBytes { return file.Close() } data, readErr := io.ReadAll(io.LimitReader(file, maxLegacyRuntimeScaffoldBytes+1)) if err := errors.Join(readErr, file.Close()); err != nil { return err } if len(data) > maxLegacyRuntimeScaffoldBytes || !isReplaceableLegacy(data) { return nil } return safeWriteAt(root, rel, os.O_WRONLY|os.O_TRUNC|openNoFollow, 0o644, content) } if !errors.Is(err, os.ErrNotExist) { return err } if err := ensureDirUnderRoot(root, filepath.Dir(rel), 0o755); err != nil { return err } return safeWriteAt(root, rel, os.O_WRONLY|os.O_CREATE|os.O_EXCL|openNoFollow, 0o644, content) } func isLegacyPythonScaffold(content []byte) bool { return strings.TrimSpace(string(content)) == strings.TrimSpace(legacyPythonMainTemplate) } func isLegacyNodeScaffold(content []byte) bool { s := string(content) return strings.Contains(s, `const express = require("express");`) && strings.Contains(s, "Hello World from ADPanel!") } func scaffoldStartFile(startFile, fallback string) string { file := filepath.Base(strings.TrimSpace(startFile)) if file == "." || file == ".." || file == "" { return fallback } return file } func scaffoldPython(serverDir, startFile string) error { file := scaffoldStartFile(startFile, "main.py") return writeGeneratedRuntimeFile(serverDir, filepath.Join(serverDir, file), []byte(pythonMainTemplate), isLegacyPythonScaffold) } func scaffoldNode(serverDir, name, startFile string, port int) error { file := scaffoldStartFile(startFile, "index.js") if err := writeGeneratedRuntimeFile(serverDir, filepath.Join(serverDir, file), []byte(buildNodeIndexTemplate(port)), isLegacyNodeScaffold); err != nil { return err } pkg := map[string]any{ "name": name, "private": true, "version": "1.0.0", "main": "index.js", "scripts": map[string]string{"start": "node index.js"}, "dependencies": map[string]string{}, } data, err := json.MarshalIndent(pkg, "", " ") if err != nil { return err } return writeGeneratedRuntimeFile(serverDir, filepath.Join(serverDir, "package.json"), data, nil) } func ensureRuntimeEntrypointScaffold(ctx context.Context, serverDir, template, commandTemplate, dataDir, workdir, startFile string, hostPort int) error { if _, rebuilding := ctx.Value(reinstallContainerContextKey{}).(*reinstallFileHandoff); rebuilding { return nil } command := sanitizeRuntimeCommand(commandTemplate) if command == "" { return nil } args := parseShellArgs(command) execName, execIndex := resolveRuntimeProcessExecutable(args) if execIndex < 0 { return nil } if isPythonRuntimeExecutable(execName) { target := firstRuntimeCommandFileTarget(args, execIndex, map[string]bool{".py": true}) if target == "" && strings.EqualFold(strings.TrimSpace(template), "python") { if startFile == "" { startFile = "main.py" } target = path.Join(strings.TrimRight(dataDir, "/"), startFile) } if hostPath := containerPathToServerPath(serverDir, dataDir, workdir, target); hostPath != "" { return writeGeneratedRuntimeFile(serverDir, hostPath, []byte(pythonMainTemplate), isLegacyPythonScaffold) } return nil } if isNodeRuntimeExecutable(execName) { target := firstRuntimeCommandFileTarget(args, execIndex, map[string]bool{".js": true, ".mjs": true, ".cjs": true}) normalized := strings.ToLower(strings.TrimSpace(template)) if target == "" && (normalized == "nodejs" || normalized == "discord-bot") { if startFile == "" { startFile = "index.js" } target = path.Join(strings.TrimRight(dataDir, "/"), startFile) } if hostPath := containerPathToServerPath(serverDir, dataDir, workdir, target); hostPath != "" { return writeGeneratedRuntimeFile(serverDir, hostPath, []byte(buildNodeIndexTemplate(hostPort)), isLegacyNodeScaffold) } } return nil }