0
0
Fork 0
mirror of https://github.com/matrix-org/dendrite synced 2024-12-14 12:53:52 +01:00

- Removed double imports (#1989)

- Lower cased error messages

Signed-off-by: Ryan Whittington <twentybitdev@gmail.com>

Co-authored-by: kegsay <kegan@matrix.org>
This commit is contained in:
Ryan W 2021-09-08 17:31:03 +01:00 committed by GitHub
parent 7dc8fb1fe7
commit a624eab309
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
38 changed files with 162 additions and 177 deletions

View file

@ -40,7 +40,6 @@ import (
"golang.org/x/net/http2/h2c" "golang.org/x/net/http2/h2c"
pineconeMulticast "github.com/matrix-org/pinecone/multicast" pineconeMulticast "github.com/matrix-org/pinecone/multicast"
"github.com/matrix-org/pinecone/router"
pineconeRouter "github.com/matrix-org/pinecone/router" pineconeRouter "github.com/matrix-org/pinecone/router"
pineconeSessions "github.com/matrix-org/pinecone/sessions" pineconeSessions "github.com/matrix-org/pinecone/sessions"
"github.com/matrix-org/pinecone/types" "github.com/matrix-org/pinecone/types"
@ -196,7 +195,7 @@ func (m *DendriteMonolith) RegisterDevice(localpart, deviceID string) (string, e
func (m *DendriteMonolith) staticPeerConnect() { func (m *DendriteMonolith) staticPeerConnect() {
attempt := func() { attempt := func() {
if m.PineconeRouter.PeerCount(router.PeerTypeRemote) == 0 { if m.PineconeRouter.PeerCount(pineconeRouter.PeerTypeRemote) == 0 {
m.staticPeerMutex.RLock() m.staticPeerMutex.RLock()
uri := m.staticPeerURI uri := m.staticPeerURI
m.staticPeerMutex.RUnlock() m.staticPeerMutex.RUnlock()

View file

@ -32,7 +32,7 @@ func ParseTSParam(req *http.Request) (time.Time, error) {
// The parameter exists, parse into a Time object // The parameter exists, parse into a Time object
ts, err := strconv.ParseInt(tsStr, 10, 64) ts, err := strconv.ParseInt(tsStr, 10, 64)
if err != nil { if err != nil {
return time.Time{}, fmt.Errorf("Param 'ts' is no valid int (%s)", err.Error()) return time.Time{}, fmt.Errorf("param 'ts' is no valid int (%s)", err.Error())
} }
return time.Unix(ts/1000, 0), nil return time.Unix(ts/1000, 0), nil

View file

@ -23,7 +23,6 @@ import (
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -50,18 +49,18 @@ type devicesDeleteJSON struct {
// GetDeviceByID handles /devices/{deviceID} // GetDeviceByID handles /devices/{deviceID}
func GetDeviceByID( func GetDeviceByID(
req *http.Request, userAPI userapi.UserInternalAPI, device *api.Device, req *http.Request, userAPI api.UserInternalAPI, device *api.Device,
deviceID string, deviceID string,
) util.JSONResponse { ) util.JSONResponse {
var queryRes userapi.QueryDevicesResponse var queryRes api.QueryDevicesResponse
err := userAPI.QueryDevices(req.Context(), &userapi.QueryDevicesRequest{ err := userAPI.QueryDevices(req.Context(), &api.QueryDevicesRequest{
UserID: device.UserID, UserID: device.UserID,
}, &queryRes) }, &queryRes)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("QueryDevices failed") util.GetLogger(req.Context()).WithError(err).Error("QueryDevices failed")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()
} }
var targetDevice *userapi.Device var targetDevice *api.Device
for _, device := range queryRes.Devices { for _, device := range queryRes.Devices {
if device.ID == deviceID { if device.ID == deviceID {
targetDevice = &device targetDevice = &device
@ -88,10 +87,10 @@ func GetDeviceByID(
// GetDevicesByLocalpart handles /devices // GetDevicesByLocalpart handles /devices
func GetDevicesByLocalpart( func GetDevicesByLocalpart(
req *http.Request, userAPI userapi.UserInternalAPI, device *api.Device, req *http.Request, userAPI api.UserInternalAPI, device *api.Device,
) util.JSONResponse { ) util.JSONResponse {
var queryRes userapi.QueryDevicesResponse var queryRes api.QueryDevicesResponse
err := userAPI.QueryDevices(req.Context(), &userapi.QueryDevicesRequest{ err := userAPI.QueryDevices(req.Context(), &api.QueryDevicesRequest{
UserID: device.UserID, UserID: device.UserID,
}, &queryRes) }, &queryRes)
if err != nil { if err != nil {

View file

@ -23,7 +23,6 @@ import (
federationSenderAPI "github.com/matrix-org/dendrite/federationsender/api" federationSenderAPI "github.com/matrix-org/dendrite/federationsender/api"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/util" "github.com/matrix-org/util"
@ -115,7 +114,7 @@ func DirectoryRoom(
// SetLocalAlias implements PUT /directory/room/{roomAlias} // SetLocalAlias implements PUT /directory/room/{roomAlias}
func SetLocalAlias( func SetLocalAlias(
req *http.Request, req *http.Request,
device *api.Device, device *userapi.Device,
alias string, alias string,
cfg *config.ClientAPI, cfg *config.ClientAPI,
rsAPI roomserverAPI.RoomserverInternalAPI, rsAPI roomserverAPI.RoomserverInternalAPI,
@ -192,7 +191,7 @@ func SetLocalAlias(
// RemoveLocalAlias implements DELETE /directory/room/{roomAlias} // RemoveLocalAlias implements DELETE /directory/room/{roomAlias}
func RemoveLocalAlias( func RemoveLocalAlias(
req *http.Request, req *http.Request,
device *api.Device, device *userapi.Device,
alias string, alias string,
rsAPI roomserverAPI.RoomserverInternalAPI, rsAPI roomserverAPI.RoomserverInternalAPI,
) util.JSONResponse { ) util.JSONResponse {

View file

@ -19,16 +19,15 @@ import (
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
// Logout handles POST /logout // Logout handles POST /logout
func Logout( func Logout(
req *http.Request, userAPI userapi.UserInternalAPI, device *api.Device, req *http.Request, userAPI api.UserInternalAPI, device *api.Device,
) util.JSONResponse { ) util.JSONResponse {
var performRes userapi.PerformDeviceDeletionResponse var performRes api.PerformDeviceDeletionResponse
err := userAPI.PerformDeviceDeletion(req.Context(), &userapi.PerformDeviceDeletionRequest{ err := userAPI.PerformDeviceDeletion(req.Context(), &api.PerformDeviceDeletionRequest{
UserID: device.UserID, UserID: device.UserID,
DeviceIDs: []string{device.ID}, DeviceIDs: []string{device.ID},
}, &performRes) }, &performRes)
@ -45,10 +44,10 @@ func Logout(
// LogoutAll handles POST /logout/all // LogoutAll handles POST /logout/all
func LogoutAll( func LogoutAll(
req *http.Request, userAPI userapi.UserInternalAPI, device *api.Device, req *http.Request, userAPI api.UserInternalAPI, device *api.Device,
) util.JSONResponse { ) util.JSONResponse {
var performRes userapi.PerformDeviceDeletionResponse var performRes api.PerformDeviceDeletionResponse
err := userAPI.PerformDeviceDeletion(req.Context(), &userapi.PerformDeviceDeletionRequest{ err := userAPI.PerformDeviceDeletion(req.Context(), &api.PerformDeviceDeletionRequest{
UserID: device.UserID, UserID: device.UserID,
DeviceIDs: nil, DeviceIDs: nil,
}, &performRes) }, &performRes)

View file

@ -26,7 +26,6 @@ import (
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/threepid" "github.com/matrix-org/dendrite/clientapi/threepid"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/roomserver/api"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
@ -107,7 +106,7 @@ func sendMembership(ctx context.Context, accountDB accounts.Database, device *us
if err = roomserverAPI.SendEvents( if err = roomserverAPI.SendEvents(
ctx, rsAPI, ctx, rsAPI,
api.KindNew, roomserverAPI.KindNew,
[]*gomatrixserverlib.HeaderedEvent{event.Event.Headered(roomVer)}, []*gomatrixserverlib.HeaderedEvent{event.Event.Headered(roomVer)},
cfg.Matrix.ServerName, cfg.Matrix.ServerName,
nil, nil,
@ -328,11 +327,11 @@ func loadProfile(
return profile, err return profile, err
} }
func extractRequestData(req *http.Request, roomID string, rsAPI api.RoomserverInternalAPI) ( func extractRequestData(req *http.Request, roomID string, rsAPI roomserverAPI.RoomserverInternalAPI) (
body *threepid.MembershipRequest, evTime time.Time, roomVer gomatrixserverlib.RoomVersion, resErr *util.JSONResponse, body *threepid.MembershipRequest, evTime time.Time, roomVer gomatrixserverlib.RoomVersion, resErr *util.JSONResponse,
) { ) {
verReq := api.QueryRoomVersionForRoomRequest{RoomID: roomID} verReq := roomserverAPI.QueryRoomVersionForRoomRequest{RoomID: roomID}
verRes := api.QueryRoomVersionForRoomResponse{} verRes := roomserverAPI.QueryRoomVersionForRoomResponse{}
if err := rsAPI.QueryRoomVersionForRoom(req.Context(), &verReq, &verRes); err != nil { if err := rsAPI.QueryRoomVersionForRoom(req.Context(), &verReq, &verRes); err != nil {
resErr = &util.JSONResponse{ resErr = &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
@ -402,13 +401,13 @@ func checkAndProcessThreepid(
return return
} }
func checkMemberInRoom(ctx context.Context, rsAPI api.RoomserverInternalAPI, userID, roomID string) *util.JSONResponse { func checkMemberInRoom(ctx context.Context, rsAPI roomserverAPI.RoomserverInternalAPI, userID, roomID string) *util.JSONResponse {
tuple := gomatrixserverlib.StateKeyTuple{ tuple := gomatrixserverlib.StateKeyTuple{
EventType: gomatrixserverlib.MRoomMember, EventType: gomatrixserverlib.MRoomMember,
StateKey: userID, StateKey: userID,
} }
var membershipRes api.QueryCurrentStateResponse var membershipRes roomserverAPI.QueryCurrentStateResponse
err := rsAPI.QueryCurrentState(ctx, &api.QueryCurrentStateRequest{ err := rsAPI.QueryCurrentState(ctx, &roomserverAPI.QueryCurrentStateRequest{
RoomID: roomID, RoomID: roomID,
StateTuples: []gomatrixserverlib.StateKeyTuple{tuple}, StateTuples: []gomatrixserverlib.StateKeyTuple{tuple},
}, &membershipRes) }, &membershipRes)
@ -445,8 +444,8 @@ func SendForget(
) util.JSONResponse { ) util.JSONResponse {
ctx := req.Context() ctx := req.Context()
logger := util.GetLogger(ctx).WithField("roomID", roomID).WithField("userID", device.UserID) logger := util.GetLogger(ctx).WithField("roomID", roomID).WithField("userID", device.UserID)
var membershipRes api.QueryMembershipForUserResponse var membershipRes roomserverAPI.QueryMembershipForUserResponse
membershipReq := api.QueryMembershipForUserRequest{ membershipReq := roomserverAPI.QueryMembershipForUserRequest{
RoomID: roomID, RoomID: roomID,
UserID: device.UserID, UserID: device.UserID,
} }
@ -468,11 +467,11 @@ func SendForget(
} }
} }
request := api.PerformForgetRequest{ request := roomserverAPI.PerformForgetRequest{
RoomID: roomID, RoomID: roomID,
UserID: device.UserID, UserID: device.UserID,
} }
response := api.PerformForgetResponse{} response := roomserverAPI.PerformForgetResponse{}
if err := rsAPI.PerformForget(ctx, &request, &response); err != nil { if err := rsAPI.PerformForget(ctx, &request, &response); err != nil {
logger.WithError(err).Error("PerformForget: unable to forget room") logger.WithError(err).Error("PerformForget: unable to forget room")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()

View file

@ -9,7 +9,6 @@ import (
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/dendrite/userapi/storage/accounts" "github.com/matrix-org/dendrite/userapi/storage/accounts"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/util" "github.com/matrix-org/util"
@ -29,7 +28,7 @@ type newPasswordAuth struct {
func Password( func Password(
req *http.Request, req *http.Request,
userAPI userapi.UserInternalAPI, userAPI api.UserInternalAPI,
accountDB accounts.Database, accountDB accounts.Database,
device *api.Device, device *api.Device,
cfg *config.ClientAPI, cfg *config.ClientAPI,
@ -90,11 +89,11 @@ func Password(
} }
// Ask the user API to perform the password change. // Ask the user API to perform the password change.
passwordReq := &userapi.PerformPasswordUpdateRequest{ passwordReq := &api.PerformPasswordUpdateRequest{
Localpart: localpart, Localpart: localpart,
Password: r.NewPassword, Password: r.NewPassword,
} }
passwordRes := &userapi.PerformPasswordUpdateResponse{} passwordRes := &api.PerformPasswordUpdateResponse{}
if err := userAPI.PerformPasswordUpdate(req.Context(), passwordReq, passwordRes); err != nil { if err := userAPI.PerformPasswordUpdate(req.Context(), passwordReq, passwordRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("PerformPasswordUpdate failed") util.GetLogger(req.Context()).WithError(err).Error("PerformPasswordUpdate failed")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()
@ -107,12 +106,12 @@ func Password(
// If the request asks us to log out all other devices then // If the request asks us to log out all other devices then
// ask the user API to do that. // ask the user API to do that.
if r.LogoutDevices { if r.LogoutDevices {
logoutReq := &userapi.PerformDeviceDeletionRequest{ logoutReq := &api.PerformDeviceDeletionRequest{
UserID: device.UserID, UserID: device.UserID,
DeviceIDs: nil, DeviceIDs: nil,
ExceptDeviceID: device.ID, ExceptDeviceID: device.ID,
} }
logoutRes := &userapi.PerformDeviceDeletionResponse{} logoutRes := &api.PerformDeviceDeletionResponse{}
if err := userAPI.PerformDeviceDeletion(req.Context(), logoutReq, logoutRes); err != nil { if err := userAPI.PerformDeviceDeletion(req.Context(), logoutReq, logoutRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceDeletion failed") util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceDeletion failed")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()

View file

@ -22,7 +22,6 @@ import (
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/roomserver/api"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
@ -113,7 +112,7 @@ func SendRedaction(
return jsonerror.InternalServerError() return jsonerror.InternalServerError()
} }
var queryRes api.QueryLatestEventsAndStateResponse var queryRes roomserverAPI.QueryLatestEventsAndStateResponse
e, err := eventutil.QueryAndBuildEvent(req.Context(), &builder, cfg.Matrix, time.Now(), rsAPI, &queryRes) e, err := eventutil.QueryAndBuildEvent(req.Context(), &builder, cfg.Matrix, time.Now(), rsAPI, &queryRes)
if err == eventutil.ErrRoomNoExists { if err == eventutil.ErrRoomNoExists {
return util.JSONResponse{ return util.JSONResponse{
@ -121,7 +120,7 @@ func SendRedaction(
JSON: jsonerror.NotFound("Room does not exist"), JSON: jsonerror.NotFound("Room does not exist"),
} }
} }
if err = roomserverAPI.SendEvents(context.Background(), rsAPI, api.KindNew, []*gomatrixserverlib.HeaderedEvent{e}, cfg.Matrix.ServerName, nil); err != nil { if err = roomserverAPI.SendEvents(context.Background(), rsAPI, roomserverAPI.KindNew, []*gomatrixserverlib.HeaderedEvent{e}, cfg.Matrix.ServerName, nil); err != nil {
util.GetLogger(req.Context()).WithError(err).Errorf("failed to SendEvents") util.GetLogger(req.Context()).WithError(err).Errorf("failed to SendEvents")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()
} }

View file

@ -68,18 +68,18 @@ func (r *SharedSecretRegistration) IsValidMacLogin(
) (bool, error) { ) (bool, error) {
// Check that shared secret registration isn't disabled. // Check that shared secret registration isn't disabled.
if r.sharedSecret == "" { if r.sharedSecret == "" {
return false, errors.New("Shared secret registration is disabled") return false, errors.New("shared secret registration is disabled")
} }
if !r.validNonce(nonce) { if !r.validNonce(nonce) {
return false, fmt.Errorf("Incorrect or expired nonce: %s", nonce) return false, fmt.Errorf("incorrect or expired nonce: %s", nonce)
} }
// Check that username/password don't contain the HMAC delimiters. // Check that username/password don't contain the HMAC delimiters.
if strings.Contains(username, "\x00") { if strings.Contains(username, "\x00") {
return false, errors.New("Username contains invalid character") return false, errors.New("username contains invalid character")
} }
if strings.Contains(password, "\x00") { if strings.Contains(password, "\x00") {
return false, errors.New("Password contains invalid character") return false, errors.New("password contains invalid character")
} }
adminString := "notadmin" adminString := "notadmin"

View file

@ -81,7 +81,7 @@ func CreateSession(
// Error if the status isn't OK // Error if the status isn't OK
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("Could not create a session on the server %s", req.IDServer) return "", fmt.Errorf("could not create a session on the server %s", req.IDServer)
} }
// Extract the SID from the response and return it // Extract the SID from the response and return it
@ -168,7 +168,7 @@ func PublishAssociation(creds Credentials, userID string, cfg *config.ClientAPI)
// Error if the status isn't OK // Error if the status isn't OK
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Could not publish the association on the server %s", creds.IDServer) return fmt.Errorf("could not publish the association on the server %s", creds.IDServer)
} }
return nil return nil

View file

@ -31,11 +31,11 @@ func ParseUsernameParam(usernameParam string, expectedServerName *gomatrixserver
lp, domain, err := gomatrixserverlib.SplitID('@', usernameParam) lp, domain, err := gomatrixserverlib.SplitID('@', usernameParam)
if err != nil { if err != nil {
return "", errors.New("Invalid username") return "", errors.New("invalid username")
} }
if expectedServerName != nil && domain != *expectedServerName { if expectedServerName != nil && domain != *expectedServerName {
return "", errors.New("User ID does not belong to this server") return "", errors.New("user ID does not belong to this server")
} }
localpart = lp localpart = lp

View file

@ -49,7 +49,6 @@ import (
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
pineconeMulticast "github.com/matrix-org/pinecone/multicast" pineconeMulticast "github.com/matrix-org/pinecone/multicast"
"github.com/matrix-org/pinecone/router"
pineconeRouter "github.com/matrix-org/pinecone/router" pineconeRouter "github.com/matrix-org/pinecone/router"
pineconeSessions "github.com/matrix-org/pinecone/sessions" pineconeSessions "github.com/matrix-org/pinecone/sessions"
@ -125,7 +124,7 @@ func main() {
connectToStaticPeer := func() { connectToStaticPeer := func() {
attempt := func() { attempt := func() {
if pRouter.PeerCount(router.PeerTypeRemote) == 0 { if pRouter.PeerCount(pineconeRouter.PeerTypeRemote) == 0 {
uri := *instancePeer uri := *instancePeer
if uri == "" { if uri == "" {
return return

View file

@ -148,7 +148,7 @@ func buildDendrite(httpClient *http.Client, dockerClient *client.Client, tmpDir,
// add top level Dockerfile // add top level Dockerfile
err = ioutil.WriteFile(path.Join(*flagHead, "Dockerfile"), []byte(Dockerfile), os.ModePerm) err = ioutil.WriteFile(path.Join(*flagHead, "Dockerfile"), []byte(Dockerfile), os.ModePerm)
if err != nil { if err != nil {
return "", fmt.Errorf("Custom HEAD: failed to inject /Dockerfile: %w", err) return "", fmt.Errorf("custom HEAD: failed to inject /Dockerfile: %w", err)
} }
// now tarball it // now tarball it
var buffer bytes.Buffer var buffer bytes.Buffer

View file

@ -711,7 +711,7 @@ withNextEvent:
} }
if missing := len(missingAuthEvents); missing > 0 { if missing := len(missingAuthEvents); missing > 0 {
return fmt.Errorf("Event refers to %d auth_events which we failed to fetch", missing) return fmt.Errorf("event refers to %d auth_events which we failed to fetch", missing)
} }
return nil return nil
} }

View file

@ -30,7 +30,6 @@ import (
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
) )
// KeyChangeConsumer consumes events that originate in key server. // KeyChangeConsumer consumes events that originate in key server.
@ -82,7 +81,7 @@ func (t *KeyChangeConsumer) Start() error {
func (t *KeyChangeConsumer) onMessage(msg *sarama.ConsumerMessage) error { func (t *KeyChangeConsumer) onMessage(msg *sarama.ConsumerMessage) error {
var m api.DeviceMessage var m api.DeviceMessage
if err := json.Unmarshal(msg.Value, &m); err != nil { if err := json.Unmarshal(msg.Value, &m); err != nil {
log.WithError(err).Errorf("failed to read device message from key change topic") logrus.WithError(err).Errorf("failed to read device message from key change topic")
return nil return nil
} }
switch m.Type { switch m.Type {
@ -96,7 +95,7 @@ func (t *KeyChangeConsumer) onMessage(msg *sarama.ConsumerMessage) error {
} }
func (t *KeyChangeConsumer) onDeviceKeyMessage(m api.DeviceMessage) error { func (t *KeyChangeConsumer) onDeviceKeyMessage(m api.DeviceMessage) error {
logger := log.WithField("user_id", m.UserID) logger := logrus.WithField("user_id", m.UserID)
// only send key change events which originated from us // only send key change events which originated from us
_, originServerName, err := gomatrixserverlib.SplitID('@', m.UserID) _, originServerName, err := gomatrixserverlib.SplitID('@', m.UserID)
@ -142,7 +141,7 @@ func (t *KeyChangeConsumer) onDeviceKeyMessage(m api.DeviceMessage) error {
return err return err
} }
log.Infof("Sending device list update message to %q", destinations) logrus.Infof("Sending device list update message to %q", destinations)
return t.queues.SendEDU(edu, t.serverName, destinations) return t.queues.SendEDU(edu, t.serverName, destinations)
} }
@ -158,7 +157,7 @@ func (t *KeyChangeConsumer) onCrossSigningMessage(m api.DeviceMessage) error {
// end up parroting information we received from other servers. // end up parroting information we received from other servers.
return nil return nil
} }
logger := log.WithField("user_id", output.UserID) logger := logrus.WithField("user_id", output.UserID)
var queryRes roomserverAPI.QueryRoomsForUserResponse var queryRes roomserverAPI.QueryRoomsForUserResponse
err = t.rsAPI.QueryRoomsForUser(context.Background(), &roomserverAPI.QueryRoomsForUserRequest{ err = t.rsAPI.QueryRoomsForUser(context.Background(), &roomserverAPI.QueryRoomsForUserRequest{

View file

@ -409,7 +409,7 @@ func (r *FederationSenderInternalAPI) performOutboundPeekUsingServer(
return fmt.Errorf("sanityCheckAuthChain: %w", err) return fmt.Errorf("sanityCheckAuthChain: %w", err)
} }
if err = respState.Check(ctx, r.keyRing, federatedAuthProvider(ctx, r.federation, r.keyRing, serverName)); err != nil { if err = respState.Check(ctx, r.keyRing, federatedAuthProvider(ctx, r.federation, r.keyRing, serverName)); err != nil {
return fmt.Errorf("Error checking state returned from peeking: %w", err) return fmt.Errorf("error checking state returned from peeking: %w", err)
} }
// If we've got this far, the remote server is peeking. // If we've got this far, the remote server is peeking.
@ -523,7 +523,7 @@ func (r *FederationSenderInternalAPI) PerformLeave(
// If we reach here then we didn't complete a leave for some reason. // If we reach here then we didn't complete a leave for some reason.
return fmt.Errorf( return fmt.Errorf(
"Failed to leave room %q through %d server(s)", "failed to leave room %q through %d server(s)",
request.RoomID, len(request.ServerNames), request.RoomID, len(request.ServerNames),
) )
} }

View file

@ -29,7 +29,6 @@ import (
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
"go.uber.org/atomic" "go.uber.org/atomic"
) )
@ -72,7 +71,7 @@ type destinationQueue struct {
// start sending events to that destination. // start sending events to that destination.
func (oq *destinationQueue) sendEvent(event *gomatrixserverlib.HeaderedEvent, receipt *shared.Receipt) { func (oq *destinationQueue) sendEvent(event *gomatrixserverlib.HeaderedEvent, receipt *shared.Receipt) {
if event == nil { if event == nil {
log.Errorf("attempt to send nil PDU with destination %q", oq.destination) logrus.Errorf("attempt to send nil PDU with destination %q", oq.destination)
return return
} }
// Create a database entry that associates the given PDU NID with // Create a database entry that associates the given PDU NID with
@ -84,7 +83,7 @@ func (oq *destinationQueue) sendEvent(event *gomatrixserverlib.HeaderedEvent, re
oq.destination, // the destination server name oq.destination, // the destination server name
receipt, // NIDs from federationsender_queue_json table receipt, // NIDs from federationsender_queue_json table
); err != nil { ); err != nil {
log.WithError(err).Errorf("failed to associate PDU %q with destination %q", event.EventID(), oq.destination) logrus.WithError(err).Errorf("failed to associate PDU %q with destination %q", event.EventID(), oq.destination)
return return
} }
// Check if the destination is blacklisted. If it isn't then wake // Check if the destination is blacklisted. If it isn't then wake
@ -116,7 +115,7 @@ func (oq *destinationQueue) sendEvent(event *gomatrixserverlib.HeaderedEvent, re
// start sending events to that destination. // start sending events to that destination.
func (oq *destinationQueue) sendEDU(event *gomatrixserverlib.EDU, receipt *shared.Receipt) { func (oq *destinationQueue) sendEDU(event *gomatrixserverlib.EDU, receipt *shared.Receipt) {
if event == nil { if event == nil {
log.Errorf("attempt to send nil EDU with destination %q", oq.destination) logrus.Errorf("attempt to send nil EDU with destination %q", oq.destination)
return return
} }
// Create a database entry that associates the given PDU NID with // Create a database entry that associates the given PDU NID with
@ -127,7 +126,7 @@ func (oq *destinationQueue) sendEDU(event *gomatrixserverlib.EDU, receipt *share
oq.destination, // the destination server name oq.destination, // the destination server name
receipt, // NIDs from federationsender_queue_json table receipt, // NIDs from federationsender_queue_json table
); err != nil { ); err != nil {
log.WithError(err).Errorf("failed to associate EDU with destination %q", oq.destination) logrus.WithError(err).Errorf("failed to associate EDU with destination %q", oq.destination)
return return
} }
// Check if the destination is blacklisted. If it isn't then wake // Check if the destination is blacklisted. If it isn't then wake
@ -281,7 +280,7 @@ func (oq *destinationQueue) backgroundSend() {
// It's been suggested that we should give up because the backoff // It's been suggested that we should give up because the backoff
// has exceeded a maximum allowable value. Clean up the in-memory // has exceeded a maximum allowable value. Clean up the in-memory
// buffers at this point. The PDU clean-up is already on a defer. // buffers at this point. The PDU clean-up is already on a defer.
log.Warnf("Blacklisting %q due to exceeding backoff threshold", oq.destination) logrus.Warnf("Blacklisting %q due to exceeding backoff threshold", oq.destination)
oq.pendingMutex.Lock() oq.pendingMutex.Lock()
for i := range oq.pendingPDUs { for i := range oq.pendingPDUs {
oq.pendingPDUs[i] = nil oq.pendingPDUs[i] = nil
@ -298,7 +297,7 @@ func (oq *destinationQueue) backgroundSend() {
// We haven't backed off yet, so wait for the suggested amount of // We haven't backed off yet, so wait for the suggested amount of
// time. // time.
duration := time.Until(*until) duration := time.Until(*until)
log.Warnf("Backing off %q for %s", oq.destination, duration) logrus.Warnf("Backing off %q for %s", oq.destination, duration)
oq.backingOff.Store(true) oq.backingOff.Store(true)
destinationQueueBackingOff.Inc() destinationQueueBackingOff.Inc()
select { select {
@ -421,13 +420,13 @@ func (oq *destinationQueue) nextTransaction(
if pduReceipts != nil { if pduReceipts != nil {
//logrus.Infof("Cleaning PDUs %q", pduReceipt.String()) //logrus.Infof("Cleaning PDUs %q", pduReceipt.String())
if err = oq.db.CleanPDUs(context.Background(), oq.destination, pduReceipts); err != nil { if err = oq.db.CleanPDUs(context.Background(), oq.destination, pduReceipts); err != nil {
log.WithError(err).Errorf("Failed to clean PDUs for server %q", t.Destination) logrus.WithError(err).Errorf("Failed to clean PDUs for server %q", t.Destination)
} }
} }
if eduReceipts != nil { if eduReceipts != nil {
//logrus.Infof("Cleaning EDUs %q", eduReceipt.String()) //logrus.Infof("Cleaning EDUs %q", eduReceipt.String())
if err = oq.db.CleanEDUs(context.Background(), oq.destination, eduReceipts); err != nil { if err = oq.db.CleanEDUs(context.Background(), oq.destination, eduReceipts); err != nil {
log.WithError(err).Errorf("Failed to clean EDUs for server %q", t.Destination) logrus.WithError(err).Errorf("Failed to clean EDUs for server %q", t.Destination)
} }
} }
// Reset the transaction ID. // Reset the transaction ID.
@ -440,9 +439,9 @@ func (oq *destinationQueue) nextTransaction(
// will retry again, subject to backoff. // will retry again, subject to backoff.
return false, 0, 0, err return false, 0, 0, err
default: default:
log.WithFields(log.Fields{ logrus.WithFields(logrus.Fields{
"destination": oq.destination, "destination": oq.destination,
log.ErrorKey: err, logrus.ErrorKey: err,
}).Debugf("Failed to send transaction %q", t.TransactionID) }).Debugf("Failed to send transaction %q", t.TransactionID)
return false, 0, 0, err return false, 0, 0, err
} }

View file

@ -28,7 +28,7 @@ import (
// ErrRoomNoExists is returned when trying to lookup the state of a room that // ErrRoomNoExists is returned when trying to lookup the state of a room that
// doesn't exist // doesn't exist
var ErrRoomNoExists = errors.New("Room does not exist") var ErrRoomNoExists = errors.New("room does not exist")
// QueryAndBuildEvent builds a Matrix event using the event builder and roomserver query // QueryAndBuildEvent builds a Matrix event using the event builder and roomserver query
// API client provided. If also fills roomserver query API response (if provided) // API client provided. If also fills roomserver query API response (if provided)

View file

@ -73,9 +73,9 @@ func PostJSON(
Message string `json:"message"` Message string `json:"message"`
} }
if msgerr := json.NewDecoder(res.Body).Decode(&errorBody); msgerr == nil { if msgerr := json.NewDecoder(res.Body).Decode(&errorBody); msgerr == nil {
return fmt.Errorf("Internal API: %d from %s: %s", res.StatusCode, apiURL, errorBody.Message) return fmt.Errorf("internal API: %d from %s: %s", res.StatusCode, apiURL, errorBody.Message)
} }
return fmt.Errorf("Internal API: %d from %s", res.StatusCode, apiURL) return fmt.Errorf("internal API: %d from %s", res.StatusCode, apiURL)
} }
return json.NewDecoder(res.Body).Decode(response) return json.NewDecoder(res.Body).Decode(response)
} }

View file

@ -46,7 +46,7 @@ func (m *Migrations) RunDeltas(db *sql.DB, props *config.DatabaseOptions) error
minVer := int64(0) minVer := int64(0)
migrations, err := m.collect(minVer, maxVer) migrations, err := m.collect(minVer, maxVer)
if err != nil { if err != nil {
return fmt.Errorf("RunDeltas: Failed to collect migrations: %w", err) return fmt.Errorf("runDeltas: Failed to collect migrations: %w", err)
} }
if props.ConnectionString.IsPostgres() { if props.ConnectionString.IsPostgres() {
if err = goose.SetDialect("postgres"); err != nil { if err = goose.SetDialect("postgres"); err != nil {
@ -57,12 +57,12 @@ func (m *Migrations) RunDeltas(db *sql.DB, props *config.DatabaseOptions) error
return err return err
} }
} else { } else {
return fmt.Errorf("Unknown connection string: %s", props.ConnectionString) return fmt.Errorf("unknown connection string: %s", props.ConnectionString)
} }
for { for {
current, err := goose.EnsureDBVersion(db) current, err := goose.EnsureDBVersion(db)
if err != nil { if err != nil {
return fmt.Errorf("RunDeltas: Failed to EnsureDBVersion: %w", err) return fmt.Errorf("runDeltas: Failed to EnsureDBVersion: %w", err)
} }
next, err := migrations.Next(current) next, err := migrations.Next(current)
@ -71,11 +71,11 @@ func (m *Migrations) RunDeltas(db *sql.DB, props *config.DatabaseOptions) error
return nil return nil
} }
return fmt.Errorf("RunDeltas: Failed to load next migration to %+v : %w", next, err) return fmt.Errorf("runDeltas: Failed to load next migration to %+v : %w", next, err)
} }
if err = next.Up(db); err != nil { if err = next.Up(db); err != nil {
return fmt.Errorf("RunDeltas: Failed run migration: %w", err) return fmt.Errorf("runDeltas: Failed run migration: %w", err)
} }
} }
} }

View file

@ -25,7 +25,7 @@ import (
) )
// ErrUserExists is returned if a username already exists in the database. // ErrUserExists is returned if a username already exists in the database.
var ErrUserExists = errors.New("Username already exists") var ErrUserExists = errors.New("username already exists")
// A Transaction is something that can be committed or rolledback. // A Transaction is something that can be committed or rolledback.
type Transaction interface { type Transaction interface {

View file

@ -37,10 +37,10 @@ import (
// For example, if Base64Hash is 'qwerty', the path will be 'q/w/erty/file'. // For example, if Base64Hash is 'qwerty', the path will be 'q/w/erty/file'.
func GetPathFromBase64Hash(base64Hash types.Base64Hash, absBasePath config.Path) (string, error) { func GetPathFromBase64Hash(base64Hash types.Base64Hash, absBasePath config.Path) (string, error) {
if len(base64Hash) < 3 { if len(base64Hash) < 3 {
return "", fmt.Errorf("Invalid filePath (Base64Hash too short - min 3 characters): %q", base64Hash) return "", fmt.Errorf("invalid filePath (Base64Hash too short - min 3 characters): %q", base64Hash)
} }
if len(base64Hash) > 255 { if len(base64Hash) > 255 {
return "", fmt.Errorf("Invalid filePath (Base64Hash too long - max 255 characters): %q", base64Hash) return "", fmt.Errorf("invalid filePath (Base64Hash too long - max 255 characters): %q", base64Hash)
} }
filePath, err := filepath.Abs(filepath.Join( filePath, err := filepath.Abs(filepath.Join(
@ -51,14 +51,14 @@ func GetPathFromBase64Hash(base64Hash types.Base64Hash, absBasePath config.Path)
"file", "file",
)) ))
if err != nil { if err != nil {
return "", fmt.Errorf("Unable to construct filePath: %w", err) return "", fmt.Errorf("unable to construct filePath: %w", err)
} }
// check if the absolute absBasePath is a prefix of the absolute filePath // check if the absolute absBasePath is a prefix of the absolute filePath
// if so, no directory escape has occurred and the filePath is valid // if so, no directory escape has occurred and the filePath is valid
// Note: absBasePath is already absolute // Note: absBasePath is already absolute
if !strings.HasPrefix(filePath, string(absBasePath)) { if !strings.HasPrefix(filePath, string(absBasePath)) {
return "", fmt.Errorf("Invalid filePath (not within absBasePath %v): %v", absBasePath, filePath) return "", fmt.Errorf("invalid filePath (not within absBasePath %v): %v", absBasePath, filePath)
} }
return filePath, nil return filePath, nil
@ -102,7 +102,7 @@ func MoveFileWithHashCheck(tmpDir types.Path, mediaMetadata *types.MediaMetadata
func RemoveDir(dir types.Path, logger *log.Entry) { func RemoveDir(dir types.Path, logger *log.Entry) {
dirErr := os.RemoveAll(string(dir)) dirErr := os.RemoveAll(string(dir))
if dirErr != nil { if dirErr != nil {
logger.WithError(dirErr).WithField("dir", dir).Warn("Failed to remove directory") logger.WithError(dirErr).WithField("dir", dir).Warn("failed to remove directory")
} }
} }
@ -153,11 +153,11 @@ func moveFile(src types.Path, dst types.Path) error {
err := os.MkdirAll(dstDir, 0770) err := os.MkdirAll(dstDir, 0770)
if err != nil { if err != nil {
return fmt.Errorf("Failed to make directory: %w", err) return fmt.Errorf("failed to make directory: %w", err)
} }
err = os.Rename(string(src), string(dst)) err = os.Rename(string(src), string(dst))
if err != nil { if err != nil {
return fmt.Errorf("Failed to move directory: %w", err) return fmt.Errorf("failed to move directory: %w", err)
} }
return nil return nil
} }
@ -165,11 +165,11 @@ func moveFile(src types.Path, dst types.Path) error {
func createTempFileWriter(absBasePath config.Path) (*bufio.Writer, *os.File, types.Path, error) { func createTempFileWriter(absBasePath config.Path) (*bufio.Writer, *os.File, types.Path, error) {
tmpDir, err := createTempDir(absBasePath) tmpDir, err := createTempDir(absBasePath)
if err != nil { if err != nil {
return nil, nil, "", fmt.Errorf("Failed to create temp dir: %w", err) return nil, nil, "", fmt.Errorf("failed to create temp dir: %w", err)
} }
writer, tmpFile, err := createFileWriter(tmpDir) writer, tmpFile, err := createFileWriter(tmpDir)
if err != nil { if err != nil {
return nil, nil, "", fmt.Errorf("Failed to create file writer: %w", err) return nil, nil, "", fmt.Errorf("failed to create file writer: %w", err)
} }
return writer, tmpFile, tmpDir, nil return writer, tmpFile, tmpDir, nil
} }
@ -178,11 +178,11 @@ func createTempFileWriter(absBasePath config.Path) (*bufio.Writer, *os.File, typ
func createTempDir(baseDirectory config.Path) (types.Path, error) { func createTempDir(baseDirectory config.Path) (types.Path, error) {
baseTmpDir := filepath.Join(string(baseDirectory), "tmp") baseTmpDir := filepath.Join(string(baseDirectory), "tmp")
if err := os.MkdirAll(baseTmpDir, 0770); err != nil { if err := os.MkdirAll(baseTmpDir, 0770); err != nil {
return "", fmt.Errorf("Failed to create base temp dir: %w", err) return "", fmt.Errorf("failed to create base temp dir: %w", err)
} }
tmpDir, err := ioutil.TempDir(baseTmpDir, "") tmpDir, err := ioutil.TempDir(baseTmpDir, "")
if err != nil { if err != nil {
return "", fmt.Errorf("Failed to create temp dir: %w", err) return "", fmt.Errorf("failed to create temp dir: %w", err)
} }
return types.Path(tmpDir), nil return types.Path(tmpDir), nil
} }
@ -194,7 +194,7 @@ func createFileWriter(directory types.Path) (*bufio.Writer, *os.File, error) {
filePath := filepath.Join(string(directory), "content") filePath := filepath.Join(string(directory), "content")
file, err := os.Create(filePath) file, err := os.Create(filePath)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("Failed to create file: %w", err) return nil, nil, fmt.Errorf("failed to create file: %w", err)
} }
return bufio.NewWriter(file), file, nil return bufio.NewWriter(file), file, nil

View file

@ -51,7 +51,7 @@ func (r *Inviter) PerformInvite(
targetUserID := *event.StateKey() targetUserID := *event.StateKey()
info, err := r.DB.RoomInfo(ctx, roomID) info, err := r.DB.RoomInfo(ctx, roomID)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to load RoomInfo: %w", err) return nil, fmt.Errorf("failed to load RoomInfo: %w", err)
} }
log.WithFields(log.Fields{ log.WithFields(log.Fields{

View file

@ -24,7 +24,6 @@ import (
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
fsAPI "github.com/matrix-org/dendrite/federationsender/api" fsAPI "github.com/matrix-org/dendrite/federationsender/api"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/roomserver/api"
rsAPI "github.com/matrix-org/dendrite/roomserver/api" rsAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/internal/helpers" "github.com/matrix-org/dendrite/roomserver/internal/helpers"
"github.com/matrix-org/dendrite/roomserver/internal/input" "github.com/matrix-org/dendrite/roomserver/internal/input"
@ -49,17 +48,17 @@ type Joiner struct {
// PerformJoin handles joining matrix rooms, including over federation by talking to the federationsender. // PerformJoin handles joining matrix rooms, including over federation by talking to the federationsender.
func (r *Joiner) PerformJoin( func (r *Joiner) PerformJoin(
ctx context.Context, ctx context.Context,
req *api.PerformJoinRequest, req *rsAPI.PerformJoinRequest,
res *api.PerformJoinResponse, res *rsAPI.PerformJoinResponse,
) { ) {
roomID, joinedVia, err := r.performJoin(ctx, req) roomID, joinedVia, err := r.performJoin(ctx, req)
if err != nil { if err != nil {
sentry.CaptureException(err) sentry.CaptureException(err)
perr, ok := err.(*api.PerformError) perr, ok := err.(*rsAPI.PerformError)
if ok { if ok {
res.Error = perr res.Error = perr
} else { } else {
res.Error = &api.PerformError{ res.Error = &rsAPI.PerformError{
Msg: err.Error(), Msg: err.Error(),
} }
} }
@ -70,18 +69,18 @@ func (r *Joiner) PerformJoin(
func (r *Joiner) performJoin( func (r *Joiner) performJoin(
ctx context.Context, ctx context.Context,
req *api.PerformJoinRequest, req *rsAPI.PerformJoinRequest,
) (string, gomatrixserverlib.ServerName, error) { ) (string, gomatrixserverlib.ServerName, error) {
_, domain, err := gomatrixserverlib.SplitID('@', req.UserID) _, domain, err := gomatrixserverlib.SplitID('@', req.UserID)
if err != nil { if err != nil {
return "", "", &api.PerformError{ return "", "", &rsAPI.PerformError{
Code: api.PerformErrorBadRequest, Code: rsAPI.PerformErrorBadRequest,
Msg: fmt.Sprintf("Supplied user ID %q in incorrect format", req.UserID), Msg: fmt.Sprintf("Supplied user ID %q in incorrect format", req.UserID),
} }
} }
if domain != r.Cfg.Matrix.ServerName { if domain != r.Cfg.Matrix.ServerName {
return "", "", &api.PerformError{ return "", "", &rsAPI.PerformError{
Code: api.PerformErrorBadRequest, Code: rsAPI.PerformErrorBadRequest,
Msg: fmt.Sprintf("User %q does not belong to this homeserver", req.UserID), Msg: fmt.Sprintf("User %q does not belong to this homeserver", req.UserID),
} }
} }
@ -91,20 +90,20 @@ func (r *Joiner) performJoin(
if strings.HasPrefix(req.RoomIDOrAlias, "#") { if strings.HasPrefix(req.RoomIDOrAlias, "#") {
return r.performJoinRoomByAlias(ctx, req) return r.performJoinRoomByAlias(ctx, req)
} }
return "", "", &api.PerformError{ return "", "", &rsAPI.PerformError{
Code: api.PerformErrorBadRequest, Code: rsAPI.PerformErrorBadRequest,
Msg: fmt.Sprintf("Room ID or alias %q is invalid", req.RoomIDOrAlias), Msg: fmt.Sprintf("Room ID or alias %q is invalid", req.RoomIDOrAlias),
} }
} }
func (r *Joiner) performJoinRoomByAlias( func (r *Joiner) performJoinRoomByAlias(
ctx context.Context, ctx context.Context,
req *api.PerformJoinRequest, req *rsAPI.PerformJoinRequest,
) (string, gomatrixserverlib.ServerName, error) { ) (string, gomatrixserverlib.ServerName, error) {
// Get the domain part of the room alias. // Get the domain part of the room alias.
_, domain, err := gomatrixserverlib.SplitID('#', req.RoomIDOrAlias) _, domain, err := gomatrixserverlib.SplitID('#', req.RoomIDOrAlias)
if err != nil { if err != nil {
return "", "", fmt.Errorf("Alias %q is not in the correct format", req.RoomIDOrAlias) return "", "", fmt.Errorf("alias %q is not in the correct format", req.RoomIDOrAlias)
} }
req.ServerNames = append(req.ServerNames, domain) req.ServerNames = append(req.ServerNames, domain)
@ -122,7 +121,7 @@ func (r *Joiner) performJoinRoomByAlias(
err = r.FSAPI.PerformDirectoryLookup(ctx, &dirReq, &dirRes) err = r.FSAPI.PerformDirectoryLookup(ctx, &dirReq, &dirRes)
if err != nil { if err != nil {
logrus.WithError(err).Errorf("error looking up alias %q", req.RoomIDOrAlias) logrus.WithError(err).Errorf("error looking up alias %q", req.RoomIDOrAlias)
return "", "", fmt.Errorf("Looking up alias %q over federation failed: %w", req.RoomIDOrAlias, err) return "", "", fmt.Errorf("looking up alias %q over federation failed: %w", req.RoomIDOrAlias, err)
} }
roomID = dirRes.RoomID roomID = dirRes.RoomID
req.ServerNames = append(req.ServerNames, dirRes.ServerNames...) req.ServerNames = append(req.ServerNames, dirRes.ServerNames...)
@ -135,14 +134,14 @@ func (r *Joiner) performJoinRoomByAlias(
// Otherwise, look up if we know this room alias locally. // Otherwise, look up if we know this room alias locally.
err = r.RSAPI.GetRoomIDForAlias(ctx, &getRoomReq, &getRoomRes) err = r.RSAPI.GetRoomIDForAlias(ctx, &getRoomReq, &getRoomRes)
if err != nil { if err != nil {
return "", "", fmt.Errorf("Lookup room alias %q failed: %w", req.RoomIDOrAlias, err) return "", "", fmt.Errorf("lookup room alias %q failed: %w", req.RoomIDOrAlias, err)
} }
roomID = getRoomRes.RoomID roomID = getRoomRes.RoomID
} }
// If the room ID is empty then we failed to look up the alias. // If the room ID is empty then we failed to look up the alias.
if roomID == "" { if roomID == "" {
return "", "", fmt.Errorf("Alias %q not found", req.RoomIDOrAlias) return "", "", fmt.Errorf("alias %q not found", req.RoomIDOrAlias)
} }
// If we do, then pluck out the room ID and continue the join. // If we do, then pluck out the room ID and continue the join.
@ -153,7 +152,7 @@ func (r *Joiner) performJoinRoomByAlias(
// TODO: Break this function up a bit // TODO: Break this function up a bit
func (r *Joiner) performJoinRoomByID( func (r *Joiner) performJoinRoomByID(
ctx context.Context, ctx context.Context,
req *api.PerformJoinRequest, req *rsAPI.PerformJoinRequest,
) (string, gomatrixserverlib.ServerName, error) { ) (string, gomatrixserverlib.ServerName, error) {
// The original client request ?server_name=... may include this HS so filter that out so we // The original client request ?server_name=... may include this HS so filter that out so we
// don't attempt to make_join with ourselves // don't attempt to make_join with ourselves
@ -168,8 +167,8 @@ func (r *Joiner) performJoinRoomByID(
// Get the domain part of the room ID. // Get the domain part of the room ID.
_, domain, err := gomatrixserverlib.SplitID('!', req.RoomIDOrAlias) _, domain, err := gomatrixserverlib.SplitID('!', req.RoomIDOrAlias)
if err != nil { if err != nil {
return "", "", &api.PerformError{ return "", "", &rsAPI.PerformError{
Code: api.PerformErrorBadRequest, Code: rsAPI.PerformErrorBadRequest,
Msg: fmt.Sprintf("Room ID %q is invalid: %s", req.RoomIDOrAlias, err), Msg: fmt.Sprintf("Room ID %q is invalid: %s", req.RoomIDOrAlias, err),
} }
} }
@ -207,10 +206,10 @@ func (r *Joiner) performJoinRoomByID(
// Force a federated join if we aren't in the room and we've been // Force a federated join if we aren't in the room and we've been
// given some server names to try joining by. // given some server names to try joining by.
inRoomReq := &api.QueryServerJoinedToRoomRequest{ inRoomReq := &rsAPI.QueryServerJoinedToRoomRequest{
RoomID: req.RoomIDOrAlias, RoomID: req.RoomIDOrAlias,
} }
inRoomRes := &api.QueryServerJoinedToRoomResponse{} inRoomRes := &rsAPI.QueryServerJoinedToRoomResponse{}
if err = r.Queryer.QueryServerJoinedToRoom(ctx, inRoomReq, inRoomRes); err != nil { if err = r.Queryer.QueryServerJoinedToRoom(ctx, inRoomReq, inRoomRes); err != nil {
return "", "", fmt.Errorf("r.Queryer.QueryServerJoinedToRoom: %w", err) return "", "", fmt.Errorf("r.Queryer.QueryServerJoinedToRoom: %w", err)
} }
@ -267,21 +266,21 @@ func (r *Joiner) performJoinRoomByID(
// If we haven't already joined the room then send an event // If we haven't already joined the room then send an event
// into the room changing our membership status. // into the room changing our membership status.
if !alreadyJoined { if !alreadyJoined {
inputReq := api.InputRoomEventsRequest{ inputReq := rsAPI.InputRoomEventsRequest{
InputRoomEvents: []api.InputRoomEvent{ InputRoomEvents: []rsAPI.InputRoomEvent{
{ {
Kind: api.KindNew, Kind: rsAPI.KindNew,
Event: event.Headered(buildRes.RoomVersion), Event: event.Headered(buildRes.RoomVersion),
AuthEventIDs: event.AuthEventIDs(), AuthEventIDs: event.AuthEventIDs(),
SendAsServer: string(r.Cfg.Matrix.ServerName), SendAsServer: string(r.Cfg.Matrix.ServerName),
}, },
}, },
} }
inputRes := api.InputRoomEventsResponse{} inputRes := rsAPI.InputRoomEventsResponse{}
r.Inputer.InputRoomEvents(ctx, &inputReq, &inputRes) r.Inputer.InputRoomEvents(ctx, &inputReq, &inputRes)
if err = inputRes.Err(); err != nil { if err = inputRes.Err(); err != nil {
return "", "", &api.PerformError{ return "", "", &rsAPI.PerformError{
Code: api.PerformErrorNotAllowed, Code: rsAPI.PerformErrorNotAllowed,
Msg: fmt.Sprintf("InputRoomEvents auth failed: %s", err), Msg: fmt.Sprintf("InputRoomEvents auth failed: %s", err),
} }
} }
@ -296,9 +295,9 @@ func (r *Joiner) performJoinRoomByID(
// Otherwise we'll try a federated join as normal, since it's quite // Otherwise we'll try a federated join as normal, since it's quite
// possible that the room still exists on other servers. // possible that the room still exists on other servers.
if len(req.ServerNames) == 0 { if len(req.ServerNames) == 0 {
return "", "", &api.PerformError{ return "", "", &rsAPI.PerformError{
Code: api.PerformErrorNoRoom, Code: rsAPI.PerformErrorNoRoom,
Msg: fmt.Sprintf("Room ID %q does not exist", req.RoomIDOrAlias), Msg: fmt.Sprintf("room ID %q does not exist", req.RoomIDOrAlias),
} }
} }
} }
@ -309,7 +308,7 @@ func (r *Joiner) performJoinRoomByID(
default: default:
// Something else went wrong. // Something else went wrong.
return "", "", fmt.Errorf("Error joining local room: %q", err) return "", "", fmt.Errorf("error joining local room: %q", err)
} }
// By this point, if req.RoomIDOrAlias contained an alias, then // By this point, if req.RoomIDOrAlias contained an alias, then
@ -321,7 +320,7 @@ func (r *Joiner) performJoinRoomByID(
func (r *Joiner) performFederatedJoinRoomByID( func (r *Joiner) performFederatedJoinRoomByID(
ctx context.Context, ctx context.Context,
req *api.PerformJoinRequest, req *rsAPI.PerformJoinRequest,
) (gomatrixserverlib.ServerName, error) { ) (gomatrixserverlib.ServerName, error) {
// Try joining by all of the supplied server names. // Try joining by all of the supplied server names.
fedReq := fsAPI.PerformJoinRequest{ fedReq := fsAPI.PerformJoinRequest{
@ -333,8 +332,8 @@ func (r *Joiner) performFederatedJoinRoomByID(
fedRes := fsAPI.PerformJoinResponse{} fedRes := fsAPI.PerformJoinResponse{}
r.FSAPI.PerformJoin(ctx, &fedReq, &fedRes) r.FSAPI.PerformJoin(ctx, &fedReq, &fedRes)
if fedRes.LastError != nil { if fedRes.LastError != nil {
return "", &api.PerformError{ return "", &rsAPI.PerformError{
Code: api.PerformErrRemote, Code: rsAPI.PerformErrRemote,
Msg: fedRes.LastError.Message, Msg: fedRes.LastError.Message,
RemoteCode: fedRes.LastError.Code, RemoteCode: fedRes.LastError.Code,
} }
@ -344,7 +343,7 @@ func (r *Joiner) performFederatedJoinRoomByID(
func buildEvent( func buildEvent(
ctx context.Context, db storage.Database, cfg *config.Global, builder *gomatrixserverlib.EventBuilder, ctx context.Context, db storage.Database, cfg *config.Global, builder *gomatrixserverlib.EventBuilder,
) (*gomatrixserverlib.HeaderedEvent, *api.QueryLatestEventsAndStateResponse, error) { ) (*gomatrixserverlib.HeaderedEvent, *rsAPI.QueryLatestEventsAndStateResponse, error) {
eventsNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(builder) eventsNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(builder)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("gomatrixserverlib.StateNeededForEventBuilder: %w", err) return nil, nil, fmt.Errorf("gomatrixserverlib.StateNeededForEventBuilder: %w", err)
@ -354,8 +353,8 @@ func buildEvent(
return nil, nil, errors.New("expecting state tuples for event builder, got none") return nil, nil, errors.New("expecting state tuples for event builder, got none")
} }
var queryRes api.QueryLatestEventsAndStateResponse var queryRes rsAPI.QueryLatestEventsAndStateResponse
err = helpers.QueryLatestEventsAndState(ctx, db, &api.QueryLatestEventsAndStateRequest{ err = helpers.QueryLatestEventsAndState(ctx, db, &rsAPI.QueryLatestEventsAndStateRequest{
RoomID: builder.RoomID, RoomID: builder.RoomID,
StateToFetch: eventsNeeded.Tuples(), StateToFetch: eventsNeeded.Tuples(),
}, &queryRes) }, &queryRes)

View file

@ -45,15 +45,15 @@ func (r *Leaver) PerformLeave(
) ([]api.OutputEvent, error) { ) ([]api.OutputEvent, error) {
_, domain, err := gomatrixserverlib.SplitID('@', req.UserID) _, domain, err := gomatrixserverlib.SplitID('@', req.UserID)
if err != nil { if err != nil {
return nil, fmt.Errorf("Supplied user ID %q in incorrect format", req.UserID) return nil, fmt.Errorf("supplied user ID %q in incorrect format", req.UserID)
} }
if domain != r.Cfg.Matrix.ServerName { if domain != r.Cfg.Matrix.ServerName {
return nil, fmt.Errorf("User %q does not belong to this homeserver", req.UserID) return nil, fmt.Errorf("user %q does not belong to this homeserver", req.UserID)
} }
if strings.HasPrefix(req.RoomID, "!") { if strings.HasPrefix(req.RoomID, "!") {
return r.performLeaveRoomByID(ctx, req, res) return r.performLeaveRoomByID(ctx, req, res)
} }
return nil, fmt.Errorf("Room ID %q is invalid", req.RoomID) return nil, fmt.Errorf("room ID %q is invalid", req.RoomID)
} }
func (r *Leaver) performLeaveRoomByID( func (r *Leaver) performLeaveRoomByID(
@ -68,7 +68,7 @@ func (r *Leaver) performLeaveRoomByID(
var host gomatrixserverlib.ServerName var host gomatrixserverlib.ServerName
_, host, err = gomatrixserverlib.SplitID('@', senderUser) _, host, err = gomatrixserverlib.SplitID('@', senderUser)
if err != nil { if err != nil {
return nil, fmt.Errorf("Sender %q is invalid", senderUser) return nil, fmt.Errorf("sender %q is invalid", senderUser)
} }
if host != r.Cfg.Matrix.ServerName { if host != r.Cfg.Matrix.ServerName {
return r.performFederatedRejectInvite(ctx, req, res, senderUser, eventID) return r.performFederatedRejectInvite(ctx, req, res, senderUser, eventID)
@ -91,19 +91,19 @@ func (r *Leaver) performLeaveRoomByID(
return nil, err return nil, err
} }
if !latestRes.RoomExists { if !latestRes.RoomExists {
return nil, fmt.Errorf("Room %q does not exist", req.RoomID) return nil, fmt.Errorf("room %q does not exist", req.RoomID)
} }
// Now let's see if the user is in the room. // Now let's see if the user is in the room.
if len(latestRes.StateEvents) == 0 { if len(latestRes.StateEvents) == 0 {
return nil, fmt.Errorf("User %q is not a member of room %q", req.UserID, req.RoomID) return nil, fmt.Errorf("user %q is not a member of room %q", req.UserID, req.RoomID)
} }
membership, err := latestRes.StateEvents[0].Membership() membership, err := latestRes.StateEvents[0].Membership()
if err != nil { if err != nil {
return nil, fmt.Errorf("Error getting membership: %w", err) return nil, fmt.Errorf("error getting membership: %w", err)
} }
if membership != gomatrixserverlib.Join && membership != gomatrixserverlib.Invite { if membership != gomatrixserverlib.Join && membership != gomatrixserverlib.Invite {
return nil, fmt.Errorf("User %q is not joined to the room (membership is %q)", req.UserID, membership) return nil, fmt.Errorf("user %q is not joined to the room (membership is %q)", req.UserID, membership)
} }
// Prepare the template for the leave event. // Prepare the template for the leave event.
@ -161,7 +161,7 @@ func (r *Leaver) performFederatedRejectInvite(
) ([]api.OutputEvent, error) { ) ([]api.OutputEvent, error) {
_, domain, err := gomatrixserverlib.SplitID('@', senderUser) _, domain, err := gomatrixserverlib.SplitID('@', senderUser)
if err != nil { if err != nil {
return nil, fmt.Errorf("User ID %q invalid: %w", senderUser, err) return nil, fmt.Errorf("user ID %q invalid: %w", senderUser, err)
} }
// Ask the federation sender to perform a federated leave for us. // Ask the federation sender to perform a federated leave for us.

View file

@ -96,7 +96,7 @@ func (r *Peeker) performPeekRoomByAlias(
// Get the domain part of the room alias. // Get the domain part of the room alias.
_, domain, err := gomatrixserverlib.SplitID('#', req.RoomIDOrAlias) _, domain, err := gomatrixserverlib.SplitID('#', req.RoomIDOrAlias)
if err != nil { if err != nil {
return "", fmt.Errorf("Alias %q is not in the correct format", req.RoomIDOrAlias) return "", fmt.Errorf("alias %q is not in the correct format", req.RoomIDOrAlias)
} }
req.ServerNames = append(req.ServerNames, domain) req.ServerNames = append(req.ServerNames, domain)
@ -114,7 +114,7 @@ func (r *Peeker) performPeekRoomByAlias(
err = r.FSAPI.PerformDirectoryLookup(ctx, &dirReq, &dirRes) err = r.FSAPI.PerformDirectoryLookup(ctx, &dirReq, &dirRes)
if err != nil { if err != nil {
logrus.WithError(err).Errorf("error looking up alias %q", req.RoomIDOrAlias) logrus.WithError(err).Errorf("error looking up alias %q", req.RoomIDOrAlias)
return "", fmt.Errorf("Looking up alias %q over federation failed: %w", req.RoomIDOrAlias, err) return "", fmt.Errorf("looking up alias %q over federation failed: %w", req.RoomIDOrAlias, err)
} }
roomID = dirRes.RoomID roomID = dirRes.RoomID
req.ServerNames = append(req.ServerNames, dirRes.ServerNames...) req.ServerNames = append(req.ServerNames, dirRes.ServerNames...)
@ -122,13 +122,13 @@ func (r *Peeker) performPeekRoomByAlias(
// Otherwise, look up if we know this room alias locally. // Otherwise, look up if we know this room alias locally.
roomID, err = r.DB.GetRoomIDForAlias(ctx, req.RoomIDOrAlias) roomID, err = r.DB.GetRoomIDForAlias(ctx, req.RoomIDOrAlias)
if err != nil { if err != nil {
return "", fmt.Errorf("Lookup room alias %q failed: %w", req.RoomIDOrAlias, err) return "", fmt.Errorf("lookup room alias %q failed: %w", req.RoomIDOrAlias, err)
} }
} }
// If the room ID is empty then we failed to look up the alias. // If the room ID is empty then we failed to look up the alias.
if roomID == "" { if roomID == "" {
return "", fmt.Errorf("Alias %q not found", req.RoomIDOrAlias) return "", fmt.Errorf("alias %q not found", req.RoomIDOrAlias)
} }
// If we do, then pluck out the room ID and continue the peek. // If we do, then pluck out the room ID and continue the peek.

View file

@ -71,7 +71,7 @@ func (v *StateResolution) LoadStateAtSnapshot(
if !ok { if !ok {
// This should only get hit if the database is corrupt. // This should only get hit if the database is corrupt.
// It should be impossible for an event to reference a NID that doesn't exist // It should be impossible for an event to reference a NID that doesn't exist
panic(fmt.Errorf("Corrupt DB: Missing state block numeric ID %d", stateBlockNID)) panic(fmt.Errorf("corrupt DB: Missing state block numeric ID %d", stateBlockNID))
} }
fullState = append(fullState, entries...) fullState = append(fullState, entries...)
} }
@ -146,7 +146,7 @@ func (v *StateResolution) LoadCombinedStateAfterEvents(
if !ok { if !ok {
// This should only get hit if the database is corrupt. // This should only get hit if the database is corrupt.
// It should be impossible for an event to reference a NID that doesn't exist // It should be impossible for an event to reference a NID that doesn't exist
panic(fmt.Errorf("Corrupt DB: Missing state snapshot numeric ID %d", prevState.BeforeStateSnapshotNID)) panic(fmt.Errorf("corrupt DB: Missing state snapshot numeric ID %d", prevState.BeforeStateSnapshotNID))
} }
// Combine all the state entries for this snapshot. // Combine all the state entries for this snapshot.
@ -157,7 +157,7 @@ func (v *StateResolution) LoadCombinedStateAfterEvents(
if !ok { if !ok {
// This should only get hit if the database is corrupt. // This should only get hit if the database is corrupt.
// It should be impossible for an event to reference a NID that doesn't exist // It should be impossible for an event to reference a NID that doesn't exist
panic(fmt.Errorf("Corrupt DB: Missing state block numeric ID %d", stateBlockNID)) panic(fmt.Errorf("corrupt DB: Missing state block numeric ID %d", stateBlockNID))
} }
fullState = append(fullState, entries...) fullState = append(fullState, entries...)
} }
@ -757,7 +757,7 @@ func (v *StateResolution) resolveConflictsV1(
for _, resolvedEvent := range resolvedEvents { for _, resolvedEvent := range resolvedEvents {
entry, ok := eventIDMap[resolvedEvent.EventID()] entry, ok := eventIDMap[resolvedEvent.EventID()]
if !ok { if !ok {
panic(fmt.Errorf("Missing state entry for event ID %q", resolvedEvent.EventID())) panic(fmt.Errorf("missing state entry for event ID %q", resolvedEvent.EventID()))
} }
notConflicted = append(notConflicted, entry) notConflicted = append(notConflicted, entry)
} }
@ -880,7 +880,7 @@ func (v *StateResolution) resolveConflictsV2(
for _, resolvedEvent := range resolvedEvents { for _, resolvedEvent := range resolvedEvents {
entry, ok := eventIDMap[resolvedEvent.EventID()] entry, ok := eventIDMap[resolvedEvent.EventID()]
if !ok { if !ok {
panic(fmt.Errorf("Missing state entry for event ID %q", resolvedEvent.EventID())) panic(fmt.Errorf("missing state entry for event ID %q", resolvedEvent.EventID()))
} }
notConflicted = append(notConflicted, entry) notConflicted = append(notConflicted, entry)
} }
@ -958,7 +958,7 @@ func (v *StateResolution) loadStateEvents(
for _, entry := range eventEntries { for _, entry := range eventEntries {
event, ok := eventMap(events).lookup(entry.EventNID) event, ok := eventMap(events).lookup(entry.EventNID)
if !ok { if !ok {
panic(fmt.Errorf("Corrupt DB: Missing event numeric ID %d", entry.EventNID)) panic(fmt.Errorf("corrupt DB: Missing event numeric ID %d", entry.EventNID))
} }
result = append(result, event.Event) result = append(result, event.Event)
eventIDMap[event.Event.EventID()] = entry eventIDMap[event.Event.EventID()] = entry

View file

@ -1136,7 +1136,7 @@ func (d *Database) loadStateAtSnapshot(
if !ok { if !ok {
// This should only get hit if the database is corrupt. // This should only get hit if the database is corrupt.
// It should be impossible for an event to reference a NID that doesn't exist // It should be impossible for an event to reference a NID that doesn't exist
panic(fmt.Errorf("Corrupt DB: Missing state block numeric ID %d", stateBlockNID)) panic(fmt.Errorf("corrupt DB: Missing state block numeric ID %d", stateBlockNID))
} }
fullState = append(fullState, entries...) fullState = append(fullState, entries...)
} }

View file

@ -98,7 +98,7 @@ func Enable(
) error { ) error {
db, err := NewDatabase(&base.Cfg.MSCs.Database) db, err := NewDatabase(&base.Cfg.MSCs.Database)
if err != nil { if err != nil {
return fmt.Errorf("Cannot enable MSC2836: %w", err) return fmt.Errorf("cannot enable MSC2836: %w", err)
} }
hooks.Enable() hooks.Enable()
hooks.Attach(hooks.KindNewEventPersisted, func(headeredEvent interface{}) { hooks.Attach(hooks.KindNewEventPersisted, func(headeredEvent interface{}) {

View file

@ -57,7 +57,7 @@ func Enable(
) error { ) error {
db, err := NewDatabase(&base.Cfg.MSCs.Database) db, err := NewDatabase(&base.Cfg.MSCs.Database)
if err != nil { if err != nil {
return fmt.Errorf("Cannot enable MSC2946: %w", err) return fmt.Errorf("cannot enable MSC2946: %w", err)
} }
hooks.Enable() hooks.Enable()
hooks.Attach(hooks.KindNewEventPersisted, func(headeredEvent interface{}) { hooks.Attach(hooks.KindNewEventPersisted, func(headeredEvent interface{}) {

View file

@ -30,7 +30,6 @@ import (
"github.com/matrix-org/dendrite/syncapi/types" "github.com/matrix-org/dendrite/syncapi/types"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
) )
// OutputKeyChangeEventConsumer consumes events that originated in the key server. // OutputKeyChangeEventConsumer consumes events that originated in the key server.
@ -128,7 +127,7 @@ func (s *OutputKeyChangeEventConsumer) onDeviceKeyMessage(m api.DeviceMessage, o
UserID: output.UserID, UserID: output.UserID,
}, &queryRes) }, &queryRes)
if err != nil { if err != nil {
log.WithError(err).Error("syncapi: failed to QuerySharedUsers for key change event from key server") logrus.WithError(err).Error("syncapi: failed to QuerySharedUsers for key change event from key server")
sentry.CaptureException(err) sentry.CaptureException(err)
return err return err
} }
@ -155,7 +154,7 @@ func (s *OutputKeyChangeEventConsumer) onCrossSigningMessage(m api.DeviceMessage
UserID: output.UserID, UserID: output.UserID,
}, &queryRes) }, &queryRes)
if err != nil { if err != nil {
log.WithError(err).Error("syncapi: failed to QuerySharedUsers for key change event from key server") logrus.WithError(err).Error("syncapi: failed to QuerySharedUsers for key change event from key server")
sentry.CaptureException(err) sentry.CaptureException(err)
return err return err
} }

View file

@ -19,7 +19,6 @@ import (
"strings" "strings"
"github.com/Shopify/sarama" "github.com/Shopify/sarama"
"github.com/matrix-org/dendrite/keyserver/api"
keyapi "github.com/matrix-org/dendrite/keyserver/api" keyapi "github.com/matrix-org/dendrite/keyserver/api"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/syncapi/types" "github.com/matrix-org/dendrite/syncapi/types"
@ -31,8 +30,8 @@ const DeviceListLogName = "dl"
// DeviceOTKCounts adds one-time key counts to the /sync response // DeviceOTKCounts adds one-time key counts to the /sync response
func DeviceOTKCounts(ctx context.Context, keyAPI keyapi.KeyInternalAPI, userID, deviceID string, res *types.Response) error { func DeviceOTKCounts(ctx context.Context, keyAPI keyapi.KeyInternalAPI, userID, deviceID string, res *types.Response) error {
var queryRes api.QueryOneTimeKeysResponse var queryRes keyapi.QueryOneTimeKeysResponse
keyAPI.QueryOneTimeKeys(ctx, &api.QueryOneTimeKeysRequest{ keyAPI.QueryOneTimeKeys(ctx, &keyapi.QueryOneTimeKeysRequest{
UserID: userID, UserID: userID,
DeviceID: deviceID, DeviceID: deviceID,
}, &queryRes) }, &queryRes)
@ -81,8 +80,8 @@ func DeviceListCatchup(
if toLog := to; toLog.Partition == partition && toLog.Offset > 0 { if toLog := to; toLog.Partition == partition && toLog.Offset > 0 {
toOffset = toLog.Offset toOffset = toLog.Offset
} }
var queryRes api.QueryKeyChangesResponse var queryRes keyapi.QueryKeyChangesResponse
keyAPI.QueryKeyChanges(ctx, &api.QueryKeyChangesRequest{ keyAPI.QueryKeyChanges(ctx, &keyapi.QueryKeyChangesRequest{
Partition: partition, Partition: partition,
Offset: offset, Offset: offset,
ToOffset: toOffset, ToOffset: toOffset,

View file

@ -30,7 +30,6 @@ import (
"github.com/matrix-org/dendrite/syncapi/types" "github.com/matrix-org/dendrite/syncapi/types"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
) )
// Database is a temporary struct until we have made syncserver.go the same for both pq/sqlite // Database is a temporary struct until we have made syncserver.go the same for both pq/sqlite
@ -309,7 +308,7 @@ func (d *Database) StreamEventsToEvents(device *userapi.Device, in []types.Strea
"transaction_id", in[i].TransactionID.TransactionID, "transaction_id", in[i].TransactionID.TransactionID,
) )
if err != nil { if err != nil {
log.WithFields(log.Fields{ logrus.WithFields(logrus.Fields{
"event_id": out[i].EventID(), "event_id": out[i].EventID(),
}).WithError(err).Warnf("Failed to add transaction ID to event") }).WithError(err).Warnf("Failed to add transaction ID to event")
} }
@ -529,7 +528,7 @@ func (d *Database) RedactEvent(ctx context.Context, redactedEventID string, reda
return err return err
} }
if len(redactedEvents) == 0 { if len(redactedEvents) == 0 {
log.WithField("event_id", redactedEventID).WithField("redaction_event", redactedBecause.EventID()).Warnf("missing redacted event for redaction") logrus.WithField("event_id", redactedEventID).WithField("redaction_event", redactedBecause.EventID()).Warnf("missing redacted event for redaction")
return nil return nil
} }
eventToRedact := redactedEvents[0].Unwrap() eventToRedact := redactedEvents[0].Unwrap()
@ -645,7 +644,7 @@ func (d *Database) fetchMissingStateEvents(
return nil, err return nil, err
} }
if len(stateEvents) != len(missing) { if len(stateEvents) != len(missing) {
log.WithContext(ctx).Warnf("Failed to map all event IDs to events (got %d, wanted %d)", len(stateEvents), len(missing)) logrus.WithContext(ctx).Warnf("Failed to map all event IDs to events (got %d, wanted %d)", len(stateEvents), len(missing))
// TODO: Why is this happening? It's probably the roomserver. Uncomment // TODO: Why is this happening? It's probably the roomserver. Uncomment
// this error again when we work out what it is and fix it, otherwise we // this error again when we work out what it is and fix it, otherwise we

View file

@ -29,10 +29,10 @@ var (
// ErrInvalidSyncTokenType is returned when an attempt at creating a // ErrInvalidSyncTokenType is returned when an attempt at creating a
// new instance of SyncToken with an invalid type (i.e. neither "s" // new instance of SyncToken with an invalid type (i.e. neither "s"
// nor "t"). // nor "t").
ErrInvalidSyncTokenType = fmt.Errorf("Sync token has an unknown prefix (should be either s or t)") ErrInvalidSyncTokenType = fmt.Errorf("sync token has an unknown prefix (should be either s or t)")
// ErrInvalidSyncTokenLen is returned when the pagination token is an // ErrInvalidSyncTokenLen is returned when the pagination token is an
// invalid length // invalid length
ErrInvalidSyncTokenLen = fmt.Errorf("Sync token has an invalid length") ErrInvalidSyncTokenLen = fmt.Errorf("sync token has an invalid length")
) )
type StateDelta struct { type StateDelta struct {

View file

@ -177,10 +177,10 @@ func (a *UserInternalAPI) deviceListUpdate(userID string, deviceIDs []string) er
DeviceKeys: deviceKeys, DeviceKeys: deviceKeys,
}, &uploadRes) }, &uploadRes)
if uploadRes.Error != nil { if uploadRes.Error != nil {
return fmt.Errorf("Failed to delete device keys: %v", uploadRes.Error) return fmt.Errorf("failed to delete device keys: %v", uploadRes.Error)
} }
if len(uploadRes.KeyErrors) > 0 { if len(uploadRes.KeyErrors) > 0 {
return fmt.Errorf("Failed to delete device keys, key errors: %+v", uploadRes.KeyErrors) return fmt.Errorf("failed to delete device keys, key errors: %+v", uploadRes.KeyErrors)
} }
return nil return nil
} }
@ -242,10 +242,10 @@ func (a *UserInternalAPI) PerformDeviceUpdate(ctx context.Context, req *api.Perf
OnlyDisplayNameUpdates: true, OnlyDisplayNameUpdates: true,
}, &uploadRes) }, &uploadRes)
if uploadRes.Error != nil { if uploadRes.Error != nil {
return fmt.Errorf("Failed to update device key display name: %v", uploadRes.Error) return fmt.Errorf("failed to update device key display name: %v", uploadRes.Error)
} }
if len(uploadRes.KeyErrors) > 0 { if len(uploadRes.KeyErrors) > 0 {
return fmt.Errorf("Failed to update device key display name, key errors: %+v", uploadRes.KeyErrors) return fmt.Errorf("failed to update device key display name, key errors: %+v", uploadRes.KeyErrors)
} }
} }
return nil return nil

View file

@ -67,4 +67,4 @@ type Database interface {
// Err3PIDInUse is the error returned when trying to save an association involving // Err3PIDInUse is the error returned when trying to save an association involving
// a third-party identifier which is already associated to a local user. // a third-party identifier which is already associated to a local user.
var Err3PIDInUse = errors.New("This third-party identifier is already in use") var Err3PIDInUse = errors.New("this third-party identifier is already in use")

View file

@ -28,7 +28,6 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/dendrite/userapi/storage/accounts/postgres/deltas" "github.com/matrix-org/dendrite/userapi/storage/accounts/postgres/deltas"
_ "github.com/matrix-org/dendrite/userapi/storage/accounts/postgres/deltas"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
@ -271,7 +270,7 @@ func (d *Database) hashPassword(plaintext string) (hash string, err error) {
// Err3PIDInUse is the error returned when trying to save an association involving // Err3PIDInUse is the error returned when trying to save an association involving
// a third-party identifier which is already associated to a local user. // a third-party identifier which is already associated to a local user.
var Err3PIDInUse = errors.New("This third-party identifier is already in use") var Err3PIDInUse = errors.New("this third-party identifier is already in use")
// SaveThreePIDAssociation saves the association between a third party identifier // SaveThreePIDAssociation saves the association between a third party identifier
// and a local Matrix user (identified by the user's ID's local part). // and a local Matrix user (identified by the user's ID's local part).

View file

@ -304,7 +304,7 @@ func (d *Database) hashPassword(plaintext string) (hash string, err error) {
// Err3PIDInUse is the error returned when trying to save an association involving // Err3PIDInUse is the error returned when trying to save an association involving
// a third-party identifier which is already associated to a local user. // a third-party identifier which is already associated to a local user.
var Err3PIDInUse = errors.New("This third-party identifier is already in use") var Err3PIDInUse = errors.New("this third-party identifier is already in use")
// SaveThreePIDAssociation saves the association between a third party identifier // SaveThreePIDAssociation saves the association between a third party identifier
// and a local Matrix user (identified by the user's ID's local part). // and a local Matrix user (identified by the user's ID's local part).