Compare commits

..

25 commits

Author SHA1 Message Date
lda
5851298957 [FIX] Fix conflicts and make branch buildable. 2024-01-06 16:14:31 +01:00
lda
568543ab39 [FIX+META] Write changelog and enforce GET on RoomAliases 2024-01-06 16:14:31 +01:00
lda
5d2ca5a21b [MOD/WIP] Refactor code to use CommonIDs instead of UserIds 2024-01-06 16:14:31 +01:00
lda
88c9d10f90 [MOD] Add basic length checking 2024-01-06 16:14:31 +01:00
lda
2a61df37ad [ADD/WIP] Start adding a basic IPv6 parser.
It's only missing verification and a little cleanup
2024-01-06 16:14:31 +01:00
lda
b71b90e7b0 [ADD] Add basic privilege checking for RouteRoomAliases
For now, this checking is incomplete, and it probably will stay
that way until rooms are properly implemented.
2024-01-06 16:14:31 +01:00
lda
e8b4ef135d [MOD] Declare versions v1.2-v1.6 alongside v1.7
This should increase compatibility with some clients still not supporting v1.7(like Nheko).
2024-01-06 16:14:31 +01:00
lda
3c11d666c8 [MOD] Remove decoding code
This requires Cytoplasm #19 however now.
2024-01-06 16:14:31 +01:00
lda
288ab5da54 [ADD/WIP] Add ParserRecomposeCommonID 2024-01-06 16:14:31 +01:00
lda
8e177baef7 [FIX] Remove mention of Cytoplasm in gitignore. 2024-01-06 16:14:31 +01:00
lda
56d348454e [ADD] Implement barebones of GET /rooms/{id}/alias 2024-01-06 16:14:31 +01:00
lda
ad1901017f [MOD] Delete id relation when DELETE is requested. 2024-01-06 16:14:31 +01:00
lda
48ffd86553 [ADD/WIP] Start adding room ID -> alias relation 2024-01-06 16:14:31 +01:00
lda
c1933a2184 [MOD/WIP] Take into account room IDs
This might need a refactor.
2024-01-06 16:14:31 +01:00
lda
78daf86eb3 [MOD/WIP] Start doing checks on room alias
NOTE: Currently UNTESTED.
2024-01-06 16:14:31 +01:00
lda
8eab884289 [MOD/WIP] Start adding the server parsing code
Might need some clean-up, and also we'll need to refactor the
User API to use CommonIDs instead
2024-01-06 16:14:31 +01:00
lda
4e7554d241 [FIX] Fix the user ID parser to actually work 2024-01-06 16:14:31 +01:00
lda
30679d7999 [MOD] Make the User API use a bit of the parser 2024-01-06 16:14:31 +01:00
lda
4298ee469a [MOD] Drop old Parser API, add new ID parser 2024-01-06 16:14:31 +01:00
lda
4a575cee1d [FIX] Ensure NULL in case of failure
Oops!
2024-01-06 16:14:31 +01:00
lda
572d69c3f6 [MOD] Use Parser API for user ID parsing
Only tested with POST /login though, but it should work
2024-01-06 16:14:31 +01:00
lda
b378d443c0 [MOD/FIX] Make the Parser API usable
It should now be good enough for parsing simple grammars(user IDs
for example)
2024-01-06 16:14:31 +01:00
lda
20a44a0664 [ADD/WIP] Add corresponding source code for parser 2024-01-06 16:14:31 +01:00
lda
a493f3de85 [ADD/WIP] Start working on basic parser header 2024-01-06 16:14:31 +01:00
35e41d9f6b [FIX] Fix commit f61009a423's mistake 2024-01-06 16:14:31 +01:00
29 changed files with 245 additions and 662 deletions

View file

@ -1,27 +0,0 @@
name: Compile Telodendria
run-name: Compile Telodendria on ${{ forgejo.actor }}
on:
push:
branches:
- 'ma*'
pull_request:
types: [opened, synchronize, reopened]
jobs:
"Compile Telodendria":
strategy:
matrix:
os: [alpine]
arch: [aarch64]
runs-on: ["${{ matrix.os }}", "${{ matrix.arch }}"]
steps:
- name: Check out repository
uses: actions/checkout@v4
with:
submodules: true
- name: Configure Telodendria
run: ./configure
- name: Configure & Build Cytoplasm
run: make cytoplasm
- name: Build Telodendria
run: make

View file

@ -1,44 +0,0 @@
name: Release Telodendria
run-name: Release Telodendria on ${{ forgejo.actor }}
on:
push:
tags:
- 'v*'
jobs:
"Release Telodendria":
strategy:
matrix:
os: [alpine]
arch: [aarch64]
runs-on: ["${{ matrix.os }}", "${{ matrix.arch }}"]
steps:
- name: Check out repository
uses: actions/checkout@v4
with:
submodules: true
- name: Archive submodules
run: git submodule foreach --recursive 'git archive --format tar --prefix=$displaypath/ -o submodule.tar HEAD'
- name: Archive repository
run: git archive --format tar -o release.tar HEAD
- name: Produce release archive
run: |
TOPDIR=$(pwd) git submodule --quiet foreach --recursive 'cd $TOPDIR; tar --concatenate --file=release.tar $displaypath/submodule.tar; rm -fv $displaypath/submodule.tar'
gzip release.tar
mkdir release
mv release.tar.gz release/Telodendria-$GITHUB_REF_NAME.tar.gz
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: Telodendria-$GITHUB_REF_NAME.tar.gz
path: release/Telodendria-$GITHUB_REF_NAME.tar.gz
- name: Publish release
uses: actions/forgejo-release@v2
with:
tag: $GITHUB_REF_NAME
title: "Telodendria $GITHUB_REF_NAME"
release-dir: release/
release-notes: "docs/CHANGELOG.md"
direction: upload
prerelease: true

3
.gitmodules vendored
View file

@ -1,3 +0,0 @@
[submodule "Cytoplasm"]
path = Cytoplasm
url = https://git.telodendria.io/Telodendria/Cytoplasm.git

@ -1 +0,0 @@
Subproject commit 4f316ff7b3a955b831ca4aefb8679ddf3396a7d0

View file

@ -1,13 +0,0 @@
{
"header": "Schema\/UserDirectoryRequest.h",
"types": {
"UserDirectoryRequest": {
"fields": {
"search_term": { "type": "string" },
"limit": { "type": "integer" }
},
"type": "struct"
}
},
"guard": "TELODENDRIA_SCHEMA_USERDIRECTORYREQUEST_H"
}

123
configure vendored
View file

