miaopanel
1// Package dbmanager manages MySQL/MariaDB databases through the local mysql
2// and mysqldump clients. It never builds a shell command: identifiers are
3// validated and values are escaped before they reach the SQL string.
4package dbmanager
5
6import (
7 "compress/gzip"
8 "context"
9 "crypto/rand"
10 "encoding/base64"
11 "errors"
12 "fmt"
13 "io"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "regexp"
18 "strconv"
19 "strings"
20 "sync"
21 "time"
22
23 "github.com/miaopanel/miaopanel/internal/config"
24 "github.com/miaopanel/miaopanel/internal/store"
25 "github.com/miaopanel/miaopanel/internal/system"
26)
27
28var (
29 nameRe = regexp.MustCompile(`^[A-Za-z0-9_]{1,32}$`)
30 charsetRe = regexp.MustCompile(`^[A-Za-z0-9_]{2,20}$`)
31)
32
33var systemDatabases = map[string]bool{
34 "information_schema": true,
35 "mysql": true,
36 "performance_schema": true,
37 "sys": true,
38}
39
40// Service exposes database operations to the API layer.
41type Service struct {
42 cfg *config.Config
43 db *store.Store
44 runner *system.Runner
45 mu sync.Mutex
46}
47
48// New builds the database manager.
49func New(cfg *config.Config, db *store.Store) *Service {
50 return &Service{cfg: cfg, db: db, runner: system.NewRunner()}
51}
52
53// Available reports whether a mysql client is present.
54func (s *Service) Available() bool { return mysqlBinary() != "" }
55
56// Info describes the local server for the advanced settings panel.
57type Info struct {
58 Version string `json:"version"`
59 DataDir string `json:"data_dir"`
60 Port int `json:"port"`
61 Socket string `json:"socket"`
62 RootPasswordSet bool `json:"root_password_set"`
63 Client string `json:"client"`
64}
65
66// Info reads server variables.
67func (s *Service) Info(ctx context.Context) (Info, error) {
68 out, err := s.runSQL(ctx, `SELECT @@version, @@datadir, @@port, @@socket`)
69 if err != nil {
70 return Info{}, err
71 }
72 parts := strings.Split(strings.TrimSpace(out), "\t")
73 info := Info{Client: mysqlBinary(), RootPasswordSet: s.rootPassword() != ""}
74 if len(parts) > 0 {
75 info.Version = parts[0]
76 }
77 if len(parts) > 1 {
78 info.DataDir = parts[1]
79 }
80 if len(parts) > 2 {
81 info.Port, _ = strconv.Atoi(parts[2])
82 }
83 if len(parts) > 3 {
84 info.Socket = parts[3]
85 }
86 return info, nil
87}
88
89// List synchronizes unmanaged databases and returns the tracked rows.
90func (s *Service) List(ctx context.Context, q string) ([]*store.ManagedDatabase, error) {
91 if !s.Available() {
92 return nil, errors.New("未检测到 mysql 客户端,请先在应用商店安装 MySQL 或 MariaDB")
93 }
94 if err := s.Sync(ctx); err != nil {
95 return nil, err
96 }
97 return s.db.ListDatabases(ctx, q)
98}
99
100// Sync imports databases that exist on the server but not in the panel.
101func (s *Service) Sync(ctx context.Context) error {
102 out, err := s.runSQL(ctx, `SHOW DATABASES`)
103 if err != nil {
104 return err
105 }
106 s.mu.Lock()
107 defer s.mu.Unlock()
108 for _, line := range strings.Split(out, "\n") {
109 name := strings.TrimSpace(line)
110 if name == "" || systemDatabases[name] {
111 continue
112 }
113 if err := s.db.UpsertSyncedDatabase(ctx, name); err != nil {
114 return err
115 }
116 }
117 return nil
118}
119
120// CreateInput is the create-database payload.
121type CreateInput struct {
122 Name string `json:"name"`
123 Username string `json:"username"`
124 Password string `json:"password"`
125 Charset string `json:"charset"`
126 Remark string `json:"remark"`
127 Remote bool `json:"remote"`
128}
129
130// Create provisions a database and a dedicated user.
131func (s *Service) Create(ctx context.Context, in CreateInput) (*store.ManagedDatabase, error) {
132 in.Name = strings.TrimSpace(in.Name)
133 in.Username = strings.TrimSpace(in.Username)
134 if in.Username == "" {
135 in.Username = in.Name
136 }
137 if !nameRe.MatchString(in.Name) || !nameRe.MatchString(in.Username) {
138 return nil, errors.New("数据库名和用户名只能包含字母、数字、下划线,长度 1-32")
139 }
140 if in.Charset == "" {
141 in.Charset = "utf8mb4"
142 }
143 if !charsetRe.MatchString(in.Charset) {
144 return nil, errors.New("字符集不合法")
145 }
146 if in.Password == "" {
147 in.Password = randomPassword()
148 }
149 if err := validatePassword(in.Password); err != nil {
150 return nil, err
151 }
152 if _, err := s.db.DatabaseByName(ctx, in.Name); err == nil {
153 return nil, errors.New("该数据库已被面板管理")
154 } else if !errors.Is(err, store.ErrNotFound) {
155 return nil, err
156 }
157 host := "localhost"
158 if in.Remote {
159 host = "%"
160 }
161 if _, err := s.runSQL(ctx, fmt.Sprintf("CREATE DATABASE %s DEFAULT CHARACTER SET %s",
162 quoteIdent(in.Name), in.Charset)); err != nil {
163 return nil, fmt.Errorf("创建数据库失败: %w", err)
164 }
165 userSQL := fmt.Sprintf("CREATE USER %s@%s IDENTIFIED BY %s",
166 quoteString(in.Username), quoteString(host), quoteString(in.Password))
167 if _, err := s.runSQL(ctx, userSQL); err != nil {
168 _, _ = s.runSQL(ctx, "DROP DATABASE IF EXISTS "+quoteIdent(in.Name))
169 return nil, fmt.Errorf("创建数据库用户失败: %w", err)
170 }
171 grantSQL := fmt.Sprintf("GRANT ALL PRIVILEGES ON %s.* TO %s@%s",
172 quoteIdent(in.Name), quoteString(in.Username), quoteString(host))
173 if _, err := s.runSQL(ctx, grantSQL); err != nil {
174 _, _ = s.runSQL(ctx, "DROP USER IF EXISTS "+quoteString(in.Username)+"@"+quoteString(host))
175 _, _ = s.runSQL(ctx, "DROP DATABASE IF EXISTS "+quoteIdent(in.Name))
176 return nil, fmt.Errorf("授权失败: %w", err)
177 }
178 _, _ = s.runSQL(ctx, "FLUSH PRIVILEGES")
179 row := &store.ManagedDatabase{
180 Name: in.Name, Username: in.Username, Password: in.Password,
181 Host: host, Charset: in.Charset, Remark: in.Remark, Managed: true,
182 }
183 if err := s.db.CreateDatabase(ctx, row); err != nil {
184 _, _ = s.runSQL(ctx, "DROP USER IF EXISTS "+quoteString(in.Username)+"@"+quoteString(host))
185 _, _ = s.runSQL(ctx, "DROP DATABASE IF EXISTS "+quoteIdent(in.Name))
186 return nil, err
187 }
188 return row, nil
189}
190
191// Delete drops a database, its user (when not shared) and its backups.
192func (s *Service) Delete(ctx context.Context, id int64) error {
193 d, err := s.db.DatabaseByID(ctx, id)
194 if err != nil {
195 return err
196 }
197 if _, err := s.runSQL(ctx, "DROP DATABASE IF EXISTS "+quoteIdent(d.Name)); err != nil {
198 return fmt.Errorf("删除数据库失败: %w", err)
199 }
200 if d.Managed {
201 others, err := s.db.DatabasesByUsername(ctx, d.Username, d.ID)
202 if err != nil {
203 return err
204 }
205 if len(others) == 0 {
206 _, _ = s.runSQL(ctx, fmt.Sprintf("DROP USER IF EXISTS %s@%s",
207 quoteString(d.Username), quoteString(d.Host)))
208 }
209 }
210 backups, _ := s.db.ListBackups(ctx, d.ID)
211 for _, b := range backups {
212 _ = os.Remove(b.Path)
213 _ = s.db.DeleteBackup(ctx, b.ID)
214 }
215 return s.db.DeleteDatabase(ctx, id)
216}
217
218// ChangePassword rotates the database user password.
219func (s *Service) ChangePassword(ctx context.Context, id int64, password string) error {
220 if err := validatePassword(password); err != nil {
221 return err
222 }
223 d, err := s.db.DatabaseByID(ctx, id)
224 if err != nil {
225 return err
226 }
227 if err := s.setPassword(ctx, d.Username, d.Host, password); err != nil {
228 return err
229 }
230 return s.db.UpdateDatabasePassword(ctx, id, password)
231}
232
233func (s *Service) setPassword(ctx context.Context, user, host, password string) error {
234 alter := fmt.Sprintf("ALTER USER %s@%s IDENTIFIED BY %s",
235 quoteString(user), quoteString(host), quoteString(password))
236 if _, err := s.runSQL(ctx, alter); err == nil {
237 return nil
238 }
239 // MySQL 5.5/5.6 and old MariaDB use SET PASSWORD; MySQL 8+ only supports
240 // ALTER USER, so this fallback is attempted only after the first failure.
241 legacy := fmt.Sprintf("SET PASSWORD FOR %s@%s = PASSWORD(%s)",
242 quoteString(user), quoteString(host), quoteString(password))
243 if _, err := s.runSQL(ctx, legacy); err != nil {
244 return err
245 }
246 return nil
247}
248
249// Backup dumps one database into data/backups/db and records the file.
250func (s *Service) Backup(ctx context.Context, id int64) (*store.DatabaseBackup, error) {
251 d, err := s.db.DatabaseByID(ctx, id)
252 if err != nil {
253 return nil, err
254 }
255 dump := mysqldumpBinary()
256 if dump == "" {
257 return nil, errors.New("未检测到 mysqldump")
258 }
259 dir := filepath.Join(s.cfg.DataDir, "backups", "db")
260 if err := os.MkdirAll(dir, 0o700); err != nil {
261 return nil, err
262 }
263 safeName := strings.NewReplacer("/", "_", "\\", "_", "..", "_").Replace(d.Name)
264 name := fmt.Sprintf("%s-%s.sql.gz", safeName, time.Now().Format("20060102-150405"))
265 path := filepath.Join(dir, name)
266 f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
267 if err != nil {
268 return nil, err
269 }
270 runCtx, cancel := context.WithTimeout(ctx, 30*time.Minute)
271 defer cancel()
272 args := []string{"--protocol=socket", "--socket=" + mysqlSocket(), "-uroot",
273 "--single-transaction", "--quick", "--default-character-set=utf8mb4", d.Name}
274 cmd := exec.CommandContext(runCtx, dump, args...)
275 cmd.Env = s.mysqlEnv()
276 stdout, err := cmd.StdoutPipe()
277 if err != nil {
278 f.Close()
279 _ = os.Remove(path)
280 return nil, err
281 }
282 stderr := &strings.Builder{}
283 cmd.Stderr = stderr
284 if err := cmd.Start(); err != nil {
285 f.Close()
286 _ = os.Remove(path)
287 return nil, err
288 }
289 gz := gzip.NewWriter(f)
290 _, copyErr := io.Copy(gz, stdout)
291 closeErr := gz.Close()
292 fileErr := f.Close()
293 waitErr := cmd.Wait()
294 if copyErr != nil || closeErr != nil || fileErr != nil || waitErr != nil {
295 _ = os.Remove(path)
296 if waitErr != nil {
297 return nil, fmt.Errorf("备份失败: %v %s", waitErr, strings.TrimSpace(stderr.String()))
298 }
299 return nil, fmt.Errorf("备份写入失败: %v", firstError(copyErr, closeErr, fileErr))
300 }
301 fi, err := os.Stat(path)
302 if err != nil {
303 return nil, err
304 }
305 row := &store.DatabaseBackup{DatabaseID: d.ID, DatabaseName: d.Name, Path: path, Size: fi.Size()}
306 if err := s.db.CreateBackup(ctx, row); err != nil {
307 _ = os.Remove(path)
308 return nil, err
309 }
310 return row, nil
311}
312
313// ListBackups returns the backups of one database.
314func (s *Service) ListBackups(ctx context.Context, id int64) ([]*store.DatabaseBackup, error) {
315 return s.db.ListBackups(ctx, id)
316}
317
318// AllBackups returns every dump for the recycle-bin view.
319func (s *Service) AllBackups(ctx context.Context) ([]*store.DatabaseBackup, error) {
320 return s.db.AllBackups(ctx)
321}
322
323// OpenBackup returns a backup file for download.
324func (s *Service) OpenBackup(ctx context.Context, id int64) (*os.File, *store.DatabaseBackup, error) {
325 b, err := s.db.BackupByID(ctx, id)
326 if err != nil {
327 return nil, nil, err
328 }
329 f, err := os.Open(b.Path)
330 if err != nil {
331 return nil, nil, err
332 }
333 return f, b, nil
334}
335
336// Restore loads a gzip dump back into its database.
337func (s *Service) Restore(ctx context.Context, id int64) error {
338 b, err := s.db.BackupByID(ctx, id)
339 if err != nil {
340 return err
341 }
342 f, err := os.Open(b.Path)
343 if err != nil {
344 return err
345 }
346 defer f.Close()
347 gz, err := gzip.NewReader(f)
348 if err != nil {
349 return err
350 }
351 defer gz.Close()
352 return s.importSQL(ctx, b.DatabaseName, gz)
353}
354
355// DeleteBackup removes the file and its metadata.
356func (s *Service) DeleteBackup(ctx context.Context, id int64) error {
357 b, err := s.db.BackupByID(ctx, id)
358 if err != nil {
359 return err
360 }
361 _ = os.Remove(b.Path)
362 return s.db.DeleteBackup(ctx, id)
363}
364
365// ImportSQL pipes an uploaded dump into a database.
366func (s *Service) ImportSQL(ctx context.Context, id int64, r io.Reader) error {
367 d, err := s.db.DatabaseByID(ctx, id)
368 if err != nil {
369 return err
370 }
371 return s.importSQL(ctx, d.Name, r)
372}
373
374func (s *Service) importSQL(ctx context.Context, database string, r io.Reader) error {
375 mysql := mysqlBinary()
376 if mysql == "" {
377 return errors.New("未检测到 mysql 客户端")
378 }
379 runCtx, cancel := context.WithTimeout(ctx, 30*time.Minute)
380 defer cancel()
381 cmd := exec.CommandContext(runCtx, mysql, "--protocol=socket", "--socket="+mysqlSocket(),
382 "-uroot", "--database="+database)
383 cmd.Env = s.mysqlEnv()
384 cmd.Stdin = r
385 stderr := &strings.Builder{}
386 cmd.Stderr = stderr
387 if err := cmd.Run(); err != nil {
388 return fmt.Errorf("导入失败: %v %s", err, strings.TrimSpace(stderr.String()))
389 }
390 return nil
391}
392
393// SignonCredential is the dedicated MySQL account used by phpMyAdmin SSO.
394type SignonCredential struct {
395 User string
396 Password string
397 Host string
398 Port int
399}
400
401// EnsureSignonUser creates or updates the panel-managed phpMyAdmin account and
402// returns its credentials. The password lives only in a root-only panel file;
403// the phpMyAdmin login is issued through a short-lived panel token.
404func (s *Service) EnsureSignonUser(ctx context.Context) (SignonCredential, error) {
405 if !s.Available() {
406 return SignonCredential{}, errors.New("未检测到 MySQL/MariaDB 服务")
407 }
408 s.mu.Lock()
409 defer s.mu.Unlock()
410 const user = "mp_pma"
411 const host = "localhost"
412 password := ""
413 path := filepath.Join(s.cfg.DataDir, "phpmyadmin_auto_password.txt")
414 if raw, err := os.ReadFile(path); err == nil {
415 for _, line := range strings.Split(string(raw), "\n") {
416 line = strings.TrimSpace(line)
417 if strings.HasPrefix(line, user+":") {
418 password = strings.TrimSpace(strings.TrimPrefix(line, user+":"))
419 break
420 }
421 }
422 }
423 if len(password) < 8 {
424 password = randomPassword()
425 }
426 create := fmt.Sprintf("CREATE USER %s@%s IDENTIFIED BY %s",
427 quoteString(user), quoteString(host), quoteString(password))
428 if _, err := s.runSQL(ctx, create); err != nil {
429 // MySQL 5.6 has no CREATE USER IF NOT EXISTS, while MySQL 8 removed
430 // IDENTIFIED BY from GRANT USAGE. Try both compatibility forms.
431 legacy := fmt.Sprintf("GRANT USAGE ON *.* TO %s@%s IDENTIFIED BY %s",
432 quoteString(user), quoteString(host), quoteString(password))
433 if _, err2 := s.runSQL(ctx, legacy); err2 != nil {
434 upsert := fmt.Sprintf("CREATE USER IF NOT EXISTS %s@%s IDENTIFIED BY %s",
435 quoteString(user), quoteString(host), quoteString(password))
436 if _, err3 := s.runSQL(ctx, upsert); err3 != nil {
437 return SignonCredential{}, fmt.Errorf("创建 phpMyAdmin 数据库账号失败: %v / %v", err, err2)
438 }
439 }
440 }
441 if err := s.setPassword(ctx, user, host, password); err != nil {
442 return SignonCredential{}, fmt.Errorf("设置 phpMyAdmin 数据库账号密码失败: %w", err)
443 }
444 grant := fmt.Sprintf("GRANT ALL PRIVILEGES ON *.* TO %s@%s WITH GRANT OPTION",
445 quoteString(user), quoteString(host))
446 if _, err := s.runSQL(ctx, grant); err != nil {
447 return SignonCredential{}, fmt.Errorf("授权 phpMyAdmin 账号失败: %w", err)
448 }
449 _, _ = s.runSQL(ctx, "FLUSH PRIVILEGES")
450 if err := os.WriteFile(path, []byte(user+": "+password+"\n"), 0o600); err != nil {
451 return SignonCredential{}, fmt.Errorf("保存 phpMyAdmin 账号密码失败: %w", err)
452 }
453 return SignonCredential{User: user, Password: password, Host: host, Port: 3306}, nil
454}
455
456// SetRootPassword changes the local root password and stores it for later
457// client calls. It deliberately does not log the password.
458func (s *Service) SetRootPassword(ctx context.Context, password string) error {
459 if err := validatePassword(password); err != nil {
460 return err
461 }
462 if err := s.setPassword(ctx, "root", "localhost", password); err != nil {
463 return fmt.Errorf("修改 root 密码失败: %w", err)
464 }
465 note := fmt.Sprintf("root: %s\n", password)
466 return os.WriteFile(filepath.Join(s.cfg.DataDir, "mysql_root_password.txt"), []byte(note), 0o600)
467}
468
469// RootPasswordSet reports whether the panel has a stored root password.
470func (s *Service) RootPasswordSet() bool { return s.rootPassword() != "" }
471
472func (s *Service) runSQL(ctx context.Context, sql string) (string, error) {
473 bin := mysqlBinary()
474 if bin == "" {
475 return "", errors.New("未检测到 mysql 客户端")
476 }
477 args := []string{"--protocol=socket", "--socket=" + mysqlSocket(), "-uroot",
478 "--default-character-set=utf8mb4", "-N", "-B", "-e", sql}
479 res, err := s.runner.RunEnv(ctx, s.mysqlEnv(), bin, args...)
480 if err != nil {
481 msg := strings.TrimSpace(res.Stderr)
482 if msg == "" {
483 msg = err.Error()
484 }
485 return "", errors.New(msg)
486 }
487 return res.Stdout, nil
488}
489
490func (s *Service) mysqlEnv() []string {
491 if pw := s.rootPassword(); pw != "" {
492 return []string{"MYSQL_PWD=" + pw}
493 }
494 return nil
495}
496
497func (s *Service) rootPassword() string {
498 raw, err := os.ReadFile(filepath.Join(s.cfg.DataDir, "mysql_root_password.txt"))
499 if err != nil {
500 return ""
501 }
502 for _, line := range strings.Split(string(raw), "\n") {
503 line = strings.TrimSpace(line)
504 if line == "" {
505 continue
506 }
507 if strings.HasPrefix(line, "root:") {
508 return strings.TrimSpace(strings.TrimPrefix(line, "root:"))
509 }
510 return line
511 }
512 return ""
513}
514
515func mysqlBinary() string {
516 for _, p := range []string{
517 "/www/server/mysql/current/bin/mysql",
518 "/usr/bin/mysql",
519 "/usr/local/bin/mysql",
520 } {
521 if st, err := os.Stat(p); err == nil && !st.IsDir() {
522 return p
523 }
524 }
525 if p, err := exec.LookPath("mysql"); err == nil {
526 return p
527 }
528 return ""
529}
530
531// mysqlSocket keeps the client talking to the server socket managed by the
532// panel. Oracle's 5.6 client still defaults to /tmp/mysql.sock, while both the
533// legacy unit and the APT packages listen on /run/mysqld/mysqld.sock.
534func mysqlSocket() string {
535 for _, p := range []string{
536 "/run/mysqld/mysqld.sock",
537 "/var/run/mysqld/mysqld.sock",
538 "/tmp/mysql.sock",
539 } {
540 if st, err := os.Stat(p); err == nil && !st.IsDir() {
541 return p
542 }
543 }
544 return "/run/mysqld/mysqld.sock"
545}
546
547func mysqldumpBinary() string {
548 for _, p := range []string{
549 "/www/server/mysql/current/bin/mysqldump",
550 "/usr/bin/mysqldump",
551 "/usr/local/bin/mysqldump",
552 } {
553 if st, err := os.Stat(p); err == nil && !st.IsDir() {
554 return p
555 }
556 }
557 if p, err := exec.LookPath("mysqldump"); err == nil {
558 return p
559 }
560 return ""
561}
562
563func quoteIdent(s string) string {
564 return "`" + strings.ReplaceAll(s, "`", "``") + "`"
565}
566
567func quoteString(s string) string {
568 s = strings.ReplaceAll(s, `\`, `\\`)
569 s = strings.ReplaceAll(s, `'`, `''`)
570 return "'" + s + "'"
571}
572
573func validatePassword(p string) error {
574 if len(p) < 8 || len(p) > 128 {
575 return errors.New("密码长度需为 8-128 位")
576 }
577 if strings.ContainsAny(p, "'\\\n\r\x00") {
578 return errors.New("密码不能包含引号、反斜杠或换行")
579 }
580 return nil
581}
582
583func randomPassword() string {
584 b := make([]byte, 18)
585 if _, err := rand.Read(b); err != nil {
586 return "Miao" + strconv.FormatInt(time.Now().UnixNano(), 36)
587 }
588 return base64.RawURLEncoding.EncodeToString(b)
589}
590
591func firstError(errs ...error) error {
592 for _, err := range errs {
593 if err != nil {
594 return err
595 }
596 }
597 return nil
598}