/* * RoutesAuth.c - bundled Matrix route handlers. * * merged from: RouteLogin.c, RouteLogout.c, RouteRegister.c, RouteRefresh.c, RouteTokenValid.c, RouteRequestToken.c, RouteUiaFallback.c, RouteChangePwd.c, RouteWhoami.c, RouteVersions.c, RouteCapabilities.c, RouteFederationVersion.c, RoutePrivileges.c, RouteProcControl.c, RouteDeactivate.c, RouteAdminDeactivate.c, RouteAdminTokens.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 ROUTE_IMPL(RouteLogin, path, argp) { RouteArgs *args = argp; HashMap *request = NULL; HashMap *response = NULL; Array *enabledFlows; HashMap *pwdFlow; JsonValue *val; HashMap *identifier; LoginRequest loginRequest; LoginRequestUserIdentifier userIdentifier; CommonID *userId = NULL; Db *db = args->matrixArgs->db; User *user; UserLoginInfo *loginInfo; char *fullUsername; char *type; char *initialDeviceDisplayName; char *deviceId; char *password; int refreshToken; 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); } (void) path; memset(&loginRequest, 0, sizeof(LoginRequest)); memset(&userIdentifier, 0, sizeof(LoginRequestUserIdentifier)); switch (HttpRequestMethodGet(args->context)) { case HTTP_GET: response = HashMapCreate(); enabledFlows = ArrayCreate(); pwdFlow = HashMapCreate(); HashMapSet(pwdFlow, "type", JsonValueString("m.login.password")); ArrayAdd(enabledFlows, JsonValueObject(pwdFlow)); HashMapSet(response, "flows", JsonValueArray(enabledFlows)); break; case HTTP_POST: request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); break; } val = HashMapGet(request, "type"); if (val && JsonValueType(val) == JSON_STRING && StrEquals(JsonValueAsString(val), "m.login.application_service")) { char *asToken = NULL; char *asSender; char *asUser; Appservice *as; JsonValue *identifierValue; JsonValue *deviceValue; response = MatrixGetAccessToken(args->context, &asToken); if (response) { goto finish; } as = AppserviceFromToken(asToken); if (!as) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } identifierValue = HashMapGet(request, "identifier"); if (!identifierValue || JsonValueType(identifierValue) != JSON_OBJECT) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_MISSING_PARAM, NULL); goto finish; } identifier = JsonValueAsObject(identifierValue); val = HashMapGet(identifier, "type"); if (!val || JsonValueType(val) != JSON_STRING || !StrEquals(JsonValueAsString(val), "m.id.user")) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, NULL); goto finish; } if (!LoginRequestUserIdentifierFromJson(identifier, &userIdentifier, &msg)) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } userId = UserIdParse(userIdentifier.user, config.serverName); if (!userId) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, NULL); goto finish; } asUser = StrConcat(4, "@", userId->local, ":", config.serverName); asSender = AppserviceSender(as, config.serverName); if (!AppserviceAllowsUser(as, asUser) && (!asSender || !StrEquals(asUser, asSender))) { Free(asUser); if (asSender) { Free(asSender); } HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } deviceValue = HashMapGet(request, "device_id"); deviceId = deviceValue && JsonValueType(deviceValue) == JSON_STRING ? JsonValueAsString(deviceValue) : "APPSERVICE"; response = HashMapCreate(); HashMapSet(response, "access_token", JsonValueString(asToken)); HashMapSet(response, "device_id", JsonValueString(deviceId)); HashMapSet(response, "user_id", JsonValueString(asUser)); HashMapSet(response, "well_known", JsonValueObject(MatrixClientWellKnown( config.baseUrl, config.identityServer))); Free(asUser); if (asSender) { Free(asSender); } goto finish; } if (!LoginRequestFromJson(request, &loginRequest, &msg)) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); break; } if (loginRequest.type != REQUEST_TYPE_PASSWORD) { msg = "Unsupported login type."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); break; } identifier = loginRequest.identifier; val = HashMapGet(identifier, "type"); if (!val) { msg = "No login identifier type set."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_MISSING_PARAM, NULL); break; } if (JsonValueType(val) != JSON_STRING) { msg = "Invalid login identifier type."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); break; } type = JsonValueAsString(val); if (!StrEquals(type, "m.id.user")) { msg = "Invalid login identifier type."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); break; } if (!LoginRequestUserIdentifierFromJson(identifier, &userIdentifier, &msg)) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); break; } userId = UserIdParse(userIdentifier.user, config.serverName); if (!userId) { msg = "Invalid user ID."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); break; } if (!ParserServerNameEquals(userId->server, config.serverName) || !UserExists(db, userId->local)) { msg = "Unknown user ID."; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); break; } deviceId = loginRequest.device_id; initialDeviceDisplayName =loginRequest.initial_device_display_name; password = loginRequest.password; refreshToken = loginRequest.refresh_token; user = UserLock(db, userId->local); if (!user) { msg = "Couldn't lock user."; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); break; } if (UserDeactivated(user)) { UserUnlock(user); HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_USER_DEACTIVATED, NULL); break; } loginInfo = UserLogin(user, password, deviceId, initialDeviceDisplayName, refreshToken); if (!loginInfo) { msg = "Invalid creditentials for user."; UserUnlock(user); HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); break; } response = HashMapCreate(); HashMapSet(response, "access_token", JsonValueString(loginInfo->accessToken->string)); HashMapSet(response, "device_id", JsonValueString(loginInfo->accessToken->deviceId)); if (refreshToken) { HashMapSet(response, "expires_in_ms", JsonValueInteger(loginInfo->accessToken->lifetime)); HashMapSet(response, "refresh_token", JsonValueString(loginInfo->refreshToken)); } fullUsername = StrConcat(4, "@", UserGetName(user), ":", config.serverName); HashMapSet(response, "user_id", JsonValueString(fullUsername)); Free(fullUsername); HashMapSet(response, "well_known", JsonValueObject( MatrixClientWellKnown(config.baseUrl, config.identityServer))); UserAccessTokenFree(loginInfo->accessToken); Free(loginInfo->refreshToken); Free(loginInfo); UserUnlock(user); break; default: msg = "Route only accepts GET and POST."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); break; } finish: UserIdFree(userId); JsonFree(request); ConfigUnlock(&config); LoginRequestFree(&loginRequest); LoginRequestUserIdentifierFree(&userIdentifier); 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 ROUTE_IMPL(RouteLogout, path, argp) { RouteArgs *args = argp; HashMap *response = NULL; char *tokenstr; char *msg; Db *db = args->matrixArgs->db; User *user; if (HttpRequestMethodGet(args->context) != HTTP_POST) { msg = "This route only accepts POST."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, msg); } response = MatrixGetAccessToken(args->context, &tokenstr); if (response) { return response; } user = UserAuthenticate(db, tokenstr); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); return MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); } if (ArraySize(path) == 1) { if (!StrEquals(ArrayGet(path, 0), "all")) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } if (!UserDeleteTokens(user, NULL)) { /* If we can't delete all of our tokens, then something is * wrong. */ HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } response = HashMapCreate(); } else { if (!UserDeleteToken(user, tokenstr)) { msg = "Internal server error: couldn't delete token."; HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, msg); goto finish; } response = HashMapCreate(); } finish: UserUnlock(user); 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 #include static Array * RouteRegisterRegFlow(void) { Array *response = ArrayCreate(); if (!response) { return NULL; } ArrayAdd(response, UiaStageBuild("m.login.registration_token", NULL)); return response; } ROUTE_IMPL(RouteRegister, path, argp) { RouteArgs *args = argp; HashMap *request = NULL; HashMap *response = NULL; RegistrationRequest regReq; char *kind; char *fullUsername; char *msg; char *username; Db *db = args->matrixArgs->db; User *user = NULL; Array *uiaFlows = NULL; int uiaResult; char *session; DbRef *sessionRef; Config config; regReq.username = NULL; regReq.password = NULL; regReq.device_id = NULL; regReq.initial_device_display_name = NULL; regReq.refresh_token = 0; regReq.inhibit_login = 0; 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); } if (ArraySize(path) == 0) { if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, NULL); goto end; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto end; } if (!RegistrationRequestFromJson(request, ®Req, &msg)) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, msg); goto end; } if (regReq.username) { if (!UserValidate(regReq.username, config.serverName)) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_USERNAME, NULL); goto finish; } if (UserExists(db, regReq.username)) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_USER_IN_USE, NULL); goto finish; } } uiaFlows = ArrayCreate(); ArrayAdd(uiaFlows, RouteRegisterRegFlow()); if (config.registration) { ArrayAdd(uiaFlows, UiaDummyFlow()); } uiaResult = UiaComplete(uiaFlows, args->context, db, request, &response, config); if (uiaResult < 0) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } else if (!uiaResult) { /* UiaComplete() sets the response and status for us. */ goto finish; } kind = HashMapGet(HttpRequestParams(args->context), "kind"); /* We don't support guest accounts yet */ if (kind && !StrEquals(kind, "user")) { msg = "Guest accounts are currently not supported"; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } if (!regReq.password) { msg = "'password' field is unset"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_MISSING_PARAM, msg); goto finish; } /* All of the other fields are optional, we don't have to check * them. */ user = UserCreate(db, regReq.username, regReq.password); response = HashMapCreate(); fullUsername = StrConcat(4, "@", UserGetName(user), ":", config.serverName); HashMapSet(response, "user_id", JsonValueString(fullUsername)); Free(fullUsername); HttpResponseStatus(args->context, HTTP_OK); if (!regReq.inhibit_login) { UserLoginInfo *loginInfo = UserLogin(user, regReq.password, regReq.device_id, regReq.initial_device_display_name, regReq.refresh_token); HashMapSet(response, "access_token", JsonValueString(loginInfo->accessToken->string)); HashMapSet(response, "device_id", JsonValueString(loginInfo->accessToken->deviceId)); if (regReq.refresh_token) { HashMapSet(response, "expires_in_ms", JsonValueInteger(loginInfo->accessToken->lifetime)); HashMapSet(response, "refresh_token", JsonValueString(loginInfo->refreshToken)); } UserAccessTokenFree(loginInfo->accessToken); Free(loginInfo->refreshToken); Free(loginInfo); } session = JsonValueAsString(JsonGet(request, 2, "auth", "session")); sessionRef = DbLock(db, 2, "user_interactive", session); if (sessionRef) { char *token = JsonValueAsString(HashMapGet(DbJson(sessionRef), "registration_token")); /* Grant the privileges specified by the given token */ if (token) { RegTokenInfo *info = RegTokenGetInfo(db, token); if (info) { UserSetPrivileges(user, UserDecodePrivileges(info->grants)); RegTokenClose(info); RegTokenFree(info); } } DbUnlock(db, sessionRef); } else { Log(LOG_WARNING, "Unable to lock UIA session reference to check"); Log(LOG_WARNING, "privileges for user registration."); } Log(LOG_INFO, "Registered user '%s'", UserGetName(user)); UserUnlock(user); finish: UiaFlowsFree(uiaFlows); RegistrationRequestFree(®Req); JsonFree(request); } else { if (HttpRequestMethodGet(args->context) == HTTP_GET && StrEquals(ArrayGet(path, 0), "available")) { username = HashMapGet( HttpRequestParams(args->context), "username"); if (!username) { msg = "'username' path parameter is not set."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_MISSING_PARAM, msg); } else if (!UserValidate(username, config.serverName)) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_USERNAME, NULL); } else if (!UserExists(db, username)) { response = HashMapCreate(); HashMapSet(response, "available", JsonValueBoolean(1)); } else { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_USER_IN_USE, NULL); } } else { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_UNRECOGNIZED, NULL); } } end: ConfigUnlock(&config); 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 ROUTE_IMPL(RouteRefresh, path, argp) { RouteArgs *args = argp; HashMap *request; HashMap *response = NULL; JsonValue *val; char *refreshToken; char *oldAccessToken; UserAccessToken *newAccessToken; char *deviceId; char *msg; Db *db = args->matrixArgs->db; User *user = NULL; DbRef *rtRef = NULL; DbRef *oAtRef = NULL; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_POST) { msg = "This route only accepts POST."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, msg); } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_NOT_JSON, NULL); } val = HashMapGet(request, "refresh_token"); if (!val || JsonValueType(val) != JSON_STRING) { msg = "'refresh_token' is unset or not a string."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } refreshToken = JsonValueAsString(val); /* Get the refresh token object */ rtRef = DbLock(db, 3, "tokens", "refresh", refreshToken); if (!rtRef) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } /* Get the access token and device the refresh token refreshes */ oldAccessToken = JsonValueAsString(HashMapGet(DbJson(rtRef), "refreshes")); oAtRef = DbLock(db, 3, "tokens", "access", oldAccessToken); if (!oAtRef) { Log(LOG_ERR, "Refresh token '%s' points to an access token that doesn't exist.", refreshToken); Log(LOG_WARNING, "This refresh token will be deleted."); HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); DbUnlock(db, rtRef); DbDelete(db, 3, "tokens", "refresh", refreshToken); rtRef = NULL; goto finish; } /* Get the user associated with the access token and device */ user = UserLock(db, JsonValueAsString(HashMapGet(DbJson(oAtRef), "user"))); if (!user) { Log(LOG_ERR, "Access token '%s' points to a user that doesn't exist.", oldAccessToken); Log(LOG_WARNING, "This access token will be deleted."); HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); DbUnlock(db, rtRef); DbDelete(db, 3, "tokens", "refresh", refreshToken); DbUnlock(db, oAtRef); DbDelete(db, 3, "tokens", "access", oldAccessToken); rtRef = NULL; oAtRef = NULL; goto finish; } /* Generate a new access token associated with the device and user. */ deviceId = JsonValueAsString(HashMapGet(DbJson(oAtRef), "device")); newAccessToken = UserAccessTokenGenerate(user, deviceId, 1); UserAccessTokenSave(db, newAccessToken); /* Replace old access token in User */ JsonValueFree(JsonSet(UserGetDevices(user), JsonValueString(newAccessToken->string), 2, deviceId, "accessToken")); /* Delete old access token */ DbUnlock(db, oAtRef); DbDelete(db, 3, "tokens", "access", oldAccessToken); /* Update the refresh token to point to the new access token */ JsonValueFree(HashMapSet(DbJson(rtRef), "refreshes", JsonValueString(newAccessToken->string))); /* Return the new access token and expiration timestamp to the * client */ response = HashMapCreate(); HashMapSet(response, "access_token", JsonValueString(newAccessToken->string)); HashMapSet(response, "expires_in_ms", JsonValueInteger(newAccessToken->lifetime)); UserAccessTokenFree(newAccessToken); finish: JsonFree(request); DbUnlock(db, rtRef); UserUnlock(user); 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 ROUTE_IMPL(RouteTokenValid, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; HashMap *request = NULL; RegTokenInfo *info = NULL; char *tokenstr; char *msg; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_GET) { msg = "This route only accepts GET."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, msg); } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_NOT_JSON, NULL); } tokenstr = JsonValueAsString(HashMapGet(request, "token")); if (!tokenstr || !RegTokenExists(db, tokenstr)) { response = HashMapCreate(); JsonFree(request); HashMapSet(response, "valid", JsonValueBoolean(0)); return response; } info = RegTokenGetInfo(db, tokenstr); response = HashMapCreate(); if (!RegTokenValid(info)) { JsonFree(request); RegTokenClose(info); RegTokenFree(info); HashMapSet(response, "valid", JsonValueBoolean(0)); return response; } RegTokenClose(info); RegTokenFree(info); HashMapSet(response, "valid", JsonValueBoolean(1)); 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 ROUTE_IMPL(RouteRequestToken, path, argp) { RouteArgs *args = argp; char *type = ArrayGet(path, 0); HashMap *request; HashMap *response; char *msg; RequestToken reqTok; reqTok.client_secret = NULL; reqTok.next_link = NULL; reqTok.id_access_token = NULL; reqTok.id_server = NULL; reqTok.email = NULL; reqTok.country = NULL; reqTok.phone_number = NULL; reqTok.send_attempt = -1; if (HttpRequestMethodGet(args->context) != HTTP_POST) { msg = "This route only accepts POST."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, msg); } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_NOT_JSON, NULL); } if (!RequestTokenFromJson(request, &reqTok, &msg)) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (!reqTok.client_secret) { msg = "'client_secret' is not set"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (strlen(reqTok.client_secret) > 255 || StrBlank(reqTok.client_secret)) { msg = "'client_secret' is blank or too long"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (reqTok.send_attempt == -1) { msg = "Invalid or inexistent 'send_attempt'"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (!reqTok.next_link) { msg = "'next_link' is not set"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (!reqTok.id_access_token) { msg = "'id_access_token' is not set"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (!reqTok.id_server) { msg = "'id_server' is not set"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (StrEquals(type, "email")) { if (!reqTok.email) { msg = "Type is set to 'email' yet none was set"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } } else if (StrEquals(type, "msisdn")) { if (!reqTok.country) { msg = "Type is set to 'msisdn' yet no country is set"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (strlen(reqTok.country) != 2) { msg = "Invalid country tag, length must be 2"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (!reqTok.phone_number) { msg = "Type is set to 'msisdn' yet phone_number is unset"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } } else { /* Should not be possible */ HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_THREEPID_DENIED, NULL); finish: JsonFree(request); RequestTokenFree(&reqTok); 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 ROUTE_IMPL(RouteUiaFallback, path, argp) { RouteArgs *args = argp; Stream *stream = HttpServerStream(args->context); HashMap *requestParams = HttpRequestParams(args->context); char *authType = ArrayGet(path, 0); char *sessionId; char *msg; if (!authType) { /* This should never happen */ Log(LOG_ERR, "Programmer error in RouteUiaFallback()!"); HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, NULL); } if (HttpRequestMethodGet(args->context) == HTTP_POST) { HashMap *request; HashMap *response; int uiaResult; Config config; Array *flows; Array *flow; ConfigLock(args->matrixArgs->db, &config); if (!config.ok) { Log(LOG_ERR, "%s", config.err); HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } request = JsonDecode(HttpServerStream(args->context)); if (!request) { ConfigUnlock(&config); HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_NOT_JSON, NULL); } flow = ArrayCreate(); flows = ArrayCreate(); ArrayAdd(flow, UiaStageBuild(authType, NULL)); ArrayAdd(flows, flow); uiaResult = UiaComplete(flows, args->context, args->matrixArgs->db, request, &response, config); UiaFlowsFree(flows); if (uiaResult < 0) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); } else if (uiaResult) { response = HashMapCreate(); } JsonFree(request); ConfigUnlock(&config); return response; } else if (HttpRequestMethodGet(args->context) != HTTP_GET) { msg = "Route only supports GET."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, msg); } sessionId = HashMapGet(requestParams, "session"); if (!sessionId) { msg = "'session' parameter is unset."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_MISSING_PARAM, msg); } HttpResponseHeader(args->context, "Content-Type", "text/html"); HttpSendHeaders(args->context); HtmlBegin(stream, "Authentication"); if (StrEquals(authType, "m.login.password")) { HtmlBeginForm(stream, "auth-form"); StreamPuts(stream, "" "" "" "" "
" ""); HtmlEndForm(stream); HtmlBeginJs(stream); StreamPrintf(stream, "function buildRequest() {" " let user = document.getElementById('user').value;" " let pass = document.getElementById('password').value;" " if (!user || !pass) {" " setFormError('Please specify a username and password.');" " return false;" " }" " return {" " auth: {" " type: '%s'," " identifier: {" " type: 'm.id.user'," " user: user" " }," " password: pass," " session: '%s'" " }" " };" "}", authType, sessionId); HtmlEndJs(stream); } else if (StrEquals(authType, "m.login.registration_token")) { HtmlBeginForm(stream, "auth-form"); StreamPuts(stream, "" "" "
" ""); HtmlEndForm(stream); HtmlBeginJs(stream); StreamPrintf(stream, "function buildRequest() {" " let token = document.getElementById('token').value;" " if (!token) { " " setFormError('Please specify a registration token.');" " return false;" " }" " return {" " auth: {" " type: '%s'," " session: '%s'," " token: token" " }" " };" "}", authType, sessionId); HtmlEndJs(stream); } /* * TODO: implement m.login.recaptcha, m.login.sso, * m.login.email.identity, m.login.msisdn here */ else { HttpResponseStatus(args->context, HTTP_NOT_FOUND); StreamPrintf(stream, "

