[MOD] Use Parser API for user ID parsing

Only tested with POST /login though, but it should work
This commit is contained in:
lda 2023-11-24 21:19:54 +01:00
parent b378d443c0
commit 572d69c3f6

View file

@ -31,6 +31,10 @@
#include <Cytoplasm/Int64.h> #include <Cytoplasm/Int64.h>
#include <Cytoplasm/UInt64.h> #include <Cytoplasm/UInt64.h>
#include <Parser.h>
#include <ctype.h>
#include <string.h> #include <string.h>
struct User struct User
@ -882,51 +886,88 @@ finish:
return arr; return arr;
} }
static int
UserIdParseLocal(Parser *p, char **ret)
{
int c;
if (!p || !ret)
{
return 0;
}
ParserStartCopy(p);
/* Always assume the general case here: every ASCII char,
* minus ':'. */
while (isascii((c = ParserGetc(p))) && c != ':')
{
/* Do nothing. */
}
if (c != EOF)
{
ParserUndo(p);
}
*ret = ParserEndCopy(p);
return 1;
}
static int
UserIdParseServer(Parser *p, char **ret)
{
int c;
if (!p || !ret)
{
return 0;
}
ParserStartCopy(p);
/* Allow *every* ASCII character. */
while (isascii((c = ParserGetc(p))))
{
/* Do nothing. */
}
if (c != EOF)
{
ParserUndo(p);
}
*ret = ParserEndCopy(p);
return 1;
}
UserId * UserId *
UserIdParse(char *id, char *defaultServer) UserIdParse(char *id, char *defaultServer)
{ {
UserId *userId; UserId *userId;
Parser *p;
if (!id) if (!id)
{ {
return NULL; return NULL;
} }
id = StrDuplicate(id); p = ParserCreate(id);
if (!id)
{
return NULL;
}
userId = Malloc(sizeof(UserId)); userId = Malloc(sizeof(UserId));
userId->localpart = NULL;
userId->server = NULL;
if (!userId) if (!userId)
{ {
goto finish; goto finish;
} }
/* Fully-qualified user ID */ /* Fully-qualified user ID.
if (*id == '@') * TODO: Generalise this for parsing namespaced IDs,
* like room aliases and IDs. */
if (ParserExcept(p, '@'))
{ {
char *localStart = id + 1; if (!UserIdParseLocal(p, &userId->localpart) ||
char *serverStart = localStart; !ParserExcept(p, ':') ||
!UserIdParseServer(p, &userId->server))
while (*serverStart != ':' && *serverStart != '\0')
{ {
serverStart++; if (userId->localpart)
{
Free(userId->localpart);
} }
if (*serverStart == '\0')
{
Free(userId); Free(userId);
userId = NULL;
goto finish;
} }
*serverStart = '\0';
serverStart++;
userId->localpart = StrDuplicate(localStart);
userId->server = StrDuplicate(serverStart);
} }
else else
{ {
@ -942,7 +983,7 @@ UserIdParse(char *id, char *defaultServer)
} }
finish: finish:
Free(id); ParserEnd(p);
return userId; return userId;
} }