aboutsummaryrefslogtreecommitdiff
path: root/clientapi/routing/joinroom.go
blob: f55d1b6ab1c6f46d85cda33cc80fb1e6a8b7fc59 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright 2017 Vector Creations Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package routing

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/matrix-org/dendrite/clientapi/auth/authtypes"
	"github.com/matrix-org/dendrite/clientapi/auth/storage/accounts"
	"github.com/matrix-org/dendrite/clientapi/httputil"
	"github.com/matrix-org/dendrite/clientapi/jsonerror"
	"github.com/matrix-org/dendrite/clientapi/producers"
	"github.com/matrix-org/dendrite/common"
	"github.com/matrix-org/dendrite/common/config"
	federationSenderAPI "github.com/matrix-org/dendrite/federationsender/api"
	roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
	"github.com/matrix-org/gomatrix"
	"github.com/matrix-org/gomatrixserverlib"
	"github.com/matrix-org/util"
)

// JoinRoomByIDOrAlias implements the "/join/{roomIDOrAlias}" API.
// https://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-join-roomidoralias
func JoinRoomByIDOrAlias(
	req *http.Request,
	device *authtypes.Device,
	roomIDOrAlias string,
	cfg *config.Dendrite,
	federation *gomatrixserverlib.FederationClient,
	producer *producers.RoomserverProducer,
	queryAPI roomserverAPI.RoomserverQueryAPI,
	aliasAPI roomserverAPI.RoomserverAliasAPI,
	fsAPI federationSenderAPI.FederationSenderInternalAPI,
	keyRing gomatrixserverlib.KeyRing,
	accountDB accounts.Database,
) util.JSONResponse {
	var content map[string]interface{} // must be a JSON object
	if resErr := httputil.UnmarshalJSONRequest(req, &content); resErr != nil {
		return *resErr
	}

	evTime, err := httputil.ParseTSParam(req)
	if err != nil {
		return util.JSONResponse{
			Code: http.StatusBadRequest,
			JSON: jsonerror.InvalidArgumentValue(err.Error()),
		}
	}

	localpart, _, err := gomatrixserverlib.SplitID('@', device.UserID)
	if err != nil {
		util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
		return jsonerror.InternalServerError()
	}

	profile, err := accountDB.GetProfileByLocalpart(req.Context(), localpart)
	if err != nil {
		util.GetLogger(req.Context()).WithError(err).Error("accountDB.GetProfileByLocalpart failed")
		return jsonerror.InternalServerError()
	}

	content["membership"] = gomatrixserverlib.Join
	content["displayname"] = profile.DisplayName
	content["avatar_url"] = profile.AvatarURL

	r := joinRoomReq{
		req, evTime, content, device.UserID, cfg, federation, producer,
		queryAPI, aliasAPI, fsAPI, keyRing,
	}

	if strings.HasPrefix(roomIDOrAlias, "!") {
		return r.joinRoomByID(roomIDOrAlias)
	}
	if strings.HasPrefix(roomIDOrAlias, "#") {
		return r.joinRoomByAlias(roomIDOrAlias)
	}
	return util.JSONResponse{
		Code: http.StatusBadRequest,
		JSON: jsonerror.BadJSON(
			fmt.Sprintf("Invalid first character '%s' for room ID or alias",
				string([]rune(roomIDOrAlias)[0])), // Wrapping with []rune makes this call UTF-8 safe
		),
	}
}

type joinRoomReq struct {
	req        *http.Request
	evTime     time.Time
	content    map[string]interface{}
	userID     string
	cfg        *config.Dendrite
	federation *gomatrixserverlib.FederationClient
	producer   *producers.RoomserverProducer
	queryAPI   roomserverAPI.RoomserverQueryAPI
	aliasAPI   roomserverAPI.RoomserverAliasAPI
	fsAPI      federationSenderAPI.FederationSenderInternalAPI
	keyRing    gomatrixserverlib.KeyRing
}

