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