// Package dbmanager manages MySQL/MariaDB databases through the local mysql // and mysqldump clients. It never builds a shell command: identifiers are // validated and values are escaped before they reach the SQL string. package dbmanager import ( "compress/gzip" "context" "crypto/rand" "encoding/base64" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "sync" "time" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/store" "github.com/miaopanel/miaopanel/internal/system" ) var ( nameRe = regexp.MustCompile(`^[A-Za-z0-9_]{1,32}$`) charsetRe = regexp.MustCompile(`^[A-Za-z0-9_]{2,20}$`) ) var systemDatabases = map[string]bool{ "information_schema": true, "mysql": true, "performance_schema": true, "sys": true, } // Service exposes database operations to the API layer. type Service struct { cfg *config.Config db *store.Store runner *system.Runner mu sync.Mutex } // New builds the database manager. func New(cfg *config.Config, db *store.Store) *Service { return &Service{cfg: cfg, db: db, runner: system.NewRunner()} } // Available reports whether a mysql client is present. func (s *Service) Available() bool { return mysqlBinary() != "" } // Info describes the local server for the advanced settings panel. type Info struct { Version string `json:"version"` DataDir string `json:"data_dir"` Port int `json:"port"` Socket string `json:"socket"` RootPasswordSet bool `json:"root_password_set"` Client string `json:"client"` } // Info reads server variables. func (s *Service) Info(ctx context.Context) (Info, error) { out, err := s.runSQL(ctx, `SELECT @@version, @@datadir, @@port, @@socket`) if err != nil { return Info{}, err } parts := strings.Split(strings.TrimSpace(out), "\t") info := Info{Client: mysqlBinary(), RootPasswordSet: s.rootPassword() != ""} if len(parts) > 0 { info.Version = parts[0] } if len(parts) > 1 { info.DataDir = parts[1] } if len(parts) > 2 { info.Port, _ = strconv.Atoi(parts[2]) } if len(parts) > 3 { info.Socket = parts[3] } return info, nil } // List synchronizes unmanaged databases and returns the tracked rows. func (s *Service) List(ctx context.Context, q string) ([]*store.ManagedDatabase, error) { if !s.Available() { return nil, errors.New("未检测到 mysql 客户端,请先在应用商店安装 MySQL 或 MariaDB") } if err := s.Sync(ctx); err != nil { return nil, err } return s.db.ListDatabases(ctx, q) } // Sync imports databases that exist on the server but not in the panel. func (s *Service) Sync(ctx context.Context) error { out, err := s.runSQL(ctx, `SHOW DATABASES`) if err != nil { return err } s.mu.Lock() defer s.mu.Unlock() for _, line := range strings.Split(out, "\n") { name := strings.TrimSpace(line) if name == "" || systemDatabases[name] { continue } if err := s.db.UpsertSyncedDatabase(ctx, name); err != nil { return err } } return nil } // CreateInput is the create-database payload. type CreateInput struct { Name string `json:"name"` Username string `json:"username"` Password string `json:"password"` Charset string `json:"charset"` Remark string `json:"remark"` Remote bool `json:"remote"` } // Create provisions a database and a dedicated user. func (s *Service) Create(ctx context.Context, in CreateInput) (*store.ManagedDatabase, error) { in.Name = strings.TrimSpace(in.Name) in.Username = strings.TrimSpace(in.Username) if in.Username == "" { in.Username = in.Name } if !nameRe.MatchString(in.Name) || !nameRe.MatchString(in.Username) { return nil, errors.New("数据库名和用户名只能包含字母、数字、下划线,长度 1-32") } if in.Charset == "" { in.Charset = "utf8mb4" } if !charsetRe.MatchString(in.Charset) { return nil, errors.New("字符集不合法") } if in.Password == "" { in.Password = randomPassword() } if err := validatePassword(in.Password); err != nil { return nil, err } if _, err := s.db.DatabaseByName(ctx, in.Name); err == nil { return nil, errors.New("该数据库已被面板管理") } else if !errors.Is(err, store.ErrNotFound) { return nil, err } host := "localhost" if in.Remote { host = "%" } if _, err := s.runSQL(ctx, fmt.Sprintf("CREATE DATABASE %s DEFAULT CHARACTER SET %s", quoteIdent(in.Name), in.Charset)); err != nil { return nil, fmt.Errorf("创建数据库失败: %w", err) } userSQL := fmt.Sprintf("CREATE USER %s@%s IDENTIFIED BY %s", quoteString(in.Username), quoteString(host), quoteString(in.Password)) if _, err := s.runSQL(ctx, userSQL); err != nil { _, _ = s.runSQL(ctx, "DROP DATABASE IF EXISTS "+quoteIdent(in.Name)) return nil, fmt.Errorf("创建数据库用户失败: %w", err) } grantSQL := fmt.Sprintf("GRANT ALL PRIVILEGES ON %s.* TO %s@%s", quoteIdent(in.Name), quoteString(in.Username), quoteString(host)) if _, err := s.runSQL(ctx, grantSQL); err != nil { _, _ = s.runSQL(ctx, "DROP USER IF EXISTS "+quoteString(in.Username)+"@"+quoteString(host)) _, _ = s.runSQL(ctx, "DROP DATABASE IF EXISTS "+quoteIdent(in.Name)) return nil, fmt.Errorf("授权失败: %w", err) } _, _ = s.runSQL(ctx, "FLUSH PRIVILEGES") row := &store.ManagedDatabase{ Name: in.Name, Username: in.Username, Password: in.Password, Host: host, Charset: in.Charset, Remark: in.Remark, Managed: true, } if err := s.db.CreateDatabase(ctx, row); err != nil { _, _ = s.runSQL(ctx, "DROP USER IF EXISTS "+quoteString(in.Username)+"@"+quoteString(host)) _, _ = s.runSQL(ctx, "DROP DATABASE IF EXISTS "+quoteIdent(in.Name)) return nil, err } return row, nil } // Delete drops a database, its user (when not shared) and its backups. func (s *Service) Delete(ctx context.Context, id int64) error { d, err := s.db.DatabaseByID(ctx, id) if err != nil { return err } if _, err := s.runSQL(ctx, "DROP DATABASE IF EXISTS "+quoteIdent(d.Name)); err != nil { return fmt.Errorf("删除数据库失败: %w", err) } if d.Managed { others, err := s.db.DatabasesByUsername(ctx, d.Username, d.ID) if err != nil { return err } if len(others) == 0 { _, _ = s.runSQL(ctx, fmt.Sprintf("DROP USER IF EXISTS %s@%s", quoteString(d.Username), quoteString(d.Host))) } } backups, _ := s.db.ListBackups(ctx, d.ID) for _, b := range backups { _ = os.Remove(b.Path) _ = s.db.DeleteBackup(ctx, b.ID) } return s.db.DeleteDatabase(ctx, id) } // ChangePassword rotates the database user password. func (s *Service) ChangePassword(ctx context.Context, id int64, password string) error { if err := validatePassword(password); err != nil { return err } d, err := s.db.DatabaseByID(ctx, id) if err != nil { return err } if err := s.setPassword(ctx, d.Username, d.Host, password); err != nil { return err } return s.db.UpdateDatabasePassword(ctx, id, password) } func (s *Service) setPassword(ctx context.Context, user, host, password string) error { alter := fmt.Sprintf("ALTER USER %s@%s IDENTIFIED BY %s", quoteString(user), quoteString(host), quoteString(password)) if _, err := s.runSQL(ctx, alter); err == nil { return nil } // MySQL 5.5/5.6 and old MariaDB use SET PASSWORD; MySQL 8+ only supports // ALTER USER, so this fallback is attempted only after the first failure. legacy := fmt.Sprintf("SET PASSWORD FOR %s@%s = PASSWORD(%s)", quoteString(user), quoteString(host), quoteString(password)) if _, err := s.runSQL(ctx, legacy); err != nil { return err } return nil } // Backup dumps one database into data/backups/db and records the file. func (s *Service) Backup(ctx context.Context, id int64) (*store.DatabaseBackup, error) { d, err := s.db.DatabaseByID(ctx, id) if err != nil { return nil, err } dump := mysqldumpBinary() if dump == "" { return nil, errors.New("未检测到 mysqldump") } dir := filepath.Join(s.cfg.DataDir, "backups", "db") if err := os.MkdirAll(dir, 0o700); err != nil { return nil, err } safeName := strings.NewReplacer("/", "_", "\\", "_", "..", "_").Replace(d.Name) name := fmt.Sprintf("%s-%s.sql.gz", safeName, time.Now().Format("20060102-150405")) path := filepath.Join(dir, name) f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) if err != nil { return nil, err } runCtx, cancel := context.WithTimeout(ctx, 30*time.Minute) defer cancel() args := []string{"--protocol=socket", "--socket=" + mysqlSocket(), "-uroot", "--single-transaction", "--quick", "--default-character-set=utf8mb4", d.Name} cmd := exec.CommandContext(runCtx, dump, args...) cmd.Env = s.mysqlEnv() stdout, err := cmd.StdoutPipe() if err != nil { f.Close() _ = os.Remove(path) return nil, err } stderr := &strings.Builder{} cmd.Stderr = stderr if err := cmd.Start(); err != nil { f.Close() _ = os.Remove(path) return nil, err } gz := gzip.NewWriter(f) _, copyErr := io.Copy(gz, stdout) closeErr := gz.Close() fileErr := f.Close() waitErr := cmd.Wait() if copyErr != nil || closeErr != nil || fileErr != nil || waitErr != nil { _ = os.Remove(path) if waitErr != nil { return nil, fmt.Errorf("备份失败: %v %s", waitErr, strings.TrimSpace(stderr.String())) } return nil, fmt.Errorf("备份写入失败: %v", firstError(copyErr, closeErr, fileErr)) } fi, err := os.Stat(path) if err != nil { return nil, err } row := &store.DatabaseBackup{DatabaseID: d.ID, DatabaseName: d.Name, Path: path, Size: fi.Size()} if err := s.db.CreateBackup(ctx, row); err != nil { _ = os.Remove(path) return nil, err } return row, nil } // ListBackups returns the backups of one database. func (s *Service) ListBackups(ctx context.Context, id int64) ([]*store.DatabaseBackup, error) { return s.db.ListBackups(ctx, id) } // AllBackups returns every dump for the recycle-bin view. func (s *Service) AllBackups(ctx context.Context) ([]*store.DatabaseBackup, error) { return s.db.AllBackups(ctx) } // OpenBackup returns a backup file for download. func (s *Service) OpenBackup(ctx context.Context, id int64) (*os.File, *store.DatabaseBackup, error) { b, err := s.db.BackupByID(ctx, id) if err != nil { return nil, nil, err } f, err := os.Open(b.Path) if err != nil { return nil, nil, err } return f, b, nil } // Restore loads a gzip dump back into its database. func (s *Service) Restore(ctx context.Context, id int64) error { b, err := s.db.BackupByID(ctx, id) if err != nil { return err } f, err := os.Open(b.Path) if err != nil { return err } defer f.Close() gz, err := gzip.NewReader(f) if err != nil { return err } defer gz.Close() return s.importSQL(ctx, b.DatabaseName, gz) } // DeleteBackup removes the file and its metadata. func (s *Service) DeleteBackup(ctx context.Context, id int64) error { b, err := s.db.BackupByID(ctx, id) if err != nil { return err } _ = os.Remove(b.Path) return s.db.DeleteBackup(ctx, id) } // ImportSQL pipes an uploaded dump into a database. func (s *Service) ImportSQL(ctx context.Context, id int64, r io.Reader) error { d, err := s.db.DatabaseByID(ctx, id) if err != nil { return err } return s.importSQL(ctx, d.Name, r) } func (s *Service) importSQL(ctx context.Context, database string, r io.Reader) error { mysql := mysqlBinary() if mysql == "" { return errors.New("未检测到 mysql 客户端") } runCtx, cancel := context.WithTimeout(ctx, 30*time.Minute) defer cancel() cmd := exec.CommandContext(runCtx, mysql, "--protocol=socket", "--socket="+mysqlSocket(), "-uroot", "--database="+database) cmd.Env = s.mysqlEnv() cmd.Stdin = r stderr := &strings.Builder{} cmd.Stderr = stderr if err := cmd.Run(); err != nil { return fmt.Errorf("导入失败: %v %s", err, strings.TrimSpace(stderr.String())) } return nil } // SignonCredential is the dedicated MySQL account used by phpMyAdmin SSO. type SignonCredential struct { User string Password string Host string Port int } // EnsureSignonUser creates or updates the panel-managed phpMyAdmin account and // returns its credentials. The password lives only in a root-only panel file; // the phpMyAdmin login is issued through a short-lived panel token. func (s *Service) EnsureSignonUser(ctx context.Context) (SignonCredential, error) { if !s.Available() { return SignonCredential{}, errors.New("未检测到 MySQL/MariaDB 服务") } s.mu.Lock() defer s.mu.Unlock() const user = "mp_pma" const host = "localhost" password := "" path := filepath.Join(s.cfg.DataDir, "phpmyadmin_auto_password.txt") if raw, err := os.ReadFile(path); err == nil { for _, line := range strings.Split(string(raw), "\n") { line = strings.TrimSpace(line) if strings.HasPrefix(line, user+":") { password = strings.TrimSpace(strings.TrimPrefix(line, user+":")) break } } } if len(password) < 8 { password = randomPassword() } create := fmt.Sprintf("CREATE USER %s@%s IDENTIFIED BY %s", quoteString(user), quoteString(host), quoteString(password)) if _, err := s.runSQL(ctx, create); err != nil { // MySQL 5.6 has no CREATE USER IF NOT EXISTS, while MySQL 8 removed // IDENTIFIED BY from GRANT USAGE. Try both compatibility forms. legacy := fmt.Sprintf("GRANT USAGE ON *.* TO %s@%s IDENTIFIED BY %s", quoteString(user), quoteString(host), quoteString(password)) if _, err2 := s.runSQL(ctx, legacy); err2 != nil { upsert := fmt.Sprintf("CREATE USER IF NOT EXISTS %s@%s IDENTIFIED BY %s", quoteString(user), quoteString(host), quoteString(password)) if _, err3 := s.runSQL(ctx, upsert); err3 != nil { return SignonCredential{}, fmt.Errorf("创建 phpMyAdmin 数据库账号失败: %v / %v", err, err2) } } } if err := s.setPassword(ctx, user, host, password); err != nil { return SignonCredential{}, fmt.Errorf("设置 phpMyAdmin 数据库账号密码失败: %w", err) } grant := fmt.Sprintf("GRANT ALL PRIVILEGES ON *.* TO %s@%s WITH GRANT OPTION", quoteString(user), quoteString(host)) if _, err := s.runSQL(ctx, grant); err != nil { return SignonCredential{}, fmt.Errorf("授权 phpMyAdmin 账号失败: %w", err) } _, _ = s.runSQL(ctx, "FLUSH PRIVILEGES") if err := os.WriteFile(path, []byte(user+": "+password+"\n"), 0o600); err != nil { return SignonCredential{}, fmt.Errorf("保存 phpMyAdmin 账号密码失败: %w", err) } return SignonCredential{User: user, Password: password, Host: host, Port: 3306}, nil } // SetRootPassword changes the local root password and stores it for later // client calls. It deliberately does not log the password. func (s *Service) SetRootPassword(ctx context.Context, password string) error { if err := validatePassword(password); err != nil { return err } if err := s.setPassword(ctx, "root", "localhost", password); err != nil { return fmt.Errorf("修改 root 密码失败: %w", err) } note := fmt.Sprintf("root: %s\n", password) return os.WriteFile(filepath.Join(s.cfg.DataDir, "mysql_root_password.txt"), []byte(note), 0o600) } // RootPasswordSet reports whether the panel has a stored root password. func (s *Service) RootPasswordSet() bool { return s.rootPassword() != "" } func (s *Service) runSQL(ctx context.Context, sql string) (string, error) { bin := mysqlBinary() if bin == "" { return "", errors.New("未检测到 mysql 客户端") } args := []string{"--protocol=socket", "--socket=" + mysqlSocket(), "-uroot", "--default-character-set=utf8mb4", "-N", "-B", "-e", sql} res, err := s.runner.RunEnv(ctx, s.mysqlEnv(), bin, args...) if err != nil { msg := strings.TrimSpace(res.Stderr) if msg == "" { msg = err.Error() } return "", errors.New(msg) } return res.Stdout, nil } func (s *Service) mysqlEnv() []string { if pw := s.rootPassword(); pw != "" { return []string{"MYSQL_PWD=" + pw} } return nil } func (s *Service) rootPassword() string { raw, err := os.ReadFile(filepath.Join(s.cfg.DataDir, "mysql_root_password.txt")) if err != nil { return "" } for _, line := range strings.Split(string(raw), "\n") { line = strings.TrimSpace(line) if line == "" { continue } if strings.HasPrefix(line, "root:") { return strings.TrimSpace(strings.TrimPrefix(line, "root:")) } return line } return "" } func mysqlBinary() string { for _, p := range []string{ "/www/server/mysql/current/bin/mysql", "/usr/bin/mysql", "/usr/local/bin/mysql", } { if st, err := os.Stat(p); err == nil && !st.IsDir() { return p } } if p, err := exec.LookPath("mysql"); err == nil { return p } return "" } // mysqlSocket keeps the client talking to the server socket managed by the // panel. Oracle's 5.6 client still defaults to /tmp/mysql.sock, while both the // legacy unit and the APT packages listen on /run/mysqld/mysqld.sock. func mysqlSocket() string { for _, p := range []string{ "/run/mysqld/mysqld.sock", "/var/run/mysqld/mysqld.sock", "/tmp/mysql.sock", } { if st, err := os.Stat(p); err == nil && !st.IsDir() { return p } } return "/run/mysqld/mysqld.sock" } func mysqldumpBinary() string { for _, p := range []string{ "/www/server/mysql/current/bin/mysqldump", "/usr/bin/mysqldump", "/usr/local/bin/mysqldump", } { if st, err := os.Stat(p); err == nil && !st.IsDir() { return p } } if p, err := exec.LookPath("mysqldump"); err == nil { return p } return "" } func quoteIdent(s string) string { return "`" + strings.ReplaceAll(s, "`", "``") + "`" } func quoteString(s string) string { s = strings.ReplaceAll(s, `\`, `\\`) s = strings.ReplaceAll(s, `'`, `''`) return "'" + s + "'" } func validatePassword(p string) error { if len(p) < 8 || len(p) > 128 { return errors.New("密码长度需为 8-128 位") } if strings.ContainsAny(p, "'\\\n\r\x00") { return errors.New("密码不能包含引号、反斜杠或换行") } return nil } func randomPassword() string { b := make([]byte, 18) if _, err := rand.Read(b); err != nil { return "Miao" + strconv.FormatInt(time.Now().UnixNano(), 36) } return base64.RawURLEncoding.EncodeToString(b) } func firstError(errs ...error) error { for _, err := range errs { if err != nil { return err } } return nil }