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