2.79 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 *b_id = xs_toupper_i(xs_dup(xs_dict_get(st, "id")));
1138            bst = xs_dict_set(bst, "id", b_id);
1139
1140            xs_free(st);
1141            st = bst;
1142        }
1143        else
1144            xs_free(bst);
1145    }
1146
1147    return st;
1148}
1149
1150
1151xs_dict *mastoapi_relationship(snac *snac, const char *md5)
1152{
1153    xs_dict *rel = NULL;
1154    xs *actor_o  = NULL;
1155
1156    if (valid_status(object_get_by_md5(md5, &actor_o))) {
1157        rel = xs_dict_new();
1158
1159        const char *actor = xs_dict_get(actor_o, "id");
1160
1161        rel = xs_dict_append(rel, "id",                   md5);
1162        rel = xs_dict_append(rel, "following",
1163            following_check(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1164
1165        rel = xs_dict_append(rel, "showing_reblogs",      xs_stock(XSTYPE_TRUE));
1166        rel = xs_dict_append(rel, "notifying",            xs_stock(XSTYPE_FALSE));
1167        rel = xs_dict_append(rel, "followed_by",
1168            follower_check(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1169
1170        rel = xs_dict_append(rel, "blocking",
1171            is_muted(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1172
1173        rel = xs_dict_append(rel, "muting",               xs_stock(XSTYPE_FALSE));
1174        rel = xs_dict_append(rel, "muting_notifications", xs_stock(XSTYPE_FALSE));
1175        rel = xs_dict_append(rel, "requested",            xs_stock(XSTYPE_FALSE));
1176        rel = xs_dict_append(rel, "domain_blocking",      xs_stock(XSTYPE_FALSE));
1177        rel = xs_dict_append(rel, "endorsed",             xs_stock(XSTYPE_FALSE));
1178        rel = xs_dict_append(rel, "note",                 "");
1179    }
1180
1181    return rel;
1182}
1183
1184
1185int process_auth_token(snac *snac, const xs_dict *req)
1186/* processes an authorization token, if there is one */
1187{
1188    int logged_in = 0;
1189    const char *v;
1190
1191    /* if there is an authorization field, try to validate it */
1192    if (!xs_is_null(v = xs_dict_get(req, "authorization")) && xs_startswith(v, "Bearer ")) {
1193        xs *tokid = xs_replace_n(v, "Bearer ", "", 1);
1194        xs *token = token_get(tokid);
1195
1196        if (token != NULL) {
1197            const char *uid = xs_dict_get(token, "uid");
1198
1199            if (!xs_is_null(uid) && user_open(snac, uid)) {
1200                logged_in = 1;
1201
1202                /* this counts as a 'login' */
1203                lastlog_write(snac, "mastoapi");
1204
1205                srv_debug(2, xs_fmt("mastoapi auth: valid token for user '%s'", uid));
1206            }
1207            else
1208                srv_log(xs_fmt("mastoapi auth: corrupted token '%s'", tokid));
1209        }
1210        else
1211            srv_log(xs_fmt("mastoapi auth: invalid token '%s'", tokid));
1212    }
1213
1214    return logged_in;
1215}
1216
1217
1218void credentials_get(char **body, char **ctype, int *status, snac snac)
1219{
1220    xs *acct = xs_dict_new();
1221
1222    const xs_val *bot = xs_dict_get(snac.config, "bot");
1223
1224    acct = xs_dict_append(acct, "id", snac.md5);
1225    acct = xs_dict_append(acct, "username", xs_dict_get(snac.config, "uid"));
1226    acct = xs_dict_append(acct, "acct", xs_dict_get(snac.config, "uid"));
1227    acct = xs_dict_append(acct, "display_name", xs_dict_get(snac.config, "name"));
1228    acct = xs_dict_append(acct, "created_at", xs_dict_get(snac.config, "published"));
1229    acct = xs_dict_append(acct, "last_status_at", xs_dict_get(snac.config, "published"));
1230    acct = xs_dict_append(acct, "note", xs_dict_get(snac.config, "bio"));
1231    acct = xs_dict_append(acct, "url", snac.actor);
1232
1233    acct = xs_dict_append(acct, "locked",
1234        xs_stock(xs_is_true(xs_dict_get(snac.config, "approve_followers")) ? XSTYPE_TRUE : XSTYPE_FALSE));
1235
1236    acct = xs_dict_append(acct, "bot", xs_stock(xs_is_true(bot) ? XSTYPE_TRUE : XSTYPE_FALSE));
1237    acct = xs_dict_append(acct, "emojis", xs_stock(XSTYPE_LIST));
1238
1239    xs *src = xs_json_loads("{\"privacy\":\"public\", \"language\":\"en\","
1240        "\"follow_requests_count\": 0,"
1241        "\"sensitive\":false,\"fields\":[],\"note\":\"\"}");
1242    /* some apps take the note from the source object */
1243    src = xs_dict_set(src, "note", xs_dict_get(snac.config, "bio"));
1244    src = xs_dict_set(src, "privacy", xs_type(xs_dict_get(snac.config, "private")) == XSTYPE_TRUE ? "private" : "public");
1245
1246    const xs_str *cw = xs_dict_get(snac.config, "cw");
1247    src = xs_dict_set(src, "sensitive",
1248        strcmp(cw, "open") == 0 ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1249
1250    src = xs_dict_set(src, "bot", xs_stock(xs_is_true(bot) ? XSTYPE_TRUE : XSTYPE_FALSE));
1251
1252    xs *avatar = NULL;
1253    const char *av = xs_dict_get(snac.config, "avatar");
1254
1255    if (xs_is_null(av) || *av == '\0')
1256        avatar = xs_fmt("%s/susie.png", srv_baseurl);
1257    else
1258        avatar = xs_dup(av);
1259
1260    acct = xs_dict_append(acct, "avatar", avatar);
1261    acct = xs_dict_append(acct, "avatar_static", avatar);
1262
1263    xs *header = NULL;
1264    const char *hd = xs_dict_get(snac.config, "header");
1265
1266    if (!xs_is_null(hd))
1267        header = xs_dup(hd);
1268    else
1269        header = xs_str_new(NULL);
1270
1271    acct = xs_dict_append(acct, "header", header);
1272    acct = xs_dict_append(acct, "header_static", header);
1273
1274    const xs_dict *metadata = xs_dict_get(snac.config, "metadata");
1275    if (xs_type(metadata) == XSTYPE_DICT) {
1276        xs *fields = xs_list_new();
1277        const xs_str *k;
1278        const xs_str *v;
1279
1280        xs_dict *val_links = snac.links;
1281        if (xs_is_null(val_links))
1282            val_links = xs_stock(XSTYPE_DICT);
1283
1284        int c = 0;
1285        while (xs_dict_next(metadata, &k, &v, &c)) {
1286            xs *val_date = NULL;
1287
1288            const xs_number *verified_time = xs_dict_get(val_links, v);
1289            if (xs_type(verified_time) == XSTYPE_NUMBER) {
1290                time_t t = xs_number_get(verified_time);
1291
1292                if (t > 0)
1293                    val_date = xs_str_utctime(t, ISO_DATE_SPEC);
1294            }
1295
1296            xs *d = xs_dict_new();
1297
1298            d = xs_dict_append(d, "name", k);
1299            d = xs_dict_append(d, "value", v);
1300            d = xs_dict_append(d, "verified_at",
1301                               xs_type(val_date) == XSTYPE_STRING && *val_date ? val_date : xs_stock(XSTYPE_NULL));
1302
1303            fields = xs_list_append(fields, d);
1304        }
1305
1306        acct = xs_dict_set(acct, "fields", fields);
1307        /* some apps take the fields from the source object */
1308        src = xs_dict_set(src, "fields", fields);
1309    }
1310
1311    acct = xs_dict_append(acct, "source", src);
1312    acct = xs_dict_append(acct, "followers_count", xs_stock(0));
1313    acct = xs_dict_append(acct, "following_count", xs_stock(0));
1314    acct = xs_dict_append(acct, "statuses_count", xs_stock(0));
1315
1316    /* does this user want to publish their contact metrics? */
1317    if (xs_is_true(xs_dict_get(snac.config, "show_contact_metrics"))) {
1318        int fwing = following_list_len(&snac);
1319        int fwers = follower_list_len(&snac);
1320        xs *ni = xs_number_new(fwing);
1321        xs *ne = xs_number_new(fwers);
1322
1323        acct = xs_dict_append(acct, "followers_count", ne);
1324        acct = xs_dict_append(acct, "following_count", ni);
1325    }
1326
1327    *body = xs_json_dumps(acct, 4);
1328    *ctype = "application/json";
1329    *status = HTTP_STATUS_OK;
1330}
1331
1332
1333xs_list *mastoapi_timeline(snac *user, const xs_dict *args, const char *index_fn)
1334{
1335    xs_list *out = xs_list_new();
1336    FILE *f;
1337    char md5[MD5_HEX_SIZE];
1338
1339    if (dbglevel) {
1340        xs *js = xs_json_dumps(args, 0);
1341        srv_debug(1, xs_fmt("mastoapi_timeline args %s", js));
1342    }
1343
1344    if ((f = fopen(index_fn, "r")) == NULL)
1345        return out;
1346
1347    const char *max_id   = xs_dict_get(args, "max_id");
1348    const char *since_id = xs_dict_get(args, "since_id");
1349    const char *min_id   = xs_dict_get(args, "min_id"); /* unsupported old-to-new navigation */
1350    const char *limit_s  = xs_dict_get(args, "limit");
1351    int (*iterator)(FILE *, char *);
1352    int initial_status = 0;
1353    int ascending = 0;
1354    int limit = 0;
1355    int cnt   = 0;
1356
1357    if (!xs_is_null(limit_s))
1358        limit = atoi(limit_s);
1359
1360    if (limit == 0)
1361        limit = 20;
1362
1363    if (min_id) {
1364        iterator = &index_asc_next;
1365        initial_status = index_asc_first(f, md5, MID_TO_MD5(min_id));
1366        ascending = 1;
1367    }
1368    else {
1369        iterator = &index_desc_next;
1370        initial_status = index_desc_first(f, md5, 0);
1371    }
1372
1373    if (initial_status) {
1374        do {
1375            xs *msg = NULL;
1376
1377            /* only return entries older that max_id */
1378            if (max_id) {
1379                if (strcmp(md5, MID_TO_MD5(max_id)) == 0) {
1380                    max_id = NULL;
1381                    if (ascending)
1382                        break;
1383                }
1384                if (!ascending)
1385                    continue;
1386            }
1387
1388            /* only returns entries newer than since_id */
1389            if (since_id) {
1390                if (strcmp(md5, MID_TO_MD5(since_id)) == 0) {
1391                    if (!ascending)
1392                        break;
1393                    since_id = NULL;
1394                }
1395                if (ascending)
1396                    continue;
1397            }
1398
1399            /* get the entry */
1400            if (user) {
1401                if (!valid_status(timeline_get_by_md5(user, md5, &msg)))
1402                    continue;
1403            }
1404            else {
1405                if (!valid_status(object_get_by_md5(md5, &msg)))
1406                    continue;
1407            }
1408
1409            /* discard non-Notes */
1410            const char *id   = xs_dict_get(msg, "id");
1411            const char *type = xs_dict_get(msg, "type");
1412            if (!xs_match(type, POSTLIKE_OBJECT_TYPE))
1413                continue;
1414
1415            if (id && is_instance_blocked(id))
1416                continue;
1417
1418            const char *from = NULL;
1419            if (strcmp(type, "Page") == 0)
1420                from = xs_dict_get(msg, "audience");
1421
1422            if (from == NULL)
1423                from = get_atto(msg);
1424
1425            if (from == NULL)
1426                continue;
1427
1428            if (user) {
1429                /* is this message from a person we don't follow? */
1430                if (strcmp(from, user->actor) && !following_check(user, from)) {
1431                    /* discard if it was not boosted */
1432                    xs *idx = object_announces(id);
1433
1434                    if (xs_list_len(idx) == 0)
1435                        continue;
1436                }
1437
1438                /* discard notes from muted morons */
1439                if (is_muted(user, from))
1440                    continue;
1441
1442                /* discard hidden notes */
1443                if (is_hidden(user, id))
1444                    continue;
1445            }
1446            else {
1447                /* skip non-public messages */
1448                if (!is_msg_public(msg))
1449                    continue;
1450
1451                /* discard messages from private users */
1452                if (is_msg_from_private_user(msg))
1453                    continue;
1454            }
1455
1456            /* if it has a name and it's not an object that may have one,
1457               it's a poll vote, so discard it */
1458            if (!xs_is_null(xs_dict_get(msg, "name")) && !xs_match(type, "Page|Video|Audio|Event"))
1459                continue;
1460
1461            /* convert the Note into a Mastodon status */
1462            xs *st = mastoapi_status(user, msg);
1463
1464            if (st != NULL) {
1465                if (ascending)
1466                    out = xs_list_insert(out, 0, st);
1467                else
1468                    out = xs_list_append(out, st);
1469                cnt++;
1470            }
1471
1472        } while ((cnt < limit) && (*iterator)(f, md5));
1473    }
1474
1475    int more = index_desc_next(f, md5);
1476
1477    fclose(f);
1478
1479    srv_debug(1, xs_fmt("mastoapi_timeline ret %d%s", cnt, more ? " (+)" : ""));
1480
1481    return out;
1482}
1483
1484
1485xs_str *timeline_link_header(const char *endpoint, xs_list *timeline)
1486/* returns a Link header with paging information */
1487{
1488    xs_str *s = NULL;
1489
1490    if (xs_list_len(timeline) == 0)
1491        return NULL;
1492
1493    const xs_dict *first_st = xs_list_get(timeline, 0);
1494    const xs_dict *last_st  = xs_list_get(timeline, -1);
1495    const char *first_id    = xs_dict_get(first_st, "id");
1496    const char *last_id     = xs_dict_get(last_st, "id");
1497    const char *host        = xs_dict_get(srv_config, "host");
1498    const char *protocol    = xs_dict_get_def(srv_config, "protocol", "https");
1499
1500    s = xs_fmt(
1501        "<%s:/" "/%s%s?max_id=%s>; rel=\"next\", "
1502        "<%s:/" "/%s%s?since_id=%s>; rel=\"prev\"",
1503        protocol, host, endpoint, last_id,
1504        protocol, host, endpoint, first_id);
1505
1506    srv_debug(1, xs_fmt("timeline_link_header %s", s));
1507
1508    return s;
1509}
1510
1511
1512xs_list *mastoapi_account_lists(snac *user, const char *uid)
1513/* returns the list of list an user is in */
1514{
1515    xs_list *out  = xs_list_new();
1516    xs *actor_md5 = NULL;
1517    xs *lol       = list_maint(user, NULL, 0);
1518
1519    if (uid) {
1520        if (!xs_is_hex(uid))
1521            actor_md5 = xs_md5_hex(uid, strlen(uid));
1522        else
1523            actor_md5 = xs_dup(uid);
1524    }
1525
1526    const xs_list *li;
1527    xs_list_foreach(lol, li) {
1528        const char *list_id    = xs_list_get(li, 0);
1529        const char *list_title = xs_list_get(li, 1);
1530        if (uid) {
1531            xs *users = list_content(user, list_id, NULL, 0);
1532            if (xs_list_in(users, actor_md5) == -1)
1533                continue;
1534        }
1535
1536        xs *d = xs_dict_new();
1537
1538        d = xs_dict_append(d, "id", list_id);
1539        d = xs_dict_append(d, "title", list_title);
1540        d = xs_dict_append(d, "replies_policy", "list");
1541        d = xs_dict_append(d, "exclusive", xs_stock(XSTYPE_FALSE));
1542
1543        out = xs_list_append(out, d);
1544    }
1545
1546    return out;
1547}
1548
1549
1550int mastoapi_get_handler(const xs_dict *req, const char *q_path,
1551                         char **body, int *b_size, char **ctype, xs_str **link)
1552{
1553    (void)b_size;
1554
1555    if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
1556        return 0;
1557
1558    int status    = HTTP_STATUS_NOT_FOUND;
1559    const xs_dict *args = xs_dict_get(req, "q_vars");
1560    xs *cmd       = xs_replace_n(q_path, "/api", "", 1);
1561
1562    snac snac1 = {0};
1563    int logged_in = process_auth_token(&snac1, req);
1564
1565    if (strcmp(cmd, "/v1/accounts/verify_credentials") == 0) { /** **/
1566        if (logged_in) {
1567            credentials_get(body, ctype, &status, snac1);
1568        }
1569        else {
1570            status = HTTP_STATUS_UNPROCESSABLE_CONTENT; // (no login)
1571        }
1572    }
1573    else
1574    if (strcmp(cmd, "/v1/accounts/relationships") == 0) { /** **/
1575        /* find if an account is followed, blocked, etc. */
1576        /* the account to get relationships about is in args "id[]" */
1577
1578        if (logged_in) {
1579            xs *res         = xs_list_new();
1580            const char *md5 = xs_dict_get(args, "id[]");
1581
1582            if (xs_is_null(md5))
1583                md5 = xs_dict_get(args, "id");
1584
1585            if (!xs_is_null(md5)) {
1586                if (xs_type(md5) == XSTYPE_LIST)
1587                    md5 = xs_list_get(md5, 0);
1588
1589                xs *rel = mastoapi_relationship(&snac1, md5);
1590
1591                if (rel != NULL)
1592                    res = xs_list_append(res, rel);
1593            }
1594
1595            *body  = xs_json_dumps(res, 4);
1596            *ctype = "application/json";
1597            status = HTTP_STATUS_OK;
1598        }
1599        else
1600            status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
1601    }
1602    else
1603    if (strcmp(cmd, "/v1/accounts/lookup") == 0) { /** **/
1604        /* lookup an account */
1605        const char *acct = xs_dict_get(args, "acct");
1606
1607        if (!xs_is_null(acct)) {
1608            xs *s = xs_strip_chars_i(xs_dup(acct), "@");
1609            xs *l = xs_split_n(s, "@", 1);
1610            const char *uid = xs_list_get(l, 0);
1611            const char *host = xs_list_get(l, 1);
1612
1613            if (uid && (!host || strcmp(host, xs_dict_get(srv_config, "host")) == 0)) {
1614                snac user;
1615
1616                if (user_open(&user, uid)) {
1617                    xs *actor = msg_actor(&user);
1618                    xs *macct = mastoapi_account(NULL, actor);
1619
1620                    *body  = xs_json_dumps(macct, 4);
1621                    *ctype = "application/json";
1622                    status = HTTP_STATUS_OK;
1623
1624                    user_free(&user);
1625                }
1626            }
1627        }
1628    }
1629    else
1630    if (xs_startswith(cmd, "/v1/accounts/")) { /** **/
1631        /* account-related information */
1632        xs *l = xs_split(cmd, "/");
1633        const char *uid = xs_list_get(l, 3);
1634        const char *opt = xs_list_get(l, 4);
1635
1636        if (uid != NULL) {
1637            snac snac2;
1638            xs *out   = NULL;
1639            xs *actor = NULL;
1640
1641            if (logged_in && strcmp(uid, "search") == 0) { /** **/
1642                /* search for accounts starting with q */
1643                const char *aq = xs_dict_get(args, "q");
1644
1645                if (!xs_is_null(aq)) {
1646                    xs *q    = xs_utf8_to_lower(aq);
1647                    out      = xs_list_new();
1648                    xs *wing = following_list(&snac1);
1649                    xs *wers = follower_list(&snac1);
1650                    xs *ulst = user_list();
1651                    xs_list *p;
1652                    const xs_str *v;
1653                    xs_set seen;
1654
1655                    xs_set_init(&seen);
1656
1657                    /* user relations */
1658                    xs_list *lsts[] = { wing, wers, NULL };
1659                    int n;
1660                    for (n = 0; (p = lsts[n]) != NULL; n++) {
1661
1662                        while (xs_list_iter(&p, &v)) {
1663                            /* already seen? skip */
1664                            if (xs_set_add(&seen, v) == 0)
1665                                continue;
1666
1667                            xs *actor = NULL;
1668
1669                            if (valid_status(object_get(v, &actor))) {
1670                                const char *uname = xs_dict_get(actor, "preferredUsername");
1671
1672                                if (!xs_is_null(uname)) {
1673                                    xs *luname = xs_tolower_i(xs_dup(uname));
1674
1675                                    if (xs_startswith(luname, q)) {
1676                                        xs *acct = mastoapi_account(&snac1, actor);
1677
1678                                        out = xs_list_append(out, acct);
1679                                    }
1680                                }
1681                            }
1682                        }
1683                    }
1684
1685                    /* local users */
1686                    p = ulst;
1687                    while (xs_list_iter(&p, &v)) {
1688                        snac user;
1689
1690                        /* skip this same user */
1691                        if (strcmp(v, xs_dict_get(snac1.config, "uid")) == 0)
1692                            continue;
1693
1694                        /* skip if the uid does not start with the query */
1695                        xs *v2 = xs_tolower_i(xs_dup(v));
1696                        if (!xs_startswith(v2, q))
1697                            continue;
1698
1699                        if (user_open(&user, v)) {
1700                            /* if it's not already seen, add it */
1701                            if (xs_set_add(&seen, user.actor) == 1) {
1702                                xs *actor = msg_actor(&user);
1703                                xs *acct  = mastoapi_account(&snac1, actor);
1704
1705                                out = xs_list_append(out, acct);
1706                            }
1707
1708                            user_free(&user);
1709                        }
1710                    }
1711
1712                    xs_set_free(&seen);
1713                }
1714            }
1715            else
1716            /* is it a local user? */
1717            if (user_open(&snac2, uid) || user_open_by_md5(&snac2, uid)) {
1718                if (opt == NULL) {
1719                    /* account information */
1720                    actor = msg_actor(&snac2);
1721                    out   = mastoapi_account(NULL, actor);
1722                }
1723                else
1724                if (strcmp(opt, "statuses") == 0) { /** **/
1725                    /* the public list of posts of a user */
1726                    xs *timeline = timeline_simple_list(&snac2, "public", 0, 256, NULL);
1727                    xs_list *p   = timeline;
1728                    const xs_str *v;
1729
1730                    out = xs_list_new();
1731
1732                    while (xs_list_iter(&p, &v)) {
1733                        xs *msg = NULL;
1734
1735                        if (valid_status(timeline_get_by_md5(&snac2, v, &msg))) {
1736                            /* add only posts by the author */
1737                            if (strcmp(xs_dict_get(msg, "type"), "Note") == 0 &&
1738                                xs_startswith(xs_dict_get(msg, "id"), snac2.actor)) {
1739                                xs *st = mastoapi_status(&snac2, msg);
1740
1741                                if (st)
1742                                    out = xs_list_append(out, st);
1743                            }
1744                        }
1745                    }
1746                }
1747                else
1748                if (strcmp(opt, "featured_tags") == 0) {
1749                    /* snac doesn't have features tags, yet? */
1750                    /* implement empty response so apps like Tokodon don't show an error */
1751                    out = xs_list_new();
1752                }
1753                else
1754                if (strcmp(opt, "following") == 0) {
1755                    xs *wing = following_list(&snac1);
1756                    out = xs_list_new();
1757                    int c = 0;
1758                    const char *v;
1759
1760                    while (xs_list_next(wing, &v, &c)) {
1761                        xs *actor = NULL;
1762
1763                        if (valid_status(object_get(v, &actor))) {
1764                            xs *acct = mastoapi_account(NULL, actor);
1765                            out = xs_list_append(out, acct);
1766                        }
1767                    }
1768                }
1769                else
1770                if (strcmp(opt, "followers") == 0) {
1771                    out = xs_list_new();
1772                }
1773                else
1774                if (strcmp(opt, "lists") == 0) {
1775                    out = mastoapi_account_lists(&snac1, uid);
1776                }
1777
1778                user_free(&snac2);
1779            }
1780            else {
1781                /* try the uid as the md5 of a possibly loaded actor */
1782                if (logged_in && valid_status(object_get_by_md5(uid, &actor))) {
1783                    if (opt == NULL) {
1784                        /* account information */
1785                        out = mastoapi_account(&snac1, actor);
1786                    }
1787                    else
1788                    if (strcmp(opt, "statuses") == 0) {
1789                        /* we don't serve statuses of others; return the empty list */
1790                        out = xs_list_new();
1791                    }
1792                    else
1793                    if (strcmp(opt, "featured_tags") == 0) {
1794                        /* snac doesn't have features tags, yet? */
1795                        /* implement empty response so apps like Tokodon don't show an error */
1796                        out = xs_list_new();
1797                    }
1798                    else
1799                    if (strcmp(opt, "lists") == 0) {
1800                        out = mastoapi_account_lists(&snac1, uid);
1801                    }
1802                }
1803            }
1804
1805            if (out != NULL) {
1806                *body  = xs_json_dumps(out, 4);
1807                *ctype = "application/json";
1808                status = HTTP_STATUS_OK;
1809            }
1810        }
1811    }
1812    else
1813    if (strcmp(cmd, "/v1/timelines/home") == 0) { /** **/
1814        /* the private timeline */
1815        if (logged_in) {
1816            xs *ifn = user_index_fn(&snac1, "private");
1817            xs *out = mastoapi_timeline(&snac1, args, ifn);
1818
1819            *link = timeline_link_header("/api/v1/timelines/home", out);
1820
1821            *body  = xs_json_dumps(out, 4);
1822            *ctype = "application/json";
1823            status = HTTP_STATUS_OK;
1824
1825            srv_debug(2, xs_fmt("mastoapi timeline: returned %d entries", xs_list_len(out)));
1826        }
1827        else {
1828            status = HTTP_STATUS_UNAUTHORIZED;
1829        }
1830    }
1831    else
1832    if (strcmp(cmd, "/v1/timelines/public") == 0) { /** **/
1833        /* the instance public timeline (public timelines for all users) */
1834        xs *ifn = instance_index_fn();
1835        xs *out = mastoapi_timeline(NULL, args, ifn);
1836
1837        *body  = xs_json_dumps(out, 4);
1838        *ctype = "application/json";
1839        status = HTTP_STATUS_OK;
1840    }
1841    else
1842    if (xs_startswith(cmd, "/v1/timelines/tag/")) { /** **/
1843        /* get the tag */
1844        xs *l = xs_split(cmd, "/");
1845        const char *tag = xs_list_get(l, -1);
1846
1847        xs *ifn = tag_fn(tag);
1848        xs *out = mastoapi_timeline(NULL, args, ifn);
1849
1850        *body  = xs_json_dumps(out, 4);
1851        *ctype = "application/json";
1852        status = HTTP_STATUS_OK;
1853    }
1854    else
1855    if (xs_startswith(cmd, "/v1/timelines/list/")) { /** **/
1856        /* get the list id */
1857        if (logged_in) {
1858            xs *l = xs_split(cmd, "/");
1859            const char *list = xs_list_get(l, -1);
1860
1861            xs *ifn = list_timeline_fn(&snac1, list);
1862            xs *out = mastoapi_timeline(NULL, args, ifn);
1863
1864            *body  = xs_json_dumps(out, 4);
1865            *ctype = "application/json";
1866            status = HTTP_STATUS_OK;
1867        }
1868        else
1869            status = HTTP_STATUS_MISDIRECTED_REQUEST;
1870    }
1871    else
1872    if (strcmp(cmd, "/v1/conversations") == 0) { /** **/
1873        /* TBD */
1874        *body  = xs_dup("[]");
1875        *ctype = "application/json";
1876        status = HTTP_STATUS_OK;
1877    }
1878    else
1879    if (strcmp(cmd, "/v1/notifications") == 0) { /** **/
1880        if (logged_in) {
1881            xs *l      = notify_list(&snac1, 0, 64);
1882            xs *out    = xs_list_new();
1883            const char *v;
1884            const xs_list *excl = xs_dict_get(args, "exclude_types[]");
1885            const xs_list *incl = xs_dict_get(args, "types[]");
1886            const char *min_id = xs_dict_get(args, "min_id");
1887            const char *max_id = xs_dict_get(args, "max_id");
1888            const char *limit = xs_dict_get(args, "limit");
1889            int limit_count = 0;
1890            if (xs_is_string(limit)) {
1891                limit_count = atoi(limit);
1892            }
1893
1894            if (dbglevel) {
1895                xs *js = xs_json_dumps(args, 0);
1896                srv_debug(1, xs_fmt("mastoapi_notifications args %s", js));
1897            }
1898
1899            xs_list_foreach(l, v) {
1900                xs *noti = notify_get(&snac1, v);
1901
1902                if (noti == NULL)
1903                    continue;
1904
1905                const char *type  = xs_dict_get(noti, "type");
1906                const char *utype = xs_dict_get(noti, "utype");
1907                const char *objid = xs_dict_get(noti, "objid");
1908                const char *id    = xs_dict_get(noti, "id");
1909                const char *actid = xs_dict_get(noti, "actor");
1910                xs *fid = xs_replace(id, ".", "");
1911                xs *actor = NULL;
1912                xs *entry = NULL;
1913
1914                if (!valid_status(actor_get(actid, &actor)))
1915                    continue;
1916
1917                if (objid != NULL && !valid_status(object_get(objid, &entry)))
1918                    continue;
1919
1920                if (is_hidden(&snac1, objid))
1921                    continue;
1922
1923                if (max_id) {
1924                    if (strcmp(fid, max_id) == 0)
1925                        max_id = NULL;
1926
1927                    continue;
1928                }
1929
1930                if (min_id) {
1931                    if (strcmp(fid, min_id) <= 0) {
1932                        continue;
1933                    }
1934                }
1935
1936                /* convert the type */
1937                if (strcmp(type, "Like") == 0 || strcmp(type, "EmojiReact") == 0)
1938                    type = "favourite";
1939                else
1940                if (strcmp(type, "Announce") == 0)
1941                    type = "reblog";
1942                else
1943                if (strcmp(type, "Follow") == 0)
1944                    type = "follow";
1945                else
1946                if (strcmp(type, "Create") == 0)
1947                    type = "mention";
1948                else
1949                if (strcmp(type, "Update") == 0 && strcmp(utype, "Question") == 0)
1950                    type = "poll";
1951                else
1952                    continue;
1953
1954                /* excluded type? */
1955                if (xs_is_list(excl) && xs_list_in(excl, type) != -1)
1956                    continue;
1957
1958                /* included type? */
1959                if (xs_is_list(incl) && xs_list_in(incl, type) == -1)
1960                    continue;
1961
1962                xs *mn = xs_dict_new();
1963
1964                mn = xs_dict_append(mn, "type", type);
1965
1966                mn = xs_dict_append(mn, "id", fid);
1967
1968                mn = xs_dict_append(mn, "created_at", xs_dict_get(noti, "date"));
1969
1970                xs *acct = mastoapi_account(&snac1, actor);
1971
1972                if (acct == NULL)
1973                    continue;
1974
1975                mn = xs_dict_append(mn, "account", acct);
1976
1977                if (strcmp(type, "follow") != 0 && !xs_is_null(objid)) {
1978                    xs *st = mastoapi_status(&snac1, entry);
1979
1980                    if (st)
1981                        mn = xs_dict_append(mn, "status", st);
1982                }
1983
1984                out = xs_list_append(out, mn);
1985
1986                if (--limit_count <= 0)
1987                    break;
1988            }
1989
1990            srv_debug(1, xs_fmt("mastoapi_notifications count %d", xs_list_len(out)));
1991
1992            *body  = xs_json_dumps(out, 4);
1993            *ctype = "application/json";
1994            status = HTTP_STATUS_OK;
1995        }
1996        else
1997            status = HTTP_STATUS_UNAUTHORIZED;
1998    }
1999    else
2000    if (strcmp(cmd, "/v1/filters") == 0) { /** **/
2001        /* snac will never have filters */
2002        *body  = xs_dup("[]");
2003        *ctype = "application/json";
2004        status = HTTP_STATUS_OK;
2005    }
2006    else
2007    if (strcmp(cmd, "/v2/filters") == 0) { /** **/
2008        /* snac will never have filters
2009         * but still, without a v2 endpoint a short delay is introduced
2010         * in some apps */
2011        *body  = xs_dup("[]");
2012        *ctype = "application/json";
2013        status = HTTP_STATUS_OK;
2014    }
2015    else
2016    if (strcmp(cmd, "/v1/favourites") == 0) { /** **/
2017        /* snac will never support a list of favourites */
2018        *body  = xs_dup("[]");
2019        *ctype = "application/json";
2020        status = HTTP_STATUS_OK;
2021    }
2022    else
2023    if (strcmp(cmd, "/v1/bookmarks") == 0) { /** **/
2024        if (logged_in) {
2025            xs *ifn = bookmark_index_fn(&snac1);
2026            xs *out = mastoapi_timeline(&snac1, args, ifn);
2027
2028            *body  = xs_json_dumps(out, 4);
2029            *ctype = "application/json";
2030            status = HTTP_STATUS_OK;
2031        }
2032        else
2033            status = HTTP_STATUS_UNAUTHORIZED;
2034    }
2035    else
2036    if (strcmp(cmd, "/v1/lists") == 0) { /** list of lists **/
2037        if (logged_in) {
2038            xs *l  = mastoapi_account_lists(&snac1, NULL);
2039
2040            *body  = xs_json_dumps(l, 4);
2041            *ctype = "application/json";
2042            status = HTTP_STATUS_OK;
2043        }
2044        else
2045            status = HTTP_STATUS_UNAUTHORIZED;
2046    }
2047    else
2048    if (xs_startswith(cmd, "/v1/lists/")) { /** list information **/
2049        if (logged_in) {
2050            xs *l = xs_split(cmd, "/");
2051            const char *p = xs_list_get(l, -1);
2052
2053            if (p) {
2054                if (strcmp(p, "accounts") == 0) {
2055                    p = xs_list_get(l, -2);
2056
2057                    if (p && xs_is_hex(p)) {
2058                        xs *actors = list_content(&snac1, p, NULL, 0);
2059                        xs *out = xs_list_new();
2060                        int c = 0;
2061                        const char *v;
2062
2063                        while (xs_list_next(actors, &v, &c)) {
2064                            xs *actor = NULL;
2065
2066                            if (valid_status(object_get_by_md5(v, &actor))) {
2067                                xs *acct = mastoapi_account(&snac1, actor);
2068                                out = xs_list_append(out, acct);
2069                            }
2070                        }
2071
2072                        *body  = xs_json_dumps(out, 4);
2073                        *ctype = "application/json";
2074                        status = HTTP_STATUS_OK;
2075                    }
2076                }
2077                else
2078                if (xs_is_hex(p)) {
2079                    xs *out = xs_list_new();
2080                    xs *lol = list_maint(&snac1, NULL, 0);
2081                    int c = 0;
2082                    const xs_list *v;
2083
2084                    while (xs_list_next(lol, &v, &c)) {
2085                        const char *id = xs_list_get(v, 0);
2086
2087                        if (id && strcmp(id, p) == 0) {
2088                            xs *d = xs_dict_new();
2089
2090                            d = xs_dict_append(d, "id", p);
2091                            d = xs_dict_append(d, "title", xs_list_get(v, 1));
2092                            d = xs_dict_append(d, "replies_policy", "list");
2093                            d = xs_dict_append(d, "exclusive", xs_stock(XSTYPE_FALSE));
2094
2095                            out = xs_dup(d);
2096                            break;
2097                        }
2098                    }
2099
2100                    *body  = xs_json_dumps(out, 4);
2101                    *ctype = "application/json";
2102                    status = HTTP_STATUS_OK;
2103                }
2104            }
2105        }
2106        else
2107            status = HTTP_STATUS_UNAUTHORIZED;
2108    }
2109    else
2110    if (strcmp(cmd, "/v1/scheduled_statuses") == 0) { /** **/
2111        /* snac does not schedule notes */
2112        *body  = xs_dup("[]");
2113        *ctype = "application/json";
2114        status = HTTP_STATUS_OK;
2115    }
2116    else
2117    if (strcmp(cmd, "/v1/follow_requests") == 0) { /** **/
2118        if (logged_in) {
2119            xs *pend = pending_list(&snac1);
2120            xs *resp = xs_list_new();
2121            const char *id;
2122
2123            xs_list_foreach(pend, id) {
2124                xs *actor = NULL;
2125
2126                if (valid_status(object_get(id, &actor))) {
2127                    xs *acct = mastoapi_account(&snac1, actor);
2128
2129                    if (acct)
2130                        resp = xs_list_append(resp, acct);
2131                }
2132            }
2133
2134            *body  = xs_json_dumps(resp, 4);
2135            *ctype = "application/json";
2136            status = HTTP_STATUS_OK;
2137        }
2138    }
2139    else
2140    if (strcmp(cmd, "/v1/announcements") == 0) { /** **/
2141        if (logged_in) {
2142            xs *resp = xs_list_new();
2143            double la = 0.0;
2144            xs *user_la = xs_dup(xs_dict_get(snac1.config, "last_announcement"));
2145            if (user_la != NULL)
2146                la = xs_number_get(user_la);
2147            xs *val_date = xs_str_utctime(la, ISO_DATE_SPEC);
2148
2149            /* contrary to html, we always send the announcement and set the read flag instead */
2150
2151            const t_announcement *annce = announcement(la);
2152            if (annce != NULL && annce->text != NULL) {
2153                xs *an = xs_dict_new();
2154                xs *id = xs_fmt("%d", annce->timestamp);
2155                xs *ct = xs_fmt("<p>%s</p>", annce->text);
2156
2157                an = xs_dict_set(an, "id",           id);
2158                an = xs_dict_set(an, "content",      ct);
2159                an = xs_dict_set(an, "starts_at",    xs_stock(XSTYPE_NULL));
2160                an = xs_dict_set(an, "ends_at",      xs_stock(XSTYPE_NULL));
2161                an = xs_dict_set(an, "all_day",      xs_stock(XSTYPE_TRUE));
2162                an = xs_dict_set(an, "published_at", val_date);
2163                an = xs_dict_set(an, "updated_at",   val_date);
2164                an = xs_dict_set(an, "read",         (annce->timestamp >= la)
2165                    ? xs_stock(XSTYPE_FALSE) : xs_stock(XSTYPE_TRUE));
2166                an = xs_dict_set(an, "mentions",     xs_stock(XSTYPE_LIST));
2167                an = xs_dict_set(an, "statuses",     xs_stock(XSTYPE_LIST));
2168                an = xs_dict_set(an, "tags",         xs_stock(XSTYPE_LIST));
2169                an = xs_dict_set(an, "emojis",       xs_stock(XSTYPE_LIST));
2170                an = xs_dict_set(an, "reactions",    xs_stock(XSTYPE_LIST));
2171                resp = xs_list_append(resp, an);
2172            }
2173
2174            *body  = xs_json_dumps(resp, 4);
2175            *ctype = "application/json";
2176            status = HTTP_STATUS_OK;
2177        }
2178    }
2179    else
2180    if (strcmp(cmd, "/v1/custom_emojis") == 0) { /** **/
2181        xs *emo = emojis();
2182        xs *list = xs_list_new();
2183        int c = 0;
2184        const xs_str *k;
2185        const xs_val *v;
2186        while(xs_dict_next(emo, &k, &v, &c)) {
2187            xs *current = xs_dict_new();
2188            if (xs_startswith(v, "https://") && xs_startswith((xs_mime_by_ext(v)), "image/")) {
2189                /* remove first and last colon */
2190                xs *shortcode = xs_replace(k, ":", "");
2191                current = xs_dict_append(current, "shortcode", shortcode);
2192                current = xs_dict_append(current, "url", v);
2193                current = xs_dict_append(current, "static_url", v);
2194                current = xs_dict_append(current, "visible_in_picker", xs_stock(XSTYPE_TRUE));
2195                list = xs_list_append(list, current);
2196            }
2197        }
2198        *body  = xs_json_dumps(list, 0);
2199        *ctype = "application/json";
2200        status = HTTP_STATUS_OK;
2201    }
2202    else
2203    if (strcmp(cmd, "/v1/instance") == 0) { /** **/
2204        /* returns an instance object */
2205        xs *ins = xs_dict_new();
2206        const char *host  = xs_dict_get(srv_config, "host");
2207        const char *title = xs_dict_get(srv_config, "title");
2208        const char *sdesc = xs_dict_get(srv_config, "short_description");
2209
2210        ins = xs_dict_append(ins, "uri",         host);
2211        ins = xs_dict_append(ins, "domain",      host);
2212        ins = xs_dict_append(ins, "title",       title && *title ? title : host);
2213        ins = xs_dict_append(ins, "version",     "4.0.0 (not true; really " USER_AGENT ")");
2214        ins = xs_dict_append(ins, "source_url",  WHAT_IS_SNAC_URL);
2215        ins = xs_dict_append(ins, "description", host);
2216
2217        ins = xs_dict_append(ins, "short_description", sdesc && *sdesc ? sdesc : host);
2218
2219        xs *susie = xs_fmt("%s/susie.png", srv_baseurl);
2220        ins = xs_dict_append(ins, "thumbnail", susie);
2221
2222        const char *v = xs_dict_get(srv_config, "admin_email");
2223        if (xs_is_null(v) || *v == '\0')
2224            v = "admin@localhost";
2225
2226        ins = xs_dict_append(ins, "email", v);
2227
2228        ins = xs_dict_append(ins, "rules", xs_stock(XSTYPE_LIST));
2229
2230        xs *l1 = xs_list_append(xs_list_new(), "en");
2231        ins = xs_dict_append(ins, "languages", l1);
2232
2233        xs *wss = xs_fmt("wss:/" "/%s", xs_dict_get(srv_config, "host"));
2234        xs *urls = xs_dict_new();
2235        urls = xs_dict_append(urls, "streaming_api", wss);
2236
2237        ins = xs_dict_append(ins, "urls", urls);
2238
2239        xs *d2 = xs_dict_append(xs_dict_new(), "user_count", xs_stock(0));
2240        d2 = xs_dict_append(d2, "status_count", xs_stock(0));
2241        d2 = xs_dict_append(d2, "domain_count", xs_stock(0));
2242        ins = xs_dict_append(ins, "stats", d2);
2243
2244        ins = xs_dict_append(ins, "registrations",     xs_stock(XSTYPE_FALSE));
2245        ins = xs_dict_append(ins, "approval_required", xs_stock(XSTYPE_FALSE));
2246        ins = xs_dict_append(ins, "invites_enabled",   xs_stock(XSTYPE_FALSE));
2247
2248        xs *cfg = xs_dict_new();
2249
2250        {
2251            xs *d11 = xs_json_loads("{\"characters_reserved_per_url\":32,"
2252                "\"max_characters\":100000,\"max_media_attachments\":4}");
2253
2254            const xs_number *max_attachments = xs_dict_get(srv_config, "max_attachments");
2255            if (xs_type(max_attachments) == XSTYPE_NUMBER)
2256                d11 = xs_dict_set(d11, "max_media_attachments", max_attachments);
2257
2258            cfg = xs_dict_append(cfg, "statuses", d11);
2259
2260            xs *d12 = xs_json_loads("{\"max_featured_tags\":0}");
2261            cfg = xs_dict_append(cfg, "accounts", d12);
2262
2263            xs *d13 = xs_json_loads("{\"image_matrix_limit\":33177600,"
2264                        "\"image_size_limit\":16777216,"
2265                        "\"video_frame_rate_limit\":120,"
2266                        "\"video_matrix_limit\":8294400,"
2267                        "\"video_size_limit\":103809024}"
2268            );
2269
2270            {
2271                /* get the supported mime types from the internal list */
2272                const char **p = xs_mime_types;
2273                xs_set mtypes;
2274                xs_set_init(&mtypes);
2275
2276                while (*p) {
2277                    const char *type = p[1];
2278
2279                    if (xs_startswith(type, "image/") ||
2280                        xs_startswith(type, "video/") ||
2281                        xs_startswith(type, "audio/"))
2282                        xs_set_add(&mtypes, type);
2283
2284                    p += 2;
2285                }
2286
2287                xs *l = xs_set_result(&mtypes);
2288                d13 = xs_dict_append(d13, "supported_mime_types", l);
2289            }
2290
2291            cfg = xs_dict_append(cfg, "media_attachments", d13);
2292
2293            xs *d14 = xs_json_loads("{\"max_characters_per_option\":50,"
2294                "\"max_expiration\":2629746,"
2295                "\"max_options\":8,\"min_expiration\":300}");
2296            cfg = xs_dict_append(cfg, "polls", d14);
2297        }
2298
2299        ins = xs_dict_append(ins, "configuration", cfg);
2300
2301        const char *admin_account = xs_dict_get(srv_config, "admin_account");
2302
2303        if (!xs_is_null(admin_account) && *admin_account) {
2304            snac admin;
2305
2306            if (user_open(&admin, admin_account)) {
2307                xs *actor = msg_actor(&admin);
2308                xs *acct  = mastoapi_account(NULL, actor);
2309
2310                ins = xs_dict_append(ins, "contact_account", acct);
2311
2312                user_free(&admin);
2313            }
2314        }
2315
2316        *body  = xs_json_dumps(ins, 4);
2317        *ctype = "application/json";
2318        status = HTTP_STATUS_OK;
2319    }
2320    else
2321    if (strcmp(cmd, "/v1/instance/peers") == 0) { /** **/
2322        /* get the collected inbox list as the instances "this domain is aware of" */
2323        xs *list = inbox_list();
2324        xs *peers = xs_list_new();
2325        const char *inbox;
2326
2327        xs_list_foreach(list, inbox) {
2328            xs *l = xs_split(inbox, "/");
2329            const char *domain = xs_list_get(l, 2);
2330
2331            if (xs_is_string(domain))
2332                peers = xs_list_append(peers, domain);
2333        }
2334
2335        *body  = xs_json_dumps(peers, 4);
2336        *ctype = "application/json";
2337        status = HTTP_STATUS_OK;
2338    }
2339    else
2340    if (strcmp(cmd, "/v1/instance/extended_description") == 0) { /** **/
2341        xs *d = xs_dict_new();
2342        xs *greeting = xs_fmt("%s/greeting.html", srv_basedir);
2343        time_t t = mtime(greeting);
2344        xs *updated_at = xs_str_iso_date(t);
2345        xs *content = xs_replace(snac_blurb, "%host%", xs_dict_get(srv_config, "host"));
2346
2347        d = xs_dict_set(d, "updated_at", updated_at);
2348        d = xs_dict_set(d, "content", content);
2349
2350        *body  = xs_json_dumps(d, 4);
2351        *ctype = "application/json";
2352        status = HTTP_STATUS_OK;
2353    }
2354    else
2355    if (xs_startswith(cmd, "/v1/statuses/")) { /** **/
2356        /* information about a status */
2357        if (logged_in) {
2358            xs *l = xs_split(cmd, "/");
2359            const char *oid = xs_list_get(l, 3);
2360            const char *op = xs_list_get(l, 4);
2361
2362            if (!xs_is_null(oid)) {
2363                xs *msg = NULL;
2364                xs *out = NULL;
2365
2366                /* skip the 'fake' part of the id */
2367                oid = MID_TO_MD5(oid);
2368
2369                xs *id = xs_tolower_i(xs_dup(oid));
2370
2371                if (valid_status(object_get_by_md5(id, &msg))) {
2372                    if (op == NULL) {
2373                        if (!is_muted(&snac1, get_atto(msg))) {
2374                            /* return the status itself */
2375                            out = mastoapi_status(&snac1, msg);
2376                        }
2377                    }
2378                    else
2379                    if (strcmp(op, "context") == 0) { /** **/
2380                        /* return ancestors and children */
2381                        xs *anc = xs_list_new();
2382                        xs *des = xs_list_new();
2383                        xs_list *p;
2384                        const xs_str *v;
2385                        char pid[MD5_HEX_SIZE];
2386
2387                        /* build the [grand]parent list, moving up */
2388                        strncpy(pid, id, sizeof(pid));
2389
2390                        while (object_parent(pid, pid)) {
2391                            xs *m2 = NULL;
2392
2393                            if (valid_status(timeline_get_by_md5(&snac1, pid, &m2))) {
2394                                xs *st = mastoapi_status(&snac1, m2);
2395
2396                                if (st)
2397                                    anc = xs_list_insert(anc, 0, st);
2398                            }
2399                            else
2400                                break;
2401                        }
2402
2403                        /* build the children list */
2404                        xs *children = object_children(xs_dict_get(msg, "id"));
2405                        p = children;
2406
2407                        while (xs_list_iter(&p, &v)) {
2408                            xs *m2 = NULL;
2409
2410                            if (valid_status(timeline_get_by_md5(&snac1, v, &m2))) {
2411                                if (xs_is_null(xs_dict_get(m2, "name"))) {
2412                                    xs *st = mastoapi_status(&snac1, m2);
2413
2414                                    if (st)
2415                                        des = xs_list_append(des, st);
2416                                }
2417                            }
2418                        }
2419
2420                        out = xs_dict_new();
2421                        out = xs_dict_append(out, "ancestors",   anc);
2422                        out = xs_dict_append(out, "descendants", des);
2423                    }
2424                    else
2425                    if (strcmp(op, "reblogged_by") == 0 || /** **/
2426                        strcmp(op, "favourited_by") == 0) { /** **/
2427                        /* return the list of people who liked or boosted this */
2428                        out = xs_list_new();
2429
2430                        xs *l = NULL;
2431
2432                        if (op[0] == 'r')
2433                            l = object_announces(xs_dict_get(msg, "id"));
2434                        else
2435                            l = object_likes(xs_dict_get(msg, "id"));
2436
2437                        xs_list *p = l;
2438                        const xs_str *v;
2439
2440                        while (xs_list_iter(&p, &v)) {
2441                            xs *actor2 = NULL;
2442
2443                            if (valid_status(object_get_by_md5(v, &actor2))) {
2444                                xs *acct2 = mastoapi_account(&snac1, actor2);
2445
2446                                out = xs_list_append(out, acct2);
2447                            }
2448                        }
2449                    }
2450                    else
2451                    if (strcmp(op, "source") == 0) { /** **/
2452                        out = xs_dict_new();
2453
2454                        /* get the mastoapi status id */
2455                        out = xs_dict_append(out, "id", xs_list_get(l, 3));
2456
2457                        out = xs_dict_append(out, "text", xs_dict_get(msg, "sourceContent"));
2458                        out = xs_dict_append(out, "spoiler_text", xs_dict_get(msg, "summary"));
2459                    }
2460                }
2461                else
2462                    srv_debug(1, xs_fmt("mastoapi status: bad id %s", id));
2463
2464                if (out != NULL) {
2465                    *body  = xs_json_dumps(out, 4);
2466                    *ctype = "application/json";
2467                    status = HTTP_STATUS_OK;
2468                }
2469            }
2470        }
2471        else
2472            status = HTTP_STATUS_UNAUTHORIZED;
2473    }
2474    else
2475    if (strcmp(cmd, "/v1/preferences") == 0) { /** **/
2476        *body  = xs_dup("{}");
2477        *ctype = "application/json";
2478        status = HTTP_STATUS_OK;
2479    }
2480    else
2481    if (strcmp(cmd, "/v1/markers") == 0) { /** **/
2482        if (logged_in) {
2483            const xs_list *timeline = xs_dict_get(args, "timeline[]");
2484            xs_str *json = NULL;
2485            if (!xs_is_null(timeline))
2486                json = xs_json_dumps(markers_get(&snac1, timeline), 4);
2487
2488            if (!xs_is_null(json))
2489                *body = json;
2490            else
2491                *body = xs_dup("{}");
2492
2493            *ctype = "application/json";
2494            status = HTTP_STATUS_OK;
2495        }
2496        else
2497            status = HTTP_STATUS_UNAUTHORIZED;
2498    }
2499    else
2500    if (strcmp(cmd, "/v1/followed_tags") == 0) { /** **/
2501        if (logged_in) {
2502            xs *r = xs_list_new();
2503            const xs_list *followed_hashtags = xs_dict_get_def(snac1.config,
2504                        "followed_hashtags", xs_stock(XSTYPE_LIST));
2505            const char *hashtag;
2506
2507            xs_list_foreach(followed_hashtags, hashtag) {
2508                if (*hashtag == '#') {
2509                    xs *d = xs_dict_new();
2510                    xs *s = xs_fmt("%s?t=%s", srv_baseurl, hashtag + 1);
2511
2512                    d = xs_dict_set(d, "name", hashtag + 1);
2513                    d = xs_dict_set(d, "url", s);
2514                    d = xs_dict_set(d, "history", xs_stock(XSTYPE_LIST));
2515
2516                    r = xs_list_append(r, d);
2517                }
2518            }
2519
2520            *body  = xs_json_dumps(r, 4);
2521            *ctype = "application/json";
2522            status = HTTP_STATUS_OK;
2523        }
2524        else
2525            status = HTTP_STATUS_UNAUTHORIZED;
2526    }
2527    else
2528    if (strcmp(cmd, "/v1/blocks") == 0) { /** **/
2529        *body  = xs_dup("[]");
2530        *ctype = "application/json";
2531        status = HTTP_STATUS_OK;
2532    }
2533    else
2534    if (strcmp(cmd, "/v1/mutes") == 0) { /** **/
2535        *body  = xs_dup("[]");
2536        *ctype = "application/json";
2537        status = HTTP_STATUS_OK;
2538    }
2539    else
2540    if (strcmp(cmd, "/v1/trends/tags") == 0) { /** **/
2541        *body  = xs_dup("[]");
2542        *ctype = "application/json";
2543        status = HTTP_STATUS_OK;
2544    }
2545    else
2546    if (strcmp(cmd, "/v1/trends/statuses") == 0) { /** **/
2547        *body  = xs_dup("[]");
2548        *ctype = "application/json";
2549        status = HTTP_STATUS_OK;
2550    }
2551    else
2552    if (strcmp(cmd, "/v2/search") == 0) { /** **/
2553        if (logged_in) {
2554            const char *q      = xs_dict_get(args, "q");
2555            const char *type   = xs_dict_get(args, "type");
2556            const char *offset = xs_dict_get(args, "offset");
2557
2558            xs *acl = xs_list_new();
2559            xs *stl = xs_list_new();
2560            xs *htl = xs_list_new();
2561            xs *res = xs_dict_new();
2562
2563            if (xs_is_null(offset) || strcmp(offset, "0") == 0) {
2564                /* reply something only for offset 0; otherwise,
2565                   apps like Tusky keep asking again and again */
2566                if (xs_startswith(q, "https://")) {
2567                    if (!timeline_here(&snac1, q)) {
2568                        xs *object = NULL;
2569                        int status;
2570
2571                        status = activitypub_request(&snac1, q, &object);
2572                        snac_debug(&snac1, 1, xs_fmt("Request searched URL %s %d", q, status));
2573
2574                        if (valid_status(status)) {
2575                            /* got it; also request the actor */
2576                            const char *attr_to = get_atto(object);
2577                            xs *actor_obj = NULL;
2578
2579                            if (!xs_is_null(attr_to)) {
2580                                status = actor_request(&snac1, attr_to, &actor_obj);
2581
2582                                snac_debug(&snac1, 1, xs_fmt("Request author %s of %s %d", attr_to, q, status));
2583
2584                                if (valid_status(status)) {
2585                                    /* add the actor */
2586                                    actor_add(attr_to, actor_obj);
2587
2588                                    /* add the post to the timeline */
2589                                    timeline_add(&snac1, q, object);
2590                                }
2591                            }
2592                        }
2593                    }
2594                }
2595
2596                if (!xs_is_null(q)) {
2597                    if (xs_is_null(type) || strcmp(type, "accounts") == 0) {
2598                        /* do a webfinger query */
2599                        char *actor = NULL;
2600                        char *user  = NULL;
2601
2602                        if (valid_status(webfinger_request(q, &actor, &user)) && actor) {
2603                            xs *actor_o = NULL;
2604
2605                            if (valid_status(actor_request(&snac1, actor, &actor_o))) {
2606                                xs *acct = mastoapi_account(NULL, actor_o);
2607
2608                                acl = xs_list_append(acl, acct);
2609
2610                                if (!object_here(actor))
2611                                    object_add(actor, actor_o);
2612                            }
2613                        }
2614                    }
2615
2616                    if (xs_is_null(type) || strcmp(type, "hashtags") == 0) {
2617                        /* search this tag */
2618                        xs *tl = tag_search((char *)q, 0, 1);
2619
2620                        if (xs_list_len(tl)) {
2621                            xs *d = xs_dict_new();
2622
2623                            d = xs_dict_append(d, "name", q);
2624                            xs *url = xs_fmt("%s?t=%s", srv_baseurl, q);
2625                            d = xs_dict_append(d, "url", url);
2626                            d = xs_dict_append(d, "history", xs_stock(XSTYPE_LIST));
2627
2628                            htl = xs_list_append(htl, d);
2629                        }
2630                    }
2631
2632                    if (xs_is_null(type) || strcmp(type, "statuses") == 0) {
2633                        int to = 0;
2634                        int cnt = 40;
2635                        xs *tl = content_search(&snac1, q, 1, 0, cnt, 0, &to);
2636                        int c = 0;
2637                        const char *v;
2638
2639                        while (xs_list_next(tl, &v, &c) && --cnt) {
2640                            xs *post = NULL;
2641
2642                            if (!valid_status(timeline_get_by_md5(&snac1, v, &post)))
2643                                continue;
2644
2645                            xs *s = mastoapi_status(&snac1, post);
2646
2647                            if (!xs_is_null(s))
2648                                stl = xs_list_append(stl, s);
2649                        }
2650                    }
2651                }
2652            }
2653
2654            res = xs_dict_append(res, "accounts", acl);
2655            res = xs_dict_append(res, "statuses", stl);
2656            res = xs_dict_append(res, "hashtags", htl);
2657
2658            *body  = xs_json_dumps(res, 4);
2659            *ctype = "application/json";
2660            status = HTTP_STATUS_OK;
2661        }
2662        else
2663            status = HTTP_STATUS_UNAUTHORIZED;
2664    }
2665
2666    /* user cleanup */
2667    if (logged_in)
2668        user_free(&snac1);
2669
2670    srv_debug(1, xs_fmt("mastoapi_get_handler %s %d", q_path, status));
2671
2672    return status;
2673}
2674
2675
2676int mastoapi_post_handler(const xs_dict *req, const char *q_path,
2677                          const char *payload, int p_size,
2678                          char **body, int *b_size, char **ctype)
2679{
2680    (void)p_size;
2681    (void)b_size;
2682
2683    if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
2684        return 0;
2685
2686    int status    = HTTP_STATUS_NOT_FOUND;
2687    xs *args      = NULL;
2688    const char *i_ctype = xs_dict_get(req, "content-type");
2689
2690    if (i_ctype && xs_startswith(i_ctype, "application/json")) {
2691        if (!xs_is_null(payload))
2692            args = xs_json_loads(payload);
2693    }
2694    else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
2695    {
2696        // Some apps send form data instead of json so we should cater for those
2697        if (!xs_is_null(payload)) {
2698            args    = xs_url_vars(payload);
2699        }
2700    }
2701    else
2702        args = xs_dup(xs_dict_get(req, "p_vars"));
2703
2704    if (args == NULL)
2705        return HTTP_STATUS_BAD_REQUEST;
2706
2707    xs *cmd = xs_replace_n(q_path, "/api", "", 1);
2708
2709    snac snac = {0};
2710    int logged_in = process_auth_token(&snac, req);
2711
2712    if (strcmp(cmd, "/v1/apps") == 0) { /** **/
2713        const char *name  = xs_dict_get(args, "client_name");
2714        const char *ruri  = xs_dict_get(args, "redirect_uris");
2715        const char *scope = xs_dict_get(args, "scope");
2716
2717        /* Ice Cubes sends these values as query parameters, so try these */
2718        if (name == NULL && ruri == NULL && scope == NULL) {
2719            args = xs_dup(xs_dict_get(req, "q_vars"));
2720            name  = xs_dict_get(args, "client_name");
2721            ruri  = xs_dict_get(args, "redirect_uris");
2722            scope = xs_dict_get(args, "scope");
2723        }
2724
2725        if (xs_type(ruri) == XSTYPE_LIST)
2726            ruri = xs_dict_get(ruri, 0);
2727
2728        if (name && ruri) {
2729            xs *app  = xs_dict_new();
2730            xs *id   = xs_replace_i(tid(0), ".", "");
2731            xs *csec = random_str();
2732            xs *vkey = random_str();
2733            xs *cid  = NULL;
2734
2735            /* pick a non-existent random cid */
2736            for (;;) {
2737                cid = random_str();
2738                xs *p_app = app_get(cid);
2739
2740                if (p_app == NULL)
2741                    break;
2742
2743                xs_free(cid);
2744            }
2745
2746            app = xs_dict_append(app, "name",          name);
2747            app = xs_dict_append(app, "redirect_uri",  ruri);
2748            app = xs_dict_append(app, "client_id",     cid);
2749            app = xs_dict_append(app, "client_secret", csec);
2750            app = xs_dict_append(app, "vapid_key",     vkey);
2751            app = xs_dict_append(app, "id",            id);
2752
2753            *body  = xs_json_dumps(app, 4);
2754            *ctype = "application/json";
2755            status = HTTP_STATUS_OK;
2756
2757            app = xs_dict_append(app, "code", "");
2758
2759            if (scope)
2760                app = xs_dict_append(app, "scope", scope);
2761
2762            app_add(cid, app);
2763
2764            srv_debug(1, xs_fmt("mastoapi apps: new app %s", cid));
2765        }
2766    }
2767    else
2768    if (strcmp(cmd, "/v1/statuses") == 0) { /** **/
2769        if (logged_in) {
2770            /* post a new Note */
2771            const char *content    = xs_dict_get(args, "status");
2772            const char *mid        = xs_dict_get(args, "in_reply_to_id");
2773            const char *visibility = xs_dict_get(args, "visibility");
2774            const char *summary    = xs_dict_get(args, "spoiler_text");
2775            const char *media_ids  = xs_dict_get(args, "media_ids");
2776            const char *language   = xs_dict_get(args, "language");
2777
2778            if (xs_is_null(media_ids))
2779                media_ids = xs_dict_get(args, "media_ids[]");
2780
2781            if (xs_is_null(media_ids))
2782                media_ids = xs_dict_get(args, "media_ids");
2783
2784            if (xs_is_null(visibility))
2785                visibility = "public";
2786
2787            xs *attach_list = xs_list_new();
2788            xs *irt         = NULL;
2789
2790            /* is it a reply? */
2791            if (mid != NULL) {
2792                xs *r_msg = NULL;
2793                const char *md5 = MID_TO_MD5(mid);
2794
2795                if (valid_status(object_get_by_md5(md5, &r_msg)))
2796                    irt = xs_dup(xs_dict_get(r_msg, "id"));
2797            }
2798
2799            /* does it have attachments? */
2800            if (!xs_is_null(media_ids)) {
2801                xs *mi = NULL;
2802
2803                if (xs_type(media_ids) == XSTYPE_LIST)
2804                    mi = xs_dup(media_ids);
2805                else {
2806                    mi = xs_list_new();
2807                    mi = xs_list_append(mi, media_ids);
2808                }
2809
2810                xs_list *p = mi;
2811                const xs_str *v;
2812
2813                while (xs_list_iter(&p, &v)) {
2814                    xs *l    = xs_list_new();
2815                    xs *url  = xs_fmt("%s/s/%s", snac.actor, v);
2816                    xs *desc = static_get_meta(&snac, v);
2817
2818                    l = xs_list_append(l, url);
2819                    l = xs_list_append(l, desc);
2820
2821                    attach_list = xs_list_append(attach_list, l);
2822                }
2823            }
2824
2825            /* prepare the message */
2826            int scope = 1;
2827            if (strcmp(visibility, "unlisted") == 0)
2828                scope = 2;
2829            else
2830            if (strcmp(visibility, "public") == 0)
2831                scope = 0;
2832
2833            xs *msg = msg_note(&snac, content, NULL, irt, attach_list, scope, language, NULL);
2834
2835            if (!xs_is_null(summary) && *summary) {
2836                msg = xs_dict_set(msg, "sensitive", xs_stock(XSTYPE_TRUE));
2837                msg = xs_dict_set(msg, "summary",   summary);
2838            }
2839
2840            /* scheduled? */
2841            const char *scheduled_at = xs_dict_get(args, "scheduled_at");
2842
2843            if (xs_is_string(scheduled_at) && *scheduled_at) {
2844                msg = xs_dict_set(msg, "published", scheduled_at);
2845
2846                schedule_add(&snac, xs_dict_get(msg, "id"), msg);
2847            }
2848            else {
2849                /* store */
2850                timeline_add(&snac, xs_dict_get(msg, "id"), msg);
2851
2852                /* 'Create' message */
2853                xs *c_msg = msg_create(&snac, msg);
2854                enqueue_message(&snac, c_msg);
2855
2856                timeline_touch(&snac);
2857            }
2858
2859            /* convert to a mastodon status as a response code */
2860            xs *st = mastoapi_status(&snac, msg);
2861
2862            *body  = xs_json_dumps(st, 4);
2863            *ctype = "application/json";
2864            status = HTTP_STATUS_OK;
2865        }
2866        else
2867            status = HTTP_STATUS_UNAUTHORIZED;
2868    }
2869    else
2870    if (xs_startswith(cmd, "/v1/statuses")) { /** **/
2871        if (logged_in) {
2872            /* operations on a status */
2873            xs *l = xs_split(cmd, "/");
2874            const char *mid = xs_list_get(l, 3);
2875            const char *op  = xs_list_get(l, 4);
2876
2877            if (!xs_is_null(mid)) {
2878                xs *msg = NULL;
2879                xs *out = NULL;
2880
2881                /* skip the 'fake' part of the id */
2882                mid = MID_TO_MD5(mid);
2883
2884                if (valid_status(timeline_get_by_md5(&snac, mid, &msg))) {
2885                    const char *id = xs_dict_get(msg, "id");
2886
2887                    if (op == NULL) {
2888                        /* no operation (?) */
2889                    }
2890                    else
2891                    if (strcmp(op, "favourite") == 0) { /** **/
2892                        xs *n_msg = msg_admiration(&snac, id, "Like");
2893
2894                        if (n_msg != NULL) {
2895                            enqueue_message(&snac, n_msg);
2896                            timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 1);
2897
2898                            out = mastoapi_status(&snac, msg);
2899                        }
2900                    }
2901                    else
2902                    if (strcmp(op, "unfavourite") == 0) { /** **/
2903                        xs *n_msg = msg_repulsion(&snac, id, "Like");
2904
2905                        if (n_msg != NULL) {
2906                            enqueue_message(&snac, n_msg);
2907
2908                            out = mastoapi_status(&snac, msg);
2909                        }
2910                    }
2911                    else
2912                    if (strcmp(op, "reblog") == 0) { /** **/
2913                        xs *n_msg = msg_admiration(&snac, id, "Announce");
2914
2915                        if (n_msg != NULL) {
2916                            enqueue_message(&snac, n_msg);
2917                            timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 0);
2918
2919                            out = mastoapi_status(&snac, msg);
2920                        }
2921                    }
2922                    else
2923                    if (strcmp(op, "unreblog") == 0) { /** **/
2924                        xs *n_msg = msg_repulsion(&snac, id, "Announce");
2925
2926                        if (n_msg != NULL) {
2927                            enqueue_message(&snac, n_msg);
2928
2929                            out = mastoapi_status(&snac, msg);
2930                        }
2931                    }
2932                    else
2933                    if (strcmp(op, "bookmark") == 0) { /** **/
2934                        /* bookmark this message */
2935                        if (bookmark(&snac, id) == 0)
2936                            out = mastoapi_status(&snac, msg);
2937                        else
2938                            status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2939                    }
2940                    else
2941                    if (strcmp(op, "unbookmark") == 0) { /** **/
2942                        /* unbookmark this message */
2943                        unbookmark(&snac, id);
2944                        out = mastoapi_status(&snac, msg);
2945                    }
2946                    else
2947                    if (strcmp(op, "pin") == 0) { /** **/
2948                        /* pin this message */
2949                        if (pin(&snac, id) == 0)
2950                            out = mastoapi_status(&snac, msg);
2951                        else
2952                            status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2953                    }
2954                    else
2955                    if (strcmp(op, "unpin") == 0) { /** **/
2956                        /* unpin this message */
2957                        unpin(&snac, id);
2958                        out = mastoapi_status(&snac, msg);
2959                    }
2960                    else
2961                    if (strcmp(op, "mute") == 0) { /** **/
2962                        /* Mastodon's mute is snac's hide */
2963                    }
2964                    else
2965                    if (strcmp(op, "unmute") == 0) { /** **/
2966                        /* Mastodon's unmute is snac's unhide */
2967                    }
2968                }
2969
2970                if (out != NULL) {
2971                    *body  = xs_json_dumps(out, 4);
2972                    *ctype = "application/json";
2973                    status = HTTP_STATUS_OK;
2974                }
2975            }
2976        }
2977        else
2978            status = HTTP_STATUS_UNAUTHORIZED;
2979    }
2980    else
2981    if (strcmp(cmd, "/v1/notifications/clear") == 0) { /** **/
2982        if (logged_in) {
2983            notify_clear(&snac);
2984            timeline_touch(&snac);
2985
2986            *body  = xs_dup("{}");
2987            *ctype = "application/json";
2988            status = HTTP_STATUS_OK;
2989        }
2990        else
2991            status = HTTP_STATUS_UNAUTHORIZED;
2992    }
2993    else
2994    if (strcmp(cmd, "/v1/push/subscription") == 0) { /** **/
2995        /* I don't know what I'm doing */
2996        if (logged_in) {
2997            const char *v;
2998
2999            xs *wpush = xs_dict_new();
3000
3001            wpush = xs_dict_append(wpush, "id", "1");
3002
3003            v = xs_dict_get(args, "data");
3004            v = xs_dict_get(v, "alerts");
3005            wpush = xs_dict_append(wpush, "alerts", v);
3006
3007            v = xs_dict_get(args, "subscription");
3008            v = xs_dict_get(v, "endpoint");
3009            wpush = xs_dict_append(wpush, "endpoint", v);
3010
3011            xs *server_key = random_str();
3012            wpush = xs_dict_append(wpush, "server_key", server_key);
3013
3014            *body  = xs_json_dumps(wpush, 4);
3015            *ctype = "application/json";
3016            status = HTTP_STATUS_OK;
3017        }
3018        else
3019            status = HTTP_STATUS_UNAUTHORIZED;
3020    }
3021    else
3022    if (strcmp(cmd, "/v1/media") == 0 || strcmp(cmd, "/v2/media") == 0) { /** **/
3023        if (logged_in) {
3024            const xs_list *file = xs_dict_get(args, "file");
3025            const char *desc    = xs_dict_get(args, "description");
3026
3027            if (xs_is_null(desc))
3028                desc = "";
3029
3030            status = HTTP_STATUS_BAD_REQUEST;
3031
3032            if (xs_type(file) == XSTYPE_LIST) {
3033                const char *fn = xs_list_get(file, 0);
3034
3035                if (*fn != '\0') {
3036                    char *ext = strrchr(fn, '.');
3037                    char rnd[32];
3038                    xs_rnd_buf(rnd, sizeof(rnd));
3039                    xs *hash  = xs_md5_hex(rnd, sizeof(rnd));
3040                    xs *id    = xs_fmt("post-%s%s", hash, ext ? ext : "");
3041                    xs *url   = xs_fmt("%s/s/%s", snac.actor, id);
3042                    int fo    = xs_number_get(xs_list_get(file, 1));
3043                    int fs    = xs_number_get(xs_list_get(file, 2));
3044
3045                    /* store */
3046                    static_put(&snac, id, payload + fo, fs);
3047                    static_put_meta(&snac, id, desc);
3048
3049                    /* prepare a response */
3050                    xs *rsp = xs_dict_new();
3051
3052                    rsp = xs_dict_append(rsp, "id",          id);
3053                    rsp = xs_dict_append(rsp, "type",        "image");
3054                    rsp = xs_dict_append(rsp, "url",         url);
3055                    rsp = xs_dict_append(rsp, "preview_url", url);
3056                    rsp = xs_dict_append(rsp, "remote_url",  url);
3057                    rsp = xs_dict_append(rsp, "description", desc);
3058
3059                    *body  = xs_json_dumps(rsp, 4);
3060                    *ctype = "application/json";
3061                    status = HTTP_STATUS_OK;
3062                }
3063            }
3064        }
3065        else
3066            status = HTTP_STATUS_UNAUTHORIZED;
3067    }
3068    else
3069    if (xs_startswith(cmd, "/v1/accounts")) { /** **/
3070        if (logged_in) {
3071            /* account-related information */
3072            xs *l = xs_split(cmd, "/");
3073            const char *md5 = xs_list_get(l, 3);
3074            const char *opt = xs_list_get(l, 4);
3075            xs *rsp = NULL;
3076
3077            if (!xs_is_null(md5) && *md5) {
3078                xs *actor_o = NULL;
3079
3080                if (xs_is_null(opt)) {
3081                    /* ? */
3082                }
3083                else
3084                if (strcmp(opt, "follow") == 0) { /** **/
3085                    if (valid_status(object_get_by_md5(md5, &actor_o))) {
3086                        const char *actor = xs_dict_get(actor_o, "id");
3087
3088                        xs *msg = msg_follow(&snac, actor);
3089
3090                        if (msg != NULL) {
3091                            /* reload the actor from the message, in may be different */
3092                            actor = xs_dict_get(msg, "object");
3093
3094                            following_add(&snac, actor, msg);
3095
3096                            enqueue_output_by_actor(&snac, msg, actor, 0);
3097
3098                            rsp = mastoapi_relationship(&snac, md5);
3099                        }
3100                    }
3101                }
3102                else
3103                if (strcmp(opt, "unfollow") == 0) { /** **/
3104                    if (valid_status(object_get_by_md5(md5, &actor_o))) {
3105                        const char *actor = xs_dict_get(actor_o, "id");
3106
3107                        /* get the following object */
3108                        xs *object = NULL;
3109
3110                        if (valid_status(following_get(&snac, actor, &object))) {
3111                            xs *msg = msg_undo(&snac, xs_dict_get(object, "object"));
3112
3113                            following_del(&snac, actor);
3114
3115                            enqueue_output_by_actor(&snac, msg, actor, 0);
3116
3117                            rsp = mastoapi_relationship(&snac, md5);
3118                        }
3119                    }
3120                }
3121                else
3122                if (strcmp(opt, "block") == 0) { /** **/
3123                    if (valid_status(object_get_by_md5(md5, &actor_o))) {
3124                        const char *actor = xs_dict_get(actor_o, "id");
3125
3126                        mute(&snac, actor);
3127
3128                        rsp = mastoapi_relationship(&snac, md5);
3129                    }
3130                }
3131                else
3132                if (strcmp(opt, "unblock") == 0) { /** **/
3133                    if (valid_status(object_get_by_md5(md5, &actor_o))) {
3134                        const char *actor = xs_dict_get(actor_o, "id");
3135
3136                        unmute(&snac, actor);
3137
3138                        rsp = mastoapi_relationship(&snac, md5);
3139                    }
3140                }
3141            }
3142
3143            if (rsp != NULL) {
3144                *body  = xs_json_dumps(rsp, 4);
3145                *ctype = "application/json";
3146                status = HTTP_STATUS_OK;
3147            }
3148        }
3149        else
3150            status = HTTP_STATUS_UNAUTHORIZED;
3151    }
3152    else
3153    if (xs_startswith(cmd, "/v1/polls")) { /** **/
3154        if (logged_in) {
3155            /* operations on a status */
3156            xs *l = xs_split(cmd, "/");
3157            const char *mid = xs_list_get(l, 3);
3158            const char *op  = xs_list_get(l, 4);
3159
3160            if (!xs_is_null(mid)) {
3161                xs *msg = NULL;
3162                xs *out = NULL;
3163
3164                /* skip the 'fake' part of the id */
3165                mid = MID_TO_MD5(mid);
3166
3167                if (valid_status(timeline_get_by_md5(&snac, mid, &msg))) {
3168                    const char *id   = xs_dict_get(msg, "id");
3169                    const char *atto = get_atto(msg);
3170
3171                    const xs_list *opts = xs_dict_get(msg, "oneOf");
3172                    if (opts == NULL)
3173                        opts = xs_dict_get(msg, "anyOf");
3174
3175                    if (op == NULL) {
3176                    }
3177                    else
3178                    if (strcmp(op, "votes") == 0) {
3179                        const xs_list *choices = xs_dict_get(args, "choices[]");
3180
3181                        if (xs_is_null(choices))
3182                            choices = xs_dict_get(args, "choices");
3183
3184                        if (xs_type(choices) == XSTYPE_LIST) {
3185                            const xs_str *v;
3186
3187                            int c = 0;
3188                            while (xs_list_next(choices, &v, &c)) {
3189                                int io           = atoi(v);
3190                                const xs_dict *o = xs_list_get(opts, io);
3191
3192                                if (o) {
3193                                    const char *name = xs_dict_get(o, "name");
3194
3195                                    xs *msg = msg_note(&snac, "", atto, (char *)id, NULL, 1, NULL, NULL);
3196                                    msg = xs_dict_append(msg, "name", name);
3197
3198                                    xs *c_msg = msg_create(&snac, msg);
3199                                    enqueue_message(&snac, c_msg);
3200                                    timeline_add(&snac, xs_dict_get(msg, "id"), msg);
3201                                }
3202                            }
3203
3204                            out = mastoapi_poll(&snac, msg);
3205                        }
3206                    }
3207                }
3208
3209                if (out != NULL) {
3210                    *body  = xs_json_dumps(out, 4);
3211                    *ctype = "application/json";
3212                    status = HTTP_STATUS_OK;
3213                }
3214            }
3215        }
3216        else
3217            status = HTTP_STATUS_UNAUTHORIZED;
3218    }
3219    else
3220    if (strcmp(cmd, "/v1/lists") == 0) {
3221        if (logged_in) {
3222            const char *title = xs_dict_get(args, "title");
3223
3224            if (xs_type(title) == XSTYPE_STRING) {
3225                /* add the list */
3226                xs *out = xs_dict_new();
3227                xs *lid = list_maint(&snac, title, 1);
3228
3229                if (!xs_is_null(lid)) {
3230                    out = xs_dict_append(out, "id", lid);
3231                    out = xs_dict_append(out, "title", title);
3232                    out = xs_dict_append(out, "replies_policy", xs_dict_get_def(args, "replies_policy", "list"));
3233                    out = xs_dict_append(out, "exclusive", xs_stock(XSTYPE_FALSE));
3234
3235                    status = HTTP_STATUS_OK;
3236                }
3237                else {
3238                    out = xs_dict_append(out, "error", "cannot create list");
3239                    status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
3240                }
3241
3242                *body  = xs_json_dumps(out, 4);
3243                *ctype = "application/json";
3244            }
3245            else
3246                status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
3247        }
3248    }
3249    else
3250    if (xs_startswith(cmd, "/v1/lists/")) { /** list maintenance **/
3251        if (logged_in) {
3252            xs *l = xs_split(cmd, "/");
3253            const char *op = xs_list_get(l, -1);
3254            const char *id = xs_list_get(l, -2);
3255
3256            if (op && id && xs_is_hex(id)) {
3257                if (strcmp(op, "accounts") == 0) {
3258                    const xs_list *accts = xs_dict_get(args, "account_ids[]");
3259
3260                    if (xs_is_null(accts))
3261                        accts = xs_dict_get(args, "account_ids");
3262
3263                    int c = 0;
3264                    const char *v;
3265
3266                    while (xs_list_next(accts, &v, &c)) {
3267                        list_content(&snac, id, v, 1);
3268                    }
3269
3270                    xs *out = xs_dict_new();
3271                    *body   = xs_json_dumps(out, 4);
3272                    *ctype  = "application/json";
3273                    status  = HTTP_STATUS_OK;
3274                }
3275            }
3276        }
3277    }
3278    else if (strcmp(cmd, "/v1/markers") == 0) { /** **/
3279        xs_str *json = NULL;
3280        if (logged_in) {
3281            const xs_str *home_marker = xs_dict_get(args, "home[last_read_id]");
3282            if (xs_is_null(home_marker)) {
3283                const xs_dict *home = xs_dict_get(args, "home");
3284                if (!xs_is_null(home))
3285                    home_marker = xs_dict_get(home, "last_read_id");
3286            }
3287
3288            const xs_str *notify_marker = xs_dict_get(args, "notifications[last_read_id]");
3289            if (xs_is_null(notify_marker)) {
3290                const xs_dict *notify = xs_dict_get(args, "notifications");
3291                if (!xs_is_null(notify))
3292                    notify_marker = xs_dict_get(notify, "last_read_id");
3293            }
3294            json = xs_json_dumps(markers_set(&snac, home_marker, notify_marker), 4);
3295        }
3296        if (!xs_is_null(json))
3297            *body = json;
3298        else
3299            *body = xs_dup("{}");
3300
3301        *ctype = "application/json";
3302        status = HTTP_STATUS_OK;
3303    }
3304    else
3305    if (xs_startswith(cmd, "/v1/follow_requests")) { /** **/
3306        if (logged_in) {
3307            /* "authorize" or "reject" */
3308            xs *rel = NULL;
3309            xs *l = xs_split(cmd, "/");
3310            const char *md5 = xs_list_get(l, -2);
3311            const char *s_cmd = xs_list_get(l, -1);
3312
3313            if (xs_is_string(md5) && xs_is_string(s_cmd)) {
3314                xs *actor = NULL;
3315
3316                if (valid_status(object_get_by_md5(md5, &actor))) {
3317                    const char *actor_id = xs_dict_get(actor, "id");
3318
3319                    if (strcmp(s_cmd, "authorize") == 0) {
3320                        xs *fwreq = pending_get(&snac, actor_id);
3321
3322                        if (fwreq != NULL) {
3323                            xs *reply = msg_accept(&snac, fwreq, actor_id);
3324
3325                            enqueue_message(&snac, reply);
3326
3327                            if (xs_is_null(xs_dict_get(fwreq, "published"))) {
3328                                xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
3329                                fwreq = xs_dict_set(fwreq, "published", date);
3330                            }
3331
3332                            timeline_add(&snac, xs_dict_get(fwreq, "id"), fwreq);
3333
3334                            follower_add(&snac, actor_id);
3335
3336                            pending_del(&snac, actor_id);
3337                            rel = mastoapi_relationship(&snac, md5);
3338                        }
3339                    }
3340                    else
3341                    if (strcmp(s_cmd, "reject") == 0) {
3342                        pending_del(&snac, actor_id);
3343                        rel = mastoapi_relationship(&snac, md5);
3344                    }
3345                }
3346            }
3347
3348            if (rel != NULL) {
3349                *body = xs_json_dumps(rel, 4);
3350                *ctype = "application/json";
3351                status = HTTP_STATUS_OK;
3352            }
3353        }
3354    }
3355    else
3356    if (xs_startswith(cmd, "/v1/tags/")) { /** **/
3357        if (logged_in) {
3358            xs *l = xs_split(cmd, "/");
3359            const char *i_tag = xs_list_get(l, 3);
3360            const char *cmd = xs_list_get(l, 4);
3361
3362            status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
3363
3364            if (xs_is_string(i_tag) && xs_is_string(cmd)) {
3365                int ok = 0;
3366
3367                xs *tag = xs_fmt("#%s", i_tag);
3368                xs *followed_hashtags = xs_dup(xs_dict_get_def(snac.config,
3369                                "followed_hashtags", xs_stock(XSTYPE_LIST)));
3370
3371                if (strcmp(cmd, "follow") == 0) {
3372                    followed_hashtags = xs_list_append(followed_hashtags, tag);
3373                    ok = 1;
3374                }
3375                else
3376                if (strcmp(cmd, "unfollow") == 0) {
3377                    int off = xs_list_in(followed_hashtags, tag);
3378
3379                    if (off != -1)
3380                        followed_hashtags = xs_list_del(followed_hashtags, off);
3381
3382                    ok = 1;
3383                }
3384
3385                if (ok) {
3386                    /* update */
3387                    xs_dict_set(snac.config, "followed_hashtags", followed_hashtags);
3388                    user_persist(&snac, 0);
3389
3390                    xs *d = xs_dict_new();
3391                    xs *s = xs_fmt("%s?t=%s", srv_baseurl, i_tag);
3392                    d = xs_dict_set(d, "name", i_tag);
3393                    d = xs_dict_set(d, "url", s);
3394                    d = xs_dict_set(d, "history", xs_stock(XSTYPE_LIST));
3395
3396                    *body = xs_json_dumps(d, 4);
3397                    *ctype = "application/json";
3398                    status = HTTP_STATUS_OK;
3399                }
3400            }
3401        }
3402    }
3403    else
3404        status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
3405
3406    /* user cleanup */
3407    if (logged_in)
3408        user_free(&snac);
3409
3410    srv_debug(1, xs_fmt("mastoapi_post_handler %s %d", q_path, status));
3411
3412    return status;
3413}
3414
3415
3416int mastoapi_delete_handler(const xs_dict *req, const char *q_path,
3417                          const char *payload, int p_size,
3418                          char **body, int *b_size, char **ctype)
3419{
3420    (void)p_size;
3421    (void)body;
3422    (void)b_size;
3423    (void)ctype;
3424
3425    if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
3426        return 0;
3427
3428    int status    = HTTP_STATUS_NOT_FOUND;
3429    xs *args      = NULL;
3430    const char *i_ctype = xs_dict_get(req, "content-type");
3431
3432    if (i_ctype && xs_startswith(i_ctype, "application/json")) {
3433        if (!xs_is_null(payload))
3434            args = xs_json_loads(payload);
3435    }
3436    else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
3437    {
3438        // Some apps send form data instead of json so we should cater for those
3439        if (!xs_is_null(payload)) {
3440            args = xs_url_vars(payload);
3441        }
3442    }
3443    else
3444        args = xs_dup(xs_dict_get(req, "p_vars"));
3445
3446    if (args == NULL)
3447        return HTTP_STATUS_BAD_REQUEST;
3448
3449    snac snac = {0};
3450    int logged_in = process_auth_token(&snac, req);
3451
3452    xs *cmd = xs_replace_n(q_path, "/api", "", 1);
3453
3454    if (xs_startswith(cmd, "/v1/push/subscription") || xs_startswith(cmd, "/v2/push/subscription")) { /** **/
3455        // pretend we deleted it, since it doesn't exist anyway
3456        status = HTTP_STATUS_OK;
3457    }
3458    else
3459    if (xs_startswith(cmd, "/v1/lists/")) {
3460        if (logged_in) {
3461            xs *l = xs_split(cmd, "/");
3462            const char *p = xs_list_get(l, -1);
3463
3464            if (p) {
3465                if (strcmp(p, "accounts") == 0) {
3466                    /* delete account from list */
3467                    p = xs_list_get(l, -2);
3468                    const xs_list *accts = xs_dict_get(args, "account_ids[]");
3469
3470                    if (xs_is_null(accts))
3471                        accts = xs_dict_get(args, "account_ids");
3472
3473                    int c = 0;
3474                    const char *v;
3475
3476                    while (xs_list_next(accts, &v, &c)) {
3477                        list_content(&snac, p, v, 2);
3478                    }
3479                }
3480                else {
3481                    /* delete list */
3482                    if (xs_is_hex(p)) {
3483                        list_maint(&snac, p, 2);
3484                    }
3485                }
3486            }
3487
3488            *ctype = "application/json";
3489            status = HTTP_STATUS_OK;
3490        }
3491        else
3492            status = HTTP_STATUS_UNAUTHORIZED;
3493    }
3494
3495    /* user cleanup */
3496    if (logged_in)
3497        user_free(&snac);
3498
3499    srv_debug(1, xs_fmt("mastoapi_delete_handler %s %d", q_path, status));
3500
3501    return status;
3502}
3503
3504
3505int mastoapi_put_handler(const xs_dict *req, const char *q_path,
3506                          const char *payload, int p_size,
3507                          char **body, int *b_size, char **ctype)
3508{
3509    (void)p_size;
3510    (void)b_size;
3511
3512    if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
3513        return 0;
3514
3515    int status    = HTTP_STATUS_NOT_FOUND;
3516    xs *args      = NULL;
3517    const char *i_ctype = xs_dict_get(req, "content-type");
3518
3519    if (i_ctype && xs_startswith(i_ctype, "application/json")) {
3520        if (!xs_is_null(payload))
3521            args = xs_json_loads(payload);
3522    }
3523    else
3524        args = xs_dup(xs_dict_get(req, "p_vars"));
3525
3526    if (args == NULL)
3527        return HTTP_STATUS_BAD_REQUEST;
3528
3529    xs *cmd = xs_replace_n(q_path, "/api", "", 1);
3530
3531    snac snac = {0};
3532    int logged_in = process_auth_token(&snac, req);
3533
3534    if (xs_startswith(cmd, "/v1/media") || xs_startswith(cmd, "/v2/media")) { /** **/
3535        if (logged_in) {
3536            xs *l = xs_split(cmd, "/");
3537            const char *stid = xs_list_get(l, 3);
3538
3539            if (!xs_is_null(stid)) {
3540                const char *desc = xs_dict_get(args, "description");
3541
3542                /* set the image metadata */
3543                static_put_meta(&snac, stid, desc);
3544
3545                /* prepare a response */
3546                xs *rsp = xs_dict_new();
3547                xs *url = xs_fmt("%s/s/%s", snac.actor, stid);
3548
3549                rsp = xs_dict_append(rsp, "id",          stid);
3550                rsp = xs_dict_append(rsp, "type",        "image");
3551                rsp = xs_dict_append(rsp, "url",         url);
3552                rsp = xs_dict_append(rsp, "preview_url", url);
3553                rsp = xs_dict_append(rsp, "remote_url",  url);
3554                rsp = xs_dict_append(rsp, "description", desc);
3555
3556                *body  = xs_json_dumps(rsp, 4);
3557                *ctype = "application/json";
3558                status = HTTP_STATUS_OK;
3559            }
3560        }
3561        else
3562            status = HTTP_STATUS_UNAUTHORIZED;
3563    }
3564    else
3565    if (xs_startswith(cmd, "/v1/statuses")) {
3566        if (logged_in) {
3567            xs *l = xs_split(cmd, "/");
3568            const char *mid = xs_list_get(l, 3);
3569
3570            if (!xs_is_null(mid)) {
3571                const char *md5 = MID_TO_MD5(mid);
3572                xs *rsp = NULL;
3573                xs *msg = NULL;
3574
3575                if (valid_status(timeline_get_by_md5(&snac, md5, &msg))) {
3576                    const char *content = xs_dict_get(args, "status");
3577                    xs *atls = xs_list_new();
3578                    xs *f_content = not_really_markdown(content, &atls, NULL);
3579
3580                    /* replace fields with new content */
3581                    msg = xs_dict_set(msg, "sourceContent", content);
3582                    msg = xs_dict_set(msg, "content", f_content);
3583
3584                    xs *updated = xs_str_utctime(0, ISO_DATE_SPEC);
3585                    msg = xs_dict_set(msg, "updated", updated);
3586
3587                    /* overwrite object, not updating the indexes */
3588                    object_add_ow(xs_dict_get(msg, "id"), msg);
3589
3590                    /* update message */
3591                    xs *c_msg = msg_update(&snac, msg);
3592
3593                    enqueue_message(&snac, c_msg);
3594
3595                    rsp = mastoapi_status(&snac, msg);
3596                }
3597
3598                if (rsp != NULL) {
3599                    *body  = xs_json_dumps(rsp, 4);
3600                    *ctype = "application/json";
3601                    status = HTTP_STATUS_OK;
3602                }
3603            }
3604        }
3605        else
3606            status = HTTP_STATUS_UNAUTHORIZED;
3607    }
3608
3609    /* user cleanup */
3610    if (logged_in)
3611        user_free(&snac);
3612
3613    srv_debug(1, xs_fmt("mastoapi_put_handler %s %d", q_path, status));
3614
3615    return status;
3616}
3617
3618void persist_image(const char *key, const xs_val *data, const char *payload, snac *snac)
3619/* Store header or avatar */
3620{
3621    if (data != NULL) {
3622        if (xs_type(data) == XSTYPE_LIST) {
3623            const char *fn = xs_list_get(data, 0);
3624
3625            if (fn && *fn) {
3626                const char *ext = strrchr(fn, '.');
3627
3628                /* Mona iOS sends always jpg as application/octet-stream with no filename */
3629                if (ext == NULL || strcmp(fn, key) == 0) {
3630                    ext = ".jpg";
3631                }
3632
3633                /* Make sure we have a unique file name, otherwise updated images will not be
3634                 * re-loaded by clients. */
3635                xs *rnd         = random_str();
3636                xs *hash        = xs_md5_hex(rnd, strlen(rnd));
3637                xs *id          = xs_fmt("%s%s", hash, ext);
3638                xs *url         = xs_fmt("%s/s/%s", snac->actor, id);
3639                int fo          = xs_number_get(xs_list_get(data, 1));
3640                int fs          = xs_number_get(xs_list_get(data, 2));
3641
3642                /* store */
3643                static_put(snac, id, payload + fo, fs);
3644
3645                snac->config = xs_dict_set(snac->config, key, url);
3646            }
3647        }
3648    }
3649}
3650
3651int mastoapi_patch_handler(const xs_dict *req, const char *q_path,
3652                          const char *payload, int p_size,
3653                          char **body, int *b_size, char **ctype)
3654/* Handle profile updates */
3655{
3656    (void)p_size;
3657    (void)b_size;
3658
3659    if (!xs_startswith(q_path, "/api/v1/"))
3660        return 0;
3661
3662    int status    = HTTP_STATUS_NOT_FOUND;
3663    xs *args      = NULL;
3664    const char *i_ctype = xs_dict_get(req, "content-type");
3665
3666    if (i_ctype && xs_startswith(i_ctype, "application/json")) {
3667        if (!xs_is_null(payload))
3668            args = xs_json_loads(payload);
3669    }
3670    else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
3671    {
3672        // Some apps send form data instead of json so we should cater for those
3673        if (!xs_is_null(payload)) {
3674            args    = xs_url_vars(payload);
3675        }
3676    }
3677    else
3678        args = xs_dup(xs_dict_get(req, "p_vars"));
3679
3680    if (args == NULL)
3681        return HTTP_STATUS_BAD_REQUEST;
3682
3683    xs *cmd = xs_replace_n(q_path, "/api", "", 1);
3684
3685    snac snac = {0};
3686    int logged_in = process_auth_token(&snac, req);
3687
3688    if (xs_startswith(cmd, "/v1/accounts/update_credentials")) {
3689        /* Update user profile fields */
3690        if (logged_in) {
3691            int c = 0;
3692            const xs_str *k;
3693            const xs_val *v;
3694            const xs_str *field_name = NULL;
3695            xs *new_fields = xs_dict_new();
3696            while (xs_dict_next(args, &k, &v, &c)) {
3697                if (strcmp(k, "display_name") == 0) {
3698                    if (v != NULL)
3699                        snac.config = xs_dict_set(snac.config, "name", v);
3700                }
3701                else
3702                if (strcmp(k, "note") == 0) {
3703                    if (v != NULL)
3704                        snac.config = xs_dict_set(snac.config, "bio", v);
3705                }
3706                else
3707                if (strcmp(k, "bot") == 0) {
3708                    if (v != NULL)
3709                        snac.config = xs_dict_set(snac.config, "bot",
3710                            (strcmp(v, "true") == 0 ||
3711                                strcmp(v, "1") == 0) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
3712                }
3713                else
3714                if (strcmp(k, "source[sensitive]") == 0) {
3715                    if (v != NULL)
3716                        snac.config = xs_dict_set(snac.config, "cw",
3717                            strcmp(v, "true") == 0 ? "open" : "");
3718                }
3719                else
3720                if (strcmp(k, "source[privacy]") == 0) {
3721                    if (v != NULL)
3722                        snac.config = xs_dict_set(snac.config, "private",
3723                            strcmp(v, "private") == 0 ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
3724                }
3725                else
3726                if (strcmp(k, "header") == 0) {
3727                    persist_image("header", v, payload, &snac);
3728                }
3729                else
3730                if (strcmp(k, "avatar") == 0) {
3731                    persist_image("avatar", v, payload, &snac);
3732                }
3733                else
3734                if (xs_between("fields_attributes", k, "[name]")) {
3735                    field_name = strcmp(v, "") != 0 ? v : NULL;
3736                }
3737                else
3738                if (xs_between("fields_attributes", k, "[value]")) {
3739                    if (field_name != NULL) {
3740                        new_fields = xs_dict_set(new_fields, field_name, v);
3741                        snac.config = xs_dict_set(snac.config, "metadata", new_fields);
3742                    }
3743                }
3744                /* we don't have support for the following options, yet
3745                   - discoverable (0/1)
3746                   - locked (0/1)
3747                 */
3748            }
3749
3750            /* Persist profile */
3751            if (user_persist(&snac, 1) == 0)
3752                credentials_get(body, ctype, &status, snac);
3753            else
3754                status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
3755        }
3756        else
3757            status = HTTP_STATUS_UNAUTHORIZED;
3758    }
3759
3760    /* user cleanup */
3761    if (logged_in)
3762        user_free(&snac);
3763
3764    srv_debug(1, xs_fmt("mastoapi_patch_handler %s %d", q_path, status));
3765
3766    return status;
3767}
3768
3769
3770void mastoapi_purge(void)
3771{
3772    xs *spec   = xs_fmt("%s/app/" "*.json", srv_basedir);
3773    xs *files  = xs_glob(spec, 1, 0);
3774    xs_list *p = files;
3775    const xs_str *v;
3776
3777    time_t mt = time(NULL) - 3600;
3778
3779    while (xs_list_iter(&p, &v)) {
3780        xs *cid = xs_replace(v, ".json", "");
3781        xs *fn  = _app_fn(cid);
3782
3783        if (mtime(fn) < mt) {
3784            /* get the app */
3785            xs *app = app_get(cid);
3786
3787            if (app) {
3788                /* old apps with no uid are incomplete cruft */
3789                const char *uid = xs_dict_get(app, "uid");
3790
3791                if (xs_is_null(uid) || *uid == '\0') {
3792                    unlink(fn);
3793                    srv_debug(2, xs_fmt("purged %s", fn));
3794                }
3795            }
3796        }
3797    }
3798}
3799
3800
3801#endif /* #ifndef NO_MASTODON_API */