package site import ( "bytes" "fmt" "os" "path/filepath" "runtime" "sort" "strings" ) // Executable describes a runnable file inside a project directory. type Executable struct { Name string `json:"name"` Path string `json:"path"` // relative command, e.g. ./app Size int64 `json:"size"` } // projectPath resolves a project directory. Both absolute paths inside the // web root and panel-relative paths ("/demo") are accepted. func (s *Service) projectPath(p string) (string, error) { p = strings.TrimSpace(p) if p == "" { return "", invalid("缺少项目目录") } clean := filepath.Clean(p) if rel, err := filepath.Rel(s.cfg.WebRoot, clean); err == nil && rel != "." && !strings.HasPrefix(rel, "..") { return clean, nil } if strings.HasPrefix(clean, "/") { candidate := filepath.Join(s.cfg.WebRoot, strings.TrimPrefix(clean, "/")) if rel, err := filepath.Rel(s.cfg.WebRoot, candidate); err == nil && rel != "." && !strings.HasPrefix(rel, "..") { return candidate, nil } } return "", invalid("项目目录必须位于 %s 内", s.cfg.WebRoot) } // Executables lists ELF binaries and scripts with the executable bit set. func (s *Service) Executables(dir string) ([]Executable, error) { clean, err := s.projectPath(dir) if err != nil { return nil, err } entries, err := os.ReadDir(clean) if err != nil { return nil, invalid("无法读取项目目录: %v", err) } out := make([]Executable, 0, 4) for _, entry := range entries { if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") { continue } info, err := entry.Info() if err != nil || !info.Mode().IsRegular() { continue } if !runnableFile(clean, entry.Name(), info) { continue } out = append(out, Executable{ Name: entry.Name(), Path: "./" + entry.Name(), Size: info.Size(), }) } sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) return out, nil } func runnableFile(dir, name string, info os.FileInfo) bool { if runtime.GOOS == "windows" { return strings.HasSuffix(strings.ToLower(name), ".exe") } // Uploads land with 0644, so the executable bit is not required here; // ensureExecutable() adds it when the site is created. f, err := os.Open(filepath.Join(dir, name)) if err != nil { return false } defer f.Close() head := make([]byte, 4) n, _ := f.Read(head) if n >= 4 && bytes.Equal(head[:4], []byte{0x7f, 'E', 'L', 'F'}) { return true } return n >= 2 && head[0] == '#' && head[1] == '!' } // resolveGoCommand picks a start command when the operator leaves it empty. // Preference: the site slug, then the common binary names, then the only // candidate available. func (s *Service) resolveGoCommand(dir, slug string) (string, error) { list, err := s.Executables(dir) if err != nil { return "", err } if len(list) == 0 { return "", invalid("在 %s 中未找到可执行文件(ELF 或脚本),请先上传编译产物,或手动填写执行命令", dir) } for _, want := range []string{slug, "app", "main", "server", "run", "start"} { for _, candidate := range list { if candidate.Name == want { return candidate.Path, nil } } } return list[0].Path, nil } // ensureExecutable makes the command target runnable. It runs on create, // update and every start/restart, because binaries replaced through the file // manager come back with mode 0644 and systemd then exits 126 in a restart // loop. Interpreter commands ("npm start", "java -jar x") are left alone. func ensureExecutable(dir, cmd string) error { fields := strings.Fields(cmd) if len(fields) == 0 { return nil } target := strings.Trim(fields[0], `"'`) var path string switch { case strings.HasPrefix(target, "./"): path = filepath.Join(dir, strings.TrimPrefix(target, "./")) case filepath.IsAbs(target): rel, err := filepath.Rel(dir, target) if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { return nil // outside the project: let the shell resolve it } path = target default: return nil } info, err := os.Stat(path) if err != nil { return fmt.Errorf("启动命令 %q 指向的文件不存在,请先上传可执行文件", target) } if info.IsDir() { return fmt.Errorf("启动命令 %q 指向的是目录", target) } if !info.Mode().IsRegular() { return fmt.Errorf("启动命令 %q 不是普通文件", target) } if runtime.GOOS != "windows" && info.Mode().Perm()&0o111 == 0 { if err := os.Chmod(path, 0o755); err != nil { return fmt.Errorf("无法为 %s 添加执行权限: %w", target, err) } } if err := checkScriptLineEndings(path); err != nil { return err } return nil } // checkScriptLineEndings rejects CRLF shebangs: the kernel looks for // "/bin/sh\r" and systemd reports a bare exit code with no useful message. func checkScriptLineEndings(path string) error { f, err := os.Open(path) if err != nil { return nil } defer f.Close() head := make([]byte, 256) n, _ := f.Read(head) if n < 2 || head[0] != '#' || head[1] != '!' { return nil } if bytes.Contains(head[:n], []byte("\r\n")) { return fmt.Errorf("%s 是 Windows(CRLF) 换行的脚本,Linux 无法执行;请转换为 LF 换行", filepath.Base(path)) } return nil } // DescribeExecutable formats a candidate for logging. func DescribeExecutable(e Executable) string { return fmt.Sprintf("%s (%d bytes)", e.Path, e.Size) }