Unknown auth type: %s

", authType); goto finish; } HtmlBeginJs(stream); StreamPrintf(stream, "function processResponse(xhr) {" " let r = JSON.parse(xhr.responseText);" " console.log(r);" " if (xhr.status == 200 || r.completed.includes('%s')) {" " if (window.onAuthDone) {" " window.onAuthDone();" " } else if (window.opener && window.opener.postMessage) {" " window.opener.postMessage('authDone', '*');" " } else {" " setFormError('Client error.');" " }" " } else if (r.session != '%s') {" " setFormError('Invalid session.');" " } else {" " setFormError('Invalid credentials.');" " }" "}", authType, sessionId); StreamPuts(stream, "onFormSubmit('auth-form', (frm) => {" " let request = buildRequest();" " if (request) {" " jsonRequest('POST', window.location.pathname, request, processResponse);" " }" "});"); HtmlEndJs(stream); finish: HtmlEnd(stream); return NULL; } /* * 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 static Array * PasswordFlow(void) { Array *ret = ArrayCreate(); if (!ret) { return NULL; } ArrayAdd(ret, UiaStageBuild("m.login.password", NULL)); return ret; } ROUTE_IMPL(RouteChangePwd, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; User *user = NULL; HashMap *request = NULL; HashMap *response = NULL; JsonValue *val = NULL; Array *uiaFlows = NULL; int uiaResult; int logoutDevices = 1; char *token; char *newPassword; 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); } (void) path; if (HttpRequestMethodGet(args->context) != HTTP_POST) { msg = "Route only supports POST."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); goto finish; } 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; } uiaFlows = ArrayCreate(); ArrayAdd(uiaFlows, PasswordFlow()); uiaResult = UiaComplete(uiaFlows, args->context, db, request, &response, config); UiaFlowsFree(uiaFlows); if (uiaResult < 0) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } else if (!uiaResult) { goto finish; } newPassword = JsonValueAsString(HashMapGet(request, "new_password")); if (!newPassword) { msg = "'new_password' is unset or not a string."; JsonFree(request); HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } val = HashMapGet(request, "logout_devices"); if (val) { logoutDevices = JsonValueAsBoolean(val); } /* Let's authenticate the user */ user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } UserSetPassword(user, newPassword); /* We might want to logout all extra devices */ if (logoutDevices) { /* Deletes all tokens except the passed token */ UserDeleteTokens(user, token); } response = HashMapCreate(); finish: ConfigUnlock(&config); 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 ROUTE_IMPL(RouteWhoami, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; User *user = NULL; char *token; char *userID; char *deviceID; 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); } (void) path; /* Get the request */ response = MatrixGetAccessToken(args->context, &token); if (response) { /* No token? */ goto finish; } /* Authenticate with our token */ user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } response = HashMapCreate(); userID = StrConcat(4, "@", UserGetName(user), ":", config.serverName); deviceID = StrDuplicate(UserGetDeviceId(user)); UserUnlock(user); HashMapSet(response, "device_id", JsonValueString(deviceID)); HashMapSet(response, "user_id", JsonValueString(userID)); Free(userID); Free(deviceID); finish: ConfigUnlock(&config); 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(RouteVersions, path, argp) { HashMap *response = HashMapCreate(); Array *versions = ArrayCreate(); (void) path; (void) argp; #define DECLARE_SPEC_VERSION(x) ArrayAdd(versions, JsonValueString(x)) DECLARE_SPEC_VERSION("v1.2"); DECLARE_SPEC_VERSION("v1.3"); DECLARE_SPEC_VERSION("v1.4"); DECLARE_SPEC_VERSION("v1.5"); DECLARE_SPEC_VERSION("v1.6"); /* The curently supported version. */ DECLARE_SPEC_VERSION("v1.7"); #undef DECLARE_SPEC_VERSION HashMapSet(response, "versions", JsonValueArray(versions)); 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 ROUTE_IMPL(RouteCapabilities, path, argp) { HashMap *response; HashMap *capabilities; HashMap *roomVersions; (void) path; (void) argp; response = HashMapCreate(); capabilities = HashMapCreate(); roomVersions = HashMapCreate(); JsonSet(capabilities, JsonValueBoolean(1), 2, "m.change_password", "enabled"); JsonSet(capabilities, JsonValueBoolean(1), 2, "m.set_displayname", "enabled"); JsonSet(capabilities, JsonValueBoolean(1), 2, "m.set_avatar_url", "enabled"); JsonSet(capabilities, JsonValueBoolean(1), 2, "m.3pid_changes", "enabled"); /* The storage layer is version-agnostic, so advertise the common * stable room versions and default to 10 (what RoomCreate uses). */ { char *versions[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" }; size_t i; for (i = 0; i < sizeof(versions) / sizeof(versions[0]); i++) { HashMapSet(roomVersions, versions[i], JsonValueString("stable")); } } JsonSet(capabilities, JsonValueString("10"), 2, "m.room_versions", "default"); JsonSet(capabilities, JsonValueObject(roomVersions), 2, "m.room_versions", "available"); HashMapSet(response, "capabilities", JsonValueObject(capabilities)); return response; } /* * Copyright (C) 2022-2024 Jordan Bancino <@jordan:bancino.net> 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 ROUTE_IMPL(RouteFederationVersion,path,argp) { (void) path; (void) argp; HashMap *response; response = MatrixFederationVersion(); 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(RoutePrivileges, path, argp) { RouteArgs *args = argp; HashMap *response; char *token; User *user = NULL; HashMap *request = NULL; JsonValue *val; int privileges; char *msg; 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_GRANT_PRIVILEGES)) { msg = "User doesn't have the GRANT_PRIVILEGES privilege"; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); goto finish; } /* If a user was specified in the URL, switch to that user after * verifying that the current user has privileges to do so */ if (ArraySize(path) == 1) { UserUnlock(user); user = UserLock(args->matrixArgs->db, ArrayGet(path, 0)); if (!user) { msg = "Unknown user."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } } switch (HttpRequestMethodGet(args->context)) { case HTTP_POST: case HTTP_PUT: case HTTP_DELETE: request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); break; } val = HashMapGet(request, "privileges"); if (!val || JsonValueType(val) != JSON_ARRAY) { msg = "'privileges' is unset or not an array."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); break; } switch (HttpRequestMethodGet(args->context)) { case HTTP_POST: privileges = UserDecodePrivileges(JsonValueAsArray(val)); break; case HTTP_PUT: privileges = UserGetPrivileges(user); privileges |= UserDecodePrivileges(JsonValueAsArray(val)); break; case HTTP_DELETE: privileges = UserGetPrivileges(user); privileges &= ~UserDecodePrivileges(JsonValueAsArray(val)); break; default: /* Impossible */ privileges = USER_NONE; break; } if (!UserSetPrivileges(user, privileges)) { msg = "Internal server error: couldn't set privileges."; HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, msg); break; } /* Fall through */ case HTTP_GET: response = HashMapCreate(); HashMapSet(response, "privileges", JsonValueArray(UserEncodePrivileges(UserGetPrivileges(user)))); break; default: msg = "Route only accepts POST, PUT, DELETE, and GET."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); goto finish; break; } finish: 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 ROUTE_IMPL(RouteProcControl, path, argp) { RouteArgs *args = argp; char *op = ArrayGet(path, 0); HashMap *response; char *token; char *msg; User *user = NULL; 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_PROC_CONTROL)) { msg = "User doesn't have PROC_CONTROL privilege."; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); goto finish; } msg = "Unknown operation."; switch (HttpRequestMethodGet(args->context)) { case HTTP_POST: if (StrEquals(op, "restart")) { raise(SIGUSR1); } else if (StrEquals(op, "shutdown")) { raise(SIGINT); } else { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); goto finish; } break; case HTTP_GET: if (StrEquals(op, "stats")) { size_t allocated = MemoryAllocated(); response = HashMapCreate(); HashMapSet(response, "version", JsonValueString(TELODENDRIA_VERSION)); HashMapSet(response, "memory_allocated", JsonValueInteger(allocated)); goto finish; } else { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); goto finish; } default: HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, msg); goto finish; break; } response = HashMapCreate(); finish: UserUnlock(user); 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(RouteDeactivate, path, argp) { RouteArgs *args = argp; HashMap *response = NULL; HashMap *request = NULL; int uiaResult; char *tokenstr = NULL; Array *uiaFlows; Db *db = args->matrixArgs->db; User *user = NULL; Config config; char *msg; (void) path; ConfigLock(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; } if (HttpRequestMethodGet(args->context) != HTTP_POST) { msg = "Route only accepts 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; } uiaFlows = ArrayCreate(); response = MatrixGetAccessToken(args->context, &tokenstr); if (response) { /* No access token provided, require password */ Array *passwordFlow = ArrayCreate(); ArrayAdd(passwordFlow, UiaStageBuild("m.login.password", NULL)); ArrayAdd(uiaFlows, passwordFlow); } else { /* Access token provided, no further authentication needed. */ ArrayAdd(uiaFlows, UiaDummyFlow()); JsonFree(response); } uiaResult = UiaComplete(uiaFlows, args->context, db, request, &response, config); UiaFlowsFree(uiaFlows); if (uiaResult < 0) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } else if (!uiaResult) { goto finish; } if (tokenstr) { user = UserAuthenticate(db, tokenstr); } else { /* No access token, we have to get the user off UIA */ char *session = JsonValueAsString(JsonGet(request, 2, "auth", "session")); DbRef *sessionRef = DbLock(db, 2, "user_interactive", session); char *userId = JsonValueAsString(HashMapGet(DbJson(sessionRef), "user")); user = UserLock(db, userId); DbUnlock(db, sessionRef); } if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } if (!UserDeleteTokens(user, NULL) || !UserDeactivate(user, NULL, NULL)) { msg = "Internal server error: couldn't remove user properly."; HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, msg); goto finish; } response = HashMapCreate(); /* * "This must be success if the homeserver has no identifiers to * unbind for the user." */ HashMapSet(response, "id_server_unbind_result", JsonValueString("success")); finish: JsonFree(request); UserUnlock(user); ConfigUnlock(&config); 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 ROUTE_IMPL(RouteAdminDeactivate, path, argp) { RouteArgs *args = argp; HashMap *request = NULL; HashMap *response = NULL; JsonValue *val; char *reason = "Deactivated by admin"; char *removedLocalpart = ArrayGet(path, 0); char *token; Db *db = args->matrixArgs->db; User *user = NULL; User *removed = NULL; HttpRequestMethod method = HttpRequestMethodGet(args->context); if ((method != HTTP_DELETE) && (method != HTTP_PUT)) { char * msg = "Route only supports DELETE and PUT as for now."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, msg); } if (method == HTTP_DELETE) { request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_NOT_JSON, NULL); } val = HashMapGet(request, "reason"); if (val && JsonValueType(val) == JSON_STRING) { reason = JsonValueAsString(val); } } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); removed = UserLock(db, removedLocalpart); if (!user || !removed) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } if (!(UserGetPrivileges(user) & USER_DEACTIVATE)) { char * msg = "User doesn't have the DEACTIVATE privilege."; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); goto finish; } if (method == HTTP_DELETE) { UserDeactivate(removed, UserGetName(user), reason); response = HashMapCreate(); JsonSet(response, JsonValueString(removedLocalpart), 1, "user"); JsonSet(response, JsonValueString(reason), 1, "reason"); JsonSet(response, JsonValueString(UserGetName(user)), 1, "banned_by"); } else { UserReactivate(removed); HttpResponseStatus(args->context, HTTP_NO_CONTENT); } finish: UserUnlock(user); UserUnlock(removed); 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 ROUTE_IMPL(RouteAdminTokens, path, argp) { RouteArgs *args = argp; HashMap *request = NULL; HashMap *response = NULL; char *token; char *msg; Db *db = args->matrixArgs->db; User *user = NULL; HttpRequestMethod method = HttpRequestMethodGet(args->context); Array *tokensarray; Array *tokens; RegTokenInfo *info; RegTokenInfo *req; size_t i; if (method != HTTP_GET && method != HTTP_POST && method != HTTP_DELETE) { msg = "Route only supports GET, POST, and DELETE"; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, msg); } 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; } if (!(UserGetPrivileges(user) & USER_ISSUE_TOKENS)) { msg = "User doesn't have the ISSUE_TOKENS privilege."; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); goto finish; } switch (method) { case HTTP_GET: if (ArraySize(path) == 0) { tokensarray = ArrayCreate(); /* Get all registration tokens */ tokens = DbList(db, 2, "tokens", "registration"); response = HashMapCreate(); for (i = 0; i < ArraySize(tokens); i++) { char *tokenname = ArrayGet(tokens, i); HashMap *jsoninfo; info = RegTokenGetInfo(db, tokenname); jsoninfo = RegTokenInfoToJson(info); RegTokenClose(info); RegTokenFree(info); ArrayAdd(tokensarray, JsonValueObject(jsoninfo)); } JsonSet(response, JsonValueArray(tokensarray), 1, "tokens"); DbListFree(tokens); break; } info = RegTokenGetInfo(db, ArrayGet(path, 0)); if (!info) { msg = "Token doesn't exist."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } response = RegTokenInfoToJson(info); RegTokenClose(info); RegTokenFree(info); break; case HTTP_POST: request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } req = Malloc(sizeof(RegTokenInfo)); memset(req, 0, sizeof(RegTokenInfo)); if (!RegTokenInfoFromJson(request, req, &msg)) { RegTokenInfoFree(req); Free(req); HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, msg); goto finish; } if (!req->name) { req->name = StrRandom(16); } /* Create the actual token that will be stored. */ info = RegTokenCreate(db, req->name, UserGetName(user), req->expires_on, req->uses, UserDecodePrivileges(req->grants)); if (!info) { RegTokenClose(info); RegTokenFree(info); RegTokenInfoFree(req); Free(req); HttpResponseStatus(args->context, HTTP_BAD_REQUEST); msg = "Cannot create token."; response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } response = RegTokenInfoToJson(info); RegTokenClose(info); RegTokenFree(info); RegTokenInfoFree(req); Free(req); break; case HTTP_DELETE: if (ArraySize(path) == 0) { msg = "No registration token given to DELETE /tokens/[token]."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } info = RegTokenGetInfo(db, ArrayGet(path, 0)); RegTokenDelete(info); response = HashMapCreate(); break; default: /* Should not be possible. */ break; } finish: UserUnlock(user); JsonFree(request); return response; }