From 0a29aa7f5a8f57ee9d368507449bc8cd46e8850c Mon Sep 17 00:00:00 2001 From: Jordan Bancino Date: Sat, 7 Jan 2023 04:33:32 +0000 Subject: [PATCH] Move string related functions to a new String API. I think we have accumulated enough string functions that they should have their own API. This shortens the function names a bit too. --- TODO.txt | 11 ++- src/Db.c | 17 ++-- src/Json.c | 8 +- src/Matrix.c | 8 +- src/Routes/RouteLogin.c | 4 +- src/Routes/RouteMatrix.c | 4 +- src/Routes/RouteRegister.c | 14 +-- src/Routes/RouteWellKnown.c | 6 +- src/String.c | 189 ++++++++++++++++++++++++++++++++++++ src/TelodendriaConfig.c | 8 +- src/UserInteractiveAuth.c | 8 +- src/Util.c | 150 ---------------------------- src/include/String.h | 41 ++++++++ src/include/Util.h | 12 --- 14 files changed, 275 insertions(+), 205 deletions(-) create mode 100644 src/String.c create mode 100644 src/include/String.h diff --git a/TODO.txt b/TODO.txt index 16ade87..0c8b01c 100644 --- a/TODO.txt +++ b/TODO.txt @@ -14,17 +14,18 @@ Milestone: v0.2.0 [x] Abstract user-interactive authentication [ ] Abstract /email/requestToken and /msidsn/requestToken -[ ] Document UserInteractiveAuth (move docs from Matrix) -[ ] Document MemoryHexDump -[ ] Move String functions to a new String.h? -[~] Make UtilStringConcat use varargs - [ ] Update documentation +[x] Move String functions to a new String.h +[x] Make StringConcat use varargs [x] Look into seeding random strings (possibly create Random.h?) [~] User registration [x] Username validation [x] Password hashing [ ] User API +[ ] Document UserInteractiveAuth (move docs from Matrix) +[ ] Document MemoryHexDump +[ ] Document String and remove old functions from Util + Milestone: v1.0.0 ----------------- diff --git a/src/Db.c b/src/Db.c index 4e7c27d..d4f98da 100644 --- a/src/Db.c +++ b/src/Db.c @@ -26,6 +26,7 @@ #include #include #include +#include #include #include @@ -200,7 +201,7 @@ DbHashKey(Array * args) for (i = 0; i < ArraySize(args); i++) { - char *tmp = UtilStringConcat(2, str, ArrayGet(args, i)); + char *tmp = StringConcat(2, str, ArrayGet(args, i)); Free(str); str = tmp; @@ -213,13 +214,13 @@ static char * DbDirName(Db * db, Array * args) { size_t i; - char *str = UtilStringConcat(2, db->dir, "/"); + char *str = StringConcat(2, db->dir, "/"); for (i = 0; i < ArraySize(args) - 1; i++) { char *tmp; - tmp = UtilStringConcat(3, str, ArrayGet(args, i), "/"); + tmp = StringConcat(3, str, ArrayGet(args, i), "/"); Free(str); @@ -233,12 +234,12 @@ static char * DbFileName(Db * db, Array * args) { size_t i; - char *str = UtilStringConcat(2, db->dir, "/"); + char *str = StringConcat(2, db->dir, "/"); for (i = 0; i < ArraySize(args); i++) { char *tmp; - char *arg = UtilStringDuplicate(ArrayGet(args, i)); + char *arg = StringDuplicate(ArrayGet(args, i)); size_t j = 0; /* Sanitize name to prevent directory traversal attacks */ @@ -258,7 +259,7 @@ DbFileName(Db * db, Array * args) j++; } - tmp = UtilStringConcat(3, str, arg, + tmp = StringConcat(3, str, arg, (i < ArraySize(args) - 1) ? "/" : ".json"); Free(arg); @@ -503,11 +504,11 @@ DbLockFromArr(Db * db, Array * args) for (i = 0; i < ArraySize(args); i++) { - ArrayAdd(name, UtilStringDuplicate(ArrayGet(args, i))); + ArrayAdd(name, StringDuplicate(ArrayGet(args, i))); } ref->name = name; - HashMapSet(db->cache, UtilStringDuplicate(hash), ref); + HashMapSet(db->cache, StringDuplicate(hash), ref); db->cacheSize += ref->size; ref->next = NULL; diff --git a/src/Json.c b/src/Json.c index 3144e83..a3d1d06 100644 --- a/src/Json.c +++ b/src/Json.c @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include @@ -486,7 +486,7 @@ JsonDecodeString(FILE * in) /* Encode the 4-byte UTF-8 buffer into a series * of 1-byte characters */ - utf8Ptr = UtilUtf8Encode(utf8); + utf8Ptr = StringUtf8Encode(utf8); if (!utf8Ptr) { /* Mem error */ @@ -494,8 +494,8 @@ JsonDecodeString(FILE * in) return NULL; } - /* Move the output of UtilUtf8Encode() into our - * local buffer */ + /* Move the output of StringUtf8Encode() into + * our local buffer */ strcpy(a, utf8Ptr); Free(utf8Ptr); break; diff --git a/src/Matrix.c b/src/Matrix.c index 3d0dfaf..a269732 100644 --- a/src/Matrix.c +++ b/src/Matrix.c @@ -30,7 +30,7 @@ #include #include #include -#include +#include #include @@ -83,7 +83,7 @@ MatrixHttpHandler(HttpServerContext * context, void *argp) } pathParts = MATRIX_PATH_CREATE(); - requestPathCpy = UtilStringDuplicate(requestPath); + requestPathCpy = StringDuplicate(requestPath); key = requestPathCpy; while ((pathPart = strtok_r(key, "/", &key))) @@ -295,8 +295,8 @@ MatrixErrorCreate(MatrixError errorArg) return NULL; } - HashMapSet(errorObj, "errcode", JsonValueString(UtilStringDuplicate(errcode))); - HashMapSet(errorObj, "error", JsonValueString(UtilStringDuplicate(error))); + HashMapSet(errorObj, "errcode", JsonValueString(StringDuplicate(errcode))); + HashMapSet(errorObj, "error", JsonValueString(StringDuplicate(error))); return errorObj; } diff --git a/src/Routes/RouteLogin.c b/src/Routes/RouteLogin.c index 7555e08..6f9343a 100644 --- a/src/Routes/RouteLogin.c +++ b/src/Routes/RouteLogin.c @@ -27,7 +27,7 @@ #include #include -#include +#include ROUTE_IMPL(RouteLogin, args) { @@ -49,7 +49,7 @@ ROUTE_IMPL(RouteLogin, args) pwdFlow = HashMapCreate(); HashMapSet(pwdFlow, "type", - JsonValueString(UtilStringDuplicate("m.login.password"))); + JsonValueString(StringDuplicate("m.login.password"))); ArrayAdd(enabledFlows, JsonValueObject(pwdFlow)); HashMapSet(response, "flows", JsonValueArray(enabledFlows)); diff --git a/src/Routes/RouteMatrix.c b/src/Routes/RouteMatrix.c index 9fa4327..2f7457b 100644 --- a/src/Routes/RouteMatrix.c +++ b/src/Routes/RouteMatrix.c @@ -28,7 +28,7 @@ #include #include #include -#include +#include ROUTE_IMPL(RouteMatrix, args) { @@ -51,7 +51,7 @@ ROUTE_IMPL(RouteMatrix, args) Free(pathPart); - ArrayAdd(versions, JsonValueString(UtilStringDuplicate("v1.5"))); + ArrayAdd(versions, JsonValueString(StringDuplicate("v1.5"))); response = HashMapCreate(); HashMapSet(response, "versions", JsonValueArray(versions)); diff --git a/src/Routes/RouteRegister.c b/src/Routes/RouteRegister.c index 838a989..89f14c4 100644 --- a/src/Routes/RouteRegister.c +++ b/src/Routes/RouteRegister.c @@ -27,7 +27,7 @@ #include #include -#include +#include #include #include @@ -80,7 +80,7 @@ ROUTE_IMPL(RouteRegister, args) response = MatrixErrorCreate(M_BAD_JSON); goto finish; } - username = UtilStringDuplicate(JsonValueAsString(val)); + username = StringDuplicate(JsonValueAsString(val)); if (!MatrixUserValidate(username, args->matrixArgs->config->serverName)) { @@ -127,7 +127,7 @@ ROUTE_IMPL(RouteRegister, args) goto finish; } - password = UtilStringDuplicate(JsonValueAsString(val)); + password = StringDuplicate(JsonValueAsString(val)); val = HashMapGet(request, "device_id"); if (val) @@ -139,7 +139,7 @@ ROUTE_IMPL(RouteRegister, args) goto finish; } - deviceId = UtilStringDuplicate(JsonValueAsString(val)); + deviceId = StringDuplicate(JsonValueAsString(val)); } val = HashMapGet(request, "inhibit_login"); @@ -165,7 +165,7 @@ ROUTE_IMPL(RouteRegister, args) goto finish; } - initialDeviceDisplayName = UtilStringDuplicate(JsonValueAsString(val)); + initialDeviceDisplayName = StringDuplicate(JsonValueAsString(val)); } val = HashMapGet(request, "refresh_token"); @@ -183,12 +183,12 @@ ROUTE_IMPL(RouteRegister, args) if (!username) { - username = UtilRandomString(16); + username = StringRandom(16); } if (!inhibitLogin && !deviceId) { - deviceId = UtilRandomString(10); + deviceId = StringRandom(10); } /* These values are already set */ diff --git a/src/Routes/RouteWellKnown.c b/src/Routes/RouteWellKnown.c index 6b7d13a..9e74960 100644 --- a/src/Routes/RouteWellKnown.c +++ b/src/Routes/RouteWellKnown.c @@ -28,7 +28,7 @@ #include #include #include -#include +#include ROUTE_IMPL(RouteWellKnown, args) { @@ -53,14 +53,14 @@ ROUTE_IMPL(RouteWellKnown, args) response = HashMapCreate(); - HashMapSet(homeserver, "base_url", JsonValueString(UtilStringDuplicate(args->matrixArgs->config->baseUrl))); + HashMapSet(homeserver, "base_url", JsonValueString(StringDuplicate(args->matrixArgs->config->baseUrl))); HashMapSet(response, "m.homeserver", JsonValueObject(homeserver)); if (args->matrixArgs->config->identityServer) { HashMap *identityServer = HashMapCreate(); - HashMapSet(identityServer, "base_url", JsonValueString(UtilStringDuplicate(args->matrixArgs->config->identityServer))); + HashMapSet(identityServer, "base_url", JsonValueString(StringDuplicate(args->matrixArgs->config->identityServer))); HashMapSet(response, "m.identity_server", identityServer); } diff --git a/src/String.c b/src/String.c new file mode 100644 index 0000000..8daddb8 --- /dev/null +++ b/src/String.c @@ -0,0 +1,189 @@ +/* + * Copyright (C) 2022-2023 Jordan Bancino <@jordan:bancino.net> + * + * 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 + +char * +StringUtf8Encode(unsigned long utf8) +{ + char *str; + + str = Malloc(5 * sizeof(char)); + if (!str) + { + return NULL; + } + + if (utf8 <= 0x7F) /* Plain ASCII */ + { + str[0] = (char) utf8; + str[1] = '\0'; + } + else if (utf8 <= 0x07FF) /* 2-byte */ + { + str[0] = (char) (((utf8 >> 6) & 0x1F) | 0xC0); + str[1] = (char) (((utf8 >> 0) & 0x3F) | 0x80); + str[2] = '\0'; + } + else if (utf8 <= 0xFFFF) /* 3-byte */ + { + str[0] = (char) (((utf8 >> 12) & 0x0F) | 0xE0); + str[1] = (char) (((utf8 >> 6) & 0x3F) | 0x80); + str[2] = (char) (((utf8 >> 0) & 0x3F) | 0x80); + str[3] = '\0'; + } + else if (utf8 <= 0x10FFFF) /* 4-byte */ + { + str[0] = (char) (((utf8 >> 18) & 0x07) | 0xF0); + str[1] = (char) (((utf8 >> 12) & 0x3F) | 0x80); + str[2] = (char) (((utf8 >> 6) & 0x3F) | 0x80); + str[3] = (char) (((utf8 >> 0) & 0x3F) | 0x80); + str[4] = '\0'; + } + else + { + /* Send replacement character */ + str[0] = (char) 0xEF; + str[1] = (char) 0xBF; + str[2] = (char) 0xBD; + str[3] = '\0'; + } + + return str; +} + +char * +StringDuplicate(const char *inStr) +{ + size_t len; + char *outStr; + + len = strlen(inStr); + outStr = Malloc(len + 1); /* For the null terminator */ + if (!outStr) + { + return NULL; + } + + strcpy(outStr, inStr); + + return outStr; +} + +char * +StringConcat(size_t nStr,...) +{ + va_list argp; + char *str; + char *strp; + size_t strLen = 0; + size_t i; + + va_start(argp, nStr); + for (i = 0; i < nStr; i++) + { + char *argStr = va_arg(argp, char *); + + if (argStr) + { + strLen += strlen(argStr); + } + } + va_end(argp); + + str = Malloc(strLen + 1); + strp = str; + + va_start(argp, nStr); + + for (i = 0; i < nStr; i++) + { + /* Manually copy chars instead of using strcopy() so we don't + * have to call strlen() on the strings again, and we aren't + * writing useless null chars. */ + + char *argStr = va_arg(argp, char *); + + if (argStr) + { + while (*argStr) + { + *strp = *argStr; + strp++; + argStr++; + } + } + } + + va_end(argp); + str[strLen] = '\0'; + return str; +} + +char * +StringRandom(size_t len) +{ + static const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + static pthread_mutex_t seedLock = PTHREAD_MUTEX_INITIALIZER; + static unsigned int seed = 0; + + char *str; + size_t i; + + if (!len) + { + return NULL; + } + + str = Malloc(len + 1); + if (!str) + { + return NULL; + } + + pthread_mutex_lock(&seedLock); + + if (!seed) + { + seed = UtilServerTs() ^ getpid() ^ (unsigned long) pthread_self(); + } + + for (i = 0; i < len; i++) + { + str[i] = charset[rand_r(&seed) % (sizeof(charset) - 1)]; + } + + pthread_mutex_unlock(&seedLock); + + str[len] = '\0'; + return str; +} diff --git a/src/TelodendriaConfig.c b/src/TelodendriaConfig.c index 20a51bc..1fb7bfe 100644 --- a/src/TelodendriaConfig.c +++ b/src/TelodendriaConfig.c @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include #include @@ -53,7 +53,7 @@ } #define CONFIG_COPY_STRING(into) \ - into = UtilStringDuplicate(JsonValueAsString(value)); + into = StringDuplicate(JsonValueAsString(value)); #define CONFIG_OPTIONAL_STRING(into, key, default) \ value = HashMapGet(config, key); \ @@ -64,12 +64,12 @@ Log(lc, LOG_ERR, "Expected " key " to be of type JSON_STRING"); \ goto error; \ } \ - into = UtilStringDuplicate(JsonValueAsString(value)); \ + into = StringDuplicate(JsonValueAsString(value)); \ } \ else \ { \ Log(lc, LOG_INFO, "Using default value " #default " for " key "."); \ - into = default ? UtilStringDuplicate(default) : NULL; \ + into = default ? StringDuplicate(default) : NULL; \ } #define CONFIG_OPTIONAL_INTEGER(into, key, default) \ diff --git a/src/UserInteractiveAuth.c b/src/UserInteractiveAuth.c index 967d432..fb326a2 100644 --- a/src/UserInteractiveAuth.c +++ b/src/UserInteractiveAuth.c @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include @@ -38,7 +38,7 @@ BuildDummyFlow(void) Array *flows = ArrayCreate(); ArrayAdd(stages, - JsonValueString(UtilStringDuplicate("m.login.dummy"))); + JsonValueString(StringDuplicate("m.login.dummy"))); HashMapSet(dummyFlow, "stages", JsonValueArray(stages)); ArrayAdd(flows, JsonValueObject(dummyFlow)); @@ -68,7 +68,7 @@ UserInteractiveAuth(HttpServerContext * context, Db * db, { HashMap *response = NULL; HashMap *persist; - char *session = UtilRandomString(24); + char *session = StringRandom(24); ref = DbLock(db, 1, "user_interactive"); if (!ref) @@ -84,7 +84,7 @@ UserInteractiveAuth(HttpServerContext * context, Db * db, response = BuildDummyFlow(); HashMapSet(response, "session", - JsonValueString(UtilStringDuplicate(session))); + JsonValueString(StringDuplicate(session))); return response; } diff --git a/src/Util.c b/src/Util.c index ecb438f..7bd77a6 100644 --- a/src/Util.c +++ b/src/Util.c @@ -144,122 +144,11 @@ UtilMkdir(const char *dir, const mode_t mode) return 0; } -char * -UtilUtf8Encode(unsigned long utf8) -{ - char *str; - str = Malloc(5 * sizeof(char)); - if (!str) - { - return NULL; - } - if (utf8 <= 0x7F) /* Plain ASCII */ - { - str[0] = (char) utf8; - str[1] = '\0'; - } - else if (utf8 <= 0x07FF) /* 2-byte */ - { - str[0] = (char) (((utf8 >> 6) & 0x1F) | 0xC0); - str[1] = (char) (((utf8 >> 0) & 0x3F) | 0x80); - str[2] = '\0'; - } - else if (utf8 <= 0xFFFF) /* 3-byte */ - { - str[0] = (char) (((utf8 >> 12) & 0x0F) | 0xE0); - str[1] = (char) (((utf8 >> 6) & 0x3F) | 0x80); - str[2] = (char) (((utf8 >> 0) & 0x3F) | 0x80); - str[3] = '\0'; - } - else if (utf8 <= 0x10FFFF) /* 4-byte */ - { - str[0] = (char) (((utf8 >> 18) & 0x07) | 0xF0); - str[1] = (char) (((utf8 >> 12) & 0x3F) | 0x80); - str[2] = (char) (((utf8 >> 6) & 0x3F) | 0x80); - str[3] = (char) (((utf8 >> 0) & 0x3F) | 0x80); - str[4] = '\0'; - } - else - { - /* Send replacement character */ - str[0] = (char) 0xEF; - str[1] = (char) 0xBF; - str[2] = (char) 0xBD; - str[3] = '\0'; - } - return str; -} -char * -UtilStringDuplicate(char *inStr) -{ - size_t len; - char *outStr; - len = strlen(inStr); - outStr = Malloc(len + 1); /* For the null terminator */ - if (!outStr) - { - return NULL; - } - - strcpy(outStr, inStr); - - return outStr; -} - -char * -UtilStringConcat(size_t nStr,...) -{ - va_list argp; - char *str; - char *strp; - size_t strLen = 0; - size_t i; - - va_start(argp, nStr); - for (i = 0; i < nStr; i++) - { - char *argStr = va_arg(argp, char *); - - if (argStr) - { - strLen += strlen(argStr); - } - } - va_end(argp); - - str = Malloc(strLen + 1); - strp = str; - - va_start(argp, nStr); - - for (i = 0; i < nStr; i++) - { - /* Manually copy chars instead of using strcopy() so we don't - * have to call strlen() on the strings again, and we aren't - * writing useless null chars. */ - - char *argStr = va_arg(argp, char *); - - if (argStr) - { - while (*argStr) - { - *strp = *argStr; - strp++; - argStr++; - } - } - } - - va_end(argp); - str[strLen] = '\0'; - return str; -} int UtilSleepMillis(long ms) @@ -407,42 +296,3 @@ UtilGetLine(char **linePtr, size_t * n, FILE * stream) { return UtilGetDelim(linePtr, n, '\n', stream); } - -char * -UtilRandomString(size_t len) -{ - static const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - static pthread_mutex_t seedLock = PTHREAD_MUTEX_INITIALIZER; - static unsigned int seed = 0; - - char *str; - size_t i; - - if (!len) - { - return NULL; - } - - str = Malloc(len + 1); - if (!str) - { - return NULL; - } - - pthread_mutex_lock(&seedLock); - - if (!seed) - { - seed = UtilServerTs() ^ getpid() ^ (unsigned long) pthread_self(); - } - - for (i = 0; i < len; i++) - { - str[i] = charset[rand_r(&seed) % (sizeof(charset) - 1)]; - } - - pthread_mutex_unlock(&seedLock); - - str[len] = '\0'; - return str; -} diff --git a/src/include/String.h b/src/include/String.h new file mode 100644 index 0000000..fcebd37 --- /dev/null +++ b/src/include/String.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2022-2023 Jordan Bancino <@jordan:bancino.net> + * + * 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. + */ +#ifndef TELODENDRIA_STRING_H +#define TELODENDRIA_STRING_H + +#include + +extern char * + StringUtf8Encode(unsigned long); + +extern char * + StringDuplicate(const char *); + +extern char * + StringConcat(size_t,...); + +extern char * + StringRandom(size_t); + +#endif /* TELODENDRIA_STRING_H */ diff --git a/src/include/Util.h b/src/include/Util.h index a163b52..ee03694 100644 --- a/src/include/Util.h +++ b/src/include/Util.h @@ -38,15 +38,6 @@ extern unsigned long extern int UtilMkdir(const char *, const mode_t); -extern char * - UtilUtf8Encode(unsigned long); - -extern char * - UtilStringDuplicate(char *); - -extern char * - UtilStringConcat(size_t,...); - extern int UtilSleepMillis(long); @@ -59,7 +50,4 @@ extern ssize_t extern ssize_t UtilGetLine(char **, size_t *, FILE *); -extern char * - UtilRandomString(size_t); - #endif /* TELODENDRIA_UTIL_H */