2.92 activitypub.c
   1/* snac - A simple, minimalistic ActivityPub instance */
   2/* copyright (c) 2022 - 2026 grunfink et al. / MIT license */
   3
   4#include "xs.h"
   5#include "xs_json.h"
   6#include "xs_curl.h"
   7#include "xs_url.h"
   8#include "xs_mime.h"
   9#include "xs_openssl.h"
  10#include "xs_regex.h"
  11#include "xs_time.h"
  12#include "xs_set.h"
  13#include "xs_match.h"
  14#include "xs_unicode.h"
  15#include "xs_webmention.h"
  16#include "xs_http.h"
  17
  18#include "snac.h"
  19
  20#include <stddef.h>
  21#include <sys/wait.h>
  22
  23const char * const public_address = "https:/" "/www.w3.org/ns/activitystreams#Public";
  24
  25/* susie.png */
  26
  27const char * const susie =
  28    "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  29    "CEkxzAAAAUUlEQVQoz43R0QkAMQwCUDdw/y3dwE"
  30    "vsvzlL4X1IoQkAisKmwfAFT3RgJHbQezpSRoXEq"
  31    "eqCL9BJBf7h3QbOCCxV5EVWMEMwG7K1/WODtlvx"
  32    "AYTtEsDU9F34AAAAAElFTkSuQmCC";
  33
  34const char * const susie_cool =
  35    "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  36    "CEkxzAAAAV0lEQVQoz43RwQ3AMAwCQDZg/y3ZgN"
  37    "qo3+JaedwDOUQBQFHYaTB8wTM6sGl2cMPu+DFzn"
  38    "+ZcgN7wF7ZVihXkfSlWIVzIA6dbQzaygllpNuTX"
  39    "ZmmFNlvxADX1+o0cUPMbAAAAAElFTkSuQmCC";
  40
  41const char * const susie_muertos =
  42    "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  43    "CEkxzAAAAV0lEQVQoz4XQsQ0AMQxCUW/A/lv+DT"
  44    "ic6zGRolekIMyMELNp8PiCEw6Q4w4NoAt53IH5m"
  45    "xXksrZYgZwJrIox+Z8vJAfe2lCxG6AK7eKkWcEb"
  46    "QHbF617xAQatAAD7jJHUAAAAAElFTkSuQmCC";
  47
  48
  49const char *default_avatar_base64(void)
  50/* returns the default avatar in base64 */
  51{
  52    time_t t = time(NULL);
  53    struct tm tm;
  54    const char *p = susie;
  55
  56    gmtime_r(&t, &tm);
  57
  58    if (tm.tm_mon == 10 && tm.tm_mday == 2)
  59        p = susie_muertos;
  60    else
  61    if (tm.tm_wday == 0 || tm.tm_wday == 6)
  62        p = susie_cool;
  63
  64    return p;
  65}
  66
  67
  68int activitypub_request(snac *user, const char *url, xs_dict **data)
  69/* request an object */
  70{
  71    int status = 0;
  72    xs *response = NULL;
  73    xs *payload = NULL;
  74    int p_size;
  75    const char *ctype;
  76
  77    *data = NULL;
  78
  79    if (user != NULL) {
  80        /* get from the net */
  81        response = http_signed_request(user, "GET", url,
  82            NULL, NULL, 0, &status, &payload, &p_size, 0);
  83    }
  84
  85    if (status == 0 || (status >= 500 && status <= 599)) {
  86        /* I found an instance running Misskey that returned
  87           500 on signed messages but returned the object
  88           perfectly without signing (?), so why not try */
  89        xs_free(response);
  90
  91        xs *hdrs = xs_dict_new();
  92        hdrs = xs_dict_append(hdrs, "accept",     "application/activity+json");
  93        hdrs = xs_dict_append(hdrs, "user-agent", USER_AGENT);
  94
  95        response = xs_http_request("GET", url, hdrs,
  96            NULL, 0, &status, &payload, &p_size, 0);
  97    }
  98
  99    if (valid_status(status)) {
 100        /* ensure it's ActivityPub data */
 101        ctype = xs_dict_get(response, "content-type");
 102
 103        if (xs_is_null(ctype))
 104            status = HTTP_STATUS_BAD_REQUEST;
 105        else
 106        if (xs_str_in(ctype, "application/activity+json") != -1 ||
 107            xs_str_in(ctype, "application/ld+json") != -1) {
 108
 109            /* if there is no payload, fail */
 110            if (xs_is_null(payload))
 111                status = HTTP_STATUS_BAD_REQUEST;
 112            else
 113                *data = xs_json_loads(payload);
 114        }
 115        else
 116            status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
 117    }
 118
 119    return status;
 120}
 121
 122
 123static xs_dict *actor_get_collections(snac *user, xs_dict *actor, int throttle)
 124/* fetches follower/following/statuses counts from an actor's collections and adds them to the actor object */
 125{
 126    /* only fetch if counts are not already present in the actor object */
 127    const xs_number *existing_followers = xs_dict_get(actor, "followers_count");
 128    const xs_number *existing_following = xs_dict_get(actor, "following_count");
 129    const xs_number *existing_statuses = xs_dict_get(actor, "statuses_count");
 130
 131    /* skip if we already have all counts */
 132    if (xs_type(existing_followers) == XSTYPE_NUMBER &&
 133        xs_type(existing_following) == XSTYPE_NUMBER &&
 134        xs_type(existing_statuses) == XSTYPE_NUMBER) {
 135        return actor;
 136    }
 137
 138    /* CRITICAL: duplicate URLs BEFORE any xs_dict_set calls, as xs_dict_set can reallocate the dict */
 139    xs *followers_url = xs_dup(xs_dict_get(actor, "followers"));
 140    xs *following_url = xs_dup(xs_dict_get(actor, "following"));
 141    xs *outbox_url = xs_dup(xs_dict_get(actor, "outbox"));
 142
 143    /* only fetch followers count if not already present */
 144    if (xs_type(existing_followers) != XSTYPE_NUMBER && !xs_is_null(followers_url)) {
 145        xs *followers_coll = NULL;
 146        if (valid_status(activitypub_request(user, followers_url, &followers_coll))) {
 147            const xs_number *total = xs_dict_get(followers_coll, "totalItems");
 148            if (xs_type(total) == XSTYPE_NUMBER) {
 149                xs *total_copy = xs_dup(total);
 150                actor = xs_dict_set(actor, "followers_count", total_copy);
 151            }
 152        }
 153        /* throttle to prevent resource exhaustion on low-power devices */
 154        if (throttle)
 155            usleep(100000); /* 100ms delay between requests */
 156    }
 157
 158    /* only fetch following count if not already present */
 159    if (xs_type(existing_following) != XSTYPE_NUMBER && !xs_is_null(following_url)) {
 160        xs *following_coll = NULL;
 161        if (valid_status(activitypub_request(user, following_url, &following_coll))) {
 162            const xs_number *total = xs_dict_get(following_coll, "totalItems");
 163            if (xs_type(total) == XSTYPE_NUMBER) {
 164                xs *total_copy = xs_dup(total);
 165                actor = xs_dict_set(actor, "following_count", total_copy);
 166            }
 167        }
 168        /* throttle to prevent resource exhaustion on low-power devices */
 169        if (throttle)
 170            usleep(100000); /* 100ms delay between requests */
 171    }
 172
 173    /* only fetch statuses count if not already present */
 174    if (xs_type(existing_statuses) != XSTYPE_NUMBER && !xs_is_null(outbox_url)) {
 175        xs *outbox_coll = NULL;
 176        if (valid_status(activitypub_request(user, outbox_url, &outbox_coll))) {
 177            const xs_number *total = xs_dict_get(outbox_coll, "totalItems");
 178            if (xs_type(total) == XSTYPE_NUMBER) {
 179                xs *total_copy = xs_dup(total);
 180                actor = xs_dict_set(actor, "statuses_count", total_copy);
 181            }
 182        }
 183        /* throttle to prevent resource exhaustion on low-power devices */
 184        if (throttle)
 185            usleep(100000); /* 100ms delay between requests */
 186    }
 187
 188    return actor;
 189}
 190
 191
 192int actor_request(snac *user, const char *actor, xs_dict **data)
 193/* request an actor */
 194{
 195    int status;
 196    xs *payload = NULL;
 197
 198    if (data)
 199        *data = NULL;
 200
 201    /* get from disk first */
 202    status = actor_get_refresh(user, actor, data);
 203
 204    if (!valid_status(status)) {
 205        /* actor data non-existent: get from the net */
 206        status = activitypub_request(user, actor, &payload);
 207
 208        if (valid_status(status)) {
 209            /* fetch collection counts when initially fetching an actor (no throttle) */
 210            payload = actor_get_collections(user, payload, 0);
 211
 212            /* renew data */
 213            status = actor_add(actor, payload);
 214
 215            if (data != NULL) {
 216                *data   = payload;
 217                payload = NULL;
 218            }
 219        }
 220        else
 221            srv_debug(1, xs_fmt("actor_request error %s %d", actor, status));
 222    }
 223
 224    /* collect the (presumed) shared inbox in this actor */
 225    if (xs_type(xs_dict_get(srv_config, "disable_inbox_collection")) != XSTYPE_TRUE) {
 226        if (valid_status(status) && data && *data)
 227            inbox_add_by_actor(*data);
 228    }
 229
 230    return status;
 231}
 232
 233
 234const char *get_atto(const xs_dict *msg)
 235/* gets the attributedTo field (an actor) */
 236{
 237    const xs_val *actor = xs_dict_get(msg, "attributedTo");
 238
 239    /* if the actor is a list of objects (like on Peertube videos), pick the Person */
 240    if (xs_type(actor) == XSTYPE_LIST) {
 241        const xs_list *p = actor;
 242        int c = 0;
 243        const xs_dict *v;
 244        actor = NULL;
 245
 246        while (actor == NULL && xs_list_next(p, &v, &c)) {
 247            if (xs_type(v) == XSTYPE_DICT) {
 248                const char *type = xs_dict_get(v, "type");
 249                if (xs_type(type) == XSTYPE_STRING && strcmp(type, "Person") == 0) {
 250                    actor = xs_dict_get(v, "id");
 251
 252                    if (xs_type(actor) != XSTYPE_STRING)
 253                        actor = NULL;
 254                }
 255            }
 256        }
 257    }
 258    else
 259    if (xs_type(actor) == XSTYPE_DICT) {
 260        /* bandwagon.fm returns this */
 261        actor = xs_dict_get(actor, "id");
 262    }
 263
 264    return actor;
 265}
 266
 267
 268const char *get_in_reply_to(const xs_dict *msg)
 269/* gets the inReplyTo id */
 270{
 271    const xs_val *in_reply_to = xs_dict_get(msg, "inReplyTo");
 272
 273    if (xs_type(in_reply_to) == XSTYPE_DICT)
 274        in_reply_to = xs_dict_get(in_reply_to, "id");
 275
 276    return in_reply_to;
 277}
 278
 279
 280xs_list *get_attachments(const xs_dict *msg)
 281/* unify the garbage fire that are the attachments */
 282{
 283    xs_list *l = xs_list_new();
 284    const xs_list *p;
 285
 286    /* try first the attachments list */
 287    if (!xs_is_null(p = xs_dict_get(msg, "attachment"))) {
 288        xs *attach = NULL;
 289        const xs_val *v;
 290
 291        /* ensure it's a list */
 292        if (xs_type(p) == XSTYPE_DICT) {
 293            attach = xs_list_new();
 294            attach = xs_list_append(attach, p);
 295        }
 296        else
 297            attach = xs_dup(p);
 298
 299        if (xs_type(attach) == XSTYPE_LIST && xs_list_len(attach) == 0) {
 300            /* does the message have an image? */
 301            const xs_dict *d = xs_dict_get(msg, "image");
 302            if (xs_type(d) == XSTYPE_DICT) {
 303                /* add it to the attachment list */
 304                attach = xs_list_append(attach, d);
 305            }
 306        }
 307
 308        /* now iterate the list */
 309        int c = 0;
 310        while (xs_list_next(attach, &v, &c)) {
 311            const char *type = xs_dict_get(v, "mediaType");
 312            if (xs_is_null(type))
 313                type = xs_dict_get(v, "type");
 314
 315            if (xs_is_null(type))
 316                continue;
 317
 318            const char *href = xs_dict_get(v, "url");
 319            if (xs_is_null(href))
 320                href = xs_dict_get(v, "href");
 321            if (xs_is_null(href))
 322                continue;
 323
 324            /* infer MIME type from non-specific attachments */
 325            if (xs_list_len(attach) < 2 && xs_match(type, "Link|Document")) {
 326                char *mt = (char *)xs_mime_by_ext(href);
 327
 328                if (xs_match(mt, "image/*|audio/*|video/*")) /* */
 329                    type = mt;
 330            }
 331
 332            const char *name = xs_dict_get(v, "name");
 333            if (xs_is_null(name))
 334                name = xs_dict_get(msg, "name");
 335            if (xs_is_null(name))
 336                name = "";
 337
 338            xs *d = xs_dict_new();
 339            d = xs_dict_append(d, "type", type);
 340            d = xs_dict_append(d, "href", href);
 341            d = xs_dict_append(d, "name", name);
 342
 343            const xs_dict *icon = xs_dict_get(v, "icon");
 344            if (xs_type(icon) == XSTYPE_DICT)
 345                d = xs_dict_append(d, "icon", icon);
 346
 347            l = xs_list_append(l, d);
 348        }
 349    }
 350
 351    /** urls (attachments from Peertube) **/
 352    p = xs_dict_get(msg, "url");
 353
 354    if (xs_type(p) == XSTYPE_LIST) {
 355        const char *href = NULL;
 356        const char *type = NULL;
 357        int c = 0;
 358        const xs_val *v;
 359
 360        while (href == NULL && xs_list_next(p, &v, &c)) {
 361            if (xs_type(v) == XSTYPE_DICT) {
 362                const char *mtype = xs_dict_get(v, "type");
 363
 364                if (xs_type(mtype) == XSTYPE_STRING && strcmp(mtype, "Link") == 0) {
 365                    mtype = xs_dict_get(v, "mediaType");
 366                    const xs_list *tag = xs_dict_get(v, "tag");
 367
 368                    if (xs_type(mtype) == XSTYPE_STRING &&
 369                        strcmp(mtype, "application/x-mpegURL") == 0 &&
 370                        xs_type(tag) == XSTYPE_LIST) {
 371                        /* now iterate the tag list, looking for a video URL */
 372                        const xs_dict *d;
 373                        int c = 0;
 374
 375                        while (href == NULL && xs_list_next(tag, &d, &c)) {
 376                            if (xs_type(d) == XSTYPE_DICT) {
 377                                if (xs_type(mtype = xs_dict_get(d, "mediaType")) == XSTYPE_STRING &&
 378                                    xs_startswith(mtype, "video/")) {
 379                                    const char *h = xs_dict_get(d, "href");
 380
 381                                    /* this is probably it */
 382                                    if (xs_type(h) == XSTYPE_STRING) {
 383                                        href = h;
 384                                        type = mtype;
 385                                    }
 386                                }
 387                            }
 388                        }
 389                    }
 390                }
 391            }
 392        }
 393
 394        if (href && type) {
 395            xs *d = xs_dict_new();
 396            d = xs_dict_append(d, "href", href);
 397            d = xs_dict_append(d, "type", type);
 398            d = xs_dict_append(d, "name", "---");
 399
 400            l = xs_list_append(l, d);
 401        }
 402    }
 403
 404    return l;
 405}
 406
 407
 408int hashtag_in_msg(const xs_list *hashtags, const xs_dict *msg)
 409/* returns 1 if the message contains any of the list of hashtags */
 410{
 411    if (xs_is_list(hashtags) && xs_is_dict(msg)) {
 412        const xs_list *tags_in_msg = xs_dict_get(msg, "tag");
 413
 414        if (xs_is_list(tags_in_msg)) {
 415            const xs_dict *te;
 416
 417            /* iterate the tags in the message */
 418            xs_list_foreach(tags_in_msg, te) {
 419                if (xs_is_dict(te)) {
 420                    const char *type = xs_dict_get(te, "type");
 421                    const char *name = xs_dict_get(te, "name");
 422
 423                    if (xs_is_string(type) && xs_is_string(name)) {
 424                        if (strcmp(type, "Hashtag") == 0) {
 425                            xs *lc_name = xs_utf8_to_lower(name);
 426
 427                            if (xs_list_in(hashtags, lc_name) != -1)
 428                                return 1;
 429                        }
 430                    }
 431                }
 432            }
 433        }
 434    }
 435
 436    return 0;
 437}
 438
 439
 440int followed_hashtag_check(snac *user, const xs_dict *msg)
 441/* returns 1 if this message contains a hashtag followed by me */
 442{
 443    return hashtag_in_msg(xs_dict_get(user->config, "followed_hashtags"), msg);
 444}
 445
 446
 447int blocked_hashtag_check(snac *user, const xs_dict *msg)
 448/* returns 1 if this message contains a hashtag blocked by me */
 449{
 450    return hashtag_in_msg(xs_dict_get(user->config, "blocked_hashtags"), msg);
 451}
 452
 453
 454int timeline_request(snac *snac, const char **id, xs_str **wrk, int level)
 455/* ensures that an entry and its ancestors are in the timeline */
 456{
 457    int status = 0;
 458
 459    if (level < MAX_CONVERSATION_LEVELS && !xs_is_null(*id)) {
 460        xs *msg = NULL;
 461
 462        /* from a blocked instance? discard and break */
 463        if (is_instance_blocked(*id)) {
 464            snac_debug(snac, 1, xs_fmt("timeline_request blocked instance %s", *id));
 465            return status;
 466        }
 467
 468        /* is the object already there? */
 469        if (!valid_status((status = object_get(*id, &msg)))) {
 470            /* no; download it */
 471            status = activitypub_request(snac, *id, &msg);
 472        }
 473
 474        if (valid_status(status)) {
 475            const xs_dict *object = msg;
 476            const char *type = xs_dict_get(object, "type");
 477
 478            /* get the id again from the object, as it may be different */
 479            const char *nid = xs_dict_get(object, "id");
 480
 481            if (xs_type(nid) != XSTYPE_STRING)
 482                return 0;
 483
 484            if (wrk && strcmp(nid, *id) != 0) {
 485                snac_debug(snac, 1,
 486                    xs_fmt("timeline_request canonical id for %s is %s", *id, nid));
 487
 488                *wrk = xs_dup(nid);
 489                *id  = *wrk;
 490            }
 491
 492            if (xs_is_null(type))
 493                type = "(null)";
 494
 495            srv_debug(2, xs_fmt("timeline_request type %s '%s'", nid, type));
 496
 497            if (strcmp(type, "Create") == 0) {
 498                /* some software like lemmy nest Announce + Create + Note */
 499                if (!xs_is_null(object = xs_dict_get(object, "object"))) {
 500                    type = xs_dict_get(object, "type");
 501                    nid  = xs_dict_get(object, "id");
 502                }
 503                else
 504                    type = "(null)";
 505            }
 506
 507            if (xs_match(type, POSTLIKE_OBJECT_TYPE)) {
 508                if (content_match("filter_reject.txt", object))
 509                    snac_log(snac, xs_fmt("timeline_request rejected by content %s", nid));
 510                else
 511                if (blocked_hashtag_check(snac, object))
 512                    snac_log(snac, xs_fmt("timeline_request rejected by hashtag %s", nid));
 513                else {
 514                    const char *actor = get_atto(object);
 515
 516                    if (!xs_is_null(actor)) {
 517                        /* request (and drop) the actor for this entry */
 518                        if (!valid_status(actor_request(snac, actor, NULL))) {
 519                            /* failed? retry later */
 520                            enqueue_actor_refresh(snac, actor, 60);
 521                        }
 522
 523                        /* does it have an ancestor? */
 524                        const char *in_reply_to = get_in_reply_to(object);
 525
 526                        /* store */
 527                        timeline_add(snac, nid, object);
 528
 529                        /* redistribute to lists for this user */
 530                        list_distribute(snac, actor, object);
 531
 532                        /* recurse! */
 533                        timeline_request(snac, &in_reply_to, NULL, level + 1);
 534                    }
 535                }
 536            }
 537        }
 538    }
 539
 540    return status;
 541}
 542
 543
 544int send_to_inbox_raw(const char *keyid, const char *seckey,
 545                  const xs_str *inbox, const xs_dict *msg,
 546                  xs_val **payload, int *p_size, int timeout)
 547/* sends a message to an Inbox */
 548{
 549    int status;
 550    xs_dict *response;
 551    xs *j_msg = xs_json_dumps((xs_dict *)msg, 4);
 552
 553    response = http_signed_request_raw(keyid, seckey, "POST", inbox,
 554        NULL, j_msg, strlen(j_msg), &status, payload, p_size, timeout);
 555
 556    xs_free(response);
 557
 558    return status;
 559}
 560
 561
 562int send_to_inbox(snac *snac, const xs_str *inbox, const xs_dict *msg,
 563                  xs_val **payload, int *p_size, int timeout)
 564/* sends a message to an Inbox */
 565{
 566    const char *seckey = xs_dict_get(snac->key, "secret");
 567
 568    return send_to_inbox_raw(snac->actor, seckey, inbox, msg, payload, p_size, timeout);
 569}
 570
 571
 572xs_str *get_actor_inbox(const char *actor, int shared)
 573/* gets an actor's inbox */
 574{
 575    xs *data = NULL;
 576    const char *v = NULL;
 577
 578    if (valid_status(actor_request(NULL, actor, &data))) {
 579        /* try first endpoints/sharedInbox */
 580        if (shared && (v = xs_dict_get(data, "endpoints")))
 581            v = xs_dict_get(v, "sharedInbox");
 582
 583        /* try then the regular inbox */
 584        if (xs_is_null(v))
 585            v = xs_dict_get(data, "inbox");
 586    }
 587
 588    return xs_is_null(v) ? NULL : xs_dup(v);
 589}
 590
 591
 592int send_to_actor(snac *snac, const char *actor, const xs_dict *msg,
 593                  xs_val **payload, int *p_size, int timeout)
 594/* sends a message to an actor */
 595{
 596    int status = HTTP_STATUS_BAD_REQUEST;
 597    xs *inbox = get_actor_inbox(actor, 1);
 598
 599    if (!xs_is_null(inbox))
 600        status = send_to_inbox(snac, inbox, msg, payload, p_size, timeout);
 601
 602    return status;
 603}
 604
 605
 606void post_message(snac *snac, const char *actor, const xs_dict *msg)
 607/* posts a message immediately (bypassing the output queues) */
 608{
 609    xs *payload = NULL;
 610    int p_size;
 611
 612    int status = send_to_actor(snac, actor, msg, &payload, &p_size, 3);
 613
 614    srv_log(xs_fmt("post_message to actor %s %d", actor, status));
 615
 616    if (!valid_status(status))
 617        /* cannot send right now, enqueue */
 618        enqueue_message(snac, msg);
 619}
 620
 621
 622xs_list *recipient_list(snac *snac, const xs_dict *msg, int expand_public)
 623/* returns the list of recipients for a message */
 624{
 625    const xs_val *to = xs_dict_get(msg, "to");
 626    const xs_val *cc = xs_dict_get(msg, "cc");
 627    xs_set rcpts;
 628    int n;
 629
 630    xs_set_init(&rcpts);
 631
 632    const xs_list *lists[] = { to, cc, NULL };
 633    for (n = 0; lists[n]; n++) {
 634        xs_list *l = (xs_list *)lists[n];
 635        const char *v;
 636        xs *tl = NULL;
 637
 638        /* if it's a string, create a list with only one element */
 639        if (xs_type(l) == XSTYPE_STRING) {
 640            tl = xs_list_new();
 641            tl = xs_list_append(tl, l);
 642
 643            l = tl;
 644        }
 645
 646        while (xs_list_iter(&l, &v)) {
 647            if (expand_public) {
 648                xs *followers_url = xs_fmt("%s/followers", snac->actor);
 649                if (strcmp(v, public_address) == 0 ||
 650                    /* check if it's a followers collection URL */
 651                    (xs_type(v) == XSTYPE_STRING &&
 652                        strcmp(v, followers_url) == 0) ||
 653                    (xs_type(v) == XSTYPE_LIST &&
 654                        xs_list_in(v, followers_url) != -1)) {
 655                    /* iterate the followers and add them */
 656                    xs *fwers = follower_list(snac);
 657                    const char *actor;
 658
 659                    char *p = fwers;
 660                    while (xs_list_iter(&p, &actor))
 661                        xs_set_add(&rcpts, actor);
 662                }
 663                else
 664                    xs_set_add(&rcpts, v);
 665            }
 666            else
 667                xs_set_add(&rcpts, v);
 668        }
 669    }
 670
 671    return xs_set_result(&rcpts);
 672}
 673
 674
 675int is_msg_public(const xs_dict *msg)
 676/* checks if a message is public */
 677{
 678    const char *to = xs_dict_get(msg, "to");
 679    const char *cc = xs_dict_get(msg, "cc");
 680    int n;
 681
 682    const char *lists[] = { to, cc, NULL };
 683    for (n = 0; lists[n]; n++) {
 684        const xs_val *l = lists[n];
 685
 686        if (xs_type(l) == XSTYPE_STRING) {
 687            if (strcmp(l, public_address) == 0)
 688                return 1;
 689        }
 690        else
 691        if (xs_type(l) == XSTYPE_LIST) {
 692            if (xs_list_in(l, public_address) != -1)
 693                return 1;
 694        }
 695    }
 696
 697    return 0;
 698}
 699
 700
 701int is_msg_from_private_user(const xs_dict *msg)
 702/* checks if a message is from a local, private user */
 703{
 704    int ret = 0;
 705
 706    /* is this message from a local user? */
 707    if (xs_startswith(xs_dict_get(msg, "id"), srv_baseurl)) {
 708        const char *atto = get_atto(msg);
 709        xs *l = xs_split(atto, "/");
 710        const char *uid = xs_list_get(l, -1);
 711        snac user;
 712
 713        if (uid && user_open(&user, uid)) {
 714            if (xs_type(xs_dict_get(user.config, "private")) == XSTYPE_TRUE)
 715                ret = 1;
 716
 717            user_free(&user);
 718        }
 719    }
 720
 721    return ret;
 722}
 723
 724
 725void followed_hashtag_distribute(const xs_dict *msg)
 726/* distribute this post to all users following the included hashtags */
 727{
 728    const char *id = xs_dict_get(msg, "id");
 729    const xs_list *tags_in_msg = xs_dict_get(msg, "tag");
 730
 731    if (!xs_is_string(id) || !xs_is_list(tags_in_msg) || xs_list_len(tags_in_msg) == 0)
 732        return;
 733
 734    srv_debug(1, xs_fmt("followed_hashtag_distribute check for %s", id));
 735
 736    xs *users = user_list();
 737    const char *uid;
 738
 739    xs_list_foreach(users, uid) {
 740        snac user;
 741
 742        if (user_open(&user, uid)) {
 743            if (followed_hashtag_check(&user, msg)) {
 744                timeline_add(&user, id, msg);
 745
 746                snac_log(&user, xs_fmt("followed hashtag in %s", id));
 747            }
 748
 749            user_free(&user);
 750        }
 751    }
 752}
 753
 754
 755int is_msg_for_me(snac *snac, const xs_dict *c_msg)
 756/* checks if this message is for me */
 757{
 758    const char *type  = xs_dict_get(c_msg, "type");
 759    const char *actor = xs_dict_get(c_msg, "actor");
 760
 761    if (strcmp(actor, snac->actor) == 0) {
 762        /* message by myself? (most probably via the shared-inbox) reject */
 763        snac_debug(snac, 1, xs_fmt("ignoring message by myself"));
 764        return 0;
 765    }
 766
 767    if (xs_match(type, "Like|Announce|EmojiReact")) {
 768        const char *object = xs_dict_get(c_msg, "object");
 769        xs *obj = NULL;
 770
 771        if (xs_is_dict(object)) {
 772            obj = xs_dup(object);
 773            object = xs_dict_get(object, "id");
 774        }
 775
 776        /* bad object id? reject */
 777        if (!xs_is_string(object))
 778            return 0;
 779
 780        /* try to get the object */
 781        if (!xs_is_dict(obj))
 782            object_get(object, &obj);
 783
 784        /* if it's about one of our posts, accept it */
 785        if (is_msg_mine(snac, object))
 786            return 2;
 787
 788        /* blocked by hashtag? */
 789        if (blocked_hashtag_check(snac, obj))
 790            return 0;
 791
 792        /* if it's by someone we follow, accept it */
 793        if (following_check(snac, actor))
 794            return 1;
 795
 796        /* do we follow any hashtag? */
 797        if (followed_hashtag_check(snac, obj))
 798            return 7;
 799
 800        return 0;
 801    }
 802
 803    /* if it's an Undo, it must be from someone related to us */
 804    if (xs_match(type, "Undo")) {
 805        return follower_check(snac, actor) || following_check(snac, actor);
 806    }
 807
 808    /* if it's an Accept + Follow, it must be for a Follow we created */
 809    if (xs_match(type, "Accept")) {
 810        return following_check(snac, actor);
 811    }
 812
 813    /* if it's a Follow, it must be explicitly for us */
 814    if (xs_match(type, "Follow")) {
 815        const char *object = xs_dict_get(c_msg, "object");
 816        return !xs_is_null(object) && (strcmp(snac->actor, object) == 0 || strcmp(snac->actor_alt, object) == 0);
 817    }
 818
 819    /* only accept Ping directed to us */
 820    if (xs_match(type, "Ping")) {
 821        const char *dest = xs_dict_get(c_msg, "to");
 822        return !xs_is_null(dest) && (strcmp(snac->actor, dest) == 0 || strcmp(snac->actor_alt, dest) == 0);
 823    }
 824
 825    /* if it's not a Create or Update, allow as is */
 826    if (!xs_match(type, "Create|Update")) {
 827        return 1;
 828    }
 829
 830    const xs_dict *msg = xs_dict_get(c_msg, "object");
 831
 832    /* any blocked hashtag? reject */
 833    if (blocked_hashtag_check(snac, msg)) {
 834        snac_debug(snac, 1, xs_fmt("blocked by hashtag %s", xs_dict_get(msg, "id")));
 835        return 0;
 836    }
 837
 838    int pub_msg = is_msg_public(c_msg);
 839
 840    /* if this message is public and we follow the actor of this post, allow */
 841    if (pub_msg && following_check(snac, actor))
 842        return 1;
 843
 844    xs *rcpts = recipient_list(snac, msg, 0);
 845    xs_list *p = rcpts;
 846    const xs_str *v;
 847
 848    xs *actor_followers = NULL;
 849
 850    if (!pub_msg) {
 851        /* not a public message; get the actor and its followers list */
 852        xs *actor_obj = NULL;
 853
 854        if (valid_status(object_get(actor, &actor_obj))) {
 855            const xs_val *fw = xs_dict_get(actor_obj, "followers");
 856            if (fw)
 857                actor_followers = xs_dup(fw);
 858        }
 859    }
 860
 861    while(xs_list_iter(&p, &v)) {
 862        /* explicitly for me? accept */
 863        if (strcmp(v, snac->actor) == 0 || strcmp(v, snac->actor_alt) == 0)
 864            return 2;
 865
 866        if (pub_msg) {
 867            /* a public message for someone we follow? (probably cc'ed) accept */
 868            if (strcmp(v, public_address) != 0 && following_check(snac, v))
 869                return 5;
 870        }
 871        else
 872        if (actor_followers && strcmp(v, actor_followers) == 0) {
 873            /* if this message is for this actor's followers, are we one of them? */
 874            if (following_check(snac, actor))
 875                return 6;
 876        }
 877    }
 878
 879    /* accept if it's by someone we follow */
 880    const char *atto = get_atto(msg);
 881
 882    if (pub_msg && !xs_is_null(atto) && following_check(snac, atto))
 883        return 3;
 884
 885    /* is this message a reply to another? */
 886    const char *irt = get_in_reply_to(msg);
 887    if (!xs_is_null(irt)) {
 888        xs *r_msg = NULL;
 889
 890        /* try to get the replied message */
 891        if (valid_status(object_get(irt, &r_msg))) {
 892            atto = get_atto(r_msg);
 893
 894            /* accept if the replied message is from someone we follow */
 895            if (pub_msg && !xs_is_null(atto) && following_check(snac, atto))
 896                return 4;
 897        }
 898    }
 899
 900    /* does this message contain a tag we are following? */
 901    if (pub_msg && followed_hashtag_check(snac, msg))
 902        return 7;
 903
 904    return 0;
 905}
 906
 907
 908xs_str *process_tags(snac *snac, const char *content, xs_list **tag)
 909/* parses mentions and tags from content */
 910{
 911    xs_str *nc  = xs_str_new(NULL);
 912    xs_list *tl = *tag;
 913    xs *split;
 914    xs_list *p;
 915    const xs_val *v;
 916    int n = 0;
 917
 918    /* create a default server for incomplete mentions */
 919    xs *def_srv = NULL;
 920
 921    if (xs_list_len(tl)) {
 922        /* if there are any mentions, get the server from
 923           the first one, which is the inReplyTo author */
 924        p = tl;
 925        while (xs_list_iter(&p, &v)) {
 926            const char *type = xs_dict_get(v, "type");
 927            const char *name = xs_dict_get(v, "name");
 928
 929            if (type && name && strcmp(type, "Mention") == 0) {
 930                xs *l = xs_split(name, "@");
 931
 932                def_srv = xs_dup(xs_list_get(l, -1));
 933
 934                break;
 935            }
 936        }
 937    }
 938
 939    if (xs_is_null(def_srv))
 940        /* use this same server */
 941        def_srv = xs_dup(xs_dict_get(srv_config, "host"));
 942
 943    split = xs_regex_split(content, "(@[A-Za-z0-9_]+(@[A-Za-z0-9\\.-]+)?|&#[0-9]+;|#(_|[^[:punct:][:space:]])+)");
 944
 945    p = split;
 946    while (xs_list_iter(&p, &v)) {
 947        if ((n & 0x1)) {
 948            if (*v == '@') {
 949                xs *link = NULL;
 950                xs *wuid = NULL;
 951
 952                if (strchr(v + 1, '@') == NULL) {
 953                    /* only one @? it's a dumb Mastodon-like mention
 954                       without server; add the default one */
 955                    wuid = xs_fmt("%s@%s", v, def_srv);
 956
 957                    snac_debug(snac, 2, xs_fmt("mention without server '%s' '%s'", v, wuid));
 958                }
 959                else
 960                    wuid = xs_dup(v);
 961
 962                /* query the webfinger about this fellow */
 963                xs *actor = NULL;
 964                xs *uid   = NULL;
 965                int status;
 966
 967                status = webfinger_request(wuid, &actor, &uid);
 968
 969                if (valid_status(status) && actor && uid) {
 970                    xs *d = xs_dict_new();
 971                    xs *n = xs_fmt("@%s", uid);
 972
 973                    d = xs_dict_append(d, "type",   "Mention");
 974                    d = xs_dict_append(d, "href",   actor);
 975                    d = xs_dict_append(d, "name",   n);
 976
 977                    tl = xs_list_append(tl, d);
 978
 979                    link = xs_fmt("<span class=\"h-card\"><a href=\"%s\" class=\"u-url mention\">%s</a></span>", actor, n);
 980                }
 981
 982                if (!xs_is_null(link))
 983                    nc = xs_str_cat(nc, link);
 984                else
 985                    nc = xs_str_cat(nc, v);
 986            }
 987            else
 988            if (*v == '#') {
 989                /* hashtag */
 990                xs *d = xs_dict_new();
 991                xs *n = xs_utf8_to_lower(v);
 992                xs *h = xs_fmt("%s?t=%s", srv_baseurl, n + 1);
 993                xs *l = xs_fmt("<a href=\"%s\" class=\"mention hashtag\" rel=\"tag\">%s</a>", h, v);
 994
 995                d = xs_dict_append(d, "type",   "Hashtag");
 996                d = xs_dict_append(d, "href",   h);
 997                d = xs_dict_append(d, "name",   n);
 998
 999                tl = xs_list_append(tl, d);
1000
1001                /* add the code */
1002                nc = xs_str_cat(nc, l);
1003            }
1004            else
1005            if (*v == '&') {
1006                /* HTML Unicode entity, probably part of an emoji */
1007
1008                /* write as is */
1009                nc = xs_str_cat(nc, v);
1010            }
1011        }
1012        else
1013            nc = xs_str_cat(nc, v);
1014
1015        n++;
1016    }
1017
1018    *tag = tl;
1019
1020    return nc;
1021}
1022
1023
1024void collect_replies(snac *user, const char *id)
1025/* collects all replies for a post */
1026{
1027    xs *obj = NULL;
1028
1029    if (!valid_status(object_get(id, &obj))) {
1030        snac_debug(user, 1, xs_fmt("collect_replies: object '%s' is not here", id));
1031        return;
1032    }
1033
1034    const xs_dict *replies_first = xs_dict_get_path(obj, "replies.first");
1035    if (!xs_is_dict(replies_first)) {
1036        snac_debug(user, 1, xs_fmt("collect_replies: object '%s' does not have replies.first", id));
1037        return;
1038    }
1039
1040    const xs_list *level0_replies = xs_dict_get(replies_first, "items");
1041    const xs_list *level1_replies = NULL;
1042
1043    const char *next = xs_dict_get(replies_first, "next");
1044    xs *reply_obj = NULL;
1045
1046    if (xs_is_string(next) && !valid_status(activitypub_request(user, next, &reply_obj))) {
1047        snac_debug(user, 1, xs_fmt("collect_replies: error getting next replies object '%s'", next));
1048        return;
1049    }
1050
1051    if (xs_is_dict(reply_obj))
1052        level1_replies = xs_dict_get(reply_obj, "items");
1053
1054    xs *items = xs_list_new();
1055
1056    if (xs_is_list(level0_replies))
1057        items = xs_list_cat(items, level0_replies);
1058
1059    if (xs_is_list(level1_replies))
1060        items = xs_list_cat(items, level1_replies);
1061
1062    const xs_val *v;
1063
1064    xs_list_foreach(items, v) {
1065        xs *reply = NULL;
1066
1067        if (xs_is_string(v)) {
1068            /* request the object */
1069            if (!valid_status(object_get(v, &reply))) {
1070                if (!valid_status(activitypub_request(user, v, &reply))) {
1071                    snac_debug(user, 1, xs_fmt("collect_replies: error requesting object '%s'", v));
1072                    continue;
1073                }
1074            }
1075        }
1076        else
1077        if (xs_is_dict(v)) {
1078            /* actually the post object */
1079            reply = xs_dup(v);
1080        }
1081
1082        if (!xs_is_dict(reply))
1083            continue;
1084
1085        const char *id      = xs_dict_get(reply, "id");
1086        const char *type    = xs_dict_get(reply, "type");
1087        const char *attr_to = get_atto(reply);
1088
1089        if (!xs_is_string(id) || !xs_is_string(type) || !xs_is_string(attr_to))
1090            continue;
1091
1092        if (!xs_match(type, POSTLIKE_OBJECT_TYPE))
1093            continue;
1094
1095        if (timeline_here(user, id)) {
1096            snac_debug(user, 1, xs_fmt("collect_replies: item already in timeline %s", id));
1097            continue;
1098        }
1099
1100        enqueue_actor_refresh(user, attr_to, 0);
1101
1102        timeline_add(user, id, reply);
1103
1104        snac_log(user, xs_fmt("new '%s' (collect_replies) %s %s", type, attr_to, id));
1105    }
1106}
1107
1108
1109void collect_outbox(snac *user, const char *actor_id)
1110/* gets an actor's outbox and inserts a bunch of posts in a user's timeline */
1111{
1112    int status;
1113    xs *actor = NULL;
1114
1115    if (!valid_status(status = actor_request(user, actor_id, &actor))) {
1116        snac_debug(user, 1, xs_fmt("collect_outbox: cannot get actor object '%s' %d", actor_id, status));
1117        return;
1118    }
1119
1120    xs *outbox = NULL;
1121    const char *outbox_url = xs_dict_get(actor, "outbox");
1122
1123    if (!xs_is_string(outbox_url))
1124        return;
1125
1126    if (!valid_status(status = activitypub_request(user, outbox_url, &outbox))) {
1127        snac_debug(user, 1, xs_fmt("collect_outbox: cannot get actor outbox '%s' %d", outbox_url, status));
1128        return;
1129    }
1130
1131    const xs_list *ordered_items = xs_dict_get(outbox, "orderedItems");
1132
1133    if (!xs_is_list(ordered_items)) {
1134        /* the list is not here; does it have a 'first'? */
1135        const char *first = xs_dict_get(outbox, "first");
1136
1137        if (xs_is_string(first)) {
1138            /* download this instead */
1139            xs *first2 = xs_dup(first);
1140            xs_free(outbox);
1141
1142            if (!valid_status(status = activitypub_request(user, first2, &outbox))) {
1143                snac_debug(user, 1, xs_fmt("collect_outbox: cannot get first page of outbox '%s' %d", first2, status));
1144                return;
1145            }
1146
1147            /* last chance */
1148            ordered_items = xs_dict_get(outbox, "orderedItems");
1149        }
1150    }
1151
1152    if (!xs_is_list(ordered_items)) {
1153        snac_debug(user, 1, xs_fmt("collect_outbox: cannot get list of posts for actor '%s' outbox", actor_id));
1154        return;
1155    }
1156
1157    /* well, ok, then */
1158    int max = 4;
1159    const xs_val *v;
1160
1161    xs_list_foreach(ordered_items, v) {
1162        if (max == 0)
1163            break;
1164
1165        xs *post = NULL;
1166
1167        if (xs_is_string(v)) {
1168            /* it's probably the post url */
1169            if (!valid_status(activitypub_request(user, v, &post)))
1170                continue;
1171        }
1172        else
1173        if (xs_is_dict(v))
1174            post = xs_dup(v);
1175
1176        if (post == NULL)
1177            continue;
1178
1179        const char *type = xs_dict_get(post, "type");
1180
1181        if (!xs_is_string(type) || strcmp(type, "Create")) {
1182            /* not a post */
1183            continue;
1184        }
1185        if (is_msg_for_me(user, post) == 0) {
1186            /* not for us */
1187            continue;
1188        }
1189
1190        const xs_dict *object = xs_dict_get(post, "object");
1191
1192        if (!xs_is_dict(object))
1193            continue;
1194
1195        type = xs_dict_get(object, "type");
1196        const char *id = xs_dict_get(object, "id");
1197        const char *attr_to = get_atto(object);
1198
1199        if (!xs_is_string(type) || !xs_is_string(id) || !xs_is_string(attr_to))
1200            continue;
1201
1202        if (!timeline_here(user, id)) {
1203            timeline_add(user, id, object);
1204            snac_log(user, xs_fmt("new '%s' (collect_outbox) %s %s", type, attr_to, id));
1205        }
1206        else
1207            snac_debug(user, 1, xs_fmt("collect_outbox: post '%s' already here", id));
1208
1209        max--;
1210    }
1211}
1212
1213
1214void notify(snac *snac, const char *type, const char *utype, const char *actor, const xs_dict *msg)
1215/* notifies the user of relevant events */
1216{
1217    /* skip our own notifications */
1218    if (strcmp(snac->actor, actor) == 0)
1219        return;
1220
1221    const char *id = xs_dict_get(msg, "id");
1222
1223    if (strcmp(type, "Create") == 0) {
1224        /* only notify of notes specifically for us */
1225        xs *rcpts = recipient_list(snac, msg, 0);
1226
1227        if (xs_list_in(rcpts, snac->actor) == -1)
1228            return;
1229
1230        /* discard votes */
1231        const xs_dict *note = xs_dict_get(msg, "object");
1232
1233        if (note && !xs_is_null(xs_dict_get(note, "name")))
1234            return;
1235    }
1236
1237    if (strcmp(type, "Undo") == 0 && strcmp(utype, "Follow") != 0)
1238        return;
1239
1240    /* get the object id */
1241    const char *objid = xs_dict_get(msg, "object");
1242
1243    if (xs_type(objid) == XSTYPE_DICT)
1244        objid = xs_dict_get(objid, "id");
1245
1246    if (xs_match(type, "Like|Announce|EmojiReact")) {
1247        /* if it's not an admiration about something by us, done */
1248        if (xs_is_null(objid) || !is_msg_mine(snac, objid))
1249            return;
1250
1251        /* if it's an announce by our own relay, done */
1252        xs *relay_id = xs_fmt("%s/relay", srv_baseurl);
1253        if (xs_startswith(id, relay_id))
1254            return;
1255    }
1256
1257    /* updated poll? */
1258    if (strcmp(type, "Update") == 0 && strcmp(utype, "Question") == 0) {
1259        const xs_dict *poll;
1260        const char *poll_id;
1261
1262        if ((poll = xs_dict_get(msg, "object")) == NULL)
1263            return;
1264
1265        /* if it's not closed, discard */
1266        if (xs_is_null(xs_dict_get(poll, "closed")))
1267            return;
1268
1269        if ((poll_id = xs_dict_get(poll, "id")) == NULL)
1270            return;
1271
1272        /* if it's not ours and we didn't vote, discard */
1273        if (!is_msg_mine(snac, poll_id) && !was_question_voted(snac, poll_id))
1274            return;
1275    }
1276
1277    /* user will love to know about this! */
1278
1279    /* prepare message body */
1280    xs *body = xs_fmt("User  : @%s@%s\n",
1281        xs_dict_get(snac->config, "uid"),
1282        xs_dict_get(srv_config,   "host")
1283    );
1284
1285    if (strcmp(utype, "(null)") != 0) {
1286        xs *s1 = xs_fmt("Type  : %s + %s\n", type, utype);
1287        body = xs_str_cat(body, s1);
1288    }
1289    else {
1290        xs *s1 = xs_fmt("Type  : %s\n", type);
1291        body = xs_str_cat(body, s1);
1292    }
1293
1294    {
1295        xs *s1 = xs_fmt("Actor : %s\n", actor);
1296        body = xs_str_cat(body, s1);
1297    }
1298
1299    if (objid != NULL) {
1300        xs *s1 = xs_fmt("Object: %s\n", objid);
1301        body = xs_str_cat(body, s1);
1302    }
1303
1304    /* email */
1305
1306    const char *email = "[disabled by admin]";
1307
1308    if (xs_type(xs_dict_get(srv_config, "disable_email_notifications")) != XSTYPE_TRUE) {
1309        email = xs_dict_get(snac->config_o, "email");
1310        if (xs_is_null(email)) {
1311            email = xs_dict_get(snac->config, "email");
1312
1313            if (xs_is_null(email))
1314                email = "[empty]";
1315        }
1316    }
1317
1318    if (*email != '\0' && *email != '[') {
1319        snac_debug(snac, 1, xs_fmt("email notify %s %s %s", type, utype, actor));
1320
1321        xs *subject = xs_fmt("snac notify for @%s@%s",
1322                    xs_dict_get(snac->config, "uid"), xs_dict_get(srv_config, "host"));
1323        xs *from    = xs_fmt("<snac-daemon@%s>", xs_dict_get(srv_config, "host"));
1324        xs *header  = xs_fmt(
1325                    "From: snac-daemon %s\n"
1326                    "To: %s\n"
1327                    "Subject: %s\n"
1328                    "\n",
1329                    from, email, subject);
1330
1331        xs *mailinfo = xs_dict_new();
1332        xs *bd = xs_fmt("%s%s", header, body);
1333        mailinfo = xs_dict_append(mailinfo, "from", from);
1334        mailinfo = xs_dict_append(mailinfo, "to", email);
1335        mailinfo = xs_dict_append(mailinfo, "body", bd);
1336
1337        enqueue_email(mailinfo, 0);
1338    }
1339
1340    /* telegram */
1341
1342    const char *bot     = xs_dict_get(snac->config, "telegram_bot");
1343    const char *chat_id = xs_dict_get(snac->config, "telegram_chat_id");
1344
1345    if (!xs_is_null(bot) && !xs_is_null(chat_id) && *bot && *chat_id)
1346        enqueue_telegram(body, bot, chat_id);
1347
1348    /* ntfy */
1349    const char *ntfy_server = xs_dict_get(snac->config, "ntfy_server");
1350    const char *ntfy_token  = xs_dict_get(snac->config, "ntfy_token");
1351
1352    if (!xs_is_null(ntfy_server) && *ntfy_server)
1353        enqueue_ntfy(body, ntfy_server, ntfy_token);
1354
1355    /* auto boost */
1356    if (xs_match(type, "Create") && xs_is_true(xs_dict_get(snac->config, "auto_boost"))) {
1357        xs *msg = msg_admiration(snac, objid, "Announce");
1358        enqueue_message(snac, msg);
1359
1360        snac_debug(snac, 1, xs_fmt("auto boosted %s", objid));
1361    }
1362
1363    /* finally, store it in the notification folder */
1364    if (strcmp(type, "Follow") == 0)
1365        objid = id;
1366    else
1367    if (strcmp(utype, "Follow") == 0)
1368        objid = actor;
1369
1370    notify_add(snac, type, utype, actor, objid != NULL ? objid : id, msg);
1371}
1372
1373/** messages **/
1374
1375xs_dict *msg_base(snac *snac, const char *type, const char *id,
1376                  const char *actor, const char *date, const char *object)
1377/* creates a base ActivityPub message */
1378{
1379    xs *did       = NULL;
1380    xs *published = NULL;
1381    xs *ntid      = tid(0);
1382    const char *obj_id;
1383
1384    if (xs_type(object) == XSTYPE_DICT)
1385        obj_id = xs_dict_get(object, "id");
1386    else
1387        obj_id = object;
1388
1389    /* generated values */
1390    if (date && strcmp(date, "@now") == 0) {
1391        published = xs_str_utctime(0, ISO_DATE_SPEC);
1392        date = published;
1393    }
1394
1395    if (id != NULL) {
1396        if (strcmp(id, "@dummy") == 0) {
1397            did = xs_fmt("%s/d/%s/%s", snac->actor, ntid, type);
1398
1399            id = did;
1400        }
1401        else
1402        if (strcmp(id, "@object") == 0) {
1403            if (obj_id != NULL) {
1404                did = xs_fmt("%s/%s_%s", obj_id, type, ntid);
1405                id = did;
1406            }
1407            else
1408                id = NULL;
1409        }
1410        else
1411        if (strcmp(id, "@wrapper") == 0) {
1412            /* like @object, but always generate the same id */
1413            if (object != NULL) {
1414                date = xs_dict_get(object, "published");
1415                did = xs_fmt("%s/%s", obj_id, type);
1416                id = did;
1417            }
1418            else
1419                id = NULL;
1420        }
1421    }
1422
1423    xs_dict *msg = xs_dict_new();
1424
1425    msg = xs_dict_append(msg, "@context", "https:/" "/www.w3.org/ns/activitystreams");
1426    msg = xs_dict_append(msg, "type",     type);
1427
1428    if (id != NULL)
1429        msg = xs_dict_append(msg, "id", id);
1430
1431    if (actor != NULL)
1432        msg = xs_dict_append(msg, "actor", actor);
1433
1434    if (date != NULL)
1435        msg = xs_dict_append(msg, "published", date);
1436
1437    if (object != NULL)
1438        msg = xs_dict_append(msg, "object", object);
1439
1440    return msg;
1441}
1442
1443
1444xs_dict *msg_collection(snac *snac, const char *id, int items)
1445/* creates an empty OrderedCollection message */
1446{
1447    xs_dict *msg = msg_base(snac, "OrderedCollection", id, NULL, NULL, NULL);
1448    xs *n = xs_number_new(items);
1449
1450    msg = xs_dict_append(msg, "attributedTo", snac->actor);
1451    msg = xs_dict_append(msg, "totalItems",   n);
1452
1453    return msg;
1454}
1455
1456
1457xs_dict *msg_replies(snac *user, const char *id, int fill)
1458/* creates a CollectionPage with replies of id */
1459{
1460    xs *r_id = xs_replace(id, "/p/", "/r/");
1461    xs *r_idp = xs_fmt("%s?page=true", r_id);
1462    xs *r_idh = xs_fmt("%s", r_id);
1463
1464    xs_dict *msg = msg_base(user, "CollectionPage", r_idp, NULL, NULL, NULL);
1465
1466    msg = xs_dict_set(msg, "partOf", r_idh);
1467
1468    xs *items = xs_list_new();
1469    if (fill) {
1470        xs *children = object_children(id);
1471        const char *md5;
1472
1473        xs_list_foreach(children, md5) {
1474            xs *obj = NULL;
1475
1476            if (valid_status(object_get_by_md5(md5, &obj)) && is_msg_public(obj)) {
1477                const char *c_id = xs_dict_get(obj, "id");
1478
1479                if (xs_is_string(c_id))
1480                    items = xs_list_append(items, c_id);
1481            }
1482        }
1483    }
1484    else {
1485        msg = xs_dict_del(msg, "@context");
1486        msg = xs_dict_del(msg, "id");
1487        msg = xs_dict_set(msg, "next", r_idp);
1488    }
1489
1490    msg = xs_dict_set(msg, "items", items);
1491
1492    return msg;
1493}
1494
1495
1496xs_dict *msg_accept(snac *snac, const xs_val *object, const char *to)
1497/* creates an Accept message (as a response to a Follow) */
1498{
1499    xs_dict *msg = msg_base(snac, "Accept", "@dummy", snac->actor, NULL, object);
1500
1501    msg = xs_dict_append(msg, "to", to);
1502
1503    return msg;
1504}
1505
1506
1507xs_dict *msg_update(snac *snac, const xs_dict *object)
1508/* creates an Update message */
1509{
1510    xs_dict *msg = msg_base(snac, "Update", "@object", snac->actor, "@now", object);
1511
1512    const char *type = xs_dict_get(object, "type");
1513
1514    if (strcmp(type, "Note") == 0) {
1515        msg = xs_dict_append(msg, "to", xs_dict_get(object, "to"));
1516        msg = xs_dict_append(msg, "cc", xs_dict_get(object, "cc"));
1517    }
1518    else
1519    if (strcmp(type, "Person") == 0) {
1520        msg = xs_dict_append(msg, "to", public_address);
1521
1522        /* also spam the people being followed, so that
1523           they have the newest information about who we are */
1524        xs *cc = following_list(snac);
1525
1526        msg = xs_dict_append(msg, "cc", cc);
1527    }
1528    else
1529        msg = xs_dict_append(msg, "to", public_address);
1530
1531    return msg;
1532}
1533
1534
1535xs_dict *msg_admiration(snac *snac, const char *object, const char *type)
1536/* creates a Like, Announce or EmojiReact message */
1537{
1538    xs *a_msg    = NULL;
1539    xs_dict *msg = NULL;
1540    xs *wrk      = NULL;
1541    char t       = 0;
1542
1543    switch (*type) {
1544        case 'L':
1545            t = 'l';
1546            break;
1547        case 'A':
1548            t = 'a';
1549            break;
1550        case 'E':
1551            t = 'e';
1552            break;
1553    }
1554
1555    /* call the object */
1556    timeline_request(snac, &object, &wrk, 0);
1557
1558    if (valid_status(object_get(object, &a_msg))) {
1559        xs *rcpts = xs_list_new();
1560        xs *o_md5 = xs_md5_hex(object, strlen(object));
1561        xs *id    = xs_fmt("%s/%c/%s", snac->actor, t, o_md5);
1562
1563        msg = msg_base(snac, type, id, snac->actor, "@now", object);
1564
1565        if (is_msg_public(a_msg))
1566            rcpts = xs_list_append(rcpts, public_address);
1567
1568        rcpts = xs_list_append(rcpts, get_atto(a_msg));
1569
1570        msg = xs_dict_append(msg, "to", rcpts);
1571    }
1572    else
1573        snac_log(snac, xs_fmt("msg_admiration cannot retrieve object %s", object));
1574
1575    return msg;
1576}
1577
1578
1579xs_dict *msg_repulsion(snac *user, const char *id, const char *type)
1580/* creates an Undo + admiration message */
1581{
1582    xs *a_msg    = NULL;
1583    xs_dict *msg = NULL;
1584
1585    if (valid_status(object_get(id, &a_msg))) {
1586        /* create a clone of the original admiration message */
1587        xs *object = msg_admiration(user, id, type);
1588
1589        /* delete the published date */
1590        object = xs_dict_del(object, "published");
1591
1592        /* create an undo message for this object */
1593        msg = msg_undo(user, object);
1594
1595        /* copy the 'to' field */
1596        msg = xs_dict_set(msg, "to", xs_dict_get(object, "to"));
1597    }
1598
1599    /* now we despise this */
1600    object_unadmire(id, user->actor, *type == 'L' ? 1 : 0);
1601
1602    return msg;
1603}
1604
1605xs_dict *msg_emoji_init(snac *snac, const char *mid, const char *eid_o)
1606/* creates an emoji reaction from a local user */
1607{
1608    xs_dict *n_msg = msg_admiration(snac, mid, "EmojiReact");
1609
1610    xs *eid = xs_strip_chars_i(xs_dup(eid_o), ":");
1611    xs *content = NULL;
1612    xs *tag = xs_list_new();
1613    xs *dict = xs_dict_new();
1614    xs *icon = xs_dict_new();
1615    xs *accounts = xs_list_new();
1616    xs *emjs = emojis_rm_categories();
1617
1618    /* may be a default emoji */
1619    xs *eidd = xs_dup(eid);
1620    const char *eidda = eid;
1621
1622    if (xs_is_emoji(xs_utf8_dec(&eidda)))
1623        content = xs_dup(eid);
1624
1625    else if (*eid == '%') {
1626        content = xs_url_dec_emoji(xs_dup(eid));
1627        if (content == NULL) {
1628            xs_free(n_msg);
1629            return NULL;
1630        }
1631    }
1632    else {
1633        content = xs_fmt(":%s:", eid);
1634        const char *emo = xs_dict_get(emjs, content);
1635
1636        if (emo == NULL) {
1637            xs_free(n_msg);
1638            return NULL;
1639        }
1640
1641        if (xs_match(emo, "https://*|http://*")) { /* emoji is an URL to an image */
1642            icon = xs_dict_set(icon, "type", "Image");
1643            icon = xs_dict_set(icon, "url", emo);
1644            dict = xs_dict_set(dict, "icon", icon);
1645
1646            dict = xs_dict_set(dict, "id", emo);
1647            dict = xs_dict_set(dict, "name", content);
1648            dict = xs_dict_set(dict, "type", "Emoji");
1649            tag = xs_list_append(tag, dict);
1650        }
1651        else
1652        if (xs_startswith(emo, "&#")) {
1653            /* snac default emoji as an HTML entity: decode */
1654            content = xs_free(content);
1655
1656            xs *s1 = xs_strip_chars_i(xs_dup(emo), "&#");
1657            unsigned int cpoint = 0;
1658            sscanf(s1, "%u;", &cpoint);
1659
1660            if (cpoint)
1661                content = xs_utf8_cat(xs_str_new(NULL), cpoint);
1662            else
1663                content = xs_dup(emo);
1664        }
1665        else {
1666            /* use as it is and hope for the best */
1667            xs_free(content);
1668            content = xs_dup(emo);
1669        }
1670    }
1671
1672    accounts = xs_list_append(accounts, snac->actor);
1673
1674    xs *to_duplicate = xs_dup(xs_list_get(xs_dict_get(n_msg, "to"), 1));
1675    n_msg = xs_dict_set(n_msg, "content", content);
1676    n_msg = xs_dict_set(n_msg, "accounts", accounts);
1677    n_msg = xs_dict_set(n_msg, "attributedTo", to_duplicate);
1678    n_msg = xs_dict_set(n_msg, "accountId", snac->uid);
1679    n_msg = xs_dict_set(n_msg, "tag", tag);
1680
1681    int ret = timeline_admire(snac, xs_dict_get(n_msg, "object"), snac->actor, 1, n_msg);
1682    if (ret == 200 || ret == 201) {
1683        enqueue_message(snac, n_msg);
1684        return n_msg;
1685    }
1686
1687    xs_free(n_msg);
1688    return NULL;
1689}
1690
1691xs_dict *msg_emoji_unreact(snac *user, const char *mid, const char *eid)
1692/* creates an Undo + emoji reaction message */
1693{
1694    xs *a_msg    = NULL;
1695    xs_dict *msg = NULL;
1696
1697    if (valid_status(object_get(mid, &a_msg))) {
1698        /* create a clone of the original admiration message */
1699        xs *object = msg_admiration(user, mid, "EmojiReact");
1700
1701        /* delete the published date */
1702        object = xs_dict_del(object, "published");
1703
1704        /* create an undo message for this object */
1705        msg = msg_undo(user, object);
1706
1707        /* copy the 'to' field */
1708        msg = xs_dict_set(msg, "to", xs_dict_get(object, "to"));
1709    }
1710
1711    xs *emotes = object_get_emoji_reacts(mid);
1712    const char *v;
1713    int c = 0;
1714
1715    /* may be a default emoji */
1716    if (strlen(eid) == 12 && *eid == '%') {
1717        eid = xs_url_dec(eid);
1718        if (eid == NULL) {
1719            xs_free(msg);
1720            return NULL;
1721        }
1722    }
1723
1724    /* lets get all emotes for this msg, and compare it to our content */
1725    while (xs_list_next(emotes, &v, &c)) {
1726        xs *e = NULL;
1727        if (valid_status(object_get_by_md5(v, &e))) {
1728            const char *content = xs_dict_get(e, "content");
1729            const char *id = xs_dict_get(e, "id");
1730            const char *actor = xs_dict_get(e, "actor");
1731            /* maybe formated as :{emoteName}: too */
1732            if (xs_str_in(eid, content) != -1)
1733                if (strcmp(user->actor, actor) == 0) {
1734                    object_rm_emoji_react(mid, id);
1735                    return msg;
1736                }
1737        }
1738    }
1739
1740    xs_free(msg);
1741    return NULL;
1742}
1743
1744
1745xs_dict *msg_actor_place(snac *user, const char *label)
1746/* creates a Place object, if the user has a location defined */
1747{
1748    xs_dict *place = NULL;
1749    const char *latitude = xs_dict_get_def(user->config, "latitude", "");
1750    const char *longitude = xs_dict_get_def(user->config, "longitude", "");
1751
1752    if (*latitude && *longitude) {
1753        xs *d_la = xs_number_new(atof(latitude));
1754        xs *d_lo = xs_number_new(atof(longitude));
1755
1756        place = msg_base(user, "Place", NULL, user->actor, NULL, NULL);
1757
1758        place = xs_dict_set(place, "name", label);
1759        place = xs_dict_set(place, "latitude", d_la);
1760        place = xs_dict_set(place, "longitude", d_lo);
1761    }
1762
1763    return place;
1764}
1765
1766
1767xs_dict *msg_actor(snac *snac)
1768/* create a Person message for this actor */
1769{
1770    xs *ctxt     = xs_list_new();
1771    xs *icon     = xs_dict_new();
1772    xs *keys     = xs_dict_new();
1773    xs *tags     = xs_list_new();
1774    xs *avtr     = NULL;
1775    xs *kid      = NULL;
1776    xs *f_bio    = NULL;
1777    xs_dict *msg = NULL;
1778    const char *p;
1779    int n;
1780
1781    /* everybody loves some caching */
1782    if (time(NULL) - object_mtime(snac->actor) < 3 * 3600 &&
1783        valid_status(object_get(snac->actor, &msg))) {
1784        snac_debug(snac, 2, xs_fmt("Returning cached actor %s", snac->actor));
1785
1786        return msg;
1787    }
1788
1789    msg = msg_base(snac, "Person", snac->actor, NULL, NULL, NULL);
1790
1791    /* change the @context (is this really necessary?) */
1792    ctxt = xs_list_append(ctxt, "https:/" "/www.w3.org/ns/activitystreams");
1793    ctxt = xs_list_append(ctxt, "https:/" "/w3id.org/security/v1");
1794    msg = xs_dict_set(msg, "@context",          ctxt);
1795
1796    msg = xs_dict_set(msg, "url",               snac->actor);
1797    msg = xs_dict_set(msg, "name",              xs_dict_get(snac->config, "name"));
1798    msg = xs_dict_set(msg, "preferredUsername", snac->uid);
1799    msg = xs_dict_set(msg, "published",         xs_dict_get(snac->config, "published"));
1800
1801    // this exists so we get the emoji tags from our name too.
1802    // and then we just throw away the result, because it's kinda useless to have markdown in the display name.
1803    xs *name_dummy = not_really_markdown(xs_dict_get(snac->config, "name"), NULL, &tags);
1804
1805    xs *f_bio_2 = not_really_markdown(xs_dict_get(snac->config, "bio"), NULL, &tags);
1806    f_bio = process_tags(snac, f_bio_2, &tags);
1807    msg = xs_dict_set(msg, "summary", f_bio);
1808    msg = xs_dict_set(msg, "tag", tags);
1809
1810    char *folders[] = { "inbox", "outbox", "followers", "following", "featured", NULL };
1811    for (n = 0; folders[n]; n++) {
1812        xs *f = xs_fmt("%s/%s", snac->actor, folders[n]);
1813        msg = xs_dict_set(msg, folders[n], f);
1814    }
1815
1816    p = xs_dict_get(snac->config, "avatar");
1817
1818    if (*p == '\0')
1819        avtr = xs_fmt("%s/susie.png", srv_baseurl);
1820    else
1821        avtr = xs_dup(p);
1822
1823    icon = xs_dict_append(icon, "type",         "Image");
1824    icon = xs_dict_append(icon, "mediaType",    xs_mime_by_ext(avtr));
1825    icon = xs_dict_append(icon, "url",          avtr);
1826    msg = xs_dict_set(msg, "icon", icon);
1827
1828    kid = xs_fmt("%s#main-key", snac->actor);
1829
1830    keys = xs_dict_append(keys, "id",           kid);
1831    keys = xs_dict_append(keys, "owner",        snac->actor);
1832    keys = xs_dict_append(keys, "publicKeyPem", xs_dict_get(snac->key, "public"));
1833    msg = xs_dict_set(msg, "publicKey", keys);
1834
1835    /* if the "bot" config field is set to true, change type to "Service" */
1836    if (xs_type(xs_dict_get(snac->config, "bot")) == XSTYPE_TRUE)
1837        msg = xs_dict_set(msg, "type", "Service");
1838
1839    /* if it's named "relay", then identify as an "Application" */
1840    if (strcmp(snac->uid, "relay") == 0)
1841        msg = xs_dict_set(msg, "type", "Application");
1842
1843    /* add the header image, if there is one defined */
1844    const char *header = xs_dict_get(snac->config, "header");
1845    if (!xs_is_null(header)) {
1846        xs *d = xs_dict_new();
1847        d = xs_dict_append(d, "type",       "Image");
1848        d = xs_dict_append(d, "mediaType",  xs_mime_by_ext(header));
1849        d = xs_dict_append(d, "url",        header);
1850        msg = xs_dict_set(msg, "image", d);
1851    }
1852
1853    /* add the metadata as attachments of PropertyValue */
1854    xs *metadata = NULL;
1855    const xs_dict *md = xs_dict_get(snac->config, "metadata");
1856
1857    if (xs_type(md) == XSTYPE_DICT)
1858        metadata = xs_dup(md);
1859    else
1860    if (xs_type(md) == XSTYPE_STRING) {
1861        metadata = xs_dict_new();
1862        xs *l = xs_split(md, "\n");
1863        const char *ll;
1864
1865        xs_list_foreach(l, ll) {
1866            xs *kv = xs_split_n(ll, "=", 1);
1867            const char *k = xs_list_get(kv, 0);
1868            const char *v = xs_list_get(kv, 1);
1869
1870            if (k && v) {
1871                xs *kk = xs_strip_i(xs_dup(k));
1872                xs *vv = xs_strip_i(xs_dup(v));
1873                metadata = xs_dict_set(metadata, kk, vv);
1874            }
1875        }
1876    }
1877
1878    if (xs_type(metadata) == XSTYPE_DICT) {
1879        xs *attach = xs_list_new();
1880        const xs_str *k;
1881        const xs_str *v;
1882
1883        int c = 0;
1884        while (xs_dict_next(metadata, &k, &v, &c)) {
1885            xs *d = xs_dict_new();
1886
1887            xs *k2 = encode_html(k);
1888            xs *v2 = NULL;
1889
1890            if (xs_startswith(v, "https:/") || xs_startswith(v, "http:/")) {
1891                xs *t = encode_html(v);
1892                v2 = xs_fmt("<a href=\"%s\" rel=\"me\">%s</a>", t, t);
1893            }
1894            else
1895                v2 = encode_html(v);
1896
1897            d = xs_dict_append(d, "type",  "PropertyValue");
1898            d = xs_dict_append(d, "name",  k2);
1899            d = xs_dict_append(d, "value", v2);
1900
1901            attach = xs_list_append(attach, d);
1902        }
1903
1904        msg = xs_dict_set(msg, "attachment", attach);
1905    }
1906
1907    /* use shared inboxes? */
1908    if (xs_is_true(xs_dict_get(srv_config, "shared_inboxes")) || strcmp(snac->uid, "relay") == 0) {
1909        xs *d = xs_dict_new();
1910        xs *si = xs_fmt("%s/shared-inbox", srv_baseurl);
1911        d = xs_dict_append(d, "sharedInbox", si);
1912        msg = xs_dict_set(msg, "endpoints", d);
1913    }
1914
1915    /* does this user have an aka? */
1916    const char *aka = xs_dict_get(snac->config, "alias");
1917    if (xs_type(aka) == XSTYPE_STRING && *aka) {
1918        xs *loaka = xs_list_append(xs_list_new(), aka);
1919
1920        msg = xs_dict_set(msg, "alsoKnownAs", loaka);
1921    }
1922
1923    const xs_val *manually = xs_dict_get(snac->config, "approve_followers");
1924    msg = xs_dict_set(msg, "manuallyApprovesFollowers",
1925        xs_stock(xs_is_true(manually) ? XSTYPE_TRUE : XSTYPE_FALSE));
1926
1927    /* if there are location coords, create a Place object */
1928    xs *location = msg_actor_place(snac, "Home");
1929    if (xs_type(location) == XSTYPE_DICT)
1930        msg = xs_dict_set(msg, "location", location);
1931
1932    xs *webfinger = xs_fmt("%s@%s", snac->uid, xs_dict_get(srv_config, "host"));
1933    msg = xs_dict_set(msg, "webfinger", webfinger);
1934
1935    if (xs_is_true(xs_dict_get(snac->config, "show_contact_metrics"))) {
1936        xs *fwing = xs_number_new_l(following_list_len(snac));
1937        xs *fwers = xs_number_new_l(follower_list_len(snac));
1938
1939        msg = xs_dict_set(msg, "following_count", fwing);
1940        msg = xs_dict_set(msg, "followers_count", fwers);
1941    }
1942
1943    /* cache it */
1944    snac_debug(snac, 1, xs_fmt("Caching actor %s", snac->actor));
1945    object_add_ow(snac->actor, msg);
1946
1947    return msg;
1948}
1949
1950
1951xs_dict *msg_create(snac *snac, const xs_dict *object)
1952/* creates a 'Create' message */
1953{
1954    xs_dict *msg = msg_base(snac, "Create", "@wrapper", snac->actor, NULL, object);
1955    const xs_val *v;
1956
1957    if ((v = get_atto(object)))
1958        msg = xs_dict_append(msg, "attributedTo", v);
1959
1960    if ((v = xs_dict_get(object, "cc")))
1961        msg = xs_dict_append(msg, "cc", v);
1962
1963    if ((v = xs_dict_get(object, "to")))
1964        msg = xs_dict_append(msg, "to", v);
1965    else
1966        msg = xs_dict_append(msg, "to", public_address);
1967
1968    return msg;
1969}
1970
1971
1972xs_dict *msg_undo(snac *snac, const xs_val *object)
1973/* creates an 'Undo' message */
1974{
1975    xs_dict *msg = msg_base(snac, "Undo", "@object", snac->actor, "@now", object);
1976    const char *to;
1977
1978    if (xs_type(object) == XSTYPE_DICT && (to = xs_dict_get(object, "object")))
1979        msg = xs_dict_append(msg, "to", to);
1980
1981    return msg;
1982}
1983
1984
1985xs_dict *msg_delete(snac *snac, const char *id)
1986/* creates a 'Delete' + 'Tombstone' for a local entry */
1987{
1988    xs *tomb = xs_dict_new();
1989    xs_dict *msg = NULL;
1990
1991    /* sculpt the tombstone */
1992    tomb = xs_dict_append(tomb, "type", "Tombstone");
1993    tomb = xs_dict_append(tomb, "id",   id);
1994
1995    /* now create the Delete */
1996    msg = msg_base(snac, "Delete", "@object", snac->actor, "@now", tomb);
1997
1998    xs *to = xs_list_new();
1999    xs *involved = object_likes(id);
2000    xs *boosts = object_announces(id);
2001    xs *children = object_children(id);
2002    const char *md5;
2003
2004    involved = xs_list_cat(involved, boosts);
2005    involved = xs_list_cat(involved, children);
2006
2007    /* add everybody */
2008    to = xs_list_append(to, public_address);
2009
2010    /* add actors that liked, boosted or replied to this */
2011    xs_list_foreach(involved, md5) {
2012        xs *actor = NULL;
2013
2014        if (valid_status(object_get_by_md5(md5, &actor))) {
2015            const char *id = xs_dict_get(actor, "id");
2016            const char *atto = get_atto(actor);
2017
2018            if (xs_is_string(atto))
2019                to = xs_list_append(to, atto);
2020            else
2021            if (xs_is_string(id))
2022                to = xs_list_append(to, id);
2023        }
2024    }
2025
2026    msg = xs_dict_append(msg, "to", to);
2027
2028    return msg;
2029}
2030
2031
2032xs_dict *msg_follow(snac *snac, const char *q)
2033/* creates a 'Follow' message */
2034{
2035    xs *actor_o = NULL;
2036    xs *actor   = NULL;
2037    xs_dict *msg = NULL;
2038    int status;
2039
2040    xs *url_or_uid = xs_strip_i(xs_str_new(q));
2041
2042    if (xs_startswith(url_or_uid, "https:/") || xs_startswith(url_or_uid, "http:/"))
2043        actor = xs_dup(url_or_uid);
2044    else
2045    if (!valid_status(webfinger_request(url_or_uid, &actor, NULL)) || actor == NULL) {
2046        snac_log(snac, xs_fmt("cannot resolve user %s to follow", url_or_uid));
2047        return NULL;
2048    }
2049
2050    /* request the actor */
2051    status = actor_request(snac, actor, &actor_o);
2052
2053    if (valid_status(status)) {
2054        /* check if the actor is an alias */
2055        const char *r_actor = xs_dict_get(actor_o, "id");
2056
2057        if (r_actor && strcmp(actor, r_actor) != 0) {
2058            snac_log(snac, xs_fmt("actor to follow is an alias %s -> %s", actor, r_actor));
2059        }
2060
2061        msg = msg_base(snac, "Follow", "@dummy", snac->actor, NULL, r_actor);
2062    }
2063    else
2064        snac_log(snac, xs_fmt("cannot get actor to follow %s %d", actor, status));
2065
2066    return msg;
2067}
2068
2069
2070xs_dict *msg_note(snac *snac, const xs_str *content, const xs_val *rcpts,
2071                  const xs_str *in_reply_to, const xs_list *attach,
2072                  int scope, const char *lang_str, const char *msg_date)
2073/* creates a 'Note' message */
2074/* scope: 0, public; 1, private (mentioned only); 2, "quiet public"; 3, followers only */
2075{
2076    xs *ntid = tid(0);
2077    xs *id   = xs_fmt("%s/p/%s", snac->actor, ntid);
2078    xs *ctxt = NULL;
2079    xs *fc2  = NULL;
2080    xs *fc1  = NULL;
2081    xs *to   = NULL;
2082    xs *cc   = xs_list_new();
2083    xs *irt  = NULL;
2084    xs *tag  = xs_list_new();
2085    xs *atls = xs_list_new();
2086
2087    /* discard non-parseable dates */
2088    if (!xs_is_string(msg_date) || xs_parse_iso_date(msg_date, 0) == 0)
2089        msg_date = NULL;
2090
2091    xs_dict *msg = msg_base(snac, "Note", id, NULL, xs_or(msg_date, "@now"), NULL);
2092    xs_list *p;
2093    const xs_val *v;
2094
2095    const int priv = (scope == SCOPE_MENTIONED || scope == SCOPE_FOLLOWERS);
2096
2097    if (rcpts == NULL)
2098        to = xs_list_new();
2099    else {
2100        if (xs_type(rcpts) == XSTYPE_STRING) {
2101            to = xs_list_new();
2102            to = xs_list_append(to, rcpts);
2103        }
2104        else
2105            to = xs_dup(rcpts);
2106    }
2107
2108    /* format the content */
2109    fc2 = not_really_markdown(content, &atls, &tag);
2110
2111    if (in_reply_to != NULL && *in_reply_to) {
2112        xs *p_msg = NULL;
2113        xs *wrk   = NULL;
2114
2115        /* demand this thing */
2116        timeline_request(snac, &in_reply_to, &wrk, 0);
2117
2118        if (valid_status(object_get(in_reply_to, &p_msg))) {
2119            /* add this author as recipient */
2120            const char *a, *v;
2121
2122            if ((a = get_atto(p_msg)) && xs_list_in(to, a) == -1)
2123                to = xs_list_append(to, a);
2124
2125            /* add this author to the tag list as a mention */
2126            if (!xs_is_null(a)) {
2127                xs *l = xs_split(a, "/");
2128                xs *actor_o = NULL;
2129
2130                if (xs_list_len(l) > 3 && valid_status(object_get(a, &actor_o))) {
2131                    const char *uname = xs_dict_get(actor_o, "preferredUsername");
2132
2133                    if (!xs_is_null(uname) && *uname) {
2134                        xs *handle = xs_fmt("@%s@%s", uname, xs_list_get(l, 2));
2135
2136                        xs *t = xs_dict_new();
2137
2138                        t = xs_dict_append(t, "type", "Mention");
2139                        t = xs_dict_append(t, "href", a);
2140                        t = xs_dict_append(t, "name", handle);
2141
2142                        tag = xs_list_append(tag, t);
2143                    }
2144                }
2145            }
2146
2147            /* get the context, if there is one */
2148            if ((v = xs_dict_get(p_msg, "context")))
2149                ctxt = xs_dup(v);
2150
2151            /* propagate the conversation field, if there is one */
2152            if ((v = xs_dict_get(p_msg, "conversation")))
2153                msg = xs_dict_append(msg, "conversation", v);
2154
2155            /* if this message is public or unlisted, ours will also be */
2156            const int orig_scope = get_msg_visibility(p_msg);
2157            if (!priv && orig_scope == SCOPE_PUBLIC && xs_list_in(to, public_address) == -1)
2158                to = xs_list_append(to, public_address);
2159            else
2160            if (!priv && orig_scope == SCOPE_UNLISTED && xs_list_in(cc, public_address) == -1)
2161                cc = xs_list_append(cc, public_address);
2162        }
2163
2164        irt = xs_dup(in_reply_to);
2165    }
2166    else
2167        irt = xs_val_new(XSTYPE_NULL);
2168
2169    /* extract the mentions and hashtags and convert the content */
2170    fc1 = process_tags(snac, fc2, &tag);
2171
2172    /* create the attachment list, if there are any */
2173    if (!xs_is_null(attach)) {
2174        xs_list_foreach(attach, v) {
2175            const char *url  = xs_list_get(v, 0);
2176            const char *alt  = xs_list_get(v, 1);
2177            const char *mime = xs_mime_by_ext(url);
2178            int add = 1;
2179
2180            /* check if it's already here */
2181            const xs_dict *ad;
2182            xs_list_foreach(atls, ad) {
2183                if (strcmp(xs_dict_get_def(ad, "url", ""), url) == 0) {
2184                    add = 0;
2185                    break;
2186                }
2187            }
2188
2189            if (add) {
2190                xs *d = xs_dict_new();
2191                d = xs_dict_append(d, "mediaType", mime);
2192                d = xs_dict_append(d, "url",       url);
2193                d = xs_dict_append(d, "name",      alt);
2194                d = xs_dict_append(d, "type",
2195                    xs_startswith(mime, "image/") ? "Image" : "Document");
2196
2197                atls = xs_list_append(atls, d);
2198            }
2199        }
2200    }
2201
2202    if (ctxt == NULL)
2203        ctxt = xs_fmt("%s#ctxt", id);
2204
2205    /* add all mentions to the appropriate field */
2206    p = tag;
2207    while (xs_list_iter(&p, &v)) {
2208        if (xs_type(v) == XSTYPE_DICT) {
2209            const char *t;
2210
2211            if (!xs_is_null(t = xs_dict_get(v, "type")) && strcmp(t, "Mention") == 0) {
2212                if (!xs_is_null(t = xs_dict_get(v, "href"))) {
2213                    if (scope == SCOPE_MENTIONED) {
2214                        /* for DMs, mentions go to 'to' */
2215                        to = xs_list_append(to, t);
2216                    } else {
2217                        /* for other visibility levels, mentions go to 'cc' */
2218                        cc = xs_list_append(cc, t);
2219                    }
2220                }
2221            }
2222        }
2223    }
2224
2225    if (scope == SCOPE_UNLISTED) {
2226        /* Mastodon's "quiet public": remove from to, add public address to cc */
2227        int idx;
2228        if ((idx = xs_list_in(to, public_address)) != -1)
2229            to = xs_list_del(to, idx);
2230        if (xs_list_in(cc, public_address) == -1)
2231            cc = xs_list_append(cc, public_address);
2232    }
2233    else
2234    if (scope == SCOPE_FOLLOWERS) {
2235        /* followers-only: add followers collection to to */
2236        xs *followers_url = xs_fmt("%s/followers", snac->actor);
2237        if (xs_list_in(to, followers_url) == -1)
2238            to = xs_list_append(to, followers_url);
2239    }
2240    else
2241    if (scope == SCOPE_PUBLIC) {
2242        /* public: ensure public address is in to and not in cc */
2243        int idx;
2244        if ((idx = xs_list_in(cc, public_address)) != -1)
2245            cc = xs_list_del(cc, idx);
2246        if (xs_list_in(to, public_address) == -1)
2247            to = xs_list_append(to, public_address);
2248    }
2249
2250    /* delete all cc recipients that also are in the to */
2251    p = to;
2252    while (xs_list_iter(&p, &v)) {
2253        int i;
2254
2255        if ((i = xs_list_in(cc, v)) != -1)
2256            cc = xs_list_del(cc, i);
2257    }
2258
2259    msg = xs_dict_append(msg, "attributedTo", snac->actor);
2260    msg = xs_dict_append(msg, "summary",      "");
2261    msg = xs_dict_append(msg, "content",      fc1);
2262    msg = xs_dict_append(msg, "context",      ctxt);
2263    msg = xs_dict_append(msg, "url",          id);
2264    msg = xs_dict_append(msg, "to",           to);
2265    msg = xs_dict_append(msg, "cc",           cc);
2266    msg = xs_dict_append(msg, "inReplyTo",    irt);
2267    msg = xs_dict_append(msg, "tag",          tag);
2268
2269    msg = xs_dict_append(msg, "sourceContent", content);
2270
2271    if (xs_list_len(atls))
2272        msg = xs_dict_append(msg, "attachment", atls);
2273
2274    /* set language content map */
2275    if (xs_type(lang_str) == XSTYPE_STRING) {
2276        /* split at the first _ */
2277        xs *l0 = xs_split(lang_str, "_");
2278        const char *lang = xs_list_get(l0, 0);
2279
2280        if (xs_type(lang) == XSTYPE_STRING && strlen(lang) == 2) {
2281            /* a valid ISO language id */
2282            xs *cmap = xs_dict_new();
2283            cmap = xs_dict_set(cmap, lang, xs_dict_get(msg, "content"));
2284            msg = xs_dict_set(msg, "contentMap", cmap);
2285        }
2286    }
2287
2288    if (!priv) {
2289        /* create the replies object */
2290        xs *replies = xs_dict_new();
2291        xs *r_id = xs_replace(id, "/p/", "/r/");
2292        xs *h_id = xs_fmt("%s", r_id);
2293        xs *rp = msg_replies(snac, id, 0);
2294
2295        replies = xs_dict_set(replies, "id", h_id);
2296        replies = xs_dict_set(replies, "type", "Collection");
2297        replies = xs_dict_set(replies, "first", rp);
2298
2299        msg = xs_dict_set(msg, "replies", replies);
2300    }
2301
2302    return msg;
2303}
2304
2305
2306xs_dict *msg_ping(snac *user, const char *rcpt)
2307/* creates a Ping message (https://humungus.tedunangst.com/r/honk/v/tip/f/docs/ping.txt) */
2308{
2309    xs_dict *msg = msg_base(user, "Ping", "@dummy", user->actor, NULL, NULL);
2310
2311    msg = xs_dict_append(msg, "to", rcpt);
2312
2313    return msg;
2314}
2315
2316
2317xs_dict *msg_pong(snac *user, const char *rcpt, const char *object)
2318/* creates a Pong message (https://humungus.tedunangst.com/r/honk/v/tip/f/docs/ping.txt) */
2319{
2320    xs_dict *msg = msg_base(user, "Pong", "@dummy", user->actor, NULL, object);
2321
2322    msg = xs_dict_append(msg, "to", rcpt);
2323
2324    return msg;
2325}
2326
2327
2328xs_dict *msg_move(snac *user, const char *new_account)
2329/* creates a Move message (to move the user to new_account) */
2330{
2331    xs_dict *msg = msg_base(user, "Move", "@dummy", user->actor, NULL, user->actor);
2332
2333    msg = xs_dict_append(msg, "target", new_account);
2334
2335    return msg;
2336}
2337
2338
2339xs_dict *msg_question(snac *user, const char *content, xs_list *attach,
2340                      const xs_list *opts, int multiple, int end_secs)
2341/* creates a Question message */
2342{
2343    xs_dict *msg = msg_note(user, content, NULL, NULL, attach, 0, NULL, NULL);
2344    const xs_number *max_options = xs_dict_get(srv_config, "max_poll_options");
2345    const xs_number *max_length = xs_dict_get(srv_config, "max_poll_option_length");
2346    xs_set seen;
2347
2348    size_t max_line = 60;
2349    int max = 8;
2350    if (xs_type(max_options) == XSTYPE_NUMBER)
2351        max = xs_number_get(max_options);
2352    if (xs_type(max_length) == XSTYPE_NUMBER)
2353        max_line = xs_number_get(max_length);
2354
2355    msg = xs_dict_set(msg, "type", "Question");
2356
2357    /* make it non-editable */
2358    msg = xs_dict_del(msg, "sourceContent");
2359
2360    xs *o = xs_list_new();
2361    xs_list *p = (xs_list *)opts;
2362    const xs_str *v;
2363    xs *replies = xs_json_loads("{\"type\":\"Collection\",\"totalItems\":0}");
2364
2365    xs_set_init(&seen);
2366
2367    while (max && xs_list_iter(&p, &v)) {
2368        if (*v) {
2369            xs *v2 = xs_dup(v);
2370            xs *d  = xs_dict_new();
2371
2372            if (strlen(v2) > max_line) {
2373                v2[max_line] = '\0';
2374                v2 = xs_str_cat(v2, "...");
2375            }
2376
2377            if (xs_set_add(&seen, v2) == 1) {
2378                d = xs_dict_append(d, "type",    "Note");
2379                d = xs_dict_append(d, "name",    v2);
2380                d = xs_dict_append(d, "replies", replies);
2381                o = xs_list_append(o, d);
2382
2383                max--;
2384            }
2385        }
2386    }
2387
2388    xs_set_free(&seen);
2389
2390    msg = xs_dict_append(msg, multiple ? "anyOf" : "oneOf", o);
2391
2392    /* set the end time */
2393    time_t t = time(NULL) + end_secs;
2394    xs *et = xs_str_utctime(t, ISO_DATE_SPEC);
2395
2396    msg = xs_dict_append(msg, "endTime", et);
2397
2398    return msg;
2399}
2400
2401int get_msg_visibility(const xs_dict *msg)
2402/* determine visibility from message based on CC, TO and /followers mark */
2403{
2404    const xs_val *to = xs_dict_get(msg, "to");
2405    const xs_val *cc = xs_dict_get(msg, "cc");
2406
2407    /* check if it's unlisted (public in cc but not in to) */
2408    int pub_in_to = 0;
2409    int pub_in_cc = 0;
2410
2411    if ((xs_type(to) == XSTYPE_STRING && strcmp(to, public_address) == 0) ||
2412        (xs_type(to) == XSTYPE_LIST && xs_list_in(to, public_address) != -1))
2413        pub_in_to = 1;
2414
2415    if ((xs_type(cc) == XSTYPE_STRING && strcmp(cc, public_address) == 0) ||
2416        (xs_type(cc) == XSTYPE_LIST && xs_list_in(cc, public_address) != -1))
2417        pub_in_cc = 1;
2418
2419    if (!pub_in_to && pub_in_cc) {
2420        return SCOPE_UNLISTED;
2421    }
2422    if (pub_in_to && !pub_in_cc) {
2423        return SCOPE_PUBLIC;
2424    }
2425
2426    xs *followers_url = xs_fmt("%s/followers", xs_dict_get(msg, "attributedTo"));
2427
2428    if ((xs_type(to) == XSTYPE_STRING && strcmp(to, followers_url) == 0) ||
2429        (xs_type(to) == XSTYPE_LIST && xs_list_in(to, followers_url) != -1))
2430        return SCOPE_FOLLOWERS;
2431    else
2432        return SCOPE_MENTIONED;
2433    /* should be unreachable, someone violated the protocol.                    */
2434    /* better treat it as followers-only to make sure we don't leak information.*/
2435    return SCOPE_FOLLOWERS;
2436}
2437
2438int update_question(snac *user, const char *id)
2439/* updates the poll counts */
2440{
2441    xs *msg   = NULL;
2442    xs *rcnt  = xs_dict_new();
2443    xs *lopts = xs_list_new();
2444    const xs_list *opts;
2445    xs_list *p;
2446    const xs_val *v;
2447
2448    /* get the object */
2449    if (!valid_status(object_get(id, &msg)))
2450        return -1;
2451
2452    /* closed? do nothing more */
2453    if (xs_dict_get(msg, "closed"))
2454        return -2;
2455
2456    /* get the options */
2457    if ((opts = xs_dict_get(msg, "oneOf")) == NULL &&
2458        (opts = xs_dict_get(msg, "anyOf")) == NULL)
2459        return -3;
2460
2461    /* fill the initial count */
2462    int c = 0;
2463    while (xs_list_next(opts, &v, &c)) {
2464        const char *name = xs_dict_get(v, "name");
2465        if (name) {
2466            lopts = xs_list_append(lopts, name);
2467            rcnt  = xs_dict_set(rcnt, name, xs_stock(0));
2468        }
2469    }
2470
2471    xs_set s;
2472    xs_set_init(&s);
2473
2474    /* iterate now the children (the votes) */
2475    xs *chld = object_children(id);
2476    p = chld;
2477    while (xs_list_iter(&p, &v)) {
2478        xs *obj = NULL;
2479
2480        if (!valid_status(object_get_by_md5(v, &obj)))
2481            continue;
2482
2483        const char *name = xs_dict_get(obj, "name");
2484        const char *atto = get_atto(obj);
2485
2486        if (name && atto) {
2487            /* get the current count */
2488            const xs_number *cnt = xs_dict_get(rcnt, name);
2489
2490            if (xs_type(cnt) == XSTYPE_NUMBER) {
2491                /* if it exists, increment */
2492                xs *ucnt = xs_number_new(xs_number_get(cnt) + 1);
2493                rcnt = xs_dict_set(rcnt, name, ucnt);
2494
2495                xs_set_add(&s, atto);
2496            }
2497        }
2498    }
2499
2500    xs *rcpts = xs_set_result(&s);
2501
2502    /* create a new list of options with their new counts */
2503    xs *nopts = xs_list_new();
2504    p = lopts;
2505    while (xs_list_iter(&p, &v)) {
2506        const xs_number *cnt = xs_dict_get(rcnt, v);
2507
2508        if (xs_type(cnt) == XSTYPE_NUMBER) {
2509            xs *d1 = xs_dict_new();
2510            xs *d2 = xs_dict_new();
2511
2512            d2 = xs_dict_append(d2, "type",       "Collection");
2513            d2 = xs_dict_append(d2, "totalItems", cnt);
2514
2515            d1 = xs_dict_append(d1, "type",    "Note");
2516            d1 = xs_dict_append(d1, "name",    v);
2517            d1 = xs_dict_append(d1, "replies", d2);
2518
2519            nopts = xs_list_append(nopts, d1);
2520        }
2521    }
2522
2523    /* update the list */
2524    msg = xs_dict_set(msg, xs_dict_get(msg, "oneOf") != NULL ? "oneOf" : "anyOf", nopts);
2525
2526    /* due date? */
2527    int closed = 0;
2528    const char *end_time = xs_dict_get(msg, "endTime");
2529    if (!xs_is_null(end_time)) {
2530        xs *now = xs_str_utctime(0, ISO_DATE_SPEC);
2531
2532        /* is now greater than the endTime? */
2533        if (strcmp(now, end_time) >= 0) {
2534            xs *et    = xs_dup(end_time);
2535            msg       = xs_dict_set(msg, "closed", et);
2536
2537            closed = 1;
2538        }
2539    }
2540
2541    /* update the count of voters */
2542    xs *vcnt = xs_number_new(xs_list_len(rcpts));
2543    msg = xs_dict_set(msg, "votersCount", vcnt);
2544    msg = xs_dict_set(msg, "cc", rcpts);
2545
2546    /* store */
2547    object_add_ow(id, msg);
2548
2549    snac_debug(user, 1, xs_fmt("recounted poll %s", id));
2550    timeline_touch(user);
2551
2552    /* send an update message to all voters */
2553    xs *u_msg = msg_update(user, msg);
2554    u_msg = xs_dict_set(u_msg, "cc", rcpts);
2555
2556    enqueue_message(user, u_msg);
2557
2558    if (closed) {
2559        xs *c_msg = msg_update(user, msg);
2560        notify(user, "Update", "Question", user->actor, c_msg);
2561    }
2562
2563    return 0;
2564}
2565
2566
2567/** queues **/
2568
2569int process_input_message(snac *snac, const xs_dict *msg, const xs_dict *req)
2570/* processes an ActivityPub message from the input queue */
2571/* return values: -1, fatal error; 0, transient error, retry;
2572   1, processed and done; 2, propagate to users (only when no user is set) */
2573{
2574    const char *actor = xs_dict_get(msg, "actor");
2575    const char *type  = xs_dict_get(msg, "type");
2576    xs *actor_o = NULL;
2577    int a_status;
2578    int do_notify = 0;
2579
2580    if (xs_is_null(actor) || *actor == '\0') {
2581        srv_debug(0, xs_fmt("malformed message (bad actor)"));
2582        return -1;
2583    }
2584
2585    /* this instance is alive */
2586    instance_failure(actor, 2);
2587
2588    /* question votes may not have a type */
2589    if (xs_is_null(type))
2590        type = "Note";
2591
2592    /* reject uninteresting messages right now */
2593    if (xs_match(type, "Add|View|Reject|Read|Remove")) {
2594        srv_debug(0, xs_fmt("Ignored message of type '%s'", type));
2595
2596        /* archive the ignored activity */
2597        xs *ntid = tid(0);
2598        xs *fn = xs_fmt("%s/ignored/%s.json", srv_basedir, ntid);
2599        FILE *f;
2600
2601        if ((f = fopen(fn, "w")) != NULL) {
2602            xs_json_dump(msg, 4, f);
2603            fclose(f);
2604        }
2605
2606        return -1;
2607    }
2608
2609    if (strcmp(type, "EmojiReact") == 0 && xs_is_true(xs_dict_get(srv_config, "disable_emojireact"))) {
2610        srv_log(xs_fmt("Dropping EmojiReact from %s due to admin configuration", actor));
2611        return -1;
2612    }
2613
2614    const char *object, *utype;
2615
2616    object = xs_dict_get(msg, "object");
2617    if (object != NULL && xs_type(object) == XSTYPE_DICT)
2618        utype = xs_dict_get(object, "type");
2619    else
2620        utype = "(null)";
2621
2622    /* special case for Delete messages */
2623    if (strcmp(type, "Delete") == 0) {
2624        /* if the actor is not here, do not even try */
2625        if (!object_here(actor)) {
2626            srv_debug(1, xs_fmt("dropped 'Delete' message from unknown actor '%s'", actor));
2627            return -1;
2628        }
2629
2630        /* discard crap */
2631        if (xs_is_null(object)) {
2632            srv_log(xs_fmt("dropped 'Delete' message with invalid object from actor '%s'", actor));
2633            return -1;
2634        }
2635
2636        /* also discard if the object to be deleted is not here */
2637        const char *obj_id = object;
2638        if (xs_type(obj_id) == XSTYPE_DICT)
2639            obj_id = xs_dict_get(obj_id, "id");
2640
2641        if (xs_is_null(obj_id) || !object_here(obj_id)) {
2642            srv_debug(1, xs_fmt("dropped 'Delete' message from unknown object '%s'", obj_id));
2643            return -1;
2644        }
2645    }
2646
2647    /* bring the actor */
2648    a_status = actor_request(snac, actor, &actor_o);
2649
2650    /* do not retry permanent failures */
2651    if (a_status == HTTP_STATUS_NOT_FOUND
2652        || a_status == HTTP_STATUS_GONE
2653        || a_status < 0) {
2654        srv_debug(1, xs_fmt("dropping message due to actor error %s %d", actor, a_status));
2655        return -1;
2656    }
2657
2658    if (!valid_status(a_status)) {
2659        /* do not retry 'Delete' messages */
2660        if (strcmp(type, "Delete") == 0) {
2661            srv_debug(1, xs_fmt("dropping 'Delete' message due to actor error %s %d", actor, a_status));
2662            return -1;
2663        }
2664
2665        /* other actor download errors */
2666
2667        /* the actor may require a signed request; propagate if no user is set */
2668        if (snac == NULL)
2669            return 2;
2670
2671        /* may need a retry */
2672        srv_debug(0, xs_fmt("error requesting actor %s %d -- retry later", actor, a_status));
2673        return 0;
2674    }
2675
2676    /* check the signature */
2677    xs *sig_err = NULL;
2678
2679    if (!check_signature(req, &sig_err)) {
2680        srv_log(xs_fmt("bad signature %s (%s)", actor, sig_err));
2681
2682        srv_archive_error("check_signature", sig_err, req, msg);
2683        return -1;
2684    }
2685
2686    /* if no user is set, no further checks can be done; propagate */
2687    if (snac == NULL)
2688        return 2;
2689
2690    /* reject messages that are not for this user */
2691    if (!is_msg_for_me(snac, msg)) {
2692        snac_debug(snac, 1, xs_fmt("message from %s of type '%s' not for us", actor, type));
2693
2694        return 1;
2695    }
2696
2697    /* if it's a DM from someone we don't follow, reject the message */
2698    if (xs_type(xs_dict_get(snac->config, "drop_dm_from_unknown")) == XSTYPE_TRUE) {
2699        if (strcmp(utype, "Note") == 0 && !is_msg_public(msg) &&
2700            !following_check(snac, actor)) {
2701            snac_log(snac, xs_fmt("DM rejected from unknown actor %s", actor));
2702
2703            return 1;
2704        }
2705    }
2706
2707    /* check the minimum acceptable account age */
2708    int min_account_age = xs_number_get(xs_dict_get(srv_config, "min_account_age"));
2709
2710    if (min_account_age > 0) {
2711        const char *actor_date = xs_dict_get(actor_o, "published");
2712        if (!xs_is_null(actor_date)) {
2713            time_t actor_t = xs_parse_iso_date(actor_date, 0);
2714
2715            if (actor_t < 950000000) {
2716                snac_log(snac, xs_fmt("rejected activity from %s (suspicious date, %s)",
2717                    actor, actor_date));
2718
2719                return 1;
2720            }
2721
2722            if (actor_t > 0) {
2723                int td = (int)(time(NULL) - actor_t);
2724
2725                snac_debug(snac, 2, xs_fmt("actor %s age: %d seconds", actor, td));
2726
2727                if (td < min_account_age) {
2728                    snac_log(snac, xs_fmt("rejected activity from %s (too new, %d seconds)",
2729                        actor, td));
2730
2731                    return 1;
2732                }
2733            }
2734        }
2735        else
2736            snac_debug(snac, 1, xs_fmt("warning: empty or null creation date for %s", actor));
2737    }
2738
2739    if (strcmp(type, "Follow") == 0) { /** **/
2740        const char *id = xs_dict_get(msg, "id");
2741
2742        if (xs_is_null(id)) {
2743            snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2744        }
2745        else
2746        if (!follower_check(snac, actor)) {
2747            /* ensure the actor object is here */
2748            if (!object_here(actor)) {
2749                xs *actor_obj = NULL;
2750                actor_request(snac, actor, &actor_obj);
2751                object_add(actor, actor_obj);
2752            }
2753
2754            if (xs_is_true(xs_dict_get(snac->config, "approve_followers"))) {
2755                pending_add(snac, actor, msg);
2756
2757                snac_log(snac, xs_fmt("new pending follower approval %s", actor));
2758            }
2759            else {
2760                /* automatic following */
2761                xs *f_msg = xs_dup(msg);
2762                xs *reply = msg_accept(snac, f_msg, actor);
2763
2764                post_message(snac, actor, reply);
2765
2766                if (xs_is_null(xs_dict_get(f_msg, "published"))) {
2767                    /* add a date if it doesn't include one (Mastodon) */
2768                    xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
2769                    f_msg = xs_dict_set(f_msg, "published", date);
2770                }
2771
2772                timeline_add(snac, id, f_msg);
2773
2774                follower_add(snac, actor);
2775
2776                snac_log(snac, xs_fmt("new follower %s", actor));
2777            }
2778
2779            do_notify = 1;
2780        }
2781        else
2782            snac_log(snac, xs_fmt("repeated 'Follow' from %s", actor));
2783    }
2784    else
2785    if (strcmp(type, "Undo") == 0) { /** **/
2786        const char *id = xs_dict_get(object, "object");
2787        const char *content = xs_dict_get(object, "content");
2788        /* misskey sends emojis as like + tag */
2789        xs *cd = xs_dup(content);
2790        const char *sna = cd;
2791        const xs_dict *tag = xs_dict_get(object, "tag");
2792        unsigned int utf = xs_utf8_dec((const char **)&sna);
2793
2794        int isEmoji = 0;
2795        if (xs_is_emoji(utf) || (tag && xs_list_len(tag) > 0))
2796            isEmoji = 1;
2797
2798        if (xs_type(object) != XSTYPE_DICT) {
2799            snac_debug(snac, 1, xs_fmt("undo: overriding utype %s | %s | %s",
2800                        utype, id, actor));
2801            utype = "Follow";
2802        }
2803
2804        if (strcmp(utype, "Follow") == 0) { /** **/
2805            if (!id) {
2806                snac_log(snac, xs_fmt("no id (msg.object.object) when "
2807                      "handling follow: %s", actor));
2808                return 1;
2809            }
2810            if (strcmp(id, snac->actor) != 0 && strcmp(id, snac->actor_alt) != 0)
2811                snac_debug(snac, 1, xs_fmt("Undo + Follow from %s not for us (%s)", actor, id));
2812            else
2813            if (valid_status(follower_del(snac, actor))) {
2814                snac_log(snac, xs_fmt("no longer following us %s", actor));
2815                do_notify = 1;
2816            }
2817            else
2818            if (pending_check(snac, actor)) {
2819                pending_del(snac, actor);
2820                snac_log(snac, xs_fmt("cancelled pending follow from %s", actor));
2821            }
2822            else
2823                snac_log(snac, xs_fmt("error deleting follower %s", actor));
2824        }
2825        /* *key emojis are like w/ Emoji tag */
2826        else
2827        if ((isEmoji || strcmp(utype, "EmojiReact") == 0) &&
2828                (content && strcmp(content, "♥") != 0)) {
2829            const xs_val *mid = xs_dict_get(object, "id");
2830            int status = object_rm_emoji_react((char *)id, mid);
2831            /* ensure *key notifications type */
2832            utype = "EmojiReact";
2833
2834            snac_log(snac, xs_fmt("Undo 'EmojiReact' for %s %d", id, status));
2835        }
2836        else
2837        if (strcmp(utype, "Like") == 0) { /** **/
2838            int status = object_unadmire(id, actor, 1);
2839
2840            snac_log(snac, xs_fmt("Undo '%s' for %s %d", utype, id, status));
2841        }
2842        else
2843        if (strcmp(utype, "Announce") == 0) { /** **/
2844            int status = HTTP_STATUS_OK;
2845
2846            /* commented out: if a followed user boosts something that
2847               is requested and then unboosts, the post remains here,
2848               but with no apparent reason, and that is confusing */
2849            //status = object_unadmire(id, actor, 0);
2850
2851            snac_log(snac, xs_fmt("Unboost for %s %d", id, status));
2852        }
2853        else
2854            snac_debug(snac, 1, xs_fmt("ignored 'Undo' for object type '%s'", utype));
2855    }
2856    else
2857    if (strcmp(type, "Create") == 0) { /** **/
2858        if (is_muted(snac, actor)) {
2859            snac_log(snac, xs_fmt("ignored 'Create' + '%s' from muted actor %s", utype, actor));
2860            return 1;
2861        }
2862
2863        if (xs_match(utype, "Note|Article")) { /** **/
2864            const char *id          = xs_dict_get(object, "id");
2865            const char *in_reply_to = get_in_reply_to(object);
2866            const char *atto        = get_atto(object);
2867            xs *wrk           = NULL;
2868
2869            if (xs_is_null(id))
2870                snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2871            else
2872            if (xs_is_null(atto))
2873                snac_log(snac, xs_fmt("malformed message: no 'attributedTo' field"));
2874            else
2875            if (!xs_is_null(in_reply_to) && is_hidden(snac, in_reply_to)) {
2876                snac_debug(snac, 0, xs_fmt("dropped reply %s to hidden post %s", id, in_reply_to));
2877            }
2878            else {
2879                if (content_match("filter_reject.txt", object)) {
2880                    snac_log(snac, xs_fmt("rejected by content %s", id));
2881                    return 1;
2882                }
2883
2884                if (strcmp(actor, atto) != 0)
2885                    snac_log(snac, xs_fmt("SUSPICIOUS: actor != atto (%s != %s)", actor, atto));
2886
2887                timeline_request(snac, &in_reply_to, &wrk, 0);
2888
2889                const char *quoted_id = xs_or(xs_dict_get(object, "quoteUri"), xs_dict_get(object, "quoteUrl"));
2890
2891                if (xs_is_string(quoted_id) && xs_match(quoted_id, "https://*|http://*")) { /** **/
2892                    xs *quoted_post = NULL;
2893                    int status;
2894
2895                    if (valid_status(status = activitypub_request(snac, quoted_id, &quoted_post))) {
2896                        /* got quoted post */
2897                        object_add(quoted_id, quoted_post);
2898                    }
2899
2900                    snac_debug(snac, 1, xs_fmt("retrieving quoted post %s %d", quoted_id, status));
2901                }
2902
2903                if (timeline_add(snac, id, object)) {
2904                    snac_log(snac, xs_fmt("new '%s' %s %s", utype, actor, id));
2905                    do_notify = 1;
2906                }
2907
2908                /* if it has a "name" field, it may be a vote for a question */
2909                const char *name = xs_dict_get(object, "name");
2910
2911                if (!xs_is_null(name) && *name && !xs_is_null(in_reply_to) && *in_reply_to)
2912                    update_question(snac, in_reply_to);
2913            }
2914        }
2915        else
2916        if (strcmp(utype, "Question") == 0) { /**  **/
2917            const char *id = xs_dict_get(object, "id");
2918
2919            if (xs_is_null(id))
2920                snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2921            else
2922            if (timeline_add(snac, id, object))
2923                snac_log(snac, xs_fmt("new 'Question' %s %s", actor, id));
2924        }
2925        else
2926        if (xs_match(utype, "Audio|Video|Event")) { /** **/
2927            const char *id = xs_dict_get(object, "id");
2928
2929            if (xs_is_null(id))
2930                snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2931            else
2932            if (timeline_add(snac, id, object))
2933                snac_log(snac, xs_fmt("new '%s' %s %s", utype, actor, id));
2934        }
2935        else
2936            snac_debug(snac, 1, xs_fmt("ignored 'Create' for object type '%s'", utype));
2937    }
2938    else
2939    if (strcmp(type, "Accept") == 0) { /** **/
2940        if (strcmp(utype, "(null)") == 0) {
2941            const char *obj_id = xs_dict_get(msg, "object");
2942
2943            /* if the accepted object id is a string that may
2944               be created by us, it's a follow */
2945            if (xs_type(obj_id) == XSTYPE_STRING &&
2946                xs_startswith(obj_id, srv_baseurl) &&
2947                xs_endswith(obj_id, "/Follow"))
2948                utype = "Follow";
2949        }
2950
2951        if (strcmp(utype, "Follow") == 0) { /** **/
2952            if (following_check(snac, actor)) {
2953                following_add(snac, actor, msg);
2954                snac_log(snac, xs_fmt("confirmed follow from %s", actor));
2955
2956                /* request a bit of this fellow's outbox */
2957                enqueue_collect_outbox(snac, actor);
2958            }
2959            else
2960                snac_log(snac, xs_fmt("spurious follow accept from %s", actor));
2961        }
2962        else
2963        if (strcmp(utype, "Create") == 0) {
2964            /* some implementations send Create confirmations, go figure */
2965            snac_debug(snac, 1, xs_dup("ignored 'Accept' + 'Create'"));
2966        }
2967        else {
2968            srv_archive_error("accept", "ignored Accept", req, msg);
2969            snac_debug(snac, 1, xs_fmt("ignored 'Accept' for object type '%s'", utype));
2970        }
2971    }
2972    else
2973    if (strcmp(type, "Like") == 0 || strcmp(type, "EmojiReact") == 0) { /** **/
2974        /* misskey sends emojis as Like + tag.
2975         * It is easier to handle them both at the same time. */
2976        const char *sna = xs_dict_get(msg, "content");
2977        const xs_dict *tag = xs_dict_get(msg, "tag");
2978        unsigned int utf = xs_utf8_dec((const char **)&sna);
2979
2980        if (xs_is_emoji(utf) || (tag && xs_list_len(tag) > 0))
2981            type = "EmojiReact";
2982
2983        if (xs_type(object) == XSTYPE_DICT)
2984            object = xs_dict_get(object, "id");
2985
2986        if (xs_is_null(object))
2987            snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2988        else
2989        if (timeline_admire(snac, object, actor, 1, msg) == HTTP_STATUS_CREATED)
2990            snac_log(snac, xs_fmt("new '%s' %s %s", type, actor, object));
2991        else
2992            snac_log(snac, xs_fmt("repeated '%s' from %s to %s", type, actor, object));
2993
2994        do_notify = 1;
2995    }
2996    else
2997    if (strcmp(type, "Announce") == 0) { /** **/
2998        if (xs_type(object) == XSTYPE_DICT)
2999            object = xs_dict_get(object, "id");
3000
3001        if (xs_is_null(object))
3002            snac_log(snac, xs_fmt("malformed message: no 'id' field"));
3003        else
3004        if (is_muted(snac, actor) && !is_msg_mine(snac, object))
3005            snac_log(snac, xs_fmt("dropped 'Announce' from muted actor %s", actor));
3006        else
3007        if (is_limited(snac, actor) && !is_msg_mine(snac, object))
3008            snac_log(snac, xs_fmt("dropped 'Announce' from limited actor %s", actor));
3009        else {
3010            xs *a_msg = NULL;
3011            xs *wrk   = NULL;
3012
3013            timeline_request(snac, &object, &wrk, 0);
3014
3015            if (valid_status(object_get(object, &a_msg))) {
3016                const char *who = get_atto(a_msg);
3017
3018                /* got the admired object: instance is [back] online */
3019                instance_failure(object, 2);
3020
3021                if (who && !is_muted(snac, who)) {
3022                    /* bring the actor */
3023                    xs *who_o = NULL;
3024
3025                    if (valid_status(actor_request(snac, who, &who_o))) {
3026                        /* don't account as such announces by our own relay */
3027                        xs *this_relay = xs_fmt("%s/relay", srv_baseurl);
3028
3029                        if (strcmp(actor, this_relay) != 0) {
3030                            if (valid_status(timeline_admire(snac, object, actor, 0, a_msg)))
3031                                snac_log(snac, xs_fmt("new 'Announce' %s %s", actor, object));
3032                            else
3033                                snac_log(snac, xs_fmt("repeated 'Announce' from %s to %s",
3034                                    actor, object));
3035                        }
3036
3037                        /* distribute the post with the actor as 'proxy' */
3038                        list_distribute(snac, actor, a_msg);
3039
3040                        /* distribute the post to users following these hashtags */
3041                        followed_hashtag_distribute(a_msg);
3042
3043                        do_notify = 1;
3044                    }
3045                    else
3046                        snac_debug(snac, 1, xs_fmt("dropped 'Announce' on actor request error %s", who));
3047                }
3048                else
3049                    snac_log(snac, xs_fmt("ignored 'Announce' about muted actor %s", who));
3050            }
3051            else
3052                snac_debug(snac, 2, xs_fmt("error requesting 'Announce' object %s", object));
3053        }
3054    }
3055    else
3056    if (strcmp(type, "Update") == 0) { /** **/
3057        if (xs_match(utype, "Person|Service|Application")) { /** **/
3058            actor_add(actor, xs_dict_get(msg, "object"));
3059            timeline_touch(snac);
3060
3061            snac_log(snac, xs_fmt("updated actor %s", actor));
3062        }
3063        else
3064        if (xs_match(utype, "Note|Page|Article|Video|Audio|Event")) { /** **/
3065            const char *id = xs_dict_get(object, "id");
3066
3067            if (xs_is_null(id))
3068                snac_log(snac, xs_fmt("malformed message: no 'id' field"));
3069            else
3070            if (object_here(id)) {
3071                if (xs_startswith(id, srv_baseurl) && !xs_startswith(id, actor))
3072                    snac_log(snac, xs_fmt("ignored incorrect 'Update' %s %s", actor, id));
3073                else {
3074                    object_add_ow(id, object);
3075                    timeline_touch(snac);
3076
3077                    snac_log(snac, xs_fmt("updated '%s' %s", utype, id));
3078                }
3079            }
3080            else
3081                snac_log(snac, xs_fmt("dropped update for unknown '%s' %s", utype, id));
3082        }
3083        else
3084        if (strcmp(utype, "Question") == 0) { /** **/
3085            const char *id     = xs_dict_get(object, "id");
3086            const char *closed = xs_dict_get(object, "closed");
3087
3088            if (xs_is_null(id))
3089                snac_log(snac, xs_fmt("malformed message: no 'id' field"));
3090            else {
3091                object_add_ow(id, object);
3092                timeline_touch(snac);
3093
3094                snac_log(snac, xs_fmt("%s poll %s", closed == NULL ? "updated" : "closed", id));
3095
3096                if (closed != NULL)
3097                    do_notify = 1;
3098            }
3099        }
3100        else {
3101            srv_archive_error("unsupported_update", "unsupported_update", req, msg);
3102
3103            snac_log(snac, xs_fmt("ignored 'Update' for object type '%s'", utype));
3104        }
3105    }
3106    else
3107    if (strcmp(type, "Delete") == 0) { /** **/
3108        if (xs_type(object) == XSTYPE_DICT)
3109            object = xs_dict_get(object, "id");
3110
3111        if (xs_is_null(object))
3112            snac_log(snac, xs_fmt("malformed message: no 'id' field"));
3113        else
3114        if (object_here(object)) {
3115            if (xs_startswith(object, srv_baseurl) && !is_msg_mine(snac, object))
3116                snac_log(snac, xs_fmt("ignored incorrect 'Delete' %s %s", actor, object));
3117            else {
3118                timeline_del(snac, object);
3119                snac_debug(snac, 1, xs_fmt("new 'Delete' %s %s", actor, object));
3120            }
3121        }
3122        else
3123            snac_debug(snac, 1, xs_fmt("ignored 'Delete' for unknown object %s", object));
3124    }
3125    else
3126    if (strcmp(type, "Pong") == 0) { /** **/
3127        snac_log(snac, xs_fmt("'Pong' received from %s", actor));
3128    }
3129    else
3130    if (strcmp(type, "Ping") == 0) { /** **/
3131        const char *id = xs_dict_get(msg, "id");
3132
3133        snac_log(snac, xs_fmt("'Ping' requested from %s", actor));
3134
3135        if (!xs_is_null(id)) {
3136            xs *rsp = msg_pong(snac, actor, id);
3137
3138            enqueue_output_by_actor(snac, rsp, actor, 0);
3139        }
3140    }
3141    else
3142    if (strcmp(type, "Block") == 0) { /** **/
3143        snac_debug(snac, 1, xs_fmt("'Block' received from %s", actor));
3144
3145        /* should we MUTE the actor back? */
3146        /* mute(snac, actor); */
3147
3148        if (!xs_is_true(xs_dict_get(srv_config, "disable_block_notifications")))
3149            do_notify = 1;
3150    }
3151    else
3152    if (strcmp(type, "Move") == 0) { /** **/
3153        do_notify = 1;
3154
3155        const char *old_account = xs_dict_get(msg, "object");
3156        const char *new_account = xs_dict_get(msg, "target");
3157
3158        if (!xs_is_null(old_account) && !xs_is_null(new_account)) {
3159            if (following_check(snac, old_account)) {
3160                xs *n_actor = NULL;
3161
3162                if (valid_status(object_get(new_account, &n_actor))) {
3163                    const xs_list *aka = xs_dict_get(n_actor, "alsoKnownAs");
3164
3165                    if (xs_type(aka) == XSTYPE_LIST) {
3166                        if (xs_list_in(aka, old_account) != -1) {
3167                            /* all conditions met! */
3168
3169                            /* follow new account */
3170                            xs *f_msg = msg_follow(snac, new_account);
3171
3172                            if (f_msg != NULL) {
3173                                const char *new_actor = xs_dict_get(f_msg, "object");
3174                                following_add(snac, new_actor, f_msg);
3175                                enqueue_output_by_actor(snac, f_msg, new_actor, 0);
3176
3177                                snac_log(snac, xs_fmt("'Move': following %s", new_account));
3178                            }
3179
3180                            /* unfollow old account */
3181                            xs *of_msg = NULL;
3182
3183                            if (valid_status(following_get(snac, old_account, &of_msg))) {
3184                                xs *uf_msg = msg_undo(snac, xs_dict_get(of_msg, "object"));
3185                                following_del(snac, old_account);
3186                                enqueue_output_by_actor(snac, uf_msg, old_account, 0);
3187
3188                                snac_log(snac, xs_fmt("'Move': unfollowing %s", old_account));
3189                            }
3190                        }
3191                        else
3192                            snac_log(snac, xs_fmt("'Move' error: old actor %s not found in %s 'alsoKnownAs'",
3193                                old_account, new_account));
3194                    }
3195                    else
3196                        snac_log(snac, xs_fmt("'Move' error: cannot get %s 'alsoKnownAs'", new_account));
3197                }
3198                else {
3199                    snac_log(snac, xs_fmt("'Move' error: cannot get new actor %s", new_account));
3200
3201                    /* may be a server hiccup, retry later */
3202                    return 0;
3203                }
3204            }
3205            else
3206                snac_log(snac, xs_fmt("'Move' error: actor %s is not being followed", old_account));
3207        }
3208        else {
3209            snac_log(snac, xs_fmt("'Move' error: malformed message from %s", actor));
3210            srv_archive_error("move", "move", req, msg);
3211        }
3212    }
3213    else {
3214        srv_archive_error("unsupported_type", "unsupported_type", req, msg);
3215
3216        snac_debug(snac, 1, xs_fmt("process_input_message type '%s' ignored", type));
3217    }
3218
3219    if (do_notify) {
3220        notify(snac, type, utype, actor, msg);
3221
3222        timeline_touch(snac);
3223    }
3224
3225    return 1;
3226}
3227
3228
3229int send_email(const xs_dict *mailinfo)
3230/* invoke curl */
3231{
3232    const char *url = xs_dict_get(srv_config, "smtp_url");
3233
3234    if (!xs_is_string(url) || *url == '\0') {
3235        /* revert back to old sendmail pipe behaviour */
3236        const char *msg = xs_dict_get(mailinfo, "body");
3237        FILE *f;
3238        int status;
3239        int fds[2];
3240        pid_t pid;
3241
3242        if (pipe(fds) == -1) return -1;
3243        pid = vfork();
3244        if (pid == -1) return -1;
3245        else if (pid == 0) {
3246            dup2(fds[0], 0);
3247            close(fds[0]);
3248            close(fds[1]);
3249            execl("/usr/sbin/sendmail", "sendmail", "-t", (char *) NULL);
3250            _exit(1);
3251        }
3252        close(fds[0]);
3253        if ((f = fdopen(fds[1], "w")) == NULL) {
3254            close(fds[1]);
3255            return -1;
3256        }
3257        fprintf(f, "%s\n", msg);
3258        fclose(f);
3259        if (waitpid(pid, &status, 0) == -1) return -1;
3260        return status;
3261    }
3262
3263    const char
3264        *user = xs_dict_get(srv_config, "smtp_username"),
3265        *pass = xs_dict_get(srv_config, "smtp_password"),
3266        *from = xs_dict_get(mailinfo, "from"),
3267        *to   = xs_dict_get(mailinfo, "to"),
3268        *body = xs_dict_get(mailinfo, "body");
3269
3270    if (url == NULL || *url == '\0')
3271        url = "smtp://localhost";
3272
3273    int smtp_port = parse_port(url, NULL);
3274
3275    return xs_smtp_request(url, user, pass, from, to, body, smtp_port == 465 || smtp_port == 587);
3276}
3277
3278
3279void process_user_queue_item(snac *user, xs_dict *q_item)
3280/* processes an item from the user queue */
3281{
3282    const char *type;
3283    int queue_retry_max = xs_number_get(xs_dict_get(srv_config, "queue_retry_max"));
3284
3285    if ((type = xs_dict_get(q_item, "type")) == NULL)
3286        type = "output";
3287
3288    if (strcmp(type, "message") == 0) {
3289        const xs_dict *msg = xs_dict_get(q_item, "message");
3290        xs *rcpts = recipient_list(user, msg, 1);
3291        xs_set inboxes;
3292        const xs_str *actor;
3293
3294        xs_set_init(&inboxes);
3295
3296        /* add this shared inbox first */
3297        xs *this_shared_inbox = xs_fmt("%s/shared-inbox", srv_baseurl);
3298        xs_set_add(&inboxes, this_shared_inbox);
3299        enqueue_output(user, msg, this_shared_inbox, 0, 0);
3300
3301        /* iterate the recipients */
3302        xs_list_foreach(rcpts, actor) {
3303            /* local users were served by this_shared_inbox */
3304            if (!xs_startswith(actor, srv_baseurl)) {
3305                xs *inbox = get_actor_inbox(actor, 1);
3306
3307                if (inbox != NULL) {
3308                    /* add to the set and, if it's not there, send message */
3309                    if (xs_set_add(&inboxes, inbox) == 1)
3310                        enqueue_output(user, msg, inbox, 0, 0);
3311                }
3312                else
3313                    snac_log(user, xs_fmt("cannot find inbox for %s", actor));
3314            }
3315        }
3316
3317        /* if it's a public note or question, send to the collected inboxes */
3318        if (xs_match(xs_dict_get_def(msg, "type", ""), "Create|Update") && is_msg_public(msg)) {
3319            if (xs_type(xs_dict_get(srv_config, "disable_inbox_collection")) != XSTYPE_TRUE) {
3320                xs *shibx = inbox_list();
3321                const xs_str *inbox;
3322
3323                xs_list_foreach(shibx, inbox) {
3324                    if (xs_set_add(&inboxes, inbox) == 1)
3325                        enqueue_output(user, msg, inbox, 0, 0);
3326                }
3327            }
3328        }
3329
3330        xs_set_free(&inboxes);
3331
3332        /* relay this note */
3333        if (is_msg_public(msg) && strcmp(user->uid, "relay") != 0) { /* avoid loops */
3334            snac relay;
3335            if (user_open(&relay, "relay")) {
3336                /* a 'relay' user exists */
3337                const char *type = xs_dict_get(msg, "type");
3338
3339                if (xs_is_string(type) && strcmp(type, "Create") == 0) {
3340                    const xs_val *object = xs_dict_get(msg, "object");
3341
3342                    if (xs_is_dict(object)) {
3343                        object = xs_dict_get(object, "id");
3344
3345                        snac_debug(&relay, 1, xs_fmt("relaying message %s", object));
3346
3347                        xs *boost = msg_admiration(&relay, object, "Announce");
3348                        enqueue_message(&relay, boost);
3349                    }
3350                }
3351
3352                user_free(&relay);
3353            }
3354        }
3355    }
3356    else
3357    if (strcmp(type, "input") == 0) {
3358        /* process the message */
3359        const xs_dict *msg = xs_dict_get(q_item, "message");
3360        const xs_dict *req = xs_dict_get(q_item, "req");
3361        int retries  = xs_number_get(xs_dict_get(q_item, "retries"));
3362
3363        if (xs_is_null(msg))
3364            return;
3365
3366        if (!process_input_message(user, msg, req)) {
3367            if (retries > queue_retry_max)
3368                snac_log(user, xs_fmt("input giving up"));
3369            else {
3370                /* reenqueue */
3371                enqueue_input(user, msg, req, retries + 1);
3372                snac_log(user, xs_fmt("input requeue #%d", retries + 1));
3373            }
3374        }
3375    }
3376    else
3377    if (strcmp(type, "close_question") == 0) {
3378        /* the time for this question has ended */
3379        const char *id = xs_dict_get(q_item, "message");
3380
3381        if (!xs_is_null(id))
3382            update_question(user, id);
3383    }
3384    else
3385    if (strcmp(type, "object_request") == 0) {
3386        const char *id = xs_dict_get(q_item, "message");
3387
3388        if (!xs_is_null(id)) {
3389            int status;
3390            xs *data = NULL;
3391
3392            status = activitypub_request(user, id, &data);
3393
3394            if (valid_status(status))
3395                object_add_ow(id, data);
3396
3397            snac_debug(user, 1, xs_fmt("object_request %s %d", id, status));
3398        }
3399    }
3400    else
3401    if (strcmp(type, "verify_links") == 0) {
3402        verify_links(user);
3403    }
3404    else
3405    if (strcmp(type, "actor_refresh") == 0) {
3406        const char *actor = xs_dict_get(q_item, "actor");
3407        double mtime = object_mtime(actor);
3408
3409        if (actor_failure(actor, 0) == -1) {
3410            /* actor is broken beyond repair */
3411            snac_debug(user, 1, xs_fmt("actor_refresh skipped broken actor %s", actor));
3412        }
3413        else
3414        /* only refresh if it was refreshed more than an hour ago */
3415        if (mtime + 3600.0 < (double) time(NULL)) {
3416            xs *actor_o = NULL;
3417            int status;
3418
3419            if (valid_status((status = activitypub_request(user, actor, &actor_o)))) {
3420                /* refresh collection counts with throttling to prevent resource exhaustion */
3421                actor_o = actor_get_collections(user, actor_o, 1);
3422
3423                actor_add(actor, actor_o);
3424
3425                /* mark actor and instance as working */
3426                actor_failure(actor, 2);
3427                instance_failure(actor, 2);
3428            }
3429            else {
3430                if (status == HTTP_STATUS_GONE || status == HTTP_STATUS_NOT_FOUND) {
3431                    actor_failure(actor, 1);
3432                    snac_log(user, xs_fmt("actor_refresh marking actor %s as broken %d", actor, status));
3433                }
3434                else {
3435                    actor_failure(actor, 2);
3436                    object_touch(actor);
3437                }
3438            }
3439
3440            snac_log(user, xs_fmt("actor_refresh %s %d", actor, status));
3441        }
3442    }
3443    else
3444    if (strcmp(type, "notify_webhook") == 0) {
3445        const char *webhook = xs_dict_get(user->config, "notify_webhook");
3446
3447        if (xs_is_string(webhook) && xs_match(webhook, "https://*|http://*")) { /** **/
3448            const xs_dict *msg = xs_dict_get(q_item, "message");
3449            int retries = xs_number_get(xs_dict_get(q_item, "retries"));
3450
3451            xs *hdrs = xs_dict_new();
3452
3453            hdrs = xs_dict_set(hdrs, "content-type", "application/json");
3454            hdrs = xs_dict_set(hdrs, "user-agent",   USER_AGENT);
3455
3456            xs *body = xs_json_dumps(msg, 4);
3457
3458            int status;
3459            xs *rsp = xs_http_request("POST", webhook, hdrs, body, strlen(body), &status, NULL, NULL, 0);
3460
3461            snac_debug(user, 0, xs_fmt("webhook post %s %d", webhook, status));
3462
3463            if (!valid_status(status)) {
3464                retries++;
3465
3466                if (retries > queue_retry_max)
3467                    snac_debug(user, 0, xs_fmt("webhook post giving up %s", webhook));
3468                else {
3469                    snac_debug(user, 0, xs_fmt("webhook post requeue %s %d", webhook, retries));
3470
3471                    enqueue_notify_webhook(user, msg, retries);
3472                }
3473            }
3474        }
3475    }
3476    else
3477    if (strcmp(type, "collect_replies") == 0) {
3478        const char *post = xs_dict_get(q_item, "message");
3479
3480        collect_replies(user, post);
3481    }
3482    else
3483    if (strcmp(type, "collect_outbox") == 0) {
3484        const char *actor_id = xs_dict_get(q_item, "message");
3485
3486        collect_outbox(user, actor_id);
3487    }
3488    else
3489        snac_log(user, xs_fmt("unexpected user q_item type '%s'", type));
3490}
3491
3492
3493int process_user_queue(snac *snac)
3494/* processes a user's queue */
3495{
3496    int cnt = 0;
3497    xs *list = user_queue(snac);
3498
3499    xs_list *p = list;
3500    const xs_str *fn;
3501
3502    while (xs_list_iter(&p, &fn)) {
3503        xs *q_item = dequeue(fn);
3504
3505        if (q_item == NULL)
3506            continue;
3507
3508        process_user_queue_item(snac, q_item);
3509        cnt++;
3510    }
3511
3512    scheduled_process(snac);
3513
3514    return cnt;
3515}
3516
3517
3518xs_str *str_status(int status)
3519{
3520    return xs_fmt("%d %s", status, status < 0 ? xs_curl_strerr(status) : xs_http_status_text(status));
3521}
3522
3523
3524void process_queue_item(xs_dict *q_item)
3525/* processes an item from the global queue */
3526{
3527    const char *type = xs_dict_get(q_item, "type");
3528    int queue_retry_max = xs_number_get(xs_dict_get(srv_config, "queue_retry_max"));
3529
3530    if (strcmp(type, "output") == 0) {
3531        int status;
3532        const xs_str *inbox  = xs_dict_get(q_item, "inbox");
3533        const xs_str *keyid  = xs_dict_get(q_item, "keyid");
3534        const xs_str *seckey = xs_dict_get(q_item, "seckey");
3535        const xs_dict *msg   = xs_dict_get(q_item, "message");
3536        int retries    = xs_number_get(xs_dict_get(q_item, "retries"));
3537        int p_status   = xs_number_get(xs_dict_get(q_item, "p_status"));
3538        xs *payload    = NULL;
3539        int p_size     = 0;
3540        int timeout    = 0;
3541
3542        if (xs_is_null(inbox) || xs_is_null(msg) || xs_is_null(keyid) || xs_is_null(seckey)) {
3543            srv_log(xs_fmt("output message error: missing fields"));
3544            return;
3545        }
3546
3547        if (is_instance_blocked(inbox)) {
3548            srv_debug(0, xs_fmt("discarded output message to blocked instance %s", inbox));
3549            return;
3550        }
3551
3552        if (instance_failure(inbox, 0)) {
3553            srv_debug(1, xs_fmt("output message error: too many failures for instance %s", inbox));
3554            return;
3555        }
3556
3557        /* deliver (if previous error status was a timeout, try now longer) */
3558        if (p_status == 599)
3559            timeout = xs_number_get(xs_dict_get_def(srv_config, "queue_timeout_2", "8"));
3560        else
3561            timeout = xs_number_get(xs_dict_get_def(srv_config, "queue_timeout", "6"));
3562
3563        if (timeout == 0)
3564            timeout = 6;
3565
3566        status = send_to_inbox_raw(keyid, seckey, inbox, msg, &payload, &p_size, timeout);
3567
3568        /* register or clear a value for this instance */
3569        instance_failure(inbox, valid_status(status) ? 2 : 1);
3570
3571        if (payload) {
3572            if (p_size > 1024) {
3573                /* trim the message */
3574                payload = xs_utf8_crop_i(payload, 0, 1024);
3575                payload = xs_str_cat(payload, "...");
3576            }
3577
3578            /* strip ugly control characters */
3579            payload = xs_replace_i(payload, "\n", "");
3580            payload = xs_replace_i(payload, "\r", "");
3581
3582            if (*payload)
3583                payload = xs_str_wrap_i(" [", payload, "]");
3584        }
3585        else
3586            payload = xs_str_new(NULL);
3587
3588        xs *s_status = str_status(status);
3589
3590        srv_log(xs_fmt("output message: sent to inbox %s (%s)%s", inbox, s_status, payload));
3591
3592        if (!valid_status(status)) {
3593            retries++;
3594
3595            /* if it's not the first time it fails with a timeout,
3596               penalize the server by skipping one retry */
3597            if (p_status == status && status == HTTP_STATUS_CLIENT_CLOSED_REQUEST)
3598                retries++;
3599
3600            /* error sending; requeue? */
3601            if (status == HTTP_STATUS_BAD_REQUEST
3602                || status == HTTP_STATUS_NOT_FOUND
3603                || status == HTTP_STATUS_METHOD_NOT_ALLOWED
3604                || status == HTTP_STATUS_GONE
3605                || status == HTTP_STATUS_UNPROCESSABLE_CONTENT
3606                || status < 0)
3607                /* explicit error: discard */
3608                srv_log(xs_fmt("output message: error %s (%s)", inbox, s_status));
3609            else
3610            if (retries > queue_retry_max)
3611                srv_log(xs_fmt("output message: giving up %s (%s)", inbox, s_status));
3612            else {
3613                /* requeue */
3614                enqueue_output_raw(keyid, seckey, msg, inbox, retries, status);
3615                srv_log(xs_fmt("output message: requeue %s #%d", inbox, retries));
3616            }
3617        }
3618    }
3619    else
3620    if (strcmp(type, "email") == 0) {
3621        /* send this email */
3622        const xs_dict *msg = xs_dict_get(q_item, "message");
3623        int retries = xs_number_get(xs_dict_get(q_item, "retries"));
3624
3625        if (!send_email(msg))
3626            srv_debug(1, xs_fmt("email message sent"));
3627        else {
3628            retries++;
3629
3630            if (retries > queue_retry_max)
3631                srv_log(xs_fmt("email giving up (errno: %d)", errno));
3632            else {
3633                /* requeue */
3634                srv_log(xs_fmt(
3635                    "email requeue #%d (errno: %d)", retries, errno));
3636
3637                enqueue_email(msg, retries);
3638            }
3639        }
3640    }
3641    else
3642    if (strcmp(type, "telegram") == 0) {
3643        /* send this via telegram */
3644        const char *bot   = xs_dict_get(q_item, "bot");
3645        const char *msg   = xs_dict_get(q_item, "message");
3646        xs *chat_id = xs_dup(xs_dict_get(q_item, "chat_id"));
3647        int status  = 0;
3648
3649        /* chat_id must start with a - */
3650        if (!xs_startswith(chat_id, "-"))
3651            chat_id = xs_str_wrap_i("-", chat_id, NULL);
3652
3653        xs *url  = xs_fmt("https:/" "/api.telegram.org/bot%s/sendMessage", bot);
3654        xs *body = xs_fmt("{\"chat_id\":%s,\"text\":\"%s\"}", chat_id, msg);
3655
3656        xs *headers = xs_dict_new();
3657        headers = xs_dict_append(headers, "content-type", "application/json");
3658
3659        xs *rsp = xs_http_request("POST", url, headers,
3660                                   body, strlen(body), &status, NULL, NULL, 0);
3661        rsp = xs_free(rsp);
3662
3663        srv_debug(0, xs_fmt("telegram post %d", status));
3664    }
3665    else
3666    if (strcmp(type, "ntfy") == 0) {
3667        /* send this via ntfy */
3668        const char *ntfy_server   = xs_dict_get(q_item, "ntfy_server");
3669        const char *msg   = xs_dict_get(q_item, "message");
3670        const char *ntfy_token   = xs_dict_get(q_item, "ntfy_token");
3671        int status  = 0;
3672
3673        xs *url  = xs_fmt("%s", ntfy_server);
3674        xs *body = xs_fmt("%s", msg);
3675
3676        xs *headers = xs_dict_new();
3677        headers = xs_dict_append(headers, "content-type", "text/plain");
3678        // Append the Authorization header only if ntfy_token is not NULL
3679         if (ntfy_token != NULL) {
3680             headers = xs_dict_append(headers, "Authorization", xs_fmt("Bearer %s", ntfy_token));
3681             }
3682
3683        xs *rsp = xs_http_request("POST", url, headers,
3684                                   body, strlen(body), &status, NULL, NULL, 0);
3685        rsp = xs_free(rsp);
3686
3687        srv_debug(0, xs_fmt("ntfy post %d", status));
3688    }
3689    else
3690    if (strcmp(type, "purge") == 0) {
3691        srv_log(xs_dup("purge start"));
3692
3693        purge_all();
3694
3695        srv_log(xs_dup("purge end"));
3696    }
3697    else
3698    if (strcmp(type, "input") == 0) {
3699        const xs_dict *msg = xs_dict_get(q_item, "message");
3700        const xs_dict *req = xs_dict_get(q_item, "req");
3701        int retries  = xs_number_get(xs_dict_get(q_item, "retries"));
3702
3703        /* do some instance-level checks */
3704        int r = process_input_message(NULL, msg, req);
3705
3706        if (r == 0) {
3707            /* transient error? retry */
3708            if (retries > queue_retry_max)
3709                srv_log(xs_fmt("shared input giving up"));
3710            else {
3711                /* reenqueue */
3712                enqueue_shared_input(msg, req, retries + 1);
3713                srv_log(xs_fmt("shared input requeue #%d", retries + 1));
3714            }
3715        }
3716        else
3717        if (r == 2) {
3718            /* redistribute the input message to all users */
3719            const char *ntid = xs_dict_get(q_item, "ntid");
3720            xs *tmpfn  = xs_fmt("%s/tmp/%s.json", srv_basedir, ntid);
3721            FILE *f;
3722
3723            if ((f = fopen(tmpfn, "w")) != NULL) {
3724                xs_json_dump(q_item, 4, f);
3725                fclose(f);
3726            }
3727
3728            xs *users = user_list();
3729            xs_list *p = users;
3730            const char *v;
3731            int cnt = 0;
3732
3733            while (xs_list_iter(&p, &v)) {
3734                snac user;
3735
3736                if (user_open(&user, v)) {
3737                    int rsn = is_msg_for_me(&user, msg);
3738                    if (rsn) {
3739                        xs *fn = xs_fmt("%s/queue/%s.json", user.basedir, ntid);
3740
3741                        snac_debug(&user, 1,
3742                            xs_fmt("enqueue_input (from shared inbox) %s [%d]", xs_dict_get(msg, "id"), rsn));
3743
3744                        if (link(tmpfn, fn) < 0)
3745                            srv_log(xs_fmt("link(%s, %s) error", tmpfn, fn));
3746
3747                        cnt++;
3748                    }
3749
3750                    user_free(&user);
3751                }
3752            }
3753
3754            unlink(tmpfn);
3755
3756            if (cnt == 0) {
3757                srv_debug(1, xs_fmt("no valid recipients for %s", xs_dict_get(msg, "id")));
3758            }
3759        }
3760    }
3761    else
3762    if (strcmp(type, "webmention") == 0) {
3763        const xs_dict *msg = xs_dict_get(q_item, "message");
3764        const char *source = xs_dict_get(msg, "id");
3765        const char *content = xs_dict_get(msg, "content");
3766
3767        if (xs_is_string(source) && xs_is_string(content)) {
3768            xs *links = xs_regex_select(content, "\"https?:/" "/[^\"]+");
3769            const char *link;
3770
3771            xs_list_foreach(links, link) {
3772                xs *target = xs_strip_chars_i(xs_dup(link), "\"");
3773
3774                int r = xs_webmention_send(source, target, USER_AGENT);
3775
3776                srv_debug(1, xs_fmt("webmention source=%s target=%s %d", source, target, r));
3777            }
3778        }
3779    }
3780    else
3781    if (strcmp(type, "rss_hashtag_poll") == 0) {
3782        rss_poll_hashtags();
3783    }
3784    else
3785    if (strcmp(type, "fsck") == 0) {
3786        srv_log(xs_fmt("started deferred data integrity check"));
3787        data_fsck();
3788        srv_log(xs_fmt("finished deferred data integrity check"));
3789    }
3790    else
3791        srv_log(xs_fmt("unexpected q_item type '%s'", type));
3792}
3793
3794
3795int process_queue(void)
3796/* processes the global queue */
3797{
3798    int cnt = 0;
3799    xs *list = queue();
3800
3801    xs_list *p = list;
3802    const xs_str *fn;
3803
3804    while (xs_list_iter(&p, &fn)) {
3805        xs *q_item = dequeue(fn);
3806
3807        if (q_item != NULL) {
3808            job_post(q_item, 0);
3809            cnt++;
3810        }
3811    }
3812
3813    return cnt;
3814}
3815
3816
3817/** account migration **/
3818
3819int migrate_account(snac *user)
3820/* migrates this account to a new one (stored in the 'alias' user field) */
3821{
3822    const char *new_account = xs_dict_get(user->config, "alias");
3823
3824    if (xs_type(new_account) != XSTYPE_STRING) {
3825        snac_log(user, xs_fmt("Cannot migrate: alias (destination account) not set"));
3826        return 1;
3827    }
3828
3829    xs *new_actor = NULL;
3830    int status;
3831
3832    if (!valid_status(status = activitypub_request(user, new_account, &new_actor))) {
3833        snac_log(user, xs_fmt("Cannot migrate: error requesting actor %s %d", new_account, status));
3834        return 1;
3835    }
3836
3837    actor_add(new_account, new_actor);
3838
3839    const char *loaka = xs_dict_get(new_actor, "alsoKnownAs");
3840
3841    if (xs_type(loaka) != XSTYPE_LIST) {
3842        snac_log(user, xs_fmt("Cannot migrate: destination account doesn't have any aliases"));
3843        return 1;
3844    }
3845
3846    if (xs_list_in(loaka, user->actor) == -1) {
3847        snac_log(user, xs_fmt("Cannot migrate: destination account doesn't have this one as an alias"));
3848        return 1;
3849    }
3850
3851    xs *move = msg_move(user, new_account);
3852    xs *fwers = follower_list(user);
3853
3854    const char *actor;
3855    xs_list_foreach(fwers, actor) {
3856        /* get the actor inbox, excluding the shared one */
3857        xs *inbox = get_actor_inbox(actor, 0);
3858
3859        if (xs_is_null(inbox))
3860            snac_log(user, xs_fmt("migrate_account: cannot get inbox for actor %s", actor));
3861        else
3862            enqueue_output(user, move, inbox, 0, 0);
3863    }
3864
3865    return 0;
3866}
3867
3868
3869/** HTTP handlers */
3870
3871int activitypub_get_handler(const xs_dict *req, const char *q_path,
3872                            char **body, int *b_size, char **ctype)
3873{
3874    int status = HTTP_STATUS_OK;
3875    const char *accept = xs_dict_get(req, "accept");
3876    snac snac;
3877    xs *msg = NULL;
3878
3879    if (accept == NULL)
3880        return 0;
3881
3882    if (xs_str_in(accept, "application/activity+json") == -1 &&
3883        xs_str_in(accept, "application/ld+json") == -1)
3884        return 0;
3885
3886    xs *l = xs_split_n(q_path, "/", 2);
3887    const char *uid;
3888    const char *p_path;
3889
3890    uid = xs_list_get(l, 1);
3891    if (!user_open(&snac, uid)) {
3892        /* invalid user */
3893        status = grave(uid, 0) ? HTTP_STATUS_GONE : HTTP_STATUS_NOT_FOUND;
3894        srv_debug(1, xs_fmt("activitypub_get_handler bad user %s %d", uid, status));
3895        return status;
3896    }
3897
3898    p_path = xs_list_get(l, 2);
3899
3900    const xs_dict *q_vars = xs_dict_get(req, "q_vars");
3901
3902    *ctype  = "application/activity+json";
3903
3904    int show_contact_metrics = xs_is_true(xs_dict_get(snac.config, "show_contact_metrics"));
3905
3906    if (p_path == NULL) {
3907        /* if there was no component after the user, it's an actor request */
3908        msg = msg_actor(&snac);
3909        *ctype = "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"";
3910
3911        const char *ua = xs_dict_get(req, "user-agent");
3912
3913        snac_debug(&snac, 0, xs_fmt("serving actor [%s]", ua ? ua : "No UA"));
3914    }
3915    else
3916    if (strcmp(p_path, "outbox") == 0 || strcmp(p_path, "featured") == 0) {
3917        xs *id = xs_fmt("%s/%s", snac.actor, p_path);
3918        xs *list = xs_list_new();
3919        const char *v;
3920        int cnt = xs_number_get(xs_dict_get_def(srv_config, "max_public_entries", "20"));
3921
3922        /* get the public outbox or the pinned list */
3923        xs *elems = *p_path == 'o' ? timeline_simple_list(&snac, "public", 0, cnt, NULL) : pinned_list(&snac);
3924
3925        xs_list_foreach(elems, v) {
3926            xs *i = NULL;
3927
3928            if (valid_status(object_get_by_md5(v, &i))) {
3929                const char *type = xs_dict_get(i, "type");
3930                const char *id   = xs_dict_get(i, "id");
3931
3932                if (type && id && strcmp(type, "Note") == 0 && is_msg_mine(&snac, id)) {
3933                    if (is_msg_public(i)) {
3934                        xs *c_msg = msg_create(&snac, i);
3935                        list = xs_list_append(list, c_msg);
3936                    }
3937                }
3938            }
3939        }
3940
3941        /* replace the 'orderedItems' with the latest posts */
3942        msg = msg_collection(&snac, id, xs_list_len(list));
3943        msg = xs_dict_set(msg, "orderedItems", list);
3944    }
3945    else
3946    if (strcmp(p_path, "followers") == 0) {
3947        int total = 0;
3948
3949        if (show_contact_metrics) {
3950            total = follower_list_len(&snac);
3951        }
3952
3953        xs *id = xs_fmt("%s/%s", snac.actor, p_path);
3954        msg = msg_collection(&snac, id, total);
3955    }
3956    else
3957    if (strcmp(p_path, "following") == 0) {
3958        int total = 0;
3959
3960        if (show_contact_metrics) {
3961            total = following_list_len(&snac);
3962        }
3963
3964        xs *id = xs_fmt("%s/%s", snac.actor, p_path);
3965        msg = msg_collection(&snac, id, total);
3966    }
3967    else
3968    if (xs_startswith(p_path, "p/")) {
3969        xs *id = xs_fmt("%s/%s", snac.actor, p_path);
3970
3971        status = object_get(id, &msg);
3972
3973        /* don't return non-public objects */
3974        if (valid_status(status) && !is_msg_public(msg))
3975            status = HTTP_STATUS_NOT_FOUND;
3976    }
3977    else
3978    if (xs_startswith(p_path, "r/")) {
3979        /* replies to a post */
3980        xs *s = xs_dup(p_path);
3981        s[0] = 'p';
3982
3983        xs *id = xs_fmt("%s/%s", snac.actor, s);
3984
3985        xs *obj = NULL;
3986        status = object_get(id, &obj);
3987
3988        /* don't return non-public objects */
3989        if (!valid_status(status))
3990            status = HTTP_STATUS_NOT_FOUND;
3991        else
3992        if (!is_msg_public(obj))
3993            status = HTTP_STATUS_NOT_FOUND;
3994        else
3995        if (xs_dict_get(q_vars, "page"))
3996            msg = msg_replies(&snac, id, 1);
3997        else {
3998            const xs_dict *replies = xs_dict_get(obj, "replies");
3999            if (xs_is_dict(replies)) {
4000                msg = xs_dup(replies);
4001                msg = xs_dict_set(msg, "@context", "https:/""/www.w3.org/ns/activitystreams");
4002            }
4003        }
4004    }
4005    else
4006        status = HTTP_STATUS_NOT_FOUND;
4007
4008    if (status == HTTP_STATUS_OK && msg != NULL) {
4009        *body   = xs_json_dumps(msg, 4);
4010        *b_size = strlen(*body);
4011    }
4012
4013    snac_debug(&snac, 1, xs_fmt("activitypub_get_handler serving %s %d", q_path, status));
4014
4015    user_free(&snac);
4016
4017    return status;
4018}
4019
4020
4021int activitypub_post_handler(const xs_dict *req, const char *q_path,
4022                             char *payload, int p_size,
4023                             char **body, int *b_size, char **ctype)
4024/* processes an input message */
4025{
4026    (void)b_size;
4027
4028    int status = HTTP_STATUS_ACCEPTED;
4029    const char *i_ctype = xs_dict_get(req, "content-type");
4030    snac snac;
4031    const char *v;
4032
4033    if (i_ctype == NULL) {
4034        *body  = xs_str_new("no content-type");
4035        *ctype = "text/plain";
4036        return HTTP_STATUS_BAD_REQUEST;
4037    }
4038
4039    if (xs_is_null(payload)) {
4040        *body  = xs_str_new("no payload");
4041        *ctype = "text/plain";
4042        return HTTP_STATUS_BAD_REQUEST;
4043    }
4044
4045    if (xs_str_in(i_ctype, "application/activity+json") == -1 &&
4046        xs_str_in(i_ctype, "application/ld+json") == -1)
4047        return 0;
4048
4049    /* decode the message */
4050    xs *msg = xs_json_loads(payload);
4051    const char *id = xs_dict_get(msg, "id");
4052
4053    if (msg == NULL) {
4054        srv_log(xs_fmt("activitypub_post_handler JSON error %s", q_path));
4055
4056        srv_archive_error("activitypub_post_handler", "JSON error", req, payload);
4057
4058        *body  = xs_str_new("JSON error");
4059        *ctype = "text/plain";
4060        return HTTP_STATUS_BAD_REQUEST;
4061    }
4062
4063    if (id && is_instance_blocked(id)) {
4064        srv_debug(1, xs_fmt("full instance block for %s", id));
4065
4066        *body  = xs_str_new("blocked");
4067        *ctype = "text/plain";
4068        return HTTP_STATUS_FORBIDDEN;
4069    }
4070
4071    /* get the user and path */
4072    xs *l = xs_split_n(q_path, "/", 2);
4073
4074    if (xs_list_len(l) == 2 && strcmp(xs_list_get(l, 1), "shared-inbox") == 0) {
4075        enqueue_shared_input(msg, req, 0);
4076        return HTTP_STATUS_ACCEPTED;
4077    }
4078
4079    if (xs_list_len(l) != 3 || strcmp(xs_list_get(l, 2), "inbox") != 0) {
4080        /* strange q_path */
4081        srv_debug(1, xs_fmt("activitypub_post_handler unsupported path %s", q_path));
4082        return HTTP_STATUS_NOT_FOUND;
4083    }
4084
4085    const char *uid = xs_list_get(l, 1);
4086    if (!user_open(&snac, uid)) {
4087        /* invalid user */
4088        status = grave(uid, 0) ? HTTP_STATUS_GONE : HTTP_STATUS_NOT_FOUND;
4089        srv_debug(1, xs_fmt("activitypub_post_handler bad user %s %d", uid, status));
4090        return status;
4091    }
4092
4093    /* if it has a digest, check it now, because
4094       later the payload won't be exactly the same */
4095    if ((v = xs_dict_get(req, "digest")) != NULL) {
4096        xs *s1 = xs_sha256_base64(payload, p_size);
4097        xs *s2 = xs_fmt("SHA-256=%s", s1);
4098
4099        if (strcmp(s2, v) != 0) {
4100            srv_log(xs_fmt("digest check FAILED"));
4101
4102            *body  = xs_str_new("bad digest");
4103            *ctype = "text/plain";
4104            status = HTTP_STATUS_BAD_REQUEST;
4105        }
4106    }
4107
4108    /* if the message is from a muted actor, reject it right now */
4109    if (!xs_is_null(v = xs_dict_get(msg, "actor")) && *v) {
4110        if (is_muted(&snac, v)) {
4111            snac_log(&snac, xs_fmt("rejected message from MUTEd actor %s", v));
4112
4113            *body  = xs_str_new("rejected");
4114            *ctype = "text/plain";
4115            status = HTTP_STATUS_FORBIDDEN;
4116        }
4117    }
4118
4119    if (valid_status(status)) {
4120        enqueue_input(&snac, msg, req, 0);
4121        *ctype = "application/activity+json";
4122    }
4123
4124    user_free(&snac);
4125
4126    return status;
4127}