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