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