2.60 mastoapi.c
   1/* snac - A simple, minimalistic ActivityPub instance */
   2/* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
   3
   4#ifndef NO_MASTODON_API
   5
   6#include "xs.h"
   7#include "xs_hex.h"
   8#include "xs_openssl.h"
   9#include "xs_json.h"
  10#include "xs_io.h"
  11#include "xs_time.h"
  12#include "xs_glob.h"
  13#include "xs_set.h"
  14#include "xs_random.h"
  15#include "xs_url.h"
  16#include "xs_mime.h"
  17#include "xs_match.h"
  18
  19#include "snac.h"
  20
  21#include <sys/time.h>
  22
  23static xs_str *random_str(void)
  24/* just what is says in the tin */
  25{
  26    unsigned int data[4] = {0};
  27
  28    xs_rnd_buf(data, sizeof(data));
  29    return xs_hex_enc((char *)data, sizeof(data));
  30}
  31
  32
  33int app_add(const char *id, const xs_dict *app)
  34/* stores an app */
  35{
  36    if (!xs_is_hex(id))
  37        return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  38
  39    int status = HTTP_STATUS_CREATED;
  40    xs *fn     = xs_fmt("%s/app/", srv_basedir);
  41    FILE *f;
  42
  43    mkdirx(fn);
  44    fn = xs_str_cat(fn, id);
  45    fn = xs_str_cat(fn, ".json");
  46
  47    if ((f = fopen(fn, "w")) != NULL) {
  48        xs_json_dump(app, 4, f);
  49        fclose(f);
  50    }
  51    else
  52        status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
  53
  54    return status;
  55}
  56
  57
  58xs_str *_app_fn(const char *id)
  59{
  60    return xs_fmt("%s/app/%s.json", srv_basedir, id);
  61}
  62
  63
  64xs_dict *app_get(const char *id)
  65/* gets an app */
  66{
  67    if (!xs_is_hex(id))
  68        return NULL;
  69
  70    xs *fn       = _app_fn(id);
  71    xs_dict *app = NULL;
  72    FILE *f;
  73
  74    if ((f = fopen(fn, "r")) != NULL) {
  75        app = xs_json_load(f);
  76        fclose(f);
  77
  78    }
  79
  80    return app;
  81}
  82
  83
  84int app_del(const char *id)
  85/* deletes an app */
  86{
  87    if (!xs_is_hex(id))
  88        return -1;
  89
  90    xs *fn = _app_fn(id);
  91
  92    return unlink(fn);
  93}
  94
  95
  96int token_add(const char *id, const xs_dict *token)
  97/* stores a token */
  98{
  99    if (!xs_is_hex(id))
 100        return HTTP_STATUS_INTERNAL_SERVER_ERROR;
 101
 102    int status = HTTP_STATUS_CREATED;
 103    xs *fn     = xs_fmt("%s/token/", srv_basedir);
 104    FILE *f;
 105
 106    mkdirx(fn);
 107    fn = xs_str_cat(fn, id);
 108    fn = xs_str_cat(fn, ".json");
 109
 110    if ((f = fopen(fn, "w")) != NULL) {
 111        xs_json_dump(token, 4, f);
 112        fclose(f);
 113    }
 114    else
 115        status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
 116
 117    return status;
 118}
 119
 120
 121xs_dict *token_get(const char *id)
 122/* gets a token */
 123{
 124    if (!xs_is_hex(id))
 125        return NULL;
 126
 127    xs *fn         = xs_fmt("%s/token/%s.json", srv_basedir, id);
 128    xs_dict *token = NULL;
 129    FILE *f;
 130
 131    if ((f = fopen(fn, "r")) != NULL) {
 132        token = xs_json_load(f);
 133        fclose(f);
 134
 135        /* 'touch' the file */
 136        utimes(fn, NULL);
 137
 138        /* also 'touch' the app */
 139        const char *app_id = xs_dict_get(token, "client_id");
 140
 141        if (app_id) {
 142            xs *afn = xs_fmt("%s/app/%s.json", srv_basedir, app_id);
 143            utimes(afn, NULL);
 144        }
 145    }
 146
 147    return token;
 148}
 149
 150
 151int token_del(const char *id)
 152/* deletes a token */
 153{
 154    if (!xs_is_hex(id))
 155        return -1;
 156
 157    xs *fn = xs_fmt("%s/token/%s.json", srv_basedir, id);
 158
 159    return unlink(fn);
 160}
 161
 162
 163const char *login_page = ""
 164"<!DOCTYPE html>\n"
 165"<html>\n"
 166"<head>\n"
 167"<title>%s OAuth - Snac2</title>\n"
 168"<meta content=\"width=device-width, initial-scale=1, minimum-scale=1, user-scalable=no\" name=\"viewport\">"
 169"<style>:root {color-scheme: light dark}</style>\n"
 170"</head>\n"
 171"<body><h1>%s OAuth identify</h1>\n"
 172"<div style=\"background-color: red; color: white\">%s</div>\n"
 173"<form method=\"post\" action=\"%s:/" "/%s/%s\">\n"
 174"<p>Login: <input type=\"text\" name=\"login\"></p>\n"
 175"<p>Password: <input type=\"password\" name=\"passwd\"></p>\n"
 176"<input type=\"hidden\" name=\"redir\" value=\"%s\">\n"
 177"<input type=\"hidden\" name=\"cid\" value=\"%s\">\n"
 178"<input type=\"hidden\" name=\"state\" value=\"%s\">\n"
 179"<input type=\"submit\" value=\"OK\">\n"
 180"</form><p>%s</p></body></html>\n"
 181"";
 182
 183int oauth_get_handler(const xs_dict *req, const char *q_path,
 184                      char **body, int *b_size, char **ctype)
 185{
 186    (void)b_size;
 187
 188    if (!xs_startswith(q_path, "/oauth/"))
 189        return 0;
 190
 191    int status   = HTTP_STATUS_NOT_FOUND;
 192    const xs_dict *msg = xs_dict_get(req, "q_vars");
 193    xs *cmd      = xs_replace_n(q_path, "/oauth", "", 1);
 194
 195    srv_debug(1, xs_fmt("oauth_get_handler %s", q_path));
 196
 197    if (strcmp(cmd, "/authorize") == 0) { /** **/
 198        const char *cid   = xs_dict_get(msg, "client_id");
 199        const char *ruri  = xs_dict_get(msg, "redirect_uri");
 200        const char *rtype = xs_dict_get(msg, "response_type");
 201        const char *state = xs_dict_get(msg, "state");
 202
 203        status = HTTP_STATUS_BAD_REQUEST;
 204
 205        if (cid && ruri && rtype && strcmp(rtype, "code") == 0) {
 206            xs *app = app_get(cid);
 207
 208            if (app != NULL) {
 209                const char *host = xs_dict_get(srv_config, "host");
 210                const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
 211
 212                if (xs_is_null(state))
 213                    state = "";
 214
 215                *body  = xs_fmt(login_page, host, host, "", proto, host, "oauth/x-snac-login",
 216                                ruri, cid, state, USER_AGENT);
 217                *ctype = "text/html";
 218                status = HTTP_STATUS_OK;
 219
 220                srv_debug(1, xs_fmt("oauth authorize: generating login page"));
 221            }
 222            else
 223                srv_debug(1, xs_fmt("oauth authorize: bad client_id %s", cid));
 224        }
 225        else
 226            srv_debug(1, xs_fmt("oauth authorize: invalid or unset arguments"));
 227    }
 228    else
 229    if (strcmp(cmd, "/x-snac-get-token") == 0) { /** **/
 230        const char *host = xs_dict_get(srv_config, "host");
 231        const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
 232
 233        *body  = xs_fmt(login_page, host, host, "", proto, host, "oauth/x-snac-get-token",
 234                        "", "", "", USER_AGENT);
 235        *ctype = "text/html";
 236        status = HTTP_STATUS_OK;
 237
 238    }
 239
 240    return status;
 241}
 242
 243
 244int oauth_post_handler(const xs_dict *req, const char *q_path,
 245                       const char *payload, int p_size,
 246                       char **body, int *b_size, char **ctype)
 247{
 248    (void)p_size;
 249    (void)b_size;
 250
 251    if (!xs_startswith(q_path, "/oauth/"))
 252        return 0;
 253
 254    int status   = HTTP_STATUS_NOT_FOUND;
 255
 256    const char *i_ctype = xs_dict_get(req, "content-type");
 257    xs *args      = NULL;
 258
 259    if (i_ctype && xs_startswith(i_ctype, "application/json")) {
 260        if (!xs_is_null(payload))
 261            args = xs_json_loads(payload);
 262    }
 263    else
 264    if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded") && payload) {
 265        args    = xs_url_vars(payload);
 266    }
 267    else
 268        args = xs_dup(xs_dict_get(req, "p_vars"));
 269
 270    if (args == NULL)
 271        return HTTP_STATUS_BAD_REQUEST;
 272
 273    xs *cmd = xs_replace_n(q_path, "/oauth", "", 1);
 274
 275    srv_debug(1, xs_fmt("oauth_post_handler %s", q_path));
 276
 277    if (strcmp(cmd, "/x-snac-login") == 0) { /** **/
 278        const char *login  = xs_dict_get(args, "login");
 279        const char *passwd = xs_dict_get(args, "passwd");
 280        const char *redir  = xs_dict_get(args, "redir");
 281        const char *cid    = xs_dict_get(args, "cid");
 282        const char *state  = xs_dict_get(args, "state");
 283        const char *host   = xs_dict_get(srv_config, "host");
 284        const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
 285
 286        /* by default, generate another login form with an error */
 287        *body  = xs_fmt(login_page, host, host, "LOGIN INCORRECT", proto, host, "oauth/x-snac-login",
 288                        redir, cid, state, USER_AGENT);
 289        *ctype = "text/html";
 290        status = HTTP_STATUS_OK;
 291
 292        if (login && passwd && redir && cid) {
 293            snac snac;
 294
 295            if (user_open(&snac, login)) {
 296                /* check the login + password */
 297                if (check_password(login, passwd, xs_dict_get(snac.config, "passwd"))) {
 298                    /* success! redirect to the desired uri */
 299                    xs *code = random_str();
 300
 301                    xs_free(*body);
 302
 303                    if (strcmp(redir, "urn:ietf:wg:oauth:2.0:oob") == 0) {
 304                        *body = xs_dup(code);
 305                    }
 306                    else {
 307                        if (xs_str_in(redir, "?") != -1)
 308                            *body = xs_fmt("%s&code=%s", redir, code);
 309                        else
 310                            *body = xs_fmt("%s?code=%s", redir, code);
 311
 312                        status = HTTP_STATUS_SEE_OTHER;
 313                    }
 314
 315                    /* if there is a state, add it */
 316                    if (!xs_is_null(state) && *state) {
 317                        *body = xs_str_cat(*body, "&state=");
 318                        *body = xs_str_cat(*body, state);
 319                    }
 320
 321                    srv_log(xs_fmt("oauth x-snac-login: '%s' success, redirect to %s",
 322                                   login, *body));
 323
 324                    /* assign the login to the app */
 325                    xs *app = app_get(cid);
 326
 327                    if (app != NULL) {
 328                        app = xs_dict_set(app, "uid",  login);
 329                        app = xs_dict_set(app, "code", code);
 330                        app_add(cid, app);
 331                    }
 332                    else
 333                        srv_log(xs_fmt("oauth x-snac-login: error getting app %s", cid));
 334                }
 335                else
 336                    srv_debug(1, xs_fmt("oauth x-snac-login: login '%s' incorrect", login));
 337
 338                user_free(&snac);
 339            }
 340            else
 341                srv_debug(1, xs_fmt("oauth x-snac-login: bad user '%s'", login));
 342        }
 343        else
 344            srv_debug(1, xs_fmt("oauth x-snac-login: invalid or unset arguments"));
 345    }
 346    else
 347    if (strcmp(cmd, "/token") == 0) { /** **/
 348        xs *wrk = NULL;
 349        const char *gtype = xs_dict_get(args, "grant_type");
 350        const char *code  = xs_dict_get(args, "code");
 351        const char *cid   = xs_dict_get(args, "client_id");
 352        const char *csec  = xs_dict_get(args, "client_secret");
 353        const char *ruri  = xs_dict_get(args, "redirect_uri");
 354        const char *scope = xs_dict_get(args, "scope");
 355
 356        /* no client_secret? check if it's inside an authorization header
 357           (AndStatus does it this way) */
 358        if (xs_is_null(csec)) {
 359            const char *auhdr = xs_dict_get(req, "authorization");
 360
 361            if (!xs_is_null(auhdr) && xs_startswith(auhdr, "Basic ")) {
 362                xs *s1 = xs_replace_n(auhdr, "Basic ", "", 1);
 363                int size;
 364                xs *s2 = xs_base64_dec(s1, &size);
 365
 366                if (!xs_is_null(s2)) {
 367                    xs *l1 = xs_split(s2, ":");
 368
 369                    if (xs_list_len(l1) == 2) {
 370                        wrk = xs_dup(xs_list_get(l1, 1));
 371                        csec = wrk;
 372                    }
 373                }
 374            }
 375        }
 376
 377        /* no code? 
 378           I'm not sure of the impacts of this right now, but Subway Tooter does not
 379           provide a code so one must be generated */
 380        if (xs_is_null(code)){
 381            code = random_str();
 382        }
 383        if (gtype && code && cid && csec && ruri) {
 384            xs *app = app_get(cid);
 385
 386            if (app == NULL) {
 387                status = HTTP_STATUS_UNAUTHORIZED;
 388                srv_log(xs_fmt("oauth token: invalid app %s", cid));
 389            }
 390            else
 391            if (strcmp(csec, xs_dict_get(app, "client_secret")) != 0) {
 392                status = HTTP_STATUS_UNAUTHORIZED;
 393                srv_log(xs_fmt("oauth token: invalid client_secret for app %s", cid));
 394            }
 395            else {
 396                xs *rsp   = xs_dict_new();
 397                xs *cat   = xs_number_new(time(NULL));
 398                xs *tokid = random_str();
 399
 400                rsp = xs_dict_append(rsp, "access_token", tokid);
 401                rsp = xs_dict_append(rsp, "token_type",   "Bearer");
 402                rsp = xs_dict_append(rsp, "created_at",   cat);
 403
 404                if (!xs_is_null(scope))
 405                    rsp = xs_dict_append(rsp, "scope", scope);
 406
 407                *body  = xs_json_dumps(rsp, 4);
 408                *ctype = "application/json";
 409                status = HTTP_STATUS_OK;
 410
 411                const char *uid = xs_dict_get(app, "uid");
 412
 413                srv_debug(1, xs_fmt("oauth token: "
 414                                "successful login for %s, new token %s", uid, tokid));
 415
 416                xs *token = xs_dict_new();
 417                token = xs_dict_append(token, "token",         tokid);
 418                token = xs_dict_append(token, "client_id",     cid);
 419                token = xs_dict_append(token, "client_secret", csec);
 420                token = xs_dict_append(token, "uid",           uid);
 421                token = xs_dict_append(token, "code",          code);
 422
 423                token_add(tokid, token);
 424            }
 425        }
 426        else {
 427            srv_debug(1, xs_fmt("oauth token: invalid or unset arguments"));
 428            status = HTTP_STATUS_BAD_REQUEST;
 429        }
 430    }
 431    else
 432    if (strcmp(cmd, "/revoke") == 0) { /** **/
 433        const char *cid   = xs_dict_get(args, "client_id");
 434        const char *csec  = xs_dict_get(args, "client_secret");
 435        const char *tokid = xs_dict_get(args, "token");
 436
 437        if (cid && csec && tokid) {
 438            xs *token = token_get(tokid);
 439
 440            *body  = xs_str_new("{}");
 441            *ctype = "application/json";
 442
 443            if (token == NULL || strcmp(csec, xs_dict_get(token, "client_secret")) != 0) {
 444                srv_debug(1, xs_fmt("oauth revoke: bad secret for token %s", tokid));
 445                status = HTTP_STATUS_FORBIDDEN;
 446            }
 447            else {
 448                token_del(tokid);
 449                srv_debug(1, xs_fmt("oauth revoke: revoked token %s", tokid));
 450                status = HTTP_STATUS_OK;
 451
 452                /* also delete the app, as it serves no purpose from now on */
 453                app_del(cid);
 454            }
 455        }
 456        else {
 457            srv_debug(1, xs_fmt("oauth revoke: invalid or unset arguments"));
 458            status = HTTP_STATUS_FORBIDDEN;
 459        }
 460    }
 461    if (strcmp(cmd, "/x-snac-get-token") == 0) { /** **/
 462        const char *login  = xs_dict_get(args, "login");
 463        const char *passwd = xs_dict_get(args, "passwd");
 464        const char *host   = xs_dict_get(srv_config, "host");
 465        const char *proto  = xs_dict_get_def(srv_config, "protocol", "https");
 466
 467        /* by default, generate another login form with an error */
 468        *body  = xs_fmt(login_page, host, host, "LOGIN INCORRECT", proto, host, "oauth/x-snac-get-token",
 469                        "", "", "", USER_AGENT);
 470        *ctype = "text/html";
 471        status = HTTP_STATUS_OK;
 472
 473        if (login && passwd) {
 474            snac user;
 475
 476            if (user_open(&user, login)) {
 477                /* check the login + password */
 478                if (check_password(login, passwd, xs_dict_get(user.config, "passwd"))) {
 479                    /* success! create a new token */
 480                    xs *tokid = random_str();
 481
 482                    srv_debug(1, xs_fmt("x-snac-new-token: "
 483                                    "successful login for %s, new token %s", login, tokid));
 484
 485                    xs *token = xs_dict_new();
 486                    token = xs_dict_append(token, "token",         tokid);
 487                    token = xs_dict_append(token, "client_id",     "snac-client");
 488                    token = xs_dict_append(token, "client_secret", "");
 489                    token = xs_dict_append(token, "uid",           login);
 490                    token = xs_dict_append(token, "code",          "");
 491
 492                    token_add(tokid, token);
 493
 494                    *ctype = "text/plain";
 495                    xs_free(*body);
 496                    *body = xs_dup(tokid);
 497                }
 498
 499                user_free(&user);
 500            }
 501        }
 502    }
 503
 504    return status;
 505}
 506
 507
 508xs_str *mastoapi_id(const xs_dict *msg)
 509/* returns a somewhat Mastodon-compatible status id */
 510{
 511    const char *id = xs_dict_get(msg, "id");
 512    xs *md5        = xs_md5_hex(id, strlen(id));
 513
 514    return xs_fmt("%10.0f%s", object_ctime_by_md5(md5), md5);
 515}
 516
 517#define MID_TO_MD5(id) (id + 10)
 518
 519
 520xs_dict *mastoapi_account(const xs_dict *actor)
 521/* converts an ActivityPub actor to a Mastodon account */
 522{
 523    const char *id  = xs_dict_get(actor, "id");
 524    const char *pub = xs_dict_get(actor, "published");
 525
 526    if (xs_type(id) != XSTYPE_STRING)
 527        return NULL;
 528
 529    const char *prefu = xs_dict_get(actor, "preferredUsername");
 530
 531    const char *display_name = xs_dict_get(actor, "name");
 532    if (xs_is_null(display_name) || *display_name == '\0')
 533        display_name = prefu;
 534
 535    xs_dict *acct = xs_dict_new();
 536    xs *acct_md5  = xs_md5_hex(id, strlen(id));
 537    acct = xs_dict_append(acct, "id",           acct_md5);
 538    acct = xs_dict_append(acct, "username",     prefu);
 539    acct = xs_dict_append(acct, "display_name", display_name);
 540    acct = xs_dict_append(acct, "discoverable", xs_stock(XSTYPE_TRUE));
 541    acct = xs_dict_append(acct, "group",        xs_stock(XSTYPE_FALSE));
 542    acct = xs_dict_append(acct, "hide_collections", xs_stock(XSTYPE_FALSE));
 543    acct = xs_dict_append(acct, "indexable",    xs_stock(XSTYPE_TRUE));
 544    acct = xs_dict_append(acct, "noindex",      xs_stock(XSTYPE_FALSE));
 545    acct = xs_dict_append(acct, "roles",        xs_stock(XSTYPE_LIST));
 546
 547    {
 548        /* create the acct field as user@host */
 549        xs *l     = xs_split(id, "/");
 550        xs *fquid = xs_fmt("%s@%s", prefu, xs_list_get(l, 2));
 551        acct      = xs_dict_append(acct, "acct", fquid);
 552    }
 553
 554    if (pub)
 555        acct = xs_dict_append(acct, "created_at", pub);
 556    else {
 557        /* unset created_at crashes Tusky, so lie like a mf */
 558        xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
 559        acct = xs_dict_append(acct, "created_at", date);
 560    }
 561
 562    xs *last_status_at = xs_str_utctime(0, "%Y-%m-%d");
 563    acct = xs_dict_append(acct, "last_status_at", last_status_at);
 564
 565    const char *note = xs_dict_get(actor, "summary");
 566    if (xs_is_null(note))
 567        note = "";
 568
 569    if (strcmp(xs_dict_get(actor, "type"), "Service") == 0)
 570        acct = xs_dict_append(acct, "bot", xs_stock(XSTYPE_TRUE));
 571    else
 572        acct = xs_dict_append(acct, "bot", xs_stock(XSTYPE_FALSE));
 573
 574    acct = xs_dict_append(acct, "note", note);
 575
 576    acct = xs_dict_append(acct, "url", id);
 577    acct = xs_dict_append(acct, "uri", id);
 578
 579    xs *avatar  = NULL;
 580    const xs_dict *av = xs_dict_get(actor, "icon");
 581
 582    if (xs_type(av) == XSTYPE_DICT) {
 583        const char *url = xs_dict_get(av, "url");
 584
 585        if (url != NULL)
 586            avatar = xs_dup(url);
 587    }
 588
 589    if (avatar == NULL)
 590        avatar = xs_fmt("%s/susie.png", srv_baseurl);
 591
 592    acct = xs_dict_append(acct, "avatar", avatar);
 593    acct = xs_dict_append(acct, "avatar_static", avatar);
 594
 595    xs *header  = NULL;
 596    const xs_dict *hd = xs_dict_get(actor, "image");
 597
 598    if (xs_type(hd) == XSTYPE_DICT)
 599        header = xs_dup(xs_dict_get(hd, "url"));
 600
 601    if (xs_is_null(header))
 602        header = xs_str_new(NULL);
 603
 604    acct = xs_dict_append(acct, "header", header);
 605    acct = xs_dict_append(acct, "header_static", header);
 606
 607    /* emojis */
 608    const xs_list *p;
 609    if (!xs_is_null(p = xs_dict_get(actor, "tag"))) {
 610        xs *eml = xs_list_new();
 611        const xs_dict *v;
 612        int c = 0;
 613
 614        while (xs_list_next(p, &v, &c)) {
 615            const char *type = xs_dict_get(v, "type");
 616
 617            if (!xs_is_null(type) && strcmp(type, "Emoji") == 0) {
 618                const char *name    = xs_dict_get(v, "name");
 619                const xs_dict *icon = xs_dict_get(v, "icon");
 620
 621                if (!xs_is_null(name) && !xs_is_null(icon)) {
 622                    const char *url = xs_dict_get(icon, "url");
 623
 624                    if (!xs_is_null(url)) {
 625                        xs *nm = xs_strip_chars_i(xs_dup(name), ":");
 626                        xs *d1 = xs_dict_new();
 627
 628                        d1 = xs_dict_append(d1, "shortcode",         nm);
 629                        d1 = xs_dict_append(d1, "url",               url);
 630                        d1 = xs_dict_append(d1, "static_url",        url);
 631                        d1 = xs_dict_append(d1, "visible_in_picker", xs_stock(XSTYPE_TRUE));
 632
 633                        eml = xs_list_append(eml, d1);
 634                    }
 635                }
 636            }
 637        }
 638
 639        acct = xs_dict_append(acct, "emojis", eml);
 640    }
 641
 642    acct = xs_dict_append(acct, "locked", xs_stock(XSTYPE_FALSE));
 643    acct = xs_dict_append(acct, "followers_count", xs_stock(0));
 644    acct = xs_dict_append(acct, "following_count", xs_stock(0));
 645    acct = xs_dict_append(acct, "statuses_count", xs_stock(0));
 646
 647    xs *fields = xs_list_new();
 648    p = xs_dict_get(actor, "attachment");
 649    const xs_dict *v;
 650
 651    /* dict of validated links */
 652    xs_dict *val_links = NULL;
 653    const xs_dict *metadata  = xs_stock(XSTYPE_DICT);
 654    snac user = {0};
 655
 656    if (xs_startswith(id, srv_baseurl)) {
 657        /* if it's a local user, open it and pick its validated links */
 658        if (user_open(&user, prefu)) {
 659            val_links = user.links;
 660            metadata  = xs_dict_get_def(user.config, "metadata", xs_stock(XSTYPE_DICT));
 661        }
 662    }
 663
 664    if (xs_is_null(val_links))
 665        val_links = xs_stock(XSTYPE_DICT);
 666
 667    int c = 0;
 668    while (xs_list_next(p, &v, &c)) {
 669        const char *type  = xs_dict_get(v, "type");
 670        const char *name  = xs_dict_get(v, "name");
 671        const char *value = xs_dict_get(v, "value");
 672
 673        if (!xs_is_null(type) && !xs_is_null(name) &&
 674            !xs_is_null(value) && strcmp(type, "PropertyValue") == 0) {
 675            xs *val_date = NULL;
 676
 677            const char *url = xs_dict_get(metadata, name);
 678
 679            if (!xs_is_null(url) && xs_startswith(url, "https:/" "/")) {
 680                const xs_number *verified_time = xs_dict_get(val_links, url);
 681                if (xs_type(verified_time) == XSTYPE_NUMBER) {
 682                    time_t t = xs_number_get(verified_time);
 683
 684                    if (t > 0)
 685                        val_date = xs_str_utctime(t, ISO_DATE_SPEC);
 686                }
 687            }
 688
 689            xs *d = xs_dict_new();
 690
 691            d = xs_dict_append(d, "name", name);
 692            d = xs_dict_append(d, "value", value);
 693            d = xs_dict_append(d, "verified_at",
 694                xs_type(val_date) == XSTYPE_STRING && *val_date ?
 695                    val_date : xs_stock(XSTYPE_NULL));
 696
 697            fields = xs_list_append(fields, d);
 698        }
 699    }
 700
 701    user_free(&user);
 702
 703    acct = xs_dict_append(acct, "fields", fields);
 704
 705    return acct;
 706}
 707
 708
 709xs_str *mastoapi_date(const char *date)
 710/* converts an ISO 8601 date to whatever format Mastodon uses */
 711{
 712    xs_str *s = xs_crop_i(xs_dup(date), 0, 19);
 713    s = xs_str_cat(s, ".000Z");
 714
 715    return s;
 716}
 717
 718
 719xs_dict *mastoapi_poll(snac *snac, const xs_dict *msg)
 720/* creates a mastoapi Poll object */
 721{
 722    xs_dict *poll = xs_dict_new();
 723    xs *mid       = mastoapi_id(msg);
 724    const xs_list *opts = NULL;
 725    const xs_val *v;
 726    int num_votes = 0;
 727    xs *options = xs_list_new();
 728
 729    poll = xs_dict_append(poll, "id", mid);
 730    const char *date = xs_dict_get(msg, "endTime");
 731    if (date == NULL)
 732        date = xs_dict_get(msg, "closed");
 733    if (date == NULL)
 734        return NULL;
 735
 736    xs *fd = mastoapi_date(date);
 737    poll = xs_dict_append(poll, "expires_at", fd);
 738
 739    date = xs_dict_get(msg, "closed");
 740    time_t t = 0;
 741
 742    if (date != NULL)
 743        t = xs_parse_iso_date(date, 0);
 744
 745    poll = xs_dict_append(poll, "expired",
 746            t < time(NULL) ? xs_stock(XSTYPE_FALSE) : xs_stock(XSTYPE_TRUE));
 747
 748    if ((opts = xs_dict_get(msg, "oneOf")) != NULL)
 749        poll = xs_dict_append(poll, "multiple", xs_stock(XSTYPE_FALSE));
 750    else {
 751        opts = xs_dict_get(msg, "anyOf");
 752        poll = xs_dict_append(poll, "multiple", xs_stock(XSTYPE_TRUE));
 753    }
 754
 755    int c = 0;
 756    while (xs_list_next(opts, &v, &c)) {
 757        const char *title   = xs_dict_get(v, "name");
 758        const char *replies = xs_dict_get(v, "replies");
 759
 760        if (title && replies) {
 761            const char *votes_count = xs_dict_get(replies, "totalItems");
 762
 763            if (xs_type(votes_count) == XSTYPE_NUMBER) {
 764                xs *d = xs_dict_new();
 765                d = xs_dict_append(d, "title",  title);
 766                d = xs_dict_append(d, "votes_count", votes_count);
 767
 768                options = xs_list_append(options, d);
 769                num_votes += xs_number_get(votes_count);
 770            }
 771        }
 772    }
 773
 774    poll = xs_dict_append(poll, "options", options);
 775    xs *vc = xs_number_new(num_votes);
 776    poll = xs_dict_append(poll, "votes_count", vc);
 777
 778    poll = xs_dict_append(poll, "emojis", xs_stock(XSTYPE_LIST));
 779
 780    poll = xs_dict_append(poll, "voted",
 781            (snac && was_question_voted(snac, xs_dict_get(msg, "id"))) ?
 782                xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
 783
 784    return poll;
 785}
 786
 787
 788xs_dict *mastoapi_status(snac *snac, const xs_dict *msg)
 789/* converts an ActivityPub note to a Mastodon status */
 790{
 791    xs *actor = NULL;
 792    actor_get_refresh(snac, get_atto(msg), &actor);
 793
 794    /* if the author is not here, discard */
 795    if (actor == NULL)
 796        return NULL;
 797
 798    const char *type = xs_dict_get(msg, "type");
 799    const char *id   = xs_dict_get(msg, "id");
 800
 801    /* fail if it's not a valid actor */
 802    if (xs_is_null(type) || xs_is_null(id))
 803        return NULL;
 804
 805    xs *acct = mastoapi_account(actor);
 806    if (acct == NULL)
 807        return NULL;
 808
 809    xs *idx = NULL;
 810    xs *ixc = NULL;
 811    const char *tmp;
 812    xs *mid  = mastoapi_id(msg);
 813
 814    xs_dict *st = xs_dict_new();
 815
 816    st = xs_dict_append(st, "id",           mid);
 817    st = xs_dict_append(st, "uri",          id);
 818    st = xs_dict_append(st, "url",          id);
 819    st = xs_dict_append(st, "account",      acct);
 820
 821    xs *fd = mastoapi_date(xs_dict_get(msg, "published"));
 822    st = xs_dict_append(st, "created_at", fd);
 823
 824    {
 825        const char *content = xs_dict_get(msg, "content");
 826        const char *name    = xs_dict_get(msg, "name");
 827        xs *s1 = NULL;
 828
 829        if (name && content)
 830            s1 = xs_fmt("%s<br><br>%s", name, content);
 831        else
 832        if (name)
 833            s1 = xs_dup(name);
 834        else
 835        if (content)
 836            s1 = xs_dup(content);
 837        else
 838            s1 = xs_str_new(NULL);
 839
 840        st = xs_dict_append(st, "content", s1);
 841    }
 842
 843    st = xs_dict_append(st, "visibility",
 844        is_msg_public(msg) ? "public" : "private");
 845
 846    tmp = xs_dict_get(msg, "sensitive");
 847    if (xs_is_null(tmp))
 848        tmp = xs_stock(XSTYPE_FALSE);
 849
 850    st = xs_dict_append(st, "sensitive",    tmp);
 851
 852    tmp = xs_dict_get(msg, "summary");
 853    if (xs_is_null(tmp))
 854        tmp = "";
 855
 856    st = xs_dict_append(st, "spoiler_text", tmp);
 857
 858    /* create the list of attachments */
 859    xs *attach = get_attachments(msg);
 860
 861    {
 862        xs_list *p = attach;
 863        const xs_dict *v;
 864
 865        xs *matt = xs_list_new();
 866
 867        while (xs_list_iter(&p, &v)) {
 868            const char *type = xs_dict_get(v, "type");
 869            const char *href = xs_dict_get(v, "href");
 870            const char *name = xs_dict_get(v, "name");
 871
 872            if (xs_match(type, "image/*|video/*|Image|Video")) { /* */
 873                xs *matteid = xs_fmt("%s_%d", id, xs_list_len(matt));
 874
 875                xs *d = xs_dict_new();
 876
 877                d = xs_dict_append(d, "id",          matteid);
 878                d = xs_dict_append(d, "url",         href);
 879                d = xs_dict_append(d, "preview_url", href);
 880                d = xs_dict_append(d, "remote_url",  href);
 881                d = xs_dict_append(d, "description", name);
 882
 883                d = xs_dict_append(d, "type", (*type == 'v' || *type == 'V') ? "video" : "image");
 884
 885                matt = xs_list_append(matt, d);
 886            }
 887        }
 888
 889        st = xs_dict_append(st, "media_attachments", matt);
 890    }
 891
 892    {
 893        xs *ml  = xs_list_new();
 894        xs *htl = xs_list_new();
 895        xs *eml = xs_list_new();
 896        const xs_list *tag = xs_dict_get(msg, "tag");
 897        int n = 0;
 898
 899        xs *tag_list = NULL;
 900
 901        if (xs_type(tag) == XSTYPE_DICT) {
 902            tag_list = xs_list_new();
 903            tag_list = xs_list_append(tag_list, tag);
 904        }
 905        else
 906        if (xs_type(tag) == XSTYPE_LIST)
 907            tag_list = xs_dup(tag);
 908        else
 909            tag_list = xs_list_new();
 910
 911        tag = tag_list;
 912        const xs_dict *v;
 913
 914        int c = 0;
 915        while (xs_list_next(tag, &v, &c)) {
 916            const char *type = xs_dict_get(v, "type");
 917
 918            if (xs_is_null(type))
 919                continue;
 920
 921            xs *d1 = xs_dict_new();
 922
 923            if (strcmp(type, "Mention") == 0) {
 924                const char *name = xs_dict_get(v, "name");
 925                const char *href = xs_dict_get(v, "href");
 926
 927                if (!xs_is_null(name) && !xs_is_null(href) &&
 928                    (snac == NULL || strcmp(href, snac->actor) != 0)) {
 929                    xs *nm = xs_strip_chars_i(xs_dup(name), "@");
 930
 931                    xs *id = xs_fmt("%d", n++);
 932                    d1 = xs_dict_append(d1, "id", id);
 933                    d1 = xs_dict_append(d1, "username", nm);
 934                    d1 = xs_dict_append(d1, "acct", nm);
 935                    d1 = xs_dict_append(d1, "url", href);
 936
 937                    ml = xs_list_append(ml, d1);
 938                }
 939            }
 940            else
 941            if (strcmp(type, "Hashtag") == 0) {
 942                const char *name = xs_dict_get(v, "name");
 943                const char *href = xs_dict_get(v, "href");
 944
 945                if (!xs_is_null(name) && !xs_is_null(href)) {
 946                    xs *nm = xs_strip_chars_i(xs_dup(name), "#");
 947
 948                    d1 = xs_dict_append(d1, "name", nm);
 949                    d1 = xs_dict_append(d1, "url", href);
 950
 951                    htl = xs_list_append(htl, d1);
 952                }
 953            }
 954            else
 955            if (strcmp(type, "Emoji") == 0) {
 956                const char *name    = xs_dict_get(v, "name");
 957                const xs_dict *icon = xs_dict_get(v, "icon");
 958
 959                if (!xs_is_null(name) && !xs_is_null(icon)) {
 960                    const char *url = xs_dict_get(icon, "url");
 961
 962                    if (!xs_is_null(url)) {
 963                        xs *nm = xs_strip_chars_i(xs_dup(name), ":");
 964
 965                        d1 = xs_dict_append(d1, "shortcode", nm);
 966                        d1 = xs_dict_append(d1, "url", url);
 967                        d1 = xs_dict_append(d1, "static_url", url);
 968                        d1 = xs_dict_append(d1, "visible_in_picker", xs_stock(XSTYPE_TRUE));
 969                        d1 = xs_dict_append(d1, "category", "Emojis");
 970
 971                        eml = xs_list_append(eml, d1);
 972                    }
 973                }
 974            }
 975        }
 976
 977        st = xs_dict_append(st, "mentions", ml);
 978        st = xs_dict_append(st, "tags",     htl);
 979        st = xs_dict_append(st, "emojis",   eml);
 980    }
 981
 982    xs_free(idx);
 983    xs_free(ixc);
 984    idx = object_likes(id);
 985    ixc = xs_number_new(xs_list_len(idx));
 986
 987    st = xs_dict_append(st, "favourites_count", ixc);
 988    st = xs_dict_append(st, "favourited",
 989        (snac && xs_list_in(idx, snac->md5) != -1) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
 990
 991    xs_free(idx);
 992    xs_free(ixc);
 993    idx = object_announces(id);
 994    ixc = xs_number_new(xs_list_len(idx));
 995
 996    st = xs_dict_append(st, "reblogs_count", ixc);
 997    st = xs_dict_append(st, "reblogged",
 998        (snac && xs_list_in(idx, snac->md5) != -1) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
 999
1000    /* get the last person who boosted this */
1001    xs *boosted_by_md5 = NULL;
1002    if (xs_list_len(idx))
1003        boosted_by_md5 = xs_dup(xs_list_get(idx, -1));
1004
1005    xs_free(idx);
1006    xs_free(ixc);
1007    idx = object_children(id);
1008    ixc = xs_number_new(xs_list_len(idx));
1009
1010    st = xs_dict_append(st, "replies_count", ixc);
1011
1012    /* default in_reply_to values */
1013    st = xs_dict_append(st, "in_reply_to_id",         xs_stock(XSTYPE_NULL));
1014    st = xs_dict_append(st, "in_reply_to_account_id", xs_stock(XSTYPE_NULL));
1015
1016    tmp = xs_dict_get(msg, "inReplyTo");
1017    if (!xs_is_null(tmp)) {
1018        xs *irto = NULL;
1019
1020        if (valid_status(object_get(tmp, &irto))) {
1021            xs *irt_mid = mastoapi_id(irto);
1022            st = xs_dict_set(st, "in_reply_to_id", irt_mid);
1023
1024            const char *at = NULL;
1025            if (!xs_is_null(at = get_atto(irto))) {
1026                xs *at_md5 = xs_md5_hex(at, strlen(at));
1027                st = xs_dict_set(st, "in_reply_to_account_id", at_md5);
1028            }
1029        }
1030    }
1031
1032    st = xs_dict_append(st, "reblog",   xs_stock(XSTYPE_NULL));
1033    st = xs_dict_append(st, "card",     xs_stock(XSTYPE_NULL));
1034    st = xs_dict_append(st, "language", "en");
1035
1036    st = xs_dict_append(st, "filtered", xs_stock(XSTYPE_LIST));
1037    st = xs_dict_append(st, "muted",    xs_stock(XSTYPE_FALSE));
1038
1039    tmp = xs_dict_get(msg, "sourceContent");
1040    if (xs_is_null(tmp))
1041        tmp = "";
1042
1043    st = xs_dict_append(st, "text", tmp);
1044
1045    tmp = xs_dict_get(msg, "updated");
1046    xs *fd2 = NULL;
1047    if (xs_is_null(tmp))
1048        tmp = xs_stock(XSTYPE_NULL);
1049    else {
1050        fd2 = mastoapi_date(tmp);
1051        tmp = fd2;
1052    }
1053
1054    st = xs_dict_append(st, "edited_at", tmp);
1055
1056    if (strcmp(type, "Question") == 0) {
1057        xs *poll = mastoapi_poll(snac, msg);
1058        st = xs_dict_append(st, "poll", poll);
1059    }
1060    else
1061        st = xs_dict_append(st, "poll", xs_stock(XSTYPE_NULL));
1062
1063    st = xs_dict_append(st, "bookmarked",
1064        (snac && is_bookmarked(snac, id)) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1065
1066    st = xs_dict_append(st, "pinned",
1067        (snac && is_pinned(snac, id)) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1068
1069    /* is it a boost? */
1070    if (!xs_is_null(boosted_by_md5)) {
1071        /* create a new dummy status, using st as the 'reblog' field */
1072        xs_dict *bst = xs_dup(st);
1073        xs *b_actor = NULL;
1074
1075        if (valid_status(object_get_by_md5(boosted_by_md5, &b_actor))) {
1076            xs *b_acct   = mastoapi_account(b_actor);
1077            xs *fake_uri = NULL;
1078
1079            if (snac)
1080                fake_uri = xs_fmt("%s/d/%s/Announce", snac->actor, mid);
1081            else
1082                fake_uri = xs_fmt("%s#%s", srv_baseurl, mid);
1083
1084            bst = xs_dict_set(bst, "uri", fake_uri);
1085            bst = xs_dict_set(bst, "url", fake_uri);
1086            bst = xs_dict_set(bst, "account", b_acct);
1087            bst = xs_dict_set(bst, "content", "");
1088            bst = xs_dict_set(bst, "reblog", st);
1089
1090            xs_free(st);
1091            st = bst;
1092        }
1093    }
1094
1095    return st;
1096}
1097
1098
1099xs_dict *mastoapi_relationship(snac *snac, const char *md5)
1100{
1101    xs_dict *rel = NULL;
1102    xs *actor_o  = NULL;
1103
1104    if (valid_status(object_get_by_md5(md5, &actor_o))) {
1105        rel = xs_dict_new();
1106
1107        const char *actor = xs_dict_get(actor_o, "id");
1108
1109        rel = xs_dict_append(rel, "id",                   md5);
1110        rel = xs_dict_append(rel, "following",
1111            following_check(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1112
1113        rel = xs_dict_append(rel, "showing_reblogs",      xs_stock(XSTYPE_TRUE));
1114        rel = xs_dict_append(rel, "notifying",            xs_stock(XSTYPE_FALSE));
1115        rel = xs_dict_append(rel, "followed_by",
1116            follower_check(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1117
1118        rel = xs_dict_append(rel, "blocking",
1119            is_muted(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1120
1121        rel = xs_dict_append(rel, "muting",               xs_stock(XSTYPE_FALSE));
1122        rel = xs_dict_append(rel, "muting_notifications", xs_stock(XSTYPE_FALSE));
1123        rel = xs_dict_append(rel, "requested",            xs_stock(XSTYPE_FALSE));
1124        rel = xs_dict_append(rel, "domain_blocking",      xs_stock(XSTYPE_FALSE));
1125        rel = xs_dict_append(rel, "endorsed",             xs_stock(XSTYPE_FALSE));
1126        rel = xs_dict_append(rel, "note",                 "");
1127    }
1128
1129    return rel;
1130}
1131
1132
1133int process_auth_token(snac *snac, const xs_dict *req)
1134/* processes an authorization token, if there is one */
1135{
1136    int logged_in = 0;
1137    const char *v;
1138
1139    /* if there is an authorization field, try to validate it */
1140    if (!xs_is_null(v = xs_dict_get(req, "authorization")) && xs_startswith(v, "Bearer ")) {
1141        xs *tokid = xs_replace_n(v, "Bearer ", "", 1);
1142        xs *token = token_get(tokid);
1143
1144        if (token != NULL) {
1145            const char *uid = xs_dict_get(token, "uid");
1146
1147            if (!xs_is_null(uid) && user_open(snac, uid)) {
1148                logged_in = 1;
1149
1150                /* this counts as a 'login' */
1151                lastlog_write(snac, "mastoapi");
1152
1153                srv_debug(2, xs_fmt("mastoapi auth: valid token for user '%s'", uid));
1154            }
1155            else
1156                srv_log(xs_fmt("mastoapi auth: corrupted token '%s'", tokid));
1157        }
1158        else
1159            srv_log(xs_fmt("mastoapi auth: invalid token '%s'", tokid));
1160    }
1161
1162    return logged_in;
1163}
1164
1165void credentials_get(char **body, char **ctype, int *status, snac snac)
1166{
1167    xs *acct = xs_dict_new();
1168
1169    acct = xs_dict_append(acct, "id", snac.md5);
1170    acct = xs_dict_append(acct, "username", xs_dict_get(snac.config, "uid"));
1171    acct = xs_dict_append(acct, "acct", xs_dict_get(snac.config, "uid"));
1172    acct = xs_dict_append(acct, "display_name", xs_dict_get(snac.config, "name"));
1173    acct = xs_dict_append(acct, "created_at", xs_dict_get(snac.config, "published"));
1174    acct = xs_dict_append(acct, "last_status_at", xs_dict_get(snac.config, "published"));
1175    acct = xs_dict_append(acct, "note", xs_dict_get(snac.config, "bio"));
1176    acct = xs_dict_append(acct, "url", snac.actor);
1177    acct = xs_dict_append(acct, "locked", xs_stock(XSTYPE_FALSE));
1178    acct = xs_dict_append(acct, "bot", xs_dict_get(snac.config, "bot"));
1179    acct = xs_dict_append(acct, "emojis", xs_stock(XSTYPE_LIST));
1180
1181    xs *src = xs_json_loads("{\"privacy\":\"public\", \"language\":\"en\","
1182        "\"follow_requests_count\": 0,"
1183        "\"sensitive\":false,\"fields\":[],\"note\":\"\"}");
1184    /* some apps take the note from the source object */
1185    src = xs_dict_set(src, "note", xs_dict_get(snac.config, "bio"));
1186    src = xs_dict_set(src, "privacy", xs_type(xs_dict_get(snac.config, "private")) == XSTYPE_TRUE ? "private" : "public");
1187
1188    const xs_str *cw = xs_dict_get(snac.config, "cw");
1189    src = xs_dict_set(src, "sensitive",
1190        strcmp(cw, "open") == 0 ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1191
1192    src = xs_dict_set(src, "bot", xs_dict_get(snac.config, "bot"));
1193
1194    xs *avatar = NULL;
1195    const char *av = xs_dict_get(snac.config, "avatar");
1196
1197    if (xs_is_null(av) || *av == '\0')
1198        avatar = xs_fmt("%s/susie.png", srv_baseurl);
1199    else
1200        avatar = xs_dup(av);
1201
1202    acct = xs_dict_append(acct, "avatar", avatar);
1203    acct = xs_dict_append(acct, "avatar_static", avatar);
1204
1205    xs *header = NULL;
1206    const char *hd = xs_dict_get(snac.config, "header");
1207
1208    if (!xs_is_null(hd))
1209        header = xs_dup(hd);
1210    else
1211        header = xs_str_new(NULL);
1212
1213    acct = xs_dict_append(acct, "header", header);
1214    acct = xs_dict_append(acct, "header_static", header);
1215
1216    const xs_dict *metadata = xs_dict_get(snac.config, "metadata");
1217    if (xs_type(metadata) == XSTYPE_DICT) {
1218        xs *fields = xs_list_new();
1219        const xs_str *k;
1220        const xs_str *v;
1221
1222        xs_dict *val_links = snac.links;
1223        if (xs_is_null(val_links))
1224            val_links = xs_stock(XSTYPE_DICT);
1225
1226        int c = 0;
1227        while (xs_dict_next(metadata, &k, &v, &c)) {
1228            xs *val_date = NULL;
1229
1230            const xs_number *verified_time = xs_dict_get(val_links, v);
1231            if (xs_type(verified_time) == XSTYPE_NUMBER) {
1232                time_t t = xs_number_get(verified_time);
1233
1234                if (t > 0)
1235                    val_date = xs_str_utctime(t, ISO_DATE_SPEC);
1236            }
1237
1238            xs *d = xs_dict_new();
1239
1240            d = xs_dict_append(d, "name", k);
1241            d = xs_dict_append(d, "value", v);
1242            d = xs_dict_append(d, "verified_at",
1243                               xs_type(val_date) == XSTYPE_STRING && *val_date ? val_date : xs_stock(XSTYPE_NULL));
1244
1245            fields = xs_list_append(fields, d);
1246        }
1247
1248        acct = xs_dict_set(acct, "fields", fields);
1249        /* some apps take the fields from the source object */
1250        src = xs_dict_set(src, "fields", fields);
1251    }
1252
1253    acct = xs_dict_append(acct, "source", src);
1254    acct = xs_dict_append(acct, "followers_count", xs_stock(0));
1255    acct = xs_dict_append(acct, "following_count", xs_stock(0));
1256    acct = xs_dict_append(acct, "statuses_count", xs_stock(0));
1257
1258    *body = xs_json_dumps(acct, 4);
1259    *ctype = "application/json";
1260    *status = HTTP_STATUS_OK;
1261}
1262
1263
1264xs_list *mastoapi_timeline(snac *user, const xs_dict *args, const char *index_fn)
1265{
1266    xs_list *out = xs_list_new();
1267    FILE *f;
1268    char md5[MD5_HEX_SIZE];
1269
1270    if (dbglevel) {
1271        xs *js = xs_json_dumps(args, 0);
1272        srv_debug(1, xs_fmt("mastoapi_timeline args %s", js));
1273    }
1274
1275    if ((f = fopen(index_fn, "r")) == NULL)
1276        return out;
1277
1278    const char *max_id   = xs_dict_get(args, "max_id");
1279    const char *since_id = xs_dict_get(args, "since_id");
1280    const char *min_id   = xs_dict_get(args, "min_id");
1281    const char *limit_s  = xs_dict_get(args, "limit");
1282    int limit = 0;
1283    int cnt   = 0;
1284
1285    if (!xs_is_null(limit_s))
1286        limit = atoi(limit_s);
1287
1288    if (limit == 0)
1289        limit = 20;
1290
1291    if (index_desc_first(f, md5, 0)) {
1292        do {
1293            xs *msg = NULL;
1294
1295            /* only return entries older that max_id */
1296            if (max_id) {
1297                if (strcmp(md5, MID_TO_MD5(max_id)) == 0)
1298                    max_id = NULL;
1299
1300                continue;
1301            }
1302
1303            /* only returns entries newer than since_id */
1304            if (since_id) {
1305                if (strcmp(md5, MID_TO_MD5(since_id)) == 0)
1306                    break;
1307            }
1308
1309            /* only returns entries newer than min_id */
1310            /* what does really "Return results immediately newer than ID" mean? */
1311            if (min_id) {
1312                if (strcmp(md5, MID_TO_MD5(min_id)) == 0)
1313                    break;
1314            }
1315
1316            /* get the entry */
1317            if (user) {
1318                if (!valid_status(timeline_get_by_md5(user, md5, &msg)))
1319                    continue;
1320            }
1321            else {
1322                if (!valid_status(object_get_by_md5(md5, &msg)))
1323                    continue;
1324            }
1325
1326            /* discard non-Notes */
1327            const char *id   = xs_dict_get(msg, "id");
1328            const char *type = xs_dict_get(msg, "type");
1329            if (!xs_match(type, POSTLIKE_OBJECT_TYPE))
1330                continue;
1331
1332            const char *from = NULL;
1333            if (strcmp(type, "Page") == 0)
1334                from = xs_dict_get(msg, "audience");
1335
1336            if (from == NULL)
1337                from = get_atto(msg);
1338
1339            if (from == NULL)
1340                continue;
1341
1342            if (user) {
1343                /* is this message from a person we don't follow? */
1344                if (strcmp(from, user->actor) && !following_check(user, from)) {
1345                    /* discard if it was not boosted */
1346                    xs *idx = object_announces(id);
1347
1348                    if (xs_list_len(idx) == 0)
1349                        continue;
1350                }
1351
1352                /* discard notes from muted morons */
1353                if (is_muted(user, from))
1354                    continue;
1355
1356                /* discard hidden notes */
1357                if (is_hidden(user, id))
1358                    continue;
1359            }
1360            else {
1361                /* skip non-public messages */
1362                if (!is_msg_public(msg))
1363                    continue;
1364
1365                /* discard messages from private users */
1366                if (is_msg_from_private_user(msg))
1367                    continue;
1368            }
1369
1370            /* if it has a name and it's not a Page or a Video,
1371               it's a poll vote, so discard it */
1372            if (!xs_is_null(xs_dict_get(msg, "name")) && !xs_match(type, "Page|Video"))
1373                continue;
1374
1375            /* convert the Note into a Mastodon status */
1376            xs *st = mastoapi_status(user, msg);
1377
1378            if (st != NULL) {
1379                out = xs_list_append(out, st);
1380                cnt++;
1381            }
1382
1383        } while (cnt < limit && index_desc_next(f, md5));
1384    }
1385
1386    int more = index_desc_next(f, md5);
1387
1388    fclose(f);
1389
1390    srv_debug(1, xs_fmt("mastoapi_timeline ret %d%s", cnt, more ? " (+)" : ""));
1391
1392    return out;
1393}
1394
1395
1396int mastoapi_get_handler(const xs_dict *req, const char *q_path,
1397                         char **body, int *b_size, char **ctype)
1398{
1399    (void)b_size;
1400
1401    if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
1402        return 0;
1403
1404    int status    = HTTP_STATUS_NOT_FOUND;
1405    const xs_dict *args = xs_dict_get(req, "q_vars");
1406    xs *cmd       = xs_replace_n(q_path, "/api", "", 1);
1407
1408    snac snac1 = {0};
1409    int logged_in = process_auth_token(&snac1, req);
1410
1411    if (strcmp(cmd, "/v1/accounts/verify_credentials") == 0) { /** **/
1412        if (logged_in) {
1413            credentials_get(body, ctype, &status, snac1);
1414        }
1415        else {
1416            status = HTTP_STATUS_UNPROCESSABLE_CONTENT; // (no login)
1417        }
1418    }
1419    else
1420    if (strcmp(cmd, "/v1/accounts/relationships") == 0) { /** **/
1421        /* find if an account is followed, blocked, etc. */
1422        /* the account to get relationships about is in args "id[]" */
1423
1424        if (logged_in) {
1425            xs *res         = xs_list_new();
1426            const char *md5 = xs_dict_get(args, "id[]");
1427
1428            if (xs_is_null(md5))
1429                md5 = xs_dict_get(args, "id");
1430
1431            if (!xs_is_null(md5)) {
1432                if (xs_type(md5) == XSTYPE_LIST)
1433                    md5 = xs_list_get(md5, 0);
1434
1435                xs *rel = mastoapi_relationship(&snac1, md5);
1436
1437                if (rel != NULL)
1438                    res = xs_list_append(res, rel);
1439            }
1440
1441            *body  = xs_json_dumps(res, 4);
1442            *ctype = "application/json";
1443            status = HTTP_STATUS_OK;
1444        }
1445        else
1446            status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
1447    }
1448    else
1449    if (strcmp(cmd, "/v1/accounts/lookup") == 0) { /** **/
1450        /* lookup an account */
1451        const char *acct = xs_dict_get(args, "acct");
1452
1453        if (!xs_is_null(acct)) {
1454            xs *s = xs_strip_chars_i(xs_dup(acct), "@");
1455            xs *l = xs_split_n(s, "@", 1);
1456            const char *uid = xs_list_get(l, 0);
1457            const char *host = xs_list_get(l, 1);
1458
1459            if (uid && (!host || strcmp(host, xs_dict_get(srv_config, "host")) == 0)) {
1460                snac user;
1461
1462                if (user_open(&user, uid)) {
1463                    xs *actor = msg_actor(&user);
1464                    xs *macct = mastoapi_account(actor);
1465
1466                    *body  = xs_json_dumps(macct, 4);
1467                    *ctype = "application/json";
1468                    status = HTTP_STATUS_OK;
1469
1470                    user_free(&user);
1471                }
1472            }
1473        }
1474    }
1475    else
1476    if (xs_startswith(cmd, "/v1/accounts/")) { /** **/
1477        /* account-related information */
1478        xs *l = xs_split(cmd, "/");
1479        const char *uid = xs_list_get(l, 3);
1480        const char *opt = xs_list_get(l, 4);
1481
1482        if (uid != NULL) {
1483            snac snac2;
1484            xs *out   = NULL;
1485            xs *actor = NULL;
1486
1487            if (logged_in && strcmp(uid, "search") == 0) { /** **/
1488                /* search for accounts starting with q */
1489                const char *aq = xs_dict_get(args, "q");
1490
1491                if (!xs_is_null(aq)) {
1492                    xs *q    = xs_tolower_i(xs_dup(aq));
1493                    out      = xs_list_new();
1494                    xs *wing = following_list(&snac1);
1495                    xs *wers = follower_list(&snac1);
1496                    xs *ulst = user_list();
1497                    xs_list *p;
1498                    const xs_str *v;
1499                    xs_set seen;
1500
1501                    xs_set_init(&seen);
1502
1503                    /* user relations */
1504                    xs_list *lsts[] = { wing, wers, NULL };
1505                    int n;
1506                    for (n = 0; (p = lsts[n]) != NULL; n++) {
1507
1508                        while (xs_list_iter(&p, &v)) {
1509                            /* already seen? skip */
1510                            if (xs_set_add(&seen, v) == 0)
1511                                continue;
1512
1513                            xs *actor = NULL;
1514
1515                            if (valid_status(object_get(v, &actor))) {
1516                                const char *uname = xs_dict_get(actor, "preferredUsername");
1517
1518                                if (!xs_is_null(uname)) {
1519                                    xs *luname = xs_tolower_i(xs_dup(uname));
1520
1521                                    if (xs_startswith(luname, q)) {
1522                                        xs *acct = mastoapi_account(actor);
1523
1524                                        out = xs_list_append(out, acct);
1525                                    }
1526                                }
1527                            }
1528                        }
1529                    }
1530
1531                    /* local users */
1532                    p = ulst;
1533                    while (xs_list_iter(&p, &v)) {
1534                        snac user;
1535
1536                        /* skip this same user */
1537                        if (strcmp(v, xs_dict_get(snac1.config, "uid")) == 0)
1538                            continue;
1539
1540                        /* skip if the uid does not start with the query */
1541                        xs *v2 = xs_tolower_i(xs_dup(v));
1542                        if (!xs_startswith(v2, q))
1543                            continue;
1544
1545                        if (user_open(&user, v)) {
1546                            /* if it's not already seen, add it */
1547                            if (xs_set_add(&seen, user.actor) == 1) {
1548                                xs *actor = msg_actor(&user);
1549                                xs *acct  = mastoapi_account(actor);
1550
1551                                out = xs_list_append(out, acct);
1552                            }
1553
1554                            user_free(&user);
1555                        }
1556                    }
1557
1558                    xs_set_free(&seen);
1559                }
1560            }
1561            else
1562            /* is it a local user? */
1563            if (user_open(&snac2, uid) || user_open_by_md5(&snac2, uid)) {
1564                if (opt == NULL) {
1565                    /* account information */
1566                    actor = msg_actor(&snac2);
1567                    out   = mastoapi_account(actor);
1568                }
1569                else
1570                if (strcmp(opt, "statuses") == 0) { /** **/
1571                    /* the public list of posts of a user */
1572                    xs *timeline = timeline_simple_list(&snac2, "public", 0, 256);
1573                    xs_list *p   = timeline;
1574                    const xs_str *v;
1575
1576                    out = xs_list_new();
1577
1578                    while (xs_list_iter(&p, &v)) {
1579                        xs *msg = NULL;
1580
1581                        if (valid_status(timeline_get_by_md5(&snac2, v, &msg))) {
1582                            /* add only posts by the author */
1583                            if (strcmp(xs_dict_get(msg, "type"), "Note") == 0 &&
1584                                xs_startswith(xs_dict_get(msg, "id"), snac2.actor)) {
1585                                xs *st = mastoapi_status(&snac2, msg);
1586
1587                                if (st)
1588                                    out = xs_list_append(out, st);
1589                            }
1590                        }
1591                    }
1592                }
1593                else
1594                if (strcmp(opt, "featured_tags") == 0) {
1595                    /* snac doesn't have features tags, yet? */
1596                    /* implement empty response so apps like Tokodon don't show an error */
1597                    out = xs_list_new();
1598                }
1599                else
1600                if (strcmp(opt, "following") == 0) {
1601                    xs *wing = following_list(&snac1);
1602                    out = xs_list_new();
1603                    int c = 0;
1604                    const char *v;
1605
1606                    while (xs_list_next(wing, &v, &c)) {
1607                        xs *actor = NULL;
1608
1609                        if (valid_status(object_get(v, &actor))) {
1610                            xs *acct = mastoapi_account(actor);
1611                            out = xs_list_append(out, acct);
1612                        }
1613                    }
1614                }
1615                else
1616                if (strcmp(opt, "followers") == 0) {
1617                    out = xs_list_new();
1618                }
1619
1620                user_free(&snac2);
1621            }
1622            else {
1623                /* try the uid as the md5 of a possibly loaded actor */
1624                if (logged_in && valid_status(object_get_by_md5(uid, &actor))) {
1625                    if (opt == NULL) {
1626                        /* account information */
1627                        out = mastoapi_account(actor);
1628                    }
1629                    else
1630                    if (strcmp(opt, "statuses") == 0) {
1631                        /* we don't serve statuses of others; return the empty list */ 
1632                        out = xs_list_new();
1633                    }
1634                    else
1635                    if (strcmp(opt, "featured_tags") == 0) {
1636                        /* snac doesn't have features tags, yet? */
1637                        /* implement empty response so apps like Tokodon don't show an error */
1638                        out = xs_list_new();
1639                    }
1640                }
1641            }
1642
1643            if (out != NULL) {
1644                *body  = xs_json_dumps(out, 4);
1645                *ctype = "application/json";
1646                status = HTTP_STATUS_OK;
1647            }
1648        }
1649    }
1650    else
1651    if (strcmp(cmd, "/v1/timelines/home") == 0) { /** **/
1652        /* the private timeline */
1653        if (logged_in) {
1654            xs *ifn = user_index_fn(&snac1, "private");
1655            xs *out = mastoapi_timeline(&snac1, args, ifn);
1656
1657            *body  = xs_json_dumps(out, 4);
1658            *ctype = "application/json";
1659            status = HTTP_STATUS_OK;
1660
1661            srv_debug(2, xs_fmt("mastoapi timeline: returned %d entries", xs_list_len(out)));
1662        }
1663        else {
1664            status = HTTP_STATUS_UNAUTHORIZED;
1665        }
1666    }
1667    else
1668    if (strcmp(cmd, "/v1/timelines/public") == 0) { /** **/
1669        /* the instance public timeline (public timelines for all users) */
1670        snac *user = NULL;
1671        if (logged_in)
1672            user = &snac1;
1673
1674        xs *ifn = instance_index_fn();
1675        xs *out = mastoapi_timeline(user, args, ifn);
1676
1677        *body  = xs_json_dumps(out, 4);
1678        *ctype = "application/json";
1679        status = HTTP_STATUS_OK;
1680    }
1681    else
1682    if (xs_startswith(cmd, "/v1/timelines/tag/")) { /** **/
1683        /* get the tag */
1684        xs *l = xs_split(cmd, "/");
1685        const char *tag = xs_list_get(l, -1);
1686
1687        xs *ifn = tag_fn(tag);
1688        xs *out = mastoapi_timeline(NULL, args, ifn);
1689
1690        *body  = xs_json_dumps(out, 4);
1691        *ctype = "application/json";
1692        status = HTTP_STATUS_OK;
1693    }
1694    else
1695    if (xs_startswith(cmd, "/v1/timelines/list/")) { /** **/
1696        /* get the list id */
1697        if (logged_in) {
1698            xs *l = xs_split(cmd, "/");
1699            const char *list = xs_list_get(l, -1);
1700
1701            xs *ifn = list_timeline_fn(&snac1, list);
1702            xs *out = mastoapi_timeline(NULL, args, ifn);
1703
1704            *body  = xs_json_dumps(out, 4);
1705            *ctype = "application/json";
1706            status = HTTP_STATUS_OK;
1707        }
1708        else
1709            status = HTTP_STATUS_MISDIRECTED_REQUEST;
1710    }
1711    else
1712    if (strcmp(cmd, "/v1/conversations") == 0) { /** **/
1713        /* TBD */
1714        *body  = xs_dup("[]");
1715        *ctype = "application/json";
1716        status = HTTP_STATUS_OK;
1717    }
1718    else
1719    if (strcmp(cmd, "/v1/notifications") == 0) { /** **/
1720        if (logged_in) {
1721            xs *l      = notify_list(&snac1, 0, 64);
1722            xs *out    = xs_list_new();
1723            xs_list *p = l;
1724            const xs_dict *v;
1725            const xs_list *excl = xs_dict_get(args, "exclude_types[]");
1726
1727            while (xs_list_iter(&p, &v)) {
1728                xs *noti = notify_get(&snac1, v);
1729
1730                if (noti == NULL)
1731                    continue;
1732
1733                const char *type  = xs_dict_get(noti, "type");
1734                const char *utype = xs_dict_get(noti, "utype");
1735                const char *objid = xs_dict_get(noti, "objid");
1736                xs *actor = NULL;
1737                xs *entry = NULL;
1738
1739                if (!valid_status(actor_get(xs_dict_get(noti, "actor"), &actor)))
1740                    continue;
1741
1742                if (objid != NULL && !valid_status(object_get(objid, &entry)))
1743                    continue;
1744
1745                if (is_hidden(&snac1, objid))
1746                    continue;
1747
1748                /* convert the type */
1749                if (strcmp(type, "Like") == 0 || strcmp(type, "EmojiReact") == 0)
1750                    type = "favourite";
1751                else
1752                if (strcmp(type, "Announce") == 0)
1753                    type = "reblog";
1754                else
1755                if (strcmp(type, "Follow") == 0)
1756                    type = "follow";
1757                else
1758                if (strcmp(type, "Create") == 0)
1759                    type = "mention";
1760                else
1761                if (strcmp(type, "Update") == 0 && strcmp(utype, "Question") == 0)
1762                    type = "poll";
1763                else
1764                    continue;
1765
1766                /* excluded type? */
1767                if (!xs_is_null(excl) && xs_list_in(excl, type) != -1)
1768                    continue;
1769
1770                xs *mn = xs_dict_new();
1771
1772                mn = xs_dict_append(mn, "type", type);
1773
1774                xs *id = xs_replace(xs_dict_get(noti, "id"), ".", "");
1775                mn = xs_dict_append(mn, "id", id);
1776
1777                mn = xs_dict_append(mn, "created_at", xs_dict_get(noti, "date"));
1778
1779                xs *acct = mastoapi_account(actor);
1780                mn = xs_dict_append(mn, "account", acct);
1781
1782                if (strcmp(type, "follow") != 0 && !xs_is_null(objid)) {
1783                    xs *st = mastoapi_status(&snac1, entry);
1784
1785                    if (st)
1786                        mn = xs_dict_append(mn, "status", st);
1787                }
1788
1789                out = xs_list_append(out, mn);
1790            }
1791
1792            *body  = xs_json_dumps(out, 4);
1793            *ctype = "application/json";
1794            status = HTTP_STATUS_OK;
1795        }
1796        else
1797            status = HTTP_STATUS_UNAUTHORIZED;
1798    }
1799    else
1800    if (strcmp(cmd, "/v1/filters") == 0) { /** **/
1801        /* snac will never have filters */
1802        *body  = xs_dup("[]");
1803        *ctype = "application/json";
1804        status = HTTP_STATUS_OK;
1805    }
1806    else
1807    if (strcmp(cmd, "/v2/filters") == 0) { /** **/
1808        /* snac will never have filters 
1809         * but still, without a v2 endpoint a short delay is introduced
1810         * in some apps */
1811        *body  = xs_dup("[]");
1812        *ctype = "application/json";
1813        status = HTTP_STATUS_OK;
1814    }
1815    else
1816    if (strcmp(cmd, "/v1/favourites") == 0) { /** **/
1817        /* snac will never support a list of favourites */
1818        *body  = xs_dup("[]");
1819        *ctype = "application/json";
1820        status = HTTP_STATUS_OK;
1821    }
1822    else
1823    if (strcmp(cmd, "/v1/bookmarks") == 0) { /** **/
1824        if (logged_in) {
1825            xs *ifn = bookmark_index_fn(&snac1);
1826            xs *out = mastoapi_timeline(&snac1, args, ifn);
1827
1828            *body  = xs_json_dumps(out, 4);
1829            *ctype = "application/json";
1830            status = HTTP_STATUS_OK;
1831        }
1832        else
1833            status = HTTP_STATUS_UNAUTHORIZED;
1834    }
1835    else
1836    if (strcmp(cmd, "/v1/lists") == 0) { /** list of lists **/
1837        if (logged_in) {
1838            xs *lol = list_maint(&snac1, NULL, 0);
1839            xs *l   = xs_list_new();
1840            int c = 0;
1841            const xs_list *li;
1842
1843            while (xs_list_next(lol, &li, &c)) {
1844                xs *d = xs_dict_new();
1845
1846                d = xs_dict_append(d, "id", xs_list_get(li, 0));
1847                d = xs_dict_append(d, "title", xs_list_get(li, 1));
1848                d = xs_dict_append(d, "replies_policy", "list");
1849                d = xs_dict_append(d, "exclusive", xs_stock(XSTYPE_FALSE));
1850
1851                l = xs_list_append(l, d);
1852            }
1853
1854            *body  = xs_json_dumps(l, 4);
1855            *ctype = "application/json";
1856            status = HTTP_STATUS_OK;
1857        }
1858        else
1859            status = HTTP_STATUS_UNAUTHORIZED;
1860    }
1861    else
1862    if (xs_startswith(cmd, "/v1/lists/")) { /** list information **/
1863        if (logged_in) {
1864            xs *l = xs_split(cmd, "/");
1865            const char *p = xs_list_get(l, -1);
1866
1867            if (p) {
1868                if (strcmp(p, "accounts") == 0) {
1869                    p = xs_list_get(l, -2);
1870
1871                    if (p && xs_is_hex(p)) {
1872                        xs *actors = list_content(&snac1, p, NULL, 0);
1873                        xs *out = xs_list_new();
1874                        int c = 0;
1875                        const char *v;
1876
1877                        while (xs_list_next(actors, &v, &c)) {
1878                            xs *actor = NULL;
1879
1880                            if (valid_status(object_get_by_md5(v, &actor))) {
1881                                xs *acct = mastoapi_account(actor);
1882                                out = xs_list_append(out, acct);
1883                            }
1884                        }
1885
1886                        *body  = xs_json_dumps(out, 4);
1887                        *ctype = "application/json";
1888                        status = HTTP_STATUS_OK;
1889                    }
1890                }
1891                else
1892                if (xs_is_hex(p)) {
1893                    xs *out = xs_list_new();
1894                    xs *lol = list_maint(&snac1, NULL, 0);
1895                    int c = 0;
1896                    const xs_list *v;
1897
1898                    while (xs_list_next(lol, &v, &c)) {
1899                        const char *id = xs_list_get(v, 0);
1900
1901                        if (id && strcmp(id, p) == 0) {
1902                            xs *d = xs_dict_new();
1903
1904                            d = xs_dict_append(d, "id", p);
1905                            d = xs_dict_append(d, "title", xs_list_get(v, 1));
1906                            d = xs_dict_append(d, "replies_policy", "list");
1907                            d = xs_dict_append(d, "exclusive", xs_stock(XSTYPE_FALSE));
1908
1909                            out = xs_dup(d);
1910                            break;
1911                        }
1912                    }
1913
1914                    *body  = xs_json_dumps(out, 4);
1915                    *ctype = "application/json";
1916                    status = HTTP_STATUS_OK;
1917                }
1918            }
1919        }
1920        else
1921            status = HTTP_STATUS_UNAUTHORIZED;
1922    }
1923    else
1924    if (strcmp(cmd, "/v1/scheduled_statuses") == 0) { /** **/
1925        /* snac does not schedule notes */
1926        *body  = xs_dup("[]");
1927        *ctype = "application/json";
1928        status = HTTP_STATUS_OK;
1929    }
1930    else
1931    if (strcmp(cmd, "/v1/follow_requests") == 0) { /** **/
1932        /* snac does not support optional follow confirmations */
1933        *body  = xs_dup("[]");
1934        *ctype = "application/json";
1935        status = HTTP_STATUS_OK;
1936    }
1937    else
1938    if (strcmp(cmd, "/v1/announcements") == 0) { /** **/
1939        if (logged_in) {
1940            xs *resp = xs_list_new();
1941            double la = 0.0;
1942            xs *user_la = xs_dup(xs_dict_get(snac1.config, "last_announcement"));
1943            if (user_la != NULL)
1944                la = xs_number_get(user_la);
1945            xs *val_date = xs_str_utctime(la, ISO_DATE_SPEC);
1946
1947            /* contrary to html, we always send the announcement and set the read flag instead */
1948
1949            const t_announcement *annce = announcement(la);
1950            if (annce != NULL && annce->text != NULL) {
1951                xs *an = xs_dict_new();
1952                xs *id = xs_fmt("%d", annce->timestamp);
1953                xs *ct = xs_fmt("<p>%s</p>", annce->text);
1954
1955                an = xs_dict_set(an, "id",           id);
1956                an = xs_dict_set(an, "content",      ct);
1957                an = xs_dict_set(an, "starts_at",    xs_stock(XSTYPE_NULL));
1958                an = xs_dict_set(an, "ends_at",      xs_stock(XSTYPE_NULL));
1959                an = xs_dict_set(an, "all_day",      xs_stock(XSTYPE_TRUE));
1960                an = xs_dict_set(an, "published_at", val_date);
1961                an = xs_dict_set(an, "updated_at",   val_date);
1962                an = xs_dict_set(an, "read",         (annce->timestamp >= la)
1963                    ? xs_stock(XSTYPE_FALSE) : xs_stock(XSTYPE_TRUE));
1964                an = xs_dict_set(an, "mentions",     xs_stock(XSTYPE_LIST));
1965                an = xs_dict_set(an, "statuses",     xs_stock(XSTYPE_LIST));
1966                an = xs_dict_set(an, "tags",         xs_stock(XSTYPE_LIST));
1967                an = xs_dict_set(an, "emojis",       xs_stock(XSTYPE_LIST));
1968                an = xs_dict_set(an, "reactions",    xs_stock(XSTYPE_LIST));
1969                resp = xs_list_append(resp, an);
1970            }
1971
1972            *body  = xs_json_dumps(resp, 4);
1973            *ctype = "application/json";
1974            status = HTTP_STATUS_OK;
1975        }
1976    }
1977    else
1978    if (strcmp(cmd, "/v1/custom_emojis") == 0) { /** **/
1979        /* are you kidding me? */
1980        *body  = xs_dup("[]");
1981        *ctype = "application/json";
1982        status = HTTP_STATUS_OK;
1983    }
1984    else
1985    if (strcmp(cmd, "/v1/instance") == 0) { /** **/
1986        /* returns an instance object */
1987        xs *ins = xs_dict_new();
1988        const char *host  = xs_dict_get(srv_config, "host");
1989        const char *title = xs_dict_get(srv_config, "title");
1990        const char *sdesc = xs_dict_get(srv_config, "short_description");
1991
1992        ins = xs_dict_append(ins, "uri",         host);
1993        ins = xs_dict_append(ins, "domain",      host);
1994        ins = xs_dict_append(ins, "title",       title && *title ? title : host);
1995        ins = xs_dict_append(ins, "version",     "4.0.0 (not true; really " USER_AGENT ")");
1996        ins = xs_dict_append(ins, "source_url",  WHAT_IS_SNAC_URL);
1997        ins = xs_dict_append(ins, "description", host);
1998
1999        ins = xs_dict_append(ins, "short_description", sdesc && *sdesc ? sdesc : host);
2000
2001        xs *susie = xs_fmt("%s/susie.png", srv_baseurl);
2002        ins = xs_dict_append(ins, "thumbnail", susie);
2003
2004        const char *v = xs_dict_get(srv_config, "admin_email");
2005        if (xs_is_null(v) || *v == '\0')
2006            v = "admin@localhost";
2007
2008        ins = xs_dict_append(ins, "email", v);
2009
2010        ins = xs_dict_append(ins, "rules", xs_stock(XSTYPE_LIST));
2011
2012        xs *l1 = xs_list_append(xs_list_new(), "en");
2013        ins = xs_dict_append(ins, "languages", l1);
2014
2015        xs *wss = xs_fmt("wss:/" "/%s", xs_dict_get(srv_config, "host"));
2016        xs *urls = xs_dict_new();
2017        urls = xs_dict_append(urls, "streaming_api", wss);
2018
2019        ins = xs_dict_append(ins, "urls", urls);
2020
2021        xs *d2 = xs_dict_append(xs_dict_new(), "user_count", xs_stock(0));
2022        d2 = xs_dict_append(d2, "status_count", xs_stock(0));
2023        d2 = xs_dict_append(d2, "domain_count", xs_stock(0));
2024        ins = xs_dict_append(ins, "stats", d2);
2025
2026        ins = xs_dict_append(ins, "registrations",     xs_stock(XSTYPE_FALSE));
2027        ins = xs_dict_append(ins, "approval_required", xs_stock(XSTYPE_FALSE));
2028        ins = xs_dict_append(ins, "invites_enabled",   xs_stock(XSTYPE_FALSE));
2029
2030        xs *cfg = xs_dict_new();
2031
2032        {
2033            xs *d11 = xs_json_loads("{\"characters_reserved_per_url\":32,"
2034                "\"max_characters\":100000,\"max_media_attachments\":8}");
2035            cfg = xs_dict_append(cfg, "statuses", d11);
2036
2037            xs *d12 = xs_json_loads("{\"max_featured_tags\":0}");
2038            cfg = xs_dict_append(cfg, "accounts", d12);
2039
2040            xs *d13 = xs_json_loads("{\"image_matrix_limit\":33177600,"
2041                        "\"image_size_limit\":16777216,"
2042                        "\"video_frame_rate_limit\":120,"
2043                        "\"video_matrix_limit\":8294400,"
2044                        "\"video_size_limit\":103809024}"
2045            );
2046
2047            {
2048                /* get the supported mime types from the internal list */
2049                const char **p = xs_mime_types;
2050                xs_set mtypes;
2051                xs_set_init(&mtypes);
2052
2053                while (*p) {
2054                    const char *type = p[1];
2055
2056                    if (xs_startswith(type, "image/") ||
2057                        xs_startswith(type, "video/") ||
2058                        xs_startswith(type, "audio/"))
2059                        xs_set_add(&mtypes, type);
2060
2061                    p += 2;
2062                }
2063
2064                xs *l = xs_set_result(&mtypes);
2065                d13 = xs_dict_append(d13, "supported_mime_types", l);
2066            }
2067
2068            cfg = xs_dict_append(cfg, "media_attachments", d13);
2069
2070            xs *d14 = xs_json_loads("{\"max_characters_per_option\":50,"
2071                "\"max_expiration\":2629746,"
2072                "\"max_options\":8,\"min_expiration\":300}");
2073            cfg = xs_dict_append(cfg, "polls", d14);
2074        }
2075
2076        ins = xs_dict_append(ins, "configuration", cfg);
2077
2078        const char *admin_account = xs_dict_get(srv_config, "admin_account");
2079
2080        if (!xs_is_null(admin_account) && *admin_account) {
2081            snac admin;
2082
2083            if (user_open(&admin, admin_account)) {
2084                xs *actor = msg_actor(&admin);
2085                xs *acct  = mastoapi_account(actor);
2086
2087                ins = xs_dict_append(ins, "contact_account", acct);
2088
2089                user_free(&admin);
2090            }
2091        }
2092
2093        *body  = xs_json_dumps(ins, 4);
2094        *ctype = "application/json";
2095        status = HTTP_STATUS_OK;
2096    }
2097    else
2098    if (xs_startswith(cmd, "/v1/statuses/")) { /** **/
2099        /* information about a status */
2100        if (logged_in) {
2101            xs *l = xs_split(cmd, "/");
2102            const char *id = xs_list_get(l, 3);
2103            const char *op = xs_list_get(l, 4);
2104
2105            if (!xs_is_null(id)) {
2106                xs *msg = NULL;
2107                xs *out = NULL;
2108
2109                /* skip the 'fake' part of the id */
2110                id = MID_TO_MD5(id);
2111
2112                if (valid_status(object_get_by_md5(id, &msg))) {
2113                    if (op == NULL) {
2114                        if (!is_muted(&snac1, get_atto(msg))) {
2115                            /* return the status itself */
2116                            out = mastoapi_status(&snac1, msg);
2117                        }
2118                    }
2119                    else
2120                    if (strcmp(op, "context") == 0) { /** **/
2121                        /* return ancestors and children */
2122                        xs *anc = xs_list_new();
2123                        xs *des = xs_list_new();
2124                        xs_list *p;
2125                        const xs_str *v;
2126                        char pid[MD5_HEX_SIZE];
2127
2128                        /* build the [grand]parent list, moving up */
2129                        strncpy(pid, id, sizeof(pid));
2130
2131                        while (object_parent(pid, pid)) {
2132                            xs *m2 = NULL;
2133
2134                            if (valid_status(timeline_get_by_md5(&snac1, pid, &m2))) {
2135                                xs *st = mastoapi_status(&snac1, m2);
2136
2137                                if (st)
2138                                    anc = xs_list_insert(anc, 0, st);
2139                            }
2140                            else
2141                                break;
2142                        }
2143
2144                        /* build the children list */
2145                        xs *children = object_children(xs_dict_get(msg, "id"));
2146                        p = children;
2147
2148                        while (xs_list_iter(&p, &v)) {
2149                            xs *m2 = NULL;
2150
2151                            if (valid_status(timeline_get_by_md5(&snac1, v, &m2))) {
2152                                if (xs_is_null(xs_dict_get(m2, "name"))) {
2153                                    xs *st = mastoapi_status(&snac1, m2);
2154
2155                                    if (st)
2156                                        des = xs_list_append(des, st);
2157                                }
2158                            }
2159                        }
2160
2161                        out = xs_dict_new();
2162                        out = xs_dict_append(out, "ancestors",   anc);
2163                        out = xs_dict_append(out, "descendants", des);
2164                    }
2165                    else
2166                    if (strcmp(op, "reblogged_by") == 0 || /** **/
2167                        strcmp(op, "favourited_by") == 0) { /** **/
2168                        /* return the list of people who liked or boosted this */
2169                        out = xs_list_new();
2170
2171                        xs *l = NULL;
2172
2173                        if (op[0] == 'r')
2174                            l = object_announces(xs_dict_get(msg, "id"));
2175                        else
2176                            l = object_likes(xs_dict_get(msg, "id"));
2177
2178                        xs_list *p = l;
2179                        const xs_str *v;
2180
2181                        while (xs_list_iter(&p, &v)) {
2182                            xs *actor2 = NULL;
2183
2184                            if (valid_status(object_get_by_md5(v, &actor2))) {
2185                                xs *acct2 = mastoapi_account(actor2);
2186
2187                                out = xs_list_append(out, acct2);
2188                            }
2189                        }
2190                    }
2191                    else
2192                    if (strcmp(op, "source") == 0) { /** **/
2193                        out = xs_dict_new();
2194
2195                        /* get the mastoapi status id */
2196                        out = xs_dict_append(out, "id", xs_list_get(l, 3));
2197
2198                        out = xs_dict_append(out, "text", xs_dict_get(msg, "sourceContent"));
2199                        out = xs_dict_append(out, "spoiler_text", xs_dict_get(msg, "summary"));
2200                    }
2201                }
2202                else
2203                    srv_debug(1, xs_fmt("mastoapi status: bad id %s", id));
2204
2205                if (out != NULL) {
2206                    *body  = xs_json_dumps(out, 4);
2207                    *ctype = "application/json";
2208                    status = HTTP_STATUS_OK;
2209                }
2210            }
2211        }
2212        else
2213            status = HTTP_STATUS_UNAUTHORIZED;
2214    }
2215    else
2216    if (strcmp(cmd, "/v1/preferences") == 0) { /** **/
2217        *body  = xs_dup("{}");
2218        *ctype = "application/json";
2219        status = HTTP_STATUS_OK;
2220    }
2221    else
2222    if (strcmp(cmd, "/v1/markers") == 0) { /** **/
2223        *body  = xs_dup("{}");
2224        *ctype = "application/json";
2225        status = HTTP_STATUS_OK;
2226    }
2227    else
2228    if (strcmp(cmd, "/v1/followed_tags") == 0) { /** **/
2229        *body  = xs_dup("[]");
2230        *ctype = "application/json";
2231        status = HTTP_STATUS_OK;
2232    }
2233    else
2234    if (strcmp(cmd, "/v1/trends/tags") == 0) { /** **/
2235        *body  = xs_dup("[]");
2236        *ctype = "application/json";
2237        status = HTTP_STATUS_OK;
2238    }
2239    else
2240    if (strcmp(cmd, "/v1/trends/statuses") == 0) { /** **/
2241        *body  = xs_dup("[]");
2242        *ctype = "application/json";
2243        status = HTTP_STATUS_OK;
2244    }
2245    else
2246    if (strcmp(cmd, "/v2/search") == 0) { /** **/
2247        if (logged_in) {
2248            const char *q      = xs_dict_get(args, "q");
2249            const char *type   = xs_dict_get(args, "type");
2250            const char *offset = xs_dict_get(args, "offset");
2251
2252            xs *acl = xs_list_new();
2253            xs *stl = xs_list_new();
2254            xs *htl = xs_list_new();
2255            xs *res = xs_dict_new();
2256
2257            if (xs_is_null(offset) || strcmp(offset, "0") == 0) {
2258                /* reply something only for offset 0; otherwise,
2259                   apps like Tusky keep asking again and again */
2260
2261                if (!xs_is_null(q)) {
2262                    if (xs_is_null(type) || strcmp(type, "accounts") == 0) {
2263                        /* do a webfinger query */
2264                        char *actor = NULL;
2265                        char *user  = NULL;
2266
2267                        if (valid_status(webfinger_request(q, &actor, &user)) && actor) {
2268                            xs *actor_o = NULL;
2269
2270                            if (valid_status(actor_request(&snac1, actor, &actor_o))) {
2271                                xs *acct = mastoapi_account(actor_o);
2272
2273                                acl = xs_list_append(acl, acct);
2274
2275                                if (!object_here(actor))
2276                                    object_add(actor, actor_o);
2277                            }
2278                        }
2279                    }
2280
2281                    if (xs_is_null(type) || strcmp(type, "hashtags") == 0) {
2282                        /* search this tag */
2283                        xs *tl = tag_search((char *)q, 0, 1);
2284
2285                        if (xs_list_len(tl)) {
2286                            xs *d = xs_dict_new();
2287
2288                            d = xs_dict_append(d, "name", q);
2289                            xs *url = xs_fmt("%s?t=%s", srv_baseurl, q);
2290                            d = xs_dict_append(d, "url", url);
2291                            d = xs_dict_append(d, "history", xs_stock(XSTYPE_LIST));
2292
2293                            htl = xs_list_append(htl, d);
2294                        }
2295                    }
2296
2297                    if (xs_is_null(type) || strcmp(type, "statuses") == 0) {
2298                        int to = 0;
2299                        int cnt = 40;
2300                        xs *tl = content_search(&snac1, q, 1, 0, cnt, 0, &to);
2301                        int c = 0;
2302                        const char *v;
2303
2304                        while (xs_list_next(tl, &v, &c) && --cnt) {
2305                            xs *post = NULL;
2306
2307                            if (!valid_status(timeline_get_by_md5(&snac1, v, &post)))
2308                                continue;
2309
2310                            xs *s = mastoapi_status(&snac1, post);
2311
2312                            if (!xs_is_null(s))
2313                                stl = xs_list_append(stl, s);
2314                        }
2315                    }
2316                }
2317            }
2318
2319            res = xs_dict_append(res, "accounts", acl);
2320            res = xs_dict_append(res, "statuses", stl);
2321            res = xs_dict_append(res, "hashtags", htl);
2322
2323            *body  = xs_json_dumps(res, 4);
2324            *ctype = "application/json";
2325            status = HTTP_STATUS_OK;
2326        }
2327        else
2328            status = HTTP_STATUS_UNAUTHORIZED;
2329    }
2330
2331    /* user cleanup */
2332    if (logged_in)
2333        user_free(&snac1);
2334
2335    srv_debug(1, xs_fmt("mastoapi_get_handler %s %d", q_path, status));
2336
2337    return status;
2338}
2339
2340
2341int mastoapi_post_handler(const xs_dict *req, const char *q_path,
2342                          const char *payload, int p_size,
2343                          char **body, int *b_size, char **ctype)
2344{
2345    (void)p_size;
2346    (void)b_size;
2347
2348    if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
2349        return 0;
2350
2351    int status    = HTTP_STATUS_NOT_FOUND;
2352    xs *args      = NULL;
2353    const char *i_ctype = xs_dict_get(req, "content-type");
2354
2355    if (i_ctype && xs_startswith(i_ctype, "application/json")) {
2356        if (!xs_is_null(payload))
2357            args = xs_json_loads(payload);
2358    }
2359    else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
2360    {
2361        // Some apps send form data instead of json so we should cater for those
2362        if (!xs_is_null(payload)) {
2363            args    = xs_url_vars(payload);
2364        }
2365    }
2366    else
2367        args = xs_dup(xs_dict_get(req, "p_vars"));
2368
2369    if (args == NULL)
2370        return HTTP_STATUS_BAD_REQUEST;
2371
2372    xs *cmd = xs_replace_n(q_path, "/api", "", 1);
2373
2374    snac snac = {0};
2375    int logged_in = process_auth_token(&snac, req);
2376
2377    if (strcmp(cmd, "/v1/apps") == 0) { /** **/
2378        const char *name  = xs_dict_get(args, "client_name");
2379        const char *ruri  = xs_dict_get(args, "redirect_uris");
2380        const char *scope = xs_dict_get(args, "scope");
2381
2382        /* Ice Cubes sends these values as query parameters, so try these */
2383        if (name == NULL && ruri == NULL && scope == NULL) {
2384            args = xs_dup(xs_dict_get(req, "q_vars"));
2385            name  = xs_dict_get(args, "client_name");
2386            ruri  = xs_dict_get(args, "redirect_uris");
2387            scope = xs_dict_get(args, "scope");
2388        }
2389
2390        if (xs_type(ruri) == XSTYPE_LIST)
2391            ruri = xs_dict_get(ruri, 0);
2392
2393        if (name && ruri) {
2394            xs *app  = xs_dict_new();
2395            xs *id   = xs_replace_i(tid(0), ".", "");
2396            xs *csec = random_str();
2397            xs *vkey = random_str();
2398            xs *cid  = NULL;
2399
2400            /* pick a non-existent random cid */
2401            for (;;) {
2402                cid = random_str();
2403                xs *p_app = app_get(cid);
2404
2405                if (p_app == NULL)
2406                    break;
2407
2408                xs_free(cid);
2409            }
2410
2411            app = xs_dict_append(app, "name",          name);
2412            app = xs_dict_append(app, "redirect_uri",  ruri);
2413            app = xs_dict_append(app, "client_id",     cid);
2414            app = xs_dict_append(app, "client_secret", csec);
2415            app = xs_dict_append(app, "vapid_key",     vkey);
2416            app = xs_dict_append(app, "id",            id);
2417
2418            *body  = xs_json_dumps(app, 4);
2419            *ctype = "application/json";
2420            status = HTTP_STATUS_OK;
2421
2422            app = xs_dict_append(app, "code", "");
2423
2424            if (scope)
2425                app = xs_dict_append(app, "scope", scope);
2426
2427            app_add(cid, app);
2428
2429            srv_debug(1, xs_fmt("mastoapi apps: new app %s", cid));
2430        }
2431    }
2432    else
2433    if (strcmp(cmd, "/v1/statuses") == 0) { /** **/
2434        if (logged_in) {
2435            /* post a new Note */
2436            const char *content    = xs_dict_get(args, "status");
2437            const char *mid        = xs_dict_get(args, "in_reply_to_id");
2438            const char *visibility = xs_dict_get(args, "visibility");
2439            const char *summary    = xs_dict_get(args, "spoiler_text");
2440            const char *media_ids  = xs_dict_get(args, "media_ids");
2441
2442            if (xs_is_null(media_ids))
2443                media_ids = xs_dict_get(args, "media_ids[]");
2444
2445            if (xs_is_null(media_ids))
2446                media_ids = xs_dict_get(args, "media_ids");
2447
2448            if (xs_is_null(visibility))
2449                visibility = "public";
2450
2451            xs *attach_list = xs_list_new();
2452            xs *irt         = NULL;
2453
2454            /* is it a reply? */
2455            if (mid != NULL) {
2456                xs *r_msg = NULL;
2457                const char *md5 = MID_TO_MD5(mid);
2458
2459                if (valid_status(object_get_by_md5(md5, &r_msg)))
2460                    irt = xs_dup(xs_dict_get(r_msg, "id"));
2461            }
2462
2463            /* does it have attachments? */
2464            if (!xs_is_null(media_ids)) {
2465                xs *mi = NULL;
2466
2467                if (xs_type(media_ids) == XSTYPE_LIST)
2468                    mi = xs_dup(media_ids);
2469                else {
2470                    mi = xs_list_new();
2471                    mi = xs_list_append(mi, media_ids);
2472                }
2473
2474                xs_list *p = mi;
2475                const xs_str *v;
2476
2477                while (xs_list_iter(&p, &v)) {
2478                    xs *l    = xs_list_new();
2479                    xs *url  = xs_fmt("%s/s/%s", snac.actor, v);
2480                    xs *desc = static_get_meta(&snac, v);
2481
2482                    l = xs_list_append(l, url);
2483                    l = xs_list_append(l, desc);
2484
2485                    attach_list = xs_list_append(attach_list, l);
2486                }
2487            }
2488
2489            /* prepare the message */
2490            xs *msg = msg_note(&snac, content, NULL, irt, attach_list,
2491                        strcmp(visibility, "public") == 0 ? 0 : 1);
2492
2493            if (!xs_is_null(summary) && *summary) {
2494                msg = xs_dict_set(msg, "sensitive", xs_stock(XSTYPE_TRUE));
2495                msg = xs_dict_set(msg, "summary",   summary);
2496            }
2497
2498            /* store */
2499            timeline_add(&snac, xs_dict_get(msg, "id"), msg);
2500
2501            /* 'Create' message */
2502            xs *c_msg = msg_create(&snac, msg);
2503            enqueue_message(&snac, c_msg);
2504
2505            timeline_touch(&snac);
2506
2507            /* convert to a mastodon status as a response code */
2508            xs *st = mastoapi_status(&snac, msg);
2509
2510            *body  = xs_json_dumps(st, 4);
2511            *ctype = "application/json";
2512            status = HTTP_STATUS_OK;
2513        }
2514        else
2515            status = HTTP_STATUS_UNAUTHORIZED;
2516    }
2517    else
2518    if (xs_startswith(cmd, "/v1/statuses")) { /** **/
2519        if (logged_in) {
2520            /* operations on a status */
2521            xs *l = xs_split(cmd, "/");
2522            const char *mid = xs_list_get(l, 3);
2523            const char *op  = xs_list_get(l, 4);
2524
2525            if (!xs_is_null(mid)) {
2526                xs *msg = NULL;
2527                xs *out = NULL;
2528
2529                /* skip the 'fake' part of the id */
2530                mid = MID_TO_MD5(mid);
2531
2532                if (valid_status(timeline_get_by_md5(&snac, mid, &msg))) {
2533                    const char *id = xs_dict_get(msg, "id");
2534
2535                    if (op == NULL) {
2536                        /* no operation (?) */
2537                    }
2538                    else
2539                    if (strcmp(op, "favourite") == 0) { /** **/
2540                        xs *n_msg = msg_admiration(&snac, id, "Like");
2541
2542                        if (n_msg != NULL) {
2543                            enqueue_message(&snac, n_msg);
2544                            timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 1);
2545
2546                            out = mastoapi_status(&snac, msg);
2547                        }
2548                    }
2549                    else
2550                    if (strcmp(op, "unfavourite") == 0) { /** **/
2551                        xs *n_msg = msg_repulsion(&snac, id, "Like");
2552
2553                        if (n_msg != NULL) {
2554                            enqueue_message(&snac, n_msg);
2555
2556                            out = mastoapi_status(&snac, msg);
2557                        }
2558                    }
2559                    else
2560                    if (strcmp(op, "reblog") == 0) { /** **/
2561                        xs *n_msg = msg_admiration(&snac, id, "Announce");
2562
2563                        if (n_msg != NULL) {
2564                            enqueue_message(&snac, n_msg);
2565                            timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 0);
2566
2567                            out = mastoapi_status(&snac, msg);
2568                        }
2569                    }
2570                    else
2571                    if (strcmp(op, "unreblog") == 0) { /** **/
2572                        xs *n_msg = msg_repulsion(&snac, id, "Announce");
2573
2574                        if (n_msg != NULL) {
2575                            enqueue_message(&snac, n_msg);
2576
2577                            out = mastoapi_status(&snac, msg);
2578                        }
2579                    }
2580                    else
2581                    if (strcmp(op, "bookmark") == 0) { /** **/
2582                        /* bookmark this message */
2583                        if (bookmark(&snac, id) == 0)
2584                            out = mastoapi_status(&snac, msg);
2585                        else
2586                            status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2587                    }
2588                    else
2589                    if (strcmp(op, "unbookmark") == 0) { /** **/
2590                        /* unbookmark this message */
2591                        unbookmark(&snac, id);
2592                        out = mastoapi_status(&snac, msg);
2593                    }
2594                    else
2595                    if (strcmp(op, "pin") == 0) { /** **/
2596                        /* pin this message */
2597                        if (pin(&snac, id) == 0)
2598                            out = mastoapi_status(&snac, msg);
2599                        else
2600                            status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2601                    }
2602                    else
2603                    if (strcmp(op, "unpin") == 0) { /** **/
2604                        /* unpin this message */
2605                        unpin(&snac, id);
2606                        out = mastoapi_status(&snac, msg);
2607                    }
2608                    else
2609                    if (strcmp(op, "mute") == 0) { /** **/
2610                        /* Mastodon's mute is snac's hide */
2611                    }
2612                    else
2613                    if (strcmp(op, "unmute") == 0) { /** **/
2614                        /* Mastodon's unmute is snac's unhide */
2615                    }
2616                }
2617
2618                if (out != NULL) {
2619                    *body  = xs_json_dumps(out, 4);
2620                    *ctype = "application/json";
2621                    status = HTTP_STATUS_OK;
2622                }
2623            }
2624        }
2625        else
2626            status = HTTP_STATUS_UNAUTHORIZED;
2627    }
2628    else
2629    if (strcmp(cmd, "/v1/notifications/clear") == 0) { /** **/
2630        if (logged_in) {
2631            notify_clear(&snac);
2632            timeline_touch(&snac);
2633
2634            *body  = xs_dup("{}");
2635            *ctype = "application/json";
2636            status = HTTP_STATUS_OK;
2637        }
2638        else
2639            status = HTTP_STATUS_UNAUTHORIZED;
2640    }
2641    else
2642    if (strcmp(cmd, "/v1/push/subscription") == 0) { /** **/
2643        /* I don't know what I'm doing */
2644        if (logged_in) {
2645            const char *v;
2646
2647            xs *wpush = xs_dict_new();
2648
2649            wpush = xs_dict_append(wpush, "id", "1");
2650
2651            v = xs_dict_get(args, "data");
2652            v = xs_dict_get(v, "alerts");
2653            wpush = xs_dict_append(wpush, "alerts", v);
2654
2655            v = xs_dict_get(args, "subscription");
2656            v = xs_dict_get(v, "endpoint");
2657            wpush = xs_dict_append(wpush, "endpoint", v);
2658
2659            xs *server_key = random_str();
2660            wpush = xs_dict_append(wpush, "server_key", server_key);
2661
2662            *body  = xs_json_dumps(wpush, 4);
2663            *ctype = "application/json";
2664            status = HTTP_STATUS_OK;
2665        }
2666        else
2667            status = HTTP_STATUS_UNAUTHORIZED;
2668    }
2669    else
2670    if (strcmp(cmd, "/v1/media") == 0 || strcmp(cmd, "/v2/media") == 0) { /** **/
2671        if (logged_in) {
2672            const xs_list *file = xs_dict_get(args, "file");
2673            const char *desc    = xs_dict_get(args, "description");
2674
2675            if (xs_is_null(desc))
2676                desc = "";
2677
2678            status = HTTP_STATUS_BAD_REQUEST;
2679
2680            if (xs_type(file) == XSTYPE_LIST) {
2681                const char *fn = xs_list_get(file, 0);
2682
2683                if (*fn != '\0') {
2684                    char *ext = strrchr(fn, '.');
2685                    xs *hash  = xs_md5_hex(fn, strlen(fn));
2686                    xs *id    = xs_fmt("%s%s", hash, ext);
2687                    xs *url   = xs_fmt("%s/s/%s", snac.actor, id);
2688                    int fo    = xs_number_get(xs_list_get(file, 1));
2689                    int fs    = xs_number_get(xs_list_get(file, 2));
2690
2691                    /* store */
2692                    static_put(&snac, id, payload + fo, fs);
2693                    static_put_meta(&snac, id, desc);
2694
2695                    /* prepare a response */
2696                    xs *rsp = xs_dict_new();
2697
2698                    rsp = xs_dict_append(rsp, "id",          id);
2699                    rsp = xs_dict_append(rsp, "type",        "image");
2700                    rsp = xs_dict_append(rsp, "url",         url);
2701                    rsp = xs_dict_append(rsp, "preview_url", url);
2702                    rsp = xs_dict_append(rsp, "remote_url",  url);
2703                    rsp = xs_dict_append(rsp, "description", desc);
2704
2705                    *body  = xs_json_dumps(rsp, 4);
2706                    *ctype = "application/json";
2707                    status = HTTP_STATUS_OK;
2708                }
2709            }
2710        }
2711        else
2712            status = HTTP_STATUS_UNAUTHORIZED;
2713    }
2714    else
2715    if (xs_startswith(cmd, "/v1/accounts")) { /** **/
2716        if (logged_in) {
2717            /* account-related information */
2718            xs *l = xs_split(cmd, "/");
2719            const char *md5 = xs_list_get(l, 3);
2720            const char *opt = xs_list_get(l, 4);
2721            xs *rsp = NULL;
2722
2723            if (!xs_is_null(md5) && *md5) {
2724                xs *actor_o = NULL;
2725
2726                if (xs_is_null(opt)) {
2727                    /* ? */
2728                }
2729                else
2730                if (strcmp(opt, "follow") == 0) { /** **/
2731                    if (valid_status(object_get_by_md5(md5, &actor_o))) {
2732                        const char *actor = xs_dict_get(actor_o, "id");
2733
2734                        xs *msg = msg_follow(&snac, actor);
2735
2736                        if (msg != NULL) {
2737                            /* reload the actor from the message, in may be different */
2738                            actor = xs_dict_get(msg, "object");
2739
2740                            following_add(&snac, actor, msg);
2741
2742                            enqueue_output_by_actor(&snac, msg, actor, 0);
2743
2744                            rsp = mastoapi_relationship(&snac, md5);
2745                        }
2746                    }
2747                }
2748                else
2749                if (strcmp(opt, "unfollow") == 0) { /** **/
2750                    if (valid_status(object_get_by_md5(md5, &actor_o))) {
2751                        const char *actor = xs_dict_get(actor_o, "id");
2752
2753                        /* get the following object */
2754                        xs *object = NULL;
2755
2756                        if (valid_status(following_get(&snac, actor, &object))) {
2757                            xs *msg = msg_undo(&snac, xs_dict_get(object, "object"));
2758
2759                            following_del(&snac, actor);
2760
2761                            enqueue_output_by_actor(&snac, msg, actor, 0);
2762
2763                            rsp = mastoapi_relationship(&snac, md5);
2764                        }
2765                    }
2766                }
2767                else
2768                if (strcmp(opt, "block") == 0) { /** **/
2769                    if (valid_status(object_get_by_md5(md5, &actor_o))) {
2770                        const char *actor = xs_dict_get(actor_o, "id");
2771
2772                        mute(&snac, actor);
2773
2774                        rsp = mastoapi_relationship(&snac, md5);
2775                    }
2776                }
2777                else
2778                if (strcmp(opt, "unblock") == 0) { /** **/
2779                    if (valid_status(object_get_by_md5(md5, &actor_o))) {
2780                        const char *actor = xs_dict_get(actor_o, "id");
2781
2782                        unmute(&snac, actor);
2783
2784                        rsp = mastoapi_relationship(&snac, md5);
2785                    }
2786                }
2787            }
2788
2789            if (rsp != NULL) {
2790                *body  = xs_json_dumps(rsp, 4);
2791                *ctype = "application/json";
2792                status = HTTP_STATUS_OK;
2793            }
2794        }
2795        else
2796            status = HTTP_STATUS_UNAUTHORIZED;
2797    }
2798    else
2799    if (xs_startswith(cmd, "/v1/polls")) { /** **/
2800        if (logged_in) {
2801            /* operations on a status */
2802            xs *l = xs_split(cmd, "/");
2803            const char *mid = xs_list_get(l, 3);
2804            const char *op  = xs_list_get(l, 4);
2805
2806            if (!xs_is_null(mid)) {
2807                xs *msg = NULL;
2808                xs *out = NULL;
2809
2810                /* skip the 'fake' part of the id */
2811                mid = MID_TO_MD5(mid);
2812
2813                if (valid_status(timeline_get_by_md5(&snac, mid, &msg))) {
2814                    const char *id   = xs_dict_get(msg, "id");
2815                    const char *atto = get_atto(msg);
2816
2817                    const xs_list *opts = xs_dict_get(msg, "oneOf");
2818                    if (opts == NULL)
2819                        opts = xs_dict_get(msg, "anyOf");
2820
2821                    if (op == NULL) {
2822                    }
2823                    else
2824                    if (strcmp(op, "votes") == 0) {
2825                        const xs_list *choices = xs_dict_get(args, "choices[]");
2826
2827                        if (xs_is_null(choices))
2828                            choices = xs_dict_get(args, "choices");
2829
2830                        if (xs_type(choices) == XSTYPE_LIST) {
2831                            const xs_str *v;
2832
2833                            int c = 0;
2834                            while (xs_list_next(choices, &v, &c)) {
2835                                int io           = atoi(v);
2836                                const xs_dict *o = xs_list_get(opts, io);
2837
2838                                if (o) {
2839                                    const char *name = xs_dict_get(o, "name");
2840
2841                                    xs *msg = msg_note(&snac, "", atto, (char *)id, NULL, 1);
2842                                    msg = xs_dict_append(msg, "name", name);
2843
2844                                    xs *c_msg = msg_create(&snac, msg);
2845                                    enqueue_message(&snac, c_msg);
2846                                    timeline_add(&snac, xs_dict_get(msg, "id"), msg);
2847                                }
2848                            }
2849
2850                            out = mastoapi_poll(&snac, msg);
2851                        }
2852                    }
2853                }
2854
2855                if (out != NULL) {
2856                    *body  = xs_json_dumps(out, 4);
2857                    *ctype = "application/json";
2858                    status = HTTP_STATUS_OK;
2859                }
2860            }
2861        }
2862        else
2863            status = HTTP_STATUS_UNAUTHORIZED;
2864    }
2865    else
2866    if (strcmp(cmd, "/v1/lists") == 0) {
2867        if (logged_in) {
2868            const char *title = xs_dict_get(args, "title");
2869
2870            if (xs_type(title) == XSTYPE_STRING) {
2871                /* add the list */
2872                xs *out = xs_dict_new();
2873                xs *lid = list_maint(&snac, title, 1);
2874
2875                if (!xs_is_null(lid)) {
2876                    out = xs_dict_append(out, "id", lid);
2877                    out = xs_dict_append(out, "title", title);
2878                    out = xs_dict_append(out, "replies_policy", xs_dict_get_def(args, "replies_policy", "list"));
2879                    out = xs_dict_append(out, "exclusive", xs_stock(XSTYPE_FALSE));
2880
2881                    status = HTTP_STATUS_OK;
2882                }
2883                else {
2884                    out = xs_dict_append(out, "error", "cannot create list");
2885                    status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2886                }
2887
2888                *body  = xs_json_dumps(out, 4);
2889                *ctype = "application/json";
2890            }
2891            else
2892                status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2893        }
2894    }
2895    if (xs_startswith(cmd, "/v1/lists/")) { /** list maintenance **/
2896        if (logged_in) {
2897            xs *l = xs_split(cmd, "/");
2898            const char *op = xs_list_get(l, -1);
2899            const char *id = xs_list_get(l, -2);
2900
2901            if (op && id && xs_is_hex(id)) {
2902                if (strcmp(op, "accounts") == 0) {
2903                    const xs_list *accts = xs_dict_get(args, "account_ids[]");
2904
2905                    if (xs_is_null(accts))
2906                        accts = xs_dict_get(args, "account_ids");
2907
2908                    int c = 0;
2909                    const char *v;
2910
2911                    while (xs_list_next(accts, &v, &c)) {
2912                        list_content(&snac, id, v, 1);
2913                    }
2914
2915                    xs *out = xs_dict_new();
2916                    *body   = xs_json_dumps(out, 4);
2917                    *ctype  = "application/json";
2918                    status  = HTTP_STATUS_OK;
2919                }
2920            }
2921        }
2922        else
2923            status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2924    }
2925
2926    /* user cleanup */
2927    if (logged_in)
2928        user_free(&snac);
2929
2930    srv_debug(1, xs_fmt("mastoapi_post_handler %s %d", q_path, status));
2931
2932    return status;
2933}
2934
2935
2936int mastoapi_delete_handler(const xs_dict *req, const char *q_path,
2937                          const char *payload, int p_size,
2938                          char **body, int *b_size, char **ctype)
2939{
2940    (void)p_size;
2941    (void)body;
2942    (void)b_size;
2943    (void)ctype;
2944
2945    if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
2946        return 0;
2947
2948    int status    = HTTP_STATUS_NOT_FOUND;
2949    xs *args      = NULL;
2950    const char *i_ctype = xs_dict_get(req, "content-type");
2951
2952    if (i_ctype && xs_startswith(i_ctype, "application/json")) {
2953        if (!xs_is_null(payload))
2954            args = xs_json_loads(payload);
2955    }
2956    else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
2957    {
2958        // Some apps send form data instead of json so we should cater for those
2959        if (!xs_is_null(payload)) {
2960            args = xs_url_vars(payload);
2961        }
2962    }
2963    else
2964        args = xs_dup(xs_dict_get(req, "p_vars"));
2965
2966    if (args == NULL)
2967        return HTTP_STATUS_BAD_REQUEST;
2968
2969    snac snac = {0};
2970    int logged_in = process_auth_token(&snac, req);
2971
2972    xs *cmd = xs_replace_n(q_path, "/api", "", 1);
2973
2974    if (xs_startswith(cmd, "/v1/push/subscription") || xs_startswith(cmd, "/v2/push/subscription")) { /** **/
2975        // pretend we deleted it, since it doesn't exist anyway
2976        status = HTTP_STATUS_OK;
2977    }
2978    else
2979    if (xs_startswith(cmd, "/v1/lists/")) {
2980        if (logged_in) {
2981            xs *l = xs_split(cmd, "/");
2982            const char *p = xs_list_get(l, -1);
2983
2984            if (p) {
2985                if (strcmp(p, "accounts") == 0) {
2986                    /* delete account from list */
2987                    p = xs_list_get(l, -2);
2988                    const xs_list *accts = xs_dict_get(args, "account_ids[]");
2989
2990                    if (xs_is_null(accts))
2991                        accts = xs_dict_get(args, "account_ids");
2992
2993                    int c = 0;
2994                    const char *v;
2995
2996                    while (xs_list_next(accts, &v, &c)) {
2997                        list_content(&snac, p, v, 2);
2998                    }
2999                }
3000                else {
3001                    /* delete list */
3002                    if (xs_is_hex(p)) {
3003                        list_maint(&snac, p, 2);
3004                    }
3005                }
3006            }
3007
3008            *ctype = "application/json";
3009            status = HTTP_STATUS_OK;
3010        }
3011        else
3012            status = HTTP_STATUS_UNAUTHORIZED;
3013    }
3014
3015    /* user cleanup */
3016    if (logged_in)
3017        user_free(&snac);
3018
3019    srv_debug(1, xs_fmt("mastoapi_delete_handler %s %d", q_path, status));
3020
3021    return status;
3022}
3023
3024
3025int mastoapi_put_handler(const xs_dict *req, const char *q_path,
3026                          const char *payload, int p_size,
3027                          char **body, int *b_size, char **ctype)
3028{
3029    (void)p_size;
3030    (void)b_size;
3031
3032    if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
3033        return 0;
3034
3035    int status    = HTTP_STATUS_NOT_FOUND;
3036    xs *args      = NULL;
3037    const char *i_ctype = xs_dict_get(req, "content-type");
3038
3039    if (i_ctype && xs_startswith(i_ctype, "application/json")) {
3040        if (!xs_is_null(payload))
3041            args = xs_json_loads(payload);
3042    }
3043    else
3044        args = xs_dup(xs_dict_get(req, "p_vars"));
3045
3046    if (args == NULL)
3047        return HTTP_STATUS_BAD_REQUEST;
3048
3049    xs *cmd = xs_replace_n(q_path, "/api", "", 1);
3050
3051    snac snac = {0};
3052    int logged_in = process_auth_token(&snac, req);
3053
3054    if (xs_startswith(cmd, "/v1/media") || xs_startswith(cmd, "/v2/media")) { /** **/
3055        if (logged_in) {
3056            xs *l = xs_split(cmd, "/");
3057            const char *stid = xs_list_get(l, 3);
3058
3059            if (!xs_is_null(stid)) {
3060                const char *desc = xs_dict_get(args, "description");
3061
3062                /* set the image metadata */
3063                static_put_meta(&snac, stid, desc);
3064
3065                /* prepare a response */
3066                xs *rsp = xs_dict_new();
3067                xs *url = xs_fmt("%s/s/%s", snac.actor, stid);
3068
3069                rsp = xs_dict_append(rsp, "id",          stid);
3070                rsp = xs_dict_append(rsp, "type",        "image");
3071                rsp = xs_dict_append(rsp, "url",         url);
3072                rsp = xs_dict_append(rsp, "preview_url", url);
3073                rsp = xs_dict_append(rsp, "remote_url",  url);
3074                rsp = xs_dict_append(rsp, "description", desc);
3075
3076                *body  = xs_json_dumps(rsp, 4);
3077                *ctype = "application/json";
3078                status = HTTP_STATUS_OK;
3079            }
3080        }
3081        else
3082            status = HTTP_STATUS_UNAUTHORIZED;
3083    }
3084    else
3085    if (xs_startswith(cmd, "/v1/statuses")) {
3086        if (logged_in) {
3087            xs *l = xs_split(cmd, "/");
3088            const char *mid = xs_list_get(l, 3);
3089
3090            if (!xs_is_null(mid)) {
3091                const char *md5 = MID_TO_MD5(mid);
3092                xs *rsp = NULL;
3093                xs *msg = NULL;
3094
3095                if (valid_status(timeline_get_by_md5(&snac, md5, &msg))) {
3096                    const char *content = xs_dict_get(args, "status");
3097                    xs *atls = xs_list_new();
3098                    xs *f_content = not_really_markdown(content, &atls, NULL);
3099
3100                    /* replace fields with new content */
3101                    msg = xs_dict_set(msg, "sourceContent", content);
3102                    msg = xs_dict_set(msg, "content", f_content);
3103
3104                    xs *updated = xs_str_utctime(0, ISO_DATE_SPEC);
3105                    msg = xs_dict_set(msg, "updated", updated);
3106
3107                    /* overwrite object, not updating the indexes */
3108                    object_add_ow(xs_dict_get(msg, "id"), msg);
3109
3110                    /* update message */
3111                    xs *c_msg = msg_update(&snac, msg);
3112
3113                    enqueue_message(&snac, c_msg);
3114
3115                    rsp = mastoapi_status(&snac, msg);
3116                }
3117
3118                if (rsp != NULL) {
3119                    *body  = xs_json_dumps(rsp, 4);
3120                    *ctype = "application/json";
3121                    status = HTTP_STATUS_OK;
3122                }
3123            }
3124        }
3125        else
3126            status = HTTP_STATUS_UNAUTHORIZED;
3127    }
3128
3129    /* user cleanup */
3130    if (logged_in)
3131        user_free(&snac);
3132
3133    srv_debug(1, xs_fmt("mastoapi_put_handler %s %d", q_path, status));
3134
3135    return status;
3136}
3137
3138void persist_image(const char *key, const xs_val *data, const char *payload, snac *snac)
3139/* Store header or avatar */
3140{
3141    if (data != NULL) {
3142        if (xs_type(data) == XSTYPE_LIST) {
3143            const char *fn = xs_list_get(data, 0);
3144
3145            if (fn && *fn) {
3146                const char *ext = strrchr(fn, '.');
3147
3148                /* Mona iOS sends always jpg as application/octet-stream with no filename */
3149                if (ext == NULL || strcmp(fn, key) == 0) {
3150                    ext = ".jpg";
3151                }
3152
3153                /* Make sure we have a unique file name, otherwise updated images will not be
3154                 * re-loaded by clients. */
3155                xs *rnd         = random_str();
3156                xs *hash        = xs_md5_hex(rnd, strlen(rnd));
3157                xs *id          = xs_fmt("%s%s", hash, ext);
3158                xs *url         = xs_fmt("%s/s/%s", snac->actor, id);
3159                int fo          = xs_number_get(xs_list_get(data, 1));
3160                int fs          = xs_number_get(xs_list_get(data, 2));
3161
3162                /* store */
3163                static_put(snac, id, payload + fo, fs);
3164
3165                snac->config = xs_dict_set(snac->config, key, url);
3166            }
3167        }
3168    }
3169}
3170
3171int mastoapi_patch_handler(const xs_dict *req, const char *q_path,
3172                          const char *payload, int p_size,
3173                          char **body, int *b_size, char **ctype)
3174/* Handle profile updates */
3175{
3176    (void)p_size;
3177    (void)b_size;
3178
3179    if (!xs_startswith(q_path, "/api/v1/"))
3180        return 0;
3181
3182    int status    = HTTP_STATUS_NOT_FOUND;
3183    xs *args      = NULL;
3184    const char *i_ctype = xs_dict_get(req, "content-type");
3185
3186    if (i_ctype && xs_startswith(i_ctype, "application/json")) {
3187        if (!xs_is_null(payload))
3188            args = xs_json_loads(payload);
3189    }
3190    else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
3191    {
3192        // Some apps send form data instead of json so we should cater for those
3193        if (!xs_is_null(payload)) {
3194            args    = xs_url_vars(payload);
3195        }
3196    }
3197    else
3198        args = xs_dup(xs_dict_get(req, "p_vars"));
3199
3200    if (args == NULL)
3201        return HTTP_STATUS_BAD_REQUEST;
3202
3203    xs *cmd = xs_replace_n(q_path, "/api", "", 1);
3204
3205    snac snac = {0};
3206    int logged_in = process_auth_token(&snac, req);
3207
3208    if (xs_startswith(cmd, "/v1/accounts/update_credentials")) {
3209        /* Update user profile fields */
3210        if (logged_in) {
3211            int c = 0;
3212            const xs_str *k;
3213            const xs_val *v;
3214            const xs_str *field_name = NULL;
3215            xs *new_fields = xs_dict_new();
3216            while (xs_dict_next(args, &k, &v, &c)) {
3217                if (strcmp(k, "display_name") == 0) {
3218                    if (v != NULL)
3219                        snac.config = xs_dict_set(snac.config, "name", v);
3220                }
3221                else
3222                if (strcmp(k, "note") == 0) {
3223                    if (v != NULL)
3224                        snac.config = xs_dict_set(snac.config, "bio", v);
3225                }
3226                else
3227                if (strcmp(k, "bot") == 0) {
3228                    if (v != NULL)
3229                        snac.config = xs_dict_set(snac.config, "bot",
3230                            (strcmp(v, "true") == 0 ||
3231                                strcmp(v, "1") == 0) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
3232                }
3233                else
3234                if (strcmp(k, "source[sensitive]") == 0) {
3235                    if (v != NULL)
3236                        snac.config = xs_dict_set(snac.config, "cw",
3237                            strcmp(v, "true") == 0 ? "open" : "");
3238                }
3239                else
3240                if (strcmp(k, "source[privacy]") == 0) {
3241                    if (v != NULL)
3242                        snac.config = xs_dict_set(snac.config, "private",
3243                            strcmp(v, "private") == 0 ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
3244                }
3245                else
3246                if (strcmp(k, "header") == 0) {
3247                    persist_image("header", v, payload, &snac);
3248                }
3249                else
3250                if (strcmp(k, "avatar") == 0) {
3251                    persist_image("avatar", v, payload, &snac);
3252                }
3253                else
3254                if (xs_between("fields_attributes", k, "[name]")) {
3255                    field_name = strcmp(v, "") != 0 ? v : NULL;
3256                }
3257                else
3258                if (xs_between("fields_attributes", k, "[value]")) {
3259                    if (field_name != NULL) {
3260                        new_fields = xs_dict_set(new_fields, field_name, v);
3261                        snac.config = xs_dict_set(snac.config, "metadata", new_fields);
3262                    }
3263                }
3264                /* we don't have support for the following options, yet
3265                   - discoverable (0/1)
3266                   - locked (0/1)
3267                 */
3268            }
3269
3270            /* Persist profile */
3271            if (user_persist(&snac, 1) == 0)
3272                credentials_get(body, ctype, &status, snac);
3273            else
3274                status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
3275        }
3276        else
3277            status = HTTP_STATUS_UNAUTHORIZED;
3278    }
3279
3280    /* user cleanup */
3281    if (logged_in)
3282        user_free(&snac);
3283
3284    srv_debug(1, xs_fmt("mastoapi_patch_handler %s %d", q_path, status));
3285
3286    return status;
3287}
3288
3289
3290void mastoapi_purge(void)
3291{
3292    xs *spec   = xs_fmt("%s/app/" "*.json", srv_basedir);
3293    xs *files  = xs_glob(spec, 1, 0);
3294    xs_list *p = files;
3295    const xs_str *v;
3296
3297    time_t mt = time(NULL) - 3600;
3298
3299    while (xs_list_iter(&p, &v)) {
3300        xs *cid = xs_replace(v, ".json", "");
3301        xs *fn  = _app_fn(cid);
3302
3303        if (mtime(fn) < mt) {
3304            /* get the app */
3305            xs *app = app_get(cid);
3306
3307            if (app) {
3308                /* old apps with no uid are incomplete cruft */
3309                const char *uid = xs_dict_get(app, "uid");
3310
3311                if (xs_is_null(uid) || *uid == '\0') {
3312                    unlink(fn);
3313                    srv_debug(2, xs_fmt("purged %s", fn));
3314                }
3315            }
3316        }
3317    }
3318}
3319
3320
3321#endif /* #ifndef NO_MASTODON_API */