@ -13,40 +13,13 @@ SRC="src"
INCLUDE="src/include" INCLUDE="src/include"
TOOLS="tools/src" TOOLS="tools/src"
SCHEMA="Schema" SCHEMA="Schema"
CYTOPLASM="Cytoplasm"
CFLAGS="-O1 -D_DEFAULT_SOURCE -I${INCLUDE} -I${BUILD}" CFLAGS="-Wall -Wextra -pedantic -std=c89 -O3 -pipe -D_DEFAULT_SOURCE -I${INCLUDE} -I${BUILD}"
LIBS="-lm -pthread -lCytoplasm" LIBS="-lm -pthread -lCytoplasm"
# Set default args for all platforms # Set default args for all platforms
SCRIPT_ARGS="--prefix=/usr/local --bin-name=telodendria --version=1.7.0-alpha4" SCRIPT_ARGS="--cc=cc --prefix=/usr/local --enable-ld-extra --bin-name=telodendria --version=1.7.0-alpha4 --static $@"
if [ -f "${CYTOPLASM}/configure" ]; then
SCRIPT_ARGS="${SCRIPT_ARGS} --cytoplasm=${CYTOPLASM}"
else
SCRIPT_ARGS="${SCRIPT_ARGS} --cytoplasm=" # No cytoplasm path.
fi
# Set compiler depending on the platform.
case "$(uname)" in
Linux|NetBSD)
# These systems typically use GCC.
SCRIPT_ARGS="${SCRIPT_ARGS} --cc=gcc"
;;
OpenBSD|FreeBSD|Darwin)
# These systems typically use Clang.
SCRIPT_ARGS="${SCRIPT_ARGS} --cc=clang"
;;
*)
# Use default compiler which is required to be present on
# all POSIX-compliant systems.
SCRIPT_ARGS="${SCRIPT_ARGS} --cc=c99"
;;
esac
# Append any additional args specified by user
SCRIPT_ARGS="${SCRIPT_ARGS} $@"
echo "Processing options..." echo "Processing options..."
echo "Ran with arguments: $SCRIPT_ARGS" echo "Ran with arguments: $SCRIPT_ARGS"
@ -56,18 +29,16 @@ for arg in $SCRIPT_ARGS; do
case "$arg" in case "$arg" in
--cc=*) --cc=*)
CC=$(echo "$arg" | cut -d '=' -f 2-) CC=$(echo "$arg" | cut -d '=' -f 2-)
case "${CC}" in
gcc*|clang*)
# "Fancy" compilers that support a plethora of additional flags we
# want to enable if present.
CFLAGS="-Wall -Wextra -Werror -pedantic -std=c99 -O3 ${CFLAGS}"
LDFLAGS="${LDFLAGS} -flto -fdata-sections -ffunction-sections -s -Wl,-gc-sections"
;;
esac
;; ;;
--prefix=*) --prefix=*)
PREFIX=$(echo "$arg" | cut -d '=' -f 2-) PREFIX=$(echo "$arg" | cut -d '=' -f 2-)
;; ;;
--enable-ld-extra)
LD_EXTRA="-flto -fdata-sections -ffunction-sections -s -Wl,-gc-sections"
;;
--disable-ld-extra)
LD_EXTRA=""
;;
--bin-name=*) --bin-name=*)
BIN_NAME=$(echo "$arg" | cut -d '=' -f 2-) BIN_NAME=$(echo "$arg" | cut -d '=' -f 2-)
;; ;;
@ -76,22 +47,20 @@ for arg in $SCRIPT_ARGS; do
;; ;;
--enable-debug) --enable-debug)
DEBUG="-O0 -g" DEBUG="-O0 -g"
echo "Notice: --enable-debug implies --disable-ld-extra and --no-static."
echo "You must explicitly provide --enable-ld-extra and/or --static after"
echo "specifying --enable-debug if you wish to enable these features in debug mode."
LD_EXTRA=""
STATIC=""
;; ;;
--disable-debug) --disable-debug)
DEBUG="" DEBUG=""
;; ;;
--cytoplasm=*) --static)
CYTOPLASM=$(echo "$arg" | cut -d '=' -f 2-) STATIC="-static -Wl,-static"
if [ -n "${CYTOPLASM}" ]; then ;;
if [ ! -f "${CYTOPLASM}/configure" ]; then --no-static)
echo "Path for Cytoplasm does not appear to actually contain Cytoplasm source:" STATIC=""
echo "${CYTOPLASM}"
exit 1
fi
CFLAGS="${CFLAGS} -I${CYTOPLASM}/include"
LDFLAGS="-L${CYTOPLASM}/out/lib ${LDFLAGS}"
fi
;; ;;
*) *)
echo "Invalid argument: $arg" echo "Invalid argument: $arg"
@ -101,7 +70,7 @@ for arg in $SCRIPT_ARGS; do
done done
CFLAGS="${CFLAGS} '-DTELODENDRIA_VERSION=\"${VERSION}\"' ${DEBUG}" CFLAGS="${CFLAGS} '-DTELODENDRIA_VERSION=\"${VERSION}\"' ${DEBUG}"
LDFLAGS="${LDFLAGS} ${LIBS}" LDFLAGS="${LIBS} ${LD_EXTRA}"
# #
# Makefile generation # Makefile generation
@ -134,16 +103,6 @@ prefix() {
done done
} }
cytoplasm_tool() {
tool="$1"
if [ -n "${CYTOPLASM}" ]; then
echo "LD_LIBRARY_PATH=${CYTOPLASM}/out/lib ${CYTOPLASM}/out/bin/$tool"
else
echo "$tool"
fi
}
print_src() { print_src() {
printf '%s ' "$1" printf '%s ' "$1"
} }
@ -152,27 +111,11 @@ print_obj() {
printf '%s ' "$2" printf '%s ' "$2"
} }
get_deps() {
src="$1"
${CC} -I${INCLUDE} -I${BUILD} $(if [ -n "${CYTOPLASM}" ]; then echo "-I${CYTOPLASM}/include"; fi) -E "$src" \
| grep '^#' \
| awk '{print $3}' \
| cut -d '"' -f 2 \
| sort \
| uniq \
| grep -v '^[/<]' \
| grep -e "^${SRC}/" -e "^${BUILD}/" \
| while IFS= read -r dep; do
printf "%s " "$dep"
done
}
compile_obj() { compile_obj() {
src="$1" src="$1"
obj="$2" obj="$2"
pref="${obj}: $(get_deps ${src})" pref=$(${CC} -I${INCLUDE} -I${BUILD} -MM -MT "${obj}" "${src}")
echo "$pref $(collect ${SCHEMA}/ .json .h ${BUILD}/Schema/ print_obj)" echo "$pref $(collect ${SCHEMA}/ .json .h ${BUILD}/Schema/ print_obj)"
echo "${TAB}@mkdir -p $(dirname ${obj})" echo "${TAB}@mkdir -p $(dirname ${obj})"
echo "${TAB}\$(CC) \$(CFLAGS) -fPIC -c -o \"${obj}\" \"${src}\"" echo "${TAB}\$(CC) \$(CFLAGS) -fPIC -c -o \"${obj}\" \"${src}\""
@ -186,7 +129,7 @@ compile_bin() {
echo "${out}: ${src}" echo "${out}: ${src}"
echo "${TAB}@mkdir -p ${OUT}/bin" echo "${TAB}@mkdir -p ${OUT}/bin"
echo "${TAB}\$(CC) \$(CFLAGS) -o \"${out}\" \"${src}\" $depObjs \$(LDFLAGS)" echo "${TAB}\$(CC) \$(CFLAGS) -o \"${out}\" \"${src}\" $depObjs \$(LDFLAGS) ${STATIC}"
} }
compile_doc() { compile_doc() {
@ -199,7 +142,7 @@ compile_doc() {
echo "${out}: ${src}" echo "${out}: ${src}"
echo "${TAB}@mkdir -p ${OUT}/man/man3" echo "${TAB}@mkdir -p ${OUT}/man/man3"
echo "${TAB}$(cytoplasm_tool hdoc) -D \"Os=${BIN_NAME}\" -i \"${src}\" -o \"${out}\"" echo "${TAB}hdoc -D \"Os=${BIN_NAME}\" -i \"${src}\" -o \"${out}\""
} }
print_doc() { print_doc() {
@ -217,11 +160,11 @@ compile_schema() {
echo "${BUILD}/Schema/${out}.h:" echo "${BUILD}/Schema/${out}.h:"
echo "${TAB}@mkdir -p ${BUILD}/Schema" echo "${TAB}@mkdir -p ${BUILD}/Schema"
echo "${TAB}$(cytoplasm_tool j2s) -s \"${src}\" -h \"${BUILD}/Schema/${out}.h\" -c \"${BUILD}/Schema/${out}.c\"" echo "${TAB}j2s -s \"${src}\" -h \"${BUILD}/Schema/${out}.h\" -c \"${BUILD}/Schema/${out}.c\""
echo "${BUILD}/Schema/${out}.c:" echo "${BUILD}/Schema/${out}.c:"
echo "${TAB}@mkdir -p ${BUILD}/Schema" echo "${TAB}@mkdir -p ${BUILD}/Schema"
echo "${TAB}$(cytoplasm_tool j2s) -s \"${src}\" -h \"${BUILD}/Schema/${out}.h\" -c \"${BUILD}/Schema/${out}.c\"" echo "${TAB}j2s -s \"${src}\" -h \"${BUILD}/Schema/${out}.h\" -c \"${BUILD}/Schema/${out}.c\""
echo "${obj}: ${src} ${BUILD}/Schema/${out}.c" echo "${obj}: ${src} ${BUILD}/Schema/${out}.c"
echo "${TAB}@mkdir -p ${BUILD}/Schema" echo "${TAB}@mkdir -p ${BUILD}/Schema"
@ -231,19 +174,15 @@ compile_schema() {
install_out() { install_out() {
src="$1" src="$1"
out="$2" out="$2"
dir=$(dirname "$out")
echo "${TAB}mkdir -p \"$dir\"" echo "${TAB}install -D \"$src\" \"$out\""
echo "${TAB}cp \"$src\" \"$out\""
} }
install_man() { install_man() {
src="${OUT}/man/man3/${BIN_NAME}-$(basename $1 .h).3" src="${OUT}/man/man3/${BIN_NAME}-$(basename $1 .h).3"
out="$2" out="$2"
dir=$(dirname "$out")
echo "${TAB}mkdir -p \"$dir\"" echo "${TAB}install -D \"$src\" \"$out\""
echo "${TAB}cp \"$src\" \"$out\""
} }
uninstall_out() { uninstall_out() {
@ -291,8 +230,7 @@ ${TAB}done
${BIN_NAME}: ${OUT}/bin/${BIN_NAME} ${BIN_NAME}: ${OUT}/bin/${BIN_NAME}
install: ${BIN_NAME} install: ${BIN_NAME}
${TAB}mkdir -p \$(PREFIX)/bin ${TAB}install -D ${OUT}/bin/${BIN_NAME} \$(PREFIX)/bin/${BIN_NAME}
${TAB}cp ${OUT}/bin/${BIN_NAME} \$(PREFIX)/bin/${BIN_NAME}
uninstall: uninstall:
${TAB}rm \$(PREFIX)/bin/${BIN_NAME} ${TAB}rm \$(PREFIX)/bin/${BIN_NAME}
@ -309,13 +247,6 @@ $(collect ${SRC}/ .c .o ${BUILD}/ compile_obj)
$(collect ${TOOLS}/ .c '' ${OUT}/bin/ compile_bin) $(collect ${TOOLS}/ .c '' ${OUT}/bin/ compile_bin)
$(collect ${INCLUDE}/ .h .3 ${OUT}/man/man3/${BIN_NAME}- compile_doc) $(collect ${INCLUDE}/ .h .3 ${OUT}/man/man3/${BIN_NAME}- compile_doc)
$(
if [ -n "${CYTOPLASM}" ]; then
echo "cytoplasm:"
echo "${TAB}cd ${CYTOPLASM} && ./configure && \$(MAKE)"
fi
)
EOF EOF
echo "Done. Run 'make' to build ${BIN_NAME}." echo "Done. Run 'make' to build ${BIN_NAME}."

View file

@ -1,94 +0,0 @@
# Hosting Telodendria
These are just my own personal notes for hosting Telodendria's code infrastructure. This document is not intended to be used by normal Telodendria users or developers. It may be useful if you are *forking* Telodendria, but I sincerely hope you'll contribute to the upstream project instead. I'm writing this document solely for my own reference, but I am placing it into Telodendria's code repository in the name of transparency.
## Runners
The general sequence of steps required for setting up a CI runner is as follows:
1. Install the runner OS with all the defaults. I typically install my runners in virtual machines with 1 vcpu and 512mb RAM. Only Debian complained about this configuration, but since I didn't install a desktop environment, it worked out fine.
2. Install the packages required to build and execute the runner. These are:
- Git for checking out the source code.
- NodeJS for running `actions/checkout`, I think. Not really sure, all I know is that the runner will fail all jobs without NodeJS.
- Go for compiling the runner itself.
Run these commands to install the packages:
- **OpenBSD:** `pkg_add git go node`
- **FreeBSD:** `pkg install git go node`
- **NetBSD:** `pkgin install git go nodejs openssl mozilla-rootcerts-openssl`
(Note that the `go` executable is `go121` or whatever version was installed. and that NetBSD has no root certificates installed by default)
- **Debian:** `apt install git golang nodejs`
- **Alpine:** `apk add git go nodejs`
3. Install any development packages required to build Telodendria. For the BSDs, all development tools are built in so no additional packages are necessary. For the Linux distributions I've messed with, install these additional packages:
- **Debian:** `apt install make gcc libssl-dev`
- **Alpine:** `apk add make gcc musl-dev openssl-dev`
4. Clone `https://git.telodendria.io/Telodendria/act_runner.git`.
5. Run `go build` in the `act_runner` directory. On NetBSD, you may have to `umount /tmp` first because `/tmp` is by default very small. Otherwise, make `/tmp` larger during installation. 2GB should be plenty.
6. Run `./act_runner register` to register the runner. When prompted for the tags, follow following convention:
- **Linux Distros:** `linux`, `<distro>-v<version>`, `<arch>`
- **BSD Derivatives:** `bsd`, `<osname>-v<version>`, `<arch>`
- **Windows:** `windows`, `windows-v<version>`, `<arch>`
- **MacOS:** `macos`, `macos-v<version>`, `<arch>`
- **Others:** `other`, `<osname>-v<version>`, `<arch>`
Where `<arch>` is one of `x86` or `x64` for now. ARM runners will be a future project.
7. Run `./act_runner daemon`.
### Startup Scripts
We will obviously want `act_runner` to execute on bootup. Here are the start scripts I used:
#### Alpine
In `/etc/init.d/act_runner`:
```shell
#!/sbin/openrc-run
directory="/home/runner/act_runner"
command="/home/runner/act_runner/act_runner"
command_args="daemon"
command_user="runner:runner"
command_background="true"
pidfile="/run/act_runner.pid"
```
Don't forget to `chmod +x /etc/init.d/act_runner`.
Then just `rc-update add act_runner` and `rc-service act_runner start`.
#### Debian
In `/etc/systemd/system/act_runner.service`:
```
[Unit]
Description=Gitea Actions runner
[Service]
ExecStart=/home/runner/act_runner/act_runner daemon
ExecReload=/bin/kill -s HUP $MAINPID
WorkingDirectory=/home/runner/act_runner
TimeoutSec=0
RestartSec=10
Restart=always
User=runner
[Install]
WantedBy=multi-user.target
```
Then just `systemctl enable act_runner` and `systemctl start act_runner`.
#### Other
Eventually I got sick of writing init scripts for all the various operating systems.
Just put this in `runner`'s `crontab`:
```
@reboot cd /home/runner/act_runner && ./act_runner daemon
```
That seems to do the job good enough, and it's cross platform.

View file

@ -30,6 +30,7 @@
#include <Cytoplasm/Str.h> #include <Cytoplasm/Str.h>
#include <Cytoplasm/Db.h> #include <Cytoplasm/Db.h>
#include <Cytoplasm/Log.h> #include <Cytoplasm/Log.h>
#include <Cytoplasm/Int64.h>
#include <Cytoplasm/Util.h> #include <Cytoplasm/Util.h>
#include <sys/types.h> #include <sys/types.h>
@ -58,7 +59,7 @@ ConfigParse(HashMap * config, Config *tConfig)
memset(tConfig, 0, sizeof(Config)); memset(tConfig, 0, sizeof(Config));
tConfig->maxCache = 0; tConfig->maxCache = Int64Create(0, 0);
if (!ConfigFromJson(config, tConfig, &tConfig->err)) if (!ConfigFromJson(config, tConfig, &tConfig->err))
{ {
@ -84,17 +85,17 @@ ConfigParse(HashMap * config, Config *tConfig)
for (i = 0; i < ArraySize(tConfig->listen); i++) for (i = 0; i < ArraySize(tConfig->listen); i++)
{ {
ConfigListener *listener = ArrayGet(tConfig->listen, i); ConfigListener *listener = ArrayGet(tConfig->listen, i);
if (!listener->maxConnections) if (Int64Eq(listener->maxConnections, Int64Create(0, 0)))
{ {
listener->maxConnections = 32; listener->maxConnections = Int64Create(0, 32);
} }
if (!listener->threads) if (Int64Eq(listener->threads, Int64Create(0, 0)))
{ {
listener->threads = 4; listener->threads = Int64Create(0, 4);
} }
if (!listener->port) if (Int64Eq(listener->port, Int64Create(0, 0)))
{ {
listener->port = 8008; listener->port = Int64Create(0, 8008);
} }
} }
tConfig->ok = 1; tConfig->ok = 1;
@ -147,9 +148,9 @@ ConfigCreateDefault(Db * db)
/* Add simple listener without TLS. */ /* Add simple listener without TLS. */
config.listen = ArrayCreate(); config.listen = ArrayCreate();
listener = Malloc(sizeof(ConfigListener)); listener = Malloc(sizeof(ConfigListener));
listener->maxConnections = 32; listener->maxConnections = Int64Create(0, 32);
listener->port = 8008; listener->port = Int64Create(0, 8008);
listener->threads = 4; listener->threads = Int64Create(0, 4);
ArrayAdd(config.listen, listener); ArrayAdd(config.listen, listener);

View file

@ -36,12 +36,14 @@
#include <Cytoplasm/Args.h> #include <Cytoplasm/Args.h>
#include <Cytoplasm/Memory.h> #include <Cytoplasm/Memory.h>
#include <Config.h>
#include <Cytoplasm/Log.h> #include <Cytoplasm/Log.h>
#include <Cytoplasm/HashMap.h> #include <Cytoplasm/HashMap.h>
#include <Cytoplasm/Json.h> #include <Cytoplasm/Json.h>
#include <Cytoplasm/HttpServer.h> #include <Cytoplasm/HttpServer.h>
#include <Cytoplasm/Db.h> #include <Cytoplasm/Db.h>
#include <Cytoplasm/Cron.h> #include <Cytoplasm/Cron.h>
#include <Uia.h>
#include <Cytoplasm/Util.h> #include <Cytoplasm/Util.h>
#include <Cytoplasm/Str.h> #include <Cytoplasm/Str.h>
@ -50,9 +52,6 @@
#include <User.h> #include <User.h>
#include <RegToken.h> #include <RegToken.h>
#include <Routes.h> #include <Routes.h>
#include <Uia.h>
#include <Config.h>
static Array *httpServers; static Array *httpServers;
static volatile int restart; static volatile int restart;
@ -249,7 +248,7 @@ start:
} }
token = StrRandom(32); token = StrRandom(32);
info = RegTokenCreate(matrixArgs.db, token, NULL, /* expires */ 0, /* uses */ 1, USER_ALL); info = RegTokenCreate(matrixArgs.db, token, NULL, UInt64Create(0, 0), Int64Create(0, 1), USER_ALL);
if (!info) if (!info)
{ {
Free(token); Free(token);
@ -397,14 +396,14 @@ start:
if (args.flags & HTTP_FLAG_TLS) if (args.flags & HTTP_FLAG_TLS)
{ {
if (!UtilLastModified(serverCfg->tls.cert)) if (UInt64Eq(UtilLastModified(serverCfg->tls.cert), UInt64Create(0, 0)))
{ {
Log(LOG_ERR, "%s: %s", strerror(errno), serverCfg->tls.cert); Log(LOG_ERR, "%s: %s", strerror(errno), serverCfg->tls.cert);
exit = EXIT_FAILURE; exit = EXIT_FAILURE;
goto finish; goto finish;
} }
if (UtilLastModified(serverCfg->tls.key)) if (UInt64Eq(UtilLastModified(serverCfg->tls.key), UInt64Create(0, 0)))
{ {
Log(LOG_ERR, "%s: %s", strerror(errno), serverCfg->tls.key); Log(LOG_ERR, "%s: %s", strerror(errno), serverCfg->tls.key);
exit = EXIT_FAILURE; exit = EXIT_FAILURE;

View file

@ -27,6 +27,7 @@
#include <Cytoplasm/Memory.h> #include <Cytoplasm/Memory.h>
#include <Cytoplasm/Str.h> #include <Cytoplasm/Str.h>
#include <Cytoplasm/Int.h>
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
@ -37,7 +38,7 @@
#define Iterate(s) (*(*s)++) #define Iterate(s) (*(*s)++)
/* Parse an extended localpart */ /* Parse an extended localpart */
static bool static int
ParseUserLocalpart(char **str, char **out) ParseUserLocalpart(char **str, char **out)
{ {
char c; char c;
@ -46,7 +47,7 @@ ParseUserLocalpart(char **str, char **out)
if (!str || !out) if (!str || !out)
{ {
return false; return 0;
} }
/* An extended localpart contains every ASCII printable character, /* An extended localpart contains every ASCII printable character,
* except an ':'. */ * except an ':'. */
@ -59,7 +60,7 @@ ParseUserLocalpart(char **str, char **out)
if (length < 1) if (length < 1)
{ {
*str = start; *str = start;
return false; return 0;
} }
if (c == ':') if (c == ':')
{ {
@ -70,9 +71,8 @@ ParseUserLocalpart(char **str, char **out)
memcpy(*out, start, length); memcpy(*out, start, length);
(*out)[length] = '\0'; (*out)[length] = '\0';
return true; return 1;
} }
/* Parses an IPv4 address. */ /* Parses an IPv4 address. */
static int static int
ParseIPv4(char **str, char **out) ParseIPv4(char **str, char **out)
@ -86,7 +86,7 @@ ParseIPv4(char **str, char **out)
int digit = 0; int digit = 0;
int digits = 0; int digits = 0;
memset(buffer, 0, sizeof(buffer)); memset(buffer, '\0', 4);
start = *str; start = *str;
/* An IPv4 address is made of 4 blocks between 1-3 digits, like so: /* An IPv4 address is made of 4 blocks between 1-3 digits, like so:
@ -102,38 +102,36 @@ ParseIPv4(char **str, char **out)
{ {
/* Current digit is too long for the spec! */ /* Current digit is too long for the spec! */
*str = start; *str = start;
return false; return 0;
} }
memcpy(buffer, *str - digit - 1, digit); memcpy(buffer, *str - digit - 1, digit);
if (atoi(buffer) > 255) if (atoi(buffer) > 255)
{ {
/* Current digit is too large for the spec! */ /* Current digit is too large for the spec! */
*str = start; *str = start;
return false; return 0;
} }
memset(buffer, 0, sizeof(buffer)); memset(buffer, '\0', 4);
digit = 0; digit = 0;
digits++; /* We have parsed a digit. */ digits++; /* We have parsed a digit. */
} }
if (c == '.' || digits != 3) if (c == '.' || digits != 3)
{ {
*str = start; *str = start;
return false; return 0;
} }
length = (size_t) (*str - start) - 1; length = (size_t) (*str - start) - 1;
*out = Malloc(length + 1); *out = Malloc(length + 1);
memcpy(*out, start, length); memcpy(*out, start, length);
(*str)--; (*str)--;
return true; return 1;
} }
static int
static bool
IsIPv6Char(char c) IsIPv6Char(char c)
{ {
return (isxdigit(c) || c == ':' || c == '.'); return isxdigit(c) || c == ':' || c == '.';
} }
static int
static bool
ParseIPv6(char **str, char **out) ParseIPv6(char **str, char **out)
{ {
char *start; char *start;
@ -152,7 +150,7 @@ ParseIPv6(char **str, char **out)
goto fail; goto fail;
} }
while ((c = Iterate(str)) && IsIPv6Char(c) && digits < 8) while ((c = Iterate(str)) && IsIPv6Char(c))
{ {
char *ipv4; char *ipv4;
if (isxdigit(c)) if (isxdigit(c))
@ -176,7 +174,7 @@ ParseIPv6(char **str, char **out)
/* RFC3513 says the following: /* RFC3513 says the following:
* > 'The "::" can only appear once in an address.' */ * > 'The "::" can only appear once in an address.' */
*str = start; *str = start;
return false; return 0;
} }
if (digit < 1 || digit > 4) if (digit < 1 || digit > 4)
{ {
@ -219,13 +217,12 @@ end:
memset(*out, '\0', length + 1); memset(*out, '\0', length + 1);
memcpy(*out, start, length); memcpy(*out, start, length);
return true; return 1;
fail: fail:
*str = start; *str = start;
return false; return 0;
} }
static int
static bool
ParseHostname(char **str, char **out) ParseHostname(char **str, char **out)
{ {
char *start; char *start;
@ -242,16 +239,16 @@ ParseHostname(char **str, char **out)
if (length < 1 || length > 255) if (length < 1 || length > 255)
{ {
*str = start; *str = start;
return false; return 0;
} }
length = (size_t) (*str - start) - 1; length = (size_t) (*str - start) - 1;
*out = Malloc(length + 1); *out = Malloc(length + 1);
memcpy(*out, start, length); memcpy(*out, start, length);
(*str)--; (*str)--;
return true; return 1;
} }
static bool static int
ParseServerName(char **str, ServerPart *out) ParseServerName(char **str, ServerPart *out)
{ {
char c; char c;
@ -264,7 +261,7 @@ ParseServerName(char **str, ServerPart *out)
if (!str || !out) if (!str || !out)
{ {
return false; return 0;
} }
start = *str; start = *str;
@ -287,7 +284,7 @@ ParseServerName(char **str, ServerPart *out)
if (!host) if (!host)
{ {
/* Can't parse a valid server name. */ /* Can't parse a valid server name. */
return false; return 0;
} }
/* Now, there's only 2 options: a ':', or the end(everything else.) */ /* Now, there's only 2 options: a ':', or the end(everything else.) */
if (**str != ':') if (**str != ':')
@ -295,7 +292,7 @@ ParseServerName(char **str, ServerPart *out)
/* We're done. */ /* We're done. */
out->hostname = host; out->hostname = host;
out->port = NULL; out->port = NULL;
return true; return 1;
} }
/* TODO: Separate this out */ /* TODO: Separate this out */
startPort = ++(*str); startPort = ++(*str);
@ -308,7 +305,7 @@ ParseServerName(char **str, ServerPart *out)
*str = start; *str = start;
Free(host); Free(host);
host = NULL; host = NULL;
return false; return 0;
} }
port = Malloc(chars + 1); port = Malloc(chars + 1);
@ -319,26 +316,24 @@ ParseServerName(char **str, ServerPart *out)
Free(port); Free(port);
Free(host); Free(host);
*str = start; *str = start;
return false; return 0;
} }
out->hostname = host; out->hostname = host;
out->port = port; out->port = port;
return true; return 1;
} }
int
bool
ParseServerPart(char *str, ServerPart *part) ParseServerPart(char *str, ServerPart *part)
{ {
/* This is a wrapper behind the internal ParseServerName. */ /* This is a wrapper behind the internal ParseServerName. */
if (!str || !part) if (!str || !part)
{ {
return false; return 0;
} }
return ParseServerName(&str, part); return ParseServerName(&str, part);
} }
void void
ServerPartFree(ServerPart part) ServerPartFree(ServerPart part)
{ {
@ -352,20 +347,20 @@ ServerPartFree(ServerPart part)
} }
} }
bool int
ParseCommonID(char *str, CommonID *id) ParseCommonID(char *str, CommonID *id)
{ {
char sigil; char sigil;
if (!str || !id) if (!str || !id)
{ {
return false; return 0;
} }
/* There must at least be 2 chararacters: the sigil and a string.*/ /* There must at least be 2 chararacters: the sigil and a string.*/
if (strlen(str) < 2) if (strlen(str) < 2)
{ {
return false; return 0;
} }
sigil = *str++; sigil = *str++;
@ -374,7 +369,7 @@ ParseCommonID(char *str, CommonID *id)
*/ */
if ((sigil == '#' || sigil == '@') && strlen(str) > 255) if ((sigil == '#' || sigil == '@') && strlen(str) > 255)
{ {
return false; return 0;
} }
id->sigil = sigil; id->sigil = sigil;
id->local = NULL; id->local = NULL;
@ -388,7 +383,7 @@ ParseCommonID(char *str, CommonID *id)
* accepting it all. */ * accepting it all. */
if (!ParseUserLocalpart(&str, &id->local)) if (!ParseUserLocalpart(&str, &id->local))
{ {
return false; return 0;
} }
if (*str == ':') if (*str == ':')
{ {
@ -397,9 +392,9 @@ ParseCommonID(char *str, CommonID *id)
{ {
Free(id->local); Free(id->local);
id->local = NULL; id->local = NULL;
return false; return 0;
} }
return true; return 1;
} }
break; break;
case '!': case '!':
@ -408,23 +403,23 @@ ParseCommonID(char *str, CommonID *id)
case '@': case '@':
if (!ParseUserLocalpart(&str, &id->local)) if (!ParseUserLocalpart(&str, &id->local))
{ {
return false; return 0;
} }
if (*str++ != ':') if (*str++ != ':')
{ {
Free(id->local); Free(id->local);
id->local = NULL; id->local = NULL;
return false; return 0;
} }
if (!ParseServerName(&str, &id->server)) if (!ParseServerName(&str, &id->server))
{ {
Free(id->local); Free(id->local);
id->local = NULL; id->local = NULL;
return false; return 0;
} }
break; break;
} }
return true; return 1;
} }
void void
@ -436,18 +431,15 @@ CommonIDFree(CommonID id)
} }
ServerPartFree(id.server); ServerPartFree(id.server);
} }
int
bool
ValidCommonID(char *str, char sigil) ValidCommonID(char *str, char sigil)
{ {
CommonID id; CommonID id;
bool ret; int ret;
memset(&id, 0, sizeof(CommonID)); memset(&id, 0, sizeof(CommonID));
if (!str) if (!str)
{ {
return false; return 0;
} }
ret = ParseCommonID(str, &id) && id.sigil == sigil; ret = ParseCommonID(str, &id) && id.sigil == sigil;
@ -455,7 +447,6 @@ ValidCommonID(char *str, char sigil)
CommonIDFree(id); CommonIDFree(id);
return ret; return ret;
} }
char * char *
ParserRecomposeServerPart(ServerPart serverPart) ParserRecomposeServerPart(ServerPart serverPart)
{ {
@ -469,11 +460,10 @@ ParserRecomposeServerPart(ServerPart serverPart)
} }
return NULL; return NULL;
} }
char * char *
ParserRecomposeCommonID(CommonID id) ParserRecomposeCommonID(CommonID id)
{ {
char *ret = Malloc(2 * sizeof(char)); char *ret = Malloc(2);
ret[0] = id.sigil; ret[0] = id.sigil;
ret[1] = '\0'; ret[1] = '\0';
@ -495,18 +485,15 @@ ParserRecomposeCommonID(CommonID id)
} }
return ret; return ret;
} }
int
bool
ParserServerNameEquals(ServerPart serverPart, char *str) ParserServerNameEquals(ServerPart serverPart, char *str)
{ {
char *idServer; char *idServer;
bool ret; int ret;
if (!str) if (!str)
{ {
return false; return 0;
} }
idServer = ParserRecomposeServerPart(serverPart); idServer = ParserRecomposeServerPart(serverPart);
ret = StrEquals(idServer, str); ret = StrEquals(idServer, str);

View file

@ -31,6 +31,7 @@
#include <Cytoplasm/Json.h> #include <Cytoplasm/Json.h>
#include <Cytoplasm/Util.h> #include <Cytoplasm/Util.h>
#include <Cytoplasm/Str.h> #include <Cytoplasm/Str.h>
#include <Cytoplasm/Int64.h>
#include <Cytoplasm/Log.h> #include <Cytoplasm/Log.h>
#include <User.h> #include <User.h>
@ -39,9 +40,9 @@ int
RegTokenValid(RegTokenInfo * token) RegTokenValid(RegTokenInfo * token)
{ {
HashMap *tokenJson; HashMap *tokenJson;
int64_t uses, used; Int64 uses, used;
uint64_t expiration; UInt64 expiration;
if (!token || !RegTokenExists(token->db, token->name)) if (!token || !RegTokenExists(token->db, token->name))
{ {
@ -53,7 +54,9 @@ RegTokenValid(RegTokenInfo * token)
used = JsonValueAsInteger(HashMapGet(tokenJson, "used")); used = JsonValueAsInteger(HashMapGet(tokenJson, "used"));
expiration = JsonValueAsInteger(HashMapGet(tokenJson, "expires_on")); expiration = JsonValueAsInteger(HashMapGet(tokenJson, "expires_on"));
return (!expiration || (UtilTsMillis() < expiration)) && (uses == -1 || used < uses); return (UInt64Eq(expiration, UInt64Create(0, 0)) ||
UInt64Geq(UtilServerTs(), expiration)) &&
(Int64Eq(uses, Int64Neg(Int64Create(0, 1))) || Int64Lt(used, uses));
} }
void void
RegTokenUse(RegTokenInfo * token) RegTokenUse(RegTokenInfo * token)
@ -65,12 +68,13 @@ RegTokenUse(RegTokenInfo * token)
return; return;
} }
if (token->uses >= 0 && token->used >= token->uses) if (Int64Geq(token->uses, Int64Create(0, 0)) &&
Int64Geq(token->used, token->uses))
{ {
return; return;
} }
token->used++; token->used = Int64Add(token->used, Int64Create(0, 1));
/* Write the information to the hashmap */ /* Write the information to the hashmap */
tokenJson = DbJson(token->ref); tokenJson = DbJson(token->ref);
@ -195,11 +199,11 @@ RegTokenVerify(char *token)
} }
RegTokenInfo * RegTokenInfo *
RegTokenCreate(Db * db, char *name, char *owner, uint64_t expires, int64_t uses, int privileges) RegTokenCreate(Db * db, char *name, char *owner, UInt64 expires, Int64 uses, int privileges)
{ {
RegTokenInfo *ret; RegTokenInfo *ret;
uint64_t timestamp = UtilTsMillis(); UInt64 timestamp = UtilServerTs();
if (!db || !name) if (!db || !name)
{ {
@ -209,13 +213,13 @@ RegTokenCreate(Db * db, char *name, char *owner, uint64_t expires, int64_t uses,
/* -1 indicates infinite uses; zero and all positive values are a /* -1 indicates infinite uses; zero and all positive values are a
* valid number of uses; althought zero would be rather useless. * valid number of uses; althought zero would be rather useless.
* Anything less than -1 doesn't make sense. */ * Anything less than -1 doesn't make sense. */
if (uses < -1) if (Int64Lt(uses, Int64Neg(Int64Create(0, 1))))
{ {
return NULL; return NULL;
} }
/* Verify the token */ /* Verify the token */
if (!RegTokenVerify(name) || ((expires > 0) && (expires < timestamp))) if (!RegTokenVerify(name) || (UInt64Gt(expires, UInt64Create(0, 0)) && UInt64Lt(expires, timestamp)))
{ {
return NULL; return NULL;
} }
@ -231,7 +235,7 @@ RegTokenCreate(Db * db, char *name, char *owner, uint64_t expires, int64_t uses,
} }
ret->name = StrDuplicate(name); ret->name = StrDuplicate(name);
ret->created_by = StrDuplicate(owner); ret->created_by = StrDuplicate(owner);
ret->used = 0; ret->used = Int64Create(0, 0);
ret->uses = uses; ret->uses = uses;
ret->created_on = timestamp; ret->created_on = timestamp;
ret->expires_on = expires; ret->expires_on = expires;

View file

@ -72,7 +72,6 @@ RouterBuild(void)
R("/_matrix/client/v3/profile/(.*)", RouteUserProfile); R("/_matrix/client/v3/profile/(.*)", RouteUserProfile);
R("/_matrix/client/v3/profile/(.*)/(avatar_url|displayname)", RouteUserProfile); R("/_matrix/client/v3/profile/(.*)/(avatar_url|displayname)", RouteUserProfile);
R("/_matrix/client/v3/user_directory/search", RouteUserDirectory);
R("/_matrix/client/v3/user/(.*)/filter", RouteFilter); R("/_matrix/client/v3/user/(.*)/filter", RouteFilter);
R("/_matrix/client/v3/user/(.*)/filter/(.*)", RouteFilter); R("/_matrix/client/v3/user/(.*)/filter/(.*)", RouteFilter);

View file

@ -24,6 +24,7 @@
*/ */
#include <Routes.h> #include <Routes.h>
#include <Cytoplasm/Int64.h>
#include <User.h> #include <User.h>
#include <Cytoplasm/Memory.h> #include <Cytoplasm/Memory.h>
#include <Cytoplasm/Str.h> #include <Cytoplasm/Str.h>
@ -85,11 +86,24 @@ ROUTE_IMPL(RouteProcControl, path, argp)
if (StrEquals(op, "stats")) if (StrEquals(op, "stats"))
{ {
size_t allocated = MemoryAllocated(); size_t allocated = MemoryAllocated();
Int64 a;
response = HashMapCreate(); response = HashMapCreate();
if (sizeof(size_t) == sizeof(Int64))
{
UInt32 high = (UInt32) (allocated >> 32);
UInt32 low = (UInt32) (allocated);
a = Int64Create(high, low);
}
else
{
a = Int64Create(0, allocated);
}
HashMapSet(response, "version", JsonValueString(TELODENDRIA_VERSION)); HashMapSet(response, "version", JsonValueString(TELODENDRIA_VERSION));
HashMapSet(response, "memory_allocated", JsonValueInteger(allocated)); HashMapSet(response, "memory_allocated", JsonValueInteger(a));
goto finish; goto finish;
} }

View file

@ -40,6 +40,8 @@ ROUTE_IMPL(RouteRequestToken, path, argp)
RequestToken reqTok; RequestToken reqTok;
Int64 minusOne = Int64Neg(Int64Create(0, 1));
reqTok.client_secret = NULL; reqTok.client_secret = NULL;
reqTok.next_link = NULL; reqTok.next_link = NULL;
reqTok.id_access_token = NULL; reqTok.id_access_token = NULL;
@ -49,7 +51,7 @@ ROUTE_IMPL(RouteRequestToken, path, argp)
reqTok.country = NULL; reqTok.country = NULL;
reqTok.phone_number = NULL; reqTok.phone_number = NULL;
reqTok.send_attempt = -1; reqTok.send_attempt = minusOne;
if (HttpRequestMethodGet(args->context) != HTTP_POST) if (HttpRequestMethodGet(args->context) != HTTP_POST)
{ {
@ -88,7 +90,7 @@ ROUTE_IMPL(RouteRequestToken, path, argp)
goto finish; goto finish;
} }
if (reqTok.send_attempt == -1) if (Int64Eq(reqTok.send_attempt, minusOne))
{ {
msg = "Invalid or inexistent 'send_attempt'"; msg = "Invalid or inexistent 'send_attempt'";
HttpResponseStatus(args->context, HTTP_BAD_REQUEST); HttpResponseStatus(args->context, HTTP_BAD_REQUEST);

View file

@ -1,199 +0,0 @@
/*
* 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 dirRequest.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 <Routes.h>
#include <Cytoplasm/Array.h>
#include <Cytoplasm/HashMap.h>
#include <Cytoplasm/Json.h>
#include <Cytoplasm/Str.h>
#include <Cytoplasm/Memory.h>
#include <Cytoplasm/Db.h>
#include <Schema/UserDirectoryRequest.h>
#include <User.h>
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 = UserAuthenticate(db, 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;
}

View file

@ -185,6 +185,8 @@ ROUTE_IMPL(RouteUserProfile, path, argp)
finish: finish:
ConfigUnlock(&config); ConfigUnlock(&config);
/* Username is handled by the router, freeing it would cause issues. */
Free(entry);
UserIdFree(userId); UserIdFree(userId);
UserUnlock(user); UserUnlock(user);
JsonFree(request); JsonFree(request);

View file

@ -43,6 +43,7 @@ ROUTE_IMPL(RouteWhoami, path, argp)
char *token; char *token;
char *userID; char *userID;
char *deviceID; char *deviceID;
char *msg;
Config config; Config config;

View file

@ -133,7 +133,7 @@ TelodendriaPrintHeader(void)
Log(LOG_INFO, "%s", TelodendriaHeader[i]); Log(LOG_INFO, "%s", TelodendriaHeader[i]);
} }
Log(LOG_INFO, "Telodendria v" TELODENDRIA_VERSION " (Cytoplasm v%s)", CytoplasmGetVersionStr()); Log(LOG_INFO, "Telodendria v" TELODENDRIA_VERSION " (%s v%s)", CytoplasmGetName(), CytoplasmGetVersion());
Log(LOG_INFO, ""); Log(LOG_INFO, "");
Log(LOG_INFO, Log(LOG_INFO,
"Copyright (C) 2024 Jordan Bancino <@jordan:bancino.net>"); "Copyright (C) 2024 Jordan Bancino <@jordan:bancino.net>");

View file

@ -135,7 +135,7 @@ BuildResponse(Array * flows, Db * db, HashMap ** response, char *session, DbRef
json = DbJson(ref); json = DbJson(ref);
HashMapSet(json, "completed", JsonValueArray(ArrayCreate())); HashMapSet(json, "completed", JsonValueArray(ArrayCreate()));
HashMapSet(json, "last_access", JsonValueInteger(UtilTsMillis())); HashMapSet(json, "last_access", JsonValueInteger(UtilServerTs()));
DbUnlock(db, ref); DbUnlock(db, ref);
HashMapSet(*response, "completed", JsonValueArray(ArrayCreate())); HashMapSet(*response, "completed", JsonValueArray(ArrayCreate()));
@ -452,7 +452,7 @@ UiaComplete(Array * flows, HttpServerContext * context, Db * db,
finish: finish:
ArrayFree(possibleNext); ArrayFree(possibleNext);
JsonValueFree(HashMapSet(dbJson, "last_access", JsonValueInteger(UtilTsMillis()))); JsonValueFree(HashMapSet(dbJson, "last_access", JsonValueInteger(UtilServerTs())));
DbUnlock(db, dbRef); DbUnlock(db, dbRef);
return ret; return ret;
} }
@ -498,7 +498,7 @@ UiaCleanup(MatrixHttpHandlerArgs * args)
char *session = ArrayGet(sessions, i); char *session = ArrayGet(sessions, i);
DbRef *ref = DbLock(args->db, 2, "user_interactive", session); DbRef *ref = DbLock(args->db, 2, "user_interactive", session);
uint64_t lastAccess; UInt64 lastAccess;
if (!ref) if (!ref)
{ {
@ -513,7 +513,7 @@ UiaCleanup(MatrixHttpHandlerArgs * args)
/* If last access was greater than 15 minutes ago, remove this /* If last access was greater than 15 minutes ago, remove this
* session */ * session */
if ((UtilTsMillis() - lastAccess) > (1000 * 60 * 15)) if (UInt64Gt(UInt64Sub(UtilServerTs(), lastAccess), UInt64Create(0, 1000 * 60 * 15)))
{ {
DbDelete(args->db, 2, "user_interactive", session); DbDelete(args->db, 2, "user_interactive", session);
Log(LOG_DEBUG, "Deleted session %s", session); Log(LOG_DEBUG, "Deleted session %s", session);

View file

@ -28,6 +28,8 @@
#include <Cytoplasm/Str.h> #include <Cytoplasm/Str.h>
#include <Cytoplasm/Sha.h> #include <Cytoplasm/Sha.h>
#include <Cytoplasm/Json.h> #include <Cytoplasm/Json.h>
#include <Cytoplasm/Int64.h>
#include <Cytoplasm/UInt64.h>
#include <Parser.h> #include <Parser.h>
@ -42,7 +44,7 @@ struct User
char *deviceId; char *deviceId;
}; };
bool int
UserValidate(char *localpart, char *domain) UserValidate(char *localpart, char *domain)
{ {
size_t maxLen = 255 - strlen(domain) - 1; size_t maxLen = 255 - strlen(domain) - 1;
@ -54,23 +56,23 @@ UserValidate(char *localpart, char *domain)
if (i > maxLen) if (i > maxLen)
{ {
return false; return 0;
} }
if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
(c == '.') || (c == '_') || (c == '=') || (c == '-') || (c == '.') || (c == '_') || (c == '=') || (c == '-') ||
(c == '/'))) (c == '/')))
{ {
return false; return 0;
} }
i++; i++;
} }
return true; return 1;
} }
bool int
UserHistoricalValidate(char *localpart, char *domain) UserHistoricalValidate(char *localpart, char *domain)
{ {
size_t maxLen = 255 - strlen(domain) - 1; size_t maxLen = 255 - strlen(domain) - 1;
@ -82,21 +84,21 @@ UserHistoricalValidate(char *localpart, char *domain)
if (i > maxLen) if (i > maxLen)
{ {
return false; return 0;
} }
if (!((c >= 0x21 && c <= 0x39) || (c >= 0x3B && c <= 0x7E))) if (!((c >= 0x21 && c <= 0x39) || (c >= 0x3B && c <= 0x7E)))
{ {
return false; return 0;
} }
i++; i++;
} }
return true; return 1;
} }
bool int
UserExists(Db * db, char *name) UserExists(Db * db, char *name)
{ {
return DbExists(db, 2, "users", name); return DbExists(db, 2, "users", name);
@ -131,7 +133,7 @@ UserAuthenticate(Db * db, char *accessToken)
char *userName; char *userName;
char *deviceId; char *deviceId;
uint64_t expires; UInt64 expires;
if (!db || !accessToken) if (!db || !accessToken)
{ {
@ -155,7 +157,8 @@ UserAuthenticate(Db * db, char *accessToken)
return NULL; return NULL;
} }
if (expires && UtilTsMillis() >= expires) if (UInt64Neq(expires, UInt64Create(0, 0)) &&
UInt64Geq(UtilServerTs(), expires))
{ {
UserUnlock(user); UserUnlock(user);
DbUnlock(db, atRef); DbUnlock(db, atRef);
@ -168,14 +171,14 @@ UserAuthenticate(Db * db, char *accessToken)
return user; return user;
} }
bool int
UserUnlock(User * user) UserUnlock(User * user)
{ {
bool ret; int ret;
if (!user) if (!user)
{ {
return false; return 0;
} }
Free(user->name); Free(user->name);
@ -193,7 +196,7 @@ UserCreate(Db * db, char *name, char *password)
User *user = NULL; User *user = NULL;
HashMap *json = NULL; HashMap *json = NULL;
uint64_t ts = UtilTsMillis(); UInt64 ts = UtilServerTs();
/* TODO: Put some sort of password policy(like for example at least /* TODO: Put some sort of password policy(like for example at least
* 8 chars, or maybe check it's entropy)? */ * 8 chars, or maybe check it's entropy)? */
@ -230,7 +233,7 @@ UserCreate(Db * db, char *name, char *password)
json = DbJson(user->ref); json = DbJson(user->ref);
HashMapSet(json, "createdOn", JsonValueInteger(ts)); HashMapSet(json, "createdOn", JsonValueInteger(ts));
HashMapSet(json, "deactivated", JsonValueBoolean(false)); HashMapSet(json, "deactivated", JsonValueBoolean(0));
return user; return user;
} }
@ -353,7 +356,7 @@ UserGetDeviceId(User * user)
return user ? user->deviceId : NULL; return user ? user->deviceId : NULL;
} }
bool int
UserCheckPassword(User * user, char *password) UserCheckPassword(User * user, char *password)
{ {
HashMap *json; HashMap *json;
@ -365,11 +368,11 @@ UserCheckPassword(User * user, char *password)
char *hashedPwd; char *hashedPwd;
char *tmp; char *tmp;
bool result; int result;
if (!user || !password) if (!user || !password)
{ {
return false; return 0;
} }
json = DbJson(user->ref); json = DbJson(user->ref);
@ -379,12 +382,12 @@ UserCheckPassword(User * user, char *password)
if (!storedHash || !salt) if (!storedHash || !salt)
{ {
return false; return 0;
} }
tmp = StrConcat(2, password, salt); tmp = StrConcat(2, password, salt);
hashBytes = Sha256(tmp); hashBytes = Sha256(tmp);
hashedPwd = ShaToHex(hashBytes, HASH_SHA256); hashedPwd = ShaToHex(hashBytes);
Free(tmp); Free(tmp);
Free(hashBytes); Free(hashBytes);
@ -395,7 +398,7 @@ UserCheckPassword(User * user, char *password)
return result; return result;
} }
bool int
UserSetPassword(User * user, char *password) UserSetPassword(User * user, char *password)
{ {
HashMap *json; HashMap *json;
@ -407,7 +410,7 @@ UserSetPassword(User * user, char *password)
if (!user || !password) if (!user || !password)
{ {
return false; return 0;
} }
json = DbJson(user->ref); json = DbJson(user->ref);
@ -415,7 +418,7 @@ UserSetPassword(User * user, char *password)
salt = StrRandom(16); salt = StrRandom(16);
tmpstr = StrConcat(2, password, salt); tmpstr = StrConcat(2, password, salt);
hashBytes = Sha256(tmpstr); hashBytes = Sha256(tmpstr);
hash = ShaToHex(hashBytes, HASH_SHA256); hash = ShaToHex(hashBytes);
JsonValueFree(HashMapSet(json, "salt", JsonValueString(salt))); JsonValueFree(HashMapSet(json, "salt", JsonValueString(salt)));
JsonValueFree(HashMapSet(json, "password", JsonValueString(hash))); JsonValueFree(HashMapSet(json, "password", JsonValueString(hash)));
@ -425,10 +428,10 @@ UserSetPassword(User * user, char *password)
Free(hashBytes); Free(hashBytes);
Free(tmpstr); Free(tmpstr);
return true; return 1;
} }
bool int
UserDeactivate(User * user, char * from, char * reason) UserDeactivate(User * user, char * from, char * reason)
{ {
HashMap *json; HashMap *json;
@ -436,7 +439,7 @@ UserDeactivate(User * user, char * from, char * reason)
if (!user) if (!user)
{ {
return false; return 0;
} }
/* By default, it's the target's username */ /* By default, it's the target's username */
@ -447,7 +450,7 @@ UserDeactivate(User * user, char * from, char * reason)
json = DbJson(user->ref); json = DbJson(user->ref);
JsonValueFree(HashMapSet(json, "deactivated", JsonValueBoolean(true))); JsonValueFree(HashMapSet(json, "deactivated", JsonValueBoolean(1)));
val = JsonValueString(from); val = JsonValueString(from);
JsonValueFree(JsonSet(json, val, 2, "deactivate", "by")); JsonValueFree(JsonSet(json, val, 2, "deactivate", "by"));
@ -457,38 +460,38 @@ UserDeactivate(User * user, char * from, char * reason)
JsonValueFree(JsonSet(json, val, 2, "deactivate", "reason")); JsonValueFree(JsonSet(json, val, 2, "deactivate", "reason"));
} }
return true; return 1;
} }
bool int
UserReactivate(User * user) UserReactivate(User * user)
{ {
HashMap *json; HashMap *json;
if (!user) if (!user)
{ {
return false; return 0;
} }
json = DbJson(user->ref); json = DbJson(user->ref);
JsonValueFree(HashMapSet(json, "deactivated", JsonValueBoolean(false))); JsonValueFree(HashMapSet(json, "deactivated", JsonValueBoolean(0)));
JsonValueFree(HashMapDelete(json, "deactivate")); JsonValueFree(HashMapDelete(json, "deactivate"));
return true; return 1;
} }
bool int
UserDeactivated(User * user) UserDeactivated(User * user)
{ {
HashMap *json; HashMap *json;
if (!user) if (!user)
{ {
return true; return 1;
} }
json = DbJson(user->ref); json = DbJson(user->ref);
@ -534,17 +537,17 @@ UserAccessTokenGenerate(User * user, char *deviceId, int withRefresh)
if (withRefresh) if (withRefresh)
{ {
token->lifetime = 1000 * 60 * 60 * 24 * 7; /* 1 Week */ token->lifetime = Int64Create(0, 1000 * 60 * 60 * 24 * 7); /* 1 Week */
} }
else else
{ {
token->lifetime = 0; token->lifetime = Int64Create(0, 0);
} }
return token; return token;
} }
bool int
UserAccessTokenSave(Db * db, UserAccessToken * token) UserAccessTokenSave(Db * db, UserAccessToken * token)
{ {
DbRef *ref; DbRef *ref;
@ -552,14 +555,14 @@ UserAccessTokenSave(Db * db, UserAccessToken * token)
if (!token) if (!token)
{ {
return false; return 0;
} }
ref = DbCreate(db, 3, "tokens", "access", token->string); ref = DbCreate(db, 3, "tokens", "access", token->string);
if (!ref) if (!ref)
{ {
return false; return 0;
} }
json = DbJson(ref); json = DbJson(ref);
@ -567,9 +570,9 @@ UserAccessTokenSave(Db * db, UserAccessToken * token)
HashMapSet(json, "user", JsonValueString(token->user)); HashMapSet(json, "user", JsonValueString(token->user));
HashMapSet(json, "device", JsonValueString(token->deviceId)); HashMapSet(json, "device", JsonValueString(token->deviceId));
if (token->lifetime) if (Int64Neq(token->lifetime, Int64Create(0, 0)))
{ {
HashMapSet(json, "expires", JsonValueInteger(UtilTsMillis() + token->lifetime)); HashMapSet(json, "expires", JsonValueInteger(UInt64Add(UtilServerTs(), token->lifetime)));
} }
return DbUnlock(db, ref); return DbUnlock(db, ref);
@ -589,7 +592,7 @@ UserAccessTokenFree(UserAccessToken * token)
Free(token); Free(token);
} }
bool int
UserDeleteToken(User * user, char *token) UserDeleteToken(User * user, char *token)
{ {
char *username; char *username;
@ -607,14 +610,14 @@ UserDeleteToken(User * user, char *token)
if (!user || !token) if (!user || !token)
{ {
return false; return 0;
} }
db = user->db; db = user->db;
/* First check if the token even exists */ /* First check if the token even exists */
if (!DbExists(db, 3, "tokens", "access", token)) if (!DbExists(db, 3, "tokens", "access", token))
{ {
return false; return 0;
} }
/* If it does, get it's username. */ /* If it does, get it's username. */
@ -622,7 +625,7 @@ UserDeleteToken(User * user, char *token)
if (!tokenRef) if (!tokenRef)
{ {
return false; return 0;
} }
tokenJson = DbJson(tokenRef); tokenJson = DbJson(tokenRef);
username = JsonValueAsString(HashMapGet(tokenJson, "user")); username = JsonValueAsString(HashMapGet(tokenJson, "user"));
@ -632,7 +635,7 @@ UserDeleteToken(User * user, char *token)
{ {
/* Token does not match user, do not delete it */ /* Token does not match user, do not delete it */
DbUnlock(db, tokenRef); DbUnlock(db, tokenRef);
return false; return 0;
} }
userJson = DbJson(user->ref); userJson = DbJson(user->ref);
@ -640,7 +643,7 @@ UserDeleteToken(User * user, char *token)
if (!deviceObj) if (!deviceObj)
{ {
return false; return 0;
} }
/* Delete refresh token, if present */ /* Delete refresh token, if present */
@ -654,17 +657,17 @@ UserDeleteToken(User * user, char *token)
deletedVal = HashMapDelete(deviceObj, deviceId); deletedVal = HashMapDelete(deviceObj, deviceId);
if (!deletedVal) if (!deletedVal)
{ {
return false; return 0;
} }
JsonValueFree(deletedVal); JsonValueFree(deletedVal);
/* Delete the access token. */ /* Delete the access token. */
if (!DbUnlock(db, tokenRef) || !DbDelete(db, 3, "tokens", "access", token)) if (!DbUnlock(db, tokenRef) || !DbDelete(db, 3, "tokens", "access", token))
{ {
return false; return 0;
} }
return true; return 1;
} }
char * char *
@ -696,7 +699,7 @@ UserSetProfile(User * user, char *name, char *val)
JsonValueFree(JsonSet(json, JsonValueString(val), 2, "profile", name)); JsonValueFree(JsonSet(json, JsonValueString(val), 2, "profile", name));
} }
bool int
UserDeleteTokens(User * user, char *exempt) UserDeleteTokens(User * user, char *exempt)
{ {
HashMap *devices; HashMap *devices;
@ -705,13 +708,13 @@ UserDeleteTokens(User * user, char *exempt)
if (!user) if (!user)
{ {
return false; return 0;
} }
devices = JsonValueAsObject(HashMapGet(DbJson(user->ref), "devices")); devices = JsonValueAsObject(HashMapGet(DbJson(user->ref), "devices"));
if (!devices) if (!devices)
{ {
return false; return 0;
} }
while (HashMapIterate(devices, &deviceId, (void **) &deviceObj)) while (HashMapIterate(devices, &deviceId, (void **) &deviceObj))
@ -738,7 +741,7 @@ UserDeleteTokens(User * user, char *exempt)
JsonValueFree(HashMapDelete(devices, deviceId)); JsonValueFree(HashMapDelete(devices, deviceId));
} }
return true; return 1;
} }
int int
@ -752,30 +755,30 @@ UserGetPrivileges(User * user)
return UserDecodePrivileges(JsonValueAsArray(HashMapGet(DbJson(user->ref), "privileges"))); return UserDecodePrivileges(JsonValueAsArray(HashMapGet(DbJson(user->ref), "privileges")));
} }
bool int
UserSetPrivileges(User * user, int privileges) UserSetPrivileges(User * user, int privileges)
{ {
JsonValue *val; JsonValue *val;
if (!user) if (!user)
{ {
return false; return 0;
} }
if (!privileges) if (!privileges)
{ {
JsonValueFree(HashMapDelete(DbJson(user->ref), "privileges")); JsonValueFree(HashMapDelete(DbJson(user->ref), "privileges"));
return true; return 1;
} }
val = JsonValueArray(UserEncodePrivileges(privileges)); val = JsonValueArray(UserEncodePrivileges(privileges));
if (!val) if (!val)
{ {
return false; return 0;
} }
JsonValueFree(HashMapSet(DbJson(user->ref), "privileges", val)); JsonValueFree(HashMapSet(DbJson(user->ref), "privileges", val));
return true; return 1;
} }
int int

