package migrate import ( "context" "crypto/rand" "encoding/json" "errors" "fmt" "net/http" "slices" "strconv" "time" "github.com/rs/zerolog" "maunium.net/go/mautrix" "maunium.net/go/mautrix/appservice" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" "xessenger/bridgekit/internal/storeseal" ) // Codes a failed migration reports; the API keeps them as the reason. const ( errNotEncrypted = "not_encrypted" errSender = "sender" errRead = "read" errSend = "send" errMedia = "media" errSeal = "seal" errSelfCheck = "self_check" errTooLarge = "too_large" errStore = "store" ) // maxEvents bounds the old room a migration reads at once (the bridges fetch a limited history). const maxEvents = 200_000 // failure is a migration that stopped, with the code it reports. type failure struct { code string err error } func (f *failure) Error() string { return f.code + ": " + f.err.Error() } func (f *failure) Unwrap() error { return f.err } func fail(code string, err error) error { return &failure{code: code, err: err} } func failureCode(err error) string { var f *failure if errors.As(err, &f) { return f.code } return errStore } // job is a migration running in this process: how far it got, what it does now (phase) since when // it started, and where its time went so far (timings), for the API's log and the bridge's own. type job struct { state string done int total int err string phase string started time.Time timings timings } // What a running job does: reads the old room and works out what to write, gets the new room ready // and finds where an earlier run stopped, writes the events, or finishes (tally, ghosts, files). const ( phaseReading = "reading" phasePreparing = "preparing" phaseWriting = "writing" phaseFinishing = "finishing" ) // timings is where a history run's time went, in milliseconds: reading the old room (read), getting the // new room ready and finding where an earlier run stopped (prepare), copying files (media), sending the // events (send, joining their writers too), keeping each written event in the bridge's store and at the // API (store), reading the first one back (check), finishing (finish), and all of it (total). Lock is // how long the call that started the run waited for the room's lock. type timings struct { Lock int64 `json:"lockMs"` Read int64 `json:"readMs"` Prepare int64 `json:"prepareMs"` Media int64 `json:"mediaMs"` Send int64 `json:"sendMs"` Store int64 `json:"storeMs"` Check int64 `json:"checkMs"` Finish int64 `json:"finishMs"` Total int64 `json:"totalMs"` } // since adds the milliseconds from start to now to *into. func since(into *int64, start time.Time) { *into += time.Since(start).Milliseconds() } // slowRun is how long a history run takes before the bridge logs where its time went: the bridges log // warnings only in operation. const slowRun = 30 * time.Second // slowStep is how long one step of a move or a history call takes before the bridge logs it. const slowStep = 10 * time.Second // tookLong logs a step of a move or a history call that took slowStep or longer. func tookLong(ctx context.Context, step string, start time.Time) { if took := time.Since(start); took >= slowStep { zerolog.Ctx(ctx).Warn().Str("step", step).Int64("ms", took.Milliseconds()).Msg("A history move step took long") } } type result struct { NewRoomID id.RoomID `json:"newRoomId"` Events int `json:"events"` Files int `json:"files"` Digest string `json:"digest"` LastEventID id.EventID `json:"lastEventId"` SourceMessages int `json:"sourceMessages"` SourceReactions int `json:"sourceReactions"` SourceFiles int `json:"sourceFiles"` MissingFiles int `json:"missingFiles"` Undigestable int `json:"undigestable"` // MailCompose says the move copied the bodies of mails sent from the app (room.MailCompose). MailCompose bool `json:"mailCompose"` } func resultOf(r *room) *result { return &result{ NewRoomID: r.NewRoom, Events: r.Events, Files: r.Files, Digest: r.Digest, LastEventID: r.LastEventID, SourceMessages: r.SourceMessages, SourceReactions: r.SourceReactions, SourceFiles: r.SourceFiles, MissingFiles: r.MissingFiles, Undigestable: r.Undigestable, MailCompose: r.MailCompose, } } // handleMigrate starts or continues writing the old room's history into the new room, in the // background, and says how far it got. A failed migration is reported until it is called with // retry, which continues where it stopped. Called with start false it starts nothing: it says how far // the room's job got, or that none runs (answerIdle; this process lost it, restarting), so the API // tells the bridge who reads the room again before the job starts anew, and only then. // // The job lock is held only to look at or change the jobs, never across a read of the store or a call // to the homeserver: every running job takes it after each event it writes (progress), and every call // of every room asks it, so a slow homeserver answering one start would hold all of them up. func (m *mover) handleMigrate(w http.ResponseWriter, r *http.Request) { userID, ok := m.pathUser(w, r) if !ok { return } oldRoom, ok := pathRoom(w, r) if !ok { return } var req struct { Retry bool `json:"retry"` Start *bool `json:"start"` } if !readBody(w, r, &req) { return } ctx := m.requestContext(r) // The room's lock first, as a move takes it: a move called again (the API gives a portal's members // before each start) saves the row before it is read here or once the job started here is over, // never while it runs. No job of the room starts but under it. waiting := time.Now() lock := m.roomLock(oldRoom) lock.Lock() defer lock.Unlock() tookLong(ctx, "migrate_room_lock", waiting) lockMs := time.Since(waiting).Milliseconds() row, ok := m.migrateRow(ctx, w, userID, oldRoom) if !ok { return } if answer, running := m.jobAnswer(oldRoom); running { answerMigrate(w, answer) return } // No job of the room runs now, and none starts while its lock is held. One that ended after the row // was read above kept how far it got before it ended (its failure, or its finish), so the row is read // again: a job started from the earlier read would hold an older attempt, skip looking for the event // the ended job was writing, and write that event a second time. if row, ok = m.migrateRow(ctx, w, userID, oldRoom); !ok { return } // A portal's user is in its new room before anything is said of its history, and one written before // they were is set to be written again (user.go). if err := m.keepUser(ctx, row); err != nil { answerError(ctx, w, err, "Failed to bring the user into the new room") return } switch { case row.State == stateDone: answerMigrate(w, m.withTimings(oldRoom, map[string]any{"state": stateDone, "done": row.Events, "total": row.Events, "result": resultOf(row)})) return case row.State == stateFailed && (!req.Retry || row.Error == errSelfCheck): // A written event that decrypted to other content than was sent is for a person to look at: // a retry would take it up as written (findWritten), and the move would go on from it. answerMigrate(w, m.withTimings(oldRoom, map[string]any{"state": stateFailed, "done": row.Events, "total": row.Total, "error": row.Error})) return case req.Start != nil && !*req.Start: answerMigrate(w, map[string]any{"state": answerIdle, "done": row.Events, "total": row.Total}) return } checking := time.Now() if err := m.membersJoined(ctx, row); err != nil { answerError(ctx, w, err, "Failed to check the new room's members") return } tookLong(ctx, "migrate_members", checking) // What the run writes goes out under keys made for those just found in the room: a session made // before one of them came in would not be theirs (user.go). m.resetSession(ctx, row.NewRoom) j := &job{state: stateRunning, total: row.Total, phase: phaseReading, started: time.Now(), timings: timings{Lock: lockMs}} m.jobLock.Lock() m.jobs[oldRoom] = j m.jobLock.Unlock() go m.run(m.backgroundContext(), row, j) answerMigrate(w, map[string]any{"state": stateRunning, "done": 0, "total": row.Total, "phase": phaseReading, "elapsedMs": 0}) } // answerMigrate answers a migrate call, saying the bridge takes start false (canAsk): an API that asks a // running history without starting it does so only of a bridge that said so, as an older one would take // the ask for a start. func answerMigrate(w http.ResponseWriter, answer map[string]any) { answer["canAsk"] = true writeJSON(w, http.StatusOK, answer) } // migrateRow reads the room's move for a migrate call, or answers the call when there is none to go on // with: none at all, another user's, one not finished, or one whose new room is not encrypted. func (m *mover) migrateRow(ctx context.Context, w http.ResponseWriter, userID id.UserID, oldRoom id.RoomID) (*room, bool) { row, err := m.store.room(ctx, oldRoom) switch { case err != nil: answerError(ctx, w, err, "Failed to read the room's move") case row == nil: writeError(w, http.StatusNotFound, "M_NOT_FOUND", "The room was not moved") case !row.owns(userID): writeError(w, http.StatusForbidden, "M_FORBIDDEN", "The room was moved for another user") case row.State == stateMoving: writeError(w, http.StatusConflict, "XSG_NOT_MOVED", "The room's move did not finish") case row.Error == errNotEncrypted: writeError(w, http.StatusConflict, "XSG_NOT_ENCRYPTED", "The new room is not encrypted") default: return row, true } return nil, false } // jobAnswer is the answer for the room's job while it runs: how far it got, what it does now and for // how long it has run. func (m *mover) jobAnswer(oldRoom id.RoomID) (map[string]any, bool) { m.jobLock.Lock() defer m.jobLock.Unlock() j := m.jobs[oldRoom] if j == nil || j.state != stateRunning { return nil, false } return map[string]any{"state": stateRunning, "done": j.done, "total": j.total, "phase": j.phase, "elapsedMs": time.Since(j.started).Milliseconds()}, true } // withTimings adds where the last run of the room in this process spent its time, once it ended. func (m *mover) withTimings(oldRoom id.RoomID, answer map[string]any) map[string]any { m.jobLock.Lock() defer m.jobLock.Unlock() if j := m.jobs[oldRoom]; j != nil && j.state != stateRunning { answer["timings"] = j.timings } return answer } // membersJoined checks that the identities the moved history is for are in the new room: the keys // of what is written go only to the devices in the room when it is written. A portal's are its user // and its members (a Xessenger room's members include its users). In a portal's new room nobody else // of this homeserver may be, joined or invited, as the state store has them: those mautrix shares the // room's keys with. One who let go of the connection is put out by the bridge's member sync (bridgekit // members.go), and the history waits for that, the API trying again. func (m *mover) membersJoined(ctx context.Context, row *room) error { readers := row.Members if row.Kind == kindPortal { present, err := m.conn.StateStore.GetRoomJoinedOrInvitedMembers(ctx, row.NewRoom) if err != nil { return err } for _, userID := range present { if userID != row.User && !slices.Contains(row.Members, userID) && m.kit.HomeserverPerson(userID) { return failWith(http.StatusConflict, "XSG_OTHERS_IN_ROOM", "Somebody who does not share the connection is in the new room") } } readers = append([]id.UserID{row.User}, row.Members...) } if len(readers) == 0 { return nil } joined, err := m.conn.Bot.JoinedMembers(ctx, row.NewRoom) if err != nil { return err } for _, member := range readers { if _, ok := joined.Joined[member]; !ok { return failWith(http.StatusConflict, "XSG_MEMBERS_NOT_JOINED", "Not every member has joined the new room") } } return nil } func (m *mover) run(ctx context.Context, row *room, j *job) { log := zerolog.Ctx(ctx).With().Stringer("old_room_id", row.OldRoom).Stringer("new_room_id", row.NewRoom).Logger() ctx = log.WithContext(ctx) t := j.timings err := m.migrate(ctx, row, j, &t) t.Total = time.Since(j.started).Milliseconds() code := "" if err != nil { code = failureCode(err) log.Err(err).Str("code", code).Interface("timings", t).Msg("Failed to move a room's history") // Saved before the job is marked ended: a call that finds it ended reads the row again // (handleMigrate) and goes on from what is saved here. row.State, row.Error = stateFailed, code if storeErr := m.store.putRoom(ctx, row); storeErr != nil { log.Err(storeErr).Msg("Failed to save a failed history move") } } else { took := log.Info() if time.Duration(t.Total)*time.Millisecond >= slowRun { took = log.Warn() } took.Int("events", row.Events).Int("files", row.Files).Interface("timings", t).Msg("Moved a room's history") } m.jobLock.Lock() defer m.jobLock.Unlock() j.timings = t if err == nil { j.state = stateDone return } j.state, j.err = stateFailed, code } // progress tells how far the job got and where its time went, for the calls asking. func (m *mover) progress(j *job, done int, t *timings) { m.jobLock.Lock() j.done = done j.timings = *t m.jobLock.Unlock() } // enter tells what the job does now. func (m *mover) enter(j *job, phase string, t *timings) { m.jobLock.Lock() j.phase = phase j.timings = *t m.jobLock.Unlock() } func (m *mover) migrate(ctx context.Context, row *room, j *job, t *timings) error { // Each step's time goes to its timing once it ended, and the step under way when the run ends // (failed, or the last) gets its time too: one that waited long and then failed shows where the // time went. var step time.Time var current *int64 begin := func(into *int64) { current, step = into, time.Now() } end := func() { since(current, step) current = nil } defer func() { if current != nil { since(current, step) } }() begin(&t.Read) sealer, err := m.sealer() if err != nil { return fail(errSeal, err) } reader, err := m.reader(ctx, row) if err != nil { return err } events, names, err := readRoom(ctx, reader.Client, row.OldRoom) if err != nil { return err } counter := NewCounter(m.br.Matrix.ServerName(), m.conn.Config.AppService.ID == "telegram") for _, evt := range events { counter.Add(evt) } counts := counter.Result() p := buildPlan(events) row.State, row.Error, row.Total = stateRunning, "", len(p.Items) row.SourceMessages, row.SourceReactions, row.SourceFiles = counts.Messages, counts.Reactions, counts.Files row.Undigestable = p.Undigestable if err = m.store.putRoom(ctx, row); err != nil { return fail(errStore, err) } end() m.jobLock.Lock() j.total = row.Total m.jobLock.Unlock() m.enter(j, phasePreparing, t) begin(&t.Prepare) // The state store learns the room's members and encryption: what is written is encrypted for // them, and nothing is written into a room the store does not know to be encrypted. if _, err = m.conn.Bot.State(ctx, row.NewRoom); err != nil { return fail(errRead, fmt.Errorf("failed to read the new room's state: %w", err)) } if encrypted, err := m.conn.StateStore.IsEncrypted(ctx, row.NewRoom); err != nil { // Not an answer about the room: a retry asks again. return fail(errStore, fmt.Errorf("failed to ask the state store about the new room's encryption: %w", err)) } else if !encrypted { return fail(errNotEncrypted, errors.New("the state store does not know the new room as encrypted")) } written, err := m.store.events(ctx, row.OldRoom) if err != nil { return fail(errStore, err) } // A history written again (setAside): the messages whose earlier copies were deleted since go again // as soon as they are written. stale, err := m.store.staleEvents(ctx, row.OldRoom) if err != nil { return fail(errStore, err) } takenBack := map[string]bool{} for _, s := range stale { if s.Deleted { takenBack[string(s.OldEventID)] = true } } key, err := m.digestKey(ctx, row, sealer, len(written) > 0) if err != nil { return err } moved := make(map[string]string, len(written)) for i, e := range written { if e.Seq != i+1 || i >= len(p.Items) || p.Items[i].Old.ID != string(e.OldEventID) { // The old room no longer reads as it did when the move began. return fail(errStore, fmt.Errorf("written event %d does not match the old room", e.Seq)) } moved[string(e.OldEventID)] = string(e.NewEventID) } last := len(written) if row.Kind == kindPortal && last > 0 { // The bridge may have stopped after keeping the last written event and before pointing // bridgev2's record of it at the new event: point it again (a record already pointed stays). if err = m.repoint(ctx, p.Items[last-1], written[last-1].NewEventID); err != nil { return err } } if row.AttemptSeq == last+1 && last < len(p.Items) { found, err := m.findWritten(ctx, row, sealer, p.Items[last]) if err != nil { return err } else if found != "" { moved[p.Items[last].Old.ID] = string(found) last++ } } end() m.progress(j, last, t) m.enter(j, phaseWriting, t) w := &writer{m: m, row: row, names: names, intents: map[id.UserID]bridgev2.MatrixAPI{}, forOthers: map[id.UserID]bool{}, ghosts: map[id.UserID]bool{}} w.restoreGhosts(p.Items[:last]) checked := false for _, it := range p.Items[last:] { if err = ctx.Err(); err != nil { return fail(errSend, err) } content, ok, err := prepare(it, moved, EncodeDigestKey(key)) if err != nil { return fail(errStore, err) } else if !ok { return fail(errStore, fmt.Errorf("the message of reaction %d was not moved", it.Seq)) } begin(&t.Media) if err = m.copyMedia(ctx, row, sealer, content); err != nil { return err } end() begin(&t.Store) row.AttemptSeq = it.Seq if err = m.store.putRoom(ctx, row); err != nil { return fail(errStore, err) } end() begin(&t.Send) newEvent, err := w.send(ctx, it, content) if err != nil { return err } end() data, err := json.Marshal(content) if err != nil { return fail(errStore, err) } if !checked { // Once a run: the event the server has is encrypted, and decrypts to what was hashed. begin(&t.Check) if err = m.selfCheck(ctx, row.NewRoom, newEvent, data); err != nil { return err } end() checked = true } begin(&t.Store) if err = m.record(ctx, row, sealer, it, newEvent, data); err != nil { return err } moved[it.Old.ID] = string(newEvent) if row.Kind == kindPortal { if err = m.repoint(ctx, it, newEvent); err != nil { return err } } if takenBack[it.Old.ID] { if err = m.redactAgain(ctx, row, &movedEvent{Seq: it.Seq, NewEventID: newEvent}); err != nil { return err } } end() m.progress(j, it.Seq, t) } m.enter(j, phaseFinishing, t) begin(&t.Finish) return m.finish(ctx, row, sealer, key, w) } // digestKey is the room's digest key: kept sealed from the run that first wrote its history, or made // now for a room nothing was written into yet, and kept before anything is. Events written without a // kept key (by a bridge from before the key) stop the move: the app could not match their markers // with those written now, and the room's old history would wait for a confirmation that never comes. // So does an event such a bridge set out to write (AttemptSeq) without keeping it: it may be in the new // room, and findWritten, which reads only the markers written now, would not find it and write it again. func (m *mover) digestKey(ctx context.Context, row *room, sealer *storeseal.Sealer, written bool) ([]byte, error) { ad := m.sealContext("xessenger/migrate/key/v1", row.OldRoom, "") if row.SealedKey != "" { key, err := sealer.Open(ad, row.SealedKey) if err != nil { return nil, fail(errSeal, err) } else if len(key) != DigestKeySize { return nil, fail(errSeal, errors.New("the room's digest key has the wrong size")) } return key, nil } else if written || row.AttemptSeq > 0 { return nil, fail(errStore, errors.New("events were written without the room's digest key")) } key := make([]byte, DigestKeySize) if _, err := rand.Read(key); err != nil { return nil, fail(errSeal, err) } sealed, err := sealer.Seal(ad, key) if err != nil { return nil, fail(errSeal, err) } row.SealedKey = sealed if err = m.store.putRoom(ctx, row); err != nil { return nil, fail(errStore, err) } return key, nil } // record keeps a written event: its new ID, its content hash (sealed) and its files. Its files are kept // to write down at the API (fileNoter) first, a mail's attachments with them, as a run that goes on later // does not find a recorded event again. One whose files cannot be kept, or whose mail.json cannot be // read yet, stops the move (errStore), and the next run finds the event again (findWritten). func (m *mover) record(ctx context.Context, row *room, sealer *storeseal.Sealer, it item, newEvent id.EventID, content json.RawMessage) error { if noter, ok := m.kit.(fileNoter); ok { if err := noter.NoteWrittenFiles(ctx, row.NewRoom, newEvent, content, time.UnixMilli(it.Old.Timestamp)); err != nil { return fail(errStore, err) } } hash, err := ContentHash(content) if err != nil { return fail(errStore, err) } sealedHash, err := sealer.Seal(m.sealContext("xessenger/migrate/hash/v1", row.OldRoom, strconv.Itoa(it.Seq)), []byte(hash)) if err != nil { return fail(errSeal, err) } err = m.store.putEvent(ctx, row.OldRoom, &movedEvent{ Seq: it.Seq, OldEventID: id.EventID(it.Old.ID), NewEventID: newEvent, OldTS: it.Old.Timestamp, SealedHash: sealedHash, FileURLs: EncryptedFileURLs(content), MailCompose: !keepsOldBody(content), }) if err != nil { return fail(errStore, err) } return nil } // finish works out what the app checks the move against and lets the ghosts that only came to // write their old messages go. func (m *mover) finish(ctx context.Context, row *room, sealer *storeseal.Sealer, key []byte, w *writer) error { written, err := m.store.events(ctx, row.OldRoom) if err != nil { return fail(errStore, err) } if err = m.redactStale(ctx, row, written); err != nil { return err } mailCompose := true for _, e := range written { mailCompose = mailCompose && e.MailCompose } t, err := m.tallyOf(row, written, sealer, key, func(*movedEvent) bool { return true }) if err != nil { return err } missing, err := m.store.missingMedia(ctx, row.OldRoom) if err != nil { return fail(errStore, err) } if err = m.leaveFormerGhosts(ctx, row, w); err != nil { return err } // The copies it held go back to what its messages show (fileHolder), before the move is saved as // done: one that could not let go of them does so when it finishes again. if holder, ok := m.kit.(fileHolder); ok { if err = holder.ReleaseMovedFiles(ctx, row.NewRoom, row.OldRoom); err != nil { return fail(errStore, err) } } row.State, row.Error, row.AttemptSeq = stateDone, "", 0 row.Events, row.Files, row.Digest, row.MissingFiles = t.Events, t.Files, t.Digest, missing row.MailCompose = mailCompose row.LastEventID = "" if len(written) > 0 { row.LastEventID = written[len(written)-1].NewEventID } if err = m.store.putRoom(ctx, row); err != nil { return fail(errStore, err) } return nil } // tally is what the app checks a move against: how many moved events it decrypts, how many encrypted // files they carry (EncryptedFileURLs, each URL once) and their digest. type tally struct { Events int Files int Digest string } // tallyOf works the tally out from the written events `counted` takes: every one when the move // finishes, those not deleted in the new room since when the API asks again (handleRedacted). func (m *mover) tallyOf(row *room, written []*movedEvent, sealer *storeseal.Sealer, key []byte, counted func(*movedEvent) bool) (tally, error) { var entries []digestEntry files := map[string]bool{} for _, e := range written { if !counted(e) { continue } hash, err := sealer.Open(m.sealContext("xessenger/migrate/hash/v1", row.OldRoom, strconv.Itoa(e.Seq)), e.SealedHash) if err != nil { return tally{}, fail(errSeal, err) } entries = append(entries, digestEntry{Seq: e.Seq, From: string(e.OldEventID), Hash: string(hash)}) for _, url := range e.FileURLs { files[url] = true } } digest, err := digestOf(key, entries) if err != nil { return tally{}, fail(errStore, err) } return tally{Events: len(entries), Files: len(files), Digest: digest}, nil } // leaveFormerGhosts lets go the ghosts that joined the new room only to write their old messages: // kept, the contacts no longer in the conversation would show among its members. One that cannot // leave stops the move before it is saved as done (errSend), and the retry lets go the ones still // joined. func (m *mover) leaveFormerGhosts(ctx context.Context, row *room, w *writer) error { if row.Kind != kindPortal || len(w.ghosts) == 0 { return nil } present, err := m.openPresentGhosts(row) if err != nil { return fail(errSeal, fmt.Errorf("failed to open the ghosts present at the move: %w", err)) } members, err := m.br.Matrix.GetMembers(ctx, row.NewRoom) if err != nil { return fail(errRead, fmt.Errorf("failed to read the new room's members: %w", err)) } for ghost := range w.ghosts { if present[ghost] { continue } else if member := members[ghost]; member == nil || member.Membership != event.MembershipJoin { // Gone already: an earlier run let it go, or the network did. continue } intent, err := w.ghostIntent(ctx, ghost) if err != nil { return fail(errSend, err) } leave := &event.Content{Parsed: &event.MemberEventContent{Membership: event.MembershipLeave}} if _, err = intent.SendState(ctx, row.NewRoom, event.StateMember, ghost.String(), leave, time.Time{}); err != nil { return fail(errSend, fmt.Errorf("failed to let a former member's ghost leave the new room: %w", err)) } } return nil } // restoreGhosts takes up the ghosts that wrote what earlier runs wrote. A run cut short left the ones // it joined in the new room; this run lets the former members among them go when it is done, as it // does the ghosts it joins itself. They are not joined again here: one that writes again joins as // any writer does (intent). func (w *writer) restoreGhosts(written []item) { if w.row.Kind != kindPortal { return } for _, it := range written { sender := id.UserID(it.Old.Sender) if _, ok := w.m.br.Matrix.ParseGhostMXID(sender); ok { w.ghosts[sender] = true } } } // ghostIntent acts as a ghost that wrote: as this run did, or as bridgev2 makes it for one an earlier // run joined. func (w *writer) ghostIntent(ctx context.Context, ghost id.UserID) (bridgev2.MatrixAPI, error) { if intent, ok := w.intents[ghost]; ok { return intent, nil } ghostID, ok := w.m.br.Matrix.ParseGhostMXID(ghost) if !ok { return nil, errors.New("a writer taken up as a ghost is no ghost") } found, err := w.m.br.GetGhostByID(ctx, ghostID) if err != nil { return nil, fmt.Errorf("failed to read a former member's ghost: %w", err) } return found.Intent, nil } // reader is who reads the old room: the bot in a portal, the user in two Xessenger users' room. func (m *mover) reader(ctx context.Context, row *room) (*appservice.IntentAPI, error) { if row.Kind == kindPortal { return m.conn.Bot, nil } return m.doublePuppet(ctx, row.User) } // doublePuppet acts as a Xessenger user through the double puppet appservice the bridges share. func (m *mover) doublePuppet(ctx context.Context, userID id.UserID) (*appservice.IntentAPI, error) { if m.conn.DoublePuppet == nil { return nil, fail(errSender, errors.New("the bridge has no double puppeting")) } intent, _, err := m.conn.DoublePuppet.Setup(ctx, userID, "") if err != nil || intent == nil { return nil, fail(errSender, fmt.Errorf("cannot act as %s: %v", userID, err)) } return intent, nil } // readRoom reads a room's message events from its start, in timeline order, and the display names // their senders had: each page comes with the senders' membership as it was at its first event // (lazy-loaded members), and a later name takes the place of an earlier one. A sender who joined and // left within one page has none. func readRoom(ctx context.Context, client *mautrix.Client, roomID id.RoomID) ([]Event, map[id.UserID]string, error) { filter := `{"types":["m.room.message","m.sticker","m.poll.start","org.matrix.msc3381.poll.start","m.reaction"],"lazy_load_members":true}` var events []Event names := map[id.UserID]string{} from := "" for { query := map[string]string{"dir": "f", "limit": "1000", "filter": filter} if from != "" { query["from"] = from } var page struct { Chunk []Event `json:"chunk"` State []Event `json:"state"` End string `json:"end"` } url := client.BuildURLWithQuery(mautrix.ClientURLPath{"v3", "rooms", roomID, "messages"}, query) if _, err := client.MakeRequest(ctx, http.MethodGet, url, nil, &page); err != nil { return nil, nil, fail(errRead, fmt.Errorf("failed to read the old room: %w", err)) } events = append(events, page.Chunk...) if len(events) > maxEvents { return nil, nil, fail(errTooLarge, fmt.Errorf("the old room has more than %d events", maxEvents)) } for _, member := range page.State { var content struct { Displayname string `json:"displayname"` } if member.Type == event.StateMember.Type && member.StateKey != nil && json.Unmarshal(member.Content, &content) == nil && content.Displayname != "" { names[id.UserID(*member.StateKey)] = content.Displayname } } // An empty page reads on while it has an end: Synapse filters the events it read and may // leave none. Only no end, or one that does not move, is the room's end. if page.End == "" || page.End == from { return events, names, nil } from = page.End } } // writer sends the moved events as their senders. type writer struct { m *mover row *room // names are the display names the old room's senders had (readRoom), for the markers of the events // the bot writes for them. names map[id.UserID]string intents map[id.UserID]bridgev2.MatrixAPI // forOthers are the senders whose events the bot writes for them (writeForSender). forOthers map[id.UserID]bool // ghosts are the contacts' ghosts that joined the new room to write. ghosts map[id.UserID]bool } func (w *writer) send(ctx context.Context, it item, content map[string]any) (id.EventID, error) { sender := id.UserID(it.Old.Sender) intent, err := w.intent(ctx, sender) if err != nil { return "", err } if w.forOthers[sender] { // The marker names who wrote it: the app shows the event as theirs, the bot having written it. if marker, ok := content[MarkerKey].(map[string]any); ok { marker["sender"] = string(sender) if name := w.names[sender]; name != "" { marker["name"] = name } } } eventType := event.Type{Type: it.Old.Type, Class: event.MessageEventType} resp, err := intent.SendMessage(ctx, w.row.NewRoom, eventType, &event.Content{Raw: content}, &bridgev2.MatrixSendExtra{ Timestamp: time.UnixMilli(it.Old.Timestamp), }) if err != nil { return "", fail(errSend, fmt.Errorf("failed to write event %d: %w", it.Seq, err)) } return resp.EventID, nil } // writerKind is who writes a sender's moved events. type writerKind int const ( // writeAsBot is the bot's own events. writeAsBot writerKind = iota // writeAsGhost is a contact's events, written by its ghost (in the encrypted room, its hashed // identity, which bridgekit picks). writeAsGhost // writeAsUser is a Xessenger user's events, written by their double puppet: a user the new room is // for (the room's user and its members). writeAsUser // writeForSender is the events of someone who can no longer write in the room, a Xessenger person // who left it (their account deleted too): the bot writes them, its marker naming the sender. Taken // into the new room, they would get its keys. writeForSender ) // writerOf says who writes a sender's events: in two Xessenger users' room its members themselves; in // a portal the bot its own, a contact's ghost theirs, and a user the room is for theirs; everyone else's // the bot for them. func (w *writer) writerOf(sender id.UserID) writerKind { switch { case w.row.Kind == kindXessenger: if slices.Contains(w.row.Members, sender) { return writeAsUser } return writeForSender case sender == w.m.br.Bot.GetMXID(): return writeAsBot } if _, ok := w.m.br.Matrix.ParseGhostMXID(sender); ok { return writeAsGhost } else if sender == w.row.User || slices.Contains(w.row.Members, sender) { return writeAsUser } return writeForSender } // intent is the one that writes a sender's events (writerOf), joined to the new room. A user the room // is for whom the bridge cannot act as stops the move (errSender): writing their events as the bot's // would take them out of their hands. func (w *writer) intent(ctx context.Context, sender id.UserID) (bridgev2.MatrixAPI, error) { if intent, ok := w.intents[sender]; ok { return intent, nil } var intent bridgev2.MatrixAPI kind := w.writerOf(sender) switch kind { case writeAsBot, writeForSender: intent = w.m.br.Bot case writeAsGhost: ghostID, _ := w.m.br.Matrix.ParseGhostMXID(sender) found, err := w.m.br.GetGhostByID(ctx, ghostID) if err != nil { return nil, fail(errSender, err) } intent = found.Intent case writeAsUser: if intent = w.m.userIntent(ctx, sender); intent == nil { return nil, fail(errSender, fmt.Errorf("cannot act as %s", sender)) } } if err := intent.EnsureJoined(ctx, w.row.NewRoom); err != nil { return nil, fail(errSend, fmt.Errorf("failed to join %s to the new room: %w", sender, err)) } w.intents[sender] = intent switch kind { case writeAsGhost: w.ghosts[sender] = true case writeForSender: w.forOthers[sender] = true } return intent, nil } // userIntent is a Xessenger user's double puppet, nil when the bridge cannot act as them. func (m *mover) userIntent(ctx context.Context, userID id.UserID) bridgev2.MatrixAPI { if user, err := m.br.GetExistingUserByMXID(ctx, userID); err == nil && user != nil { if intent := user.DoublePuppet(ctx); intent != nil { return intent } } intent, _, err := m.br.Matrix.NewUserIntent(ctx, userID, "") if err != nil || intent == nil { zerolog.Ctx(ctx).Err(err).Stringer("user_id", userID).Msg("Cannot act as a user to write their messages") return nil } return intent } // repoint makes bridgev2's own record of a moved message or reaction name its new event, so that // what arrives later from the network (an edit, a reply, a reaction) points at the new room. A record // it cannot point stops the move (errStore): the event is the last written then, which the next run // points again before it goes on. func (m *mover) repoint(ctx context.Context, it item, newEvent id.EventID) error { if it.Reaction { reaction, err := m.br.DB.Reaction.GetByMXID(ctx, id.EventID(it.Old.ID)) if err != nil { return fail(errStore, fmt.Errorf("failed to read the record of reaction %d: %w", it.Seq, err)) } else if reaction == nil { return nil } reaction.MXID = newEvent if err = m.br.DB.Reaction.Upsert(ctx, reaction); err != nil { return fail(errStore, fmt.Errorf("failed to point reaction %d at its moved event: %w", it.Seq, err)) } return nil } message, err := m.br.DB.Message.GetPartByMXID(ctx, id.EventID(it.Old.ID)) if err != nil { return fail(errStore, fmt.Errorf("failed to read the record of message %d: %w", it.Seq, err)) } else if message == nil { return nil } message.MXID = newEvent if err = m.br.DB.Message.Update(ctx, message); err != nil { return fail(errStore, fmt.Errorf("failed to point message %d at its moved event: %w", it.Seq, err)) } return nil } // readWritten fetches a written event and decrypts it with the bot's own copy of the session: it // must be encrypted on the server. func (m *mover) readWritten(ctx context.Context, evt *event.Event) (json.RawMessage, error) { if evt.Type != event.EventEncrypted { return nil, fail(errNotEncrypted, fmt.Errorf("%s is not encrypted on the server", evt.ID)) } if evt.Content.Parsed == nil { if err := evt.Content.ParseRaw(evt.Type); err != nil { return nil, err } } if m.conn.Crypto == nil { return nil, fail(errNotEncrypted, errors.New("the bridge has no encryption")) } decrypted, err := m.conn.Crypto.Decrypt(ctx, evt) if err != nil { return nil, err } return decrypted.Content.VeryRaw, nil } // writtenHere says whether this bridge's own device encrypted an event, as it does every event a // move writes: mautrix names the device in what it encrypts. func (m *mover) writtenHere(evt *event.Event) bool { if m.conn.Crypto == nil { return false } client := m.conn.Crypto.Client() if client == nil || client.DeviceID == "" { return false } if evt.Content.Parsed == nil && evt.Content.ParseRaw(evt.Type) != nil { return false } encrypted, ok := evt.Content.Parsed.(*event.EncryptedEventContent) return ok && encrypted.DeviceID == client.DeviceID } // selfCheck reads back a written event: it is encrypted, and decrypts to the content that was // hashed. It catches a change in how mautrix or bridgekit build what they encrypt. Other content is // errSelfCheck, which handleMigrate does not retry; an event it could not read or decrypt is errRead, // read again by a retry. func (m *mover) selfCheck(ctx context.Context, roomID id.RoomID, eventID id.EventID, sent json.RawMessage) error { evt, err := m.conn.Bot.GetEvent(ctx, roomID, eventID) if err != nil { return fail(errRead, fmt.Errorf("failed to read back %s: %w", eventID, err)) } content, err := m.readWritten(ctx, evt) if err != nil { var f *failure if errors.As(err, &f) { return err } return fail(errRead, fmt.Errorf("failed to decrypt %s: %w", eventID, err)) } want, err := ContentHash(sent) if err != nil { return fail(errSelfCheck, err) } got, err := ContentHash(content) if err != nil || got != want { return fail(errSelfCheck, fmt.Errorf("%s decrypts to other content than was hashed", eventID)) } return nil } // readBackPage is how many of the new room's events readBack reads back at once. const readBackPage = 100 // findWritten looks for an event the bridge was writing when it stopped (readBack), and keeps it as // written when it turns up. func (m *mover) findWritten(ctx context.Context, row *room, sealer *storeseal.Sealer, it item) (id.EventID, error) { evt, content, err := m.readBack(ctx, row, it.Seq, func(marker Marker) bool { return marker.From == it.Old.ID }) if err != nil || evt == nil { return "", err } if err = m.record(ctx, row, sealer, it, evt.ID, content); err != nil { return "", err } if row.Kind == kindPortal { if err = m.repoint(ctx, it, evt.ID); err != nil { return "", err } } return evt.ID, nil } // readBack looks for the event the bridge set out to write as `seq` (isIt says whether an event whose // marker has that seq is the one): the new room is read back from its end until that marker, an // earlier one or the room's start turns up, under however much of the conversation since, and the // event is given back with its decrypted content (nil for none). A room with more than maxEvents on // top stops the move (errTooLarge) rather than take the event as never written and write it a second // time. The copies of a history written before its user was in the room (setAside) carry the same // markers and are passed over: the history written again begins after them. func (m *mover) readBack(ctx context.Context, row *room, seq int, isIt func(Marker) bool) (*event.Event, json.RawMessage, error) { stale, err := m.store.staleEvents(ctx, row.OldRoom) if err != nil { return nil, nil, fail(errStore, err) } setAside := make(map[id.EventID]bool, len(stale)) for _, s := range stale { setAside[s.NewEventID] = true } filter := &mautrix.FilterPart{Types: []event.Type{event.EventEncrypted}} from := "" for range maxEvents / readBackPage { page, err := m.conn.Bot.Messages(ctx, row.NewRoom, from, "", mautrix.DirectionBackward, filter, readBackPage) if err != nil { return nil, nil, fail(errRead, fmt.Errorf("failed to read the new room back: %w", err)) } for _, evt := range page.Chunk { if setAside[evt.ID] { continue } content, err := m.readWritten(ctx, evt) if err != nil { if m.writtenHere(evt) { // This bridge's own device encrypted it, so it may be the event that was being // written: writing that one again would leave it twice in the new room. The move // waits for a retry that can read it. return nil, nil, fail(errRead, fmt.Errorf("failed to read back %s, which this bridge wrote: %w", evt.ID, err)) } continue } marker, ok := MarkerOf(content) if !ok { continue } if marker.Seq == seq && isIt(marker) { return evt, content, nil } else if marker.Seq < seq { return nil, nil, nil } } // As in readRoom, an empty page with an end reads on. if page.End == "" || page.End == from { return nil, nil, nil } from = page.End } return nil, nil, fail(errTooLarge, fmt.Errorf("neither event %d nor an earlier one is among the new room's last %d events", seq, maxEvents)) }