/* * RoutesUser.c - bundled Matrix route handlers. * * merged from: RouteUserProfile.c, RouteUserDirectory.c, RouteConfig.c * (each handler registered in Routes.c) */ /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include #include #include #include ROUTE_IMPL(RouteUserProfile, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; CommonID *userId = NULL; User *user = NULL; char *serverName; char *username = NULL; char *entry = NULL; char *token = NULL; char *value = NULL; char *msg; Config config; ConfigLock(db, &config); if (!config.ok) { Log(LOG_ERR, "%s", config.err); HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } serverName = config.serverName; username = ArrayGet(path, 0); userId = UserIdParse(username, serverName); if (!userId) { msg = "Invalid user ID."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } if (!ParserServerNameEquals(userId->server, serverName)) { /* TODO: Implement lookup over federation. */ msg = "User profile endpoint currently doesn't support lookup over " "federation."; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); goto finish; } /* TODO: Actually implement user data */ switch (HttpRequestMethodGet(args->context)) { case HTTP_GET: user = UserLock(db, userId->local); if (!user) { msg = "Couldn't lock user."; HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, msg); goto finish; } if (ArraySize(path) > 1) { entry = ArrayGet(path, 1); response = HashMapCreate(); value = UserGetProfile(user, entry); if (value) { HashMapSet(response, entry, JsonValueString(value)); } goto finish; } response = HashMapCreate(); value = UserGetProfile(user, "avatar_url"); if (value) { HashMapSet(response, "avatar_url", JsonValueString(value)); } value = UserGetProfile(user, "displayname"); if (value) { HashMapSet(response, "displayname", JsonValueString(value)); } goto finish; case HTTP_PUT: if (ArraySize(path) > 1) { request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } entry = ArrayGet(path, 1); if (StrEquals(entry, "displayname") || StrEquals(entry, "avatar_url")) { /* Check if user has privilege to do that action. */ if (StrEquals(userId->local, UserGetName(user))) { value = JsonValueAsString(HashMapGet(request, entry)); /* TODO: Make UserSetProfile notify other parties of * the change */ UserSetProfile(user, entry, value); response = HashMapCreate(); goto finish; } /* User is not allowed to carry-on the action */ msg = "Cannot change another user's profile."; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); goto finish; } else { msg = "Invalid property being changed."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); goto finish; } } else { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_MISSING_PARAM, NULL); goto finish; } default: msg = "Route only accepts GET and PUT."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNKNOWN, msg); break; } finish: ConfigUnlock(&config); UserIdFree(userId); UserUnlock(user); JsonFree(request); return response; } /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include ROUTE_IMPL(RouteUserDirectory, path, argp) { RouteArgs *args = argp; HashMap *response = NULL; HashMap *request = NULL; Array *users = NULL; Array *results = NULL; Db *db = args->matrixArgs->db; Config config = { .ok = 0 }; User *user = NULL; char *token = NULL; char *requesterName = NULL; char *msg = NULL; UserDirectoryRequest dirRequest; size_t i, included; (void) path; dirRequest.search_term = NULL; dirRequest.limit = 10; if (HttpRequestMethodGet(args->context) != HTTP_POST) { msg = "Request supports only POST."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } if (!UserDirectoryRequestFromJson(request, &dirRequest, &msg)) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (!dirRequest.search_term) { msg = "Field 'search_term' not set."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } response = MatrixGetAccessToken(args->context, &token); if (response) { return response; } /* TODO: Actually use information related to the user. */ user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } requesterName = UserGetName(user); response = HashMapCreate(); results = ArrayCreate(); /* TODO: Check for users matching search term and users outside our * local server. */ users = DbList(db, 1, "users"); ConfigLock(db, &config); if (!config.ok) { Log(LOG_ERR, "Directory endpoint failed to lock configuration."); HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, config.err); goto finish; } #define IncludedLtLimit ((int64_t) included < dirRequest.limit) for (i = 0, included = 0; i < ArraySize(users) && IncludedLtLimit; i++) #undef IncludedLtLimit { HashMap *obj; User *currentUser; char *name = ArrayGet(users, i); char *displayName; char *lowerDisplayName; char *avatarUrl; if (!StrEquals(name, requesterName)) { currentUser = UserLock(db, name); } else { currentUser = user; } displayName = UserGetProfile(currentUser, "displayname"); lowerDisplayName = StrLower(displayName); avatarUrl = UserGetProfile(currentUser, "avatar_url"); /* Check for the user ID and display name. */ if (strstr(name, dirRequest.search_term) || (lowerDisplayName && strstr(lowerDisplayName, dirRequest.search_term))) { included++; obj = HashMapCreate(); if (displayName) { JsonSet(obj, JsonValueString(displayName), 1, "display_name"); } if (avatarUrl) { JsonSet(obj, JsonValueString(displayName), 1, "avatar_url"); } if (name) { char *uID = StrConcat(4, "@", name, ":", config.serverName); JsonSet(obj, JsonValueString(uID), 1, "user_id"); Free(uID); } ArrayAdd(results, JsonValueObject(obj)); } if (lowerDisplayName) { Free(lowerDisplayName); } if (!StrEquals(name, requesterName)) { UserUnlock(currentUser); } } JsonSet(response, JsonValueArray(results), 1, "results"); JsonSet(response, JsonValueBoolean((int64_t) included == dirRequest.limit), 1, "limited" ); finish: UserUnlock(user); JsonFree(request); DbListFree(users); ConfigUnlock(&config); UserDirectoryRequestFree(&dirRequest); return response; } /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include ROUTE_IMPL(RouteConfig, path, argp) { RouteArgs *args = argp; HashMap *response; char *token; char *msg; User *user = NULL; Config config; HashMap *request = NULL; Config newConf; HashMap *newJson = NULL; (void) path; response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = UserAuthenticate(args->matrixArgs->db, token); if (!user) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } if (!(UserGetPrivileges(user) & USER_CONFIG)) { msg = "User does not have the 'CONFIG' privilege."; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); goto finish; } ConfigLock(args->matrixArgs->db, &config); if (!config.ok) { Log(LOG_ERR, "%s", config.err); HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, config.err); goto finish; } switch (HttpRequestMethodGet(args->context)) { case HTTP_GET: response = JsonDuplicate(DbJson(config.ref)); break; case HTTP_POST: request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); break; } ConfigParse(request, &newConf); if (newConf.ok) { if (DbJsonSet(config.ref, request)) { response = HashMapCreate(); /* * TODO: Apply configuration and set this only if a main * component was reconfigured, such as the listeners. */ HashMapSet(response, "restart_required", JsonValueBoolean(1)); } else { msg = "Internal server error while writing the config."; HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, msg); } } else { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, newConf.err); } ConfigFree(&newConf); JsonFree(request); break; case HTTP_PUT: request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); break; } newJson = JsonDuplicate(DbJson(config.ref)); JsonMerge(newJson, request); ConfigParse(newJson, &newConf); if (newConf.ok) { if (DbJsonSet(config.ref, newJson)) { response = HashMapCreate(); /* * TODO: Apply configuration and set this only if a main * component was reconfigured, such as the listeners. */ HashMapSet(response, "restart_required", JsonValueBoolean(1)); } else { msg = "Internal server error while writing the config."; HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, msg); } } else { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, newConf.err); } ConfigFree(&newConf); JsonFree(request); JsonFree(newJson); break; default: msg = "Unknown request method."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); break; } finish: UserUnlock(user); ConfigUnlock(&config); return response; } static HashMap * DeviceInfo(char * deviceId, HashMap * device) { HashMap *info = HashMapCreate(); char *displayName = device ? JsonValueAsString(HashMapGet(device, "displayName")) : NULL; HashMapSet(info, "device_id", JsonValueString(deviceId)); if (displayName) { HashMapSet(info, "display_name", JsonValueString(displayName)); } return info; } static int DeviceDelete(Db * db, User * user, char * deviceId) { HashMap *devices = UserGetDevices(user); HashMap *device; JsonValue *deleted; char *accessToken; char *refreshToken; if (!devices) { return 0; } device = JsonValueAsObject(HashMapGet(devices, deviceId)); if (!device) { return 0; } accessToken = JsonValueAsString(HashMapGet(device, "accessToken")); refreshToken = JsonValueAsString(HashMapGet(device, "refreshToken")); if (accessToken) { UserDeleteToken(user, accessToken); } if (refreshToken) { DbDelete(db, 3, "tokens", "refresh", refreshToken); } deleted = HashMapDelete(devices, deviceId); if (deleted) { JsonValueFree(deleted); } return 1; } ROUTE_IMPL(RouteDevices, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; HashMap *devices = NULL; HashMap *request = NULL; User *user = NULL; Config config; HttpRequestMethod method; char *token = NULL; char *deviceId = ArraySize(path) >= 1 ? ArrayGet(path, 0) : NULL; (void) path; ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } method = HttpRequestMethodGet(args->context); devices = UserGetDevices(user); if (!deviceId) { Array *list = ArrayCreate(); char *key; void *val; if (devices) { while (HashMapIterate(devices, &key, &val)) { ArrayAdd(list, JsonValueObject(DeviceInfo(key, JsonValueAsObject(val)))); } } response = HashMapCreate(); HashMapSet(response, "devices", JsonValueArray(list)); goto finish; } if (method == HTTP_GET) { HashMap *device = devices ? JsonValueAsObject(HashMapGet(devices, deviceId)) : NULL; if (!device) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } response = DeviceInfo(deviceId, device); goto finish; } if (method == HTTP_DELETE) { if (!DeviceDelete(db, user, deviceId)) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } response = HashMapCreate(); goto finish; } if (method == HTTP_PUT) { HashMap *device = devices ? JsonValueAsObject(HashMapGet(devices, deviceId)) : NULL; char *displayName; if (!device) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } displayName = JsonValueAsString(HashMapGet(request, "display_name")); if (displayName) { HashMapSet(device, "displayName", JsonValueString(displayName)); } response = HashMapCreate(); goto finish; } HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, NULL); finish: if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); return response; } ROUTE_IMPL(RouteDeleteDevices, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; User *user = NULL; Config config; char *token = NULL; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } { Array *list = JsonValueAsArray(HashMapGet(request, "devices")); size_t i; if (!list) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, "devices is required"); goto finish; } for (i = 0; i < ArraySize(list); i++) { char *id = JsonValueAsString(ArrayGet(list, i)); if (id) { DeviceDelete(db, user, id); } } } response = HashMapCreate(); finish: if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); return response; } ROUTE_IMPL(RouteAccountData, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; User *user = NULL; DbRef *ref = NULL; Config config; HttpRequestMethod method; char *token = NULL; char *userParam; char *roomId = NULL; char *type; char *expected = NULL; ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } userParam = ArrayGet(path, 0); if (ArraySize(path) == 2) { type = ArrayGet(path, 1); } else if (ArraySize(path) == 3) { roomId = ArrayGet(path, 1); type = ArrayGet(path, 2); } else { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, NULL); goto finish; } expected = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!userParam || !StrEquals(userParam, expected)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } method = HttpRequestMethodGet(args->context); if (method == HTTP_GET) { if (roomId) { ref = DbLock(db, 4, "rooms", roomId, "accountdata", UserGetName(user)); } else { ref = DbLock(db, 2, "accountdata", UserGetName(user)); } if (!ref) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } { HashMap *all = DbJson(ref); HashMap *content = type ? JsonValueAsObject(HashMapGet(all, type)) : NULL; if (!content) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } response = JsonDuplicate(content); } goto finish; } if (method == HTTP_DELETE) { if (roomId) { ref = DbLock(db, 4, "rooms", roomId, "accountdata", UserGetName(user)); } else { ref = DbLock(db, 2, "accountdata", UserGetName(user)); } if (ref) { HashMapDelete(DbJson(ref), type); } response = HashMapCreate(); goto finish; } if (method != HTTP_PUT) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } if (roomId) { ref = DbLock(db, 4, "rooms", roomId, "accountdata", UserGetName(user)); if (!ref) { ref = DbCreate(db, 4, "rooms", roomId, "accountdata", UserGetName(user)); } } else { ref = DbLock(db, 2, "accountdata", UserGetName(user)); if (!ref) { ref = DbCreate(db, 2, "accountdata", UserGetName(user)); } } if (!ref) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } { HashMap *all = DbJson(ref); HashMapSet(all, type, JsonValueObject(JsonDuplicate(request))); } response = HashMapCreate(); finish: if (ref) { DbUnlock(db, ref); } if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); Free(expected); return response; } ROUTE_IMPL(RoutePresence, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; User *user = NULL; DbRef *ref = NULL; Config config; HttpRequestMethod method; char *token = NULL; char *userParam; char *expected = NULL; ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } userParam = ArrayGet(path, 0); method = HttpRequestMethodGet(args->context); if (method == HTTP_GET) { char *name = userParam; char *local = NULL; if (name && name[0] == '@') { size_t n = strcspn(name + 1, ":"); local = StrSubstr(name + 1, 0, n); } ref = DbLock(db, 2, "presence", local ? local : name); Free(local); if (!ref) { response = HashMapCreate(); HashMapSet(response, "presence", JsonValueString("offline")); HashMapSet(response, "last_active_ago", JsonValueInteger(0)); goto finish; } response = JsonDuplicate(DbJson(ref)); goto finish; } if (method != HTTP_PUT) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, NULL); goto finish; } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } expected = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!userParam || !StrEquals(userParam, expected)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } ref = DbLock(db, 2, "presence", UserGetName(user)); if (!ref) { ref = DbCreate(db, 2, "presence", UserGetName(user)); } if (!ref) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } DbJsonSet(ref, JsonDuplicate(request)); response = HashMapCreate(); finish: if (ref) { DbUnlock(db, ref); } if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); Free(expected); return response; } static int SameKeyAlgorithm(char * a, char * b) { size_t i = 0; if (!a || !b) { return 0; } while (a[i] && b[i] && a[i] == b[i] && a[i] != ':') { i++; } return a[i] == ':' && b[i] == ':'; } static HashMap * OtkCounts(HashMap * oneTimeKeys) { HashMap *counts = HashMapCreate(); char *keyId; void *val; if (oneTimeKeys) { while (HashMapIterate(oneTimeKeys, &keyId, &val)) { const char *colon = strchr(keyId, ':'); size_t n = colon ? (size_t) (colon - keyId) : strlen(keyId); char *algorithm = StrSubstr(keyId, 0, n); JsonValue *have = HashMapGet(counts, algorithm); long count = have ? (long) JsonValueAsInteger(have) : 0; JsonValue *old = HashMapSet(counts, algorithm, JsonValueInteger(count + 1)); if (old) { JsonValueFree(old); } Free(algorithm); } } return counts; } void KeyChangesCollect(Db * db, uint64_t from, uint64_t to, Array * out) { DbRef *ref = DbLock(db, 1, "key_changes"); HashMap *seen = HashMapCreate(); Array *list; size_t i; if (!ref) { HashMapFree(seen); return; } list = JsonValueAsArray(HashMapGet(DbJson(ref), "changes")); for (i = 0; list && i < ArraySize(list); i++) { HashMap *e = JsonValueAsObject(ArrayGet(list, i)); char *u = e ? JsonValueAsString(HashMapGet(e, "user")) : NULL; uint64_t s = e ? (uint64_t) JsonValueAsInteger(HashMapGet(e, "seq")) : 0; if (u && s >= from && (!to || s <= to) && !HashMapGet(seen, u)) { HashMapSet(seen, u, JsonValueBoolean(true)); ArrayAdd(out, JsonValueString(u)); } } DbUnlock(db, ref); HashMapFree(seen); } static void KeyChangeRecord(Db * db, char * mxid) { DbRef *ref = DbLock(db, 1, "key_changes"); if (!ref) { ref = DbCreate(db, 1, "key_changes"); } if (!ref) { return; } { HashMap *store = DbJson(ref); Array *list = JsonValueAsArray(HashMapGet(store, "changes")); HashMap *entry = HashMapCreate(); if (!list) { list = ArrayCreate(); HashMapSet(store, "changes", JsonValueArray(list)); } HashMapSet(entry, "user", JsonValueString(mxid)); HashMapSet(entry, "seq", JsonValueInteger((long) RoomStreamPosition(db))); HashMapSet(entry, "ts", JsonValueInteger((long) time(NULL))); ArrayAdd(list, JsonValueObject(entry)); } DbUnlock(db, ref); } ROUTE_IMPL(RouteKeysUpload, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; HashMap *devices = NULL; HashMap *device = NULL; HashMap *oneTimeKeys = NULL; User *user = NULL; Config config; char *token = NULL; char *deviceId = NULL; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } deviceId = UserGetDeviceId(user); devices = UserGetDevices(user); device = (devices && deviceId) ? JsonValueAsObject(HashMapGet(devices, deviceId)) : NULL; if (!device) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNKNOWN, "Unknown device"); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } { HashMap *devKeys = JsonValueAsObject(HashMapGet(request, "device_keys")); if (devKeys) { JsonValue *old = HashMapSet(device, "device_keys", JsonValueObject(JsonDuplicate(devKeys))); if (old) { JsonValueFree(old); } } } oneTimeKeys = JsonValueAsObject(HashMapGet(device, "one_time_keys")); if (!oneTimeKeys) { oneTimeKeys = HashMapCreate(); HashMapSet(device, "one_time_keys", JsonValueObject(oneTimeKeys)); } { HashMap *upload = JsonValueAsObject(HashMapGet(request, "one_time_keys")); char *keyId; void *val; if (upload) { while (HashMapIterate(upload, &keyId, &val)) { JsonValue *old = HashMapSet(oneTimeKeys, keyId, JsonValueDuplicate((JsonValue *) val)); if (old) { JsonValueFree(old); } } } } { HashMap *upload = JsonValueAsObject(HashMapGet(request, "fallback_keys")); HashMap *stored = JsonValueAsObject(HashMapGet(device, "fallback_keys")); if (upload) { char *keyId; void *val; size_t ui = 0; if (!stored) { stored = HashMapCreate(); HashMapSet(device, "fallback_keys", JsonValueObject(stored)); } while (HashMapIterateReentrant(upload, &keyId, &val, &ui)) { char *oldId; void *oldVal; size_t si = 0; JsonValue *old; while (HashMapIterateReentrant(stored, &oldId, &oldVal, &si)) { if (!StrEquals(oldId, keyId) && SameKeyAlgorithm(oldId, keyId)) { JsonValue *removed = HashMapDelete(stored, oldId); if (removed) { JsonValueFree(removed); } } } old = HashMapSet(stored, keyId, JsonValueDuplicate((JsonValue *) val)); if (old) { JsonValueFree(old); } } } } { char *mxid = StrConcat(4, "@", UserGetName(user), ":", config.serverName); KeyChangeRecord(db, mxid); Free(mxid); } response = HashMapCreate(); HashMapSet(response, "one_time_key_counts", JsonValueObject(OtkCounts(oneTimeKeys))); finish: if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); return response; } static int DeviceRequested(JsonValue * filter, char * deviceId) { Array *list; size_t i; if (!filter || JsonValueType(filter) != JSON_ARRAY) { return 1; } list = JsonValueAsArray(filter); if (ArraySize(list) == 0) { return 1; } for (i = 0; i < ArraySize(list); i++) { char *id = JsonValueAsString(ArrayGet(list, i)); if (id && StrEquals(id, deviceId)) { return 1; } } return 0; } ROUTE_IMPL(RouteKeysQuery, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; HashMap *out = NULL; HashMap *masterOut = NULL; HashMap *selfOut = NULL; Config config; char *token = NULL; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } out = HashMapCreate(); masterOut = HashMapCreate(); selfOut = HashMapCreate(); { HashMap *want = JsonValueAsObject(HashMapGet(request, "device_keys")); char *userId; void *filterVal; if (want) { while (HashMapIterate(want, &userId, &filterVal)) { CommonID *id = UserIdParse(userId, config.serverName); User *other; HashMap *devices; HashMap *devOut; int any = 0; if (!id) { continue; } other = UserLock(db, id->local); UserIdFree(id); if (!other) { continue; } devOut = HashMapCreate(); devices = UserGetDevices(other); if (devices) { char *devId; void *devVal; while (HashMapIterate(devices, &devId, &devVal)) { HashMap *dev = JsonValueAsObject(devVal); HashMap *keys = dev ? JsonValueAsObject(HashMapGet(dev, "device_keys")) : NULL; if (keys && DeviceRequested((JsonValue *) filterVal, devId)) { HashMapSet(devOut, devId, JsonValueObject(JsonDuplicate(keys))); any = 1; } } } if (any) { HashMapSet(out, userId, JsonValueObject(devOut)); } else { JsonValueFree(JsonValueObject(devOut)); } { DbRef *xref = DbLock(db, 2, "cross_signing", UserGetName(other)); if (xref) { HashMap *cs = DbJson(xref); HashMap *master = JsonValueAsObject(HashMapGet(cs, "master_key")); HashMap *self = JsonValueAsObject(HashMapGet(cs, "self_signing_key")); if (master) { HashMapSet(masterOut, userId, JsonValueObject(JsonDuplicate(master))); } if (self) { HashMapSet(selfOut, userId, JsonValueObject(JsonDuplicate(self))); } DbUnlock(db, xref); } } UserUnlock(other); } } } response = HashMapCreate(); HashMapSet(response, "device_keys", JsonValueObject(out)); HashMapSet(response, "master_keys", JsonValueObject(masterOut)); HashMapSet(response, "self_signing_keys", JsonValueObject(selfOut)); finish: JsonFree(request); ConfigUnlock(&config); return response; } ROUTE_IMPL(RouteKeysClaim, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; HashMap *out = NULL; Config config; char *token = NULL; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } out = HashMapCreate(); { HashMap *want = JsonValueAsObject(HashMapGet(request, "one_time_keys")); char *userId; void *devicesVal; if (want) { while (HashMapIterate(want, &userId, &devicesVal)) { CommonID *id = UserIdParse(userId, config.serverName); User *other; HashMap *devices; HashMap *devOut; char *devId; void *algVal; if (!id) { continue; } other = UserLock(db, id->local); UserIdFree(id); if (!other) { continue; } devOut = HashMapCreate(); devices = UserGetDevices(other); { int any = 0; if (devices && JsonValueType((JsonValue *) devicesVal) == JSON_OBJECT) { HashMap *wanted = JsonValueAsObject((JsonValue *) devicesVal); while (HashMapIterate(wanted, &devId, &algVal)) { char *algorithm = JsonValueAsString((JsonValue *) algVal); HashMap *dev = JsonValueAsObject(HashMapGet(devices, devId)); HashMap *otks = dev ? JsonValueAsObject(HashMapGet(dev, "one_time_keys")) : NULL; char *keyId; void *keyVal; int found = 0; if (!algorithm) { continue; } if (otks) { size_t oi = 0; while (HashMapIterateReentrant(otks, &keyId, &keyVal, &oi)) { if (strncmp(keyId, algorithm, strlen(algorithm)) == 0 && keyId[strlen(algorithm)] == ':') { HashMap *chosenDev; chosenDev = JsonValueAsObject(HashMapGet(devOut, devId)); if (!chosenDev) { chosenDev = HashMapCreate(); HashMapSet(devOut, devId, JsonValueObject(chosenDev)); } HashMapSet(chosenDev, keyId, JsonValueDuplicate((JsonValue *) keyVal)); any = 1; found = 1; { JsonValue *removed = HashMapDelete(otks, keyId); if (removed) { JsonValueFree(removed); } } break; } } } if (!found) { HashMap *fb = JsonValueAsObject(HashMapGet(dev, "fallback_keys")); char *fbId; void *fbVal; if (fb) { size_t fi = 0; while (HashMapIterateReentrant(fb, &fbId, &fbVal, &fi)) { if (strncmp(fbId, algorithm, strlen(algorithm)) == 0 && fbId[strlen(algorithm)] == ':') { HashMap *chosenDev = JsonValueAsObject(HashMapGet(devOut, devId)); JsonValue *fbKey; HashMap *fbObj; if (!chosenDev) { chosenDev = HashMapCreate(); HashMapSet(devOut, devId, JsonValueObject(chosenDev)); } fbKey = JsonValueDuplicate((JsonValue *) fbVal); fbObj = JsonValueAsObject(fbKey); if (fbObj) { HashMapSet(fbObj, "fallback", JsonValueBoolean(1)); } HashMapSet(chosenDev, fbId, fbKey); any = 1; break; } } } } } } if (any) { HashMapSet(out, userId, JsonValueObject(devOut)); } else { JsonValueFree(JsonValueObject(devOut)); } } UserUnlock(other); } } } response = HashMapCreate(); HashMapSet(response, "one_time_keys", JsonValueObject(out)); finish: JsonFree(request); ConfigUnlock(&config); return response; } ROUTE_IMPL(RouteCrossSigningUpload, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; User *user = NULL; DbRef *ref = NULL; Config config; char *token = NULL; const char *fields[] = { "master_key", "self_signing_key", "user_signing_key" }; size_t i; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } ref = DbLock(db, 2, "cross_signing", UserGetName(user)); if (!ref) { ref = DbCreate(db, 2, "cross_signing", UserGetName(user)); } if (!ref) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } for (i = 0; i < sizeof(fields) / sizeof(fields[0]); i++) { HashMap *key = JsonValueAsObject(HashMapGet(request, fields[i])); if (key) { JsonValue *old = HashMapSet(DbJson(ref), (char *) fields[i], JsonValueObject(JsonDuplicate(key))); if (old) { JsonValueFree(old); } } } response = HashMapCreate(); finish: if (ref) { DbUnlock(db, ref); } if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); return response; } ROUTE_IMPL(RouteSignaturesUpload, path, argp) { RouteArgs *args = argp; HashMap *response = NULL; HashMap *request = NULL; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } request = JsonDecode(HttpServerStream(args->context)); response = HashMapCreate(); HashMapSet(response, "failures", JsonValueObject(HashMapCreate())); JsonFree(request); return response; } ROUTE_IMPL(RouteKeysChanges, path, argp) { RouteArgs *args = argp; HashMap *response; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_GET) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } { HashMap *params = HttpRequestParams(args->context); Array *changed = ArrayCreate(); uint64_t from = 0; uint64_t to = 0; if (params) { char *f = HashMapGet(params, "from"); char *t = HashMapGet(params, "to"); from = f ? strtoull(f, NULL, 10) : 0; to = t ? strtoull(t, NULL, 10) : 0; } KeyChangesCollect(args->matrixArgs->db, from, to, changed); response = HashMapCreate(); HashMapSet(response, "changed", JsonValueArray(changed)); HashMapSet(response, "left", JsonValueArray(ArrayCreate())); } return response; } static void QueueToDevice(Db * db, char * user, char * device, HashMap * event) { DbRef *ref = DbLock(db, 3, "to_device", user, device); if (!ref) { ref = DbCreate(db, 3, "to_device", user, device); } if (!ref) { return; } { HashMap *store = DbJson(ref); Array *events = JsonValueAsArray(HashMapGet(store, "events")); if (!events) { events = ArrayCreate(); HashMapSet(store, "events", JsonValueArray(events)); } ArrayAdd(events, JsonValueObject(event)); } DbUnlock(db, ref); } ROUTE_IMPL(RouteSendToDevice, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; User *user = NULL; Config config; char *token = NULL; char *eventType; char *sender = NULL; eventType = ArraySize(path) >= 1 ? ArrayGet(path, 0) : NULL; if (HttpRequestMethodGet(args->context) != HTTP_PUT || !eventType) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } sender = StrConcat(4, "@", UserGetName(user), ":", config.serverName); request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } { HashMap *messages = JsonValueAsObject(HashMapGet(request, "messages")); char *userId; void *devicesVal; if (messages) { while (HashMapIterate(messages, &userId, &devicesVal)) { CommonID *id = UserIdParse(userId, config.serverName); HashMap *devices; char *devId; void *contentVal; if (!id) { continue; } devices = JsonValueAsObject((JsonValue *) devicesVal); if (!devices) { UserIdFree(id); continue; } while (HashMapIterate(devices, &devId, &contentVal)) { HashMap *event; HashMap *content = JsonValueAsObject((JsonValue *) contentVal); HashMap *targets = NULL; char *listId; void *unused; if (!content) { continue; } if (StrEquals(devId, "*")) { User *target = UserLock(db, id->local); if (target) { HashMap *allDevices = UserGetDevices(target); targets = HashMapCreate(); if (allDevices) { while (HashMapIterate(allDevices, &listId, &unused)) { HashMapSet(targets, listId, JsonValueBoolean(true)); } } UserUnlock(target); } } else { targets = HashMapCreate(); HashMapSet(targets, devId, JsonValueBoolean(true)); } if (targets) { char *targetId; void *tv; while (HashMapIterate(targets, &targetId, &tv)) { event = HashMapCreate(); HashMapSet(event, "type", JsonValueString(eventType)); HashMapSet(event, "sender", JsonValueString(sender)); HashMapSet(event, "content", JsonValueObject(JsonDuplicate(content))); QueueToDevice(db, id->local, targetId, event); } JsonValueFree(JsonValueObject(targets)); } } UserIdFree(id); } } } response = HashMapCreate(); finish: if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); Free(sender); return response; }