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