// 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" "regexp" "runtime" "strings" "time" "github.com/go-sql-driver/mysql" ) const ( 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 mysqlErrLockWait = 1205 mysqlErrDeadlock = 1213 ) var ( errLockTimeout = errors.New("database lock busy") 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 { recordsSchema string recordsTable string webuiSchema string webuiPrefix string records string schema string users string sessions string delegations string audit string locks string } type tableLayout struct { recordsSchema string recordsPrefix string webuiSchema string webuiPrefix string } func tableNamesFor(cfg Config) (tableNames, error) { return newTableNames(tableLayout{ recordsSchema: cfg.DBName, recordsPrefix: cfg.DBTablePrefix, webuiSchema: cfg.DBWebUIName, webuiPrefix: cfg.DBWebUIPrefix, }) } func newTableNames(l tableLayout) (tableNames, error) { if !validTablePrefix(l.recordsPrefix) || !validTablePrefix(l.webuiPrefix) { return tableNames{}, errors.New("invalid table prefix") } if !validDBIdentifier(l.recordsSchema) || !validDBIdentifier(l.webuiSchema) { return tableNames{}, errors.New("invalid database name") } webui := func(name string) string { return qualifiedIdent(l.webuiSchema, l.webuiPrefix+"webui_"+name) } return tableNames{ recordsSchema: l.recordsSchema, recordsTable: l.recordsPrefix + "records", webuiSchema: l.webuiSchema, webuiPrefix: l.webuiPrefix, records: qualifiedIdent(l.recordsSchema, l.recordsPrefix+"records"), schema: webui("schema"), users: webui("users"), sessions: webui("sessions"), delegations: webui("zone_delegations"), audit: webui("audit"), locks: webui("locks"), }, nil } func qualifiedIdent(schema, name string) string { return quoteIdent(schema) + "." + quoteIdent(name) } func quoteIdent(name string) string { return "`" + strings.ReplaceAll(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, "{locks}", t.locks, ).Replace(query) } func (t tableNames) migrateLockName() string { return t.webuiPrefix + "webui_migrate" } func (t tableNames) zoneLockName(zone string) string { sum := sha256.Sum256([]byte(zone)) return t.webuiPrefix + "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.DBWebUIName mc.ParseTime = true mc.Loc = time.UTC _ = mc.Apply(mysql.Charset("utf8mb4", "")) 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, "webui_database", cfg.DBWebUIName, "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.recordsTable rows, err := q.QueryContext(ctx, "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, CHARACTER_MAXIMUM_LENGTH FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?", t.recordsSchema, 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(t.recordsSchema, table, columns); err != nil { return err } log.DebugContext(ctx, "records table contract verified", "database", t.recordsSchema, "table", table) return nil } func checkRecordsColumns(schema, table string, columns map[string]columnInfo) error { if len(columns) == 0 { return fmt.Errorf("%w: table %s does not exist in database %s or is not readable", errContract, table, schema) } 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 } // An upsert locks the zone until the transaction ends. Changing the row // also gives Galera a certification key when different writers use the zone. const zoneLockSQL = "INSERT INTO {locks} (`name`, `generation`) VALUES (?, 0) " + "ON DUPLICATE KEY UPDATE `generation` = 1 - `generation`" func lockBusy(err error) bool { return mysqlErrorIs(err, mysqlErrLockWait) || mysqlErrorIs(err, mysqlErrDeadlock) } func lockError(ctx, waitCtx context.Context, err error) error { if lockBusy(err) || (ctx.Err() == nil && errors.Is(waitCtx.Err(), context.DeadlineExceeded)) { return fmt.Errorf("%w: %w", errLockTimeout, err) } return err } func runZoneTx(ctx context.Context, db txBeginner, t tableNames, zone string, log *slog.Logger, fn func(*sql.Tx) error) error { name := t.zoneLockName(zone) err := runInTx(ctx, db, func(tx *sql.Tx) error { waitCtx, cancel := context.WithTimeout(ctx, zoneLockTimeout) defer cancel() if _, err := tx.ExecContext(waitCtx, t.sql(zoneLockSQL), name); err != nil { return fmt.Errorf("acquire zone lock: %w", lockError(ctx, waitCtx, err)) } log.DebugContext(ctx, "zone lock acquired", "lock", name) return fn(tx) }) // A Galera certification failure can first surface at commit. if lockBusy(err) && !errors.Is(err, errLockTimeout) { return fmt.Errorf("%w: %w", errLockTimeout, err) } return err } 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 { return mysqlErrorIs(err, mysqlErrDupEntry) } func mysqlErrorIs(err error, number uint16) bool { var me *mysql.MySQLError return errors.As(err, &me) && me.Number == number } 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<