package migrate import ( "context" "encoding/json" "errors" "fmt" "net/http" "slices" "time" "github.com/rs/zerolog" "maunium.net/go/mautrix" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // maxStrays bounds the strays one room may have redacted. A forward backfill sends one message twice (all // its parts) before it stops; a room showing more is for a person to look at. const maxStrays = 20 // handleStrays finds, and with apply redacts, the strays in a portal's new room: the copies of an old // message bridgev2 sent into it as it made it, when a bridge from before moveChatInfo created the room with // the messenger's info as it came (CanBackfill). bridgev2's forward backfill sent the chat's latest // messages from the oldest, unmarked, and stopped after the first, whose record it already had (the // database refused it a second one). The app counts only marked events (confirm.ts), so a stray changes // no confirmation; it only shows the message twice. A redacted one the app reports among the deleted // events (`redacted`), and the bridge leaves it out of nothing: it is no event the move wrote. // // An event is a stray when all of this holds (isStray): // - it is a message event of the new room (encrypted, not state), not redacted yet, older on the server // than the room's creation (its origin_server_ts, which bridgev2 sets to the message's time); // - this bridge sent it, as a contact's ghost or the room's user, encrypted by the bridge's own device; // - bridgev2 has no record of it (no message part, no reaction): the record it tried to keep was refused; // - it decrypts, with the bridge's own session, to content without a move's marker; // - that content is a message, a reply or a thread's reply: it relates to no event, or as m.thread; // - bridgev2 has a record of a message of the portal from the same sender at the same millisecond, kept // under another event (the old room's, or the moved copy since); // - that event shows the same message (sameMessage: kind, text, file name, file type and size), and // bridgev2 still has no record of the event once that is read. // // One that meets every rule but the last is counted as unconfirmed and left alone: the same sender can // send two messages in one millisecond (a messenger that counts in seconds gives them one), and bridgev2 // sends a message before it keeps its record, so a real message that came in just then has none for a // moment. A copy of a message edited since shows its new text and is left too. // // The room is read from its start, and only up to the first event the move wrote: bridgev2 made the room, // and sent the strays, before the move took the room as moved, so none is after what the move wrote. A // message that came in while the room was made (a real one, sent once) has its own record. An edit that // came in then has none (bridgev2 keeps an edit in the record of the message it edits), and a messenger // that gives times in seconds can give it its message's millisecond: it relates to that message as // m.replace, which a forward backfill never sends (it sends a message as it is now). Nor does it send any // other relation a stray could carry, so an event with one (a reaction, m.annotation, say) is no stray. // // The room's lock is held, as for a move, and a room whose history is being written answers XSG_RUNNING: // an event the job is writing has no record yet. Redactions go as the bot, through bridgekit (which // lets the files the stray carried go, mediarefs.go). // // POST …/rooms/{roomId}/migrate/strays {apply?} -> {newRoomId, strays, redacted, unreadable, unconfirmed} func (m *mover) handleStrays(w http.ResponseWriter, r *http.Request) { oldRoom, ok := pathRoom(w, r) if !ok { return } lock := m.roomLock(oldRoom) lock.Lock() defer lock.Unlock() row, ok := m.ownedRoom(w, r) if !ok { return } var req struct { Apply bool `json:"apply"` } if !readBody(w, r, &req) { return } if row.Kind != kindPortal { writeError(w, http.StatusConflict, "XSG_NOT_PORTAL", "Only a portal's new room is made by bridgev2") return } else if row.State == stateMoving || row.NewRoom == "" || row.Error == errNotEncrypted { writeError(w, http.StatusConflict, "XSG_NOT_MOVED", "The room has no encrypted new room") return } else if m.running(oldRoom) { writeError(w, http.StatusConflict, "XSG_RUNNING", "The room's history is being written") return } ctx := m.requestContext(r) scan, err := m.strays(ctx, row) if err != nil { answerError(ctx, w, err, "Failed to look for strays") return } found := scan.found answer := map[string]any{"newRoomId": row.NewRoom, "strays": len(found), "redacted": 0, "unreadable": scan.unreadable, "unconfirmed": scan.unconfirmed} if !req.Apply || len(found) == 0 { writeJSON(w, http.StatusOK, answer) return } else if len(found) > maxStrays { writeError(w, http.StatusConflict, "XSG_TOO_MANY_STRAYS", "The room has more strays than a forward backfill leaves") return } for i, eventID := range found { redaction := &event.Content{Parsed: &event.RedactionEventContent{Redacts: eventID}} if _, err = m.br.Bot.SendMessage(ctx, row.NewRoom, event.EventRedaction, redaction, nil); err != nil { zerolog.Ctx(ctx).Err(err).Stringer("new_room_id", row.NewRoom).Int("redacted", i).Msg("Failed to redact a stray") writeError(w, http.StatusServiceUnavailable, "XSG_SEND", "Failed to redact a stray") return } answer["redacted"] = i + 1 } zerolog.Ctx(ctx).Info().Stringer("old_room_id", row.OldRoom).Stringer("new_room_id", row.NewRoom).Int("redacted", len(found)).Msg("Redacted the strays bridgev2 sent into a moved portal's new room") writeJSON(w, http.StatusOK, answer) } // strayScan is what strays finds in a new room: the strays, the events this bridge encrypted there that // it cannot read, and those that meet every rule but showing what the record's event shows (unconfirmed). type strayScan struct { found []id.EventID unreadable int unconfirmed int } // strays reads the new room from its start up to the first event the move wrote and sorts what it finds // (handleStrays). func (m *mover) strays(ctx context.Context, row *room) (*strayScan, error) { created, err := m.conn.Bot.FullStateEvent(ctx, row.NewRoom, event.StateCreate, "") if err != nil || created == nil || created.Timestamp <= 0 { zerolog.Ctx(ctx).Err(err).Stringer("new_room_id", row.NewRoom).Msg("Failed to read the new room's creation") return nil, failWith(http.StatusServiceUnavailable, "XSG_READ", "Failed to read the new room") } written, err := m.store.events(ctx, row.OldRoom) if err != nil { return nil, err } moved := make(map[id.EventID]bool, len(written)) for _, e := range written { moved[e.NewEventID] = true } key := networkid.PortalKey{ID: row.PortalID, Receiver: row.PortalReceiver} filter := &mautrix.FilterPart{Types: []event.Type{event.EventEncrypted}} scan := &strayScan{} from := "" for range maxEvents / readBackPage { page, err := m.conn.Bot.Messages(ctx, row.NewRoom, from, "", mautrix.DirectionForward, filter, readBackPage) if err != nil { zerolog.Ctx(ctx).Err(err).Stringer("new_room_id", row.NewRoom).Msg("Failed to read the new room") return nil, failWith(http.StatusServiceUnavailable, "XSG_READ", "Failed to read the new room") } for _, evt := range page.Chunk { if moved[evt.ID] { return scan, nil } verdict, err := m.isStray(ctx, row, key, moved, created.Timestamp, evt) if err != nil { return nil, err } switch verdict { case strayFound: scan.found = append(scan.found, evt.ID) case strayUnreadable: scan.unreadable++ case strayUnconfirmed: scan.unconfirmed++ } } // As in readRoom, an empty page with an end reads on. if page.End == "" || page.End == from { return scan, nil } from = page.End } return nil, failWith(http.StatusConflict, "XSG_TOO_LARGE", fmt.Sprintf("The new room has more than %d events before its moved history", maxEvents)) } // strayVerdict is what isStray makes of an event of the new room. type strayVerdict int const ( notStray strayVerdict = iota strayFound // strayUnreadable: this bridge encrypted it and cannot decrypt it now; it is left alone. strayUnreadable // strayUnconfirmed: it meets every rule but the last, so nothing shows it is a copy; it is left alone. strayUnconfirmed ) // isStray tells whether an event of the new room is a stray (handleStrays). func (m *mover) isStray(ctx context.Context, row *room, key networkid.PortalKey, moved map[id.EventID]bool, created int64, evt *event.Event) (strayVerdict, error) { if evt.Type != event.EventEncrypted || evt.StateKey != nil || evt.Unsigned.RedactedBecause != nil || evt.Timestamp >= created { return notStray, nil } ghost, isGhost := m.br.Matrix.ParseGhostMXID(evt.Sender) if (!isGhost || ghost == "") && evt.Sender != row.User { return notStray, nil } else if !m.writtenHere(evt) { return notStray, nil } if recorded, err := m.recorded(ctx, evt.ID); err != nil || recorded { return notStray, err } content, err := m.readWritten(ctx, evt) if err != nil { var f *failure if errors.As(err, &f) && f.code == errNotEncrypted { // The bridge has no encryption: nothing it wrote can be read. return strayUnreadable, nil } zerolog.Ctx(ctx).Warn().Err(err).Stringer("event_id", evt.ID).Msg("Failed to decrypt an event this bridge wrote while looking for strays") return strayUnreadable, nil } if _, marked := MarkerOf(content); marked { return notStray, nil } else if !backfillShaped(content) { return notStray, nil } at := time.UnixMilli(evt.Timestamp) // bridgev2 keeps a message's time in nanoseconds and gives the server its milliseconds. messages, err := m.br.DB.Message.GetMessagesBetweenTimeQuery(ctx, key, at.Add(-time.Nanosecond), at.Add(time.Millisecond-time.Nanosecond)) if err != nil { return notStray, fmt.Errorf("failed to read the portal's messages at %d: %w", evt.Timestamp, err) } var kept []id.EventID for _, message := range messages { if message.MXID == evt.ID { continue } if message.SenderMXID == evt.Sender || (isGhost && (message.SenderID == ghost || message.SenderMXID == m.br.Matrix.FormatGhostMXID(ghost))) { kept = append(kept, message.MXID) } } if len(kept) == 0 { return notStray, nil } // The same sender can send two messages in one millisecond (a messenger that counts in seconds gives // them one), and one that came in just now has no record for a moment: only the record's event showing // the same message tells a copy. if !slices.ContainsFunc(kept, func(eventID id.EventID) bool { return m.showsTheSame(ctx, row, moved, eventID, content) }) { return strayUnconfirmed, nil } // bridgev2 sends a message before it keeps its record: one with the same content that came in just // as it was read may have its record by now. if recorded, err := m.recorded(ctx, evt.ID); err != nil || recorded { return notStray, err } return strayFound, nil } // recorded says whether bridgev2 keeps a record of an event, as a message's part or a reaction. func (m *mover) recorded(ctx context.Context, eventID id.EventID) (bool, error) { if part, err := m.br.DB.Message.GetPartByMXID(ctx, eventID); err != nil { return false, fmt.Errorf("failed to read the record of %s: %w", eventID, err) } else if part != nil { return true, nil } reaction, err := m.br.DB.Reaction.GetByMXID(ctx, eventID) if err != nil { return false, fmt.Errorf("failed to read the record of %s: %w", eventID, err) } return reaction != nil, nil } // showsTheSame says whether the event a record names shows what content shows (sameMessage). The record // names the moved copy in the new room or the old room's event (a message that came in later, the new // room's). One that cannot be read confirms nothing, nor does a deleted one (its content is gone). func (m *mover) showsTheSame(ctx context.Context, row *room, moved map[id.EventID]bool, eventID id.EventID, content json.RawMessage) bool { rooms := []id.RoomID{row.OldRoom, row.NewRoom} if moved[eventID] { rooms = rooms[1:] } for _, roomID := range rooms { evt, err := m.conn.Bot.GetEvent(ctx, roomID, eventID) if errors.Is(err, mautrix.MNotFound) { continue } else if err != nil { zerolog.Ctx(ctx).Warn().Err(err).Stringer("event_id", eventID).Msg("Failed to read the event a record names while looking for strays") return false } kept := evt.Content.VeryRaw if evt.Type == event.EventEncrypted { if kept, err = m.readWritten(ctx, evt); err != nil { zerolog.Ctx(ctx).Warn().Err(err).Stringer("event_id", eventID).Msg("Failed to decrypt the event a record names while looking for strays") return false } } return sameMessage(kept, content) } return false } // shownMessage is what a message shows: its kind, text, file name and file (type and size). It leaves out // what a copy has otherwise: relations, formatting, where the file is and the move's marker. type shownMessage struct { MsgType string `json:"msgtype"` Body string `json:"body"` FileName string `json:"filename"` Info struct { MimeType string `json:"mimetype"` Size int64 `json:"size"` } `json:"info"` } // sameMessage says whether two contents show the same message. Content that shows no text and no file // name, or that cannot be read, is the same as nothing. func sameMessage(a, b json.RawMessage) bool { var x, y shownMessage if json.Unmarshal(a, &x) != nil || json.Unmarshal(b, &y) != nil { return false } return x == y && (x.Body != "" || x.FileName != "") } // backfillShaped says whether decrypted content is what a forward backfill sends: a message relating to // no event, a reply (m.in_reply_to, no rel_type) or a thread's reply (m.thread). An edit (m.replace), a // reaction (m.annotation) or any other relation is not, nor is content whose relation cannot be read. func backfillShaped(content json.RawMessage) bool { var holder struct { RelatesTo *struct { Type event.RelationType `json:"rel_type"` } `json:"m.relates_to"` } if json.Unmarshal(content, &holder) != nil { return false } return holder.RelatesTo == nil || holder.RelatesTo.Type == "" || holder.RelatesTo.Type == event.RelThread }