// Package config loads, validates and persists the panel configuration. package config import ( "encoding/json" "errors" "fmt" "net" "os" "path/filepath" "runtime" "strings" ) // Nginx describes how the panel talks to the managed nginx instance. type Nginx struct { Bin string `json:"bin"` // nginx binary, empty = auto detect Conf string `json:"conf"` // main nginx.conf VhostDir string `json:"vhost_dir"` // directory holding per-site server blocks CertDir string `json:"cert_dir"` // ACME certificate storage ReloadCmd string `json:"reload_cmd"` // optional custom reload command } // DefaultUpdateURL is the release control plane queried by the update dialog. const DefaultUpdateURL = "https://mmmb.fangqihang.cn" // Config is the persisted panel configuration (config.json, mode 0600). type Config struct { Addr string `json:"addr"` Entry string `json:"entry"` // secret URL prefix, empty = disabled (not recommended) PanelDir string `json:"panel_dir"` DataDir string `json:"data_dir"` WebRoot string `json:"web_root"` LogDir string `json:"log_dir"` Nginx Nginx `json:"nginx"` SessionTTLMinutes int `json:"session_ttl_minutes"` SecureCookie bool `json:"secure_cookie"` TrustProxy bool `json:"trust_proxy"` Debug bool `json:"debug"` // UpdateURL is the control plane used for online upgrades. Empty falls back // to DefaultUpdateURL; UpdateCheck turns the startup check off entirely. UpdateURL string `json:"update_url"` UpdateCheck bool `json:"update_check"` // WAFGatewayAddr is the loopback listener of the deep inspection gateway. // It is never exposed directly; nginx proxies to it. WAFGatewayAddr string `json:"waf_gateway_addr"` // PluginRepoURL is the cloud control plane that publishes third-party // plugins. Empty falls back to the update server. PluginRepoURL string `json:"plugin_repo_url"` // PluginAutoUpdate installs signed patch updates in the background. PluginAutoUpdate bool `json:"plugin_auto_update"` // PluginsDir holds installed plugin files. PluginsDir string `json:"plugins_dir"` // HTTPS enables the built-in TLS endpoint. The panel serves HTTP and HTTPS // on the same port, so bookmarks, the installer and reverse proxies keep // working. A nil value means enabled: this way every config.json written by // an older release gains HTTPS after an upgrade without a migration step. HTTPS *bool `json:"https"` // HTTPSCert and HTTPSKey point at an operator supplied certificate. When // they are empty a self signed certificate is generated in DataDir/certs. HTTPSCert string `json:"https_cert"` HTTPSKey string `json:"https_key"` // HTTPSHosts adds extra names (a public IP behind NAT, a domain pointing at // this host) to the generated certificate. The machine's own addresses are // detected automatically; anything else must be listed here or browsers and // native clients reject the certificate with a name mismatch. HTTPSHosts []string `json:"https_hosts"` // AppDomain is the publicly trusted domain issued by the settings page for // the mobile app. When set, HTTPSCert/HTTPSKey point at its certificate. AppDomain string `json:"app_domain"` path string // location of config.json, not serialized } // Default returns platform aware defaults. func Default() *Config { linux := runtime.GOOS == "linux" c := &Config{ Addr: "0.0.0.0:8888", SessionTTLMinutes: 30, WAFGatewayAddr: "127.0.0.1:8899", UpdateURL: DefaultUpdateURL, UpdateCheck: true, PluginRepoURL: DefaultUpdateURL, } if linux { c.PanelDir = "/www/server/panel" c.WebRoot = "/www/wwwroot" c.LogDir = "/www/wwwlogs" c.Nginx = Nginx{ Bin: "/www/server/nginx/sbin/nginx", Conf: "/www/server/nginx/conf/nginx.conf", VhostDir: "/www/server/panel/vhost/nginx", CertDir: "/www/server/panel/vhost/cert", } } else { c.PanelDir = "./panel" c.WebRoot = "./wwwroot" c.LogDir = "./wwwlogs" c.Nginx = Nginx{ Bin: "", Conf: "", VhostDir: "./panel/vhost/nginx", CertDir: "./panel/vhost/cert", } } c.DataDir = filepath.Join(c.PanelDir, "data") c.PluginsDir = filepath.Join(c.PanelDir, "plugins") return c } // DefaultPath is the config location used when -config is not supplied. func DefaultPath() string { if runtime.GOOS == "linux" { return "/www/server/panel/config.json" } return "./panel/config.json" } // Load reads path into the defaults. A missing file is created with a fresh // security entry so the first start is immediately protected. func Load(path string) (*Config, error) { c := Default() c.path = path raw, err := os.ReadFile(path) created := false switch { case err == nil: if err := json.Unmarshal(raw, c); err != nil { return nil, fmt.Errorf("parse %s: %w", path, err) } case errors.Is(err, os.ErrNotExist): created = true if c.Entry == "" { c.Entry = RandomEntry(8) } default: return nil, err } if err := c.Normalize(); err != nil { return nil, err } // Relative paths are anchored at the config file so that "-config" works // from any working directory. c.resolveRelative() if created { if err := c.Save(); err != nil { return nil, err } } return c, nil } // resolveRelative anchors every relative path at the configuration directory. // The base is made absolute first: Save() persists the resolved values, and a // relative -config path would otherwise be re-anchored on every restart // (panel/panel/panel). func (c *Config) resolveRelative() { base := filepath.Dir(c.path) if base == "" { base = "." } if abs, err := filepath.Abs(base); err == nil { base = abs } resolve := func(p *string) { if *p != "" && !filepath.IsAbs(*p) { *p = filepath.Clean(filepath.Join(base, *p)) } } resolve(&c.PanelDir) resolve(&c.DataDir) resolve(&c.WebRoot) resolve(&c.LogDir) resolve(&c.PluginsDir) resolve(&c.Nginx.VhostDir) resolve(&c.Nginx.CertDir) resolve(&c.Nginx.Conf) resolve(&c.HTTPSCert) resolve(&c.HTTPSKey) } // Normalize fills derived fields and validates the security critical parts. func (c *Config) Normalize() error { if c.DataDir == "" { c.DataDir = filepath.Join(c.PanelDir, "data") } if c.PluginsDir == "" { c.PluginsDir = filepath.Join(c.PanelDir, "plugins") } if c.PluginRepoURL == "" { c.PluginRepoURL = DefaultUpdateURL } if c.Nginx.VhostDir == "" { c.Nginx.VhostDir = filepath.Join(c.PanelDir, "vhost", "nginx") } if c.Nginx.CertDir == "" { c.Nginx.CertDir = filepath.Join(c.PanelDir, "vhost", "cert") } if c.SessionTTLMinutes <= 0 { c.SessionTTLMinutes = 30 } if !validLoopbackAddr(c.WAFGatewayAddr) { c.WAFGatewayAddr = "127.0.0.1:8899" } if c.HTTPS == nil { on := true c.HTTPS = &on } // Trim and de-duplicate the extra certificate names once, so the generated // certificate stays stable across restarts (a changed set forces a re-issue). hosts := make([]string, 0, len(c.HTTPSHosts)) seenHost := map[string]bool{} for _, h := range c.HTTPSHosts { h = strings.TrimSpace(h) if h == "" || seenHost[h] { continue } seenHost[h] = true hosts = append(hosts, h) } c.HTTPSHosts = hosts c.Entry = normalizeEntry(c.Entry) c.resolveNginx() // Only absolute http(s) endpoints are acceptable for the update check. if u := strings.TrimSpace(c.UpdateURL); u != "" && !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") { c.UpdateURL = DefaultUpdateURL } if c.Entry != "" && len(c.Entry) < 6 { return fmt.Errorf("安全入口至少 6 个字符,当前为 %q", c.Entry) } return nil } // resolveNginx repairs stale or missing nginx paths. The panel can be // installed before nginx exists, and distributions disagree on both the // binary and the main configuration location, so detection happens at every // start instead of being frozen into config.json. func (c *Config) resolveNginx() { if c.Nginx.Bin == "" || !fileExists(c.Nginx.Bin) { if p := findNginx(); p != "" { c.Nginx.Bin = p } } if c.Nginx.Conf == "" || !fileExists(c.Nginx.Conf) { for _, p := range []string{ "/etc/nginx/nginx.conf", "/usr/local/nginx/conf/nginx.conf", "/www/server/nginx/conf/nginx.conf", } { if fileExists(p) { c.Nginx.Conf = p break } } } } // validLoopbackAddr keeps the inspection gateway on the loopback interface. // A public listener would expose an unauthenticated proxy. func validLoopbackAddr(addr string) bool { host, port, err := net.SplitHostPort(addr) if err != nil || port == "" { return false } if host == "localhost" { return true } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() } func fileExists(p string) bool { if p == "" { return false } st, err := os.Stat(p) return err == nil && !st.IsDir() } func normalizeEntry(s string) string { s = strings.TrimSpace(s) s = strings.Trim(s, "/") if s == "" { return "" } // Only URL safe, non ambiguous characters. var b strings.Builder for _, r := range s { switch { case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '-', r == '_': b.WriteRune(r) case r >= 'A' && r <= 'Z': b.WriteRune(r + 32) } } return b.String() } func findNginx() string { for _, p := range []string{"/www/server/nginx/sbin/nginx", "/usr/sbin/nginx", "/usr/local/sbin/nginx"} { if st, err := os.Stat(p); err == nil && !st.IsDir() { return p } } if p, err := lookPath("nginx"); err == nil { return p } return "" } // RefreshNginx re-detects the nginx binary and main configuration. It is used // after the app store installs nginx into a running panel. func (c *Config) RefreshNginx() { c.resolveNginx() } // Save writes the configuration atomically with 0600 permissions. func (c *Config) Save() error { if c.path == "" { c.path = DefaultPath() } if err := os.MkdirAll(filepath.Dir(c.path), 0o755); err != nil { return err } raw, err := json.MarshalIndent(c, "", " ") if err != nil { return err } return WriteFileAtomic(c.path, append(raw, '\n'), 0o600) } // Path reports where the configuration lives. func (c *Config) Path() string { return c.path } // SessionTTL returns the idle timeout of a session. func (c *Config) SessionTTL() int { return c.SessionTTLMinutes * 60 } // HTTPSEnabled reports whether the built-in TLS endpoint is active. func (c *Config) HTTPSEnabled() bool { return c.HTTPS == nil || *c.HTTPS } // SetHTTPS turns the built-in TLS endpoint on or off. func (c *Config) SetHTTPS(on bool) { v := on; c.HTTPS = &v } // SelfSignedDir holds the generated certificate of the panel. func (c *Config) SelfSignedDir() string { return filepath.Join(c.DataDir, "certs") } // UpdateBase returns the release control plane without a trailing slash. func (c *Config) UpdateBase() string { u := strings.TrimSpace(c.UpdateURL) if u == "" { u = DefaultUpdateURL } return strings.TrimRight(u, "/") } // SiteConfPath returns the main vhost file of a site. func (c *Config) SiteConfPath(slug string) string { return filepath.Join(c.Nginx.VhostDir, slug+".conf") } // ExtensionDir returns the per-site fragment directory. func (c *Config) ExtensionDir(slug string) string { return filepath.Join(c.Nginx.VhostDir, "extension", slug) } // PluginConfDir holds nginx fragments contributed by plugins. func (c *Config) PluginConfDir() string { return filepath.Join(c.Nginx.VhostDir, "plugin") } // PluginConfPath is the fragment of one plugin. func (c *Config) PluginConfPath(slug string) string { return filepath.Join(c.PluginConfDir(), slug+".conf") } // PluginDir is the install root of one plugin. func (c *Config) PluginDir(slug string) string { return filepath.Join(c.PluginsDir, slug) } // PluginDataDir is the writable state of one plugin. func (c *Config) PluginDataDir(slug string) string { return filepath.Join(c.DataDir, "plugins", slug) } // OriginConfPath returns the loopback origin server block used when traffic // is routed through the WAF gateway. func (c *Config) OriginConfPath(slug string) string { return filepath.Join(c.Nginx.VhostDir, slug+".origin.conf") } // RewritePath returns the per-site rewrite snippet. func (c *Config) RewritePath(slug string) string { return filepath.Join(c.Nginx.VhostDir, "rewrite", slug+".conf") } // WellKnownPath returns the ACME challenge include of a site. func (c *Config) WellKnownPath(slug string) string { return filepath.Join(c.Nginx.VhostDir, "well-known", slug+".conf") } // SiteRoot returns the default document root for a slug. func (c *Config) SiteRoot(slug string) string { return filepath.Join(c.WebRoot, slug) } // SiteLogDir returns the per-site log directory. func (c *Config) SiteLogDir(slug string) string { return filepath.Join(c.LogDir, slug) } // EnsureDirs creates all directories the panel needs. func (c *Config) EnsureDirs() error { dirs := []string{ c.DataDir, c.WebRoot, c.LogDir, c.Nginx.VhostDir, filepath.Join(c.Nginx.VhostDir, "http"), filepath.Join(c.Nginx.VhostDir, "extension"), filepath.Join(c.Nginx.VhostDir, "rewrite"), filepath.Join(c.Nginx.VhostDir, "well-known"), c.PluginConfDir(), c.Nginx.CertDir, filepath.Join(c.DataDir, "backups"), filepath.Join(c.DataDir, "tmp"), filepath.Join(c.DataDir, "tmp", "plugins"), filepath.Join(c.DataDir, "plugins"), filepath.Join(c.DataDir, "plugins-trash"), c.PluginsDir, c.SelfSignedDir(), } for _, d := range dirs { if strings.TrimSpace(d) == "" { // Configs built programmatically in tests may skip Normalize. continue } if err := os.MkdirAll(d, 0o755); err != nil { return fmt.Errorf("创建目录 %s: %w", d, err) } } return nil }