%s
站点已创建 · MiaoPanel
// Package site implements the lifecycle of a managed website or application. package site import ( "context" "errors" "fmt" "net" "os" "os/user" "path/filepath" "regexp" "runtime" "strconv" "strings" "sync" "time" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/fsutil" "github.com/miaopanel/miaopanel/internal/store" "github.com/miaopanel/miaopanel/internal/system" "github.com/miaopanel/miaopanel/internal/webserver" ) // Service owns site creation, updates and process control. type Service struct { cfg *config.Config db *store.Store nginx *webserver.Manager runner *system.Runner distro system.Distro // mu serialises create/update/delete. Port allocation reads the database // and only writes the new row after nginx accepted the config, so without // this lock two concurrent creations both pick the same free port. mu sync.Mutex } // NewService wires the site service. func NewService(cfg *config.Config, db *store.Store, ng *webserver.Manager, runner *system.Runner) *Service { return &Service{cfg: cfg, db: db, nginx: ng, runner: runner, distro: system.Detect()} } // BySlug loads a site by its stable identifier. func (s *Service) BySlug(ctx context.Context, slug string) (*store.Site, error) { return s.db.SiteBySlug(ctx, slug) } // Input describes a create-or-update request. type Input struct { Name string `json:"name"` Kind string `json:"kind"` Domains []string `json:"domains"` Root string `json:"root"` Port int `json:"port"` PHPVersion string `json:"php_version"` RunUser string `json:"run_user"` StartCmd string `json:"start_cmd"` Env string `json:"env"` Upstream string `json:"upstream"` Remark string `json:"remark"` Options store.SiteOptions } var ( slugRe = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`) 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:]+\]?$`) // Shell metacharacters are rejected in start commands even though the // command is run through `sh -lc` by systemd (product requirement: allow // simple commands such as "npm start" only). shellUnsafe = regexp.MustCompile("[;&|<>`$(){}\\[\\]\n\r]") // phpVersionRe keeps the value usable in a fastcgi_pass socket name. phpVersionRe = regexp.MustCompile(`^[0-9]+\.[0-9]+$`) ) var validKinds = map[string]bool{"static": true, "php": true, "go": true, "node": true, "proxy": true} // Create validates the input, allocates resources and applies configuration. // Any failure rolls back every step already performed. func (s *Service) Create(ctx context.Context, in Input) (*store.Site, error) { s.mu.Lock() defer s.mu.Unlock() if err := s.cfg.EnsureDirs(); err != nil { return nil, err } // The UI only asks for a domain; the identifier used for directories and // unit names is derived from it unless the operator overrides it. in.Domains = normalizeDomainList(in.Domains) in.Name = strings.ToLower(strings.TrimSpace(in.Name)) if in.Name == "" && len(in.Domains) > 0 { in.Name = deriveSlug(in.Domains[0]) } if strings.TrimSpace(in.Root) != "" { root, err := s.projectPath(in.Root) if err != nil { return nil, err } in.Root = root } if err := s.validate(ctx, &in, 0); err != nil { return nil, err } if existing, err := s.db.SiteBySlug(ctx, in.Name); err == nil && existing.ID != 0 { return nil, invalid("站点标识 %q 已被使用,请在「更多配置」中修改", in.Name) } slug := in.Name if in.Root == "" { in.Root = s.cfg.SiteRoot(slug) } if isApp(in.Kind) { used, err := s.db.PortsInUse(ctx) if err != nil { return nil, err } if in.Port == 0 { port, err := system.AllocatePort(8000, 9999, used) if err != nil { return nil, err } in.Port = port } else if owner, taken := used[in.Port]; taken { return nil, invalid("端口 %d 已被站点 %s 使用", in.Port, owner) } // An explicit upstream wins: proxy sites often point at an existing // service (https, another host, a path prefix) and overwriting it with // 127.0.0.1:Port made those sites silently proxy to the wrong place. if strings.TrimSpace(in.Upstream) == "" { in.Upstream = "http://127.0.0.1:" + strconv.Itoa(in.Port) } } // Go projects only need a binary; when the command is omitted we look for // an ELF/script in the project directory (same behaviour as the reference // panel, where project_cmd defaults to the selected executable). if in.Kind == "go" && strings.TrimSpace(in.StartCmd) == "" { cmd, err := s.resolveGoCommand(in.Root, slug) if err != nil { return nil, err } in.StartCmd = cmd } if in.Kind == "go" && in.StartCmd != "" { if err := ensureExecutable(in.Root, in.StartCmd); err != nil { return nil, err } } if in.Kind == "php" && in.PHPVersion == "" { in.PHPVersion = "8.2" } if in.RunUser == "" { in.RunUser = "www" } if in.Kind == "static" || in.Kind == "php" { in.Port = 80 } if in.Options.ListenPort != 0 && (in.Options.ListenPort < 1 || in.Options.ListenPort > 65535) { return nil, invalid("监听端口超出范围") } if !in.Options.SecurityHead { // Sensible secure-by-default for new sites. in.Options.SecurityHead = true } if in.Options.WAFRate == 0 { in.Options.WAFRate = 20 in.Options.WAFBurst = 40 } s.ensureGatewayPort(ctx, &in.Options) st := &store.Site{ Name: in.Name, Slug: slug, Kind: in.Kind, Root: in.Root, Port: in.Port, PHPVersion: in.PHPVersion, Status: "running", RunUser: in.RunUser, StartCmd: in.StartCmd, Env: in.Env, Upstream: in.Upstream, Remark: in.Remark, Options: in.Options, Domains: in.Domains, } createdRoot := false if _, err := os.Stat(st.Root); os.IsNotExist(err) { if err := os.MkdirAll(st.Root, 0o755); err != nil { return nil, fmt.Errorf("创建网站目录: %w", err) } createdRoot = true } if err := s.writeSkeleton(st); err != nil { if createdRoot { _ = os.RemoveAll(st.Root) } return nil, err } s.chownRoot(ctx, st) if isApp(st.Kind) && st.StartCmd != "" { if err := s.writeUnit(ctx, st); err != nil { s.rollbackCreate(ctx, st, createdRoot) return nil, err } } if err := s.nginx.ApplySite(ctx, st); err != nil { s.rollbackCreate(ctx, st, createdRoot) return nil, err } if err := s.db.CreateSite(ctx, st); err != nil { s.rollbackCreate(ctx, st, createdRoot) return nil, err } return st, nil } // Update changes mutable attributes and re-renders configuration. func (s *Service) Update(ctx context.Context, id int64, in Input) (*store.Site, error) { s.mu.Lock() defer s.mu.Unlock() st, err := s.db.SiteByID(ctx, id) if err != nil { return nil, err } // A partial client must not silently reset security relevant settings: // every option it did not send keeps the stored value. in.Options = mergeOptions(st.Options, in.Options) if err := s.validate(ctx, &in, id); err != nil { return nil, err } if strings.TrimSpace(in.Root) != "" { root, err := s.projectPath(in.Root) if err != nil { return nil, err } in.Root = root } if in.Root == "" { in.Root = st.Root } if in.Name == "" { in.Name = st.Name } if st.Kind == "go" && strings.TrimSpace(in.StartCmd) == "" { cmd, err := s.resolveGoCommand(in.Root, st.Slug) if err != nil { return nil, err } in.StartCmd = cmd } if st.Kind == "go" && in.StartCmd != "" { if err := ensureExecutable(in.Root, in.StartCmd); err != nil { return nil, err } } in.Domains = normalizeDomainList(in.Domains) // Older API clients do not send gateway_port; keep the allocated one or // the next apply would have to renumber it and briefly disable deep // inspection for this site. if in.Options.GatewayPort == 0 { in.Options.GatewayPort = st.Options.GatewayPort } if in.Options.ListenPort == 0 { in.Options.ListenPort = st.Options.ListenPort } s.ensureGatewayPort(ctx, &in.Options) // Empty values mean "unchanged": an older mobile client that only edits the // remark must not blank the run user (systemd would then run as root) or // the PHP version. if in.PHPVersion == "" { in.PHPVersion = st.PHPVersion } if in.RunUser == "" { in.RunUser = st.RunUser } if in.StartCmd == "" { in.StartCmd = st.StartCmd } if strings.TrimSpace(in.Upstream) == "" { in.Upstream = st.Upstream } st.Name = in.Name st.Root = in.Root st.PHPVersion = in.PHPVersion st.RunUser = in.RunUser st.StartCmd = in.StartCmd st.Env = in.Env st.Upstream = in.Upstream st.Remark = in.Remark st.Options = in.Options if len(in.Domains) > 0 { st.Domains = in.Domains } if isApp(st.Kind) { if in.Port > 0 && in.Port != st.Port { used, err := s.db.PortsInUse(ctx) if err != nil { return nil, err } if owner, taken := used[in.Port]; taken && owner != st.Slug { return nil, invalid("端口 %d 已被站点 %s 使用", in.Port, owner) } st.Port = in.Port } if strings.TrimSpace(st.Upstream) == "" { st.Upstream = "http://127.0.0.1:" + strconv.Itoa(st.Port) } } if err := s.writeSkeleton(st); err != nil { return nil, err } s.chownRoot(ctx, st) if isApp(st.Kind) && st.StartCmd != "" { if err := s.writeUnit(ctx, st); err != nil { return nil, err } } if err := s.nginx.ApplySite(ctx, st); err != nil { return nil, err } if err := s.db.UpdateSite(ctx, st); err != nil { return nil, err } return st, nil } // Delete removes configuration, the unit and optionally the document root. func (s *Service) Delete(ctx context.Context, id int64, removeFiles bool) error { st, err := s.db.SiteByID(ctx, id) if err != nil { return err } if isApp(st.Kind) { svc := s.serviceFor(st) _ = svc.Remove(ctx) } if err := s.nginx.DeleteSite(ctx, st.Slug); err != nil { return err } if err := s.db.DeleteSite(ctx, id); err != nil { return err } _ = s.db.DeleteSSLCert(ctx, id) _ = os.RemoveAll(filepath.Join(s.cfg.Nginx.CertDir, st.Slug)) _ = os.RemoveAll(s.cfg.SiteLogDir(st.Slug)) // The launcher script is panel owned and must not outlive the site. _ = os.Remove(filepath.Join(st.Root, ".mp-start.sh")) if removeFiles { root := filepath.Clean(st.Root) if s.safeToRemove(root) { if err := os.RemoveAll(root); err != nil { return fmt.Errorf("删除网站目录失败: %w", err) } } } return nil } // Action performs start/stop/restart for application sites. func (s *Service) Action(ctx context.Context, id int64, action string) error { st, err := s.db.SiteByID(ctx, id) if err != nil { return err } if !isApp(st.Kind) { return errors.New("静态/PHP 站点无需启停") } svc := s.serviceFor(st) // A binary replaced through the file manager loses its executable bit and // systemd then restarts forever with status 126. Repair it before every // start instead of surfacing an opaque exit code. if action == "start" || action == "restart" { if err := s.prepareApp(st); err != nil { return err } } switch action { case "start": if err := svc.Start(ctx); err != nil { return s.appActionError(ctx, svc, st, "启动", err) } return s.db.UpdateSiteStatus(ctx, id, "running") case "stop": if err := svc.Stop(ctx); err != nil { return err } return s.db.UpdateSiteStatus(ctx, id, "stopped") case "restart": if err := svc.Restart(ctx); err != nil { return s.appActionError(ctx, svc, st, "重启", err) } return s.db.UpdateSiteStatus(ctx, id, "running") default: return fmt.Errorf("未知操作 %q", action) } } // prepareApp validates the run target before handing it to systemd. func (s *Service) prepareApp(st *store.Site) error { if st.Kind != "go" { return nil } if strings.TrimSpace(st.StartCmd) == "" { return errors.New("站点没有配置启动命令,请在「更多配置」中填写可执行文件") } return ensureExecutable(st.Root, st.StartCmd) } // appActionError appends the recent unit output so a bare exit code becomes // actionable in the UI. func (s *Service) appActionError(ctx context.Context, svc *system.Service, st *store.Site, verb string, err error) error { tail, _ := svc.Logs(ctx, 5) tail = strings.TrimSpace(tail) if tail == "" { if lines, ferr := system.Tail(filepath.Join(s.cfg.SiteLogDir(st.Slug), "app.log"), 5); ferr == nil { tail = strings.TrimSpace(strings.Join(lines, " | ")) } } if tail == "" { return fmt.Errorf("%s失败: %w", verb, err) } return fmt.Errorf("%s失败: %w;最近日志: %s", verb, err, tail) } // Logs returns the tail of access, error or application logs. func (s *Service) Logs(ctx context.Context, id int64, kind string, lines int) ([]string, error) { st, err := s.db.SiteByID(ctx, id) if err != nil { return nil, err } if lines <= 0 || lines > 2000 { lines = 300 } switch kind { case "access": return tailLog(filepath.Join(s.cfg.SiteLogDir(st.Slug), "access.log"), lines) case "error": return tailLog(filepath.Join(s.cfg.SiteLogDir(st.Slug), "error.log"), lines) case "app": if !isApp(st.Kind) { return nil, errors.New("该站点没有应用日志") } out, err := s.serviceFor(st).Logs(ctx, lines) if err != nil { return nil, err } return strings.Split(strings.TrimRight(out, "\n"), "\n"), nil default: return nil, fmt.Errorf("未知日志类型 %q", kind) } } // tailLog treats a missing log file as an empty log: a freshly created site // has no access/error log yet and that is not an error worth showing the user. func tailLog(path string, lines int) ([]string, error) { out, err := system.Tail(path, lines) if err != nil { if os.IsNotExist(err) { return []string{}, nil } return nil, err } return out, nil } // WriteRewrite replaces the rewrite snippet after validation. func (s *Service) WriteRewrite(ctx context.Context, id int64, content string) error { st, err := s.db.SiteByID(ctx, id) if err != nil { return err } if len(content) > 256*1024 { return errors.New("伪静态内容过大") } return s.nginx.Apply(ctx, &webserver.Render{Files: map[string][]byte{ s.cfg.RewritePath(st.Slug): []byte(content), }}) } // normalizeDomainList trims and lowercases operator input. func normalizeDomainList(list []string) []string { out := make([]string, 0, len(list)) for _, d := range list { d = strings.ToLower(strings.TrimSpace(d)) d = strings.TrimPrefix(d, "http://") d = strings.TrimPrefix(d, "https://") d = strings.TrimSuffix(d, "/") if d != "" { out = append(out, d) } } return out } // mergeOptions keeps every stored field the request did not mention, so a // partial update cannot silently disable security headers or reset WAF rates. func mergeOptions(old, in store.SiteOptions) store.SiteOptions { if len(in.Present) == 0 { // The request carried no options at all (older client, or only the // remark was edited): keep every stored value. return old } out := old if in.Present["https_redirect"] { out.HTTPSRedirect = in.HTTPSRedirect } if in.Present["hsts"] { out.HSTS = in.HSTS } if in.Present["security_headers"] { out.SecurityHead = in.SecurityHead } if in.Present["limit_rate_kb"] { out.LimitRate = in.LimitRate } if in.Present["conn_per_ip"] { out.ConnPerIP = in.ConnPerIP } if in.Present["conn_per_server"] { out.ConnPerServer = in.ConnPerServer } if in.Present["anti_leech"] { out.AntiLeak = in.AntiLeak } if in.Present["anti_leech_hosts"] { out.AntiLeakHosts = in.AntiLeakHosts } if in.Present["ip_mode"] { out.IPMode = in.IPMode } if in.Present["ip_list"] { out.IPList = in.IPList } if in.Present["waf"] { out.WAF = in.WAF } if in.Present["waf_rate"] { out.WAFRate = in.WAFRate } if in.Present["waf_burst"] { out.WAFBurst = in.WAFBurst } if in.Present["gateway_port"] { out.GatewayPort = in.GatewayPort } if in.Present["custom_nginx"] { out.Custom = in.Custom } if in.Present["listen_port"] { out.ListenPort = in.ListenPort } if in.Present["docker_container_id"] { out.DockerContainerID = in.DockerContainerID } if in.Present["docker_container_name"] { out.DockerContainerName = in.DockerContainerName } if in.Present["docker_container_port"] { out.DockerContainerPort = in.DockerContainerPort } if in.Present["docker_host_port"] { out.DockerHostPort = in.DockerHostPort } out.Present = in.Present return out } // deriveSlug turns the primary domain into a filesystem and systemd safe name. func deriveSlug(domain string) string { domain = strings.TrimPrefix(strings.ToLower(domain), "*.") var b strings.Builder for _, r := range domain { switch { case r >= 'a' && r <= 'z', r >= '0' && r <= '9': b.WriteRune(r) case r == '.' || r == '-' || r == '_': b.WriteRune('-') } } slug := strings.Trim(b.String(), "-") for strings.Contains(slug, "--") { slug = strings.ReplaceAll(slug, "--", "-") } if len(slug) > 63 { slug = slug[:63] } slug = strings.Trim(slug, "-") if slug == "" { slug = "site-" + strconv.FormatInt(time.Now().Unix(), 36) } return slug } // ValidationError marks user input problems so the API can answer 400. type ValidationError struct{ Msg string } func (e *ValidationError) Error() string { return e.Msg } func invalid(format string, args ...any) error { return &ValidationError{Msg: fmt.Sprintf(format, args...)} } func (s *Service) validate(ctx context.Context, in *Input, exceptID int64) error { if err := s.validateInner(ctx, in, exceptID); err != nil { var ve *ValidationError if errors.As(err, &ve) { return err } return invalid("%s", err.Error()) } return nil } func (s *Service) validateInner(ctx context.Context, in *Input, exceptID int64) error { in.Name = strings.ToLower(strings.TrimSpace(in.Name)) if !slugRe.MatchString(in.Name) { return errors.New("站点名称只能包含小写字母、数字、点、下划线和短横线,且不能以符号开头") } if !validKinds[in.Kind] { return fmt.Errorf("不支持的站点类型 %q", in.Kind) } if len(in.Domains) == 0 { return errors.New("至少需要一个域名") } seen := map[string]bool{} clean := make([]string, 0, len(in.Domains)) for _, d := range in.Domains { d = strings.ToLower(strings.TrimSpace(d)) d = strings.TrimPrefix(d, "http://") d = strings.TrimPrefix(d, "https://") d = strings.TrimSuffix(d, "/") if !domainRe.MatchString(d) { return fmt.Errorf("域名格式不正确: %q", d) } if seen[d] { continue } seen[d] = true clean = append(clean, d) } in.Domains = clean if in.Root != "" { if strings.ContainsAny(in.Root, " \n\t") { return errors.New("网站目录不能包含空白字符") } root := filepath.Clean(in.Root) rel, err := filepath.Rel(s.cfg.WebRoot, root) if err != nil || rel == "." || strings.HasPrefix(rel, "..") { return fmt.Errorf("网站目录必须位于 %s 内", s.cfg.WebRoot) } in.Root = root } if isApp(in.Kind) { if in.Port != 0 && (in.Port < 1 || in.Port > 65535) { return invalid("端口超出范围") } if in.Port == 80 || in.Port == 443 { return invalid("应用端口不能占用 80/443,nginx 需要监听这两个端口") } if in.StartCmd != "" && shellUnsafe.MatchString(in.StartCmd) { return invalid("启动命令不能包含 shell 元字符") } } if in.Kind == "php" && in.PHPVersion != "" && !phpVersionRe.MatchString(in.PHPVersion) { return invalid("PHP 版本格式不正确: %s", in.PHPVersion) } if in.Options.ListenPort != 0 && (in.Options.ListenPort < 1 || in.Options.ListenPort > 65535) { return invalid("监听端口超出范围") } if in.Options.ListenPort == 443 { return invalid("监听端口不能占用 443,HTTPS 固定使用该端口") } for _, ip := range in.Options.IPList { if !validCIDR(ip) { return invalid("IP 列表格式不正确: %s", ip) } } for _, h := range in.Options.AntiLeakHosts { if !validRefererHost(h) { return invalid("防盗链域名格式不正确: %s", h) } } if in.Kind == "proxy" { up := strings.TrimSpace(in.Upstream) if up == "" && in.Port == 0 { return invalid("反向代理需要填写上游地址或端口") } if up != "" && !strings.HasPrefix(up, "http://") && !strings.HasPrefix(up, "https://") { return invalid("上游地址必须以 http:// 或 https:// 开头") } } for _, d := range in.Domains { taken, err := s.db.DomainTaken(ctx, d, exceptID) if err != nil { return err } if taken { return fmt.Errorf("域名 %s 已被其他站点使用", d) } } return nil } func (s *Service) writeSkeleton(st *store.Site) error { if err := os.MkdirAll(st.Root, 0o755); err != nil { return err } index := filepath.Join(st.Root, "index.html") if st.Kind == "static" && !fsutil.Exists(index) { html := fmt.Sprintf(`
站点已创建 · MiaoPanel