// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import ( "database/sql" "errors" "fmt" "strings" "time" ) func newSOASerial(now time.Time) uint32 { year, month, day := now.UTC().Date() return uint32(year)*1000000 + uint32(month)*10000 + uint32(day)*100 } func nextSOASerial(serial uint32, now time.Time) uint32 { if serial == 0 { return 0 } next := serial + 1 if serial%100 == 99 { date, err := time.Parse("20060102", fmt.Sprintf("%08d", serial/100)) if err == nil { next = newSOASerial(date.AddDate(0, 0, 1)) } } return max(next, newSOASerial(now), 1) } func storedSOASerial(row recordRow) (serial uint32, present bool) { if row.Content.Valid { decoded, err := inspectRecordContent("SOA", row.Content.String) if err == nil && decoded.fields["serial"] == "" { return decoded.data.(soaData).Serial, hasContentKey(decoded.object, "serial") } } return 0, false } func prepareSOAUpdate(current, proposed recordRow) (recordRow, error) { serial, present := storedSOASerial(current) proposed.ID = current.ID return withSOASerial(proposed, serial, present) } func withSOASerial(row recordRow, serial uint32, present bool) (recordRow, error) { if row.RecordType != "SOA" || !row.Content.Valid { return recordRow{}, errors.New("cannot set serial without SOA content") } data, err := decodeRecord("SOA", row.Content.String) if err != nil { return recordRow{}, err } soa := data.(soaData) soa.Serial = serial content, _ := encodeRecord(soa) if !present { content = strings.TrimSuffix(content, ",\"serial\":0}") + "}" } row.Content = sql.NullString{String: content, Valid: true} return row, nil } func updateSOASerial(current []recordRow, changes zoneChanges, now time.Time) (*recordRow, error) { if changes.empty() { return nil, nil } original := make(map[int64]recordRow) for _, row := range current { if row.RecordType == "SOA" { original[row.ID] = row } } var soa []recordRow for _, row := range changes.finalRows(current) { if row.RecordType == "SOA" { soa = append(soa, row) } } if len(soa) != 1 { return nil, nil } before, ok := original[soa[0].ID] if !ok { return nil, nil } serial, _ := storedSOASerial(before) switch { case serial != 0: serial = nextSOASerial(serial, now) case changes.ManageSerial: serial = newSOASerial(now) default: return nil, nil } row, err := withSOASerial(soa[0], serial, true) if err != nil { return nil, err } return &row, nil }