miaopanel
1package site
2
3import (
4 "bytes"
5 "fmt"
6 "os"
7 "path/filepath"
8 "runtime"
9 "sort"
10 "strings"
11)
12
13// Executable describes a runnable file inside a project directory.
14type Executable struct {
15 Name string `json:"name"`
16 Path string `json:"path"` // relative command, e.g. ./app
17 Size int64 `json:"size"`
18}
19
20// projectPath resolves a project directory. Both absolute paths inside the
21// web root and panel-relative paths ("/demo") are accepted.
22func (s *Service) projectPath(p string) (string, error) {
23 p = strings.TrimSpace(p)
24 if p == "" {
25 return "", invalid("缺少项目目录")
26 }
27 clean := filepath.Clean(p)
28 if rel, err := filepath.Rel(s.cfg.WebRoot, clean); err == nil && rel != "." && !strings.HasPrefix(rel, "..") {
29 return clean, nil
30 }
31 if strings.HasPrefix(clean, "/") {
32 candidate := filepath.Join(s.cfg.WebRoot, strings.TrimPrefix(clean, "/"))
33 if rel, err := filepath.Rel(s.cfg.WebRoot, candidate); err == nil && rel != "." && !strings.HasPrefix(rel, "..") {
34 return candidate, nil
35 }
36 }
37 return "", invalid("项目目录必须位于 %s 内", s.cfg.WebRoot)
38}
39
40// Executables lists ELF binaries and scripts with the executable bit set.
41func (s *Service) Executables(dir string) ([]Executable, error) {
42 clean, err := s.projectPath(dir)
43 if err != nil {
44 return nil, err
45 }
46 entries, err := os.ReadDir(clean)
47 if err != nil {
48 return nil, invalid("无法读取项目目录: %v", err)
49 }
50 out := make([]Executable, 0, 4)
51 for _, entry := range entries {
52 if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") {
53 continue
54 }
55 info, err := entry.Info()
56 if err != nil || !info.Mode().IsRegular() {
57 continue
58 }
59 if !runnableFile(clean, entry.Name(), info) {
60 continue
61 }
62 out = append(out, Executable{
63 Name: entry.Name(),
64 Path: "./" + entry.Name(),
65 Size: info.Size(),
66 })
67 }
68 sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
69 return out, nil
70}
71
72func runnableFile(dir, name string, info os.FileInfo) bool {
73 if runtime.GOOS == "windows" {
74 return strings.HasSuffix(strings.ToLower(name), ".exe")
75 }
76 // Uploads land with 0644, so the executable bit is not required here;
77 // ensureExecutable() adds it when the site is created.
78 f, err := os.Open(filepath.Join(dir, name))
79 if err != nil {
80 return false
81 }
82 defer f.Close()
83 head := make([]byte, 4)
84 n, _ := f.Read(head)
85 if n >= 4 && bytes.Equal(head[:4], []byte{0x7f, 'E', 'L', 'F'}) {
86 return true
87 }
88 return n >= 2 && head[0] == '#' && head[1] == '!'
89}
90
91// resolveGoCommand picks a start command when the operator leaves it empty.
92// Preference: the site slug, then the common binary names, then the only
93// candidate available.
94func (s *Service) resolveGoCommand(dir, slug string) (string, error) {
95 list, err := s.Executables(dir)
96 if err != nil {
97 return "", err
98 }
99 if len(list) == 0 {
100 return "", invalid("在 %s 中未找到可执行文件(ELF 或脚本),请先上传编译产物,或手动填写执行命令", dir)
101 }
102 for _, want := range []string{slug, "app", "main", "server", "run", "start"} {
103 for _, candidate := range list {
104 if candidate.Name == want {
105 return candidate.Path, nil
106 }
107 }
108 }
109 return list[0].Path, nil
110}
111
112// ensureExecutable makes the command target runnable. It runs on create,
113// update and every start/restart, because binaries replaced through the file
114// manager come back with mode 0644 and systemd then exits 126 in a restart
115// loop. Interpreter commands ("npm start", "java -jar x") are left alone.
116func ensureExecutable(dir, cmd string) error {
117 fields := strings.Fields(cmd)
118 if len(fields) == 0 {
119 return nil
120 }
121 target := strings.Trim(fields[0], `"'`)
122 var path string
123 switch {
124 case strings.HasPrefix(target, "./"):
125 path = filepath.Join(dir, strings.TrimPrefix(target, "./"))
126 case filepath.IsAbs(target):
127 rel, err := filepath.Rel(dir, target)
128 if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
129 return nil // outside the project: let the shell resolve it
130 }
131 path = target
132 default:
133 return nil
134 }
135 info, err := os.Stat(path)
136 if err != nil {
137 return fmt.Errorf("启动命令 %q 指向的文件不存在,请先上传可执行文件", target)
138 }
139 if info.IsDir() {
140 return fmt.Errorf("启动命令 %q 指向的是目录", target)
141 }
142 if !info.Mode().IsRegular() {
143 return fmt.Errorf("启动命令 %q 不是普通文件", target)
144 }
145 if runtime.GOOS != "windows" && info.Mode().Perm()&0o111 == 0 {
146 if err := os.Chmod(path, 0o755); err != nil {
147 return fmt.Errorf("无法为 %s 添加执行权限: %w", target, err)
148 }
149 }
150 if err := checkScriptLineEndings(path); err != nil {
151 return err
152 }
153 return nil
154}
155
156// checkScriptLineEndings rejects CRLF shebangs: the kernel looks for
157// "/bin/sh\r" and systemd reports a bare exit code with no useful message.
158func checkScriptLineEndings(path string) error {
159 f, err := os.Open(path)
160 if err != nil {
161 return nil
162 }
163 defer f.Close()
164 head := make([]byte, 256)
165 n, _ := f.Read(head)
166 if n < 2 || head[0] != '#' || head[1] != '!' {
167 return nil
168 }
169 if bytes.Contains(head[:n], []byte("\r\n")) {
170 return fmt.Errorf("%s 是 Windows(CRLF) 换行的脚本,Linux 无法执行;请转换为 LF 换行", filepath.Base(path))
171 }
172 return nil
173}
174
175// DescribeExecutable formats a candidate for logging.
176func DescribeExecutable(e Executable) string {
177 return fmt.Sprintf("%s (%d bytes)", e.Path, e.Size)
178}