2.60 activitypub.c
   1/* snac - A simple, minimalistic ActivityPub instance */
   2/* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
   3
   4#include "xs.h"
   5#include "xs_json.h"
   6#include "xs_curl.h"
   7#include "xs_mime.h"
   8#include "xs_openssl.h"
   9#include "xs_regex.h"
  10#include "xs_time.h"
  11#include "xs_set.h"
  12#include "xs_match.h"
  13
  14#include "snac.h"
  15
  16#include <sys/wait.h>
  17
  18const char *public_address = "https:/" "/www.w3.org/ns/activitystreams#Public";
  19
  20/* susie.png */
  21
  22const char *susie =
  23    "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  24    "CEkxzAAAAUUlEQVQoz43R0QkAMQwCUDdw/y3dwE"
  25    "vsvzlL4X1IoQkAisKmwfAFT3RgJHbQezpSRoXEq"
  26    "eqCL9BJBf7h3QbOCCxV5EVWMEMwG7K1/WODtlvx"
  27    "AYTtEsDU9F34AAAAAElFTkSuQmCC";
  28
  29const char *susie_cool =
  30    "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  31    "CEkxzAAAAV0lEQVQoz43RwQ3AMAwCQDZg/y3ZgN"
  32    "qo3+JaedwDOUQBQFHYaTB8wTM6sGl2cMPu+DFzn"
  33    "+ZcgN7wF7ZVihXkfSlWIVzIA6dbQzaygllpNuTX"
  34    "ZmmFNlvxADX1+o0cUPMbAAAAAElFTkSuQmCC";
  35
  36const char *susie_muertos = 
  37    "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  38    "CEkxzAAAAV0lEQVQoz4XQsQ0AMQxCUW/A/lv+DT"
  39    "ic6zGRolekIMyMELNp8PiCEw6Q4w4NoAt53IH5m"
  40    "xXksrZYgZwJrIox+Z8vJAfe2lCxG6AK7eKkWcEb"
  41    "QHbF617xAQatAAD7jJHUAAAAAElFTkSuQmCC";
  42
  43
  44const char *default_avatar_base64(void)
  45/* returns the default avatar in base64 */
  46{
  47    time_t t = time(NULL);
  48    struct tm tm;
  49    const char *p = susie;
  50
  51    gmtime_r(&t, &tm);
  52
  53    if (tm.tm_mon == 10 && tm.tm_mday == 2)
  54        p = susie_muertos;
  55    else
  56    if (tm.tm_wday == 0 || tm.tm_wday == 6)
  57        p = susie_cool;
  58
  59    return p;
  60}
  61
  62
  63int activitypub_request(snac *user, const char *url, xs_dict **data)
  64/* request an object */
  65{
  66    int status = 0;
  67    xs *response = NULL;
  68    xs *payload = NULL;
  69    int p_size;
  70    const char *ctype;
  71
  72    *data = NULL;
  73
  74    if (user != NULL) {
  75        /* get from the net */
  76        response = http_signed_request(user, "GET", url,
  77            NULL, NULL, 0, &status, &payload, &p_size, 0);
  78    }
  79
  80    if (status == 0 || (status >= 500 && status <= 599)) {
  81        /* I found an instance running Misskey that returned
  82           500 on signed messages but returned the object
  83           perfectly without signing (?), so why not try */
  84        xs_free(response);
  85
  86        xs *hdrs = xs_dict_new();
  87        hdrs = xs_dict_append(hdrs, "accept",     "application/activity+json");
  88        hdrs = xs_dict_append(hdrs, "user-agent", USER_AGENT);
  89
  90        response = xs_http_request("GET", url, hdrs,
  91            NULL, 0, &status, &payload, &p_size, 0);
  92    }
  93
  94    if (valid_status(status)) {
  95        /* ensure it's ActivityPub data */
  96        ctype = xs_dict_get(response, "content-type");
  97
  98        if (xs_is_null(ctype))
  99            status = HTTP_STATUS_BAD_REQUEST;
 100        else
 101        if (xs_str_in(ctype, "application/activity+json") != -1 ||
 102            xs_str_in(ctype, "application/ld+json") != -1) {
 103
 104            /* if there is no payload, fail */
 105            if (xs_is_null(payload))
 106                status = HTTP_STATUS_BAD_REQUEST;
 107            else
 108                *data = xs_json_loads(payload);
 109        }
 110        else
 111            status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
 112    }
 113
 114    return status;
 115}
 116
 117
 118int actor_request(snac *user, const char *actor, xs_dict **data)
 119/* request an actor */
 120{
 121    int status;
 122    xs *payload = NULL;
 123
 124    if (data)
 125        *data = NULL;
 126
 127    /* get from disk first */
 128    status = actor_get_refresh(user, actor, data);
 129
 130    if (!valid_status(status)) {
 131        /* actor data non-existent: get from the net */
 132        status = activitypub_request(user, actor, &payload);
 133
 134        if (valid_status(status)) {
 135            /* renew data */
 136            status = actor_add(actor, payload);
 137
 138            if (data != NULL) {
 139                *data   = payload;
 140                payload = NULL;
 141            }
 142        }
 143        else
 144            srv_debug(1, xs_fmt("actor_request error %s %d", actor, status));
 145    }
 146
 147    /* collect the (presumed) shared inbox in this actor */
 148    if (xs_type(xs_dict_get(srv_config, "disable_inbox_collection")) != XSTYPE_TRUE) {
 149        if (valid_status(status) && data && *data)
 150            inbox_add_by_actor(*data);
 151    }
 152
 153    return status;
 154}
 155
 156
 157const char *get_atto(const xs_dict *msg)
 158/* gets the attributedTo field (an actor) */
 159{
 160    const xs_val *actor = xs_dict_get(msg, "attributedTo");
 161
 162    /* if the actor is a list of objects (like on Peertube videos), pick the Person */
 163    if (xs_type(actor) == XSTYPE_LIST) {
 164        const xs_list *p = actor;
 165        int c = 0;
 166        const xs_dict *v;
 167        actor = NULL;
 168
 169        while (actor == NULL && xs_list_next(p, &v, &c)) {
 170            if (xs_type(v) == XSTYPE_DICT) {
 171                const char *type = xs_dict_get(v, "type");
 172                if (xs_type(type) == XSTYPE_STRING && strcmp(type, "Person") == 0) {
 173                    actor = xs_dict_get(v, "id");
 174
 175                    if (xs_type(actor) != XSTYPE_STRING)
 176                        actor = NULL;
 177                }
 178            }
 179        }
 180    }
 181
 182    return actor;
 183}
 184
 185
 186xs_list *get_attachments(const xs_dict *msg)
 187/* unify the garbage fire that are the attachments */
 188{
 189    xs_list *l = xs_list_new();
 190    const xs_list *p;
 191
 192    /* try first the attachments list */
 193    if (!xs_is_null(p = xs_dict_get(msg, "attachment"))) {
 194        xs *attach = NULL;
 195        const xs_val *v;
 196
 197        /* ensure it's a list */
 198        if (xs_type(p) == XSTYPE_DICT) {
 199            attach = xs_list_new();
 200            attach = xs_list_append(attach, p);
 201        }
 202        else
 203            attach = xs_dup(p);
 204
 205        if (xs_type(attach) == XSTYPE_LIST) {
 206            /* does the message have an image? */
 207            const xs_dict *d = xs_dict_get(msg, "image");
 208            if (xs_type(d) == XSTYPE_DICT) {
 209                /* add it to the attachment list */
 210                attach = xs_list_append(attach, d);
 211            }
 212        }
 213
 214        /* now iterate the list */
 215        int c = 0;
 216        while (xs_list_next(attach, &v, &c)) {
 217            const char *type = xs_dict_get(v, "mediaType");
 218            if (xs_is_null(type))
 219                type = xs_dict_get(v, "type");
 220
 221            if (xs_is_null(type))
 222                continue;
 223
 224            const char *href = xs_dict_get(v, "url");
 225            if (xs_is_null(href))
 226                href = xs_dict_get(v, "href");
 227            if (xs_is_null(href))
 228                continue;
 229
 230            /* infer MIME type from non-specific attachments */
 231            if (xs_list_len(attach) < 2 && xs_match(type, "Link|Document")) {
 232                char *mt = (char *)xs_mime_by_ext(href);
 233
 234                if (xs_match(mt, "image/*|audio/*|video/*")) /* */
 235                    type = mt;
 236            }
 237
 238            const char *name = xs_dict_get(v, "name");
 239            if (xs_is_null(name))
 240                name = xs_dict_get(msg, "name");
 241            if (xs_is_null(name))
 242                name = "";
 243
 244            xs *d = xs_dict_new();
 245            d = xs_dict_append(d, "type", type);
 246            d = xs_dict_append(d, "href", href);
 247            d = xs_dict_append(d, "name", name);
 248
 249            l = xs_list_append(l, d);
 250        }
 251    }
 252
 253    /** urls (attachments from Peertube) **/
 254    p = xs_dict_get(msg, "url");
 255
 256    if (xs_type(p) == XSTYPE_LIST) {
 257        const char *href = NULL;
 258        const char *type = NULL;
 259        int c = 0;
 260        const xs_val *v;
 261
 262        while (href == NULL && xs_list_next(p, &v, &c)) {
 263            if (xs_type(v) == XSTYPE_DICT) {
 264                const char *mtype = xs_dict_get(v, "type");
 265
 266                if (xs_type(mtype) == XSTYPE_STRING && strcmp(mtype, "Link") == 0) {
 267                    mtype = xs_dict_get(v, "mediaType");
 268                    const xs_list *tag = xs_dict_get(v, "tag");
 269
 270                    if (xs_type(mtype) == XSTYPE_STRING &&
 271                        strcmp(mtype, "application/x-mpegURL") == 0 &&
 272                        xs_type(tag) == XSTYPE_LIST) {
 273                        /* now iterate the tag list, looking for a video URL */
 274                        const xs_dict *d;
 275                        int c = 0;
 276
 277                        while (href == NULL && xs_list_next(tag, &d, &c)) {
 278                            if (xs_type(d) == XSTYPE_DICT) {
 279                                if (xs_type(mtype = xs_dict_get(d, "mediaType")) == XSTYPE_STRING &&
 280                                    xs_startswith(mtype, "video/")) {
 281                                    const char *h = xs_dict_get(d, "href");
 282
 283                                    /* this is probably it */
 284                                    if (xs_type(h) == XSTYPE_STRING) {
 285                                        href = h;
 286                                        type = mtype;
 287                                    }
 288                                }
 289                            }
 290                        }
 291                    }
 292                }
 293            }
 294        }
 295
 296        if (href && type) {
 297            xs *d = xs_dict_new();
 298            d = xs_dict_append(d, "href", href);
 299            d = xs_dict_append(d, "type", type);
 300            d = xs_dict_append(d, "name", "---");
 301
 302            l = xs_list_append(l, d);
 303        }
 304    }
 305
 306    return l;
 307}
 308
 309
 310int timeline_request(snac *snac, const char **id, xs_str **wrk, int level)
 311/* ensures that an entry and its ancestors are in the timeline */
 312{
 313    int status = 0;
 314
 315    if (level < MAX_CONVERSATION_LEVELS && !xs_is_null(*id)) {
 316        xs *msg = NULL;
 317
 318        /* from a blocked instance? discard and break */
 319        if (is_instance_blocked(*id)) {
 320            snac_debug(snac, 1, xs_fmt("timeline_request blocked instance %s", *id));
 321            return status;
 322        }
 323
 324        /* is the object already there? */
 325        if (!valid_status(object_get(*id, &msg))) {
 326            /* no; download it */
 327            status = activitypub_request(snac, *id, &msg);
 328
 329            if (valid_status(status)) {
 330                const xs_dict *object = msg;
 331                const char *type = xs_dict_get(object, "type");
 332
 333                /* get the id again from the object, as it may be different */
 334                const char *nid = xs_dict_get(object, "id");
 335
 336                if (xs_type(nid) != XSTYPE_STRING)
 337                    return 0;
 338
 339                if (wrk && strcmp(nid, *id) != 0) {
 340                    snac_debug(snac, 1,
 341                        xs_fmt("timeline_request canonical id for %s is %s", *id, nid));
 342
 343                    *wrk = xs_dup(nid);
 344                    *id  = *wrk;
 345                }
 346
 347                if (xs_is_null(type))
 348                    type = "(null)";
 349
 350                srv_debug(2, xs_fmt("timeline_request type %s '%s'", nid, type));
 351
 352                if (strcmp(type, "Create") == 0) {
 353                    /* some software like lemmy nest Announce + Create + Note */
 354                    if (!xs_is_null(object = xs_dict_get(object, "object"))) {
 355                        type = xs_dict_get(object, "type");
 356                        nid  = xs_dict_get(object, "id");
 357                    }
 358                    else
 359                        type = "(null)";
 360                }
 361
 362                if (xs_match(type, POSTLIKE_OBJECT_TYPE)) {
 363                    if (content_match("filter_reject.txt", object))
 364                        snac_log(snac, xs_fmt("timeline_request rejected by content %s", nid));
 365                    else {
 366                        const char *actor = get_atto(object);
 367
 368                        if (!xs_is_null(actor)) {
 369                            /* request (and drop) the actor for this entry */
 370                            if (!valid_status(actor_request(snac, actor, NULL))) {
 371                                /* failed? retry later */
 372                                enqueue_actor_refresh(snac, actor, 60);
 373                            }
 374
 375                            /* does it have an ancestor? */
 376                            const char *in_reply_to = xs_dict_get(object, "inReplyTo");
 377
 378                            /* store */
 379                            timeline_add(snac, nid, object);
 380
 381                            /* recurse! */
 382                            timeline_request(snac, &in_reply_to, NULL, level + 1);
 383                        }
 384                    }
 385                }
 386            }
 387        }
 388    }
 389
 390    return status;
 391}
 392
 393
 394int send_to_inbox_raw(const char *keyid, const char *seckey,
 395                  const xs_str *inbox, const xs_dict *msg,
 396                  xs_val **payload, int *p_size, int timeout)
 397/* sends a message to an Inbox */
 398{
 399    int status;
 400    xs_dict *response;
 401    xs *j_msg = xs_json_dumps((xs_dict *)msg, 4);
 402
 403    response = http_signed_request_raw(keyid, seckey, "POST", inbox,
 404        NULL, j_msg, strlen(j_msg), &status, payload, p_size, timeout);
 405
 406    xs_free(response);
 407
 408    return status;
 409}
 410
 411
 412int send_to_inbox(snac *snac, const xs_str *inbox, const xs_dict *msg,
 413                  xs_val **payload, int *p_size, int timeout)
 414/* sends a message to an Inbox */
 415{
 416    const char *seckey = xs_dict_get(snac->key, "secret");
 417
 418    return send_to_inbox_raw(snac->actor, seckey, inbox, msg, payload, p_size, timeout);
 419}
 420
 421
 422xs_str *get_actor_inbox(const char *actor, int shared)
 423/* gets an actor's inbox */
 424{
 425    xs *data = NULL;
 426    const char *v = NULL;
 427
 428    if (valid_status(actor_request(NULL, actor, &data))) {
 429        /* try first endpoints/sharedInbox */
 430        if (shared && (v = xs_dict_get(data, "endpoints")))
 431            v = xs_dict_get(v, "sharedInbox");
 432
 433        /* try then the regular inbox */
 434        if (xs_is_null(v))
 435            v = xs_dict_get(data, "inbox");
 436    }
 437
 438    return xs_is_null(v) ? NULL : xs_dup(v);
 439}
 440
 441
 442int send_to_actor(snac *snac, const char *actor, const xs_dict *msg,
 443                  xs_val **payload, int *p_size, int timeout)
 444/* sends a message to an actor */
 445{
 446    int status = HTTP_STATUS_BAD_REQUEST;
 447    xs *inbox = get_actor_inbox(actor, 1);
 448
 449    if (!xs_is_null(inbox))
 450        status = send_to_inbox(snac, inbox, msg, payload, p_size, timeout);
 451
 452    return status;
 453}
 454
 455
 456void post_message(snac *snac, const char *actor, const xs_dict *msg)
 457/* posts a message immediately (bypassing the output queues) */
 458{
 459    xs *payload = NULL;
 460    int p_size;
 461
 462    int status = send_to_actor(snac, actor, msg, &payload, &p_size, 3);
 463
 464    srv_log(xs_fmt("post_message to actor %s %d", actor, status));
 465
 466    if (!valid_status(status))
 467        /* cannot send right now, enqueue */
 468        enqueue_message(snac, msg);
 469}
 470
 471
 472xs_list *recipient_list(snac *snac, const xs_dict *msg, int expand_public)
 473/* returns the list of recipients for a message */
 474{
 475    const xs_val *to = xs_dict_get(msg, "to");
 476    const xs_val *cc = xs_dict_get(msg, "cc");
 477    xs_set rcpts;
 478    int n;
 479
 480    xs_set_init(&rcpts);
 481
 482    const xs_list *lists[] = { to, cc, NULL };
 483    for (n = 0; lists[n]; n++) {
 484        xs_list *l = (xs_list *)lists[n];
 485        const char *v;
 486        xs *tl = NULL;
 487
 488        /* if it's a string, create a list with only one element */
 489        if (xs_type(l) == XSTYPE_STRING) {
 490            tl = xs_list_new();
 491            tl = xs_list_append(tl, l);
 492
 493            l = tl;
 494        }
 495
 496        while (xs_list_iter(&l, &v)) {
 497            if (expand_public && strcmp(v, public_address) == 0) {
 498                /* iterate the followers and add them */
 499                xs *fwers = follower_list(snac);
 500                const char *actor;
 501
 502                char *p = fwers;
 503                while (xs_list_iter(&p, &actor))
 504                    xs_set_add(&rcpts, actor);
 505            }
 506            else
 507                xs_set_add(&rcpts, v);
 508        }
 509    }
 510
 511    return xs_set_result(&rcpts);
 512}
 513
 514
 515int is_msg_public(const xs_dict *msg)
 516/* checks if a message is public */
 517{
 518    const char *to = xs_dict_get(msg, "to");
 519    const char *cc = xs_dict_get(msg, "cc");
 520    int n;
 521
 522    const char *lists[] = { to, cc, NULL };
 523    for (n = 0; lists[n]; n++) {
 524        const xs_val *l = lists[n];
 525
 526        if (xs_type(l) == XSTYPE_STRING) {
 527            if (strcmp(l, public_address) == 0)
 528                return 1;
 529        }
 530        else
 531        if (xs_type(l) == XSTYPE_LIST) {
 532            if (xs_list_in(l, public_address) != -1)
 533                return 1;
 534        }
 535    }
 536
 537    return 0;
 538}
 539
 540
 541int is_msg_from_private_user(const xs_dict *msg)
 542/* checks if a message is from a local, private user */
 543{
 544    int ret = 0;
 545
 546    /* is this message from a local user? */
 547    if (xs_startswith(xs_dict_get(msg, "id"), srv_baseurl)) {
 548        const char *atto = get_atto(msg);
 549        xs *l = xs_split(atto, "/");
 550        const char *uid = xs_list_get(l, -1);
 551        snac user;
 552
 553        if (uid && user_open(&user, uid)) {
 554            if (xs_type(xs_dict_get(user.config, "private")) == XSTYPE_TRUE)
 555                ret = 1;
 556
 557            user_free(&user);
 558        }
 559    }
 560
 561    return ret;
 562}
 563
 564
 565int is_msg_for_me(snac *snac, const xs_dict *c_msg)
 566/* checks if this message is for me */
 567{
 568    const char *type  = xs_dict_get(c_msg, "type");
 569    const char *actor = xs_dict_get(c_msg, "actor");
 570
 571    if (strcmp(actor, snac->actor) == 0) {
 572        /* message by myself? (most probably via the shared-inbox) reject */
 573        snac_debug(snac, 1, xs_fmt("ignoring message by myself"));
 574        return 0;
 575    }
 576
 577    if (xs_match(type, "Like|Announce|EmojiReact")) {
 578        const char *object = xs_dict_get(c_msg, "object");
 579
 580        if (xs_type(object) == XSTYPE_DICT)
 581            object = xs_dict_get(object, "id");
 582
 583        /* bad object id? reject */
 584        if (xs_type(object) != XSTYPE_STRING)
 585            return 0;
 586
 587        /* if it's about one of our posts, accept it */
 588        if (xs_startswith(object, snac->actor))
 589            return 2;
 590
 591        /* if it's by someone we don't follow, reject */
 592        return following_check(snac, actor);
 593    }
 594
 595    /* if it's an Undo, it must be from someone related to us */
 596    if (xs_match(type, "Undo")) {
 597        return follower_check(snac, actor) || following_check(snac, actor);
 598    }
 599
 600    /* if it's an Accept + Follow, it must be for a Follow we created */
 601    if (xs_match(type, "Accept")) {
 602        return following_check(snac, actor);
 603    }
 604
 605    /* if it's a Follow, it must be explicitly for us */
 606    if (xs_match(type, "Follow")) {
 607        const char *object = xs_dict_get(c_msg, "object");
 608        return !xs_is_null(object) && strcmp(snac->actor, object) == 0;
 609    }
 610
 611    /* only accept Ping directed to us */
 612    if (xs_match(type, "Ping")) {
 613        const char *dest = xs_dict_get(c_msg, "to");
 614        return !xs_is_null(dest) && strcmp(snac->actor, dest) == 0;
 615    }
 616
 617    /* if it's not a Create or Update, allow as is */
 618    if (!xs_match(type, "Create|Update")) {
 619        return 1;
 620    }
 621
 622    int pub_msg = is_msg_public(c_msg);
 623
 624    /* if this message is public and we follow the actor of this post, allow */
 625    if (pub_msg && following_check(snac, actor))
 626        return 1;
 627
 628    const xs_dict *msg = xs_dict_get(c_msg, "object");
 629    xs *rcpts = recipient_list(snac, msg, 0);
 630    xs_list *p = rcpts;
 631    const xs_str *v;
 632
 633    xs *actor_followers = NULL;
 634
 635    if (!pub_msg) {
 636        /* not a public message; get the actor and its followers list */
 637        xs *actor_obj = NULL;
 638
 639        if (valid_status(object_get(actor, &actor_obj))) {
 640            const xs_val *fw = xs_dict_get(actor_obj, "followers");
 641            if (fw)
 642                actor_followers = xs_dup(fw);
 643        }
 644    }
 645
 646    while(xs_list_iter(&p, &v)) {
 647        /* explicitly for me? accept */
 648        if (strcmp(v, snac->actor) == 0)
 649            return 2;
 650
 651        if (pub_msg) {
 652            /* a public message for someone we follow? (probably cc'ed) accept */
 653            if (following_check(snac, v))
 654                return 5;
 655        }
 656        else
 657        if (actor_followers && strcmp(v, actor_followers) == 0) {
 658            /* if this message is for this actor's followers, are we one of them? */
 659            if (following_check(snac, actor))
 660                return 6;
 661        }
 662    }
 663
 664    /* accept if it's by someone we follow */
 665    const char *atto = get_atto(msg);
 666
 667    if (pub_msg && !xs_is_null(atto) && following_check(snac, atto))
 668        return 3;
 669
 670    /* is this message a reply to another? */
 671    const char *irt = xs_dict_get(msg, "inReplyTo");
 672    if (!xs_is_null(irt)) {
 673        xs *r_msg = NULL;
 674
 675        /* try to get the replied message */
 676        if (valid_status(object_get(irt, &r_msg))) {
 677            atto = get_atto(r_msg);
 678
 679            /* accept if the replied message is from someone we follow */
 680            if (pub_msg && !xs_is_null(atto) && following_check(snac, atto))
 681                return 4;
 682        }
 683    }
 684
 685    return 0;
 686}
 687
 688
 689xs_str *process_tags(snac *snac, const char *content, xs_list **tag)
 690/* parses mentions and tags from content */
 691{
 692    xs_str *nc  = xs_str_new(NULL);
 693    xs_list *tl = *tag;
 694    xs *split;
 695    xs_list *p;
 696    const xs_val *v;
 697    int n = 0;
 698
 699    /* create a default server for incomplete mentions */
 700    xs *def_srv = NULL;
 701
 702    if (xs_list_len(tl)) {
 703        /* if there are any mentions, get the server from
 704           the first one, which is the inReplyTo author */
 705        p = tl;
 706        while (xs_list_iter(&p, &v)) {
 707            const char *type = xs_dict_get(v, "type");
 708            const char *name = xs_dict_get(v, "name");
 709
 710            if (type && name && strcmp(type, "Mention") == 0) {
 711                xs *l = xs_split(name, "@");
 712
 713                def_srv = xs_dup(xs_list_get(l, -1));
 714
 715                break;
 716            }
 717        }
 718    }
 719
 720    if (xs_is_null(def_srv))
 721        /* use this same server */
 722        def_srv = xs_dup(xs_dict_get(srv_config, "host"));
 723
 724    split = xs_regex_split(content, "(@[A-Za-z0-9_]+(@[A-Za-z0-9\\.-]+)?|&#[0-9]+;|#[^[:punct:][:space:]]+)");
 725
 726    p = split;
 727    while (xs_list_iter(&p, &v)) {
 728        if ((n & 0x1)) {
 729            if (*v == '@') {
 730                xs *link = NULL;
 731                xs *wuid = NULL;
 732
 733                if (strchr(v + 1, '@') == NULL) {
 734                    /* only one @? it's a dumb Mastodon-like mention
 735                       without server; add the default one */
 736                    wuid = xs_fmt("%s@%s", v, def_srv);
 737
 738                    snac_debug(snac, 2, xs_fmt("mention without server '%s' '%s'", v, wuid));
 739                }
 740                else
 741                    wuid = xs_dup(v);
 742
 743                /* query the webfinger about this fellow */
 744                xs *actor = NULL;
 745                xs *uid   = NULL;
 746                int status;
 747
 748                status = webfinger_request(wuid, &actor, &uid);
 749
 750                if (valid_status(status) && actor && uid) {
 751                    xs *d = xs_dict_new();
 752                    xs *n = xs_fmt("@%s", uid);
 753
 754                    d = xs_dict_append(d, "type",   "Mention");
 755                    d = xs_dict_append(d, "href",   actor);
 756                    d = xs_dict_append(d, "name",   n);
 757
 758                    tl = xs_list_append(tl, d);
 759
 760                    link = xs_fmt("<a href=\"%s\" class=\"u-url h-card mention\">%s</a>", actor, n);
 761                }
 762
 763                if (!xs_is_null(link))
 764                    nc = xs_str_cat(nc, link);
 765                else
 766                    nc = xs_str_cat(nc, v);
 767            }
 768            else
 769            if (*v == '#') {
 770                /* hashtag */
 771                xs *d = xs_dict_new();
 772                xs *n = xs_tolower_i(xs_dup(v));
 773                xs *h = xs_fmt("%s?t=%s", srv_baseurl, n + 1);
 774                xs *l = xs_fmt("<a href=\"%s\" class=\"mention hashtag\" rel=\"tag\">%s</a>", h, v);
 775
 776                d = xs_dict_append(d, "type",   "Hashtag");
 777                d = xs_dict_append(d, "href",   h);
 778                d = xs_dict_append(d, "name",   n);
 779
 780                tl = xs_list_append(tl, d);
 781
 782                /* add the code */
 783                nc = xs_str_cat(nc, l);
 784            }
 785            else
 786            if (*v == '&') {
 787                /* HTML Unicode entity, probably part of an emoji */
 788
 789                /* write as is */
 790                nc = xs_str_cat(nc, v);
 791            }
 792        }
 793        else
 794            nc = xs_str_cat(nc, v);
 795
 796        n++;
 797    }
 798
 799    *tag = tl;
 800
 801    return nc;
 802}
 803
 804
 805void notify(snac *snac, const char *type, const char *utype, const char *actor, const xs_dict *msg)
 806/* notifies the user of relevant events */
 807{
 808    /* skip our own notifications */
 809    if (strcmp(snac->actor, actor) == 0)
 810        return;
 811
 812    const char *id = xs_dict_get(msg, "id");
 813
 814    if (strcmp(type, "Create") == 0) {
 815        /* only notify of notes specifically for us */
 816        xs *rcpts = recipient_list(snac, msg, 0);
 817
 818        if (xs_list_in(rcpts, snac->actor) == -1)
 819            return;
 820
 821        /* discard votes */
 822        const xs_dict *note = xs_dict_get(msg, "object");
 823
 824        if (note && !xs_is_null(xs_dict_get(note, "name")))
 825            return;
 826    }
 827
 828    if (strcmp(type, "Undo") == 0 && strcmp(utype, "Follow") != 0)
 829        return;
 830
 831    /* get the object id */
 832    const char *objid = xs_dict_get(msg, "object");
 833
 834    if (xs_type(objid) == XSTYPE_DICT)
 835        objid = xs_dict_get(objid, "id");
 836
 837    if (xs_match(type, "Like|Announce|EmojiReact")) {
 838        /* if it's not an admiration about something by us, done */
 839        if (xs_is_null(objid) || !xs_startswith(objid, snac->actor))
 840            return;
 841    }
 842
 843    /* updated poll? */
 844    if (strcmp(type, "Update") == 0 && strcmp(utype, "Question") == 0) {
 845        const xs_dict *poll;
 846        const char *poll_id;
 847
 848        if ((poll = xs_dict_get(msg, "object")) == NULL)
 849            return;
 850
 851        /* if it's not closed, discard */
 852        if (xs_is_null(xs_dict_get(poll, "closed")))
 853            return;
 854
 855        if ((poll_id = xs_dict_get(poll, "id")) == NULL)
 856            return;
 857
 858        /* if it's not ours and we didn't vote, discard */
 859        if (!xs_startswith(poll_id, snac->actor) && !was_question_voted(snac, poll_id))
 860            return;
 861    }
 862
 863    /* user will love to know about this! */
 864
 865    /* prepare message body */
 866    xs *body = xs_fmt("User  : @%s@%s\n",
 867        xs_dict_get(snac->config, "uid"),
 868        xs_dict_get(srv_config,   "host")
 869    );
 870
 871    if (strcmp(utype, "(null)") != 0) {
 872        xs *s1 = xs_fmt("Type  : %s + %s\n", type, utype);
 873        body = xs_str_cat(body, s1);
 874    }
 875    else {
 876        xs *s1 = xs_fmt("Type  : %s\n", type);
 877        body = xs_str_cat(body, s1);
 878    }
 879
 880    {
 881        xs *s1 = xs_fmt("Actor : %s\n", actor);
 882        body = xs_str_cat(body, s1);
 883    }
 884
 885    if (objid != NULL) {
 886        xs *s1 = xs_fmt("Object: %s\n", objid);
 887        body = xs_str_cat(body, s1);
 888    }
 889
 890    /* email */
 891
 892    const char *email = "[disabled by admin]";
 893
 894    if (xs_type(xs_dict_get(srv_config, "disable_email_notifications")) != XSTYPE_TRUE) {
 895        email = xs_dict_get(snac->config_o, "email");
 896        if (xs_is_null(email)) {
 897            email = xs_dict_get(snac->config, "email");
 898
 899            if (xs_is_null(email))
 900                email = "[empty]";
 901        }
 902    }
 903
 904    if (*email != '\0' && *email != '[') {
 905        snac_debug(snac, 1, xs_fmt("email notify %s %s %s", type, utype, actor));
 906
 907        xs *subject = xs_fmt("snac notify for @%s@%s",
 908                    xs_dict_get(snac->config, "uid"), xs_dict_get(srv_config, "host"));
 909        xs *from    = xs_fmt("snac-daemon <snac-daemon@%s>", xs_dict_get(srv_config, "host"));
 910        xs *header  = xs_fmt(
 911                    "From: %s\n"
 912                    "To: %s\n"
 913                    "Subject: %s\n"
 914                    "\n",
 915                    from, email, subject);
 916
 917        xs *email_body = xs_fmt("%s%s", header, body);
 918
 919        enqueue_email(email_body, 0);
 920    }
 921
 922    /* telegram */
 923
 924    const char *bot     = xs_dict_get(snac->config, "telegram_bot");
 925    const char *chat_id = xs_dict_get(snac->config, "telegram_chat_id");
 926
 927    if (!xs_is_null(bot) && !xs_is_null(chat_id) && *bot && *chat_id)
 928        enqueue_telegram(body, bot, chat_id);
 929
 930    /* ntfy */
 931    const char *ntfy_server = xs_dict_get(snac->config, "ntfy_server");
 932    const char *ntfy_token  = xs_dict_get(snac->config, "ntfy_token");
 933
 934    if (!xs_is_null(ntfy_server) && *ntfy_server)
 935        enqueue_ntfy(body, ntfy_server, ntfy_token);
 936
 937    /* auto boost */
 938    if (xs_match(type, "Create") && xs_is_true(xs_dict_get(snac->config, "auto_boost"))) {
 939        xs *msg = msg_admiration(snac, objid, "Announce");
 940        enqueue_message(snac, msg);
 941
 942        snac_debug(snac, 1, xs_fmt("auto boosted %s", objid));
 943    }
 944
 945    /* finally, store it in the notification folder */
 946    if (strcmp(type, "Follow") == 0)
 947        objid = id;
 948    else
 949    if (strcmp(utype, "Follow") == 0)
 950        objid = actor;
 951
 952    notify_add(snac, type, utype, actor, objid != NULL ? objid : id, msg);
 953}
 954
 955/** messages **/
 956
 957xs_dict *msg_base(snac *snac, const char *type, const char *id,
 958                  const char *actor, const char *date, const char *object)
 959/* creates a base ActivityPub message */
 960{
 961    xs *did       = NULL;
 962    xs *published = NULL;
 963    xs *ntid      = tid(0);
 964    const char *obj_id;
 965
 966    if (xs_type(object) == XSTYPE_DICT)
 967        obj_id = xs_dict_get(object, "id");
 968    else
 969        obj_id = object;
 970
 971    /* generated values */
 972    if (date && strcmp(date, "@now") == 0) {
 973        published = xs_str_utctime(0, ISO_DATE_SPEC);
 974        date = published;
 975    }
 976
 977    if (id != NULL) {
 978        if (strcmp(id, "@dummy") == 0) {
 979            did = xs_fmt("%s/d/%s/%s", snac->actor, ntid, type);
 980
 981            id = did;
 982        }
 983        else
 984        if (strcmp(id, "@object") == 0) {
 985            if (obj_id != NULL) {
 986                did = xs_fmt("%s/%s_%s", obj_id, type, ntid);
 987                id = did;
 988            }
 989            else
 990                id = NULL;
 991        }
 992        else
 993        if (strcmp(id, "@wrapper") == 0) {
 994            /* like @object, but always generate the same id */
 995            if (object != NULL) {
 996                date = xs_dict_get(object, "published");
 997                did = xs_fmt("%s/%s", obj_id, type);
 998                id = did;
 999            }
1000            else
1001                id = NULL;
1002        }
1003    }
1004
1005    xs_dict *msg = xs_dict_new();
1006
1007    msg = xs_dict_append(msg, "@context", "https:/" "/www.w3.org/ns/activitystreams");
1008    msg = xs_dict_append(msg, "type",     type);
1009
1010    if (id != NULL)
1011        msg = xs_dict_append(msg, "id", id);
1012
1013    if (actor != NULL)
1014        msg = xs_dict_append(msg, "actor", actor);
1015
1016    if (date != NULL)
1017        msg = xs_dict_append(msg, "published", date);
1018
1019    if (object != NULL)
1020        msg = xs_dict_append(msg, "object", object);
1021
1022    return msg;
1023}
1024
1025
1026xs_dict *msg_collection(snac *snac, const char *id)
1027/* creates an empty OrderedCollection message */
1028{
1029    xs_dict *msg = msg_base(snac, "OrderedCollection", id, NULL, NULL, NULL);
1030    xs *ol = xs_list_new();
1031
1032    msg = xs_dict_append(msg, "attributedTo", snac->actor);
1033    msg = xs_dict_append(msg, "orderedItems", ol);
1034    msg = xs_dict_append(msg, "totalItems",   xs_stock(0));
1035
1036    return msg;
1037}
1038
1039
1040xs_dict *msg_accept(snac *snac, const xs_val *object, const char *to)
1041/* creates an Accept message (as a response to a Follow) */
1042{
1043    xs_dict *msg = msg_base(snac, "Accept", "@dummy", snac->actor, NULL, object);
1044
1045    msg = xs_dict_append(msg, "to", to);
1046
1047    return msg;
1048}
1049
1050
1051xs_dict *msg_update(snac *snac, const xs_dict *object)
1052/* creates an Update message */
1053{
1054    xs_dict *msg = msg_base(snac, "Update", "@object", snac->actor, "@now", object);
1055
1056    const char *type = xs_dict_get(object, "type");
1057
1058    if (strcmp(type, "Note") == 0) {
1059        msg = xs_dict_append(msg, "to", xs_dict_get(object, "to"));
1060        msg = xs_dict_append(msg, "cc", xs_dict_get(object, "cc"));
1061    }
1062    else
1063    if (strcmp(type, "Person") == 0) {
1064        msg = xs_dict_append(msg, "to", public_address);
1065
1066        /* also spam the people being followed, so that
1067           they have the newest information about who we are */
1068        xs *cc = following_list(snac);
1069
1070        msg = xs_dict_append(msg, "cc", cc);
1071    }
1072    else
1073        msg = xs_dict_append(msg, "to", public_address);
1074
1075    return msg;
1076}
1077
1078
1079xs_dict *msg_admiration(snac *snac, const char *object, const char *type)
1080/* creates a Like or Announce message */
1081{
1082    xs *a_msg    = NULL;
1083    xs_dict *msg = NULL;
1084    xs *wrk      = NULL;
1085
1086    /* call the object */
1087    timeline_request(snac, &object, &wrk, 0);
1088
1089    if (valid_status(object_get(object, &a_msg))) {
1090        xs *rcpts = xs_list_new();
1091        xs *o_md5 = xs_md5_hex(object, strlen(object));
1092        xs *id    = xs_fmt("%s/%s/%s", snac->actor, *type == 'L' ? "l" : "a", o_md5);
1093
1094        msg = msg_base(snac, type, id, snac->actor, "@now", object);
1095
1096        if (is_msg_public(a_msg))
1097            rcpts = xs_list_append(rcpts, public_address);
1098
1099        rcpts = xs_list_append(rcpts, get_atto(a_msg));
1100
1101        msg = xs_dict_append(msg, "to", rcpts);
1102    }
1103    else
1104        snac_log(snac, xs_fmt("msg_admiration cannot retrieve object %s", object));
1105
1106    return msg;
1107}
1108
1109
1110xs_dict *msg_repulsion(snac *user, const char *id, const char *type)
1111/* creates an Undo + admiration message */
1112{
1113    xs *a_msg    = NULL;
1114    xs_dict *msg = NULL;
1115
1116    if (valid_status(object_get(id, &a_msg))) {
1117        /* create a clone of the original admiration message */
1118        xs *object = msg_admiration(user, id, type);
1119
1120        /* delete the published date */
1121        object = xs_dict_del(object, "published");
1122
1123        /* create an undo message for this object */
1124        msg = msg_undo(user, object);
1125
1126        /* copy the 'to' field */
1127        msg = xs_dict_set(msg, "to", xs_dict_get(object, "to"));
1128    }
1129
1130    /* now we despise this */
1131    object_unadmire(id, user->actor, *type == 'L' ? 1 : 0);
1132
1133    return msg;
1134}
1135
1136
1137xs_dict *msg_actor(snac *snac)
1138/* create a Person message for this actor */
1139{
1140    xs *ctxt     = xs_list_new();
1141    xs *icon     = xs_dict_new();
1142    xs *keys     = xs_dict_new();
1143    xs *tags     = xs_list_new();
1144    xs *avtr     = NULL;
1145    xs *kid      = NULL;
1146    xs *f_bio    = NULL;
1147    xs_dict *msg = msg_base(snac, "Person", snac->actor, NULL, NULL, NULL);
1148    const char *p;
1149    int n;
1150
1151    /* change the @context (is this really necessary?) */
1152    ctxt = xs_list_append(ctxt, "https:/" "/www.w3.org/ns/activitystreams");
1153    ctxt = xs_list_append(ctxt, "https:/" "/w3id.org/security/v1");
1154    msg = xs_dict_set(msg, "@context",          ctxt);
1155
1156    msg = xs_dict_set(msg, "url",               snac->actor);
1157    msg = xs_dict_set(msg, "name",              xs_dict_get(snac->config, "name"));
1158    msg = xs_dict_set(msg, "preferredUsername", snac->uid);
1159    msg = xs_dict_set(msg, "published",         xs_dict_get(snac->config, "published"));
1160
1161    xs *f_bio_2 = not_really_markdown(xs_dict_get(snac->config, "bio"), NULL, &tags);
1162    f_bio = process_tags(snac, f_bio_2, &tags);
1163    msg = xs_dict_set(msg, "summary", f_bio);
1164    msg = xs_dict_set(msg, "tag", tags);
1165
1166    char *folders[] = { "inbox", "outbox", "followers", "following", "featured", NULL };
1167    for (n = 0; folders[n]; n++) {
1168        xs *f = xs_fmt("%s/%s", snac->actor, folders[n]);
1169        msg = xs_dict_set(msg, folders[n], f);
1170    }
1171
1172    p = xs_dict_get(snac->config, "avatar");
1173
1174    if (*p == '\0')
1175        avtr = xs_fmt("%s/susie.png", srv_baseurl);
1176    else
1177        avtr = xs_dup(p);
1178
1179    icon = xs_dict_append(icon, "type",         "Image");
1180    icon = xs_dict_append(icon, "mediaType",    xs_mime_by_ext(avtr));
1181    icon = xs_dict_append(icon, "url",          avtr);
1182    msg = xs_dict_set(msg, "icon", icon);
1183
1184    kid = xs_fmt("%s#main-key", snac->actor);
1185
1186    keys = xs_dict_append(keys, "id",           kid);
1187    keys = xs_dict_append(keys, "owner",        snac->actor);
1188    keys = xs_dict_append(keys, "publicKeyPem", xs_dict_get(snac->key, "public"));
1189    msg = xs_dict_set(msg, "publicKey", keys);
1190
1191    /* if the "bot" config field is set to true, change type to "Service" */
1192    if (xs_type(xs_dict_get(snac->config, "bot")) == XSTYPE_TRUE)
1193        msg = xs_dict_set(msg, "type", "Service");
1194
1195    /* add the header image, if there is one defined */
1196    const char *header = xs_dict_get(snac->config, "header");
1197    if (!xs_is_null(header)) {
1198        xs *d = xs_dict_new();
1199        d = xs_dict_append(d, "type",       "Image");
1200        d = xs_dict_append(d, "mediaType",  xs_mime_by_ext(header));
1201        d = xs_dict_append(d, "url",        header);
1202        msg = xs_dict_set(msg, "image", d);
1203    }
1204
1205    /* add the metadata as attachments of PropertyValue */
1206    const xs_dict *metadata = xs_dict_get(snac->config, "metadata");
1207    if (xs_type(metadata) == XSTYPE_DICT) {
1208        xs *attach = xs_list_new();
1209        const xs_str *k;
1210        const xs_str *v;
1211
1212        int c = 0;
1213        while (xs_dict_next(metadata, &k, &v, &c)) {
1214            xs *d = xs_dict_new();
1215
1216            xs *k2 = encode_html(k);
1217            xs *v2 = NULL;
1218
1219            if (xs_startswith(v, "https:/") || xs_startswith(v, "http:/")) {
1220                xs *t = encode_html(v);
1221                v2 = xs_fmt("<a href=\"%s\" rel=\"me\">%s</a>", t, t);
1222            }
1223            else
1224                v2 = encode_html(v);
1225
1226            d = xs_dict_append(d, "type",  "PropertyValue");
1227            d = xs_dict_append(d, "name",  k2);
1228            d = xs_dict_append(d, "value", v2);
1229
1230            attach = xs_list_append(attach, d);
1231        }
1232
1233        msg = xs_dict_set(msg, "attachment", attach);
1234    }
1235
1236    /* use shared inboxes? */
1237    if (xs_type(xs_dict_get(srv_config, "shared_inboxes")) == XSTYPE_TRUE) {
1238        xs *d = xs_dict_new();
1239        xs *si = xs_fmt("%s/shared-inbox", srv_baseurl);
1240        d = xs_dict_append(d, "sharedInbox", si);
1241        msg = xs_dict_set(msg, "endpoints", d);
1242    }
1243
1244    /* does this user have an aka? */
1245    const char *aka = xs_dict_get(snac->config, "alias");
1246    if (xs_type(aka) == XSTYPE_STRING && *aka) {
1247        xs *loaka = xs_list_append(xs_list_new(), aka);
1248
1249        msg = xs_dict_set(msg, "alsoKnownAs", loaka);
1250    }
1251
1252    return msg;
1253}
1254
1255
1256xs_dict *msg_create(snac *snac, const xs_dict *object)
1257/* creates a 'Create' message */
1258{
1259    xs_dict *msg = msg_base(snac, "Create", "@wrapper", snac->actor, NULL, object);
1260    const xs_val *v;
1261
1262    if ((v = get_atto(object)))
1263        msg = xs_dict_append(msg, "attributedTo", v);
1264
1265    if ((v = xs_dict_get(object, "cc")))
1266        msg = xs_dict_append(msg, "cc", v);
1267
1268    if ((v = xs_dict_get(object, "to")))
1269        msg = xs_dict_append(msg, "to", v);
1270    else
1271        msg = xs_dict_append(msg, "to", public_address);
1272
1273    return msg;
1274}
1275
1276
1277xs_dict *msg_undo(snac *snac, const xs_val *object)
1278/* creates an 'Undo' message */
1279{
1280    xs_dict *msg = msg_base(snac, "Undo", "@object", snac->actor, "@now", object);
1281    const char *to;
1282
1283    if (xs_type(object) == XSTYPE_DICT && (to = xs_dict_get(object, "object")))
1284        msg = xs_dict_append(msg, "to", to);
1285
1286    return msg;
1287}
1288
1289
1290xs_dict *msg_delete(snac *snac, const char *id)
1291/* creates a 'Delete' + 'Tombstone' for a local entry */
1292{
1293    xs *tomb = xs_dict_new();
1294    xs_dict *msg = NULL;
1295
1296    /* sculpt the tombstone */
1297    tomb = xs_dict_append(tomb, "type", "Tombstone");
1298    tomb = xs_dict_append(tomb, "id",   id);
1299
1300    /* now create the Delete */
1301    msg = msg_base(snac, "Delete", "@object", snac->actor, "@now", tomb);
1302
1303    msg = xs_dict_append(msg, "to", public_address);
1304
1305    return msg;
1306}
1307
1308
1309xs_dict *msg_follow(snac *snac, const char *q)
1310/* creates a 'Follow' message */
1311{
1312    xs *actor_o = NULL;
1313    xs *actor   = NULL;
1314    xs_dict *msg = NULL;
1315    int status;
1316
1317    xs *url_or_uid = xs_strip_i(xs_str_new(q));
1318
1319    if (xs_startswith(url_or_uid, "https:/") || xs_startswith(url_or_uid, "http:/"))
1320        actor = xs_dup(url_or_uid);
1321    else
1322    if (!valid_status(webfinger_request(url_or_uid, &actor, NULL)) || actor == NULL) {
1323        snac_log(snac, xs_fmt("cannot resolve user %s to follow", url_or_uid));
1324        return NULL;
1325    }
1326
1327    /* request the actor */
1328    status = actor_request(snac, actor, &actor_o);
1329
1330    if (valid_status(status)) {
1331        /* check if the actor is an alias */
1332        const char *r_actor = xs_dict_get(actor_o, "id");
1333
1334        if (r_actor && strcmp(actor, r_actor) != 0) {
1335            snac_log(snac, xs_fmt("actor to follow is an alias %s -> %s", actor, r_actor));
1336        }
1337
1338        msg = msg_base(snac, "Follow", "@dummy", snac->actor, NULL, r_actor);
1339    }
1340    else
1341        snac_log(snac, xs_fmt("cannot get actor to follow %s %d", actor, status));
1342
1343    return msg;
1344}
1345
1346
1347xs_dict *msg_note(snac *snac, const xs_str *content, const xs_val *rcpts,
1348                  const xs_str *in_reply_to, const xs_list *attach, int priv)
1349/* creates a 'Note' message */
1350{
1351    xs *ntid = tid(0);
1352    xs *id   = xs_fmt("%s/p/%s", snac->actor, ntid);
1353    xs *ctxt = NULL;
1354    xs *fc2  = NULL;
1355    xs *fc1  = NULL;
1356    xs *to   = NULL;
1357    xs *cc   = xs_list_new();
1358    xs *irt  = NULL;
1359    xs *tag  = xs_list_new();
1360    xs *atls = xs_list_new();
1361    xs_dict *msg = msg_base(snac, "Note", id, NULL, "@now", NULL);
1362    xs_list *p;
1363    const xs_val *v;
1364
1365    if (rcpts == NULL)
1366        to = xs_list_new();
1367    else {
1368        if (xs_type(rcpts) == XSTYPE_STRING) {
1369            to = xs_list_new();
1370            to = xs_list_append(to, rcpts);
1371        }
1372        else
1373            to = xs_dup(rcpts);
1374    }
1375
1376    /* format the content */
1377    fc2 = not_really_markdown(content, &atls, &tag);
1378
1379    if (in_reply_to != NULL && *in_reply_to) {
1380        xs *p_msg = NULL;
1381        xs *wrk   = NULL;
1382
1383        /* demand this thing */
1384        timeline_request(snac, &in_reply_to, &wrk, 0);
1385
1386        if (valid_status(object_get(in_reply_to, &p_msg))) {
1387            /* add this author as recipient */
1388            const char *a, *v;
1389
1390            if ((a = get_atto(p_msg)) && xs_list_in(to, a) == -1)
1391                to = xs_list_append(to, a);
1392
1393            /* add this author to the tag list as a mention */
1394            if (!xs_is_null(a)) {
1395                xs *l = xs_split(a, "/");
1396                xs *actor_o = NULL;
1397
1398                if (xs_list_len(l) > 3 && valid_status(object_get(a, &actor_o))) {
1399                    const char *uname = xs_dict_get(actor_o, "preferredUsername");
1400
1401                    if (!xs_is_null(uname) && *uname) {
1402                        xs *handle = xs_fmt("@%s@%s", uname, xs_list_get(l, 2));
1403
1404                        xs *t = xs_dict_new();
1405
1406                        t = xs_dict_append(t, "type", "Mention");
1407                        t = xs_dict_append(t, "href", a);
1408                        t = xs_dict_append(t, "name", handle);
1409
1410                        tag = xs_list_append(tag, t);
1411                    }
1412                }
1413            }
1414
1415            /* get the context, if there is one */
1416            if ((v = xs_dict_get(p_msg, "context")))
1417                ctxt = xs_dup(v);
1418
1419            /* propagate the conversation field, if there is one */
1420            if ((v = xs_dict_get(p_msg, "conversation")))
1421                msg = xs_dict_append(msg, "conversation", v);
1422
1423            /* if this message is public, ours will also be */
1424            if (!priv && is_msg_public(p_msg) && xs_list_in(to, public_address) == -1)
1425                to = xs_list_append(to, public_address);
1426        }
1427
1428        irt = xs_dup(in_reply_to);
1429    }
1430    else
1431        irt = xs_val_new(XSTYPE_NULL);
1432
1433    /* extract the mentions and hashtags and convert the content */
1434    fc1 = process_tags(snac, fc2, &tag);
1435
1436    /* create the attachment list, if there are any */
1437    if (!xs_is_null(attach)) {
1438        int c = 0;
1439        while (xs_list_next(attach, &v, &c)) {
1440            xs *d            = xs_dict_new();
1441            const char *url  = xs_list_get(v, 0);
1442            const char *alt  = xs_list_get(v, 1);
1443            const char *mime = xs_mime_by_ext(url);
1444
1445            d = xs_dict_append(d, "mediaType", mime);
1446            d = xs_dict_append(d, "url",       url);
1447            d = xs_dict_append(d, "name",      alt);
1448            d = xs_dict_append(d, "type",
1449                xs_startswith(mime, "image/") ? "Image" : "Document");
1450
1451            atls = xs_list_append(atls, d);
1452        }
1453    }
1454
1455    if (ctxt == NULL)
1456        ctxt = xs_fmt("%s#ctxt", id);
1457
1458    /* add all mentions to the cc */
1459    p = tag;
1460    while (xs_list_iter(&p, &v)) {
1461        if (xs_type(v) == XSTYPE_DICT) {
1462            const char *t;
1463
1464            if (!xs_is_null(t = xs_dict_get(v, "type")) && strcmp(t, "Mention") == 0) {
1465                if (!xs_is_null(t = xs_dict_get(v, "href")))
1466                    cc = xs_list_append(cc, t);
1467            }
1468        }
1469    }
1470
1471    /* no recipients? must be for everybody */
1472    if (!priv && xs_list_len(to) == 0)
1473        to = xs_list_append(to, public_address);
1474
1475    /* delete all cc recipients that also are in the to */
1476    p = to;
1477    while (xs_list_iter(&p, &v)) {
1478        int i;
1479
1480        if ((i = xs_list_in(cc, v)) != -1)
1481            cc = xs_list_del(cc, i);
1482    }
1483
1484    msg = xs_dict_append(msg, "attributedTo", snac->actor);
1485    msg = xs_dict_append(msg, "summary",      "");
1486    msg = xs_dict_append(msg, "content",      fc1);
1487    msg = xs_dict_append(msg, "context",      ctxt);
1488    msg = xs_dict_append(msg, "url",          id);
1489    msg = xs_dict_append(msg, "to",           to);
1490    msg = xs_dict_append(msg, "cc",           cc);
1491    msg = xs_dict_append(msg, "inReplyTo",    irt);
1492    msg = xs_dict_append(msg, "tag",          tag);
1493
1494    msg = xs_dict_append(msg, "sourceContent", content);
1495
1496    if (xs_list_len(atls))
1497        msg = xs_dict_append(msg, "attachment", atls);
1498
1499    return msg;
1500}
1501
1502
1503xs_dict *msg_ping(snac *user, const char *rcpt)
1504/* creates a Ping message (https://humungus.tedunangst.com/r/honk/v/tip/f/docs/ping.txt) */
1505{
1506    xs_dict *msg = msg_base(user, "Ping", "@dummy", user->actor, NULL, NULL);
1507
1508    msg = xs_dict_append(msg, "to", rcpt);
1509
1510    return msg;
1511}
1512
1513
1514xs_dict *msg_pong(snac *user, const char *rcpt, const char *object)
1515/* creates a Pong message (https://humungus.tedunangst.com/r/honk/v/tip/f/docs/ping.txt) */
1516{
1517    xs_dict *msg = msg_base(user, "Pong", "@dummy", user->actor, NULL, object);
1518
1519    msg = xs_dict_append(msg, "to", rcpt);
1520
1521    return msg;
1522}
1523
1524
1525xs_dict *msg_move(snac *user, const char *new_account)
1526/* creates a Move message (to move the user to new_account) */
1527{
1528    xs_dict *msg = msg_base(user, "Move", "@dummy", user->actor, NULL, user->actor);
1529
1530    msg = xs_dict_append(msg, "target", new_account);
1531
1532    return msg;
1533}
1534
1535
1536xs_dict *msg_question(snac *user, const char *content, xs_list *attach,
1537                      const xs_list *opts, int multiple, int end_secs)
1538/* creates a Question message */
1539{
1540    xs_dict *msg = msg_note(user, content, NULL, NULL, attach, 0);
1541    int max      = 8;
1542    xs_set seen;
1543
1544    msg = xs_dict_set(msg, "type", "Question");
1545
1546    /* make it non-editable */
1547    msg = xs_dict_del(msg, "sourceContent");
1548
1549    xs *o = xs_list_new();
1550    xs_list *p = (xs_list *)opts;
1551    const xs_str *v;
1552    xs *replies = xs_json_loads("{\"type\":\"Collection\",\"totalItems\":0}");
1553
1554    xs_set_init(&seen);
1555
1556    while (max && xs_list_iter(&p, &v)) {
1557        if (*v) {
1558            xs *v2 = xs_dup(v);
1559            xs *d  = xs_dict_new();
1560
1561            if (strlen(v2) > 60) {
1562                v2[60] = '\0';
1563                v2 = xs_str_cat(v2, "...");
1564            }
1565
1566            if (xs_set_add(&seen, v2) == 1) {
1567                d = xs_dict_append(d, "type",    "Note");
1568                d = xs_dict_append(d, "name",    v2);
1569                d = xs_dict_append(d, "replies", replies);
1570                o = xs_list_append(o, d);
1571
1572                max--;
1573            }
1574        }
1575    }
1576
1577    xs_set_free(&seen);
1578
1579    msg = xs_dict_append(msg, multiple ? "anyOf" : "oneOf", o);
1580
1581    /* set the end time */
1582    time_t t = time(NULL) + end_secs;
1583    xs *et = xs_str_utctime(t, ISO_DATE_SPEC);
1584
1585    msg = xs_dict_append(msg, "endTime", et);
1586
1587    return msg;
1588}
1589
1590
1591int update_question(snac *user, const char *id)
1592/* updates the poll counts */
1593{
1594    xs *msg   = NULL;
1595    xs *rcnt  = xs_dict_new();
1596    xs *lopts = xs_list_new();
1597    const xs_list *opts;
1598    xs_list *p;
1599    const xs_val *v;
1600
1601    /* get the object */
1602    if (!valid_status(object_get(id, &msg)))
1603        return -1;
1604
1605    /* closed? do nothing more */
1606    if (xs_dict_get(msg, "closed"))
1607        return -2;
1608
1609    /* get the options */
1610    if ((opts = xs_dict_get(msg, "oneOf")) == NULL &&
1611        (opts = xs_dict_get(msg, "anyOf")) == NULL)
1612        return -3;
1613
1614    /* fill the initial count */
1615    int c = 0;
1616    while (xs_list_next(opts, &v, &c)) {
1617        const char *name = xs_dict_get(v, "name");
1618        if (name) {
1619            lopts = xs_list_append(lopts, name);
1620            rcnt  = xs_dict_set(rcnt, name, xs_stock(0));
1621        }
1622    }
1623
1624    xs_set s;
1625    xs_set_init(&s);
1626
1627    /* iterate now the children (the votes) */
1628    xs *chld = object_children(id);
1629    p = chld;
1630    while (xs_list_iter(&p, &v)) {
1631        xs *obj = NULL;
1632
1633        if (!valid_status(object_get_by_md5(v, &obj)))
1634            continue;
1635
1636        const char *name = xs_dict_get(obj, "name");
1637        const char *atto = get_atto(obj);
1638
1639        if (name && atto) {
1640            /* get the current count */
1641            const xs_number *cnt = xs_dict_get(rcnt, name);
1642
1643            if (xs_type(cnt) == XSTYPE_NUMBER) {
1644                /* if it exists, increment */
1645                xs *ucnt = xs_number_new(xs_number_get(cnt) + 1);
1646                rcnt = xs_dict_set(rcnt, name, ucnt);
1647
1648                xs_set_add(&s, atto);
1649            }
1650        }
1651    }
1652
1653    xs *rcpts = xs_set_result(&s);
1654
1655    /* create a new list of options with their new counts */
1656    xs *nopts = xs_list_new();
1657    p = lopts;
1658    while (xs_list_iter(&p, &v)) {
1659        const xs_number *cnt = xs_dict_get(rcnt, v);
1660
1661        if (xs_type(cnt) == XSTYPE_NUMBER) {
1662            xs *d1 = xs_dict_new();
1663            xs *d2 = xs_dict_new();
1664
1665            d2 = xs_dict_append(d2, "type",       "Collection");
1666            d2 = xs_dict_append(d2, "totalItems", cnt);
1667
1668            d1 = xs_dict_append(d1, "type",    "Note");
1669            d1 = xs_dict_append(d1, "name",    v);
1670            d1 = xs_dict_append(d1, "replies", d2);
1671
1672            nopts = xs_list_append(nopts, d1);
1673        }
1674    }
1675
1676    /* update the list */
1677    msg = xs_dict_set(msg, xs_dict_get(msg, "oneOf") != NULL ? "oneOf" : "anyOf", nopts);
1678
1679    /* due date? */
1680    int closed = 0;
1681    const char *end_time = xs_dict_get(msg, "endTime");
1682    if (!xs_is_null(end_time)) {
1683        xs *now = xs_str_utctime(0, ISO_DATE_SPEC);
1684
1685        /* is now greater than the endTime? */
1686        if (strcmp(now, end_time) >= 0) {
1687            xs *et    = xs_dup(end_time);
1688            msg       = xs_dict_set(msg, "closed", et);
1689
1690            closed = 1;
1691        }
1692    }
1693
1694    /* update the count of voters */
1695    xs *vcnt = xs_number_new(xs_list_len(rcpts));
1696    msg = xs_dict_set(msg, "votersCount", vcnt);
1697    msg = xs_dict_set(msg, "cc", rcpts);
1698
1699    /* store */
1700    object_add_ow(id, msg);
1701
1702    snac_debug(user, 1, xs_fmt("recounted poll %s", id));
1703    timeline_touch(user);
1704
1705    /* send an update message to all voters */
1706    xs *u_msg = msg_update(user, msg);
1707    u_msg = xs_dict_set(u_msg, "cc", rcpts);
1708
1709    enqueue_message(user, u_msg);
1710
1711    if (closed) {
1712        xs *c_msg = msg_update(user, msg);
1713        notify(user, "Update", "Question", user->actor, c_msg);
1714    }
1715
1716    return 0;
1717}
1718
1719
1720/** queues **/
1721
1722int process_input_message(snac *snac, const xs_dict *msg, const xs_dict *req)
1723/* processes an ActivityPub message from the input queue */
1724/* return values: -1, fatal error; 0, transient error, retry;
1725   1, processed and done; 2, propagate to users (only when no user is set) */
1726{
1727    const char *actor = xs_dict_get(msg, "actor");
1728    const char *type  = xs_dict_get(msg, "type");
1729    xs *actor_o = NULL;
1730    int a_status;
1731    int do_notify = 0;
1732
1733    if (xs_is_null(actor) || *actor == '\0') {
1734        srv_debug(0, xs_fmt("malformed message (bad actor)"));
1735        return -1;
1736    }
1737
1738    /* question votes may not have a type */
1739    if (xs_is_null(type))
1740        type = "Note";
1741
1742    /* reject uninteresting messages right now */
1743    if (xs_match(type, "Add|View|Reject|Read|Remove")) {
1744        srv_debug(0, xs_fmt("Ignored message of type '%s'", type));
1745        return -1;
1746    }
1747
1748    const char *object, *utype;
1749
1750    object = xs_dict_get(msg, "object");
1751    if (object != NULL && xs_type(object) == XSTYPE_DICT)
1752        utype = xs_dict_get(object, "type");
1753    else
1754        utype = "(null)";
1755
1756    /* special case for Delete messages */
1757    if (strcmp(type, "Delete") == 0) {
1758        /* if the actor is not here, do not even try */
1759        if (!object_here(actor)) {
1760            srv_debug(1, xs_fmt("dropped 'Delete' message from unknown actor '%s'", actor));
1761            return -1;
1762        }
1763
1764        /* discard crap */
1765        if (xs_is_null(object)) {
1766            srv_log(xs_fmt("dropped 'Delete' message with invalid object from actor '%s'", actor));
1767            return -1;
1768        }
1769
1770        /* also discard if the object to be deleted is not here */
1771        const char *obj_id = object;
1772        if (xs_type(obj_id) == XSTYPE_DICT)
1773            obj_id = xs_dict_get(obj_id, "id");
1774
1775        if (!object_here(obj_id)) {
1776            srv_debug(1, xs_fmt("dropped 'Delete' message from unknown object '%s'", obj_id));
1777            return -1;
1778        }
1779    }
1780
1781    /* bring the actor */
1782    a_status = actor_request(snac, actor, &actor_o);
1783
1784    /* do not retry permanent failures */
1785    if (a_status == HTTP_STATUS_NOT_FOUND
1786        || a_status == HTTP_STATUS_GONE
1787        || a_status < 0) {
1788        srv_debug(1, xs_fmt("dropping message due to actor error %s %d", actor, a_status));
1789        return -1;
1790    }
1791
1792    if (!valid_status(a_status)) {
1793        /* do not retry 'Delete' messages */
1794        if (strcmp(type, "Delete") == 0) {
1795            srv_debug(1, xs_fmt("dropping 'Delete' message due to actor error %s %d", actor, a_status));
1796            return -1;
1797        }
1798
1799        /* other actor download errors */
1800
1801        /* the actor may require a signed request; propagate if no user is set */
1802        if (snac == NULL)
1803            return 2;
1804
1805        /* may need a retry */
1806        srv_debug(0, xs_fmt("error requesting actor %s %d -- retry later", actor, a_status));
1807        return 0;
1808    }
1809
1810    /* check the signature */
1811    xs *sig_err = NULL;
1812
1813    if (!check_signature(req, &sig_err)) {
1814        srv_log(xs_fmt("bad signature %s (%s)", actor, sig_err));
1815
1816        srv_archive_error("check_signature", sig_err, req, msg);
1817        return -1;
1818    }
1819
1820    /* if no user is set, no further checks can be done; propagate */
1821    if (snac == NULL)
1822        return 2;
1823
1824    /* reject messages that are not for this user */
1825    if (!is_msg_for_me(snac, msg)) {
1826        snac_debug(snac, 1, xs_fmt("message from %s of type '%s' not for us", actor, type));
1827
1828        return 1;
1829    }
1830
1831    /* if it's a DM from someone we don't follow, reject the message */
1832    if (xs_type(xs_dict_get(snac->config, "drop_dm_from_unknown")) == XSTYPE_TRUE) {
1833        if (strcmp(utype, "Note") == 0 && !is_msg_public(msg) &&
1834            !following_check(snac, actor)) {
1835            snac_log(snac, xs_fmt("DM rejected from unknown actor %s", actor));
1836
1837            return 1;
1838        }
1839    }
1840
1841    /* check the minimum acceptable account age */
1842    int min_account_age = xs_number_get(xs_dict_get(srv_config, "min_account_age"));
1843
1844    if (min_account_age > 0) {
1845        const char *actor_date = xs_dict_get(actor_o, "published");
1846        if (!xs_is_null(actor_date)) {
1847            time_t actor_t = xs_parse_iso_date(actor_date, 0);
1848
1849            if (actor_t < 950000000) {
1850                snac_log(snac, xs_fmt("rejected activity from %s (suspicious date, %s)",
1851                    actor, actor_date));
1852
1853                return 1;
1854            }
1855
1856            if (actor_t > 0) {
1857                int td = (int)(time(NULL) - actor_t);
1858
1859                snac_debug(snac, 2, xs_fmt("actor %s age: %d seconds", actor, td));
1860
1861                if (td < min_account_age) {
1862                    snac_log(snac, xs_fmt("rejected activity from %s (too new, %d seconds)",
1863                        actor, td));
1864
1865                    return 1;
1866                }
1867            }
1868        }
1869        else
1870            snac_debug(snac, 1, xs_fmt("warning: empty or null creation date for %s", actor));
1871    }
1872
1873    if (strcmp(type, "Follow") == 0) { /** **/
1874        if (!follower_check(snac, actor)) {
1875            /* ensure the actor object is here */
1876            if (!object_here(actor)) {
1877                xs *actor_obj = NULL;
1878                actor_request(snac, actor, &actor_obj);
1879                object_add(actor, actor_obj);
1880            }
1881
1882            xs *f_msg = xs_dup(msg);
1883            xs *reply = msg_accept(snac, f_msg, actor);
1884
1885            post_message(snac, actor, reply);
1886
1887            if (xs_is_null(xs_dict_get(f_msg, "published"))) {
1888                /* add a date if it doesn't include one (Mastodon) */
1889                xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
1890                f_msg = xs_dict_set(f_msg, "published", date);
1891            }
1892
1893            timeline_add(snac, xs_dict_get(f_msg, "id"), f_msg);
1894
1895            follower_add(snac, actor);
1896
1897            snac_log(snac, xs_fmt("new follower %s", actor));
1898            do_notify = 1;
1899        }
1900        else
1901            snac_log(snac, xs_fmt("repeated 'Follow' from %s", actor));
1902    }
1903    else
1904    if (strcmp(type, "Undo") == 0) { /** **/
1905        const char *id = xs_dict_get(object, "object");
1906
1907        if (xs_type(object) != XSTYPE_DICT)
1908            utype = "Follow";
1909
1910        if (strcmp(utype, "Follow") == 0) { /** **/
1911            if (id && strcmp(id, snac->actor) != 0)
1912                snac_debug(snac, 1, xs_fmt("Undo + Follow from %s not for us (%s)", actor, id));
1913            else {
1914                if (valid_status(follower_del(snac, actor))) {
1915                    snac_log(snac, xs_fmt("no longer following us %s", actor));
1916                    do_notify = 1;
1917                }
1918                else
1919                    snac_log(snac, xs_fmt("error deleting follower %s", actor));
1920            }
1921        }
1922        else
1923        if (strcmp(utype, "Like") == 0 || strcmp(utype, "EmojiReact") == 0) { /** **/
1924            int status = object_unadmire(id, actor, 1);
1925
1926            snac_log(snac, xs_fmt("Undo '%s' for %s %d", utype, id, status));
1927        }
1928        else
1929        if (strcmp(utype, "Announce") == 0) { /** **/
1930            int status = HTTP_STATUS_OK;
1931
1932            /* commented out: if a followed user boosts something that
1933               is requested and then unboosts, the post remains here,
1934               but with no apparent reason, and that is confusing */
1935            //status = object_unadmire(id, actor, 0);
1936
1937            snac_log(snac, xs_fmt("Unboost for %s %d", id, status));
1938        }
1939        else
1940            snac_debug(snac, 1, xs_fmt("ignored 'Undo' for object type '%s'", utype));
1941    }
1942    else
1943    if (strcmp(type, "Create") == 0) { /** **/
1944        if (is_muted(snac, actor)) {
1945            snac_log(snac, xs_fmt("ignored 'Create' + '%s' from muted actor %s", utype, actor));
1946            return 1;
1947        }
1948
1949        if (xs_match(utype, "Note|Article")) { /** **/
1950            const char *id          = xs_dict_get(object, "id");
1951            const char *in_reply_to = xs_dict_get(object, "inReplyTo");
1952            const char *atto        = get_atto(object);
1953            xs *wrk           = NULL;
1954
1955            if (xs_is_null(id))
1956                snac_log(snac, xs_fmt("malformed message: no 'id' field"));
1957            else
1958            if (xs_is_null(atto))
1959                snac_log(snac, xs_fmt("malformed message: no 'attributedTo' field"));
1960            else
1961            if (!xs_is_null(in_reply_to) && is_hidden(snac, in_reply_to)) {
1962                snac_debug(snac, 0, xs_fmt("dropped reply %s to hidden post %s", id, in_reply_to));
1963            }
1964            else {
1965                if (content_match("filter_reject.txt", object)) {
1966                    snac_log(snac, xs_fmt("rejected by content %s", id));
1967                    return 1;
1968                }
1969
1970                if (strcmp(actor, atto) != 0)
1971                    snac_log(snac, xs_fmt("SUSPICIOUS: actor != atto (%s != %s)", actor, atto));
1972
1973                timeline_request(snac, &in_reply_to, &wrk, 0);
1974
1975                if (timeline_add(snac, id, object)) {
1976                    snac_log(snac, xs_fmt("new '%s' %s %s", utype, actor, id));
1977                    do_notify = 1;
1978                }
1979
1980                /* if it has a "name" field, it may be a vote for a question */
1981                const char *name = xs_dict_get(object, "name");
1982
1983                if (!xs_is_null(name) && *name && !xs_is_null(in_reply_to) && *in_reply_to)
1984                    update_question(snac, in_reply_to);
1985            }
1986        }
1987        else
1988        if (strcmp(utype, "Question") == 0) { /**  **/
1989            const char *id = xs_dict_get(object, "id");
1990
1991            if (timeline_add(snac, id, object))
1992                snac_log(snac, xs_fmt("new 'Question' %s %s", actor, id));
1993        }
1994        else
1995        if (strcmp(utype, "Video") == 0) { /** **/
1996            const char *id = xs_dict_get(object, "id");
1997
1998            if (timeline_add(snac, id, object))
1999                snac_log(snac, xs_fmt("new 'Video' %s %s", actor, id));
2000        }
2001        else
2002            snac_debug(snac, 1, xs_fmt("ignored 'Create' for object type '%s'", utype));
2003    }
2004    else
2005    if (strcmp(type, "Accept") == 0) { /** **/
2006        if (strcmp(utype, "(null)") == 0) {
2007            const char *obj_id = xs_dict_get(msg, "object");
2008
2009            /* if the accepted object id is a string that may
2010               be created by us, it's a follow */
2011            if (xs_type(obj_id) == XSTYPE_STRING &&
2012                xs_startswith(obj_id, srv_baseurl) &&
2013                xs_endswith(obj_id, "/Follow"))
2014                utype = "Follow";
2015        }
2016
2017        if (strcmp(utype, "Follow") == 0) { /** **/
2018            if (following_check(snac, actor)) {
2019                following_add(snac, actor, msg);
2020                snac_log(snac, xs_fmt("confirmed follow from %s", actor));
2021            }
2022            else
2023                snac_log(snac, xs_fmt("spurious follow accept from %s", actor));
2024        }
2025        else
2026        if (strcmp(utype, "Create") == 0) {
2027            /* some implementations send Create confirmations, go figure */
2028            snac_debug(snac, 1, xs_dup("ignored 'Accept' + 'Create'"));
2029        }
2030        else {
2031            srv_archive_error("accept", "ignored Accept", req, msg);
2032            snac_debug(snac, 1, xs_fmt("ignored 'Accept' for object type '%s'", utype));
2033        }
2034    }
2035    else
2036    if (strcmp(type, "Like") == 0 || strcmp(type, "EmojiReact") == 0) { /** **/
2037        if (xs_type(object) == XSTYPE_DICT)
2038            object = xs_dict_get(object, "id");
2039
2040        if (timeline_admire(snac, object, actor, 1) == HTTP_STATUS_CREATED)
2041            snac_log(snac, xs_fmt("new '%s' %s %s", type, actor, object));
2042        else
2043            snac_log(snac, xs_fmt("repeated 'Like' from %s to %s", actor, object));
2044
2045        do_notify = 1;
2046    }
2047    else
2048    if (strcmp(type, "Announce") == 0) { /** **/
2049        if (xs_type(object) == XSTYPE_DICT)
2050            object = xs_dict_get(object, "id");
2051
2052        if (is_muted(snac, actor) && !xs_startswith(object, snac->actor))
2053            snac_log(snac, xs_fmt("dropped 'Announce' from muted actor %s", actor));
2054        else
2055        if (is_limited(snac, actor) && !xs_startswith(object, snac->actor))
2056            snac_log(snac, xs_fmt("dropped 'Announce' from limited actor %s", actor));
2057        else {
2058            xs *a_msg = NULL;
2059            xs *wrk   = NULL;
2060
2061            timeline_request(snac, &object, &wrk, 0);
2062
2063            if (valid_status(object_get(object, &a_msg))) {
2064                const char *who = get_atto(a_msg);
2065
2066                if (who && !is_muted(snac, who)) {
2067                    /* bring the actor */
2068                    xs *who_o = NULL;
2069
2070                    if (valid_status(actor_request(snac, who, &who_o))) {
2071                        if (timeline_admire(snac, object, actor, 0) == HTTP_STATUS_CREATED)
2072                            snac_log(snac, xs_fmt("new 'Announce' %s %s", actor, object));
2073                        else
2074                            snac_log(snac, xs_fmt("repeated 'Announce' from %s to %s",
2075                                actor, object));
2076
2077                        /* distribute the post with the actor as 'proxy' */
2078                        list_distribute(snac, actor, a_msg);
2079
2080                        do_notify = 1;
2081                    }
2082                    else
2083                        snac_debug(snac, 1, xs_fmt("dropped 'Announce' on actor request error %s", who));
2084                }
2085                else
2086                    snac_log(snac, xs_fmt("ignored 'Announce' about muted actor %s", who));
2087            }
2088            else
2089                snac_debug(snac, 2, xs_fmt("error requesting 'Announce' object %s", object));
2090        }
2091    }
2092    else
2093    if (strcmp(type, "Update") == 0) { /** **/
2094        if (xs_match(utype, "Person|Service")) { /** **/
2095            actor_add(actor, xs_dict_get(msg, "object"));
2096            timeline_touch(snac);
2097
2098            snac_log(snac, xs_fmt("updated actor %s", actor));
2099        }
2100        else
2101        if (xs_match(utype, "Note|Page|Article|Video")) { /** **/
2102            const char *id = xs_dict_get(object, "id");
2103
2104            if (object_here(id)) {
2105                object_add_ow(id, object);
2106                timeline_touch(snac);
2107
2108                snac_log(snac, xs_fmt("updated '%s' %s", utype, id));
2109            }
2110            else
2111                snac_log(snac, xs_fmt("dropped update for unknown '%s' %s", utype, id));
2112        }
2113        else
2114        if (strcmp(utype, "Question") == 0) { /** **/
2115            const char *id     = xs_dict_get(object, "id");
2116            const char *closed = xs_dict_get(object, "closed");
2117
2118            object_add_ow(id, object);
2119            timeline_touch(snac);
2120
2121            snac_log(snac, xs_fmt("%s poll %s", closed == NULL ? "updated" : "closed", id));
2122
2123            if (closed != NULL)
2124                do_notify = 1;
2125        }
2126        else {
2127            srv_archive_error("unsupported_update", "unsupported_update", req, msg);
2128
2129            snac_log(snac, xs_fmt("ignored 'Update' for object type '%s'", utype));
2130        }
2131    }
2132    else
2133    if (strcmp(type, "Delete") == 0) { /** **/
2134        if (xs_type(object) == XSTYPE_DICT)
2135            object = xs_dict_get(object, "id");
2136
2137        if (object_here(object)) {
2138            timeline_del(snac, object);
2139            snac_debug(snac, 1, xs_fmt("new 'Delete' %s %s", actor, object));
2140        }
2141        else
2142            snac_debug(snac, 1, xs_fmt("ignored 'Delete' for unknown object %s", object));
2143    }
2144    else
2145    if (strcmp(type, "Pong") == 0) { /** **/
2146        snac_log(snac, xs_fmt("'Pong' received from %s", actor));
2147    }
2148    else
2149    if (strcmp(type, "Ping") == 0) { /** **/
2150        snac_log(snac, xs_fmt("'Ping' requested from %s", actor));
2151
2152        xs *rsp = msg_pong(snac, actor, xs_dict_get(msg, "id"));
2153
2154        enqueue_output_by_actor(snac, rsp, actor, 0);
2155    }
2156    else
2157    if (strcmp(type, "Block") == 0) { /** **/
2158        snac_log(snac, xs_fmt("'Block' received from %s", actor));
2159
2160        /* should we MUTE the actor back? */
2161        /* mute(snac, actor); */
2162
2163        do_notify = 1;
2164    }
2165    else
2166    if (strcmp(type, "Move") == 0) { /** **/
2167        do_notify = 1;
2168
2169        const char *old_account = xs_dict_get(msg, "object");
2170        const char *new_account = xs_dict_get(msg, "target");
2171
2172        if (!xs_is_null(old_account) && !xs_is_null(new_account)) {
2173            if (following_check(snac, old_account)) {
2174                xs *n_actor = NULL;
2175
2176                if (valid_status(object_get(new_account, &n_actor))) {
2177                    const xs_list *aka = xs_dict_get(n_actor, "alsoKnownAs");
2178
2179                    if (xs_type(aka) == XSTYPE_LIST) {
2180                        if (xs_list_in(aka, old_account) != -1) {
2181                            /* all conditions met! */
2182
2183                            /* follow new account */
2184                            xs *f_msg = msg_follow(snac, new_account);
2185
2186                            if (f_msg != NULL) {
2187                                const char *new_actor = xs_dict_get(f_msg, "object");
2188                                following_add(snac, new_actor, f_msg);
2189                                enqueue_output_by_actor(snac, f_msg, new_actor, 0);
2190
2191                                snac_log(snac, xs_fmt("'Move': following %s", new_account));
2192                            }
2193
2194                            /* unfollow old account */
2195                            xs *of_msg = NULL;
2196
2197                            if (valid_status(following_get(snac, old_account, &of_msg))) {
2198                                xs *uf_msg = msg_undo(snac, xs_dict_get(of_msg, "object"));
2199                                following_del(snac, old_account);
2200                                enqueue_output_by_actor(snac, uf_msg, old_account, 0);
2201
2202                                snac_log(snac, xs_fmt("'Move': unfollowing %s", old_account));
2203                            }
2204                        }
2205                        else
2206                            snac_log(snac, xs_fmt("'Move' error: old actor %s not found in %s 'alsoKnownAs'",
2207                                old_account, new_account));
2208                    }
2209                    else
2210                        snac_log(snac, xs_fmt("'Move' error: cannot get %s 'alsoKnownAs'", new_account));
2211                }
2212                else {
2213                    snac_log(snac, xs_fmt("'Move' error: cannot get new actor %s", new_account));
2214
2215                    /* may be a server hiccup, retry later */
2216                    return 0;
2217                }
2218            }
2219            else
2220                snac_log(snac, xs_fmt("'Move' error: actor %s is not being followed", old_account));
2221        }
2222        else {
2223            snac_log(snac, xs_fmt("'Move' error: malformed message from %s", actor));
2224            srv_archive_error("move", "move", req, msg);
2225        }
2226    }
2227    else {
2228        srv_archive_error("unsupported_type", "unsupported_type", req, msg);
2229
2230        snac_debug(snac, 1, xs_fmt("process_input_message type '%s' ignored", type));
2231    }
2232
2233    if (do_notify) {
2234        notify(snac, type, utype, actor, msg);
2235
2236        timeline_touch(snac);
2237    }
2238
2239    return 1;
2240}
2241
2242
2243int send_email(const char *msg)
2244/* invoke sendmail with email headers and body in msg */
2245{
2246    FILE *f;
2247    int status;
2248    int fds[2];
2249    pid_t pid;
2250    if (pipe(fds) == -1) return -1;
2251    pid = vfork();
2252    if (pid == -1) return -1;
2253    else if (pid == 0) {
2254        dup2(fds[0], 0);
2255        close(fds[0]);
2256        close(fds[1]);
2257        execl("/usr/sbin/sendmail", "sendmail", "-t", (char *) NULL);
2258        _exit(1);
2259    }
2260    close(fds[0]);
2261    if ((f = fdopen(fds[1], "w")) == NULL) {
2262        close(fds[1]);
2263        return -1;
2264    }
2265    fprintf(f, "%s\n", msg);
2266    fclose(f);
2267    if (waitpid(pid, &status, 0) == -1) return -1;
2268    return status;
2269}
2270
2271
2272void process_user_queue_item(snac *snac, xs_dict *q_item)
2273/* processes an item from the user queue */
2274{
2275    const char *type;
2276    int queue_retry_max = xs_number_get(xs_dict_get(srv_config, "queue_retry_max"));
2277
2278    if ((type = xs_dict_get(q_item, "type")) == NULL)
2279        type = "output";
2280
2281    if (strcmp(type, "message") == 0) {
2282        const xs_dict *msg = xs_dict_get(q_item, "message");
2283        xs *rcpts = recipient_list(snac, msg, 1);
2284        xs_set inboxes;
2285        const xs_str *actor;
2286        int c;
2287
2288        xs_set_init(&inboxes);
2289
2290        /* iterate the recipients */
2291        c = 0;
2292        while (xs_list_next(rcpts, &actor, &c)) {
2293            xs *inbox = get_actor_inbox(actor, 1);
2294
2295            if (inbox != NULL) {
2296                /* add to the set and, if it's not there, send message */
2297                if (xs_set_add(&inboxes, inbox) == 1)
2298                    enqueue_output(snac, msg, inbox, 0, 0);
2299            }
2300            else
2301                snac_log(snac, xs_fmt("cannot find inbox for %s", actor));
2302        }
2303
2304        /* if it's a public note or question, send to the collected inboxes */
2305        if (xs_match(xs_dict_get_def(msg, "type", ""), "Create|Update") && is_msg_public(msg)) {
2306            if (xs_type(xs_dict_get(srv_config, "disable_inbox_collection")) != XSTYPE_TRUE) {
2307                xs *shibx = inbox_list();
2308                const xs_str *inbox;
2309
2310                c = 0;
2311                while (xs_list_next(shibx, &inbox, &c)) {
2312                    if (xs_set_add(&inboxes, inbox) == 1)
2313                        enqueue_output(snac, msg, inbox, 0, 0);
2314                }
2315            }
2316        }
2317
2318        xs_set_free(&inboxes);
2319    }
2320    else
2321    if (strcmp(type, "input") == 0) {
2322        /* process the message */
2323        const xs_dict *msg = xs_dict_get(q_item, "message");
2324        const xs_dict *req = xs_dict_get(q_item, "req");
2325        int retries  = xs_number_get(xs_dict_get(q_item, "retries"));
2326
2327        if (xs_is_null(msg))
2328            return;
2329
2330        if (!process_input_message(snac, msg, req)) {
2331            if (retries > queue_retry_max)
2332                snac_log(snac, xs_fmt("input giving up"));
2333            else {
2334                /* reenqueue */
2335                enqueue_input(snac, msg, req, retries + 1);
2336                snac_log(snac, xs_fmt("input requeue #%d", retries + 1));
2337            }
2338        }
2339    }
2340    else
2341    if (strcmp(type, "close_question") == 0) {
2342        /* the time for this question has ended */
2343        const char *id = xs_dict_get(q_item, "message");
2344
2345        if (!xs_is_null(id))
2346            update_question(snac, id);
2347    }
2348    else
2349    if (strcmp(type, "object_request") == 0) {
2350        const char *id = xs_dict_get(q_item, "message");
2351
2352        if (!xs_is_null(id)) {
2353            int status;
2354            xs *data = NULL;
2355
2356            status = activitypub_request(snac, id, &data);
2357
2358            if (valid_status(status))
2359                object_add_ow(id, data);
2360
2361            snac_debug(snac, 1, xs_fmt("object_request %s %d", id, status));
2362        }
2363    }
2364    else
2365    if (strcmp(type, "verify_links") == 0) {
2366        verify_links(snac);
2367    }
2368    else
2369    if (strcmp(type, "actor_refresh") == 0) {
2370        const char *actor = xs_dict_get(q_item, "actor");
2371        double mtime = object_mtime(actor);
2372
2373        /* only refresh if it was refreshed more than an hour ago */
2374        if (mtime + 3600.0 < (double) time(NULL)) {
2375            xs *actor_o = NULL;
2376            int status;
2377
2378            if (valid_status((status = activitypub_request(snac, actor, &actor_o))))
2379                actor_add(actor, actor_o);
2380            else
2381                object_touch(actor);
2382
2383            snac_log(snac, xs_fmt("actor_refresh %s %d", actor, status));
2384        }
2385    }
2386    else
2387        snac_log(snac, xs_fmt("unexpected user q_item type '%s'", type));
2388}
2389
2390
2391int process_user_queue(snac *snac)
2392/* processes a user's queue */
2393{
2394    int cnt = 0;
2395    xs *list = user_queue(snac);
2396
2397    xs_list *p = list;
2398    const xs_str *fn;
2399
2400    while (xs_list_iter(&p, &fn)) {
2401        xs *q_item = dequeue(fn);
2402
2403        if (q_item == NULL)
2404            continue;
2405
2406        process_user_queue_item(snac, q_item);
2407        cnt++;
2408    }
2409
2410    return cnt;
2411}
2412
2413
2414void process_queue_item(xs_dict *q_item)
2415/* processes an item from the global queue */
2416{
2417    const char *type = xs_dict_get(q_item, "type");
2418    int queue_retry_max = xs_number_get(xs_dict_get(srv_config, "queue_retry_max"));
2419
2420    if (strcmp(type, "output") == 0) {
2421        int status;
2422        const xs_str *inbox  = xs_dict_get(q_item, "inbox");
2423        const xs_str *keyid  = xs_dict_get(q_item, "keyid");
2424        const xs_str *seckey = xs_dict_get(q_item, "seckey");
2425        const xs_dict *msg   = xs_dict_get(q_item, "message");
2426        int retries    = xs_number_get(xs_dict_get(q_item, "retries"));
2427        int p_status   = xs_number_get(xs_dict_get(q_item, "p_status"));
2428        xs *payload    = NULL;
2429        int p_size     = 0;
2430        int timeout    = 0;
2431
2432        if (xs_is_null(inbox) || xs_is_null(msg) || xs_is_null(keyid) || xs_is_null(seckey)) {
2433            srv_log(xs_fmt("output message error: missing fields"));
2434            return;
2435        }
2436
2437        if (is_instance_blocked(inbox)) {
2438            srv_debug(0, xs_fmt("discarded output message to blocked instance %s", inbox));
2439            return;
2440        }
2441
2442        /* deliver (if previous error status was a timeout, try now longer) */
2443        if (p_status == 599)
2444            timeout = xs_number_get(xs_dict_get_def(srv_config, "queue_timeout_2", "8"));
2445        else
2446            timeout = xs_number_get(xs_dict_get_def(srv_config, "queue_timeout", "6"));
2447
2448        if (timeout == 0)
2449            timeout = 6;
2450
2451        status = send_to_inbox_raw(keyid, seckey, inbox, msg, &payload, &p_size, timeout);
2452
2453        if (payload) {
2454            if (p_size > 64) {
2455                /* trim the message */
2456                payload[64] = '\0';
2457                payload = xs_str_cat(payload, "...");
2458            }
2459
2460            /* strip ugly control characters */
2461            payload = xs_replace_i(payload, "\n", "");
2462            payload = xs_replace_i(payload, "\r", "");
2463
2464            if (*payload)
2465                payload = xs_str_wrap_i(" [", payload, "]");
2466        }
2467        else
2468            payload = xs_str_new(NULL);
2469
2470        srv_log(xs_fmt("output message: sent to inbox %s %d%s", inbox, status, payload));
2471
2472        if (!valid_status(status)) {
2473            retries++;
2474
2475            /* if it's not the first time it fails with a timeout,
2476               penalize the server by skipping one retry */
2477            if (p_status == status && status == HTTP_STATUS_CLIENT_CLOSED_REQUEST)
2478                retries++;
2479
2480            /* error sending; requeue? */
2481            if (status == HTTP_STATUS_BAD_REQUEST
2482                || status == HTTP_STATUS_NOT_FOUND
2483                || status == HTTP_STATUS_METHOD_NOT_ALLOWED
2484                || status == HTTP_STATUS_GONE
2485                || status == HTTP_STATUS_UNPROCESSABLE_CONTENT
2486                || status < 0)
2487                /* explicit error: discard */
2488                srv_log(xs_fmt("output message: fatal error %s %d", inbox, status));
2489            else
2490            if (retries > queue_retry_max)
2491                srv_log(xs_fmt("output message: giving up %s %d", inbox, status));
2492            else {
2493                /* requeue */
2494                enqueue_output_raw(keyid, seckey, msg, inbox, retries, status);
2495                srv_log(xs_fmt("output message: requeue %s #%d", inbox, retries));
2496            }
2497        }
2498    }
2499    else
2500    if (strcmp(type, "email") == 0) {
2501        /* send this email */
2502        const xs_str *msg = xs_dict_get(q_item, "message");
2503        int retries = xs_number_get(xs_dict_get(q_item, "retries"));
2504
2505        if (!send_email(msg))
2506            srv_debug(1, xs_fmt("email message sent"));
2507        else {
2508            retries++;
2509
2510            if (retries > queue_retry_max)
2511                srv_log(xs_fmt("email giving up (errno: %d)", errno));
2512            else {
2513                /* requeue */
2514                srv_log(xs_fmt(
2515                    "email requeue #%d (errno: %d)", retries, errno));
2516
2517                enqueue_email(msg, retries);
2518            }
2519        }
2520    }
2521    else
2522    if (strcmp(type, "telegram") == 0) {
2523        /* send this via telegram */
2524        const char *bot   = xs_dict_get(q_item, "bot");
2525        const char *msg   = xs_dict_get(q_item, "message");
2526        xs *chat_id = xs_dup(xs_dict_get(q_item, "chat_id"));
2527        int status  = 0;
2528
2529        /* chat_id must start with a - */
2530        if (!xs_startswith(chat_id, "-"))
2531            chat_id = xs_str_wrap_i("-", chat_id, NULL);
2532
2533        xs *url  = xs_fmt("https:/" "/api.telegram.org/bot%s/sendMessage", bot);
2534        xs *body = xs_fmt("{\"chat_id\":%s,\"text\":\"%s\"}", chat_id, msg);
2535
2536        xs *headers = xs_dict_new();
2537        headers = xs_dict_append(headers, "content-type", "application/json");
2538
2539        xs *rsp = xs_http_request("POST", url, headers,
2540                                   body, strlen(body), &status, NULL, NULL, 0);
2541        rsp = xs_free(rsp);
2542
2543        srv_debug(0, xs_fmt("telegram post %d", status));
2544    }
2545    else
2546    if (strcmp(type, "ntfy") == 0) {
2547        /* send this via ntfy */
2548        const char *ntfy_server   = xs_dict_get(q_item, "ntfy_server");
2549        const char *msg   = xs_dict_get(q_item, "message");
2550        const char *ntfy_token   = xs_dict_get(q_item, "ntfy_token");
2551        int status  = 0;
2552
2553        xs *url  = xs_fmt("%s", ntfy_server);
2554        xs *body = xs_fmt("%s", msg);
2555
2556        xs *headers = xs_dict_new();
2557        headers = xs_dict_append(headers, "content-type", "text/plain");
2558        // Append the Authorization header only if ntfy_token is not NULL
2559         if (ntfy_token != NULL) {
2560             headers = xs_dict_append(headers, "Authorization", xs_fmt("Bearer %s", ntfy_token));
2561             }
2562
2563        xs *rsp = xs_http_request("POST", url, headers,
2564                                   body, strlen(body), &status, NULL, NULL, 0);
2565        rsp = xs_free(rsp);
2566
2567        srv_debug(0, xs_fmt("ntfy post %d", status));
2568    }
2569    else
2570    if (strcmp(type, "purge") == 0) {
2571        srv_log(xs_dup("purge start"));
2572
2573        purge_all();
2574
2575        srv_log(xs_dup("purge end"));
2576    }
2577    else
2578    if (strcmp(type, "input") == 0) {
2579        const xs_dict *msg = xs_dict_get(q_item, "message");
2580        const xs_dict *req = xs_dict_get(q_item, "req");
2581        int retries  = xs_number_get(xs_dict_get(q_item, "retries"));
2582
2583        /* do some instance-level checks */
2584        int r = process_input_message(NULL, msg, req);
2585
2586        if (r == 0) {
2587            /* transient error? retry */
2588            if (retries > queue_retry_max)
2589                srv_log(xs_fmt("shared input giving up"));
2590            else {
2591                /* reenqueue */
2592                enqueue_shared_input(msg, req, retries + 1);
2593                srv_log(xs_fmt("shared input requeue #%d", retries + 1));
2594            }
2595        }
2596        else
2597        if (r == 2) {
2598            /* redistribute the input message to all users */
2599            const char *ntid = xs_dict_get(q_item, "ntid");
2600            xs *tmpfn  = xs_fmt("%s/tmp/%s.json", srv_basedir, ntid);
2601            FILE *f;
2602
2603            if ((f = fopen(tmpfn, "w")) != NULL) {
2604                xs_json_dump(q_item, 4, f);
2605                fclose(f);
2606            }
2607
2608            xs *users = user_list();
2609            xs_list *p = users;
2610            const char *v;
2611            int cnt = 0;
2612
2613            while (xs_list_iter(&p, &v)) {
2614                snac user;
2615
2616                if (user_open(&user, v)) {
2617                    if (is_msg_for_me(&user, msg)) {
2618                        xs *fn = xs_fmt("%s/queue/%s.json", user.basedir, ntid);
2619
2620                        snac_debug(&user, 1,
2621                            xs_fmt("enqueue_input (from shared inbox) %s", xs_dict_get(msg, "id")));
2622
2623                        if (link(tmpfn, fn) < 0)
2624                            srv_log(xs_fmt("link(%s, %s) error", tmpfn, fn));
2625
2626                        cnt++;
2627                    }
2628
2629                    user_free(&user);
2630                }
2631            }
2632
2633            unlink(tmpfn);
2634
2635            if (cnt == 0) {
2636                srv_debug(1, xs_fmt("no valid recipients for %s", xs_dict_get(msg, "id")));
2637            }
2638        }
2639    }
2640    else
2641        srv_log(xs_fmt("unexpected q_item type '%s'", type));
2642}
2643
2644
2645int process_queue(void)
2646/* processes the global queue */
2647{
2648    int cnt = 0;
2649    xs *list = queue();
2650
2651    xs_list *p = list;
2652    const xs_str *fn;
2653
2654    while (xs_list_iter(&p, &fn)) {
2655        xs *q_item = dequeue(fn);
2656
2657        if (q_item != NULL) {
2658            job_post(q_item, 0);
2659            cnt++;
2660        }
2661    }
2662
2663    return cnt;
2664}
2665
2666
2667/** account migration **/
2668
2669int migrate_account(snac *user)
2670/* migrates this account to a new one (stored in the 'alias' user field) */
2671{
2672    const char *new_account = xs_dict_get(user->config, "alias");
2673
2674    if (xs_type(new_account) != XSTYPE_STRING) {
2675        snac_log(user, xs_fmt("Cannot migrate: alias (destination account) not set"));
2676        return 1;
2677    }
2678
2679    xs *new_actor = NULL;
2680    int status;
2681
2682    if (!valid_status(status = activitypub_request(user, new_account, &new_actor))) {
2683        snac_log(user, xs_fmt("Cannot migrate: error requesting actor %s %d", new_account, status));
2684        return 1;
2685    }
2686
2687    actor_add(new_account, new_actor);
2688
2689    const char *loaka = xs_dict_get(new_actor, "alsoKnownAs");
2690
2691    if (xs_type(loaka) != XSTYPE_LIST) {
2692        snac_log(user, xs_fmt("Cannot migrate: destination account doesn't have any aliases"));
2693        return 1;
2694    }
2695
2696    if (xs_list_in(loaka, user->actor) == -1) {
2697        snac_log(user, xs_fmt("Cannot migrate: destination account doesn't have this one as an alias"));
2698        return 1;
2699    }
2700
2701    xs *move = msg_move(user, new_account);
2702    xs *fwers = follower_list(user);
2703
2704    const char *actor;
2705    xs_list_foreach(fwers, actor) {
2706        /* get the actor inbox, excluding the shared one */
2707        xs *inbox = get_actor_inbox(actor, 0);
2708
2709        if (xs_is_null(inbox))
2710            snac_log(user, xs_fmt("migrate_account: cannot get inbox for actor %s", actor));
2711        else
2712            enqueue_output(user, move, inbox, 0, 0);
2713    }
2714
2715    return 0;
2716}
2717
2718
2719/** HTTP handlers */
2720
2721int activitypub_get_handler(const xs_dict *req, const char *q_path,
2722                            char **body, int *b_size, char **ctype)
2723{
2724    int status = HTTP_STATUS_OK;
2725    const char *accept = xs_dict_get(req, "accept");
2726    snac snac;
2727    xs *msg = NULL;
2728
2729    if (accept == NULL)
2730        return 0;
2731
2732    if (xs_str_in(accept, "application/activity+json") == -1 &&
2733        xs_str_in(accept, "application/ld+json") == -1)
2734        return 0;
2735
2736    xs *l = xs_split_n(q_path, "/", 2);
2737    const char *uid;
2738    const char *p_path;
2739
2740    uid = xs_list_get(l, 1);
2741    if (!user_open(&snac, uid)) {
2742        /* invalid user */
2743        srv_debug(1, xs_fmt("activitypub_get_handler bad user %s", uid));
2744        return HTTP_STATUS_NOT_FOUND;
2745    }
2746
2747    p_path = xs_list_get(l, 2);
2748
2749    *ctype  = "application/activity+json";
2750
2751    if (p_path == NULL) {
2752        /* if there was no component after the user, it's an actor request */
2753        msg = msg_actor(&snac);
2754        *ctype = "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"";
2755
2756        const char *ua = xs_dict_get(req, "user-agent");
2757
2758        snac_debug(&snac, 0, xs_fmt("serving actor [%s]", ua ? ua : "No UA"));
2759    }
2760    else
2761    if (strcmp(p_path, "outbox") == 0 || strcmp(p_path, "featured") == 0) {
2762        xs *id = xs_fmt("%s/%s", snac.actor, p_path);
2763        xs *list = xs_list_new();
2764        msg = msg_collection(&snac, id);
2765        const char *v;
2766        int tc = 0;
2767
2768        /* get the public outbox or the pinned list */
2769        xs *elems = *p_path == 'o' ? timeline_simple_list(&snac, "public", 0, 20) : pinned_list(&snac);
2770
2771        while (xs_list_next(elems, &v, &tc)) {
2772            xs *i = NULL;
2773
2774            if (valid_status(object_get_by_md5(v, &i))) {
2775                const char *type = xs_dict_get(i, "type");
2776                const char *id   = xs_dict_get(i, "id");
2777
2778                if (type && id && strcmp(type, "Note") == 0 && xs_startswith(id, snac.actor)) {
2779                    xs *c_msg = msg_create(&snac, i);
2780                    list = xs_list_append(list, c_msg);
2781                }
2782            }
2783        }
2784
2785        /* replace the 'orderedItems' with the latest posts */
2786        xs *items = xs_number_new(xs_list_len(list));
2787        msg = xs_dict_set(msg, "orderedItems", list);
2788        msg = xs_dict_set(msg, "totalItems",   items);
2789    }
2790    else
2791    if (strcmp(p_path, "followers") == 0 || strcmp(p_path, "following") == 0) {
2792        xs *id = xs_fmt("%s/%s", snac.actor, p_path);
2793        msg = msg_collection(&snac, id);
2794    }
2795    else
2796    if (xs_startswith(p_path, "p/")) {
2797        xs *id = xs_fmt("%s/%s", snac.actor, p_path);
2798
2799        status = object_get(id, &msg);
2800
2801        /* don't return non-public objects */
2802        if (valid_status(status) && !is_msg_public(msg))
2803            status = HTTP_STATUS_NOT_FOUND;
2804    }
2805    else
2806        status = HTTP_STATUS_NOT_FOUND;
2807
2808    if (status == HTTP_STATUS_OK && msg != NULL) {
2809        *body   = xs_json_dumps(msg, 4);
2810        *b_size = strlen(*body);
2811    }
2812
2813    snac_debug(&snac, 1, xs_fmt("activitypub_get_handler serving %s %d", q_path, status));
2814
2815    user_free(&snac);
2816
2817    return status;
2818}
2819
2820
2821int activitypub_post_handler(const xs_dict *req, const char *q_path,
2822                             char *payload, int p_size,
2823                             char **body, int *b_size, char **ctype)
2824/* processes an input message */
2825{
2826    (void)b_size;
2827
2828    int status = HTTP_STATUS_ACCEPTED;
2829    const char *i_ctype = xs_dict_get(req, "content-type");
2830    snac snac;
2831    const char *v;
2832
2833    if (i_ctype == NULL) {
2834        *body  = xs_str_new("no content-type");
2835        *ctype = "text/plain";
2836        return HTTP_STATUS_BAD_REQUEST;
2837    }
2838
2839    if (xs_is_null(payload)) {
2840        *body  = xs_str_new("no payload");
2841        *ctype = "text/plain";
2842        return HTTP_STATUS_BAD_REQUEST;
2843    }
2844
2845    if (xs_str_in(i_ctype, "application/activity+json") == -1 &&
2846        xs_str_in(i_ctype, "application/ld+json") == -1)
2847        return 0;
2848
2849    /* decode the message */
2850    xs *msg = xs_json_loads(payload);
2851    const char *id = xs_dict_get(msg, "id");
2852
2853    if (msg == NULL) {
2854        srv_log(xs_fmt("activitypub_post_handler JSON error %s", q_path));
2855
2856        srv_archive_error("activitypub_post_handler", "JSON error", req, payload);
2857
2858        *body  = xs_str_new("JSON error");
2859        *ctype = "text/plain";
2860        return HTTP_STATUS_BAD_REQUEST;
2861    }
2862
2863    if (id && is_instance_blocked(id)) {
2864        srv_debug(1, xs_fmt("full instance block for %s", id));
2865
2866        *body  = xs_str_new("blocked");
2867        *ctype = "text/plain";
2868        return HTTP_STATUS_FORBIDDEN;
2869    }
2870
2871    /* get the user and path */
2872    xs *l = xs_split_n(q_path, "/", 2);
2873
2874    if (xs_list_len(l) == 2 && strcmp(xs_list_get(l, 1), "shared-inbox") == 0) {
2875        enqueue_shared_input(msg, req, 0);
2876        return HTTP_STATUS_ACCEPTED;
2877    }
2878
2879    if (xs_list_len(l) != 3 || strcmp(xs_list_get(l, 2), "inbox") != 0) {
2880        /* strange q_path */
2881        srv_debug(1, xs_fmt("activitypub_post_handler unsupported path %s", q_path));
2882        return HTTP_STATUS_NOT_FOUND;
2883    }
2884
2885    const char *uid = xs_list_get(l, 1);
2886    if (!user_open(&snac, uid)) {
2887        /* invalid user */
2888        srv_debug(1, xs_fmt("activitypub_post_handler bad user %s", uid));
2889        return HTTP_STATUS_NOT_FOUND;
2890    }
2891
2892    /* if it has a digest, check it now, because
2893       later the payload won't be exactly the same */
2894    if ((v = xs_dict_get(req, "digest")) != NULL) {
2895        xs *s1 = xs_sha256_base64(payload, p_size);
2896        xs *s2 = xs_fmt("SHA-256=%s", s1);
2897
2898        if (strcmp(s2, v) != 0) {
2899            srv_log(xs_fmt("digest check FAILED"));
2900
2901            *body  = xs_str_new("bad digest");
2902            *ctype = "text/plain";
2903            status = HTTP_STATUS_BAD_REQUEST;
2904        }
2905    }
2906
2907    /* if the message is from a muted actor, reject it right now */
2908    if (!xs_is_null(v = xs_dict_get(msg, "actor")) && *v) {
2909        if (is_muted(&snac, v)) {
2910            snac_log(&snac, xs_fmt("rejected message from MUTEd actor %s", v));
2911
2912            *body  = xs_str_new("rejected");
2913            *ctype = "text/plain";
2914            status = HTTP_STATUS_FORBIDDEN;
2915        }
2916    }
2917
2918    if (valid_status(status)) {
2919        enqueue_input(&snac, msg, req, 0);
2920        *ctype = "application/activity+json";
2921    }
2922
2923    user_free(&snac);
2924
2925    return status;
2926}