// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import ( "context" "crypto/sha256" "database/sql" "database/sql/driver" "encoding/hex" "errors" "fmt" "log/slog" "math" "regexp" "runtime" "strings" "time" "github.com/go-sql-driver/mysql" ) const ( dbCollation = "utf8mb4_0900_ai_ci" dbConnectTimeout = 5 * time.Second dbReadTimeout = 30 * time.Second dbWriteTimeout = 30 * time.Second dbMaxOpenConns = 10 dbMaxIdleConns = 10 dbConnMaxLifetime = time.Minute dbPingMaxWait = 30 * time.Second dbPingAttemptTimeout = 5 * time.Second dbPingFirstDelay = 250 * time.Millisecond dbPingMaxDelay = 4 * time.Second zoneLockTimeout = 10 * time.Second migrateLockTimeout = 30 * time.Second mysqlErrDupEntry = 1062 ) var ( errLockTimeout = errors.New("named lock timeout") errRowNotFound = errors.New("row not found") errUsernameTaken = errors.New("username already used") errContract = errors.New("records table contract violated") errDatabase = errors.New("database unavailable") ) type dbtx interface { ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row } type txBeginner interface { BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) } type pinger interface { PingContext(ctx context.Context) error } type tableNames struct { prefix string records string schema string users string sessions string delegations string audit string } func newTableNames(prefix string) (tableNames, error) { if !validTablePrefix(prefix) { return tableNames{}, errors.New("invalid table prefix") } return tableNames{ prefix: prefix, records: quoteIdent(prefix + "records"), schema: quoteIdent(prefix + "webui_schema"), users: quoteIdent(prefix + "webui_users"), sessions: quoteIdent(prefix + "webui_sessions"), delegations: quoteIdent(prefix + "webui_zone_delegations"), audit: quoteIdent(prefix + "webui_audit"), }, nil } func quoteIdent(name string) string { return "`" + name + "`" } func (t tableNames) sql(query string) string { return strings.NewReplacer( "{records}", t.records, "{schema}", t.schema, "{users}", t.users, "{sessions}", t.sessions, "{delegations}", t.delegations, "{audit}", t.audit, ).Replace(query) } func (t tableNames) migrateLockName() string { return t.prefix + "webui_migrate" } func (t tableNames) zoneLockName(zone string) string { sum := sha256.Sum256([]byte(zone)) return t.prefix + "webui:" + hex.EncodeToString(sum[:])[:16] } func mysqlConfig(cfg Config) *mysql.Config { mc := mysql.NewConfig() mc.User = cfg.DBUser mc.Passwd = cfg.DBPassword mc.Net = "tcp" mc.Addr = cfg.DBAddress() mc.DBName = cfg.DBName mc.ParseTime = true mc.Loc = time.UTC mc.Collation = dbCollation mc.Timeout = dbConnectTimeout mc.ReadTimeout = dbReadTimeout mc.WriteTimeout = dbWriteTimeout mc.MultiStatements = false mc.InterpolateParams = false mc.TLSConfig = cfg.DBTLS return mc } func openDatabase(cfg Config, log *slog.Logger) (*sql.DB, error) { connector, err := mysql.NewConnector(mysqlConfig(cfg)) if err != nil { return nil, fmt.Errorf("%w: invalid connection settings", errDatabase) } var c driver.Connector = connector if log.Enabled(context.Background(), LevelTrace) { c = traceConnector{Connector: connector, log: log} } db := sql.OpenDB(c) db.SetMaxOpenConns(dbMaxOpenConns) db.SetMaxIdleConns(dbMaxIdleConns) db.SetConnMaxLifetime(dbConnMaxLifetime) log.Debug("database pool opened", "host", cfg.DBHost, "port", cfg.DBPort, "user", cfg.DBUser, "database", cfg.DBName, "tls", cfg.DBTLS) return db, nil } type backoff struct { maxWait time.Duration attemptTimeout time.Duration firstDelay time.Duration maxDelay time.Duration now func() time.Time sleep func(ctx context.Context, d time.Duration) error } func defaultPingBackoff() backoff { return backoff{ maxWait: dbPingMaxWait, attemptTimeout: dbPingAttemptTimeout, firstDelay: dbPingFirstDelay, maxDelay: dbPingMaxDelay, now: time.Now, sleep: sleepContext, } } func sleepContext(ctx context.Context, d time.Duration) error { t := time.NewTimer(d) defer t.Stop() select { case <-ctx.Done(): return ctx.Err() case <-t.C: return nil } } func pingDatabase(ctx context.Context, p pinger, b backoff, log *slog.Logger) error { deadline := b.now().Add(b.maxWait) delay := b.firstDelay for attempt := 1; ; attempt++ { attemptCtx, cancel := context.WithTimeout(ctx, b.attemptTimeout) err := p.PingContext(attemptCtx) cancel() if err == nil { log.DebugContext(ctx, "database reachable", "attempts", attempt) return nil } if ctx.Err() != nil { return ctx.Err() } remaining := deadline.Sub(b.now()) if remaining <= 0 { log.ErrorContext(ctx, "database unreachable", "attempts", attempt, "error", err) return fmt.Errorf("%w: ping failed after %d attempts: %v", errDatabase, attempt, err) } log.DebugContext(ctx, "database ping failed, retrying", "attempt", attempt, "delay", delay, "error", err) if err := b.sleep(ctx, min(delay, remaining)); err != nil { return err } delay = min(delay*2, b.maxDelay) } } type columnInfo struct { dataType string columnType string maxLength int64 } type contractColumn struct { name string requirement string accepts func(columnInfo) bool } func typeIn(types ...string) func(columnInfo) bool { return func(c columnInfo) bool { for _, t := range types { if c.dataType == t { return true } } return false } } func varcharOrText(minLength int64) func(columnInfo) bool { text := typeIn("text", "mediumtext", "longtext") return func(c columnInfo) bool { return (c.dataType == "varchar" && c.maxLength >= minLength) || text(c) } } var recordsContract = []contractColumn{ {"id", "INT or INT UNSIGNED", typeIn("int")}, {"zone", "VARCHAR(255) or longer, TEXT, MEDIUMTEXT or LONGTEXT", varcharOrText(255)}, {"name", "VARCHAR(255) or longer, TEXT, MEDIUMTEXT or LONGTEXT", varcharOrText(255)}, {"ttl", "INT or BIGINT", typeIn("int", "bigint")}, {"content", "TEXT, MEDIUMTEXT, LONGTEXT or JSON", typeIn("text", "mediumtext", "longtext", "json")}, {"record_type", "VARCHAR(9) or longer, TEXT, MEDIUMTEXT or LONGTEXT", varcharOrText(9)}, } func verifyRecordsContract(ctx context.Context, q dbtx, t tableNames, log *slog.Logger) error { table := t.prefix + "records" rows, err := q.QueryContext(ctx, "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, CHARACTER_MAXIMUM_LENGTH FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?", table) if err != nil { return fmt.Errorf("read records table columns: %w", err) } defer rows.Close() columns := map[string]columnInfo{} for rows.Next() { var name, dataType, columnType string var maxLength sql.NullInt64 if err := rows.Scan(&name, &dataType, &columnType, &maxLength); err != nil { return fmt.Errorf("read records table columns: %w", err) } columns[strings.ToLower(name)] = columnInfo{dataType: strings.ToLower(dataType), columnType: strings.ToLower(columnType), maxLength: maxLength.Int64} } if err := rows.Err(); err != nil { return fmt.Errorf("read records table columns: %w", err) } if err := checkRecordsColumns(table, columns); err != nil { return err } log.DebugContext(ctx, "records table contract verified", "table", table) return nil } func checkRecordsColumns(table string, columns map[string]columnInfo) error { if len(columns) == 0 { return fmt.Errorf("%w: table %s does not exist in the configured database", errContract, table) } for _, c := range recordsContract { info, ok := columns[c.name] if !ok { return fmt.Errorf("%w: table %s has no column %s", errContract, table, c.name) } if !c.accepts(info) { shown := info.columnType if shown == "" { shown = info.dataType } return fmt.Errorf("%w: column %s of table %s has incompatible type %s, it must be %s", errContract, c.name, table, shown, c.requirement) } } return nil } type namedLock struct { conn *sql.Conn name string } func acquireNamedLock(ctx context.Context, conn *sql.Conn, name string, timeout time.Duration) (*namedLock, error) { seconds := int64(math.Ceil(timeout.Seconds())) var result sql.NullInt64 if err := conn.QueryRowContext(ctx, "SELECT GET_LOCK(?, ?)", name, seconds).Scan(&result); err != nil { return nil, fmt.Errorf("acquire lock: %w", err) } if !result.Valid { return nil, errors.New("acquire lock: GET_LOCK returned NULL") } if result.Int64 != 1 { return nil, errLockTimeout } return &namedLock{conn: conn, name: name}, nil } func (l *namedLock) release(ctx context.Context) error { var result sql.NullInt64 if err := l.conn.QueryRowContext(ctx, "SELECT RELEASE_LOCK(?)", l.name).Scan(&result); err != nil { return fmt.Errorf("release lock: %w", err) } if !result.Valid || result.Int64 != 1 { return errors.New("release lock: lock was not held") } return nil } type connSource interface { Conn(ctx context.Context) (*sql.Conn, error) } func discardConn(conn *sql.Conn) { _ = conn.Raw(func(any) error { return driver.ErrBadConn }) } func withNamedLock(ctx context.Context, db connSource, name string, timeout time.Duration, log *slog.Logger, fn func(conn *sql.Conn) error) error { conn, err := db.Conn(ctx) if err != nil { return fmt.Errorf("dedicated connection: %w", err) } discard := false defer func() { if discard { discardConn(conn) return } if cerr := conn.Close(); cerr != nil { log.ErrorContext(ctx, "dedicated connection close failed", "lock", name, "error", cerr) } }() lock, err := acquireNamedLock(ctx, conn, name, timeout) if err != nil { if errors.Is(err, errLockTimeout) { log.WarnContext(ctx, "named lock timeout", "lock", name, "timeout", timeout) } return err } log.DebugContext(ctx, "named lock acquired", "lock", name) defer func() { releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dbPingAttemptTimeout) defer cancel() if rerr := lock.release(releaseCtx); rerr != nil { log.ErrorContext(ctx, "named lock release failed, discarding the connection", "lock", name, "error", rerr) discard = true return } log.DebugContext(ctx, "named lock released", "lock", name) }() return fn(conn) } func withZoneLock(ctx context.Context, db connSource, t tableNames, zone string, log *slog.Logger, fn func(conn *sql.Conn) error) error { return withNamedLock(ctx, db, t.zoneLockName(zone), zoneLockTimeout, log, fn) } func runInTx(ctx context.Context, b txBeginner, fn func(tx *sql.Tx) error) (err error) { tx, err := b.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("begin transaction: %w", err) } committed := false defer func() { if !committed { _ = tx.Rollback() } }() if err := fn(tx); err != nil { return err } if err := tx.Commit(); err != nil { return fmt.Errorf("commit transaction: %w", err) } committed = true return nil } func isDuplicateKey(err error) bool { var me *mysql.MySQLError return errors.As(err, &me) && me.Number == mysqlErrDupEntry } func dbTime(t time.Time) time.Time { return t.UTC().Truncate(time.Microsecond) } func scanUTC(t *time.Time) { *t = t.UTC() } func scanNullUTC(t *sql.NullTime) { if t.Valid { t.Time = t.Time.UTC() } } type traceConnector struct { driver.Connector log *slog.Logger } func (c traceConnector) Connect(ctx context.Context) (driver.Conn, error) { conn, err := c.Connector.Connect(ctx) if err != nil { return nil, err } return &traceConn{Conn: conn, log: c.log}, nil } type traceConn struct { driver.Conn log *slog.Logger } var errNoBeginTx = errors.New("driver connection does not support BeginTx") func (c *traceConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { b, ok := c.Conn.(driver.ConnBeginTx) if !ok { return nil, errNoBeginTx } return b.BeginTx(ctx, opts) } func (c *traceConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { if p, ok := c.Conn.(driver.ConnPrepareContext); ok { return p.PrepareContext(ctx, query) } return c.Conn.Prepare(query) } func (c *traceConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { traceSQL(ctx, c.log, query, args) if e, ok := c.Conn.(driver.ExecerContext); ok { return e.ExecContext(ctx, query, args) } return nil, driver.ErrSkip } func (c *traceConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { traceSQL(ctx, c.log, query, args) if q, ok := c.Conn.(driver.QueryerContext); ok { return q.QueryContext(ctx, query, args) } return nil, driver.ErrSkip } func (c *traceConn) Ping(ctx context.Context) error { if p, ok := c.Conn.(driver.Pinger); ok { return p.Ping(ctx) } return nil } func (c *traceConn) ResetSession(ctx context.Context) error { if r, ok := c.Conn.(driver.SessionResetter); ok { return r.ResetSession(ctx) } return nil } func (c *traceConn) IsValid() bool { if v, ok := c.Conn.(driver.Validator); ok { return v.IsValid() } return true } func (c *traceConn) CheckNamedValue(nv *driver.NamedValue) error { if n, ok := c.Conn.(driver.NamedValueChecker); ok { return n.CheckNamedValue(nv) } return driver.ErrSkip } var traceIdentifier = regexp.MustCompile(`^[A-Za-z0-9_.*:@-]{0,255}$`) type privateSQLArgsKey struct{} func privateSQLArgs(ctx context.Context, ordinals ...int) context.Context { var mask uint64 for _, ordinal := range ordinals { mask |= 1 << ordinal } return context.WithValue(ctx, privateSQLArgsKey{}, mask) } func traceValue(v driver.Value) any { switch x := v.(type) { case nil, int64, uint64, float64, bool, time.Time: return x case string: if traceIdentifier.MatchString(x) { return x } } return redactedLogValue } func ownFunction(full string) (string, bool) { pkg, name, ok := strings.Cut(full[strings.LastIndex(full, "/")+1:], ".") return name, ok && (pkg == "main" || pkg == "coredns-web-ui") } func sqlCaller() string { pcs := make([]uintptr, 48) frames := runtime.CallersFrames(pcs[:runtime.Callers(3, pcs)]) var callers []string for len(callers) < 2 { f, more := frames.Next() name, ok := ownFunction(f.Function) if ok && !strings.HasPrefix(name, "(*traceConn)") && !strings.HasPrefix(name, "traceSQL") { callers = append(callers, name) } if !more { break } } return strings.Join(callers, " < ") } func traceSQL(ctx context.Context, log *slog.Logger, query string, args []driver.NamedValue) { if !log.Enabled(ctx, LevelTrace) { return } values := make([]any, len(args)) private, _ := ctx.Value(privateSQLArgsKey{}).(uint64) for i, a := range args { if private&(1<