package webserver import ( "context" "fmt" "os" "path/filepath" "regexp" "sort" "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" ) // Manager applies nginx configuration with validate-and-rollback semantics. type Manager struct { cfg *config.Config runner *system.Runner distro system.Distro wafMu sync.RWMutex waf WAFConfig // applyMu serializes render → write → nginx -t → reload. Without it a // site update and a WAF reload can snapshot each other half way. applyMu sync.Mutex } // New builds a manager bound to the panel configuration. func New(cfg *config.Config, runner *system.Runner) *Manager { return &Manager{cfg: cfg, runner: runner, distro: system.Detect(), waf: DefaultWAF()} } // SetWAF replaces the global WAF configuration used for subsequent renders. func (m *Manager) SetWAF(w WAFConfig) { m.wafMu.Lock() m.waf = w m.wafMu.Unlock() } // WAF returns the current global WAF configuration. func (m *Manager) WAF() WAFConfig { m.wafMu.RLock() defer m.wafMu.RUnlock() return m.waf } // Available reports whether a usable nginx binary was found. On non Linux // development machines this is false and the panel runs in preview mode. func (m *Manager) Available() bool { if m.cfg.Nginx.Bin == "" { return false } st, err := os.Stat(m.cfg.Nginx.Bin) return err == nil && !st.IsDir() } // Validate runs nginx -t. A missing binary is not an error in preview mode. func (m *Manager) Validate(ctx context.Context) (string, error) { if !m.Available() { return "preview mode: nginx 未安装,跳过配置校验", nil } args := []string{"-t"} if m.cfg.Nginx.Conf != "" { args = append(args, "-c", m.cfg.Nginx.Conf) } runCtx, cancel := context.WithTimeout(ctx, 25*time.Second) defer cancel() res, err := m.runner.Run(runCtx, m.cfg.Nginx.Bin, args...) out := strings.TrimSpace(res.Stdout + "\n" + res.Stderr) if err != nil { return out, fmt.Errorf("nginx 配置校验失败: %s", out) } return out, nil } // Reload reloads nginx without dropping connections. func (m *Manager) Reload(ctx context.Context) error { if !m.Available() { return nil } return system.ReloadNginx(ctx, m.runner, m.cfg.Nginx.Bin) } // EnsureBase writes the shared snippets every site depends on. func (m *Manager) EnsureBase(ctx context.Context) error { if err := m.cfg.EnsureDirs(); err != nil { return err } if err := fsutil.WriteFileAtomic( filepath.Join(m.cfg.Nginx.VhostDir, "common", "sensitive.conf"), []byte(sensitiveFiles), 0o644); err != nil { return err } // Zones are written together with the site files inside Apply so that a // rejected configuration rolls them back as one unit. return m.EnsureHTTPInclude(ctx) } const includeMarker = "miaopanel-http-include" var httpBlockRe = regexp.MustCompile(`(?m)^[ \t]*http[ \t]*\{`) // mainConfPatch returns the main configuration with the panel includes in // place, and reports whether anything changed. // // The http level include (vhost/nginx/http/*.conf) carries log_format mp_main, // which every site block references in its access_log directive. nginx parses // sequentially, so a missing, stale or wrongly ordered include turns every // site into "[emerg] unknown log format mp_main". Presence of the marker // comment alone is therefore not enough: the two include lines are verified // and re-inserted in the correct order whenever they are absent, point at an // old directory or sit after the site include. func (m *Manager) mainConfPatch(text string) (string, bool) { vhost := strings.TrimRight(m.cfg.Nginx.VhostDir, "/") siteInclude := "include " + vhost + "/*.conf;" httpInclude := "include " + vhost + "/http/*.conf;" // Plugins contribute http level snippets (server blocks or directives). pluginInclude := "include " + vhost + "/plugin/*.conf;" siteIdx := strings.Index(text, siteInclude) httpIdx := strings.Index(text, httpInclude) pluginIdx := strings.Index(text, pluginInclude) if siteIdx >= 0 && httpIdx >= 0 && pluginIdx >= 0 && httpIdx < pluginIdx && pluginIdx < siteIdx { return text, false } // Remove previous panel lines (possibly for another vhost directory) so a // re-insertion cannot leave duplicates behind. cleaned := m.stripPanelIncludes(text) match := httpBlockRe.FindStringIndex(cleaned) if match == nil { // Unusual formatting such as "http" and "{" on separate lines: put the // http include right above the site include, which is already inside // the http block and therefore a valid position. if siteIdx >= 0 { block := " " + httpInclude + " # " + includeMarker + "\n " + pluginInclude + "\n" return text[:siteIdx] + block + text[siteIdx:], true } // No http block to patch: never touch a configuration we cannot verify. return text, false } block := "\n " + httpInclude + " # " + includeMarker + "\n " + pluginInclude + "\n " + siteInclude + "\n" return cleaned[:match[1]] + block + cleaned[match[1]:], true } // stripPanelIncludes drops include lines that point into a panel vhost // directory, whatever directory they were rendered for. Only include // directives directing at ".../vhost/nginx" (the panel layout) are removed; // unrelated includes from the distribution are preserved. func (m *Manager) stripPanelIncludes(text string) string { vhost := strings.TrimRight(m.cfg.Nginx.VhostDir, "/") lines := strings.Split(text, "\n") kept := make([]string, 0, len(lines)) for _, line := range lines { trimmed := strings.TrimSpace(line) if strings.HasPrefix(trimmed, "include ") && isPanelInclude(vhost, trimmed) { continue } if strings.HasPrefix(trimmed, "#") && strings.Contains(trimmed, includeMarker) { continue } kept = append(kept, line) } return strings.Join(kept, "\n") } // isPanelInclude reports whether an include directive targets the panel vhost // directory (either the site glob or the http level glob). func isPanelInclude(vhost, line string) bool { path := strings.TrimPrefix(line, "include ") if i := strings.Index(path, ";"); i >= 0 { path = path[:i] } path = strings.TrimSpace(path) dir := strings.TrimSuffix(path, "*.conf") dir = strings.TrimSuffix(dir, "/") dir = strings.TrimSuffix(dir, string(os.PathSeparator)) // http/ and plugin/ are subdirectories of the panel vhost tree. if i := strings.LastIndexAny(dir, `/\`); i > 0 { base := dir[i+1:] if base == "http" || base == "plugin" { dir = dir[:i] } } return dir == vhost || strings.HasSuffix(dir, "/vhost/nginx") || strings.HasSuffix(dir, "\\vhost\\nginx") } // EnsureHTTPInclude makes sure nginx.conf loads the panel snippets and the site // blocks. The main configuration is not ours, so the change is backed up and // rolled back automatically when nginx refuses the result. func (m *Manager) EnsureHTTPInclude(ctx context.Context) error { if m.cfg.Nginx.Conf == "" { return nil } raw, err := os.ReadFile(m.cfg.Nginx.Conf) if err != nil { return nil // no main configuration to patch (preview mode) } patched, changed := m.mainConfPatch(string(raw)) if !changed { return nil } backup, err := fsutil.BackupFile(m.cfg.Nginx.Conf, filepath.Join(m.cfg.DataDir, "backups", "nginx")) if err != nil { return err } if err := fsutil.WriteFileAtomic(m.cfg.Nginx.Conf, []byte(patched), 0o644); err != nil { return err } if _, err := m.Validate(ctx); err != nil { if backup != "" { _ = fsutil.CopyFile(backup, m.cfg.Nginx.Conf) } else { _ = fsutil.WriteFileAtomic(m.cfg.Nginx.Conf, raw, 0o644) } return fmt.Errorf("向 nginx.conf 注入 include 失败,已回滚: %w", err) } return m.Reload(ctx) } type fileBackup struct { data []byte existed bool } // Apply applies a render atomically: write → test → reload, restoring every // touched file if any step fails. func (m *Manager) Apply(ctx context.Context, r *Render) error { m.applyMu.Lock() defer m.applyMu.Unlock() return m.apply(ctx, r) } // apply is the lock-free implementation shared by Apply/ApplySite/ApplyAll. func (m *Manager) apply(ctx context.Context, r *Render) error { if len(r.Files) == 0 && len(r.Remove) == 0 { return nil } // Self-heal the main configuration first: without the http level include a // freshly rendered site would be rejected with "unknown log format mp_main". if err := m.EnsureHTTPInclude(ctx); err != nil { return err } backup := map[string]fileBackup{} snapshot := func(path string) error { if _, ok := backup[path]; ok { return nil } data, err := os.ReadFile(path) if os.IsNotExist(err) { backup[path] = fileBackup{} return nil } if err != nil { return err } backup[path] = fileBackup{data: data, existed: true} return nil } keep := make(map[string]bool, len(r.Keep)) for _, p := range r.Keep { keep[p] = true } paths := make([]string, 0, len(r.Files)) for p := range r.Files { paths = append(paths, p) } sort.Strings(paths) for _, p := range paths { if keep[p] { // Operator owned file: create it once, never overwrite it. Skipping // the snapshot too keeps the rollback path from restoring it later. if _, err := os.Stat(p); err == nil { continue } } if err := snapshot(p); err != nil { return err } if err := fsutil.WriteFileAtomic(p, r.Files[p], 0o644); err != nil { m.restore(backup) return err } } for _, p := range r.Remove { if err := snapshot(p); err != nil { m.restore(backup) return err } if err := os.Remove(p); err != nil && !os.IsNotExist(err) { m.restore(backup) return err } } out, err := m.Validate(ctx) if err != nil { m.restore(backup) return fmt.Errorf("%w\n%s", err, out) } if err := m.Reload(ctx); err != nil { m.restore(backup) _ = m.Reload(ctx) return err } return nil } func (m *Manager) restore(b map[string]fileBackup) { for p, o := range b { if o.existed { _ = fsutil.WriteFileAtomic(p, o.data, 0o644) } else { _ = os.Remove(p) } } } // baseRender carries the shared snippets that must travel with every apply. func (m *Manager) baseRender() *Render { return &Render{Files: map[string][]byte{ filepath.Join(m.cfg.Nginx.VhostDir, "common", "sensitive.conf"): []byte(sensitiveFiles), filepath.Join(m.cfg.Nginx.VhostDir, "http", "00-zones.conf"): []byte(zonesFor(m.WAF())), }} } func mergeRender(dst, src *Render) { for k, v := range src.Files { dst.Files[k] = v } dst.Remove = append(dst.Remove, src.Remove...) // Keep must travel with the files, otherwise ApplyAll (WAF change, panel // restart) overwrites the operator's rewrite and ACME snippets again. dst.Keep = append(dst.Keep, src.Keep...) } func (m *Manager) prepare(s *store.Site) error { if err := os.MkdirAll(m.cfg.ExtensionDir(s.Slug), 0o755); err != nil { return err } return os.MkdirAll(m.cfg.SiteLogDir(s.Slug), 0o755) } // ApplySite renders and applies a site, creating its directories first. func (m *Manager) ApplySite(ctx context.Context, s *store.Site) error { m.applyMu.Lock() defer m.applyMu.Unlock() if err := m.prepare(s); err != nil { return err } if err := m.EnsureBase(ctx); err != nil { return err } r := m.baseRender() mergeRender(r, RenderSite(m.cfg, s, m.WAF())) return m.apply(ctx, r) } // ApplyAll renders every site plus the shared snippets in one validation and // reload cycle, so a bad rule cannot leave half of the fleet on new config. func (m *Manager) ApplyAll(ctx context.Context, sites []*store.Site) error { m.applyMu.Lock() defer m.applyMu.Unlock() if err := m.EnsureBase(ctx); err != nil { return err } r := m.baseRender() for _, s := range sites { if err := m.prepare(s); err != nil { return err } mergeRender(r, RenderSite(m.cfg, s, m.WAF())) } return m.apply(ctx, r) } // DeleteSite removes every configuration file of a site (not its document // root, which the caller decides about). func (m *Manager) DeleteSite(ctx context.Context, slug string) error { m.applyMu.Lock() defer m.applyMu.Unlock() r := &Render{Remove: []string{ m.cfg.SiteConfPath(slug), m.cfg.OriginConfPath(slug), m.cfg.RewritePath(slug), m.cfg.WellKnownPath(slug), }} if err := m.apply(ctx, r); err != nil { return err } return os.RemoveAll(m.cfg.ExtensionDir(slug)) } func fileExists(p string) bool { st, err := os.Stat(p) return err == nil && !st.IsDir() }