miaopanel
1// Package config loads, validates and persists the panel configuration.
2package config
3
4import (
5 "encoding/json"
6 "errors"
7 "fmt"
8 "net"
9 "os"
10 "path/filepath"
11 "runtime"
12 "strings"
13)
14
15// Nginx describes how the panel talks to the managed nginx instance.
16type Nginx struct {
17 Bin string `json:"bin"` // nginx binary, empty = auto detect
18 Conf string `json:"conf"` // main nginx.conf
19 VhostDir string `json:"vhost_dir"` // directory holding per-site server blocks
20 CertDir string `json:"cert_dir"` // ACME certificate storage
21 ReloadCmd string `json:"reload_cmd"` // optional custom reload command
22}
23
24// DefaultUpdateURL is the release control plane queried by the update dialog.
25const DefaultUpdateURL = "https://mmmb.fangqihang.cn"
26
27// Config is the persisted panel configuration (config.json, mode 0600).
28type Config struct {
29 Addr string `json:"addr"`
30 Entry string `json:"entry"` // secret URL prefix, empty = disabled (not recommended)
31 PanelDir string `json:"panel_dir"`
32 DataDir string `json:"data_dir"`
33 WebRoot string `json:"web_root"`
34 LogDir string `json:"log_dir"`
35 Nginx Nginx `json:"nginx"`
36 SessionTTLMinutes int `json:"session_ttl_minutes"`
37 SecureCookie bool `json:"secure_cookie"`
38 TrustProxy bool `json:"trust_proxy"`
39 Debug bool `json:"debug"`
40 // UpdateURL is the control plane used for online upgrades. Empty falls back
41 // to DefaultUpdateURL; UpdateCheck turns the startup check off entirely.
42 UpdateURL string `json:"update_url"`
43 UpdateCheck bool `json:"update_check"`
44 // WAFGatewayAddr is the loopback listener of the deep inspection gateway.
45 // It is never exposed directly; nginx proxies to it.
46 WAFGatewayAddr string `json:"waf_gateway_addr"`
47 // PluginRepoURL is the cloud control plane that publishes third-party
48 // plugins. Empty falls back to the update server.
49 PluginRepoURL string `json:"plugin_repo_url"`
50 // PluginAutoUpdate installs signed patch updates in the background.
51 PluginAutoUpdate bool `json:"plugin_auto_update"`
52 // PluginsDir holds installed plugin files.
53 PluginsDir string `json:"plugins_dir"`
54 // HTTPS enables the built-in TLS endpoint. The panel serves HTTP and HTTPS
55 // on the same port, so bookmarks, the installer and reverse proxies keep
56 // working. A nil value means enabled: this way every config.json written by
57 // an older release gains HTTPS after an upgrade without a migration step.
58 HTTPS *bool `json:"https"`
59 // HTTPSCert and HTTPSKey point at an operator supplied certificate. When
60 // they are empty a self signed certificate is generated in DataDir/certs.
61 HTTPSCert string `json:"https_cert"`
62 HTTPSKey string `json:"https_key"`
63
64 // HTTPSHosts adds extra names (a public IP behind NAT, a domain pointing at
65 // this host) to the generated certificate. The machine's own addresses are
66 // detected automatically; anything else must be listed here or browsers and
67 // native clients reject the certificate with a name mismatch.
68 HTTPSHosts []string `json:"https_hosts"`
69
70 // AppDomain is the publicly trusted domain issued by the settings page for
71 // the mobile app. When set, HTTPSCert/HTTPSKey point at its certificate.
72 AppDomain string `json:"app_domain"`
73
74 path string // location of config.json, not serialized
75}
76
77// Default returns platform aware defaults.
78func Default() *Config {
79 linux := runtime.GOOS == "linux"
80 c := &Config{
81 Addr: "0.0.0.0:8888",
82 SessionTTLMinutes: 30,
83 WAFGatewayAddr: "127.0.0.1:8899",
84 UpdateURL: DefaultUpdateURL,
85 UpdateCheck: true,
86 PluginRepoURL: DefaultUpdateURL,
87 }
88 if linux {
89 c.PanelDir = "/www/server/panel"
90 c.WebRoot = "/www/wwwroot"
91 c.LogDir = "/www/wwwlogs"
92 c.Nginx = Nginx{
93 Bin: "/www/server/nginx/sbin/nginx",
94 Conf: "/www/server/nginx/conf/nginx.conf",
95 VhostDir: "/www/server/panel/vhost/nginx",
96 CertDir: "/www/server/panel/vhost/cert",
97 }
98 } else {
99 c.PanelDir = "./panel"
100 c.WebRoot = "./wwwroot"
101 c.LogDir = "./wwwlogs"
102 c.Nginx = Nginx{
103 Bin: "",
104 Conf: "",
105 VhostDir: "./panel/vhost/nginx",
106 CertDir: "./panel/vhost/cert",
107 }
108 }
109 c.DataDir = filepath.Join(c.PanelDir, "data")
110 c.PluginsDir = filepath.Join(c.PanelDir, "plugins")
111 return c
112}
113
114// DefaultPath is the config location used when -config is not supplied.
115func DefaultPath() string {
116 if runtime.GOOS == "linux" {
117 return "/www/server/panel/config.json"
118 }
119 return "./panel/config.json"
120}
121
122// Load reads path into the defaults. A missing file is created with a fresh
123// security entry so the first start is immediately protected.
124func Load(path string) (*Config, error) {
125 c := Default()
126 c.path = path
127 raw, err := os.ReadFile(path)
128 created := false
129 switch {
130 case err == nil:
131 if err := json.Unmarshal(raw, c); err != nil {
132 return nil, fmt.Errorf("parse %s: %w", path, err)
133 }
134 case errors.Is(err, os.ErrNotExist):
135 created = true
136 if c.Entry == "" {
137 c.Entry = RandomEntry(8)
138 }
139 default:
140 return nil, err
141 }
142 if err := c.Normalize(); err != nil {
143 return nil, err
144 }
145 // Relative paths are anchored at the config file so that "-config" works
146 // from any working directory.
147 c.resolveRelative()
148 if created {
149 if err := c.Save(); err != nil {
150 return nil, err
151 }
152 }
153 return c, nil
154}
155
156// resolveRelative anchors every relative path at the configuration directory.
157// The base is made absolute first: Save() persists the resolved values, and a
158// relative -config path would otherwise be re-anchored on every restart
159// (panel/panel/panel).
160func (c *Config) resolveRelative() {
161 base := filepath.Dir(c.path)
162 if base == "" {
163 base = "."
164 }
165 if abs, err := filepath.Abs(base); err == nil {
166 base = abs
167 }
168 resolve := func(p *string) {
169 if *p != "" && !filepath.IsAbs(*p) {
170 *p = filepath.Clean(filepath.Join(base, *p))
171 }
172 }
173 resolve(&c.PanelDir)
174 resolve(&c.DataDir)
175 resolve(&c.WebRoot)
176 resolve(&c.LogDir)
177 resolve(&c.PluginsDir)
178 resolve(&c.Nginx.VhostDir)
179 resolve(&c.Nginx.CertDir)
180 resolve(&c.Nginx.Conf)
181 resolve(&c.HTTPSCert)
182 resolve(&c.HTTPSKey)
183}
184
185// Normalize fills derived fields and validates the security critical parts.
186func (c *Config) Normalize() error {
187 if c.DataDir == "" {
188 c.DataDir = filepath.Join(c.PanelDir, "data")
189 }
190 if c.PluginsDir == "" {
191 c.PluginsDir = filepath.Join(c.PanelDir, "plugins")
192 }
193 if c.PluginRepoURL == "" {
194 c.PluginRepoURL = DefaultUpdateURL
195 }
196 if c.Nginx.VhostDir == "" {
197 c.Nginx.VhostDir = filepath.Join(c.PanelDir, "vhost", "nginx")
198 }
199 if c.Nginx.CertDir == "" {
200 c.Nginx.CertDir = filepath.Join(c.PanelDir, "vhost", "cert")
201 }
202 if c.SessionTTLMinutes <= 0 {
203 c.SessionTTLMinutes = 30
204 }
205 if !validLoopbackAddr(c.WAFGatewayAddr) {
206 c.WAFGatewayAddr = "127.0.0.1:8899"
207 }
208 if c.HTTPS == nil {
209 on := true
210 c.HTTPS = &on
211 }
212 // Trim and de-duplicate the extra certificate names once, so the generated
213 // certificate stays stable across restarts (a changed set forces a re-issue).
214 hosts := make([]string, 0, len(c.HTTPSHosts))
215 seenHost := map[string]bool{}
216 for _, h := range c.HTTPSHosts {
217 h = strings.TrimSpace(h)
218 if h == "" || seenHost[h] {
219 continue
220 }
221 seenHost[h] = true
222 hosts = append(hosts, h)
223 }
224 c.HTTPSHosts = hosts
225 c.Entry = normalizeEntry(c.Entry)
226 c.resolveNginx()
227 // Only absolute http(s) endpoints are acceptable for the update check.
228 if u := strings.TrimSpace(c.UpdateURL); u != "" &&
229 !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") {
230 c.UpdateURL = DefaultUpdateURL
231 }
232 if c.Entry != "" && len(c.Entry) < 6 {
233 return fmt.Errorf("安全入口至少 6 个字符,当前为 %q", c.Entry)
234 }
235 return nil
236}
237
238// resolveNginx repairs stale or missing nginx paths. The panel can be
239// installed before nginx exists, and distributions disagree on both the
240// binary and the main configuration location, so detection happens at every
241// start instead of being frozen into config.json.
242func (c *Config) resolveNginx() {
243 if c.Nginx.Bin == "" || !fileExists(c.Nginx.Bin) {
244 if p := findNginx(); p != "" {
245 c.Nginx.Bin = p
246 }
247 }
248 if c.Nginx.Conf == "" || !fileExists(c.Nginx.Conf) {
249 for _, p := range []string{
250 "/etc/nginx/nginx.conf",
251 "/usr/local/nginx/conf/nginx.conf",
252 "/www/server/nginx/conf/nginx.conf",
253 } {
254 if fileExists(p) {
255 c.Nginx.Conf = p
256 break
257 }
258 }
259 }
260}
261
262// validLoopbackAddr keeps the inspection gateway on the loopback interface.
263// A public listener would expose an unauthenticated proxy.
264func validLoopbackAddr(addr string) bool {
265 host, port, err := net.SplitHostPort(addr)
266 if err != nil || port == "" {
267 return false
268 }
269 if host == "localhost" {
270 return true
271 }
272 ip := net.ParseIP(host)
273 return ip != nil && ip.IsLoopback()
274}
275
276func fileExists(p string) bool {
277 if p == "" {
278 return false
279 }
280 st, err := os.Stat(p)
281 return err == nil && !st.IsDir()
282}
283
284func normalizeEntry(s string) string {
285 s = strings.TrimSpace(s)
286 s = strings.Trim(s, "/")
287 if s == "" {
288 return ""
289 }
290 // Only URL safe, non ambiguous characters.
291 var b strings.Builder
292 for _, r := range s {
293 switch {
294 case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '-', r == '_':
295 b.WriteRune(r)
296 case r >= 'A' && r <= 'Z':
297 b.WriteRune(r + 32)
298 }
299 }
300 return b.String()
301}
302
303func findNginx() string {
304 for _, p := range []string{"/www/server/nginx/sbin/nginx", "/usr/sbin/nginx", "/usr/local/sbin/nginx"} {
305 if st, err := os.Stat(p); err == nil && !st.IsDir() {
306 return p
307 }
308 }
309 if p, err := lookPath("nginx"); err == nil {
310 return p
311 }
312 return ""
313}
314
315// RefreshNginx re-detects the nginx binary and main configuration. It is used
316// after the app store installs nginx into a running panel.
317func (c *Config) RefreshNginx() { c.resolveNginx() }
318
319// Save writes the configuration atomically with 0600 permissions.
320func (c *Config) Save() error {
321 if c.path == "" {
322 c.path = DefaultPath()
323 }
324 if err := os.MkdirAll(filepath.Dir(c.path), 0o755); err != nil {
325 return err
326 }
327 raw, err := json.MarshalIndent(c, "", " ")
328 if err != nil {
329 return err
330 }
331 return WriteFileAtomic(c.path, append(raw, '\n'), 0o600)
332}
333
334// Path reports where the configuration lives.
335func (c *Config) Path() string { return c.path }
336
337// SessionTTL returns the idle timeout of a session.
338func (c *Config) SessionTTL() int { return c.SessionTTLMinutes * 60 }
339
340// HTTPSEnabled reports whether the built-in TLS endpoint is active.
341func (c *Config) HTTPSEnabled() bool { return c.HTTPS == nil || *c.HTTPS }
342
343// SetHTTPS turns the built-in TLS endpoint on or off.
344func (c *Config) SetHTTPS(on bool) { v := on; c.HTTPS = &v }
345
346// SelfSignedDir holds the generated certificate of the panel.
347func (c *Config) SelfSignedDir() string { return filepath.Join(c.DataDir, "certs") }
348
349// UpdateBase returns the release control plane without a trailing slash.
350func (c *Config) UpdateBase() string {
351 u := strings.TrimSpace(c.UpdateURL)
352 if u == "" {
353 u = DefaultUpdateURL
354 }
355 return strings.TrimRight(u, "/")
356}
357
358// SiteConfPath returns the main vhost file of a site.
359func (c *Config) SiteConfPath(slug string) string {
360 return filepath.Join(c.Nginx.VhostDir, slug+".conf")
361}
362
363// ExtensionDir returns the per-site fragment directory.
364func (c *Config) ExtensionDir(slug string) string {
365 return filepath.Join(c.Nginx.VhostDir, "extension", slug)
366}
367
368// PluginConfDir holds nginx fragments contributed by plugins.
369func (c *Config) PluginConfDir() string { return filepath.Join(c.Nginx.VhostDir, "plugin") }
370
371// PluginConfPath is the fragment of one plugin.
372func (c *Config) PluginConfPath(slug string) string {
373 return filepath.Join(c.PluginConfDir(), slug+".conf")
374}
375
376// PluginDir is the install root of one plugin.
377func (c *Config) PluginDir(slug string) string { return filepath.Join(c.PluginsDir, slug) }
378
379// PluginDataDir is the writable state of one plugin.
380func (c *Config) PluginDataDir(slug string) string {
381 return filepath.Join(c.DataDir, "plugins", slug)
382}
383
384// OriginConfPath returns the loopback origin server block used when traffic
385// is routed through the WAF gateway.
386func (c *Config) OriginConfPath(slug string) string {
387 return filepath.Join(c.Nginx.VhostDir, slug+".origin.conf")
388}
389
390// RewritePath returns the per-site rewrite snippet.
391func (c *Config) RewritePath(slug string) string {
392 return filepath.Join(c.Nginx.VhostDir, "rewrite", slug+".conf")
393}
394
395// WellKnownPath returns the ACME challenge include of a site.
396func (c *Config) WellKnownPath(slug string) string {
397 return filepath.Join(c.Nginx.VhostDir, "well-known", slug+".conf")
398}
399
400// SiteRoot returns the default document root for a slug.
401func (c *Config) SiteRoot(slug string) string {
402 return filepath.Join(c.WebRoot, slug)
403}
404
405// SiteLogDir returns the per-site log directory.
406func (c *Config) SiteLogDir(slug string) string {
407 return filepath.Join(c.LogDir, slug)
408}
409
410// EnsureDirs creates all directories the panel needs.
411func (c *Config) EnsureDirs() error {
412 dirs := []string{
413 c.DataDir,
414 c.WebRoot,
415 c.LogDir,
416 c.Nginx.VhostDir,
417 filepath.Join(c.Nginx.VhostDir, "http"),
418 filepath.Join(c.Nginx.VhostDir, "extension"),
419 filepath.Join(c.Nginx.VhostDir, "rewrite"),
420 filepath.Join(c.Nginx.VhostDir, "well-known"),
421 c.PluginConfDir(),
422 c.Nginx.CertDir,
423 filepath.Join(c.DataDir, "backups"),
424 filepath.Join(c.DataDir, "tmp"),
425 filepath.Join(c.DataDir, "tmp", "plugins"),
426 filepath.Join(c.DataDir, "plugins"),
427 filepath.Join(c.DataDir, "plugins-trash"),
428 c.PluginsDir,
429 c.SelfSignedDir(),
430 }
431 for _, d := range dirs {
432 if strings.TrimSpace(d) == "" {
433 // Configs built programmatically in tests may skip Normalize.
434 continue
435 }
436 if err := os.MkdirAll(d, 0o755); err != nil {
437 return fmt.Errorf("创建目录 %s: %w", d, err)
438 }
439 }
440 return nil
441}