// joinRoomByID joins a room by room ID
func (r joinRoomReq) joinRoomByID(roomID string) util.JSONResponse {
	// A client should only join a room by room ID when it has an invite
	// to the room. If the server is already in the room then we can
	// lookup the invite and process the request as a normal state event.
	// If the server is not in the room the we will need to look up the
	// remote server the invite came from in order to request a join event
	// from that server.
	queryReq := roomserverAPI.QueryInvitesForUserRequest{
		RoomID: roomID, TargetUserID: r.userID,
	}
	var queryRes roomserverAPI.QueryInvitesForUserResponse
	if err := r.queryAPI.QueryInvitesForUser(r.req.Context(), &queryReq, &queryRes); err != nil {
		util.GetLogger(r.req.Context()).WithError(err).Error("r.queryAPI.QueryInvitesForUser failed")
		return jsonerror.InternalServerError()
	}

	servers := []gomatrixserverlib.ServerName{}
	seenInInviterIDs := map[gomatrixserverlib.ServerName]bool{}
	for _, userID := range queryRes.InviteSenderUserIDs {
		_, domain, err := gomatrixserverlib.SplitID('@', userID)
		if err != nil {
			util.GetLogger(r.req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
			return jsonerror.InternalServerError()
		}
		if !seenInInviterIDs[domain] {
			servers = append(servers, domain)
			seenInInviterIDs[domain] = true
		}
	}

	// Also add the domain extracted from the roomID as a last resort to join
	// in case the client is erroneously trying to join by ID without an invite
	// or all previous attempts at domains extracted from the inviter IDs fail
	// Note: It's no guarantee we'll succeed because a room isn't bound to the domain in its ID
	_, domain, err := gomatrixserverlib.SplitID('!', roomID)
	if err != nil {
		util.GetLogger(r.req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
		return jsonerror.InternalServerError()
	}
	if domain != r.cfg.Matrix.ServerName && !seenInInviterIDs[domain] {
		servers = append(servers, domain)
	}

	return r.joinRoomUsingServers(roomID, servers)

}

// joinRoomByAlias joins a room using a room alias.
func (r joinRoomReq) joinRoomByAlias(roomAlias string) util.JSONResponse {
	_, domain, err := gomatrixserverlib.SplitID('#', roomAlias)
	if err != nil {
		return util.JSONResponse{
			Code: http.StatusBadRequest,
			JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"),
		}
	}
	if domain == r.cfg.Matrix.ServerName {
		queryReq := roomserverAPI.GetRoomIDForAliasRequest{Alias: roomAlias}
		var queryRes roomserverAPI.GetRoomIDForAliasResponse
		if err = r.aliasAPI.GetRoomIDForAlias(r.req.Context(), &queryReq, &queryRes); err != nil {
			util.GetLogger(r.req.Context()).WithError(err).Error("r.aliasAPI.GetRoomIDForAlias failed")
			return jsonerror.InternalServerError()
		}

		if len(queryRes.RoomID) > 0 {
			return r.joinRoomUsingServers(queryRes.RoomID, []gomatrixserverlib.ServerName{r.cfg.Matrix.ServerName})
		}
		// If the response doesn't contain a non-empty string, return an error
		return util.JSONResponse{
			Code: http.StatusNotFound,
			JSON: jsonerror.NotFound("Room alias " + roomAlias + " not found."),
		}
	}
	// If the room isn't local, use federation to join
	return r.joinRoomByRemoteAlias(domain, roomAlias)
}

func (r joinRoomReq) joinRoomByRemoteAlias(
	domain gomatrixserverlib.ServerName, roomAlias string,
) util.JSONResponse {
	resp, err := r.federation.LookupRoomAlias(r.req.Context(), domain, roomAlias)
	if err != nil {
		switch x := err.(type) {
		case gomatrix.HTTPError:
			if x.Code == http.StatusNotFound {
				return util.JSONResponse{
					Code: http.StatusNotFound,
					JSON: jsonerror.NotFound("Room alias not found"),
				}
			}
		}
		util.GetLogger(r.req.Context()).WithError(err).Error("r.federation.LookupRoomAlias failed")
		return jsonerror.InternalServerError()
	}

	return r.joinRoomUsingServers(resp.RoomID, resp.Servers)
}

func (r joinRoomReq) writeToBuilder(eb *gomatrixserverlib.EventBuilder, roomID string) error {
	eb.Type = "m.room.member"

	err := eb.SetContent(r.content)
	if err != nil {
		return err
	}

	err = eb.SetUnsigned(struct{}{})
	if err != nil {
		return err
	}

	eb.Sender = r.userID
	eb.StateKey = &r.userID
	eb.RoomID = roomID
	eb.Redacts = ""

	return nil
}

func (r joinRoomReq) joinRoomUsingServers(
	roomID string, servers []gomatrixserverlib.ServerName,
) util.JSONResponse {
	var eb gomatrixserverlib.EventBuilder
	err := r.writeToBuilder(&eb, roomID)
	if err != nil {
		util.GetLogger(r.req.Context()).WithError(err).Error("r.writeToBuilder failed")
		return jsonerror.InternalServerError()
	}

	queryRes := roomserverAPI.QueryLatestEventsAndStateResponse{}
	event, err := common.BuildEvent(r.req.Context(), &eb, r.cfg, r.evTime, r.queryAPI, &queryRes)
	if err == nil {
		// If we have successfully built an event at this point then we can
		// assert that the room is a local room, as BuildEvent was able to
		// add prev_events etc successfully.
		if _, err = r.producer.SendEvents(
			r.req.Context(),
			[]gomatrixserverlib.HeaderedEvent{
				(*event).Headered(queryRes.RoomVersion),
			},
			r.cfg.Matrix.ServerName,
			nil,
		); err != nil {
			util.GetLogger(r.req.Context()).WithError(err).Error("r.producer.SendEvents failed")
			return jsonerror.InternalServerError()
		}
		return util.JSONResponse{
			Code: http.StatusOK,
			JSON: struct {
				RoomID string `json:"room_id"`
			}{roomID},
		}
	}

	// Otherwise, if we've reached here, then we haven't been able to populate
	// prev_events etc for the room, therefore the room is probably federated.

	// TODO: This needs to be re-thought, as in the case of an invite, the room
	// will exist in the database in roomserver_rooms but won't have any state
	// events, therefore this below check fails.
	if err != common.ErrRoomNoExists {
		util.GetLogger(r.req.Context()).WithError(err).Error("common.BuildEvent failed")
		return jsonerror.InternalServerError()
	}

	if len(servers) == 0 {
		return util.JSONResponse{
			Code: http.StatusNotFound,
			JSON: jsonerror.NotFound("No candidate servers found for room"),
		}
	}

	var lastErr error
	for _, server := range servers {
		var response *util.JSONResponse
		response, lastErr = r.joinRoomUsingServer(roomID, server)
		if lastErr != nil {
			// There was a problem talking to one of the servers.
			util.GetLogger(r.req.Context()).WithError(lastErr).WithField("server", server).Warn("Failed to join room using server")
			// Try the next server.
			if r.req.Context().Err() != nil {
				// The request context has expired so don't bother trying any
				// more servers - they will immediately fail due to the expired
				// context.
				break
			} else {
				// The request context hasn't expired yet so try the next server.
				continue
			}
		}
		return *response
	}

	// Every server we tried to join through resulted in an error.
	// We return the error from the last server.

	// TODO: Generate the correct HTTP status code for all different
	// kinds of errors that could have happened.
	// The possible errors include:
	//   1) We can't connect to the remote servers.
	//   2) None of the servers we could connect to think we are allowed
	//	    to join the room.
	//   3) The remote server returned something invalid.
	//   4) We couldn't fetch the public keys needed to verify the
	//      signatures on the state events.
	//   5) ...
	util.GetLogger(r.req.Context()).WithError(lastErr).Error("failed to join through any server")
	return jsonerror.InternalServerError()
}

// joinRoomUsingServer tries to join a remote room using a given matrix server.
// If there was a failure communicating with the server or the response from the
// server was invalid this returns an error.
// Otherwise this returns a JSONResponse.
func (r joinRoomReq) joinRoomUsingServer(roomID string, server gomatrixserverlib.ServerName) (*util.JSONResponse, error) {
	fedJoinReq := federationSenderAPI.PerformJoinRequest{
		RoomID:     roomID,
		UserID:     r.userID,
		ServerName: server,
	}
	fedJoinRes := federationSenderAPI.PerformJoinResponse{}
	if err := r.fsAPI.PerformJoin(r.req.Context(), &fedJoinReq, &fedJoinRes); err != nil {
		return nil, err
	}

	return &util.JSONResponse{
		Code: http.StatusOK,
		// TODO: Put the response struct somewhere common.
		JSON: struct {
			RoomID string `json:"room_id"`
		}{roomID},
	}, nil
}