miaopanel
1package webserver
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "path/filepath"
8 "regexp"
9 "sort"
10 "strings"
11 "sync"
12 "time"
13
14 "github.com/miaopanel/miaopanel/internal/config"
15 "github.com/miaopanel/miaopanel/internal/fsutil"
16 "github.com/miaopanel/miaopanel/internal/store"
17 "github.com/miaopanel/miaopanel/internal/system"
18)
19
20// Manager applies nginx configuration with validate-and-rollback semantics.
21type Manager struct {
22 cfg *config.Config
23 runner *system.Runner
24 distro system.Distro
25
26 wafMu sync.RWMutex
27 waf WAFConfig
28
29 // applyMu serializes render → write → nginx -t → reload. Without it a
30 // site update and a WAF reload can snapshot each other half way.
31 applyMu sync.Mutex
32}
33
34// New builds a manager bound to the panel configuration.
35func New(cfg *config.Config, runner *system.Runner) *Manager {
36 return &Manager{cfg: cfg, runner: runner, distro: system.Detect(), waf: DefaultWAF()}
37}
38
39// SetWAF replaces the global WAF configuration used for subsequent renders.
40func (m *Manager) SetWAF(w WAFConfig) {
41 m.wafMu.Lock()
42 m.waf = w
43 m.wafMu.Unlock()
44}
45
46// WAF returns the current global WAF configuration.
47func (m *Manager) WAF() WAFConfig {
48 m.wafMu.RLock()
49 defer m.wafMu.RUnlock()
50 return m.waf
51}
52
53// Available reports whether a usable nginx binary was found. On non Linux
54// development machines this is false and the panel runs in preview mode.
55func (m *Manager) Available() bool {
56 if m.cfg.Nginx.Bin == "" {
57 return false
58 }
59 st, err := os.Stat(m.cfg.Nginx.Bin)
60 return err == nil && !st.IsDir()
61}
62
63// Validate runs nginx -t. A missing binary is not an error in preview mode.
64func (m *Manager) Validate(ctx context.Context) (string, error) {
65 if !m.Available() {
66 return "preview mode: nginx 未安装,跳过配置校验", nil
67 }
68 args := []string{"-t"}
69 if m.cfg.Nginx.Conf != "" {
70 args = append(args, "-c", m.cfg.Nginx.Conf)
71 }
72 runCtx, cancel := context.WithTimeout(ctx, 25*time.Second)
73 defer cancel()
74 res, err := m.runner.Run(runCtx, m.cfg.Nginx.Bin, args...)
75 out := strings.TrimSpace(res.Stdout + "\n" + res.Stderr)
76 if err != nil {
77 return out, fmt.Errorf("nginx 配置校验失败: %s", out)
78 }
79 return out, nil
80}
81
82// Reload reloads nginx without dropping connections.
83func (m *Manager) Reload(ctx context.Context) error {
84 if !m.Available() {
85 return nil
86 }
87 return system.ReloadNginx(ctx, m.runner, m.cfg.Nginx.Bin)
88}
89
90// EnsureBase writes the shared snippets every site depends on.
91func (m *Manager) EnsureBase(ctx context.Context) error {
92 if err := m.cfg.EnsureDirs(); err != nil {
93 return err
94 }
95 if err := fsutil.WriteFileAtomic(
96 filepath.Join(m.cfg.Nginx.VhostDir, "common", "sensitive.conf"),
97 []byte(sensitiveFiles), 0o644); err != nil {
98 return err
99 }
100 // Zones are written together with the site files inside Apply so that a
101 // rejected configuration rolls them back as one unit.
102 return m.EnsureHTTPInclude(ctx)
103}
104
105const includeMarker = "miaopanel-http-include"
106
107var httpBlockRe = regexp.MustCompile(`(?m)^[ \t]*http[ \t]*\{`)
108
109// mainConfPatch returns the main configuration with the panel includes in
110// place, and reports whether anything changed.
111//
112// The http level include (vhost/nginx/http/*.conf) carries log_format mp_main,
113// which every site block references in its access_log directive. nginx parses
114// sequentially, so a missing, stale or wrongly ordered include turns every
115// site into "[emerg] unknown log format mp_main". Presence of the marker
116// comment alone is therefore not enough: the two include lines are verified
117// and re-inserted in the correct order whenever they are absent, point at an
118// old directory or sit after the site include.
119func (m *Manager) mainConfPatch(text string) (string, bool) {
120 vhost := strings.TrimRight(m.cfg.Nginx.VhostDir, "/")
121 siteInclude := "include " + vhost + "/*.conf;"
122 httpInclude := "include " + vhost + "/http/*.conf;"
123 // Plugins contribute http level snippets (server blocks or directives).
124 pluginInclude := "include " + vhost + "/plugin/*.conf;"
125 siteIdx := strings.Index(text, siteInclude)
126 httpIdx := strings.Index(text, httpInclude)
127 pluginIdx := strings.Index(text, pluginInclude)
128 if siteIdx >= 0 && httpIdx >= 0 && pluginIdx >= 0 &&
129 httpIdx < pluginIdx && pluginIdx < siteIdx {
130 return text, false
131 }
132 // Remove previous panel lines (possibly for another vhost directory) so a
133 // re-insertion cannot leave duplicates behind.
134 cleaned := m.stripPanelIncludes(text)
135 match := httpBlockRe.FindStringIndex(cleaned)
136 if match == nil {
137 // Unusual formatting such as "http" and "{" on separate lines: put the
138 // http include right above the site include, which is already inside
139 // the http block and therefore a valid position.
140 if siteIdx >= 0 {
141 block := " " + httpInclude + " # " + includeMarker + "\n " +
142 pluginInclude + "\n"
143 return text[:siteIdx] + block + text[siteIdx:], true
144 }
145 // No http block to patch: never touch a configuration we cannot verify.
146 return text, false
147 }
148 block := "\n " + httpInclude + " # " + includeMarker + "\n " +
149 pluginInclude + "\n " + siteInclude + "\n"
150 return cleaned[:match[1]] + block + cleaned[match[1]:], true
151}
152
153// stripPanelIncludes drops include lines that point into a panel vhost
154// directory, whatever directory they were rendered for. Only include
155// directives directing at ".../vhost/nginx" (the panel layout) are removed;
156// unrelated includes from the distribution are preserved.
157func (m *Manager) stripPanelIncludes(text string) string {
158 vhost := strings.TrimRight(m.cfg.Nginx.VhostDir, "/")
159 lines := strings.Split(text, "\n")
160 kept := make([]string, 0, len(lines))
161 for _, line := range lines {
162 trimmed := strings.TrimSpace(line)
163 if strings.HasPrefix(trimmed, "include ") && isPanelInclude(vhost, trimmed) {
164 continue
165 }
166 if strings.HasPrefix(trimmed, "#") && strings.Contains(trimmed, includeMarker) {
167 continue
168 }
169 kept = append(kept, line)
170 }
171 return strings.Join(kept, "\n")
172}
173
174// isPanelInclude reports whether an include directive targets the panel vhost
175// directory (either the site glob or the http level glob).
176func isPanelInclude(vhost, line string) bool {
177 path := strings.TrimPrefix(line, "include ")
178 if i := strings.Index(path, ";"); i >= 0 {
179 path = path[:i]
180 }
181 path = strings.TrimSpace(path)
182 dir := strings.TrimSuffix(path, "*.conf")
183 dir = strings.TrimSuffix(dir, "/")
184 dir = strings.TrimSuffix(dir, string(os.PathSeparator))
185 // http/ and plugin/ are subdirectories of the panel vhost tree.
186 if i := strings.LastIndexAny(dir, `/\`); i > 0 {
187 base := dir[i+1:]
188 if base == "http" || base == "plugin" {
189 dir = dir[:i]
190 }
191 }
192 return dir == vhost || strings.HasSuffix(dir, "/vhost/nginx") ||
193 strings.HasSuffix(dir, "\\vhost\\nginx")
194}
195
196// EnsureHTTPInclude makes sure nginx.conf loads the panel snippets and the site
197// blocks. The main configuration is not ours, so the change is backed up and
198// rolled back automatically when nginx refuses the result.
199func (m *Manager) EnsureHTTPInclude(ctx context.Context) error {
200 if m.cfg.Nginx.Conf == "" {
201 return nil
202 }
203 raw, err := os.ReadFile(m.cfg.Nginx.Conf)
204 if err != nil {
205 return nil // no main configuration to patch (preview mode)
206 }
207 patched, changed := m.mainConfPatch(string(raw))
208 if !changed {
209 return nil
210 }
211 backup, err := fsutil.BackupFile(m.cfg.Nginx.Conf, filepath.Join(m.cfg.DataDir, "backups", "nginx"))
212 if err != nil {
213 return err
214 }
215 if err := fsutil.WriteFileAtomic(m.cfg.Nginx.Conf, []byte(patched), 0o644); err != nil {
216 return err
217 }
218 if _, err := m.Validate(ctx); err != nil {
219 if backup != "" {
220 _ = fsutil.CopyFile(backup, m.cfg.Nginx.Conf)
221 } else {
222 _ = fsutil.WriteFileAtomic(m.cfg.Nginx.Conf, raw, 0o644)
223 }
224 return fmt.Errorf("向 nginx.conf 注入 include 失败,已回滚: %w", err)
225 }
226 return m.Reload(ctx)
227}
228
229type fileBackup struct {
230 data []byte
231 existed bool
232}
233
234// Apply applies a render atomically: write → test → reload, restoring every
235// touched file if any step fails.
236func (m *Manager) Apply(ctx context.Context, r *Render) error {
237 m.applyMu.Lock()
238 defer m.applyMu.Unlock()
239 return m.apply(ctx, r)
240}
241
242// apply is the lock-free implementation shared by Apply/ApplySite/ApplyAll.
243func (m *Manager) apply(ctx context.Context, r *Render) error {
244 if len(r.Files) == 0 && len(r.Remove) == 0 {
245 return nil
246 }
247 // Self-heal the main configuration first: without the http level include a
248 // freshly rendered site would be rejected with "unknown log format mp_main".
249 if err := m.EnsureHTTPInclude(ctx); err != nil {
250 return err
251 }
252 backup := map[string]fileBackup{}
253 snapshot := func(path string) error {
254 if _, ok := backup[path]; ok {
255 return nil
256 }
257 data, err := os.ReadFile(path)
258 if os.IsNotExist(err) {
259 backup[path] = fileBackup{}
260 return nil
261 }
262 if err != nil {
263 return err
264 }
265 backup[path] = fileBackup{data: data, existed: true}
266 return nil
267 }
268
269 keep := make(map[string]bool, len(r.Keep))
270 for _, p := range r.Keep {
271 keep[p] = true
272 }
273 paths := make([]string, 0, len(r.Files))
274 for p := range r.Files {
275 paths = append(paths, p)
276 }
277 sort.Strings(paths)
278 for _, p := range paths {
279 if keep[p] {
280 // Operator owned file: create it once, never overwrite it. Skipping
281 // the snapshot too keeps the rollback path from restoring it later.
282 if _, err := os.Stat(p); err == nil {
283 continue
284 }
285 }
286 if err := snapshot(p); err != nil {
287 return err
288 }
289 if err := fsutil.WriteFileAtomic(p, r.Files[p], 0o644); err != nil {
290 m.restore(backup)
291 return err
292 }
293 }
294 for _, p := range r.Remove {
295 if err := snapshot(p); err != nil {
296 m.restore(backup)
297 return err
298 }
299 if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
300 m.restore(backup)
301 return err
302 }
303 }
304
305 out, err := m.Validate(ctx)
306 if err != nil {
307 m.restore(backup)
308 return fmt.Errorf("%w\n%s", err, out)
309 }
310 if err := m.Reload(ctx); err != nil {
311 m.restore(backup)
312 _ = m.Reload(ctx)
313 return err
314 }
315 return nil
316}
317
318func (m *Manager) restore(b map[string]fileBackup) {
319 for p, o := range b {
320 if o.existed {
321 _ = fsutil.WriteFileAtomic(p, o.data, 0o644)
322 } else {
323 _ = os.Remove(p)
324 }
325 }
326}
327
328// baseRender carries the shared snippets that must travel with every apply.
329func (m *Manager) baseRender() *Render {
330 return &Render{Files: map[string][]byte{
331 filepath.Join(m.cfg.Nginx.VhostDir, "common", "sensitive.conf"): []byte(sensitiveFiles),
332 filepath.Join(m.cfg.Nginx.VhostDir, "http", "00-zones.conf"): []byte(zonesFor(m.WAF())),
333 }}
334}
335
336func mergeRender(dst, src *Render) {
337 for k, v := range src.Files {
338 dst.Files[k] = v
339 }
340 dst.Remove = append(dst.Remove, src.Remove...)
341 // Keep must travel with the files, otherwise ApplyAll (WAF change, panel
342 // restart) overwrites the operator's rewrite and ACME snippets again.
343 dst.Keep = append(dst.Keep, src.Keep...)
344}
345
346func (m *Manager) prepare(s *store.Site) error {
347 if err := os.MkdirAll(m.cfg.ExtensionDir(s.Slug), 0o755); err != nil {
348 return err
349 }
350 return os.MkdirAll(m.cfg.SiteLogDir(s.Slug), 0o755)
351}
352
353// ApplySite renders and applies a site, creating its directories first.
354func (m *Manager) ApplySite(ctx context.Context, s *store.Site) error {
355 m.applyMu.Lock()
356 defer m.applyMu.Unlock()
357 if err := m.prepare(s); err != nil {
358 return err
359 }
360 if err := m.EnsureBase(ctx); err != nil {
361 return err
362 }
363 r := m.baseRender()
364 mergeRender(r, RenderSite(m.cfg, s, m.WAF()))
365 return m.apply(ctx, r)
366}
367
368// ApplyAll renders every site plus the shared snippets in one validation and
369// reload cycle, so a bad rule cannot leave half of the fleet on new config.
370func (m *Manager) ApplyAll(ctx context.Context, sites []*store.Site) error {
371 m.applyMu.Lock()
372 defer m.applyMu.Unlock()
373 if err := m.EnsureBase(ctx); err != nil {
374 return err
375 }
376 r := m.baseRender()
377 for _, s := range sites {
378 if err := m.prepare(s); err != nil {
379 return err
380 }
381 mergeRender(r, RenderSite(m.cfg, s, m.WAF()))
382 }
383 return m.apply(ctx, r)
384}
385
386// DeleteSite removes every configuration file of a site (not its document
387// root, which the caller decides about).
388func (m *Manager) DeleteSite(ctx context.Context, slug string) error {
389 m.applyMu.Lock()
390 defer m.applyMu.Unlock()
391 r := &Render{Remove: []string{
392 m.cfg.SiteConfPath(slug),
393 m.cfg.OriginConfPath(slug),
394 m.cfg.RewritePath(slug),
395 m.cfg.WellKnownPath(slug),
396 }}
397 if err := m.apply(ctx, r); err != nil {
398 return err
399 }
400 return os.RemoveAll(m.cfg.ExtensionDir(slug))
401}
402
403func fileExists(p string) bool {
404 st, err := os.Stat(p)
405 return err == nil && !st.IsDir()
406}