2022-01-27 14:29:14 +00:00
|
|
|
package input
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2023-03-13 15:45:14 +00:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2023-04-06 08:55:01 +00:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/fclient"
|
2023-04-19 14:50:33 +00:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/spec"
|
2023-03-13 15:45:14 +00:00
|
|
|
"github.com/matrix-org/util"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
fedapi "github.com/matrix-org/dendrite/federationapi/api"
|
|
|
|
"github.com/matrix-org/dendrite/internal"
|
|
|
|
"github.com/matrix-org/dendrite/roomserver/api"
|
2022-02-11 17:40:14 +00:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/state"
|
2022-02-23 15:41:32 +00:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/storage"
|
2022-02-07 19:10:01 +00:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/types"
|
2022-01-27 14:29:14 +00:00
|
|
|
)
|
|
|
|
|
2022-02-09 20:31:24 +00:00
|
|
|
type parsedRespState struct {
|
2023-05-02 14:03:16 +00:00
|
|
|
AuthEvents []gomatrixserverlib.PDU
|
|
|
|
StateEvents []gomatrixserverlib.PDU
|
2022-02-09 20:31:24 +00:00
|
|
|
}
|
|
|
|
|
2023-04-27 15:35:19 +00:00
|
|
|
func (p *parsedRespState) Events() []gomatrixserverlib.PDU {
|
2023-05-02 14:03:16 +00:00
|
|
|
eventsByID := make(map[string]gomatrixserverlib.PDU, len(p.AuthEvents)+len(p.StateEvents))
|
2022-02-28 14:51:40 +00:00
|
|
|
for i, event := range p.AuthEvents {
|
|
|
|
eventsByID[event.EventID()] = p.AuthEvents[i]
|
|
|
|
}
|
|
|
|
for i, event := range p.StateEvents {
|
|
|
|
eventsByID[event.EventID()] = p.StateEvents[i]
|
|
|
|
}
|
2023-05-02 14:03:16 +00:00
|
|
|
allEvents := make([]gomatrixserverlib.PDU, 0, len(eventsByID))
|
2022-02-28 14:51:40 +00:00
|
|
|
for _, event := range eventsByID {
|
|
|
|
allEvents = append(allEvents, event)
|
|
|
|
}
|
2023-04-27 15:35:19 +00:00
|
|
|
return gomatrixserverlib.ReverseTopologicalOrdering(
|
|
|
|
gomatrixserverlib.ToPDUs(allEvents), gomatrixserverlib.TopologicalOrderByAuthEvents)
|
2022-02-28 14:51:40 +00:00
|
|
|
}
|
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
type missingStateReq struct {
|
2022-11-02 11:30:49 +00:00
|
|
|
log *logrus.Entry
|
2023-04-19 14:50:33 +00:00
|
|
|
virtualHost spec.ServerName
|
|
|
|
origin spec.ServerName
|
2023-02-24 08:40:20 +00:00
|
|
|
db storage.RoomDatabase
|
2022-02-23 15:41:32 +00:00
|
|
|
roomInfo *types.RoomInfo
|
2022-01-27 14:29:14 +00:00
|
|
|
inputer *Inputer
|
|
|
|
keys gomatrixserverlib.JSONVerifier
|
2022-05-05 18:30:38 +00:00
|
|
|
federation fedapi.RoomserverFederationAPI
|
2022-01-27 14:29:14 +00:00
|
|
|
roomsMu *internal.MutexByRoom
|
2023-04-19 14:50:33 +00:00
|
|
|
servers []spec.ServerName
|
2022-01-27 14:29:14 +00:00
|
|
|
hadEvents map[string]bool
|
|
|
|
hadEventsMutex sync.Mutex
|
2023-05-02 14:03:16 +00:00
|
|
|
haveEvents map[string]gomatrixserverlib.PDU
|
2022-01-27 14:29:14 +00:00
|
|
|
haveEventsMutex sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
// processEventWithMissingState is the entrypoint for a missingStateReq
|
|
|
|
// request, as called from processRoomEvent.
|
2022-02-10 10:05:14 +00:00
|
|
|
// nolint:gocyclo
|
2022-01-27 14:29:14 +00:00
|
|
|
func (t *missingStateReq) processEventWithMissingState(
|
2023-05-02 14:03:16 +00:00
|
|
|
ctx context.Context, e gomatrixserverlib.PDU, roomVersion gomatrixserverlib.RoomVersion,
|
2022-02-10 10:05:14 +00:00
|
|
|
) (*parsedRespState, error) {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "processEventWithMissingState")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
// We are missing the previous events for this events.
|
|
|
|
// This means that there is a gap in our view of the history of the
|
|
|
|
// room. There two ways that we can handle such a gap:
|
|
|
|
// 1) We can fill in the gap using /get_missing_events
|
|
|
|
// 2) We can leave the gap and request the state of the room at
|
|
|
|
// this event from the remote server using either /state_ids
|
|
|
|
// or /state.
|
|
|
|
// Synapse will attempt to do 1 and if that fails or if the gap is
|
|
|
|
// too large then it will attempt 2.
|
|
|
|
// Synapse will use /state_ids if possible since usually the state
|
|
|
|
// is largely unchanged and it is more efficient to fetch a list of
|
|
|
|
// event ids and then use /event to fetch the individual events.
|
|
|
|
// However not all version of synapse support /state_ids so you may
|
|
|
|
// need to fallback to /state.
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log = util.GetLogger(ctx).WithFields(map[string]interface{}{
|
2022-01-27 14:29:14 +00:00
|
|
|
"txn_event": e.EventID(),
|
|
|
|
"room_id": e.RoomID(),
|
|
|
|
"txn_prev_events": e.PrevEventIDs(),
|
|
|
|
})
|
|
|
|
|
|
|
|
// Attempt to fill in the gap using /get_missing_events
|
|
|
|
// This will either:
|
|
|
|
// - fill in the gap completely then process event `e` returning no backwards extremity
|
|
|
|
// - fail to fill in the gap and tell us to terminate the transaction err=not nil
|
|
|
|
// - fail to fill in the gap and tell us to fetch state at the new backwards extremity, and to not terminate the transaction
|
2022-02-10 10:05:14 +00:00
|
|
|
newEvents, isGapFilled, prevStatesKnown, err := t.getMissingEvents(ctx, e, roomVersion)
|
2022-01-27 14:29:14 +00:00
|
|
|
if err != nil {
|
2022-02-10 10:05:14 +00:00
|
|
|
return nil, fmt.Errorf("t.getMissingEvents: %w", err)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
if len(newEvents) == 0 {
|
2022-02-10 10:05:14 +00:00
|
|
|
return nil, fmt.Errorf("expected to find missing events but didn't")
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
if isGapFilled {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.Infof("Gap filled by /get_missing_events, injecting %d new events", len(newEvents))
|
2022-01-27 14:29:14 +00:00
|
|
|
// we can just inject all the newEvents as new as we may have only missed 1 or 2 events and have filled
|
|
|
|
// in the gap in the DAG
|
|
|
|
for _, newEvent := range newEvents {
|
2022-11-15 15:05:23 +00:00
|
|
|
err = t.inputer.processRoomEvent(ctx, t.virtualHost, &api.InputRoomEvent{
|
2022-02-07 19:10:01 +00:00
|
|
|
Kind: api.KindOld,
|
2023-05-02 14:03:16 +00:00
|
|
|
Event: &types.HeaderedEvent{PDU: newEvent},
|
2022-01-27 14:29:14 +00:00
|
|
|
Origin: t.origin,
|
|
|
|
SendAsServer: api.DoNotSendToOtherServers,
|
|
|
|
})
|
|
|
|
if err != nil {
|
2022-02-07 19:10:01 +00:00
|
|
|
if _, ok := err.(types.RejectedError); !ok {
|
2022-02-10 10:05:14 +00:00
|
|
|
return nil, fmt.Errorf("t.inputer.processRoomEvent (filling gap): %w", err)
|
2022-02-07 19:10:01 +00:00
|
|
|
}
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-10 10:05:14 +00:00
|
|
|
// If we filled the gap *and* we know the state before the prev events
|
|
|
|
// then there's nothing else to do, we have everything we need to deal
|
|
|
|
// with the new event.
|
|
|
|
if isGapFilled && prevStatesKnown {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.Infof("Gap filled and state found for all prev events")
|
2022-02-10 10:05:14 +00:00
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, if we've reached this point, it's possible that we've
|
|
|
|
// either not closed the gap, or we did but we still don't seem to
|
|
|
|
// know the events before the new event. Start by looking up the
|
|
|
|
// state at the event at the back of the gap and we'll try to roll
|
|
|
|
// forward the state first.
|
2022-01-27 14:29:14 +00:00
|
|
|
backwardsExtremity := newEvents[0]
|
|
|
|
newEvents = newEvents[1:]
|
|
|
|
|
2022-02-10 10:05:14 +00:00
|
|
|
resolvedState, err := t.lookupResolvedStateBeforeEvent(ctx, backwardsExtremity, roomVersion)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("t.lookupState (backwards extremity): %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
hadEvents := map[string]bool{}
|
|
|
|
t.hadEventsMutex.Lock()
|
|
|
|
for k, v := range t.hadEvents {
|
|
|
|
hadEvents[k] = v
|
|
|
|
}
|
|
|
|
t.hadEventsMutex.Unlock()
|
|
|
|
|
|
|
|
sendOutliers := func(resolvedState *parsedRespState) error {
|
2022-02-28 14:51:40 +00:00
|
|
|
outliers := resolvedState.Events()
|
|
|
|
outlierRoomEvents := make([]api.InputRoomEvent, 0, len(outliers))
|
2022-02-10 10:05:14 +00:00
|
|
|
for _, outlier := range outliers {
|
|
|
|
if hadEvents[outlier.EventID()] {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
outlierRoomEvents = append(outlierRoomEvents, api.InputRoomEvent{
|
|
|
|
Kind: api.KindOutlier,
|
2023-05-02 14:03:16 +00:00
|
|
|
Event: &types.HeaderedEvent{PDU: outlier},
|
2022-02-10 10:05:14 +00:00
|
|
|
Origin: t.origin,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
for _, ire := range outlierRoomEvents {
|
2022-11-15 15:05:23 +00:00
|
|
|
if err = t.inputer.processRoomEvent(ctx, t.virtualHost, &ire); err != nil {
|
2022-02-10 10:05:14 +00:00
|
|
|
if _, ok := err.(types.RejectedError); !ok {
|
|
|
|
return fmt.Errorf("t.inputer.processRoomEvent (outlier): %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send outliers first so we can send the state along with the new backwards
|
|
|
|
// extremity without any missing auth events.
|
|
|
|
if err = sendOutliers(resolvedState); err != nil {
|
|
|
|
return nil, fmt.Errorf("sendOutliers: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now send the backward extremity into the roomserver with the
|
|
|
|
// newly resolved state. This marks the "oldest" point in the backfill and
|
|
|
|
// sets the baseline state for any new events after this.
|
|
|
|
stateIDs := make([]string, 0, len(resolvedState.StateEvents))
|
|
|
|
for _, event := range resolvedState.StateEvents {
|
|
|
|
stateIDs = append(stateIDs, event.EventID())
|
|
|
|
}
|
|
|
|
|
2022-11-15 15:05:23 +00:00
|
|
|
err = t.inputer.processRoomEvent(ctx, t.virtualHost, &api.InputRoomEvent{
|
2022-02-10 10:05:14 +00:00
|
|
|
Kind: api.KindOld,
|
2023-05-02 14:03:16 +00:00
|
|
|
Event: &types.HeaderedEvent{PDU: backwardsExtremity},
|
2022-02-10 10:05:14 +00:00
|
|
|
Origin: t.origin,
|
|
|
|
HasState: true,
|
|
|
|
StateEventIDs: stateIDs,
|
|
|
|
SendAsServer: api.DoNotSendToOtherServers,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
if _, ok := err.(types.RejectedError); !ok {
|
|
|
|
return nil, fmt.Errorf("t.inputer.processRoomEvent (backward extremity): %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Then send all of the newer backfilled events, of which will all be newer
|
|
|
|
// than the backward extremity, into the roomserver without state. This way
|
|
|
|
// they will automatically fast-forward based on the room state at the
|
|
|
|
// extremity in the last step.
|
|
|
|
for _, newEvent := range newEvents {
|
2022-11-15 15:05:23 +00:00
|
|
|
err = t.inputer.processRoomEvent(ctx, t.virtualHost, &api.InputRoomEvent{
|
2022-02-10 10:05:14 +00:00
|
|
|
Kind: api.KindOld,
|
2023-05-02 14:03:16 +00:00
|
|
|
Event: &types.HeaderedEvent{PDU: newEvent},
|
2022-02-10 10:05:14 +00:00
|
|
|
Origin: t.origin,
|
|
|
|
SendAsServer: api.DoNotSendToOtherServers,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
if _, ok := err.(types.RejectedError); !ok {
|
|
|
|
return nil, fmt.Errorf("t.inputer.processRoomEvent (fast forward): %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finally, check again if we know everything we need to know in order to
|
|
|
|
// make forward progress. If the prev state is known then we consider the
|
|
|
|
// rolled forward state to be sufficient — we now know all of the state
|
|
|
|
// before the prev events. If we don't then we need to look up the state
|
|
|
|
// before the new event as well, otherwise we will never make any progress.
|
|
|
|
if t.isPrevStateKnown(ctx, e) {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we still haven't got the state for the prev events then we'll go and
|
|
|
|
// ask the federation for it if needed.
|
|
|
|
resolvedState, err = t.lookupResolvedStateBeforeEvent(ctx, e, roomVersion)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("t.lookupState (new event): %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send the outliers for the retrieved state.
|
|
|
|
if err = sendOutliers(resolvedState); err != nil {
|
|
|
|
return nil, fmt.Errorf("sendOutliers: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Then return the resolved state, for which the caller can replace the
|
|
|
|
// HasState with the event IDs to create a new state snapshot when we
|
|
|
|
// process the new event.
|
|
|
|
return resolvedState, nil
|
|
|
|
}
|
|
|
|
|
2023-05-02 14:03:16 +00:00
|
|
|
func (t *missingStateReq) lookupResolvedStateBeforeEvent(ctx context.Context, e gomatrixserverlib.PDU, roomVersion gomatrixserverlib.RoomVersion) (*parsedRespState, error) {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "lookupResolvedStateBeforeEvent")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
type respState struct {
|
|
|
|
// A snapshot is considered trustworthy if it came from our own roomserver.
|
|
|
|
// That's because the state will have been through state resolution once
|
|
|
|
// already in QueryStateAfterEvent.
|
|
|
|
trustworthy bool
|
2022-02-09 20:31:24 +00:00
|
|
|
*parsedRespState
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// at this point we know we're going to have a gap: we need to work out the room state at the new backwards extremity.
|
|
|
|
// Therefore, we cannot just query /state_ids with this event to get the state before. Instead, we need to query
|
|
|
|
// the state AFTER all the prev_events for this event, then apply state resolution to that to get the state before the event.
|
|
|
|
var states []*respState
|
2022-02-10 10:05:14 +00:00
|
|
|
for _, prevEventID := range e.PrevEventIDs() {
|
2022-01-27 14:29:14 +00:00
|
|
|
// Look up what the state is after the backward extremity. This will either
|
|
|
|
// come from the roomserver, if we know all the required events, or it will
|
|
|
|
// come from a remote server via /state_ids if not.
|
2022-02-10 10:05:14 +00:00
|
|
|
prevState, trustworthy, err := t.lookupStateAfterEvent(ctx, roomVersion, e.RoomID(), prevEventID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("t.lookupStateAfterEvent: %w", err)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
// Append the state onto the collected state. We'll run this through the
|
|
|
|
// state resolution next.
|
|
|
|
states = append(states, &respState{trustworthy, prevState})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now that we have collected all of the state from the prev_events, we'll
|
|
|
|
// run the state through the appropriate state resolution algorithm for the
|
|
|
|
// room if needed. This does a couple of things:
|
|
|
|
// 1. Ensures that the state is deduplicated fully for each state-key tuple
|
|
|
|
// 2. Ensures that we pick the latest events from both sets, in the case that
|
|
|
|
// one of the prev_events is quite a bit older than the others
|
2022-02-09 20:31:24 +00:00
|
|
|
resolvedState := &parsedRespState{}
|
2022-01-27 14:29:14 +00:00
|
|
|
switch len(states) {
|
|
|
|
case 0:
|
2023-04-19 14:50:33 +00:00
|
|
|
extremityIsCreate := e.Type() == spec.MRoomCreate && e.StateKeyEquals("")
|
2022-01-27 14:29:14 +00:00
|
|
|
if !extremityIsCreate {
|
|
|
|
// There are no previous states and this isn't the beginning of the
|
|
|
|
// room - this is an error condition!
|
2022-02-10 10:05:14 +00:00
|
|
|
return nil, fmt.Errorf("expected %d states but got %d", len(e.PrevEventIDs()), len(states))
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
case 1:
|
|
|
|
// There's only one previous state - if it's trustworthy (came from a
|
|
|
|
// local state snapshot which will already have been through state res),
|
2022-02-10 10:05:14 +00:00
|
|
|
// use it as-is. There's no point in resolving it again. Only trust a
|
|
|
|
// trustworthy state snapshot if it actually contains some state for all
|
|
|
|
// non-create events, otherwise we need to resolve what came from federation.
|
2023-04-19 14:50:33 +00:00
|
|
|
isCreate := e.Type() == spec.MRoomCreate && e.StateKeyEquals("")
|
2022-02-10 10:05:14 +00:00
|
|
|
if states[0].trustworthy && (isCreate || len(states[0].StateEvents) > 0) {
|
2022-02-09 20:31:24 +00:00
|
|
|
resolvedState = states[0].parsedRespState
|
2022-01-27 14:29:14 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
// Otherwise, if it isn't trustworthy (came from federation), run it through
|
|
|
|
// state resolution anyway for safety, in case there are duplicates.
|
|
|
|
fallthrough
|
|
|
|
default:
|
2022-02-09 20:31:24 +00:00
|
|
|
respStates := make([]*parsedRespState, len(states))
|
2022-01-27 14:29:14 +00:00
|
|
|
for i := range states {
|
2022-02-09 20:31:24 +00:00
|
|
|
respStates[i] = states[i].parsedRespState
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
// There's more than one previous state - run them all through state res
|
2022-02-10 10:05:14 +00:00
|
|
|
var err error
|
2022-01-27 14:29:14 +00:00
|
|
|
t.roomsMu.Lock(e.RoomID())
|
2022-02-10 10:05:14 +00:00
|
|
|
resolvedState, err = t.resolveStatesAndCheck(ctx, roomVersion, respStates, e)
|
2022-01-27 14:29:14 +00:00
|
|
|
t.roomsMu.Unlock(e.RoomID())
|
|
|
|
if err != nil {
|
2022-02-10 10:05:14 +00:00
|
|
|
return nil, fmt.Errorf("t.resolveStatesAndCheck: %w", err)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-10 10:05:14 +00:00
|
|
|
return resolvedState, nil
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// lookupStateAfterEvent returns the room state after `eventID`, which is the state before eventID with the state of `eventID` (if it's a state event)
|
|
|
|
// added into the mix.
|
2022-02-09 20:31:24 +00:00
|
|
|
func (t *missingStateReq) lookupStateAfterEvent(ctx context.Context, roomVersion gomatrixserverlib.RoomVersion, roomID, eventID string) (*parsedRespState, bool, error) {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "lookupStateAfterEvent")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
// try doing all this locally before we resort to querying federation
|
2022-11-02 11:30:49 +00:00
|
|
|
respState := t.lookupStateAfterEventLocally(ctx, eventID)
|
2022-01-27 14:29:14 +00:00
|
|
|
if respState != nil {
|
|
|
|
return respState, true, nil
|
|
|
|
}
|
|
|
|
|
2022-08-03 16:37:27 +00:00
|
|
|
logrus.WithContext(ctx).Warnf("State for event %s not available locally, falling back to federation (via %d servers)", eventID, len(t.servers))
|
2022-01-27 14:29:14 +00:00
|
|
|
respState, err := t.lookupStateBeforeEvent(ctx, roomVersion, roomID, eventID)
|
|
|
|
if err != nil {
|
2022-08-03 16:37:27 +00:00
|
|
|
logrus.WithContext(ctx).WithError(err).Errorf("Failed to look up state before event %s", eventID)
|
2022-01-27 14:29:14 +00:00
|
|
|
return nil, false, fmt.Errorf("t.lookupStateBeforeEvent: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// fetch the event we're missing and add it to the pile
|
|
|
|
h, err := t.lookupEvent(ctx, roomVersion, roomID, eventID, false)
|
|
|
|
switch err.(type) {
|
|
|
|
case verifySigError:
|
|
|
|
return respState, false, nil
|
|
|
|
case nil:
|
|
|
|
// do nothing
|
|
|
|
default:
|
2022-08-03 16:37:27 +00:00
|
|
|
logrus.WithContext(ctx).WithError(err).Errorf("Failed to look up event %s", eventID)
|
2022-01-27 14:29:14 +00:00
|
|
|
return nil, false, fmt.Errorf("t.lookupEvent: %w", err)
|
|
|
|
}
|
|
|
|
h = t.cacheAndReturn(h)
|
|
|
|
if h.StateKey() != nil {
|
|
|
|
addedToState := false
|
|
|
|
for i := range respState.StateEvents {
|
|
|
|
se := respState.StateEvents[i]
|
|
|
|
if se.Type() == h.Type() && se.StateKeyEquals(*h.StateKey()) {
|
2022-02-11 17:40:14 +00:00
|
|
|
respState.StateEvents[i] = h
|
2022-01-27 14:29:14 +00:00
|
|
|
addedToState = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !addedToState {
|
2022-02-11 17:40:14 +00:00
|
|
|
respState.StateEvents = append(respState.StateEvents, h)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return respState, false, nil
|
|
|
|
}
|
|
|
|
|
2023-05-02 14:03:16 +00:00
|
|
|
func (t *missingStateReq) cacheAndReturn(ev gomatrixserverlib.PDU) gomatrixserverlib.PDU {
|
2022-01-27 14:29:14 +00:00
|
|
|
t.haveEventsMutex.Lock()
|
|
|
|
defer t.haveEventsMutex.Unlock()
|
|
|
|
if cached, exists := t.haveEvents[ev.EventID()]; exists {
|
|
|
|
return cached
|
|
|
|
}
|
|
|
|
t.haveEvents[ev.EventID()] = ev
|
|
|
|
return ev
|
|
|
|
}
|
|
|
|
|
2022-11-02 11:30:49 +00:00
|
|
|
func (t *missingStateReq) lookupStateAfterEventLocally(ctx context.Context, eventID string) *parsedRespState {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "lookupStateAfterEventLocally")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
2022-02-11 17:40:14 +00:00
|
|
|
var res parsedRespState
|
2022-08-02 11:27:15 +00:00
|
|
|
roomState := state.NewStateResolution(t.db, t.roomInfo)
|
2022-02-11 17:40:14 +00:00
|
|
|
stateAtEvents, err := t.db.StateAtEventIDs(ctx, []string{eventID})
|
|
|
|
if err != nil {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithError(err).Warnf("failed to get state after %s locally", eventID)
|
2022-02-11 17:40:14 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
stateEntries, err := roomState.LoadCombinedStateAfterEvents(ctx, stateAtEvents)
|
|
|
|
if err != nil {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithError(err).Warnf("failed to load combined state after %s locally", eventID)
|
2022-02-11 17:40:14 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
stateEventNIDs := make([]types.EventNID, 0, len(stateEntries))
|
|
|
|
for _, entry := range stateEntries {
|
|
|
|
stateEventNIDs = append(stateEventNIDs, entry.EventNID)
|
|
|
|
}
|
2023-03-01 16:06:47 +00:00
|
|
|
stateEvents, err := t.db.Events(ctx, t.roomInfo, stateEventNIDs)
|
2022-02-11 17:40:14 +00:00
|
|
|
if err != nil {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithError(err).Warnf("failed to load state events locally")
|
2022-01-27 14:29:14 +00:00
|
|
|
return nil
|
|
|
|
}
|
2023-05-02 14:03:16 +00:00
|
|
|
res.StateEvents = make([]gomatrixserverlib.PDU, 0, len(stateEvents))
|
2022-02-11 17:40:14 +00:00
|
|
|
for _, ev := range stateEvents {
|
2022-01-27 14:29:14 +00:00
|
|
|
// set the event from the haveEvents cache - this means we will share pointers with other prev_event branches for this
|
|
|
|
// processEvent request, which is better for memory.
|
2023-05-02 14:03:16 +00:00
|
|
|
res.StateEvents = append(res.StateEvents, t.cacheAndReturn(ev.PDU))
|
2022-01-27 14:29:14 +00:00
|
|
|
t.hadEvent(ev.EventID())
|
|
|
|
}
|
|
|
|
|
2022-02-11 17:40:14 +00:00
|
|
|
// encourage GC
|
|
|
|
stateEvents, stateEventNIDs, stateEntries, stateAtEvents = nil, nil, nil, nil // nolint:ineffassign
|
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
missingAuthEvents := map[string]bool{}
|
2023-05-02 14:03:16 +00:00
|
|
|
res.AuthEvents = make([]gomatrixserverlib.PDU, 0, len(stateEvents)*3)
|
2022-01-27 14:29:14 +00:00
|
|
|
for _, ev := range stateEvents {
|
|
|
|
t.haveEventsMutex.Lock()
|
|
|
|
for _, ae := range ev.AuthEventIDs() {
|
|
|
|
if aev, ok := t.haveEvents[ae]; ok {
|
2022-02-11 17:40:14 +00:00
|
|
|
res.AuthEvents = append(res.AuthEvents, aev)
|
2022-01-27 14:29:14 +00:00
|
|
|
} else {
|
|
|
|
missingAuthEvents[ae] = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
t.haveEventsMutex.Unlock()
|
|
|
|
}
|
|
|
|
// QueryStateAfterEvents does not return the auth events, so fetch them now. We know the roomserver has them else it wouldn't
|
|
|
|
// have stored the event.
|
|
|
|
if len(missingAuthEvents) > 0 {
|
|
|
|
var missingEventList []string
|
|
|
|
for evID := range missingAuthEvents {
|
|
|
|
missingEventList = append(missingEventList, evID)
|
|
|
|
}
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithField("count", len(missingEventList)).Debugf("Fetching missing auth events")
|
2023-03-01 16:06:47 +00:00
|
|
|
events, err := t.db.EventsFromIDs(ctx, t.roomInfo, missingEventList)
|
2022-02-11 17:40:14 +00:00
|
|
|
if err != nil {
|
2022-01-27 14:29:14 +00:00
|
|
|
return nil
|
|
|
|
}
|
2022-02-11 17:40:14 +00:00
|
|
|
for i, ev := range events {
|
2023-05-02 14:03:16 +00:00
|
|
|
res.AuthEvents = append(res.AuthEvents, t.cacheAndReturn(events[i].PDU))
|
2022-01-27 14:29:14 +00:00
|
|
|
t.hadEvent(ev.EventID())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-11 17:40:14 +00:00
|
|
|
return &res
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// lookuptStateBeforeEvent returns the room state before the event e, which is just /state_ids and/or /state depending on what
|
|
|
|
// the server supports.
|
|
|
|
func (t *missingStateReq) lookupStateBeforeEvent(ctx context.Context, roomVersion gomatrixserverlib.RoomVersion, roomID, eventID string) (
|
2022-02-09 20:31:24 +00:00
|
|
|
*parsedRespState, error) {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "lookupStateBeforeEvent")
|
|
|
|
defer trace.EndRegion()
|
2022-01-27 14:29:14 +00:00
|
|
|
|
|
|
|
// Attempt to fetch the missing state using /state_ids and /events
|
|
|
|
return t.lookupMissingStateViaStateIDs(ctx, roomID, eventID, roomVersion)
|
|
|
|
}
|
|
|
|
|
2023-05-02 14:03:16 +00:00
|
|
|
func (t *missingStateReq) resolveStatesAndCheck(ctx context.Context, roomVersion gomatrixserverlib.RoomVersion, states []*parsedRespState, backwardsExtremity gomatrixserverlib.PDU) (*parsedRespState, error) {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "resolveStatesAndCheck")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
2023-05-02 14:03:16 +00:00
|
|
|
var authEventList []gomatrixserverlib.PDU
|
|
|
|
var stateEventList []gomatrixserverlib.PDU
|
2022-01-27 14:29:14 +00:00
|
|
|
for _, state := range states {
|
|
|
|
authEventList = append(authEventList, state.AuthEvents...)
|
|
|
|
stateEventList = append(stateEventList, state.StateEvents...)
|
|
|
|
}
|
2023-04-27 15:35:19 +00:00
|
|
|
resolvedStateEvents, err := gomatrixserverlib.ResolveConflicts(
|
|
|
|
roomVersion, gomatrixserverlib.ToPDUs(stateEventList), gomatrixserverlib.ToPDUs(authEventList),
|
|
|
|
)
|
2022-01-27 14:29:14 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
// apply the current event
|
|
|
|
retryAllowedState:
|
|
|
|
if err = checkAllowedByState(backwardsExtremity, resolvedStateEvents); err != nil {
|
|
|
|
switch missing := err.(type) {
|
|
|
|
case gomatrixserverlib.MissingAuthEventError:
|
|
|
|
h, err2 := t.lookupEvent(ctx, roomVersion, backwardsExtremity.RoomID(), missing.AuthEventID, true)
|
|
|
|
switch err2.(type) {
|
|
|
|
case verifySigError:
|
2022-02-09 20:31:24 +00:00
|
|
|
return &parsedRespState{
|
2022-01-27 14:29:14 +00:00
|
|
|
AuthEvents: authEventList,
|
2023-05-02 14:03:16 +00:00
|
|
|
StateEvents: resolvedStateEvents,
|
2022-01-27 14:29:14 +00:00
|
|
|
}, nil
|
|
|
|
case nil:
|
|
|
|
// do nothing
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("missing auth event %s and failed to look it up: %w", missing.AuthEventID, err2)
|
|
|
|
}
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.Tracef("fetched event %s", missing.AuthEventID)
|
2022-02-11 17:40:14 +00:00
|
|
|
resolvedStateEvents = append(resolvedStateEvents, h)
|
2022-01-27 14:29:14 +00:00
|
|
|
goto retryAllowedState
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-02-09 20:31:24 +00:00
|
|
|
return &parsedRespState{
|
2022-01-27 14:29:14 +00:00
|
|
|
AuthEvents: authEventList,
|
2023-05-02 14:03:16 +00:00
|
|
|
StateEvents: resolvedStateEvents,
|
2022-01-27 14:29:14 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// get missing events for `e`. If `isGapFilled`=true then `newEvents` contains all the events to inject,
|
|
|
|
// without `e`. If `isGapFilled=false` then `newEvents` contains the response to /get_missing_events
|
2023-05-02 14:03:16 +00:00
|
|
|
func (t *missingStateReq) getMissingEvents(ctx context.Context, e gomatrixserverlib.PDU, roomVersion gomatrixserverlib.RoomVersion) (newEvents []gomatrixserverlib.PDU, isGapFilled, prevStateKnown bool, err error) {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "getMissingEvents")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
2022-11-02 11:30:49 +00:00
|
|
|
logger := t.log.WithField("event_id", e.EventID()).WithField("room_id", e.RoomID())
|
2022-02-23 15:41:32 +00:00
|
|
|
latest, _, _, err := t.db.LatestEventIDs(ctx, t.roomInfo.RoomNID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, false, false, fmt.Errorf("t.DB.LatestEventIDs: %w", err)
|
|
|
|
}
|
2022-02-07 19:10:01 +00:00
|
|
|
latestEvents := make([]string, len(latest))
|
|
|
|
for i, ev := range latest {
|
|
|
|
latestEvents[i] = ev.EventID
|
2022-01-27 14:29:14 +00:00
|
|
|
t.hadEvent(ev.EventID)
|
|
|
|
}
|
|
|
|
|
2023-04-06 08:55:01 +00:00
|
|
|
var missingResp *fclient.RespMissingEvents
|
2022-01-31 14:36:59 +00:00
|
|
|
for _, server := range t.servers {
|
2023-04-06 08:55:01 +00:00
|
|
|
var m fclient.RespMissingEvents
|
|
|
|
if m, err = t.federation.LookupMissingEvents(ctx, t.virtualHost, server, e.RoomID(), fclient.MissingEvents{
|
2022-01-27 14:29:14 +00:00
|
|
|
Limit: 20,
|
|
|
|
// The latest event IDs that the sender already has. These are skipped when retrieving the previous events of latest_events.
|
|
|
|
EarliestEvents: latestEvents,
|
|
|
|
// The event IDs to retrieve the previous events for.
|
|
|
|
LatestEvents: []string{e.EventID()},
|
|
|
|
}, roomVersion); err == nil {
|
|
|
|
missingResp = &m
|
|
|
|
break
|
|
|
|
} else {
|
2022-01-31 10:48:28 +00:00
|
|
|
logger.WithError(err).Warnf("%s pushed us an event but %q did not respond to /get_missing_events", t.origin, server)
|
2022-01-27 14:29:14 +00:00
|
|
|
if errors.Is(err, context.DeadlineExceeded) {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done(): // the parent request context timed out
|
2022-02-10 10:05:14 +00:00
|
|
|
return nil, false, false, context.DeadlineExceeded
|
2022-01-27 14:29:14 +00:00
|
|
|
default: // this request exceed its own timeout
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if missingResp == nil {
|
2022-01-31 10:48:28 +00:00
|
|
|
logger.WithError(err).Warnf(
|
2022-01-27 14:29:14 +00:00
|
|
|
"%s pushed us an event but %d server(s) couldn't give us details about prev_events via /get_missing_events - dropping this event until it can",
|
|
|
|
t.origin, len(t.servers),
|
|
|
|
)
|
2022-02-10 10:05:14 +00:00
|
|
|
return nil, false, false, missingPrevEventsError{
|
2022-01-27 14:29:14 +00:00
|
|
|
eventID: e.EventID(),
|
|
|
|
err: err,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure events from the missingResp are using the cache - missing events
|
|
|
|
// will be added and duplicates will be removed.
|
2023-05-02 14:03:16 +00:00
|
|
|
missingEvents := make([]gomatrixserverlib.PDU, 0, len(missingResp.Events))
|
2022-02-10 10:05:14 +00:00
|
|
|
for _, ev := range missingResp.Events.UntrustedEvents(roomVersion) {
|
2023-04-27 15:35:19 +00:00
|
|
|
if err = gomatrixserverlib.VerifyEventSignatures(ctx, ev, t.keys); err != nil {
|
2022-09-12 11:30:41 +00:00
|
|
|
continue
|
|
|
|
}
|
2022-02-11 17:40:14 +00:00
|
|
|
missingEvents = append(missingEvents, t.cacheAndReturn(ev))
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
2022-09-12 11:30:41 +00:00
|
|
|
logger.Debugf("get_missing_events returned %d events (%d passed signature checks)", len(missingResp.Events), len(missingEvents))
|
2022-01-27 14:29:14 +00:00
|
|
|
|
|
|
|
// topologically sort and sanity check that we are making forward progress
|
2023-05-02 14:03:16 +00:00
|
|
|
newEvents = gomatrixserverlib.ReverseTopologicalOrdering(
|
2023-04-27 15:35:19 +00:00
|
|
|
gomatrixserverlib.ToPDUs(missingEvents), gomatrixserverlib.TopologicalOrderByPrevEvents)
|
2022-01-27 14:29:14 +00:00
|
|
|
shouldHaveSomeEventIDs := e.PrevEventIDs()
|
|
|
|
hasPrevEvent := false
|
|
|
|
Event:
|
|
|
|
for _, pe := range shouldHaveSomeEventIDs {
|
|
|
|
for _, ev := range newEvents {
|
|
|
|
if ev.EventID() == pe {
|
|
|
|
hasPrevEvent = true
|
|
|
|
break Event
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !hasPrevEvent {
|
|
|
|
err = fmt.Errorf("called /get_missing_events but server %s didn't return any prev_events with IDs %v", t.origin, shouldHaveSomeEventIDs)
|
2022-01-31 10:48:28 +00:00
|
|
|
logger.WithError(err).Warnf(
|
2022-01-27 14:29:14 +00:00
|
|
|
"%s pushed us an event but couldn't give us details about prev_events via /get_missing_events - dropping this event until it can",
|
|
|
|
t.origin,
|
|
|
|
)
|
2022-02-10 10:05:14 +00:00
|
|
|
return nil, false, false, missingPrevEventsError{
|
2022-01-27 14:29:14 +00:00
|
|
|
eventID: e.EventID(),
|
|
|
|
err: err,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(newEvents) == 0 {
|
2022-02-10 10:05:14 +00:00
|
|
|
return nil, false, false, nil // TODO: error instead?
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
earliestNewEvent := newEvents[0]
|
2022-02-10 10:05:14 +00:00
|
|
|
|
|
|
|
// If we retrieved back to the beginning of the room then there's nothing else
|
|
|
|
// to do - we closed the gap.
|
2023-04-19 14:50:33 +00:00
|
|
|
if len(earliestNewEvent.PrevEventIDs()) == 0 && earliestNewEvent.Type() == spec.MRoomCreate && earliestNewEvent.StateKeyEquals("") {
|
2022-02-10 10:05:14 +00:00
|
|
|
return newEvents, true, t.isPrevStateKnown(ctx, e), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// If our backward extremity was not a known event to us then we obviously didn't
|
|
|
|
// close the gap.
|
|
|
|
if state, err := t.db.StateAtEventIDs(ctx, []string{earliestNewEvent.EventID()}); err != nil || len(state) == 0 && state[0].BeforeStateSnapshotNID == 0 {
|
|
|
|
return newEvents, false, false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// At this point we are satisfied that we know the state both at the earliest
|
|
|
|
// retrieved event and at the prev events of the new event.
|
|
|
|
return newEvents, true, t.isPrevStateKnown(ctx, e), nil
|
|
|
|
}
|
|
|
|
|
2023-05-02 14:03:16 +00:00
|
|
|
func (t *missingStateReq) isPrevStateKnown(ctx context.Context, e gomatrixserverlib.PDU) bool {
|
2022-02-10 10:05:14 +00:00
|
|
|
expected := len(e.PrevEventIDs())
|
|
|
|
state, err := t.db.StateAtEventIDs(ctx, e.PrevEventIDs())
|
|
|
|
if err != nil || len(state) != expected {
|
|
|
|
// We didn't get as many state snapshots as we expected, or there was an error,
|
|
|
|
// so we haven't completely solved the problem for the new event.
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// Check to see if we have a populated state snapshot for all of the prev events.
|
|
|
|
for _, stateAtEvent := range state {
|
|
|
|
if stateAtEvent.BeforeStateSnapshotNID == 0 {
|
|
|
|
// One of the prev events still has unknown state, so we haven't really
|
|
|
|
// solved the problem.
|
|
|
|
return false
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
}
|
2022-02-10 10:05:14 +00:00
|
|
|
return true
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
|
2022-02-09 20:31:24 +00:00
|
|
|
func (t *missingStateReq) lookupMissingStateViaState(
|
|
|
|
ctx context.Context, roomID, eventID string, roomVersion gomatrixserverlib.RoomVersion,
|
|
|
|
) (respState *parsedRespState, err error) {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "lookupMissingStateViaState")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
2022-11-15 15:05:23 +00:00
|
|
|
state, err := t.federation.LookupState(ctx, t.virtualHost, t.origin, roomID, eventID, roomVersion)
|
2022-01-27 14:29:14 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-04-14 11:32:42 +00:00
|
|
|
|
|
|
|
// Check that the returned state is valid.
|
|
|
|
authEvents, stateEvents, err := gomatrixserverlib.CheckStateResponse(ctx, &fclient.RespState{
|
2023-04-06 08:55:01 +00:00
|
|
|
StateEvents: state.GetStateEvents(),
|
|
|
|
AuthEvents: state.GetAuthEvents(),
|
2023-04-14 11:32:42 +00:00
|
|
|
}, roomVersion, t.keys, nil)
|
2022-04-05 13:43:44 +00:00
|
|
|
if err != nil {
|
2022-01-27 14:29:14 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2023-04-14 11:32:42 +00:00
|
|
|
return &parsedRespState{
|
2022-04-05 13:43:44 +00:00
|
|
|
AuthEvents: authEvents,
|
|
|
|
StateEvents: stateEvents,
|
2023-04-14 11:32:42 +00:00
|
|
|
}, nil
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *missingStateReq) lookupMissingStateViaStateIDs(ctx context.Context, roomID, eventID string, roomVersion gomatrixserverlib.RoomVersion) (
|
2022-02-09 20:31:24 +00:00
|
|
|
*parsedRespState, error) {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "lookupMissingStateViaStateIDs")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.Infof("lookupMissingStateViaStateIDs %s", eventID)
|
2022-01-27 14:29:14 +00:00
|
|
|
// fetch the state event IDs at the time of the event
|
2023-04-06 08:55:01 +00:00
|
|
|
var stateIDs gomatrixserverlib.StateIDResponse
|
2022-08-03 16:37:27 +00:00
|
|
|
var err error
|
|
|
|
count := 0
|
|
|
|
totalctx, totalcancel := context.WithTimeout(ctx, time.Minute*5)
|
|
|
|
for _, serverName := range t.servers {
|
|
|
|
reqctx, reqcancel := context.WithTimeout(totalctx, time.Second*20)
|
2022-11-15 15:05:23 +00:00
|
|
|
stateIDs, err = t.federation.LookupStateIDs(reqctx, t.virtualHost, serverName, roomID, eventID)
|
2022-08-03 16:37:27 +00:00
|
|
|
reqcancel()
|
|
|
|
if err == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
count++
|
|
|
|
}
|
|
|
|
totalcancel()
|
2022-01-27 14:29:14 +00:00
|
|
|
if err != nil {
|
2022-08-03 16:37:27 +00:00
|
|
|
return nil, fmt.Errorf("t.federation.LookupStateIDs tried %d server(s), last error: %w", count, err)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
// work out which auth/state IDs are missing
|
2023-04-06 08:55:01 +00:00
|
|
|
wantIDs := append(stateIDs.GetStateEventIDs(), stateIDs.GetAuthEventIDs()...)
|
2022-01-27 14:29:14 +00:00
|
|
|
missing := make(map[string]bool)
|
|
|
|
var missingEventList []string
|
|
|
|
t.haveEventsMutex.Lock()
|
|
|
|
for _, sid := range wantIDs {
|
|
|
|
if _, ok := t.haveEvents[sid]; !ok {
|
|
|
|
if !missing[sid] {
|
|
|
|
missing[sid] = true
|
|
|
|
missingEventList = append(missingEventList, sid)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
t.haveEventsMutex.Unlock()
|
|
|
|
|
2023-03-01 16:06:47 +00:00
|
|
|
events, err := t.db.EventsFromIDs(ctx, t.roomInfo, missingEventList)
|
2022-02-11 17:40:14 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("t.db.EventsFromIDs: %w", err)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
2022-02-11 17:40:14 +00:00
|
|
|
|
|
|
|
for i, ev := range events {
|
2023-05-02 14:03:16 +00:00
|
|
|
events[i].PDU = t.cacheAndReturn(events[i].PDU)
|
2022-01-27 14:29:14 +00:00
|
|
|
t.hadEvent(ev.EventID())
|
2022-02-11 17:40:14 +00:00
|
|
|
evID := events[i].EventID()
|
2022-01-27 14:29:14 +00:00
|
|
|
if missing[evID] {
|
|
|
|
delete(missing, evID)
|
|
|
|
}
|
|
|
|
}
|
2022-02-11 17:40:14 +00:00
|
|
|
|
|
|
|
// encourage GC
|
|
|
|
events = nil // nolint:ineffassign
|
2022-01-27 14:29:14 +00:00
|
|
|
|
|
|
|
concurrentRequests := 8
|
|
|
|
missingCount := len(missing)
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithField("event_id", eventID).Debugf("lookupMissingStateViaStateIDs missing %d/%d events", missingCount, len(wantIDs))
|
2022-01-27 14:29:14 +00:00
|
|
|
|
|
|
|
// If over 50% of the auth/state events from /state_ids are missing
|
|
|
|
// then we'll just call /state instead, otherwise we'll just end up
|
|
|
|
// hammering the remote side with /event requests unnecessarily.
|
|
|
|
if missingCount > concurrentRequests && missingCount > len(wantIDs)/2 {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithFields(logrus.Fields{
|
2022-01-27 14:29:14 +00:00
|
|
|
"missing": missingCount,
|
|
|
|
"event_id": eventID,
|
2023-04-06 08:55:01 +00:00
|
|
|
"total_state": len(stateIDs.GetStateEventIDs()),
|
|
|
|
"total_auth_events": len(stateIDs.GetAuthEventIDs()),
|
2022-01-31 10:48:28 +00:00
|
|
|
}).Debug("Fetching all state at event")
|
2022-01-27 14:29:14 +00:00
|
|
|
return t.lookupMissingStateViaState(ctx, roomID, eventID, roomVersion)
|
|
|
|
}
|
|
|
|
|
|
|
|
if missingCount > 0 {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithFields(logrus.Fields{
|
2022-01-27 14:29:14 +00:00
|
|
|
"missing": missingCount,
|
|
|
|
"event_id": eventID,
|
2023-04-06 08:55:01 +00:00
|
|
|
"total_state": len(stateIDs.GetStateEventIDs()),
|
|
|
|
"total_auth_events": len(stateIDs.GetAuthEventIDs()),
|
2022-01-27 14:29:14 +00:00
|
|
|
"concurrent_requests": concurrentRequests,
|
2022-01-31 10:48:28 +00:00
|
|
|
}).Debug("Fetching missing state at event")
|
2022-01-27 14:29:14 +00:00
|
|
|
|
|
|
|
// Create a queue containing all of the missing event IDs that we want
|
|
|
|
// to retrieve.
|
|
|
|
pending := make(chan string, missingCount)
|
|
|
|
for missingEventID := range missing {
|
|
|
|
pending <- missingEventID
|
|
|
|
}
|
|
|
|
close(pending)
|
|
|
|
|
|
|
|
// Define how many workers we should start to do this.
|
|
|
|
if missingCount < concurrentRequests {
|
|
|
|
concurrentRequests = missingCount
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the wait group.
|
|
|
|
var fetchgroup sync.WaitGroup
|
|
|
|
fetchgroup.Add(concurrentRequests)
|
|
|
|
|
|
|
|
// This is the only place where we'll write to t.haveEvents from
|
|
|
|
// multiple goroutines, and everywhere else is blocked on this
|
|
|
|
// synchronous function anyway.
|
|
|
|
var haveEventsMutex sync.Mutex
|
|
|
|
|
|
|
|
// Define what we'll do in order to fetch the missing event ID.
|
|
|
|
fetch := func(missingEventID string) {
|
2022-08-02 12:01:03 +00:00
|
|
|
h, herr := t.lookupEvent(ctx, roomVersion, roomID, missingEventID, false)
|
|
|
|
switch herr.(type) {
|
2022-01-27 14:29:14 +00:00
|
|
|
case verifySigError:
|
|
|
|
return
|
|
|
|
case nil:
|
|
|
|
break
|
|
|
|
default:
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithFields(logrus.Fields{
|
|
|
|
"missing_event_id": missingEventID,
|
2022-08-02 12:01:03 +00:00
|
|
|
}).WithError(herr).Warn("Failed to fetch missing event")
|
2022-01-27 14:29:14 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
haveEventsMutex.Lock()
|
|
|
|
t.cacheAndReturn(h)
|
|
|
|
haveEventsMutex.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the worker.
|
|
|
|
worker := func(ch <-chan string) {
|
|
|
|
defer fetchgroup.Done()
|
|
|
|
for missingEventID := range ch {
|
|
|
|
fetch(missingEventID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start the workers.
|
|
|
|
for i := 0; i < concurrentRequests; i++ {
|
|
|
|
go worker(pending)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait for the workers to finish.
|
|
|
|
fetchgroup.Wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
resp, err := t.createRespStateFromStateIDs(stateIDs)
|
|
|
|
return resp, err
|
|
|
|
}
|
|
|
|
|
2022-02-09 20:31:24 +00:00
|
|
|
func (t *missingStateReq) createRespStateFromStateIDs(
|
2023-04-06 08:55:01 +00:00
|
|
|
stateIDs gomatrixserverlib.StateIDResponse,
|
2022-02-09 20:31:24 +00:00
|
|
|
) (*parsedRespState, error) { // nolint:unparam
|
2022-01-27 14:29:14 +00:00
|
|
|
t.haveEventsMutex.Lock()
|
|
|
|
defer t.haveEventsMutex.Unlock()
|
|
|
|
|
|
|
|
// create a RespState response using the response to /state_ids as a guide
|
2022-02-09 20:31:24 +00:00
|
|
|
respState := parsedRespState{}
|
2022-01-27 14:29:14 +00:00
|
|
|
|
2023-04-06 08:55:01 +00:00
|
|
|
stateEventIDs := stateIDs.GetStateEventIDs()
|
|
|
|
authEventIDs := stateIDs.GetAuthEventIDs()
|
|
|
|
for i := range stateEventIDs {
|
|
|
|
ev, ok := t.haveEvents[stateEventIDs[i]]
|
2022-01-27 14:29:14 +00:00
|
|
|
if !ok {
|
2023-04-06 08:55:01 +00:00
|
|
|
logrus.Tracef("Missing state event in createRespStateFromStateIDs: %s", stateEventIDs[i])
|
2022-01-27 14:29:14 +00:00
|
|
|
continue
|
|
|
|
}
|
2022-02-11 17:40:14 +00:00
|
|
|
respState.StateEvents = append(respState.StateEvents, ev)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
2023-04-06 08:55:01 +00:00
|
|
|
for i := range authEventIDs {
|
|
|
|
ev, ok := t.haveEvents[authEventIDs[i]]
|
2022-01-27 14:29:14 +00:00
|
|
|
if !ok {
|
2023-04-06 08:55:01 +00:00
|
|
|
logrus.Tracef("Missing auth event in createRespStateFromStateIDs: %s", authEventIDs[i])
|
2022-01-27 14:29:14 +00:00
|
|
|
continue
|
|
|
|
}
|
2022-02-11 17:40:14 +00:00
|
|
|
respState.AuthEvents = append(respState.AuthEvents, ev)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
// We purposefully do not do auth checks on the returned events, as they will still
|
|
|
|
// be processed in the exact same way, just as a 'rejected' event
|
|
|
|
// TODO: Add a field to HeaderedEvent to indicate if the event is rejected.
|
|
|
|
return &respState, nil
|
|
|
|
}
|
|
|
|
|
2023-05-02 14:03:16 +00:00
|
|
|
func (t *missingStateReq) lookupEvent(ctx context.Context, roomVersion gomatrixserverlib.RoomVersion, _, missingEventID string, localFirst bool) (gomatrixserverlib.PDU, error) {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "lookupEvent")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
2023-04-21 16:06:29 +00:00
|
|
|
verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
if localFirst {
|
|
|
|
// fetch from the roomserver
|
2023-03-01 16:06:47 +00:00
|
|
|
events, err := t.db.EventsFromIDs(ctx, t.roomInfo, []string{missingEventID})
|
2022-02-11 17:40:14 +00:00
|
|
|
if err != nil {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.Warnf("Failed to query roomserver for missing event %s: %s - falling back to remote", missingEventID, err)
|
2022-02-11 17:40:14 +00:00
|
|
|
} else if len(events) == 1 {
|
2023-05-02 14:03:16 +00:00
|
|
|
return events[0].PDU, nil
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
}
|
2023-05-03 09:21:27 +00:00
|
|
|
var event gomatrixserverlib.PDU
|
2022-01-27 14:29:14 +00:00
|
|
|
found := false
|
2022-01-31 14:36:59 +00:00
|
|
|
for _, serverName := range t.servers {
|
2022-01-27 14:29:14 +00:00
|
|
|
reqctx, cancel := context.WithTimeout(ctx, time.Second*30)
|
|
|
|
defer cancel()
|
2022-11-15 15:05:23 +00:00
|
|
|
txn, err := t.federation.GetEvent(reqctx, t.virtualHost, serverName, missingEventID)
|
2022-01-27 14:29:14 +00:00
|
|
|
if err != nil || len(txn.PDUs) == 0 {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithError(err).WithField("missing_event_id", missingEventID).Warn("Failed to get missing /event for event ID")
|
2022-01-27 14:29:14 +00:00
|
|
|
if errors.Is(err, context.DeadlineExceeded) {
|
|
|
|
select {
|
|
|
|
case <-reqctx.Done(): // this server took too long
|
|
|
|
continue
|
|
|
|
case <-ctx.Done(): // the input request timed out
|
|
|
|
return nil, context.DeadlineExceeded
|
|
|
|
}
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2023-04-21 16:06:29 +00:00
|
|
|
event, err = verImpl.NewEventFromUntrustedJSON(txn.PDUs[0])
|
2022-01-27 14:29:14 +00:00
|
|
|
if err != nil {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithError(err).WithField("missing_event_id", missingEventID).Warnf("Failed to parse event JSON of event returned from /event")
|
2022-01-27 14:29:14 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
found = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if !found {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithField("missing_event_id", missingEventID).Warnf("Failed to get missing /event for event ID from %d server(s)", len(t.servers))
|
2022-01-27 14:29:14 +00:00
|
|
|
return nil, fmt.Errorf("wasn't able to find event via %d server(s)", len(t.servers))
|
|
|
|
}
|
2023-04-27 15:35:19 +00:00
|
|
|
if err := gomatrixserverlib.VerifyEventSignatures(ctx, event, t.keys); err != nil {
|
2022-11-02 11:30:49 +00:00
|
|
|
t.log.WithError(err).Warnf("Couldn't validate signature of event %q from /event", event.EventID())
|
2022-01-27 14:29:14 +00:00
|
|
|
return nil, verifySigError{event.EventID(), err}
|
|
|
|
}
|
2022-02-11 17:40:14 +00:00
|
|
|
return t.cacheAndReturn(event), nil
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
|
2023-05-02 14:03:16 +00:00
|
|
|
func checkAllowedByState(e gomatrixserverlib.PDU, stateEvents []gomatrixserverlib.PDU) error {
|
2022-01-27 14:29:14 +00:00
|
|
|
authUsingState := gomatrixserverlib.NewAuthEvents(nil)
|
|
|
|
for i := range stateEvents {
|
|
|
|
err := authUsingState.AddEvent(stateEvents[i])
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return gomatrixserverlib.Allowed(e, &authUsingState)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *missingStateReq) hadEvent(eventID string) {
|
|
|
|
t.hadEventsMutex.Lock()
|
|
|
|
defer t.hadEventsMutex.Unlock()
|
|
|
|
t.hadEvents[eventID] = true
|
|
|
|
}
|
|
|
|
|
|
|
|
type verifySigError struct {
|
|
|
|
eventID string
|
|
|
|
err error
|
|
|
|
}
|
|
|
|
type missingPrevEventsError struct {
|
|
|
|
eventID string
|
|
|
|
err error
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e verifySigError) Error() string {
|
|
|
|
return fmt.Sprintf("unable to verify signature of event %q: %s", e.eventID, e.err)
|
|
|
|
}
|
|
|
|
func (e missingPrevEventsError) Error() string {
|
|
|
|
return fmt.Sprintf("unable to get prev_events for event %q: %s", e.eventID, e.err)
|
|
|
|
}
|