View file

@ -25,8 +25,6 @@
#ifndef TELODENDRIA_PARSER_H #ifndef TELODENDRIA_PARSER_H
#define TELODENDRIA_PARSER_H #define TELODENDRIA_PARSER_H
#include <stdbool.h>
/*** /***
* @Nm Parser * @Nm Parser
* @Nd Functions for dealing with grammars found in Matrix * @Nd Functions for dealing with grammars found in Matrix
@ -60,17 +58,17 @@ typedef struct CommonID {
* Parses a common identifier, as per the Common Identifier Format as defined * Parses a common identifier, as per the Common Identifier Format as defined
* by the [matrix] specification. * by the [matrix] specification.
*/ */
extern bool ParseCommonID(char *, CommonID *); extern int ParseCommonID(char *, CommonID *);
/** /**
* Parses the server part in a common identifier. * Parses the server part in a common identifier.
*/ */
extern bool ParseServerPart(char *, ServerPart *); extern int ParseServerPart(char *, ServerPart *);
/** /**
* Checks whenever the string is a valid common ID with the correct sigil. * Checks whenever the string is a valid common ID with the correct sigil.
*/ */
extern bool ValidCommonID(char *, char); extern int ValidCommonID(char *, char);
/** /**
* Frees a CommonID's values. Note that it doesn't free the CommonID itself. * Frees a CommonID's values. Note that it doesn't free the CommonID itself.
@ -102,7 +100,7 @@ extern char * ParserRecomposeServerPart(ServerPart);
/** /**
* Compares whenever a ServerName is equivalent to a server name string. * Compares whenever a ServerName is equivalent to a server name string.
*/ */
extern bool ParserServerNameEquals(ServerPart, char *); extern int ParserServerNameEquals(ServerPart, char *);
#endif /* TELODENDRIA_PARSER_H */ #endif /* TELODENDRIA_PARSER_H */

