// 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 } var original *recordRow for _, row := range current { if row.RecordType != "SOA" { continue } if original != nil { return nil, errors.New("cannot determine serial with multiple SOA records") } original = &row } if original == nil { return nil, nil } serial, _ := storedSOASerial(*original) switch { case serial != 0: serial = nextSOASerial(serial, now) case changes.ManageSerial: serial = newSOASerial(now) default: return nil, nil } row := *original for _, updated := range changes.Updates { if updated.ID == original.ID { row = updated } } if changes.SOAUpdate != nil { row = *changes.SOAUpdate } row, err := withSOASerial(row, serial, true) if err != nil { return nil, err } return &row, nil }