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