View file

@ -41,6 +41,7 @@
*/ */
#include <Cytoplasm/Db.h> #include <Cytoplasm/Db.h>
#include <Cytoplasm/Int64.h>
#include <Schema/RegToken.h> #include <Schema/RegToken.h>
@ -77,7 +78,7 @@ extern RegTokenInfo * RegTokenGetInfo(Db *, char *);
* structure will be returned. Otherwise, NULL will be returned. * structure will be returned. Otherwise, NULL will be returned.
*/ */
extern RegTokenInfo * extern RegTokenInfo *
RegTokenCreate(Db *, char *, char *, uint64_t, int64_t, int); RegTokenCreate(Db *, char *, char *, UInt64, Int64, int);
/** /**
* Free the memory associated with the registration token. This should * Free the memory associated with the registration token. This should

View file

@ -86,7 +86,6 @@ ROUTE(RouteChangePwd);
ROUTE(RouteDeactivate); ROUTE(RouteDeactivate);
ROUTE(RouteTokenValid); ROUTE(RouteTokenValid);
ROUTE(RouteUserProfile); ROUTE(RouteUserProfile);
ROUTE(RouteUserDirectory);
ROUTE(RouteRequestToken); ROUTE(RouteRequestToken);
ROUTE(RouteUiaFallback); ROUTE(RouteUiaFallback);

View file

@ -39,13 +39,12 @@
* users, among many other tasks. * users, among many other tasks.
*/ */
#include <Cytoplasm/Int64.h>
#include <Cytoplasm/Db.h> #include <Cytoplasm/Db.h>
#include <Cytoplasm/Json.h> #include <Cytoplasm/Json.h>
#include <Parser.h> #include <Parser.h>
#include <stdbool.h>
/** /**
* Many functions here operate on an opaque user structure. * Many functions here operate on an opaque user structure.
*/ */
@ -78,7 +77,7 @@ typedef struct UserAccessToken
char *user; char *user;
char *string; char *string;
char *deviceId; char *deviceId;
uint64_t lifetime; Int64 lifetime;
} UserAccessToken; } UserAccessToken;
/** /**
@ -99,7 +98,7 @@ typedef struct UserLoginInfo
* the local part is allowed to be. This function is used to ensure * the local part is allowed to be. This function is used to ensure
* that client-provided Matrix IDs are valid on this server. * that client-provided Matrix IDs are valid on this server.
*/ */
extern bool UserValidate(char *, char *); extern int UserValidate(char *, char *);
/** /**
* This function behaves just like * This function behaves just like
@ -110,13 +109,13 @@ extern bool UserValidate(char *, char *);
* spec compliant but remain in use since before the new restrictions * spec compliant but remain in use since before the new restrictions
* were put in place. * were put in place.
*/ */
extern bool UserHistoricalValidate(char *, char *); extern int UserHistoricalValidate(char *, char *);
/** /**
* Determine whether the user identified by the specified localpart * Determine whether the user identified by the specified localpart
* exists in the database. * exists in the database.
*/ */
extern bool UserExists(Db *, char *); extern int UserExists(Db *, char *);
/** /**
* Create a new user with the specified localpart and password, in * Create a new user with the specified localpart and password, in
@ -147,7 +146,7 @@ extern User * UserAuthenticate(Db *, char *);
* .Fn DbUnlock * .Fn DbUnlock
* under the hood. * under the hood.
*/ */
extern bool UserUnlock(User *); extern int UserUnlock(User *);
/** /**
* Log in a user. This function takes the user's password, desired * Log in a user. This function takes the user's password, desired
@ -180,13 +179,13 @@ extern char * UserGetDeviceId(User *);
* does not store passwords in plain text, so this function hashes the * does not store passwords in plain text, so this function hashes the
* password and checks it against what is stored in the database. * password and checks it against what is stored in the database.
*/ */
extern bool UserCheckPassword(User *, char *); extern int UserCheckPassword(User *, char *);
/** /**
* Reset the given user's password by hashing a plain text password and * Reset the given user's password by hashing a plain text password and
* storing it in the database. * storing it in the database.
*/ */
extern bool UserSetPassword(User *, char *); extern int UserSetPassword(User *, char *);
/** /**
* Immediately deactivate the given user account such that it can no * Immediately deactivate the given user account such that it can no
@ -199,21 +198,21 @@ extern bool UserSetPassword(User *, char *);
* responsible for deactivating the target user is NULL, then it is * responsible for deactivating the target user is NULL, then it is
* set to the target's own name. * set to the target's own name.
*/ */
extern bool UserDeactivate(User *, char *, char *); extern int UserDeactivate(User *, char *, char *);
/** /**
* Reactivates the given user account if it has been deactvated with * Reactivates the given user account if it has been deactvated with
* .Fn UserDeactivate , * .Fn UserDeactivate ,
* otherwise, it simply doesn't do anything. * otherwise, it simply doesn't do anything.
*/ */
extern bool UserReactivate(User *); extern int UserReactivate(User *);
/** /**
* Return a boolean value indicating whether or not the user was * Return a boolean value indicating whether or not the user was
* deactivated using * deactivated using
* .Fn UserDeactivate . * .Fn UserDeactivate .
*/ */
extern bool UserDeactivated(User *); extern int UserDeactivated(User *);
/** /**
* Fetches the devices that belong to the user, in JSON format, * Fetches the devices that belong to the user, in JSON format,
@ -234,7 +233,7 @@ extern UserAccessToken * UserAccessTokenGenerate(User *, char *, int);
* Write the specified access token to the database, returning a * Write the specified access token to the database, returning a
* boolean value indicating success. * boolean value indicating success.
*/ */
extern bool UserAccessTokenSave(Db *, UserAccessToken *); extern int UserAccessTokenSave(Db *, UserAccessToken *);
/** /**
* Free the memory associated with the given access token. * Free the memory associated with the given access token.
@ -244,7 +243,7 @@ extern void UserAccessTokenFree(UserAccessToken *);
/** /**
* Delete a specific access token by name. * Delete a specific access token by name.
*/ */
extern bool UserDeleteToken(User *, char *); extern int UserDeleteToken(User *, char *);
/** /**
* Get a string property from the user's profile given the specified * Get a string property from the user's profile given the specified
@ -263,7 +262,7 @@ extern void UserSetProfile(User *, char *, char *);
* except for the one provided by name, unless NULL is provided for * except for the one provided by name, unless NULL is provided for
* the name. * the name.
*/ */
extern bool UserDeleteTokens(User *, char *); extern int UserDeleteTokens(User *, char *);
/** /**
* Get the current privileges of the user as a packed bit field. Use * Get the current privileges of the user as a packed bit field. Use
@ -275,7 +274,7 @@ extern int UserGetPrivileges(User *);
/** /**
* Set the privileges of the user. * Set the privileges of the user.
*/ */
extern bool UserSetPrivileges(User *, int); extern int UserSetPrivileges(User *, int);
/** /**
* Decode the JSON that represents the user privileges into a packed * Decode the JSON that represents the user privileges into a packed

View file

@ -64,23 +64,47 @@ query(char *select, HashMap * json, int canonical)
int expectArr = 0; int expectArr = 0;
int func = 0; int func = 0;
expectArr = (sscanf(key, "%127[^[][%zu]", keyName, &arrInd) == 2); expectArr = (sscanf(key, "%127[^[][%lu]", keyName, &arrInd) == 2);
if (keyName[0] == '@') if (keyName[0] == '@')
{ {
if (StrEquals(keyName + 1, "length")) if (StrEquals(keyName + 1, "length"))
{ {
uint64_t len; UInt64 len;
switch (JsonValueType(val)) switch (JsonValueType(val))
{ {
case JSON_ARRAY: case JSON_ARRAY:
len = ArraySize(JsonValueAsArray(val)); if (sizeof(size_t) == sizeof(UInt64))
{
size_t slen = ArraySize(JsonValueAsArray(val));
UInt32 high = slen >> 32;
UInt32 low = slen;
len = UInt64Create(high, low);
}
else
{
len = UInt64Create(0, ArraySize(JsonValueAsArray(val)));
}
val = JsonValueInteger(len); val = JsonValueInteger(len);
ArrayAdd(cleanUp, val); ArrayAdd(cleanUp, val);
break; break;
case JSON_STRING: case JSON_STRING:
len = strlen(JsonValueAsString(val)); if (sizeof(size_t) == sizeof(UInt64))
{
size_t slen = strlen(JsonValueAsString(val));
UInt32 high = slen >> 32;
UInt32 low = slen;
len = UInt64Create(high, low);
}
else
{
len = UInt64Create(0, strlen(JsonValueAsString(val)));
}
val = JsonValueInteger(len); val = JsonValueInteger(len);
ArrayAdd(cleanUp, val); ArrayAdd(cleanUp, val);
break; break;
@ -130,7 +154,7 @@ query(char *select, HashMap * json, int canonical)
{ {
size_t i; size_t i;
if (sscanf(keyName + 1, "%zu", &i) == 1) if (sscanf(keyName + 1, "%lu", &i) == 1)
{ {
JsonValueFree(ArrayDelete(JsonValueAsArray(val), i)); JsonValueFree(ArrayDelete(JsonValueAsArray(val), i));
} }