仰望星辰工作室

miaopanel

miaopanel/ internal/site/site.go 27.1 KB · 934 行 原始文件
1// Package site implements the lifecycle of a managed website or application.
2package site
3
4import (
5 "context"
6 "errors"
7 "fmt"
8 "net"
9 "os"
10 "os/user"
11 "path/filepath"
12 "regexp"
13 "runtime"
14 "strconv"
15 "strings"
16 "sync"
17 "time"
18
19 "github.com/miaopanel/miaopanel/internal/config"
20 "github.com/miaopanel/miaopanel/internal/fsutil"
21 "github.com/miaopanel/miaopanel/internal/store"
22 "github.com/miaopanel/miaopanel/internal/system"
23 "github.com/miaopanel/miaopanel/internal/webserver"
24)
25
26// Service owns site creation, updates and process control.
27type Service struct {
28 cfg *config.Config
29 db *store.Store
30 nginx *webserver.Manager
31 runner *system.Runner
32 distro system.Distro
33 // mu serialises create/update/delete. Port allocation reads the database
34 // and only writes the new row after nginx accepted the config, so without
35 // this lock two concurrent creations both pick the same free port.
36 mu sync.Mutex
37}
38
39// NewService wires the site service.
40func NewService(cfg *config.Config, db *store.Store, ng *webserver.Manager, runner *system.Runner) *Service {
41 return &Service{cfg: cfg, db: db, nginx: ng, runner: runner, distro: system.Detect()}
42}
43
44// BySlug loads a site by its stable identifier.
45func (s *Service) BySlug(ctx context.Context, slug string) (*store.Site, error) {
46 return s.db.SiteBySlug(ctx, slug)
47}
48
49// Input describes a create-or-update request.
50type Input struct {
51 Name string `json:"name"`
52 Kind string `json:"kind"`
53 Domains []string `json:"domains"`
54 Root string `json:"root"`
55 Port int `json:"port"`
56 PHPVersion string `json:"php_version"`
57 RunUser string `json:"run_user"`
58 StartCmd string `json:"start_cmd"`
59 Env string `json:"env"`
60 Upstream string `json:"upstream"`
61 Remark string `json:"remark"`
62 Options store.SiteOptions
63}
64
65var (
66 slugRe = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
67 domainRe = regexp.MustCompile(`^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$|^(\d{1,3}\.){3}\d{1,3}$|^\[?[0-9a-f:]+\]?$`)
68 // Shell metacharacters are rejected in start commands even though the
69 // command is run through `sh -lc` by systemd (product requirement: allow
70 // simple commands such as "npm start" only).
71 shellUnsafe = regexp.MustCompile("[;&|<>`$(){}\\[\\]\n\r]")
72 // phpVersionRe keeps the value usable in a fastcgi_pass socket name.
73 phpVersionRe = regexp.MustCompile(`^[0-9]+\.[0-9]+$`)
74)
75
76var validKinds = map[string]bool{"static": true, "php": true, "go": true, "node": true, "proxy": true}
77
78// Create validates the input, allocates resources and applies configuration.
79// Any failure rolls back every step already performed.
80func (s *Service) Create(ctx context.Context, in Input) (*store.Site, error) {
81 s.mu.Lock()
82 defer s.mu.Unlock()
83 if err := s.cfg.EnsureDirs(); err != nil {
84 return nil, err
85 }
86 // The UI only asks for a domain; the identifier used for directories and
87 // unit names is derived from it unless the operator overrides it.
88 in.Domains = normalizeDomainList(in.Domains)
89 in.Name = strings.ToLower(strings.TrimSpace(in.Name))
90 if in.Name == "" && len(in.Domains) > 0 {
91 in.Name = deriveSlug(in.Domains[0])
92 }
93 if strings.TrimSpace(in.Root) != "" {
94 root, err := s.projectPath(in.Root)
95 if err != nil {
96 return nil, err
97 }
98 in.Root = root
99 }
100 if err := s.validate(ctx, &in, 0); err != nil {
101 return nil, err
102 }
103 if existing, err := s.db.SiteBySlug(ctx, in.Name); err == nil && existing.ID != 0 {
104 return nil, invalid("站点标识 %q 已被使用,请在「更多配置」中修改", in.Name)
105 }
106 slug := in.Name
107 if in.Root == "" {
108 in.Root = s.cfg.SiteRoot(slug)
109 }
110 if isApp(in.Kind) {
111 used, err := s.db.PortsInUse(ctx)
112 if err != nil {
113 return nil, err
114 }
115 if in.Port == 0 {
116 port, err := system.AllocatePort(8000, 9999, used)
117 if err != nil {
118 return nil, err
119 }
120 in.Port = port
121 } else if owner, taken := used[in.Port]; taken {
122 return nil, invalid("端口 %d 已被站点 %s 使用", in.Port, owner)
123 }
124 // An explicit upstream wins: proxy sites often point at an existing
125 // service (https, another host, a path prefix) and overwriting it with
126 // 127.0.0.1:Port made those sites silently proxy to the wrong place.
127 if strings.TrimSpace(in.Upstream) == "" {
128 in.Upstream = "http://127.0.0.1:" + strconv.Itoa(in.Port)
129 }
130 }
131 // Go projects only need a binary; when the command is omitted we look for
132 // an ELF/script in the project directory (same behaviour as the reference
133 // panel, where project_cmd defaults to the selected executable).
134 if in.Kind == "go" && strings.TrimSpace(in.StartCmd) == "" {
135 cmd, err := s.resolveGoCommand(in.Root, slug)
136 if err != nil {
137 return nil, err
138 }
139 in.StartCmd = cmd
140 }
141 if in.Kind == "go" && in.StartCmd != "" {
142 if err := ensureExecutable(in.Root, in.StartCmd); err != nil {
143 return nil, err
144 }
145 }
146 if in.Kind == "php" && in.PHPVersion == "" {
147 in.PHPVersion = "8.2"
148 }
149 if in.RunUser == "" {
150 in.RunUser = "www"
151 }
152 if in.Kind == "static" || in.Kind == "php" {
153 in.Port = 80
154 }
155 if in.Options.ListenPort != 0 && (in.Options.ListenPort < 1 || in.Options.ListenPort > 65535) {
156 return nil, invalid("监听端口超出范围")
157 }
158 if !in.Options.SecurityHead {
159 // Sensible secure-by-default for new sites.
160 in.Options.SecurityHead = true
161 }
162 if in.Options.WAFRate == 0 {
163 in.Options.WAFRate = 20
164 in.Options.WAFBurst = 40
165 }
166 s.ensureGatewayPort(ctx, &in.Options)
167
168 st := &store.Site{
169 Name: in.Name, Slug: slug, Kind: in.Kind, Root: in.Root, Port: in.Port,
170 PHPVersion: in.PHPVersion, Status: "running", RunUser: in.RunUser,
171 StartCmd: in.StartCmd, Env: in.Env, Upstream: in.Upstream,
172 Remark: in.Remark, Options: in.Options, Domains: in.Domains,
173 }
174
175 createdRoot := false
176 if _, err := os.Stat(st.Root); os.IsNotExist(err) {
177 if err := os.MkdirAll(st.Root, 0o755); err != nil {
178 return nil, fmt.Errorf("创建网站目录: %w", err)
179 }
180 createdRoot = true
181 }
182 if err := s.writeSkeleton(st); err != nil {
183 if createdRoot {
184 _ = os.RemoveAll(st.Root)
185 }
186 return nil, err
187 }
188 s.chownRoot(ctx, st)
189 if isApp(st.Kind) && st.StartCmd != "" {
190 if err := s.writeUnit(ctx, st); err != nil {
191 s.rollbackCreate(ctx, st, createdRoot)
192 return nil, err
193 }
194 }
195 if err := s.nginx.ApplySite(ctx, st); err != nil {
196 s.rollbackCreate(ctx, st, createdRoot)
197 return nil, err
198 }
199 if err := s.db.CreateSite(ctx, st); err != nil {
200 s.rollbackCreate(ctx, st, createdRoot)
201 return nil, err
202 }
203 return st, nil
204}
205
206// Update changes mutable attributes and re-renders configuration.
207func (s *Service) Update(ctx context.Context, id int64, in Input) (*store.Site, error) {
208 s.mu.Lock()
209 defer s.mu.Unlock()
210 st, err := s.db.SiteByID(ctx, id)
211 if err != nil {
212 return nil, err
213 }
214 // A partial client must not silently reset security relevant settings:
215 // every option it did not send keeps the stored value.
216 in.Options = mergeOptions(st.Options, in.Options)
217 if err := s.validate(ctx, &in, id); err != nil {
218 return nil, err
219 }
220 if strings.TrimSpace(in.Root) != "" {
221 root, err := s.projectPath(in.Root)
222 if err != nil {
223 return nil, err
224 }
225 in.Root = root
226 }
227 if in.Root == "" {
228 in.Root = st.Root
229 }
230 if in.Name == "" {
231 in.Name = st.Name
232 }
233 if st.Kind == "go" && strings.TrimSpace(in.StartCmd) == "" {
234 cmd, err := s.resolveGoCommand(in.Root, st.Slug)
235 if err != nil {
236 return nil, err
237 }
238 in.StartCmd = cmd
239 }
240 if st.Kind == "go" && in.StartCmd != "" {
241 if err := ensureExecutable(in.Root, in.StartCmd); err != nil {
242 return nil, err
243 }
244 }
245 in.Domains = normalizeDomainList(in.Domains)
246 // Older API clients do not send gateway_port; keep the allocated one or
247 // the next apply would have to renumber it and briefly disable deep
248 // inspection for this site.
249 if in.Options.GatewayPort == 0 {
250 in.Options.GatewayPort = st.Options.GatewayPort
251 }
252 if in.Options.ListenPort == 0 {
253 in.Options.ListenPort = st.Options.ListenPort
254 }
255 s.ensureGatewayPort(ctx, &in.Options)
256 // Empty values mean "unchanged": an older mobile client that only edits the
257 // remark must not blank the run user (systemd would then run as root) or
258 // the PHP version.
259 if in.PHPVersion == "" {
260 in.PHPVersion = st.PHPVersion
261 }
262 if in.RunUser == "" {
263 in.RunUser = st.RunUser
264 }
265 if in.StartCmd == "" {
266 in.StartCmd = st.StartCmd
267 }
268 if strings.TrimSpace(in.Upstream) == "" {
269 in.Upstream = st.Upstream
270 }
271 st.Name = in.Name
272 st.Root = in.Root
273 st.PHPVersion = in.PHPVersion
274 st.RunUser = in.RunUser
275 st.StartCmd = in.StartCmd
276 st.Env = in.Env
277 st.Upstream = in.Upstream
278 st.Remark = in.Remark
279 st.Options = in.Options
280 if len(in.Domains) > 0 {
281 st.Domains = in.Domains
282 }
283 if isApp(st.Kind) {
284 if in.Port > 0 && in.Port != st.Port {
285 used, err := s.db.PortsInUse(ctx)
286 if err != nil {
287 return nil, err
288 }
289 if owner, taken := used[in.Port]; taken && owner != st.Slug {
290 return nil, invalid("端口 %d 已被站点 %s 使用", in.Port, owner)
291 }
292 st.Port = in.Port
293 }
294 if strings.TrimSpace(st.Upstream) == "" {
295 st.Upstream = "http://127.0.0.1:" + strconv.Itoa(st.Port)
296 }
297 }
298 if err := s.writeSkeleton(st); err != nil {
299 return nil, err
300 }
301 s.chownRoot(ctx, st)
302 if isApp(st.Kind) && st.StartCmd != "" {
303 if err := s.writeUnit(ctx, st); err != nil {
304 return nil, err
305 }
306 }
307 if err := s.nginx.ApplySite(ctx, st); err != nil {
308 return nil, err
309 }
310 if err := s.db.UpdateSite(ctx, st); err != nil {
311 return nil, err
312 }
313 return st, nil
314}
315
316// Delete removes configuration, the unit and optionally the document root.
317func (s *Service) Delete(ctx context.Context, id int64, removeFiles bool) error {
318 st, err := s.db.SiteByID(ctx, id)
319 if err != nil {
320 return err
321 }
322 if isApp(st.Kind) {
323 svc := s.serviceFor(st)
324 _ = svc.Remove(ctx)
325 }
326 if err := s.nginx.DeleteSite(ctx, st.Slug); err != nil {
327 return err
328 }
329 if err := s.db.DeleteSite(ctx, id); err != nil {
330 return err
331 }
332 _ = s.db.DeleteSSLCert(ctx, id)
333 _ = os.RemoveAll(filepath.Join(s.cfg.Nginx.CertDir, st.Slug))
334 _ = os.RemoveAll(s.cfg.SiteLogDir(st.Slug))
335 // The launcher script is panel owned and must not outlive the site.
336 _ = os.Remove(filepath.Join(st.Root, ".mp-start.sh"))
337 if removeFiles {
338 root := filepath.Clean(st.Root)
339 if s.safeToRemove(root) {
340 if err := os.RemoveAll(root); err != nil {
341 return fmt.Errorf("删除网站目录失败: %w", err)
342 }
343 }
344 }
345 return nil
346}
347
348// Action performs start/stop/restart for application sites.
349func (s *Service) Action(ctx context.Context, id int64, action string) error {
350 st, err := s.db.SiteByID(ctx, id)
351 if err != nil {
352 return err
353 }
354 if !isApp(st.Kind) {
355 return errors.New("静态/PHP 站点无需启停")
356 }
357 svc := s.serviceFor(st)
358 // A binary replaced through the file manager loses its executable bit and
359 // systemd then restarts forever with status 126. Repair it before every
360 // start instead of surfacing an opaque exit code.
361 if action == "start" || action == "restart" {
362 if err := s.prepareApp(st); err != nil {
363 return err
364 }
365 }
366 switch action {
367 case "start":
368 if err := svc.Start(ctx); err != nil {
369 return s.appActionError(ctx, svc, st, "启动", err)
370 }
371 return s.db.UpdateSiteStatus(ctx, id, "running")
372 case "stop":
373 if err := svc.Stop(ctx); err != nil {
374 return err
375 }
376 return s.db.UpdateSiteStatus(ctx, id, "stopped")
377 case "restart":
378 if err := svc.Restart(ctx); err != nil {
379 return s.appActionError(ctx, svc, st, "重启", err)
380 }
381 return s.db.UpdateSiteStatus(ctx, id, "running")
382 default:
383 return fmt.Errorf("未知操作 %q", action)
384 }
385}
386
387// prepareApp validates the run target before handing it to systemd.
388func (s *Service) prepareApp(st *store.Site) error {
389 if st.Kind != "go" {
390 return nil
391 }
392 if strings.TrimSpace(st.StartCmd) == "" {
393 return errors.New("站点没有配置启动命令,请在「更多配置」中填写可执行文件")
394 }
395 return ensureExecutable(st.Root, st.StartCmd)
396}
397
398// appActionError appends the recent unit output so a bare exit code becomes
399// actionable in the UI.
400func (s *Service) appActionError(ctx context.Context, svc *system.Service, st *store.Site, verb string, err error) error {
401 tail, _ := svc.Logs(ctx, 5)
402 tail = strings.TrimSpace(tail)
403 if tail == "" {
404 if lines, ferr := system.Tail(filepath.Join(s.cfg.SiteLogDir(st.Slug), "app.log"), 5); ferr == nil {
405 tail = strings.TrimSpace(strings.Join(lines, " | "))
406 }
407 }
408 if tail == "" {
409 return fmt.Errorf("%s失败: %w", verb, err)
410 }
411 return fmt.Errorf("%s失败: %w;最近日志: %s", verb, err, tail)
412}
413
414// Logs returns the tail of access, error or application logs.
415func (s *Service) Logs(ctx context.Context, id int64, kind string, lines int) ([]string, error) {
416 st, err := s.db.SiteByID(ctx, id)
417 if err != nil {
418 return nil, err
419 }
420 if lines <= 0 || lines > 2000 {
421 lines = 300
422 }
423 switch kind {
424 case "access":
425 return tailLog(filepath.Join(s.cfg.SiteLogDir(st.Slug), "access.log"), lines)
426 case "error":
427 return tailLog(filepath.Join(s.cfg.SiteLogDir(st.Slug), "error.log"), lines)
428 case "app":
429 if !isApp(st.Kind) {
430 return nil, errors.New("该站点没有应用日志")
431 }
432 out, err := s.serviceFor(st).Logs(ctx, lines)
433 if err != nil {
434 return nil, err
435 }
436 return strings.Split(strings.TrimRight(out, "\n"), "\n"), nil
437 default:
438 return nil, fmt.Errorf("未知日志类型 %q", kind)
439 }
440}
441
442// tailLog treats a missing log file as an empty log: a freshly created site
443// has no access/error log yet and that is not an error worth showing the user.
444func tailLog(path string, lines int) ([]string, error) {
445 out, err := system.Tail(path, lines)
446 if err != nil {
447 if os.IsNotExist(err) {
448 return []string{}, nil
449 }
450 return nil, err
451 }
452 return out, nil
453}
454
455// WriteRewrite replaces the rewrite snippet after validation.
456func (s *Service) WriteRewrite(ctx context.Context, id int64, content string) error {
457 st, err := s.db.SiteByID(ctx, id)
458 if err != nil {
459 return err
460 }
461 if len(content) > 256*1024 {
462 return errors.New("伪静态内容过大")
463 }
464 return s.nginx.Apply(ctx, &webserver.Render{Files: map[string][]byte{
465 s.cfg.RewritePath(st.Slug): []byte(content),
466 }})
467}
468
469// normalizeDomainList trims and lowercases operator input.
470func normalizeDomainList(list []string) []string {
471 out := make([]string, 0, len(list))
472 for _, d := range list {
473 d = strings.ToLower(strings.TrimSpace(d))
474 d = strings.TrimPrefix(d, "http://")
475 d = strings.TrimPrefix(d, "https://")
476 d = strings.TrimSuffix(d, "/")
477 if d != "" {
478 out = append(out, d)
479 }
480 }
481 return out
482}
483
484// mergeOptions keeps every stored field the request did not mention, so a
485// partial update cannot silently disable security headers or reset WAF rates.
486func mergeOptions(old, in store.SiteOptions) store.SiteOptions {
487 if len(in.Present) == 0 {
488 // The request carried no options at all (older client, or only the
489 // remark was edited): keep every stored value.
490 return old
491 }
492 out := old
493 if in.Present["https_redirect"] {
494 out.HTTPSRedirect = in.HTTPSRedirect
495 }
496 if in.Present["hsts"] {
497 out.HSTS = in.HSTS
498 }
499 if in.Present["security_headers"] {
500 out.SecurityHead = in.SecurityHead
501 }
502 if in.Present["limit_rate_kb"] {
503 out.LimitRate = in.LimitRate
504 }
505 if in.Present["conn_per_ip"] {
506 out.ConnPerIP = in.ConnPerIP
507 }
508 if in.Present["conn_per_server"] {
509 out.ConnPerServer = in.ConnPerServer
510 }
511 if in.Present["anti_leech"] {
512 out.AntiLeak = in.AntiLeak
513 }
514 if in.Present["anti_leech_hosts"] {
515 out.AntiLeakHosts = in.AntiLeakHosts
516 }
517 if in.Present["ip_mode"] {
518 out.IPMode = in.IPMode
519 }
520 if in.Present["ip_list"] {
521 out.IPList = in.IPList
522 }
523 if in.Present["waf"] {
524 out.WAF = in.WAF
525 }
526 if in.Present["waf_rate"] {
527 out.WAFRate = in.WAFRate
528 }
529 if in.Present["waf_burst"] {
530 out.WAFBurst = in.WAFBurst
531 }
532 if in.Present["gateway_port"] {
533 out.GatewayPort = in.GatewayPort
534 }
535 if in.Present["custom_nginx"] {
536 out.Custom = in.Custom
537 }
538 if in.Present["listen_port"] {
539 out.ListenPort = in.ListenPort
540 }
541 if in.Present["docker_container_id"] {
542 out.DockerContainerID = in.DockerContainerID
543 }
544 if in.Present["docker_container_name"] {
545 out.DockerContainerName = in.DockerContainerName
546 }
547 if in.Present["docker_container_port"] {
548 out.DockerContainerPort = in.DockerContainerPort
549 }
550 if in.Present["docker_host_port"] {
551 out.DockerHostPort = in.DockerHostPort
552 }
553 out.Present = in.Present
554 return out
555}
556
557// deriveSlug turns the primary domain into a filesystem and systemd safe name.
558func deriveSlug(domain string) string {
559 domain = strings.TrimPrefix(strings.ToLower(domain), "*.")
560 var b strings.Builder
561 for _, r := range domain {
562 switch {
563 case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
564 b.WriteRune(r)
565 case r == '.' || r == '-' || r == '_':
566 b.WriteRune('-')
567 }
568 }
569 slug := strings.Trim(b.String(), "-")
570 for strings.Contains(slug, "--") {
571 slug = strings.ReplaceAll(slug, "--", "-")
572 }
573 if len(slug) > 63 {
574 slug = slug[:63]
575 }
576 slug = strings.Trim(slug, "-")
577 if slug == "" {
578 slug = "site-" + strconv.FormatInt(time.Now().Unix(), 36)
579 }
580 return slug
581}
582
583// ValidationError marks user input problems so the API can answer 400.
584type ValidationError struct{ Msg string }
585
586func (e *ValidationError) Error() string { return e.Msg }
587
588func invalid(format string, args ...any) error {
589 return &ValidationError{Msg: fmt.Sprintf(format, args...)}
590}
591
592func (s *Service) validate(ctx context.Context, in *Input, exceptID int64) error {
593 if err := s.validateInner(ctx, in, exceptID); err != nil {
594 var ve *ValidationError
595 if errors.As(err, &ve) {
596 return err
597 }
598 return invalid("%s", err.Error())
599 }
600 return nil
601}
602
603func (s *Service) validateInner(ctx context.Context, in *Input, exceptID int64) error {
604 in.Name = strings.ToLower(strings.TrimSpace(in.Name))
605 if !slugRe.MatchString(in.Name) {
606 return errors.New("站点名称只能包含小写字母、数字、点、下划线和短横线,且不能以符号开头")
607 }
608 if !validKinds[in.Kind] {
609 return fmt.Errorf("不支持的站点类型 %q", in.Kind)
610 }
611 if len(in.Domains) == 0 {
612 return errors.New("至少需要一个域名")
613 }
614 seen := map[string]bool{}
615 clean := make([]string, 0, len(in.Domains))
616 for _, d := range in.Domains {
617 d = strings.ToLower(strings.TrimSpace(d))
618 d = strings.TrimPrefix(d, "http://")
619 d = strings.TrimPrefix(d, "https://")
620 d = strings.TrimSuffix(d, "/")
621 if !domainRe.MatchString(d) {
622 return fmt.Errorf("域名格式不正确: %q", d)
623 }
624 if seen[d] {
625 continue
626 }
627 seen[d] = true
628 clean = append(clean, d)
629 }
630 in.Domains = clean
631 if in.Root != "" {
632 if strings.ContainsAny(in.Root, " \n\t") {
633 return errors.New("网站目录不能包含空白字符")
634 }
635 root := filepath.Clean(in.Root)
636 rel, err := filepath.Rel(s.cfg.WebRoot, root)
637 if err != nil || rel == "." || strings.HasPrefix(rel, "..") {
638 return fmt.Errorf("网站目录必须位于 %s 内", s.cfg.WebRoot)
639 }
640 in.Root = root
641 }
642 if isApp(in.Kind) {
643 if in.Port != 0 && (in.Port < 1 || in.Port > 65535) {
644 return invalid("端口超出范围")
645 }
646 if in.Port == 80 || in.Port == 443 {
647 return invalid("应用端口不能占用 80/443,nginx 需要监听这两个端口")
648 }
649 if in.StartCmd != "" && shellUnsafe.MatchString(in.StartCmd) {
650 return invalid("启动命令不能包含 shell 元字符")
651 }
652 }
653 if in.Kind == "php" && in.PHPVersion != "" && !phpVersionRe.MatchString(in.PHPVersion) {
654 return invalid("PHP 版本格式不正确: %s", in.PHPVersion)
655 }
656 if in.Options.ListenPort != 0 && (in.Options.ListenPort < 1 || in.Options.ListenPort > 65535) {
657 return invalid("监听端口超出范围")
658 }
659 if in.Options.ListenPort == 443 {
660 return invalid("监听端口不能占用 443,HTTPS 固定使用该端口")
661 }
662 for _, ip := range in.Options.IPList {
663 if !validCIDR(ip) {
664 return invalid("IP 列表格式不正确: %s", ip)
665 }
666 }
667 for _, h := range in.Options.AntiLeakHosts {
668 if !validRefererHost(h) {
669 return invalid("防盗链域名格式不正确: %s", h)
670 }
671 }
672 if in.Kind == "proxy" {
673 up := strings.TrimSpace(in.Upstream)
674 if up == "" && in.Port == 0 {
675 return invalid("反向代理需要填写上游地址或端口")
676 }
677 if up != "" && !strings.HasPrefix(up, "http://") && !strings.HasPrefix(up, "https://") {
678 return invalid("上游地址必须以 http:// 或 https:// 开头")
679 }
680 }
681 for _, d := range in.Domains {
682 taken, err := s.db.DomainTaken(ctx, d, exceptID)
683 if err != nil {
684 return err
685 }
686 if taken {
687 return fmt.Errorf("域名 %s 已被其他站点使用", d)
688 }
689 }
690 return nil
691}
692
693func (s *Service) writeSkeleton(st *store.Site) error {
694 if err := os.MkdirAll(st.Root, 0o755); err != nil {
695 return err
696 }
697 index := filepath.Join(st.Root, "index.html")
698 if st.Kind == "static" && !fsutil.Exists(index) {
699 html := fmt.Sprintf(`<!doctype html>
700<html lang="zh-CN"><head><meta charset="utf-8"><title>%s</title>
701<style>body{font-family:system-ui,-apple-system,"Segoe UI",sans-serif;background:#0f1720;color:#e6edf3;display:flex;align-items:center;justify-content:center;height:100vh;margin:0}main{text-align:center}h1{font-weight:600;margin:0 0 8px}p{color:#8b949e}</style>
702</head><body><main><h1>%s</h1><p>站点已创建 · MiaoPanel</p></main></body></html>
703`, st.Name, st.Name)
704 if err := fsutil.WriteFileAtomic(index, []byte(html), 0o644); err != nil {
705 return err
706 }
707 }
708 // .user.ini restricts PHP open_basedir for this site only.
709 if st.Kind == "php" {
710 ini := fmt.Sprintf("open_basedir=%s/:%s/\n", st.Root, filepath.Join(s.cfg.PanelDir, "tmp"))
711 if err := fsutil.WriteFileAtomic(filepath.Join(st.Root, ".user.ini"), []byte(ini), 0o644); err != nil {
712 return err
713 }
714 }
715 return os.MkdirAll(s.cfg.SiteLogDir(st.Slug), 0o755)
716}
717
718func (s *Service) rollbackCreate(ctx context.Context, st *store.Site, createdRoot bool) {
719 if isApp(st.Kind) {
720 _ = s.serviceFor(st).Remove(ctx)
721 }
722 _ = s.nginx.DeleteSite(ctx, st.Slug)
723 if createdRoot {
724 _ = os.RemoveAll(st.Root)
725 }
726 _ = os.RemoveAll(s.cfg.ExtensionDir(st.Slug))
727}
728
729// chownRoot hands the document root to the runtime user so frameworks can
730// write caches, uploads and logs without the panel being involved.
731func (s *Service) chownRoot(ctx context.Context, st *store.Site) {
732 if runtime.GOOS != "linux" || st.RunUser == "" || !fileExists(st.Root) {
733 return
734 }
735 if _, err := user.Lookup(st.RunUser); err != nil {
736 return
737 }
738 _, _ = s.runner.Run(ctx, "chown", "-R", st.RunUser+":"+st.RunUser, st.Root)
739}
740
741func fileExists(p string) bool {
742 _, err := os.Stat(p)
743 return err == nil
744}
745
746func shQuote(s string) string {
747 return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
748}
749
750// validCIDR accepts a single address or a CIDR block, which is what the IP
751// control fragments can render safely.
752func validCIDR(s string) bool {
753 s = strings.TrimSpace(s)
754 if s == "" {
755 return false
756 }
757 if strings.Contains(s, "/") {
758 _, _, err := net.ParseCIDR(s)
759 return err == nil
760 }
761 return net.ParseIP(s) != nil
762}
763
764// validRefererHost keeps anti-leech hosts to characters valid_referers can
765// take; anything that could terminate the directive is rejected.
766func validRefererHost(s string) bool {
767 s = strings.TrimSpace(s)
768 if s == "" || len(s) > 255 {
769 return false
770 }
771 if strings.ContainsAny(s, " \t\r\n;\"'{}#\\") {
772 return false
773 }
774 return true
775}
776
777// ensureGatewayPort allocates the loopback origin port when deep inspection is
778// enabled globally. waf.Apply performs the same allocation in bulk; this keeps
779// a site created between two applies from temporarily losing protection.
780func (s *Service) ensureGatewayPort(ctx context.Context, opts *store.SiteOptions) {
781 if opts.GatewayPort > 0 {
782 return
783 }
784 v, err := s.db.Setting(ctx, "waf.gateway", "")
785 if err != nil || (v != "1" && v != "true") {
786 return
787 }
788 used, err := s.db.PortsInUse(ctx)
789 if err != nil {
790 return
791 }
792 port, err := system.AllocatePort(10000, 10999, used)
793 if err != nil {
794 return
795 }
796 opts.GatewayPort = port
797}
798
799func (s *Service) safeToRemove(p string) bool {
800 clean := filepath.Clean(p)
801 if clean == "/" || clean == "." || clean == "" {
802 return false
803 }
804 rel, err := filepath.Rel(s.cfg.WebRoot, clean)
805 if err != nil {
806 return false
807 }
808 return rel != "." && !strings.HasPrefix(rel, "..")
809}
810
811func (s *Service) serviceFor(st *store.Site) *system.Service {
812 return &system.Service{
813 Runner: s.runner,
814 Name: UnitName(st.Slug),
815 Distro: s.distro,
816 }
817}
818
819// UnitName is the systemd unit of a site.
820func UnitName(slug string) string { return "miaopanel-site-" + slug + ".service" }
821
822func isApp(kind string) bool { return kind == "go" || kind == "node" || kind == "proxy" }
823
824// writeUnit renders and installs the systemd unit of an application site.
825func (s *Service) writeUnit(ctx context.Context, st *store.Site) error {
826 if runtime.GOOS != "linux" {
827 return nil // preview mode on the development machine
828 }
829 if s.distro.ServiceManager() != "systemd" {
830 return errors.New("当前系统未使用 systemd,无法托管应用站点")
831 }
832 workdir := st.Root
833 logPath := filepath.Join(s.cfg.SiteLogDir(st.Slug), "app.log")
834 envFile := filepath.Join(st.Root, ".env")
835 if st.Env != "" {
836 if err := fsutil.WriteFileAtomic(envFile, []byte(st.Env+"\n"), 0o600); err != nil {
837 return err
838 }
839 }
840 // The command is stored in a script instead of being quoted into
841 // ExecStart: a start command containing a single quote produced an
842 // unbalanced unit file ("Unbalanced quoting") and the site never started,
843 // while the API still reported success. The script lives in the document
844 // root because the panel data dir is 0700 root and the unit runs as an
845 // unprivileged user; nginx refuses to serve ".mp-*" names.
846 startScript := filepath.Join(st.Root, ".mp-start.sh")
847 script := "#!/bin/sh\ncd " + shQuote(workdir) + "\nexec " + st.StartCmd + "\n"
848 if err := fsutil.WriteFileAtomic(startScript, []byte(script), 0o755); err != nil {
849 return err
850 }
851 memMax := ""
852 body := fmt.Sprintf(`[Unit]
853Description=MiaoPanel site %s
854After=network-online.target
855Wants=network-online.target
856
857[Service]
858Type=simple
859User=%s
860Group=%s
861WorkingDirectory=%s
862Environment=PATH=/www/server/node/current/bin:/www/server/go/current/bin:/www/server/python/current/bin:/usr/local/bin:/usr/bin:/bin
863EnvironmentFile=-%s
864ExecStart=/bin/sh %s
865Restart=always
866RestartSec=3
867LimitNOFILE=65535
868%s
869StandardOutput=append:%s
870StandardError=append:%s
871
872[Install]
873WantedBy=multi-user.target
874`, st.Slug, st.RunUser, st.RunUser, workdir, envFile, startScript, memMax, logPath, logPath)
875
876 svc := s.serviceFor(st)
877 if err := svc.WriteUnit(ctx, body); err != nil {
878 return err
879 }
880 return svc.Enable(ctx)
881}
882
883// AnnotateStatus fills Site.LiveStatus from the real service state so the UI
884// never claims a crashed application is still running.
885func (s *Service) AnnotateStatus(ctx context.Context, sites []*store.Site) {
886 nginx := s.nginx.Available()
887 sem := make(chan struct{}, 8)
888 var wg sync.WaitGroup
889 for _, st := range sites {
890 if !isApp(st.Kind) {
891 if nginx {
892 st.LiveStatus = "active"
893 } else {
894 st.LiveStatus = "preview"
895 }
896 continue
897 }
898 wg.Add(1)
899 sem <- struct{}{}
900 go func(site *store.Site) {
901 defer wg.Done()
902 defer func() { <-sem }()
903 site.LiveStatus = s.serviceFor(site).Active(ctx)
904 }(st)
905 }
906 wg.Wait()
907}
908
909// Port returns the application port of a site (0 for static/php).
910func Port(st *store.Site) int {
911 if isApp(st.Kind) {
912 return st.Port
913 }
914 return 0
915}
916
917// WaitHealthy polls the application port until it accepts connections.
918func (s *Service) WaitHealthy(ctx context.Context, st *store.Site, timeout time.Duration) bool {
919 if !isApp(st.Kind) {
920 return true
921 }
922 deadline := time.Now().Add(timeout)
923 for time.Now().Before(deadline) {
924 if system.Listening("127.0.0.1", st.Port) {
925 return true
926 }
927 select {
928 case <-ctx.Done():
929 return false
930 case <-time.After(500 * time.Millisecond):
931 }
932 }
933 return false
934}