package sync
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/danmestas/go-libfossil/db"
"github.com/danmestas/go-libfossil/internal/shun"
"github.com/danmestas/go-libfossil/internal/xfer"
"github.com/danmestas/go-libfossil/simio"
)
func envNowUnix(env *simio.Env) int64 {
if env != nil && env.Clock != nil {
return env.Clock.Now().Unix()
}
return time.Now().Unix()
}
// Signed erasures wire exchange (draft-fossil-sync-protocol-00 §9.3.1).
const (
configShunGroup = "/shun"
maxPushedErasures = 1024
)
func quoteSQL(s string) string {
return "'" + strings.ReplaceAll(s, "'", "''") + "'"
}
func formatShunRow(row shun.Row) []byte {
return []byte(fmt.Sprintf("%d %s scom %s", row.MTime, quoteSQL(row.UUID), quoteSQL(row.Comment)))
}
// parseShunRow parses one /shun config payload:
// MTIME SP QUOTED-UUID SP scom SP (QUOTED-SCOM | "NULL").
func parseShunRow(payload []byte) (shun.Row, bool) {
line := strings.TrimSuffix(string(payload), "\n")
mtimeText, rest, ok := strings.Cut(line, " ")
if !ok {
return shun.Row{}, false
}
mtime, err := strconv.ParseInt(mtimeText, 10, 64)
if err != nil || mtime < 0 {
return shun.Row{}, false
}
uuid, rest, ok := unquoteSQL(rest)
if !ok || !strings.HasPrefix(rest, " scom ") {
return shun.Row{}, false
}
after := strings.TrimPrefix(rest, " scom ")
var scom string
if after != "NULL" {
var tail string
scom, tail, ok = unquoteSQL(after)
if !ok || tail != "" {
return shun.Row{}, false
}
}
return shun.Row{UUID: uuid, MTime: mtime, Comment: scom}, true
}
func erasureRowKey(row shun.Row) string {
return row.UUID + "\x00" + strconv.FormatInt(row.MTime, 10) + "\x00" + row.Comment
}
// signedShunConfigCards renders all stored signed erasure rows as config /shun
// cards so reqconfig /shun serves them alongside Fossil's plain shun rows.
func signedShunConfigCards(d *db.DB) ([]xfer.Card, error) {
rows, err := shun.ListSigned(d)
if err != nil || len(rows) == 0 {
return nil, err
}
cards := make([]xfer.Card, 0, len(rows))
for _, r := range rows {
cards = append(cards, &xfer.ConfigCard{Name: configShunGroup, Content: formatShunRow(r)})
}
return cards, nil
}
// stagedCloneErasures collects erasure-key and /shun rows received during one
// clone reply so erasure-key is adopted before signed rows are verified and
// folded (§9.3.1).
type stagedCloneErasures struct {
keyRow *configRow
shunRows []shun.Row
}
func (s *stagedCloneErasures) stageConfig(payload []byte) {
for _, row := range parseConfigRows(payload) {
if row.name != shun.SettingErasureKey {
continue
}
if _, err := shun.ParsePublicKey(row.value); err == nil {
cp := row
s.keyRow = &cp
}
}
}
func (s *stagedCloneErasures) stageShun(payload []byte) {
if row, ok := parseShunRow(payload); ok {
s.shunRows = append(s.shunRows, row)
}
}
func (s *stagedCloneErasures) apply(q db.Querier, projectCode string, nowUnix int64) error {
if s.keyRow != nil {
pub, err := shun.ParsePublicKey(s.keyRow.value)
if err == nil {
if err := shun.SetPinnedKey(q, pub, s.keyRow.mtime); err != nil {
return fmt.Errorf("sync.Clone: adopt erasure-key: %w", err)
}
}
}
if len(s.shunRows) == 0 {
return nil
}
pub, pinned, err := shun.PinnedKey(q)
if err != nil {
return fmt.Errorf("sync.Clone: read erasure-key: %w", err)
}
for _, row := range s.shunRows {
form, _ := shun.Classify(row.Comment)
switch {
case form == shun.FormPlain:
if _, err := q.Exec(
"INSERT OR IGNORE INTO shun(uuid, mtime, scom) VALUES(?, ?, ?)",
row.UUID, row.MTime, row.Comment,
); err != nil {
return fmt.Errorf("sync.Clone: record shun row: %w", err)
}
case pinned:
if v, _ := shun.Judge(pub, projectCode, row); v == shun.VerdictVerified {
if _, err := shun.RecordSigned(q, row); err != nil {
return fmt.Errorf("sync.Clone: record signed erasure: %w", err)
}
}
}
}
if pinned && projectCode != "" {
if _, err := shun.ApplyDue(q, projectCode, nowUnix); err != nil {
return fmt.Errorf("sync.Clone: apply due erasures: %w", err)
}
}
return nil
}
// handleShunConfigPush enforces §9.3.1 for pushed config /shun cards when the
// server pins an erasure-key: Write-authorized pushers may push verified signed
// rows without Admin; any other pushed /shun row fails and rolls back the whole
// request before any content is stored. Without a pinned erasure-key it returns
// handled=false so the caller applies the standard §9.3 Admin rule.
func (h *handler) handleShunConfigPush(c *xfer.ConfigCard) (bool, error) {
pub, pinned, err := shun.PinnedKey(h.repo.DB())
if err != nil {
return true, fmt.Errorf("handler: read erasure-key: %w", err)
}
if !pinned {
return false, nil
}
if !h.pushOK {
h.fail("not authorized to push configuration")
return true, nil
}
row, ok := parseShunRow(c.Content)
if !ok {
h.fail("not authorized to push configuration")
return true, nil
}
if v, _ := shun.Judge(pub, h.projectCode, row); v != shun.VerdictVerified {
h.fail("not authorized to push configuration")
return true, nil
}
if h.pushedErasures >= maxPushedErasures {
return true, nil
}
h.pushedErasures++
if _, err := shun.RecordSigned(h.repo.DB(), row); err != nil {
return true, fmt.Errorf("handler: record signed erasure: %w", err)
}
if _, err := shun.ApplyDue(h.repo.DB(), h.projectCode, h.clock.Now().Unix()); err != nil {
return true, fmt.Errorf("handler: apply due erasures: %w", err)
}
return true, nil
}
// initErasures applies any locally due signed erasures and loads verified rows
// this session may push to a peer that lacks them (§9.3.1).
func (s *session) initErasures() error {
if s.projectCode != "" {
if _, err := shun.ApplyDue(s.repo.DB(), s.projectCode, envNowUnix(s.env)); err != nil {
return fmt.Errorf("sync: apply due erasures: %w", err)
}
}
if !s.opts.Push || s.projectCode == "" {
return nil
}
rows, err := shun.ListVerifiedSigned(s.repo.DB(), s.projectCode)
if err != nil {
return fmt.Errorf("sync: load signed erasures: %w", err)
}
s.pushErasures = rows
return nil
}
// handleReplyShunConfig records rows the peer announced via config /shun so we
// never re-push what it already holds, and outside clone stores only rows that
// verify against our pinned erasure-key (§9.3.1).
func (s *session) handleReplyShunConfig(c *xfer.ConfigCard) error {
if c.Name != configShunGroup {
return nil
}
row, ok := parseShunRow(c.Content)
if !ok {
return nil
}
if s.peerShunRows == nil {
s.peerShunRows = make(map[string]bool)
}
s.peerShunRows[erasureRowKey(row)] = true
if s.projectCode == "" {
return nil
}
pub, pinned, err := shun.PinnedKey(s.repo.DB())
if err != nil || !pinned {
return err
}
if v, _ := shun.Judge(pub, s.projectCode, row); v == shun.VerdictVerified {
if _, err := shun.RecordSigned(s.repo.DB(), row); err != nil {
return fmt.Errorf("sync: record signed erasure: %w", err)
}
}
return nil
}
func (s *session) missingPushErasures() []shun.Row {
var missing []shun.Row
for _, row := range s.pushErasures {
if s.peerShunRows[erasureRowKey(row)] {
continue
}
missing = append(missing, row)
if len(missing) >= maxPushedErasures {
break
}
}
return missing
}
func (s *session) erasuresOwed() bool {
return !s.erasuresSent && s.repliesSeen > 0 && s.pushing() && len(s.missingPushErasures()) > 0
}
func (s *session) pushErasureCards() []xfer.Card {
missing := s.missingPushErasures()
cards := make([]xfer.Card, 0, len(missing))
for _, row := range missing {
cards = append(cards, &xfer.ConfigCard{Name: configShunGroup, Content: formatShunRow(row)})
}
return cards
}