2.82
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 collect_replies(snac *user, const char *id)
940/* collects all replies for a post */
941{
942 xs *obj = NULL;
943
944 if (!valid_status(object_get(id, &obj))) {
945 snac_debug(user, 1, xs_fmt("collect_replies: object '%s' is not here", id));
946 return;
947 }
948
949 const xs_dict *replies_first = xs_dict_get_path(obj, "replies.first");
950 if (!xs_is_dict(replies_first)) {
951 snac_debug(user, 1, xs_fmt("collect_replies: object '%s' does not have replies.first", id));
952 return;
953 }
954
955 const xs_list *level0_replies = xs_dict_get(replies_first, "items");
956 const xs_list *level1_replies = NULL;
957
958 const char *next = xs_dict_get(replies_first, "next");
959 xs *reply_obj = NULL;
960
961 if (xs_is_string(next) && !valid_status(activitypub_request(user, next, &reply_obj))) {
962 snac_debug(user, 1, xs_fmt("collect_replies: error getting next replies object '%s'", next));
963 return;
964 }
965
966 if (xs_is_dict(reply_obj))
967 level1_replies = xs_dict_get(reply_obj, "items");
968
969 xs *items = xs_list_new();
970
971 if (xs_is_list(level0_replies))
972 items = xs_list_cat(items, level0_replies);
973
974 if (xs_is_list(level1_replies))
975 items = xs_list_cat(items, level1_replies);
976
977 const xs_val *v;
978
979 xs_list_foreach(items, v) {
980 xs *reply = NULL;
981
982 if (xs_is_string(v)) {
983 /* request the object */
984 if (!valid_status(object_get(v, &reply))) {
985 if (!valid_status(activitypub_request(user, v, &reply))) {
986 snac_debug(user, 1, xs_fmt("collect_replies: error requesting object '%s'", v));
987 continue;
988 }
989 }
990 }
991 else
992 if (xs_is_dict(v)) {
993 /* actually the post object */
994 reply = xs_dup(v);
995 }
996
997 if (!xs_is_dict(reply))
998 continue;
999
1000 const char *id = xs_dict_get(reply, "id");
1001 const char *type = xs_dict_get(reply, "type");
1002 const char *attr_to = get_atto(reply);
1003
1004 if (!xs_is_string(id) || !xs_is_string(type) || !xs_is_string(attr_to))
1005 continue;
1006
1007 if (!xs_match(type, POSTLIKE_OBJECT_TYPE))
1008 continue;
1009
1010 if (timeline_here(user, id)) {
1011 snac_debug(user, 1, xs_fmt("collect_replies: item already in timeline %s", id));
1012 continue;
1013 }
1014
1015 enqueue_actor_refresh(user, attr_to, 0);
1016
1017 timeline_add(user, id, reply);
1018
1019 snac_log(user, xs_fmt("new '%s' (collect_replies) %s %s", type, attr_to, id));
1020 }
1021}
1022
1023
1024void notify(snac *snac, const char *type, const char *utype, const char *actor, const xs_dict *msg)
1025/* notifies the user of relevant events */
1026{
1027 /* skip our own notifications */
1028 if (strcmp(snac->actor, actor) == 0)
1029 return;
1030
1031 const char *id = xs_dict_get(msg, "id");
1032
1033 if (strcmp(type, "Create") == 0) {
1034 /* only notify of notes specifically for us */
1035 xs *rcpts = recipient_list(snac, msg, 0);
1036
1037 if (xs_list_in(rcpts, snac->actor) == -1)
1038 return;
1039
1040 /* discard votes */
1041 const xs_dict *note = xs_dict_get(msg, "object");
1042
1043 if (note && !xs_is_null(xs_dict_get(note, "name")))
1044 return;
1045 }
1046
1047 if (strcmp(type, "Undo") == 0 && strcmp(utype, "Follow") != 0)
1048 return;
1049
1050 /* get the object id */
1051 const char *objid = xs_dict_get(msg, "object");
1052
1053 if (xs_type(objid) == XSTYPE_DICT)
1054 objid = xs_dict_get(objid, "id");
1055
1056 if (xs_match(type, "Like|Announce|EmojiReact")) {
1057 /* if it's not an admiration about something by us, done */
1058 if (xs_is_null(objid) || !xs_startswith(objid, snac->actor))
1059 return;
1060
1061 /* if it's an announce by our own relay, done */
1062 xs *relay_id = xs_fmt("%s/relay", srv_baseurl);
1063 if (xs_startswith(id, relay_id))
1064 return;
1065 }
1066
1067 /* updated poll? */
1068 if (strcmp(type, "Update") == 0 && strcmp(utype, "Question") == 0) {
1069 const xs_dict *poll;
1070 const char *poll_id;
1071
1072 if ((poll = xs_dict_get(msg, "object")) == NULL)
1073 return;
1074
1075 /* if it's not closed, discard */
1076 if (xs_is_null(xs_dict_get(poll, "closed")))
1077 return;
1078
1079 if ((poll_id = xs_dict_get(poll, "id")) == NULL)
1080 return;
1081
1082 /* if it's not ours and we didn't vote, discard */
1083 if (!xs_startswith(poll_id, snac->actor) && !was_question_voted(snac, poll_id))
1084 return;
1085 }
1086
1087 /* user will love to know about this! */
1088
1089 /* prepare message body */
1090 xs *body = xs_fmt("User : @%s@%s\n",
1091 xs_dict_get(snac->config, "uid"),
1092 xs_dict_get(srv_config, "host")
1093 );
1094
1095 if (strcmp(utype, "(null)") != 0) {
1096 xs *s1 = xs_fmt("Type : %s + %s\n", type, utype);
1097 body = xs_str_cat(body, s1);
1098 }
1099 else {
1100 xs *s1 = xs_fmt("Type : %s\n", type);
1101 body = xs_str_cat(body, s1);
1102 }
1103
1104 {
1105 xs *s1 = xs_fmt("Actor : %s\n", actor);
1106 body = xs_str_cat(body, s1);
1107 }
1108
1109 if (objid != NULL) {
1110 xs *s1 = xs_fmt("Object: %s\n", objid);
1111 body = xs_str_cat(body, s1);
1112 }
1113
1114 /* email */
1115
1116 const char *email = "[disabled by admin]";
1117
1118 if (xs_type(xs_dict_get(srv_config, "disable_email_notifications")) != XSTYPE_TRUE) {
1119 email = xs_dict_get(snac->config_o, "email");
1120 if (xs_is_null(email)) {
1121 email = xs_dict_get(snac->config, "email");
1122
1123 if (xs_is_null(email))
1124 email = "[empty]";
1125 }
1126 }
1127
1128 if (*email != '\0' && *email != '[') {
1129 snac_debug(snac, 1, xs_fmt("email notify %s %s %s", type, utype, actor));
1130
1131 xs *subject = xs_fmt("snac notify for @%s@%s",
1132 xs_dict_get(snac->config, "uid"), xs_dict_get(srv_config, "host"));
1133 xs *from = xs_fmt("<snac-daemon@%s>", xs_dict_get(srv_config, "host"));
1134 xs *header = xs_fmt(
1135 "From: snac-daemon %s\n"
1136 "To: %s\n"
1137 "Subject: %s\n"
1138 "\n",
1139 from, email, subject);
1140
1141 xs *mailinfo = xs_dict_new();
1142 xs *bd = xs_fmt("%s%s", header, body);
1143 mailinfo = xs_dict_append(mailinfo, "from", from);
1144 mailinfo = xs_dict_append(mailinfo, "to", email);
1145 mailinfo = xs_dict_append(mailinfo, "body", bd);
1146
1147 enqueue_email(mailinfo, 0);
1148 }
1149
1150 /* telegram */
1151
1152 const char *bot = xs_dict_get(snac->config, "telegram_bot");
1153 const char *chat_id = xs_dict_get(snac->config, "telegram_chat_id");
1154
1155 if (!xs_is_null(bot) && !xs_is_null(chat_id) && *bot && *chat_id)
1156 enqueue_telegram(body, bot, chat_id);
1157
1158 /* ntfy */
1159 const char *ntfy_server = xs_dict_get(snac->config, "ntfy_server");
1160 const char *ntfy_token = xs_dict_get(snac->config, "ntfy_token");
1161
1162 if (!xs_is_null(ntfy_server) && *ntfy_server)
1163 enqueue_ntfy(body, ntfy_server, ntfy_token);
1164
1165 /* auto boost */
1166 if (xs_match(type, "Create") && xs_is_true(xs_dict_get(snac->config, "auto_boost"))) {
1167 xs *msg = msg_admiration(snac, objid, "Announce");
1168 enqueue_message(snac, msg);
1169
1170 snac_debug(snac, 1, xs_fmt("auto boosted %s", objid));
1171 }
1172
1173 /* finally, store it in the notification folder */
1174 if (strcmp(type, "Follow") == 0)
1175 objid = id;
1176 else
1177 if (strcmp(utype, "Follow") == 0)
1178 objid = actor;
1179
1180 notify_add(snac, type, utype, actor, objid != NULL ? objid : id, msg);
1181}
1182
1183/** messages **/
1184
1185xs_dict *msg_base(snac *snac, const char *type, const char *id,
1186 const char *actor, const char *date, const char *object)
1187/* creates a base ActivityPub message */
1188{
1189 xs *did = NULL;
1190 xs *published = NULL;
1191 xs *ntid = tid(0);
1192 const char *obj_id;
1193
1194 if (xs_type(object) == XSTYPE_DICT)
1195 obj_id = xs_dict_get(object, "id");
1196 else
1197 obj_id = object;
1198
1199 /* generated values */
1200 if (date && strcmp(date, "@now") == 0) {
1201 published = xs_str_utctime(0, ISO_DATE_SPEC);
1202 date = published;
1203 }
1204
1205 if (id != NULL) {
1206 if (strcmp(id, "@dummy") == 0) {
1207 did = xs_fmt("%s/d/%s/%s", snac->actor, ntid, type);
1208
1209 id = did;
1210 }
1211 else
1212 if (strcmp(id, "@object") == 0) {
1213 if (obj_id != NULL) {
1214 did = xs_fmt("%s/%s_%s", obj_id, type, ntid);
1215 id = did;
1216 }
1217 else
1218 id = NULL;
1219 }
1220 else
1221 if (strcmp(id, "@wrapper") == 0) {
1222 /* like @object, but always generate the same id */
1223 if (object != NULL) {
1224 date = xs_dict_get(object, "published");
1225 did = xs_fmt("%s/%s", obj_id, type);
1226 id = did;
1227 }
1228 else
1229 id = NULL;
1230 }
1231 }
1232
1233 xs_dict *msg = xs_dict_new();
1234
1235 msg = xs_dict_append(msg, "@context", "https:/" "/www.w3.org/ns/activitystreams");
1236 msg = xs_dict_append(msg, "type", type);
1237
1238 if (id != NULL)
1239 msg = xs_dict_append(msg, "id", id);
1240
1241 if (actor != NULL)
1242 msg = xs_dict_append(msg, "actor", actor);
1243
1244 if (date != NULL)
1245 msg = xs_dict_append(msg, "published", date);
1246
1247 if (object != NULL)
1248 msg = xs_dict_append(msg, "object", object);
1249
1250 return msg;
1251}
1252
1253
1254xs_dict *msg_collection(snac *snac, const char *id, int items)
1255/* creates an empty OrderedCollection message */
1256{
1257 xs_dict *msg = msg_base(snac, "OrderedCollection", id, NULL, NULL, NULL);
1258 xs *n = xs_number_new(items);
1259
1260 msg = xs_dict_append(msg, "attributedTo", snac->actor);
1261 msg = xs_dict_append(msg, "totalItems", n);
1262
1263 return msg;
1264}
1265
1266
1267xs_dict *msg_replies(snac *user, const char *id, int fill)
1268/* creates a CollectionPage with replies of id */
1269{
1270 xs *r_id = xs_replace(id, "/p/", "/r/");
1271 xs *r_idp = xs_fmt("%s#page", r_id);
1272 xs *r_idh = xs_fmt("%s#hdr", r_id);
1273
1274 xs_dict *msg = msg_base(user, "CollectionPage", r_idp, NULL, NULL, NULL);
1275
1276 msg = xs_dict_set(msg, "partOf", r_idh);
1277
1278 xs *items = xs_list_new();
1279 if (fill) {
1280 xs *children = object_children(id);
1281 const char *md5;
1282
1283 xs_list_foreach(children, md5) {
1284 xs *obj = NULL;
1285
1286 if (valid_status(object_get_by_md5(md5, &obj)) && is_msg_public(obj)) {
1287 const char *c_id = xs_dict_get(obj, "id");
1288
1289 if (xs_is_string(c_id))
1290 items = xs_list_append(items, c_id);
1291 }
1292 }
1293 }
1294 else {
1295 msg = xs_dict_del(msg, "@context");
1296 msg = xs_dict_del(msg, "id");
1297 msg = xs_dict_set(msg, "next", r_idp);
1298 }
1299
1300 msg = xs_dict_set(msg, "items", items);
1301
1302 return msg;
1303}
1304
1305
1306xs_dict *msg_accept(snac *snac, const xs_val *object, const char *to)
1307/* creates an Accept message (as a response to a Follow) */
1308{
1309 xs_dict *msg = msg_base(snac, "Accept", "@dummy", snac->actor, NULL, object);
1310
1311 msg = xs_dict_append(msg, "to", to);
1312
1313 return msg;
1314}
1315
1316
1317xs_dict *msg_update(snac *snac, const xs_dict *object)
1318/* creates an Update message */
1319{
1320 xs_dict *msg = msg_base(snac, "Update", "@object", snac->actor, "@now", object);
1321
1322 const char *type = xs_dict_get(object, "type");
1323
1324 if (strcmp(type, "Note") == 0) {
1325 msg = xs_dict_append(msg, "to", xs_dict_get(object, "to"));
1326 msg = xs_dict_append(msg, "cc", xs_dict_get(object, "cc"));
1327 }
1328 else
1329 if (strcmp(type, "Person") == 0) {
1330 msg = xs_dict_append(msg, "to", public_address);
1331
1332 /* also spam the people being followed, so that
1333 they have the newest information about who we are */
1334 xs *cc = following_list(snac);
1335
1336 msg = xs_dict_append(msg, "cc", cc);
1337 }
1338 else
1339 msg = xs_dict_append(msg, "to", public_address);
1340
1341 return msg;
1342}
1343
1344
1345xs_dict *msg_admiration(snac *snac, const char *object, const char *type)
1346/* creates a Like or Announce message */
1347{
1348 xs *a_msg = NULL;
1349 xs_dict *msg = NULL;
1350 xs *wrk = NULL;
1351
1352 /* call the object */
1353 timeline_request(snac, &object, &wrk, 0);
1354
1355 if (valid_status(object_get(object, &a_msg))) {
1356 xs *rcpts = xs_list_new();
1357 xs *o_md5 = xs_md5_hex(object, strlen(object));
1358 xs *id = xs_fmt("%s/%s/%s", snac->actor, *type == 'L' ? "l" : "a", o_md5);
1359
1360 msg = msg_base(snac, type, id, snac->actor, "@now", object);
1361
1362 if (is_msg_public(a_msg))
1363 rcpts = xs_list_append(rcpts, public_address);
1364
1365 rcpts = xs_list_append(rcpts, get_atto(a_msg));
1366
1367 msg = xs_dict_append(msg, "to", rcpts);
1368 }
1369 else
1370 snac_log(snac, xs_fmt("msg_admiration cannot retrieve object %s", object));
1371
1372 return msg;
1373}
1374
1375
1376xs_dict *msg_repulsion(snac *user, const char *id, const char *type)
1377/* creates an Undo + admiration message */
1378{
1379 xs *a_msg = NULL;
1380 xs_dict *msg = NULL;
1381
1382 if (valid_status(object_get(id, &a_msg))) {
1383 /* create a clone of the original admiration message */
1384 xs *object = msg_admiration(user, id, type);
1385
1386 /* delete the published date */
1387 object = xs_dict_del(object, "published");
1388
1389 /* create an undo message for this object */
1390 msg = msg_undo(user, object);
1391
1392 /* copy the 'to' field */
1393 msg = xs_dict_set(msg, "to", xs_dict_get(object, "to"));
1394 }
1395
1396 /* now we despise this */
1397 object_unadmire(id, user->actor, *type == 'L' ? 1 : 0);
1398
1399 return msg;
1400}
1401
1402
1403xs_dict *msg_actor_place(snac *user, const char *label)
1404/* creates a Place object, if the user has a location defined */
1405{
1406 xs_dict *place = NULL;
1407 const char *latitude = xs_dict_get_def(user->config, "latitude", "");
1408 const char *longitude = xs_dict_get_def(user->config, "longitude", "");
1409
1410 if (*latitude && *longitude) {
1411 xs *d_la = xs_number_new(atof(latitude));
1412 xs *d_lo = xs_number_new(atof(longitude));
1413
1414 place = msg_base(user, "Place", NULL, user->actor, NULL, NULL);
1415
1416 place = xs_dict_set(place, "name", label);
1417 place = xs_dict_set(place, "latitude", d_la);
1418 place = xs_dict_set(place, "longitude", d_lo);
1419 }
1420
1421 return place;
1422}
1423
1424
1425xs_dict *msg_actor(snac *snac)
1426/* create a Person message for this actor */
1427{
1428 xs *ctxt = xs_list_new();
1429 xs *icon = xs_dict_new();
1430 xs *keys = xs_dict_new();
1431 xs *tags = xs_list_new();
1432 xs *avtr = NULL;
1433 xs *kid = NULL;
1434 xs *f_bio = NULL;
1435 xs_dict *msg = NULL;
1436 const char *p;
1437 int n;
1438
1439 /* everybody loves some caching */
1440 if (time(NULL) - object_mtime(snac->actor) < 3 * 3600 &&
1441 valid_status(object_get(snac->actor, &msg))) {
1442 snac_debug(snac, 2, xs_fmt("Returning cached actor %s", snac->actor));
1443
1444 return msg;
1445 }
1446
1447 msg = msg_base(snac, "Person", snac->actor, NULL, NULL, NULL);
1448
1449 /* change the @context (is this really necessary?) */
1450 ctxt = xs_list_append(ctxt, "https:/" "/www.w3.org/ns/activitystreams");
1451 ctxt = xs_list_append(ctxt, "https:/" "/w3id.org/security/v1");
1452 msg = xs_dict_set(msg, "@context", ctxt);
1453
1454 msg = xs_dict_set(msg, "url", snac->actor);
1455 msg = xs_dict_set(msg, "name", xs_dict_get(snac->config, "name"));
1456 msg = xs_dict_set(msg, "preferredUsername", snac->uid);
1457 msg = xs_dict_set(msg, "published", xs_dict_get(snac->config, "published"));
1458
1459 // this exists so we get the emoji tags from our name too.
1460 // and then we just throw away the result, because it's kinda useless to have markdown in the display name.
1461 xs *name_dummy = not_really_markdown(xs_dict_get(snac->config, "name"), NULL, &tags);
1462
1463 xs *f_bio_2 = not_really_markdown(xs_dict_get(snac->config, "bio"), NULL, &tags);
1464 f_bio = process_tags(snac, f_bio_2, &tags);
1465 msg = xs_dict_set(msg, "summary", f_bio);
1466 msg = xs_dict_set(msg, "tag", tags);
1467
1468 char *folders[] = { "inbox", "outbox", "followers", "following", "featured", NULL };
1469 for (n = 0; folders[n]; n++) {
1470 xs *f = xs_fmt("%s/%s", snac->actor, folders[n]);
1471 msg = xs_dict_set(msg, folders[n], f);
1472 }
1473
1474 p = xs_dict_get(snac->config, "avatar");
1475
1476 if (*p == '\0')
1477 avtr = xs_fmt("%s/susie.png", srv_baseurl);
1478 else
1479 avtr = xs_dup(p);
1480
1481 icon = xs_dict_append(icon, "type", "Image");
1482 icon = xs_dict_append(icon, "mediaType", xs_mime_by_ext(avtr));
1483 icon = xs_dict_append(icon, "url", avtr);
1484 msg = xs_dict_set(msg, "icon", icon);
1485
1486 kid = xs_fmt("%s#main-key", snac->actor);
1487
1488 keys = xs_dict_append(keys, "id", kid);
1489 keys = xs_dict_append(keys, "owner", snac->actor);
1490 keys = xs_dict_append(keys, "publicKeyPem", xs_dict_get(snac->key, "public"));
1491 msg = xs_dict_set(msg, "publicKey", keys);
1492
1493 /* if the "bot" config field is set to true, change type to "Service" */
1494 if (xs_type(xs_dict_get(snac->config, "bot")) == XSTYPE_TRUE)
1495 msg = xs_dict_set(msg, "type", "Service");
1496
1497 /* if it's named "relay", then identify as an "Application" */
1498 if (strcmp(snac->uid, "relay") == 0)
1499 msg = xs_dict_set(msg, "type", "Application");
1500
1501 /* add the header image, if there is one defined */
1502 const char *header = xs_dict_get(snac->config, "header");
1503 if (!xs_is_null(header)) {
1504 xs *d = xs_dict_new();
1505 d = xs_dict_append(d, "type", "Image");
1506 d = xs_dict_append(d, "mediaType", xs_mime_by_ext(header));
1507 d = xs_dict_append(d, "url", header);
1508 msg = xs_dict_set(msg, "image", d);
1509 }
1510
1511 /* add the metadata as attachments of PropertyValue */
1512 xs *metadata = NULL;
1513 const xs_dict *md = xs_dict_get(snac->config, "metadata");
1514
1515 if (xs_type(md) == XSTYPE_DICT)
1516 metadata = xs_dup(md);
1517 else
1518 if (xs_type(md) == XSTYPE_STRING) {
1519 metadata = xs_dict_new();
1520 xs *l = xs_split(md, "\n");
1521 const char *ll;
1522
1523 xs_list_foreach(l, ll) {
1524 xs *kv = xs_split_n(ll, "=", 1);
1525 const char *k = xs_list_get(kv, 0);
1526 const char *v = xs_list_get(kv, 1);
1527
1528 if (k && v) {
1529 xs *kk = xs_strip_i(xs_dup(k));
1530 xs *vv = xs_strip_i(xs_dup(v));
1531 metadata = xs_dict_set(metadata, kk, vv);
1532 }
1533 }
1534 }
1535
1536 if (xs_type(metadata) == XSTYPE_DICT) {
1537 xs *attach = xs_list_new();
1538 const xs_str *k;
1539 const xs_str *v;
1540
1541 int c = 0;
1542 while (xs_dict_next(metadata, &k, &v, &c)) {
1543 xs *d = xs_dict_new();
1544
1545 xs *k2 = encode_html(k);
1546 xs *v2 = NULL;
1547
1548 if (xs_startswith(v, "https:/") || xs_startswith(v, "http:/")) {
1549 xs *t = encode_html(v);
1550 v2 = xs_fmt("<a href=\"%s\" rel=\"me\">%s</a>", t, t);
1551 }
1552 else
1553 v2 = encode_html(v);
1554
1555 d = xs_dict_append(d, "type", "PropertyValue");
1556 d = xs_dict_append(d, "name", k2);
1557 d = xs_dict_append(d, "value", v2);
1558
1559 attach = xs_list_append(attach, d);
1560 }
1561
1562 msg = xs_dict_set(msg, "attachment", attach);
1563 }
1564
1565 /* use shared inboxes? */
1566 if (xs_is_true(xs_dict_get(srv_config, "shared_inboxes")) || strcmp(snac->uid, "relay") == 0) {
1567 xs *d = xs_dict_new();
1568 xs *si = xs_fmt("%s/shared-inbox", srv_baseurl);
1569 d = xs_dict_append(d, "sharedInbox", si);
1570 msg = xs_dict_set(msg, "endpoints", d);
1571 }
1572
1573 /* does this user have an aka? */
1574 const char *aka = xs_dict_get(snac->config, "alias");
1575 if (xs_type(aka) == XSTYPE_STRING && *aka) {
1576 xs *loaka = xs_list_append(xs_list_new(), aka);
1577
1578 msg = xs_dict_set(msg, "alsoKnownAs", loaka);
1579 }
1580
1581 const xs_val *manually = xs_dict_get(snac->config, "approve_followers");
1582 msg = xs_dict_set(msg, "manuallyApprovesFollowers",
1583 xs_stock(xs_is_true(manually) ? XSTYPE_TRUE : XSTYPE_FALSE));
1584
1585 /* if there are location coords, create a Place object */
1586 xs *location = msg_actor_place(snac, "Home");
1587 if (xs_type(location) == XSTYPE_DICT)
1588 msg = xs_dict_set(msg, "location", location);
1589
1590 /* cache it */
1591 snac_debug(snac, 1, xs_fmt("Caching actor %s", snac->actor));
1592 object_add_ow(snac->actor, msg);
1593
1594 return msg;
1595}
1596
1597
1598xs_dict *msg_create(snac *snac, const xs_dict *object)
1599/* creates a 'Create' message */
1600{
1601 xs_dict *msg = msg_base(snac, "Create", "@wrapper", snac->actor, NULL, object);
1602 const xs_val *v;
1603
1604 if ((v = get_atto(object)))
1605 msg = xs_dict_append(msg, "attributedTo", v);
1606
1607 if ((v = xs_dict_get(object, "cc")))
1608 msg = xs_dict_append(msg, "cc", v);
1609
1610 if ((v = xs_dict_get(object, "to")))
1611 msg = xs_dict_append(msg, "to", v);
1612 else
1613 msg = xs_dict_append(msg, "to", public_address);
1614
1615 return msg;
1616}
1617
1618
1619xs_dict *msg_undo(snac *snac, const xs_val *object)
1620/* creates an 'Undo' message */
1621{
1622 xs_dict *msg = msg_base(snac, "Undo", "@object", snac->actor, "@now", object);
1623 const char *to;
1624
1625 if (xs_type(object) == XSTYPE_DICT && (to = xs_dict_get(object, "object")))
1626 msg = xs_dict_append(msg, "to", to);
1627
1628 return msg;
1629}
1630
1631
1632xs_dict *msg_delete(snac *snac, const char *id)
1633/* creates a 'Delete' + 'Tombstone' for a local entry */
1634{
1635 xs *tomb = xs_dict_new();
1636 xs_dict *msg = NULL;
1637
1638 /* sculpt the tombstone */
1639 tomb = xs_dict_append(tomb, "type", "Tombstone");
1640 tomb = xs_dict_append(tomb, "id", id);
1641
1642 /* now create the Delete */
1643 msg = msg_base(snac, "Delete", "@object", snac->actor, "@now", tomb);
1644
1645 xs *to = xs_list_new();
1646 xs *involved = object_likes(id);
1647 xs *boosts = object_announces(id);
1648 xs *children = object_children(id);
1649 const char *md5;
1650
1651 involved = xs_list_cat(involved, boosts);
1652 involved = xs_list_cat(involved, children);
1653
1654 /* add everybody */
1655 to = xs_list_append(to, public_address);
1656
1657 /* add actors that liked, boosted or replied to this */
1658 xs_list_foreach(involved, md5) {
1659 xs *actor = NULL;
1660
1661 if (valid_status(object_get_by_md5(md5, &actor))) {
1662 const char *id = xs_dict_get(actor, "id");
1663 const char *atto = get_atto(actor);
1664
1665 if (xs_is_string(atto))
1666 to = xs_list_append(to, atto);
1667 else
1668 if (xs_is_string(id))
1669 to = xs_list_append(to, id);
1670 }
1671 }
1672
1673 msg = xs_dict_append(msg, "to", to);
1674
1675 return msg;
1676}
1677
1678
1679xs_dict *msg_follow(snac *snac, const char *q)
1680/* creates a 'Follow' message */
1681{
1682 xs *actor_o = NULL;
1683 xs *actor = NULL;
1684 xs_dict *msg = NULL;
1685 int status;
1686
1687 xs *url_or_uid = xs_strip_i(xs_str_new(q));
1688
1689 if (xs_startswith(url_or_uid, "https:/") || xs_startswith(url_or_uid, "http:/"))
1690 actor = xs_dup(url_or_uid);
1691 else
1692 if (!valid_status(webfinger_request(url_or_uid, &actor, NULL)) || actor == NULL) {
1693 snac_log(snac, xs_fmt("cannot resolve user %s to follow", url_or_uid));
1694 return NULL;
1695 }
1696
1697 /* request the actor */
1698 status = actor_request(snac, actor, &actor_o);
1699
1700 if (valid_status(status)) {
1701 /* check if the actor is an alias */
1702 const char *r_actor = xs_dict_get(actor_o, "id");
1703
1704 if (r_actor && strcmp(actor, r_actor) != 0) {
1705 snac_log(snac, xs_fmt("actor to follow is an alias %s -> %s", actor, r_actor));
1706 }
1707
1708 msg = msg_base(snac, "Follow", "@dummy", snac->actor, NULL, r_actor);
1709 }
1710 else
1711 snac_log(snac, xs_fmt("cannot get actor to follow %s %d", actor, status));
1712
1713 return msg;
1714}
1715
1716
1717xs_dict *msg_note(snac *snac, const xs_str *content, const xs_val *rcpts,
1718 const xs_str *in_reply_to, const xs_list *attach,
1719 int scope, const char *lang_str, const char *msg_date)
1720/* creates a 'Note' message */
1721/* scope: 0, public; 1, private (mentioned only); 2, "quiet public"; 3, followers only */
1722{
1723 xs *ntid = tid(0);
1724 xs *id = xs_fmt("%s/p/%s", snac->actor, ntid);
1725 xs *ctxt = NULL;
1726 xs *fc2 = NULL;
1727 xs *fc1 = NULL;
1728 xs *to = NULL;
1729 xs *cc = xs_list_new();
1730 xs *irt = NULL;
1731 xs *tag = xs_list_new();
1732 xs *atls = xs_list_new();
1733
1734 /* discard non-parseable dates */
1735 if (!xs_is_string(msg_date) || xs_parse_iso_date(msg_date, 0) == 0)
1736 msg_date = NULL;
1737
1738 xs_dict *msg = msg_base(snac, "Note", id, NULL, xs_or(msg_date, "@now"), NULL);
1739 xs_list *p;
1740 const xs_val *v;
1741
1742 /* FIXME: implement scope 3 */
1743 int priv = scope == 1;
1744
1745 if (rcpts == NULL)
1746 to = xs_list_new();
1747 else {
1748 if (xs_type(rcpts) == XSTYPE_STRING) {
1749 to = xs_list_new();
1750 to = xs_list_append(to, rcpts);
1751 }
1752 else
1753 to = xs_dup(rcpts);
1754 }
1755
1756 /* format the content */
1757 fc2 = not_really_markdown(content, &atls, &tag);
1758
1759 if (in_reply_to != NULL && *in_reply_to) {
1760 xs *p_msg = NULL;
1761 xs *wrk = NULL;
1762
1763 /* demand this thing */
1764 timeline_request(snac, &in_reply_to, &wrk, 0);
1765
1766 if (valid_status(object_get(in_reply_to, &p_msg))) {
1767 /* add this author as recipient */
1768 const char *a, *v;
1769
1770 if ((a = get_atto(p_msg)) && xs_list_in(to, a) == -1)
1771 to = xs_list_append(to, a);
1772
1773 /* add this author to the tag list as a mention */
1774 if (!xs_is_null(a)) {
1775 xs *l = xs_split(a, "/");
1776 xs *actor_o = NULL;
1777
1778 if (xs_list_len(l) > 3 && valid_status(object_get(a, &actor_o))) {
1779 const char *uname = xs_dict_get(actor_o, "preferredUsername");
1780
1781 if (!xs_is_null(uname) && *uname) {
1782 xs *handle = xs_fmt("@%s@%s", uname, xs_list_get(l, 2));
1783
1784 xs *t = xs_dict_new();
1785
1786 t = xs_dict_append(t, "type", "Mention");
1787 t = xs_dict_append(t, "href", a);
1788 t = xs_dict_append(t, "name", handle);
1789
1790 tag = xs_list_append(tag, t);
1791 }
1792 }
1793 }
1794
1795 /* get the context, if there is one */
1796 if ((v = xs_dict_get(p_msg, "context")))
1797 ctxt = xs_dup(v);
1798
1799 /* propagate the conversation field, if there is one */
1800 if ((v = xs_dict_get(p_msg, "conversation")))
1801 msg = xs_dict_append(msg, "conversation", v);
1802
1803 /* if this message is public, ours will also be */
1804 if (!priv && is_msg_public(p_msg) && xs_list_in(to, public_address) == -1)
1805 to = xs_list_append(to, public_address);
1806 }
1807
1808 irt = xs_dup(in_reply_to);
1809 }
1810 else
1811 irt = xs_val_new(XSTYPE_NULL);
1812
1813 /* extract the mentions and hashtags and convert the content */
1814 fc1 = process_tags(snac, fc2, &tag);
1815
1816 /* create the attachment list, if there are any */
1817 if (!xs_is_null(attach)) {
1818 xs_list_foreach(attach, v) {
1819 const char *url = xs_list_get(v, 0);
1820 const char *alt = xs_list_get(v, 1);
1821 const char *mime = xs_mime_by_ext(url);
1822 int add = 1;
1823
1824 /* check if it's already here */
1825 const xs_dict *ad;
1826 xs_list_foreach(atls, ad) {
1827 if (strcmp(xs_dict_get_def(ad, "url", ""), url) == 0) {
1828 add = 0;
1829 break;
1830 }
1831 }
1832
1833 if (add) {
1834 xs *d = xs_dict_new();
1835 d = xs_dict_append(d, "mediaType", mime);
1836 d = xs_dict_append(d, "url", url);
1837 d = xs_dict_append(d, "name", alt);
1838 d = xs_dict_append(d, "type",
1839 xs_startswith(mime, "image/") ? "Image" : "Document");
1840
1841 atls = xs_list_append(atls, d);
1842 }
1843 }
1844 }
1845
1846 if (ctxt == NULL)
1847 ctxt = xs_fmt("%s#ctxt", id);
1848
1849 /* add all mentions to the cc */
1850 p = tag;
1851 while (xs_list_iter(&p, &v)) {
1852 if (xs_type(v) == XSTYPE_DICT) {
1853 const char *t;
1854
1855 if (!xs_is_null(t = xs_dict_get(v, "type")) && strcmp(t, "Mention") == 0) {
1856 if (!xs_is_null(t = xs_dict_get(v, "href")))
1857 cc = xs_list_append(cc, t);
1858 }
1859 }
1860 }
1861
1862 if (scope == 2) {
1863 /* Mastodon's "quiet public": add public address to cc */
1864 if (xs_list_in(cc, public_address) == -1)
1865 cc = xs_list_append(cc, public_address);
1866 }
1867 else
1868 /* no recipients? must be for everybody */
1869 if (!priv && xs_list_len(to) == 0)
1870 to = xs_list_append(to, public_address);
1871
1872 /* delete all cc recipients that also are in the to */
1873 p = to;
1874 while (xs_list_iter(&p, &v)) {
1875 int i;
1876
1877 if ((i = xs_list_in(cc, v)) != -1)
1878 cc = xs_list_del(cc, i);
1879 }
1880
1881 msg = xs_dict_append(msg, "attributedTo", snac->actor);
1882 msg = xs_dict_append(msg, "summary", "");
1883 msg = xs_dict_append(msg, "content", fc1);
1884 msg = xs_dict_append(msg, "context", ctxt);
1885 msg = xs_dict_append(msg, "url", id);
1886 msg = xs_dict_append(msg, "to", to);
1887 msg = xs_dict_append(msg, "cc", cc);
1888 msg = xs_dict_append(msg, "inReplyTo", irt);
1889 msg = xs_dict_append(msg, "tag", tag);
1890
1891 msg = xs_dict_append(msg, "sourceContent", content);
1892
1893 if (xs_list_len(atls))
1894 msg = xs_dict_append(msg, "attachment", atls);
1895
1896 /* set language content map */
1897 if (xs_type(lang_str) == XSTYPE_STRING) {
1898 /* split at the first _ */
1899 xs *l0 = xs_split(lang_str, "_");
1900 const char *lang = xs_list_get(l0, 0);
1901
1902 if (xs_type(lang) == XSTYPE_STRING && strlen(lang) == 2) {
1903 /* a valid ISO language id */
1904 xs *cmap = xs_dict_new();
1905 cmap = xs_dict_set(cmap, lang, xs_dict_get(msg, "content"));
1906 msg = xs_dict_set(msg, "contentMap", cmap);
1907 }
1908 }
1909
1910 if (!priv) {
1911 /* create the replies object */
1912 xs *replies = xs_dict_new();
1913 xs *r_id = xs_replace(id, "/p/", "/r/");
1914 xs *h_id = xs_fmt("%s#hdr", r_id);
1915 xs *rp = msg_replies(snac, id, 0);
1916
1917 replies = xs_dict_set(replies, "id", h_id);
1918 replies = xs_dict_set(replies, "type", "Collection");
1919 replies = xs_dict_set(replies, "first", rp);
1920
1921 msg = xs_dict_set(msg, "replies", replies);
1922 }
1923
1924 return msg;
1925}
1926
1927
1928xs_dict *msg_ping(snac *user, const char *rcpt)
1929/* creates a Ping message (https://humungus.tedunangst.com/r/honk/v/tip/f/docs/ping.txt) */
1930{
1931 xs_dict *msg = msg_base(user, "Ping", "@dummy", user->actor, NULL, NULL);
1932
1933 msg = xs_dict_append(msg, "to", rcpt);
1934
1935 return msg;
1936}
1937
1938
1939xs_dict *msg_pong(snac *user, const char *rcpt, const char *object)
1940/* creates a Pong message (https://humungus.tedunangst.com/r/honk/v/tip/f/docs/ping.txt) */
1941{
1942 xs_dict *msg = msg_base(user, "Pong", "@dummy", user->actor, NULL, object);
1943
1944 msg = xs_dict_append(msg, "to", rcpt);
1945
1946 return msg;
1947}
1948
1949
1950xs_dict *msg_move(snac *user, const char *new_account)
1951/* creates a Move message (to move the user to new_account) */
1952{
1953 xs_dict *msg = msg_base(user, "Move", "@dummy", user->actor, NULL, user->actor);
1954
1955 msg = xs_dict_append(msg, "target", new_account);
1956
1957 return msg;
1958}
1959
1960
1961xs_dict *msg_question(snac *user, const char *content, xs_list *attach,
1962 const xs_list *opts, int multiple, int end_secs)
1963/* creates a Question message */
1964{
1965 xs_dict *msg = msg_note(user, content, NULL, NULL, attach, 0, NULL, NULL);
1966 int max = 8;
1967 xs_set seen;
1968
1969 msg = xs_dict_set(msg, "type", "Question");
1970
1971 /* make it non-editable */
1972 msg = xs_dict_del(msg, "sourceContent");
1973
1974 xs *o = xs_list_new();
1975 xs_list *p = (xs_list *)opts;
1976 const xs_str *v;
1977 xs *replies = xs_json_loads("{\"type\":\"Collection\",\"totalItems\":0}");
1978
1979 xs_set_init(&seen);
1980
1981 while (max && xs_list_iter(&p, &v)) {
1982 if (*v) {
1983 xs *v2 = xs_dup(v);
1984 xs *d = xs_dict_new();
1985
1986 if (strlen(v2) > 60) {
1987 v2[60] = '\0';
1988 v2 = xs_str_cat(v2, "...");
1989 }
1990
1991 if (xs_set_add(&seen, v2) == 1) {
1992 d = xs_dict_append(d, "type", "Note");
1993 d = xs_dict_append(d, "name", v2);
1994 d = xs_dict_append(d, "replies", replies);
1995 o = xs_list_append(o, d);
1996
1997 max--;
1998 }
1999 }
2000 }
2001
2002 xs_set_free(&seen);
2003
2004 msg = xs_dict_append(msg, multiple ? "anyOf" : "oneOf", o);
2005
2006 /* set the end time */
2007 time_t t = time(NULL) + end_secs;
2008 xs *et = xs_str_utctime(t, ISO_DATE_SPEC);
2009
2010 msg = xs_dict_append(msg, "endTime", et);
2011
2012 return msg;
2013}
2014
2015
2016int update_question(snac *user, const char *id)
2017/* updates the poll counts */
2018{
2019 xs *msg = NULL;
2020 xs *rcnt = xs_dict_new();
2021 xs *lopts = xs_list_new();
2022 const xs_list *opts;
2023 xs_list *p;
2024 const xs_val *v;
2025
2026 /* get the object */
2027 if (!valid_status(object_get(id, &msg)))
2028 return -1;
2029
2030 /* closed? do nothing more */
2031 if (xs_dict_get(msg, "closed"))
2032 return -2;
2033
2034 /* get the options */
2035 if ((opts = xs_dict_get(msg, "oneOf")) == NULL &&
2036 (opts = xs_dict_get(msg, "anyOf")) == NULL)
2037 return -3;
2038
2039 /* fill the initial count */
2040 int c = 0;
2041 while (xs_list_next(opts, &v, &c)) {
2042 const char *name = xs_dict_get(v, "name");
2043 if (name) {
2044 lopts = xs_list_append(lopts, name);
2045 rcnt = xs_dict_set(rcnt, name, xs_stock(0));
2046 }
2047 }
2048
2049 xs_set s;
2050 xs_set_init(&s);
2051
2052 /* iterate now the children (the votes) */
2053 xs *chld = object_children(id);
2054 p = chld;
2055 while (xs_list_iter(&p, &v)) {
2056 xs *obj = NULL;
2057
2058 if (!valid_status(object_get_by_md5(v, &obj)))
2059 continue;
2060
2061 const char *name = xs_dict_get(obj, "name");
2062 const char *atto = get_atto(obj);
2063
2064 if (name && atto) {
2065 /* get the current count */
2066 const xs_number *cnt = xs_dict_get(rcnt, name);
2067
2068 if (xs_type(cnt) == XSTYPE_NUMBER) {
2069 /* if it exists, increment */
2070 xs *ucnt = xs_number_new(xs_number_get(cnt) + 1);
2071 rcnt = xs_dict_set(rcnt, name, ucnt);
2072
2073 xs_set_add(&s, atto);
2074 }
2075 }
2076 }
2077
2078 xs *rcpts = xs_set_result(&s);
2079
2080 /* create a new list of options with their new counts */
2081 xs *nopts = xs_list_new();
2082 p = lopts;
2083 while (xs_list_iter(&p, &v)) {
2084 const xs_number *cnt = xs_dict_get(rcnt, v);
2085
2086 if (xs_type(cnt) == XSTYPE_NUMBER) {
2087 xs *d1 = xs_dict_new();
2088 xs *d2 = xs_dict_new();
2089
2090 d2 = xs_dict_append(d2, "type", "Collection");
2091 d2 = xs_dict_append(d2, "totalItems", cnt);
2092
2093 d1 = xs_dict_append(d1, "type", "Note");
2094 d1 = xs_dict_append(d1, "name", v);
2095 d1 = xs_dict_append(d1, "replies", d2);
2096
2097 nopts = xs_list_append(nopts, d1);
2098 }
2099 }
2100
2101 /* update the list */
2102 msg = xs_dict_set(msg, xs_dict_get(msg, "oneOf") != NULL ? "oneOf" : "anyOf", nopts);
2103
2104 /* due date? */
2105 int closed = 0;
2106 const char *end_time = xs_dict_get(msg, "endTime");
2107 if (!xs_is_null(end_time)) {
2108 xs *now = xs_str_utctime(0, ISO_DATE_SPEC);
2109
2110 /* is now greater than the endTime? */
2111 if (strcmp(now, end_time) >= 0) {
2112 xs *et = xs_dup(end_time);
2113 msg = xs_dict_set(msg, "closed", et);
2114
2115 closed = 1;
2116 }
2117 }
2118
2119 /* update the count of voters */
2120 xs *vcnt = xs_number_new(xs_list_len(rcpts));
2121 msg = xs_dict_set(msg, "votersCount", vcnt);
2122 msg = xs_dict_set(msg, "cc", rcpts);
2123
2124 /* store */
2125 object_add_ow(id, msg);
2126
2127 snac_debug(user, 1, xs_fmt("recounted poll %s", id));
2128 timeline_touch(user);
2129
2130 /* send an update message to all voters */
2131 xs *u_msg = msg_update(user, msg);
2132 u_msg = xs_dict_set(u_msg, "cc", rcpts);
2133
2134 enqueue_message(user, u_msg);
2135
2136 if (closed) {
2137 xs *c_msg = msg_update(user, msg);
2138 notify(user, "Update", "Question", user->actor, c_msg);
2139 }
2140
2141 return 0;
2142}
2143
2144
2145/** queues **/
2146
2147int process_input_message(snac *snac, const xs_dict *msg, const xs_dict *req)
2148/* processes an ActivityPub message from the input queue */
2149/* return values: -1, fatal error; 0, transient error, retry;
2150 1, processed and done; 2, propagate to users (only when no user is set) */
2151{
2152 const char *actor = xs_dict_get(msg, "actor");
2153 const char *type = xs_dict_get(msg, "type");
2154 xs *actor_o = NULL;
2155 int a_status;
2156 int do_notify = 0;
2157
2158 if (xs_is_null(actor) || *actor == '\0') {
2159 srv_debug(0, xs_fmt("malformed message (bad actor)"));
2160 return -1;
2161 }
2162
2163 /* question votes may not have a type */
2164 if (xs_is_null(type))
2165 type = "Note";
2166
2167 /* reject uninteresting messages right now */
2168 if (xs_match(type, "Add|View|Reject|Read|Remove")) {
2169 srv_debug(0, xs_fmt("Ignored message of type '%s'", type));
2170
2171 /* archive the ignored activity */
2172 xs *ntid = tid(0);
2173 xs *fn = xs_fmt("%s/ignored/%s.json", srv_basedir, ntid);
2174 FILE *f;
2175
2176 if ((f = fopen(fn, "w")) != NULL) {
2177 xs_json_dump(msg, 4, f);
2178 fclose(f);
2179 }
2180
2181 return -1;
2182 }
2183
2184 const char *object, *utype;
2185
2186 object = xs_dict_get(msg, "object");
2187 if (object != NULL && xs_type(object) == XSTYPE_DICT)
2188 utype = xs_dict_get(object, "type");
2189 else
2190 utype = "(null)";
2191
2192 /* special case for Delete messages */
2193 if (strcmp(type, "Delete") == 0) {
2194 /* if the actor is not here, do not even try */
2195 if (!object_here(actor)) {
2196 srv_debug(1, xs_fmt("dropped 'Delete' message from unknown actor '%s'", actor));
2197 return -1;
2198 }
2199
2200 /* discard crap */
2201 if (xs_is_null(object)) {
2202 srv_log(xs_fmt("dropped 'Delete' message with invalid object from actor '%s'", actor));
2203 return -1;
2204 }
2205
2206 /* also discard if the object to be deleted is not here */
2207 const char *obj_id = object;
2208 if (xs_type(obj_id) == XSTYPE_DICT)
2209 obj_id = xs_dict_get(obj_id, "id");
2210
2211 if (xs_is_null(obj_id) || !object_here(obj_id)) {
2212 srv_debug(1, xs_fmt("dropped 'Delete' message from unknown object '%s'", obj_id));
2213 return -1;
2214 }
2215 }
2216
2217 /* bring the actor */
2218 a_status = actor_request(snac, actor, &actor_o);
2219
2220 /* do not retry permanent failures */
2221 if (a_status == HTTP_STATUS_NOT_FOUND
2222 || a_status == HTTP_STATUS_GONE
2223 || a_status < 0) {
2224 srv_debug(1, xs_fmt("dropping message due to actor error %s %d", actor, a_status));
2225 return -1;
2226 }
2227
2228 if (!valid_status(a_status)) {
2229 /* do not retry 'Delete' messages */
2230 if (strcmp(type, "Delete") == 0) {
2231 srv_debug(1, xs_fmt("dropping 'Delete' message due to actor error %s %d", actor, a_status));
2232 return -1;
2233 }
2234
2235 /* other actor download errors */
2236
2237 /* the actor may require a signed request; propagate if no user is set */
2238 if (snac == NULL)
2239 return 2;
2240
2241 /* may need a retry */
2242 srv_debug(0, xs_fmt("error requesting actor %s %d -- retry later", actor, a_status));
2243 return 0;
2244 }
2245
2246 /* check the signature */
2247 xs *sig_err = NULL;
2248
2249 if (!check_signature(req, &sig_err)) {
2250 srv_log(xs_fmt("bad signature %s (%s)", actor, sig_err));
2251
2252 srv_archive_error("check_signature", sig_err, req, msg);
2253 return -1;
2254 }
2255
2256 /* if no user is set, no further checks can be done; propagate */
2257 if (snac == NULL)
2258 return 2;
2259
2260 /* reject messages that are not for this user */
2261 if (!is_msg_for_me(snac, msg)) {
2262 snac_debug(snac, 1, xs_fmt("message from %s of type '%s' not for us", actor, type));
2263
2264 return 1;
2265 }
2266
2267 /* if it's a DM from someone we don't follow, reject the message */
2268 if (xs_type(xs_dict_get(snac->config, "drop_dm_from_unknown")) == XSTYPE_TRUE) {
2269 if (strcmp(utype, "Note") == 0 && !is_msg_public(msg) &&
2270 !following_check(snac, actor)) {
2271 snac_log(snac, xs_fmt("DM rejected from unknown actor %s", actor));
2272
2273 return 1;
2274 }
2275 }
2276
2277 /* check the minimum acceptable account age */
2278 int min_account_age = xs_number_get(xs_dict_get(srv_config, "min_account_age"));
2279
2280 if (min_account_age > 0) {
2281 const char *actor_date = xs_dict_get(actor_o, "published");
2282 if (!xs_is_null(actor_date)) {
2283 time_t actor_t = xs_parse_iso_date(actor_date, 0);
2284
2285 if (actor_t < 950000000) {
2286 snac_log(snac, xs_fmt("rejected activity from %s (suspicious date, %s)",
2287 actor, actor_date));
2288
2289 return 1;
2290 }
2291
2292 if (actor_t > 0) {
2293 int td = (int)(time(NULL) - actor_t);
2294
2295 snac_debug(snac, 2, xs_fmt("actor %s age: %d seconds", actor, td));
2296
2297 if (td < min_account_age) {
2298 snac_log(snac, xs_fmt("rejected activity from %s (too new, %d seconds)",
2299 actor, td));
2300
2301 return 1;
2302 }
2303 }
2304 }
2305 else
2306 snac_debug(snac, 1, xs_fmt("warning: empty or null creation date for %s", actor));
2307 }
2308
2309 if (strcmp(type, "Follow") == 0) { /** **/
2310 const char *id = xs_dict_get(msg, "id");
2311
2312 if (xs_is_null(id)) {
2313 snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2314 }
2315 else
2316 if (!follower_check(snac, actor)) {
2317 /* ensure the actor object is here */
2318 if (!object_here(actor)) {
2319 xs *actor_obj = NULL;
2320 actor_request(snac, actor, &actor_obj);
2321 object_add(actor, actor_obj);
2322 }
2323
2324 if (xs_is_true(xs_dict_get(snac->config, "approve_followers"))) {
2325 pending_add(snac, actor, msg);
2326
2327 snac_log(snac, xs_fmt("new pending follower approval %s", actor));
2328 }
2329 else {
2330 /* automatic following */
2331 xs *f_msg = xs_dup(msg);
2332 xs *reply = msg_accept(snac, f_msg, actor);
2333
2334 post_message(snac, actor, reply);
2335
2336 if (xs_is_null(xs_dict_get(f_msg, "published"))) {
2337 /* add a date if it doesn't include one (Mastodon) */
2338 xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
2339 f_msg = xs_dict_set(f_msg, "published", date);
2340 }
2341
2342 timeline_add(snac, id, f_msg);
2343
2344 follower_add(snac, actor);
2345
2346 snac_log(snac, xs_fmt("new follower %s", actor));
2347 }
2348
2349 do_notify = 1;
2350 }
2351 else
2352 snac_log(snac, xs_fmt("repeated 'Follow' from %s", actor));
2353 }
2354 else
2355 if (strcmp(type, "Undo") == 0) { /** **/
2356 const char *id = xs_dict_get(object, "object");
2357
2358 if (xs_type(object) != XSTYPE_DICT) {
2359 snac_debug(snac, 1, xs_fmt("undo: overriding utype %s | %s | %s",
2360 utype, id, actor));
2361 utype = "Follow";
2362 }
2363
2364 if (strcmp(utype, "Follow") == 0) { /** **/
2365 if (!id) {
2366 snac_log(snac, xs_fmt("no id (msg.object.object) when "
2367 "handling follow: %s", actor));
2368 return 1;
2369 }
2370 if (strcmp(id, snac->actor) != 0)
2371 snac_debug(snac, 1, xs_fmt("Undo + Follow from %s not for us (%s)", actor, id));
2372 else
2373 if (valid_status(follower_del(snac, actor))) {
2374 snac_log(snac, xs_fmt("no longer following us %s", actor));
2375 do_notify = 1;
2376 }
2377 else
2378 if (pending_check(snac, actor)) {
2379 pending_del(snac, actor);
2380 snac_log(snac, xs_fmt("cancelled pending follow from %s", actor));
2381 }
2382 else
2383 snac_log(snac, xs_fmt("error deleting follower %s", actor));
2384 }
2385 else
2386 if (strcmp(utype, "Like") == 0 || strcmp(utype, "EmojiReact") == 0) { /** **/
2387 int status = object_unadmire(id, actor, 1);
2388
2389 snac_log(snac, xs_fmt("Undo '%s' for %s %d", utype, id, status));
2390 }
2391 else
2392 if (strcmp(utype, "Announce") == 0) { /** **/
2393 int status = HTTP_STATUS_OK;
2394
2395 /* commented out: if a followed user boosts something that
2396 is requested and then unboosts, the post remains here,
2397 but with no apparent reason, and that is confusing */
2398 //status = object_unadmire(id, actor, 0);
2399
2400 snac_log(snac, xs_fmt("Unboost for %s %d", id, status));
2401 }
2402 else
2403 snac_debug(snac, 1, xs_fmt("ignored 'Undo' for object type '%s'", utype));
2404 }
2405 else
2406 if (strcmp(type, "Create") == 0) { /** **/
2407 if (is_muted(snac, actor)) {
2408 snac_log(snac, xs_fmt("ignored 'Create' + '%s' from muted actor %s", utype, actor));
2409 return 1;
2410 }
2411
2412 if (xs_match(utype, "Note|Article")) { /** **/
2413 const char *id = xs_dict_get(object, "id");
2414 const char *in_reply_to = get_in_reply_to(object);
2415 const char *atto = get_atto(object);
2416 xs *wrk = NULL;
2417
2418 if (xs_is_null(id))
2419 snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2420 else
2421 if (xs_is_null(atto))
2422 snac_log(snac, xs_fmt("malformed message: no 'attributedTo' field"));
2423 else
2424 if (!xs_is_null(in_reply_to) && is_hidden(snac, in_reply_to)) {
2425 snac_debug(snac, 0, xs_fmt("dropped reply %s to hidden post %s", id, in_reply_to));
2426 }
2427 else {
2428 if (content_match("filter_reject.txt", object)) {
2429 snac_log(snac, xs_fmt("rejected by content %s", id));
2430 return 1;
2431 }
2432
2433 if (strcmp(actor, atto) != 0)
2434 snac_log(snac, xs_fmt("SUSPICIOUS: actor != atto (%s != %s)", actor, atto));
2435
2436 timeline_request(snac, &in_reply_to, &wrk, 0);
2437
2438 if (timeline_add(snac, id, object)) {
2439 snac_log(snac, xs_fmt("new '%s' %s %s", utype, actor, id));
2440 do_notify = 1;
2441 }
2442
2443 /* if it has a "name" field, it may be a vote for a question */
2444 const char *name = xs_dict_get(object, "name");
2445
2446 if (!xs_is_null(name) && *name && !xs_is_null(in_reply_to) && *in_reply_to)
2447 update_question(snac, in_reply_to);
2448 }
2449 }
2450 else
2451 if (strcmp(utype, "Question") == 0) { /** **/
2452 const char *id = xs_dict_get(object, "id");
2453
2454 if (xs_is_null(id))
2455 snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2456 else
2457 if (timeline_add(snac, id, object))
2458 snac_log(snac, xs_fmt("new 'Question' %s %s", actor, id));
2459 }
2460 else
2461 if (xs_match(utype, "Audio|Video|Event")) { /** **/
2462 const char *id = xs_dict_get(object, "id");
2463
2464 if (xs_is_null(id))
2465 snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2466 else
2467 if (timeline_add(snac, id, object))
2468 snac_log(snac, xs_fmt("new '%s' %s %s", utype, actor, id));
2469 }
2470 else
2471 snac_debug(snac, 1, xs_fmt("ignored 'Create' for object type '%s'", utype));
2472 }
2473 else
2474 if (strcmp(type, "Accept") == 0) { /** **/
2475 if (strcmp(utype, "(null)") == 0) {
2476 const char *obj_id = xs_dict_get(msg, "object");
2477
2478 /* if the accepted object id is a string that may
2479 be created by us, it's a follow */
2480 if (xs_type(obj_id) == XSTYPE_STRING &&
2481 xs_startswith(obj_id, srv_baseurl) &&
2482 xs_endswith(obj_id, "/Follow"))
2483 utype = "Follow";
2484 }
2485
2486 if (strcmp(utype, "Follow") == 0) { /** **/
2487 if (following_check(snac, actor)) {
2488 following_add(snac, actor, msg);
2489 snac_log(snac, xs_fmt("confirmed follow from %s", actor));
2490 }
2491 else
2492 snac_log(snac, xs_fmt("spurious follow accept from %s", actor));
2493 }
2494 else
2495 if (strcmp(utype, "Create") == 0) {
2496 /* some implementations send Create confirmations, go figure */
2497 snac_debug(snac, 1, xs_dup("ignored 'Accept' + 'Create'"));
2498 }
2499 else {
2500 srv_archive_error("accept", "ignored Accept", req, msg);
2501 snac_debug(snac, 1, xs_fmt("ignored 'Accept' for object type '%s'", utype));
2502 }
2503 }
2504 else
2505 if (strcmp(type, "Like") == 0 || strcmp(type, "EmojiReact") == 0) { /** **/
2506 if (xs_type(object) == XSTYPE_DICT)
2507 object = xs_dict_get(object, "id");
2508
2509 if (xs_is_null(object))
2510 snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2511 else
2512 if (timeline_admire(snac, object, actor, 1) == HTTP_STATUS_CREATED)
2513 snac_log(snac, xs_fmt("new '%s' %s %s", type, actor, object));
2514 else
2515 snac_log(snac, xs_fmt("repeated '%s' from %s to %s", type, actor, object));
2516
2517 do_notify = 1;
2518 }
2519 else
2520 if (strcmp(type, "Announce") == 0) { /** **/
2521 if (xs_type(object) == XSTYPE_DICT)
2522 object = xs_dict_get(object, "id");
2523
2524 if (xs_is_null(object))
2525 snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2526 else
2527 if (is_muted(snac, actor) && !xs_startswith(object, snac->actor))
2528 snac_log(snac, xs_fmt("dropped 'Announce' from muted actor %s", actor));
2529 else
2530 if (is_limited(snac, actor) && !xs_startswith(object, snac->actor))
2531 snac_log(snac, xs_fmt("dropped 'Announce' from limited actor %s", actor));
2532 else {
2533 xs *a_msg = NULL;
2534 xs *wrk = NULL;
2535
2536 timeline_request(snac, &object, &wrk, 0);
2537
2538 if (valid_status(object_get(object, &a_msg))) {
2539 const char *who = get_atto(a_msg);
2540
2541 if (who && !is_muted(snac, who)) {
2542 /* bring the actor */
2543 xs *who_o = NULL;
2544
2545 if (valid_status(actor_request(snac, who, &who_o))) {
2546 /* don't account as such announces by our own relay */
2547 xs *this_relay = xs_fmt("%s/relay", srv_baseurl);
2548
2549 if (strcmp(actor, this_relay) != 0) {
2550 if (valid_status(timeline_admire(snac, object, actor, 0)))
2551 snac_log(snac, xs_fmt("new 'Announce' %s %s", actor, object));
2552 else
2553 snac_log(snac, xs_fmt("repeated 'Announce' from %s to %s",
2554 actor, object));
2555 }
2556
2557 /* distribute the post with the actor as 'proxy' */
2558 list_distribute(snac, actor, a_msg);
2559
2560 /* distribute the post to users following these hashtags */
2561 followed_hashtag_distribute(a_msg);
2562
2563 do_notify = 1;
2564 }
2565 else
2566 snac_debug(snac, 1, xs_fmt("dropped 'Announce' on actor request error %s", who));
2567 }
2568 else
2569 snac_log(snac, xs_fmt("ignored 'Announce' about muted actor %s", who));
2570 }
2571 else
2572 snac_debug(snac, 2, xs_fmt("error requesting 'Announce' object %s", object));
2573 }
2574 }
2575 else
2576 if (strcmp(type, "Update") == 0) { /** **/
2577 if (xs_match(utype, "Person|Service|Application")) { /** **/
2578 actor_add(actor, xs_dict_get(msg, "object"));
2579 timeline_touch(snac);
2580
2581 snac_log(snac, xs_fmt("updated actor %s", actor));
2582 }
2583 else
2584 if (xs_match(utype, "Note|Page|Article|Video|Audio|Event")) { /** **/
2585 const char *id = xs_dict_get(object, "id");
2586
2587 if (xs_is_null(id))
2588 snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2589 else
2590 if (object_here(id)) {
2591 if (xs_startswith(id, srv_baseurl) && !xs_startswith(id, actor))
2592 snac_log(snac, xs_fmt("ignored incorrect 'Update' %s %s", actor, id));
2593 else {
2594 object_add_ow(id, object);
2595 timeline_touch(snac);
2596
2597 snac_log(snac, xs_fmt("updated '%s' %s", utype, id));
2598 }
2599 }
2600 else
2601 snac_log(snac, xs_fmt("dropped update for unknown '%s' %s", utype, id));
2602 }
2603 else
2604 if (strcmp(utype, "Question") == 0) { /** **/
2605 const char *id = xs_dict_get(object, "id");
2606 const char *closed = xs_dict_get(object, "closed");
2607
2608 if (xs_is_null(id))
2609 snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2610 else {
2611 object_add_ow(id, object);
2612 timeline_touch(snac);
2613
2614 snac_log(snac, xs_fmt("%s poll %s", closed == NULL ? "updated" : "closed", id));
2615
2616 if (closed != NULL)
2617 do_notify = 1;
2618 }
2619 }
2620 else {
2621 srv_archive_error("unsupported_update", "unsupported_update", req, msg);
2622
2623 snac_log(snac, xs_fmt("ignored 'Update' for object type '%s'", utype));
2624 }
2625 }
2626 else
2627 if (strcmp(type, "Delete") == 0) { /** **/
2628 if (xs_type(object) == XSTYPE_DICT)
2629 object = xs_dict_get(object, "id");
2630
2631 if (xs_is_null(object))
2632 snac_log(snac, xs_fmt("malformed message: no 'id' field"));
2633 else
2634 if (object_here(object)) {
2635 if (xs_startswith(object, srv_baseurl) && !xs_startswith(object, actor))
2636 snac_log(snac, xs_fmt("ignored incorrect 'Delete' %s %s", actor, object));
2637 else {
2638 timeline_del(snac, object);
2639 snac_debug(snac, 1, xs_fmt("new 'Delete' %s %s", actor, object));
2640 }
2641 }
2642 else
2643 snac_debug(snac, 1, xs_fmt("ignored 'Delete' for unknown object %s", object));
2644 }
2645 else
2646 if (strcmp(type, "Pong") == 0) { /** **/
2647 snac_log(snac, xs_fmt("'Pong' received from %s", actor));
2648 }
2649 else
2650 if (strcmp(type, "Ping") == 0) { /** **/
2651 const char *id = xs_dict_get(msg, "id");
2652
2653 snac_log(snac, xs_fmt("'Ping' requested from %s", actor));
2654
2655 if (!xs_is_null(id)) {
2656 xs *rsp = msg_pong(snac, actor, id);
2657
2658 enqueue_output_by_actor(snac, rsp, actor, 0);
2659 }
2660 }
2661 else
2662 if (strcmp(type, "Block") == 0) { /** **/
2663 snac_debug(snac, 1, xs_fmt("'Block' received from %s", actor));
2664
2665 /* should we MUTE the actor back? */
2666 /* mute(snac, actor); */
2667
2668 if (!xs_is_true(xs_dict_get(srv_config, "disable_block_notifications")))
2669 do_notify = 1;
2670 }
2671 else
2672 if (strcmp(type, "Move") == 0) { /** **/
2673 do_notify = 1;
2674
2675 const char *old_account = xs_dict_get(msg, "object");
2676 const char *new_account = xs_dict_get(msg, "target");
2677
2678 if (!xs_is_null(old_account) && !xs_is_null(new_account)) {
2679 if (following_check(snac, old_account)) {
2680 xs *n_actor = NULL;
2681
2682 if (valid_status(object_get(new_account, &n_actor))) {
2683 const xs_list *aka = xs_dict_get(n_actor, "alsoKnownAs");
2684
2685 if (xs_type(aka) == XSTYPE_LIST) {
2686 if (xs_list_in(aka, old_account) != -1) {
2687 /* all conditions met! */
2688
2689 /* follow new account */
2690 xs *f_msg = msg_follow(snac, new_account);
2691
2692 if (f_msg != NULL) {
2693 const char *new_actor = xs_dict_get(f_msg, "object");
2694 following_add(snac, new_actor, f_msg);
2695 enqueue_output_by_actor(snac, f_msg, new_actor, 0);
2696
2697 snac_log(snac, xs_fmt("'Move': following %s", new_account));
2698 }
2699
2700 /* unfollow old account */
2701 xs *of_msg = NULL;
2702
2703 if (valid_status(following_get(snac, old_account, &of_msg))) {
2704 xs *uf_msg = msg_undo(snac, xs_dict_get(of_msg, "object"));
2705 following_del(snac, old_account);
2706 enqueue_output_by_actor(snac, uf_msg, old_account, 0);
2707
2708 snac_log(snac, xs_fmt("'Move': unfollowing %s", old_account));
2709 }
2710 }
2711 else
2712 snac_log(snac, xs_fmt("'Move' error: old actor %s not found in %s 'alsoKnownAs'",
2713 old_account, new_account));
2714 }
2715 else
2716 snac_log(snac, xs_fmt("'Move' error: cannot get %s 'alsoKnownAs'", new_account));
2717 }
2718 else {
2719 snac_log(snac, xs_fmt("'Move' error: cannot get new actor %s", new_account));
2720
2721 /* may be a server hiccup, retry later */
2722 return 0;
2723 }
2724 }
2725 else
2726 snac_log(snac, xs_fmt("'Move' error: actor %s is not being followed", old_account));
2727 }
2728 else {
2729 snac_log(snac, xs_fmt("'Move' error: malformed message from %s", actor));
2730 srv_archive_error("move", "move", req, msg);
2731 }
2732 }
2733 else {
2734 srv_archive_error("unsupported_type", "unsupported_type", req, msg);
2735
2736 snac_debug(snac, 1, xs_fmt("process_input_message type '%s' ignored", type));
2737 }
2738
2739 if (do_notify) {
2740 notify(snac, type, utype, actor, msg);
2741
2742 timeline_touch(snac);
2743 }
2744
2745 return 1;
2746}
2747
2748
2749int send_email(const xs_dict *mailinfo)
2750/* invoke curl */
2751{
2752 const char *url = xs_dict_get(srv_config, "smtp_url");
2753
2754 if (!xs_is_string(url) || *url == '\0') {
2755 /* revert back to old sendmail pipe behaviour */
2756 const char *msg = xs_dict_get(mailinfo, "body");
2757 FILE *f;
2758 int status;
2759 int fds[2];
2760 pid_t pid;
2761
2762 if (pipe(fds) == -1) return -1;
2763 pid = vfork();
2764 if (pid == -1) return -1;
2765 else if (pid == 0) {
2766 dup2(fds[0], 0);
2767 close(fds[0]);
2768 close(fds[1]);
2769 execl("/usr/sbin/sendmail", "sendmail", "-t", (char *) NULL);
2770 _exit(1);
2771 }
2772 close(fds[0]);
2773 if ((f = fdopen(fds[1], "w")) == NULL) {
2774 close(fds[1]);
2775 return -1;
2776 }
2777 fprintf(f, "%s\n", msg);
2778 fclose(f);
2779 if (waitpid(pid, &status, 0) == -1) return -1;
2780 return status;
2781 }
2782
2783 const char
2784 *user = xs_dict_get(srv_config, "smtp_username"),
2785 *pass = xs_dict_get(srv_config, "smtp_password"),
2786 *from = xs_dict_get(mailinfo, "from"),
2787 *to = xs_dict_get(mailinfo, "to"),
2788 *body = xs_dict_get(mailinfo, "body");
2789
2790 if (url == NULL || *url == '\0')
2791 url = "smtp://localhost";
2792
2793 int smtp_port = parse_port(url, NULL);
2794
2795 return xs_smtp_request(url, user, pass, from, to, body, smtp_port == 465 || smtp_port == 587);
2796}
2797
2798
2799void process_user_queue_item(snac *user, xs_dict *q_item)
2800/* processes an item from the user queue */
2801{
2802 const char *type;
2803 int queue_retry_max = xs_number_get(xs_dict_get(srv_config, "queue_retry_max"));
2804
2805 if ((type = xs_dict_get(q_item, "type")) == NULL)
2806 type = "output";
2807
2808 if (strcmp(type, "message") == 0) {
2809 const xs_dict *msg = xs_dict_get(q_item, "message");
2810 xs *rcpts = recipient_list(user, msg, 1);
2811 xs_set inboxes;
2812 const xs_str *actor;
2813
2814 xs_set_init(&inboxes);
2815
2816 /* add this shared inbox first */
2817 xs *this_shared_inbox = xs_fmt("%s/shared-inbox", srv_baseurl);
2818 xs_set_add(&inboxes, this_shared_inbox);
2819 enqueue_output(user, msg, this_shared_inbox, 0, 0);
2820
2821 /* iterate the recipients */
2822 xs_list_foreach(rcpts, actor) {
2823 /* local users were served by this_shared_inbox */
2824 if (!xs_startswith(actor, srv_baseurl)) {
2825 xs *inbox = get_actor_inbox(actor, 1);
2826
2827 if (inbox != NULL) {
2828 /* add to the set and, if it's not there, send message */
2829 if (xs_set_add(&inboxes, inbox) == 1)
2830 enqueue_output(user, msg, inbox, 0, 0);
2831 }
2832 else
2833 snac_log(user, xs_fmt("cannot find inbox for %s", actor));
2834 }
2835 }
2836
2837 /* if it's a public note or question, send to the collected inboxes */
2838 if (xs_match(xs_dict_get_def(msg, "type", ""), "Create|Update") && is_msg_public(msg)) {
2839 if (xs_type(xs_dict_get(srv_config, "disable_inbox_collection")) != XSTYPE_TRUE) {
2840 xs *shibx = inbox_list();
2841 const xs_str *inbox;
2842
2843 xs_list_foreach(shibx, inbox) {
2844 if (xs_set_add(&inboxes, inbox) == 1)
2845 enqueue_output(user, msg, inbox, 0, 0);
2846 }
2847 }
2848 }
2849
2850 xs_set_free(&inboxes);
2851
2852 /* relay this note */
2853 if (is_msg_public(msg) && strcmp(user->uid, "relay") != 0) { /* avoid loops */
2854 snac relay;
2855 if (user_open(&relay, "relay")) {
2856 /* a 'relay' user exists */
2857 const char *type = xs_dict_get(msg, "type");
2858
2859 if (xs_is_string(type) && strcmp(type, "Create") == 0) {
2860 const xs_val *object = xs_dict_get(msg, "object");
2861
2862 if (xs_is_dict(object)) {
2863 object = xs_dict_get(object, "id");
2864
2865 snac_debug(&relay, 1, xs_fmt("relaying message %s", object));
2866
2867 xs *boost = msg_admiration(&relay, object, "Announce");
2868 enqueue_message(&relay, boost);
2869 }
2870 }
2871
2872 user_free(&relay);
2873 }
2874 }
2875 }
2876 else
2877 if (strcmp(type, "input") == 0) {
2878 /* process the message */
2879 const xs_dict *msg = xs_dict_get(q_item, "message");
2880 const xs_dict *req = xs_dict_get(q_item, "req");
2881 int retries = xs_number_get(xs_dict_get(q_item, "retries"));
2882
2883 if (xs_is_null(msg))
2884 return;
2885
2886 if (!process_input_message(user, msg, req)) {
2887 if (retries > queue_retry_max)
2888 snac_log(user, xs_fmt("input giving up"));
2889 else {
2890 /* reenqueue */
2891 enqueue_input(user, msg, req, retries + 1);
2892 snac_log(user, xs_fmt("input requeue #%d", retries + 1));
2893 }
2894 }
2895 }
2896 else
2897 if (strcmp(type, "close_question") == 0) {
2898 /* the time for this question has ended */
2899 const char *id = xs_dict_get(q_item, "message");
2900
2901 if (!xs_is_null(id))
2902 update_question(user, id);
2903 }
2904 else
2905 if (strcmp(type, "object_request") == 0) {
2906 const char *id = xs_dict_get(q_item, "message");
2907
2908 if (!xs_is_null(id)) {
2909 int status;
2910 xs *data = NULL;
2911
2912 status = activitypub_request(user, id, &data);
2913
2914 if (valid_status(status))
2915 object_add_ow(id, data);
2916
2917 snac_debug(user, 1, xs_fmt("object_request %s %d", id, status));
2918 }
2919 }
2920 else
2921 if (strcmp(type, "verify_links") == 0) {
2922 verify_links(user);
2923 }
2924 else
2925 if (strcmp(type, "actor_refresh") == 0) {
2926 const char *actor = xs_dict_get(q_item, "actor");
2927 double mtime = object_mtime(actor);
2928
2929 /* only refresh if it was refreshed more than an hour ago */
2930 if (mtime + 3600.0 < (double) time(NULL)) {
2931 xs *actor_o = NULL;
2932 int status;
2933
2934 if (valid_status((status = activitypub_request(user, actor, &actor_o))))
2935 actor_add(actor, actor_o);
2936 else
2937 object_touch(actor);
2938
2939 snac_log(user, xs_fmt("actor_refresh %s %d", actor, status));
2940 }
2941 }
2942 else
2943 if (strcmp(type, "notify_webhook") == 0) {
2944 const char *webhook = xs_dict_get(user->config, "notify_webhook");
2945
2946 if (xs_is_string(webhook) && xs_match(webhook, "https://*|http://*")) { /** **/
2947 const xs_dict *msg = xs_dict_get(q_item, "message");
2948 int retries = xs_number_get(xs_dict_get(q_item, "retries"));
2949
2950 xs *hdrs = xs_dict_new();
2951
2952 hdrs = xs_dict_set(hdrs, "content-type", "application/json");
2953 hdrs = xs_dict_set(hdrs, "user-agent", USER_AGENT);
2954
2955 xs *body = xs_json_dumps(msg, 4);
2956
2957 int status;
2958 xs *rsp = xs_http_request("POST", webhook, hdrs, body, strlen(body), &status, NULL, NULL, 0);
2959
2960 snac_debug(user, 0, xs_fmt("webhook post %s %d", webhook, status));
2961
2962 if (!valid_status(status)) {
2963 retries++;
2964
2965 if (retries > queue_retry_max)
2966 snac_debug(user, 0, xs_fmt("webhook post giving up %s", webhook));
2967 else {
2968 snac_debug(user, 0, xs_fmt("webhook post requeue %s %d", webhook, retries));
2969
2970 enqueue_notify_webhook(user, msg, retries);
2971 }
2972 }
2973 }
2974 }
2975 else
2976 if (strcmp(type, "collect_replies") == 0) {
2977 const char *post = xs_dict_get(q_item, "message");
2978
2979 collect_replies(user, post);
2980 }
2981 else
2982 snac_log(user, xs_fmt("unexpected user q_item type '%s'", type));
2983}
2984
2985
2986int process_user_queue(snac *snac)
2987/* processes a user's queue */
2988{
2989 int cnt = 0;
2990 xs *list = user_queue(snac);
2991
2992 xs_list *p = list;
2993 const xs_str *fn;
2994
2995 while (xs_list_iter(&p, &fn)) {
2996 xs *q_item = dequeue(fn);
2997
2998 if (q_item == NULL)
2999 continue;
3000
3001 process_user_queue_item(snac, q_item);
3002 cnt++;
3003 }
3004
3005 scheduled_process(snac);
3006
3007 return cnt;
3008}
3009
3010
3011xs_str *str_status(int status)
3012{
3013 return xs_fmt("%d %s", status, status < 0 ? xs_curl_strerr(status) : http_status_text(status));
3014}
3015
3016
3017void process_queue_item(xs_dict *q_item)
3018/* processes an item from the global queue */
3019{
3020 const char *type = xs_dict_get(q_item, "type");
3021 int queue_retry_max = xs_number_get(xs_dict_get(srv_config, "queue_retry_max"));
3022
3023 if (strcmp(type, "output") == 0) {
3024 int status;
3025 const xs_str *inbox = xs_dict_get(q_item, "inbox");
3026 const xs_str *keyid = xs_dict_get(q_item, "keyid");
3027 const xs_str *seckey = xs_dict_get(q_item, "seckey");
3028 const xs_dict *msg = xs_dict_get(q_item, "message");
3029 int retries = xs_number_get(xs_dict_get(q_item, "retries"));
3030 int p_status = xs_number_get(xs_dict_get(q_item, "p_status"));
3031 xs *payload = NULL;
3032 int p_size = 0;
3033 int timeout = 0;
3034
3035 if (xs_is_null(inbox) || xs_is_null(msg) || xs_is_null(keyid) || xs_is_null(seckey)) {
3036 srv_log(xs_fmt("output message error: missing fields"));
3037 return;
3038 }
3039
3040 if (is_instance_blocked(inbox)) {
3041 srv_debug(0, xs_fmt("discarded output message to blocked instance %s", inbox));
3042 return;
3043 }
3044
3045 /* deliver (if previous error status was a timeout, try now longer) */
3046 if (p_status == 599)
3047 timeout = xs_number_get(xs_dict_get_def(srv_config, "queue_timeout_2", "8"));
3048 else
3049 timeout = xs_number_get(xs_dict_get_def(srv_config, "queue_timeout", "6"));
3050
3051 if (timeout == 0)
3052 timeout = 6;
3053
3054 status = send_to_inbox_raw(keyid, seckey, inbox, msg, &payload, &p_size, timeout);
3055
3056 if (payload) {
3057 if (p_size > 64) {
3058 /* trim the message */
3059 payload[64] = '\0';
3060 payload = xs_str_cat(payload, "...");
3061 }
3062
3063 /* strip ugly control characters */
3064 payload = xs_replace_i(payload, "\n", "");
3065 payload = xs_replace_i(payload, "\r", "");
3066
3067 if (*payload)
3068 payload = xs_str_wrap_i(" [", payload, "]");
3069 }
3070 else
3071 payload = xs_str_new(NULL);
3072
3073 xs *s_status = str_status(status);
3074
3075 srv_log(xs_fmt("output message: sent to inbox %s (%s)%s", inbox, s_status, payload));
3076
3077 if (!valid_status(status)) {
3078 retries++;
3079
3080 /* if it's not the first time it fails with a timeout,
3081 penalize the server by skipping one retry */
3082 if (p_status == status && status == HTTP_STATUS_CLIENT_CLOSED_REQUEST)
3083 retries++;
3084
3085 /* error sending; requeue? */
3086 if (status == HTTP_STATUS_BAD_REQUEST
3087 || status == HTTP_STATUS_NOT_FOUND
3088 || status == HTTP_STATUS_METHOD_NOT_ALLOWED
3089 || status == HTTP_STATUS_GONE
3090 || status == HTTP_STATUS_UNPROCESSABLE_CONTENT
3091 || status < 0)
3092 /* explicit error: discard */
3093 srv_log(xs_fmt("output message: error %s (%s)", inbox, s_status));
3094 else
3095 if (retries > queue_retry_max)
3096 srv_log(xs_fmt("output message: giving up %s (%s)", inbox, s_status));
3097 else {
3098 /* requeue */
3099 enqueue_output_raw(keyid, seckey, msg, inbox, retries, status);
3100 srv_log(xs_fmt("output message: requeue %s #%d", inbox, retries));
3101 }
3102 }
3103 }
3104 else
3105 if (strcmp(type, "email") == 0) {
3106 /* send this email */
3107 const xs_dict *msg = xs_dict_get(q_item, "message");
3108 int retries = xs_number_get(xs_dict_get(q_item, "retries"));
3109
3110 if (!send_email(msg))
3111 srv_debug(1, xs_fmt("email message sent"));
3112 else {
3113 retries++;
3114
3115 if (retries > queue_retry_max)
3116 srv_log(xs_fmt("email giving up (errno: %d)", errno));
3117 else {
3118 /* requeue */
3119 srv_log(xs_fmt(
3120 "email requeue #%d (errno: %d)", retries, errno));
3121
3122 enqueue_email(msg, retries);
3123 }
3124 }
3125 }
3126 else
3127 if (strcmp(type, "telegram") == 0) {
3128 /* send this via telegram */
3129 const char *bot = xs_dict_get(q_item, "bot");
3130 const char *msg = xs_dict_get(q_item, "message");
3131 xs *chat_id = xs_dup(xs_dict_get(q_item, "chat_id"));
3132 int status = 0;
3133
3134 /* chat_id must start with a - */
3135 if (!xs_startswith(chat_id, "-"))
3136 chat_id = xs_str_wrap_i("-", chat_id, NULL);
3137
3138 xs *url = xs_fmt("https:/" "/api.telegram.org/bot%s/sendMessage", bot);
3139 xs *body = xs_fmt("{\"chat_id\":%s,\"text\":\"%s\"}", chat_id, msg);
3140
3141 xs *headers = xs_dict_new();
3142 headers = xs_dict_append(headers, "content-type", "application/json");
3143
3144 xs *rsp = xs_http_request("POST", url, headers,
3145 body, strlen(body), &status, NULL, NULL, 0);
3146 rsp = xs_free(rsp);
3147
3148 srv_debug(0, xs_fmt("telegram post %d", status));
3149 }
3150 else
3151 if (strcmp(type, "ntfy") == 0) {
3152 /* send this via ntfy */
3153 const char *ntfy_server = xs_dict_get(q_item, "ntfy_server");
3154 const char *msg = xs_dict_get(q_item, "message");
3155 const char *ntfy_token = xs_dict_get(q_item, "ntfy_token");
3156 int status = 0;
3157
3158 xs *url = xs_fmt("%s", ntfy_server);
3159 xs *body = xs_fmt("%s", msg);
3160
3161 xs *headers = xs_dict_new();
3162 headers = xs_dict_append(headers, "content-type", "text/plain");
3163 // Append the Authorization header only if ntfy_token is not NULL
3164 if (ntfy_token != NULL) {
3165 headers = xs_dict_append(headers, "Authorization", xs_fmt("Bearer %s", ntfy_token));
3166 }
3167
3168 xs *rsp = xs_http_request("POST", url, headers,
3169 body, strlen(body), &status, NULL, NULL, 0);
3170 rsp = xs_free(rsp);
3171
3172 srv_debug(0, xs_fmt("ntfy post %d", status));
3173 }
3174 else
3175 if (strcmp(type, "purge") == 0) {
3176 srv_log(xs_dup("purge start"));
3177
3178 purge_all();
3179
3180 srv_log(xs_dup("purge end"));
3181 }
3182 else
3183 if (strcmp(type, "input") == 0) {
3184 const xs_dict *msg = xs_dict_get(q_item, "message");
3185 const xs_dict *req = xs_dict_get(q_item, "req");
3186 int retries = xs_number_get(xs_dict_get(q_item, "retries"));
3187
3188 /* do some instance-level checks */
3189 int r = process_input_message(NULL, msg, req);
3190
3191 if (r == 0) {
3192 /* transient error? retry */
3193 if (retries > queue_retry_max)
3194 srv_log(xs_fmt("shared input giving up"));
3195 else {
3196 /* reenqueue */
3197 enqueue_shared_input(msg, req, retries + 1);
3198 srv_log(xs_fmt("shared input requeue #%d", retries + 1));
3199 }
3200 }
3201 else
3202 if (r == 2) {
3203 /* redistribute the input message to all users */
3204 const char *ntid = xs_dict_get(q_item, "ntid");
3205 xs *tmpfn = xs_fmt("%s/tmp/%s.json", srv_basedir, ntid);
3206 FILE *f;
3207
3208 if ((f = fopen(tmpfn, "w")) != NULL) {
3209 xs_json_dump(q_item, 4, f);
3210 fclose(f);
3211 }
3212
3213 xs *users = user_list();
3214 xs_list *p = users;
3215 const char *v;
3216 int cnt = 0;
3217
3218 while (xs_list_iter(&p, &v)) {
3219 snac user;
3220
3221 if (user_open(&user, v)) {
3222 int rsn = is_msg_for_me(&user, msg);
3223 if (rsn) {
3224 xs *fn = xs_fmt("%s/queue/%s.json", user.basedir, ntid);
3225
3226 snac_debug(&user, 1,
3227 xs_fmt("enqueue_input (from shared inbox) %s [%d]", xs_dict_get(msg, "id"), rsn));
3228
3229 if (link(tmpfn, fn) < 0)
3230 srv_log(xs_fmt("link(%s, %s) error", tmpfn, fn));
3231
3232 cnt++;
3233 }
3234
3235 user_free(&user);
3236 }
3237 }
3238
3239 unlink(tmpfn);
3240
3241 if (cnt == 0) {
3242 srv_debug(1, xs_fmt("no valid recipients for %s", xs_dict_get(msg, "id")));
3243 }
3244 }
3245 }
3246 else
3247 if (strcmp(type, "webmention") == 0) {
3248 const xs_dict *msg = xs_dict_get(q_item, "message");
3249 const char *source = xs_dict_get(msg, "id");
3250 const char *content = xs_dict_get(msg, "content");
3251
3252 if (xs_is_string(source) && xs_is_string(content)) {
3253 xs *links = xs_regex_select(content, "\"https?:/" "/[^\"]+");
3254 const char *link;
3255
3256 xs_list_foreach(links, link) {
3257 xs *target = xs_strip_chars_i(xs_dup(link), "\"");
3258
3259 int r = xs_webmention_send(source, target, USER_AGENT);
3260
3261 srv_debug(1, xs_fmt("webmention source=%s target=%s %d", source, target, r));
3262 }
3263 }
3264 }
3265 else
3266 if (strcmp(type, "rss_hashtag_poll") == 0) {
3267 rss_poll_hashtags();
3268 }
3269 else
3270 srv_log(xs_fmt("unexpected q_item type '%s'", type));
3271}
3272
3273
3274int process_queue(void)
3275/* processes the global queue */
3276{
3277 int cnt = 0;
3278 xs *list = queue();
3279
3280 xs_list *p = list;
3281 const xs_str *fn;
3282
3283 while (xs_list_iter(&p, &fn)) {
3284 xs *q_item = dequeue(fn);
3285
3286 if (q_item != NULL) {
3287 job_post(q_item, 0);
3288 cnt++;
3289 }
3290 }
3291
3292 return cnt;
3293}
3294
3295
3296/** account migration **/
3297
3298int migrate_account(snac *user)
3299/* migrates this account to a new one (stored in the 'alias' user field) */
3300{
3301 const char *new_account = xs_dict_get(user->config, "alias");
3302
3303 if (xs_type(new_account) != XSTYPE_STRING) {
3304 snac_log(user, xs_fmt("Cannot migrate: alias (destination account) not set"));
3305 return 1;
3306 }
3307
3308 xs *new_actor = NULL;
3309 int status;
3310
3311 if (!valid_status(status = activitypub_request(user, new_account, &new_actor))) {
3312 snac_log(user, xs_fmt("Cannot migrate: error requesting actor %s %d", new_account, status));
3313 return 1;
3314 }
3315
3316 actor_add(new_account, new_actor);
3317
3318 const char *loaka = xs_dict_get(new_actor, "alsoKnownAs");
3319
3320 if (xs_type(loaka) != XSTYPE_LIST) {
3321 snac_log(user, xs_fmt("Cannot migrate: destination account doesn't have any aliases"));
3322 return 1;
3323 }
3324
3325 if (xs_list_in(loaka, user->actor) == -1) {
3326 snac_log(user, xs_fmt("Cannot migrate: destination account doesn't have this one as an alias"));
3327 return 1;
3328 }
3329
3330 xs *move = msg_move(user, new_account);
3331 xs *fwers = follower_list(user);
3332
3333 const char *actor;
3334 xs_list_foreach(fwers, actor) {
3335 /* get the actor inbox, excluding the shared one */
3336 xs *inbox = get_actor_inbox(actor, 0);
3337
3338 if (xs_is_null(inbox))
3339 snac_log(user, xs_fmt("migrate_account: cannot get inbox for actor %s", actor));
3340 else
3341 enqueue_output(user, move, inbox, 0, 0);
3342 }
3343
3344 return 0;
3345}
3346
3347
3348/** HTTP handlers */
3349
3350int activitypub_get_handler(const xs_dict *req, const char *q_path,
3351 char **body, int *b_size, char **ctype)
3352{
3353 int status = HTTP_STATUS_OK;
3354 const char *accept = xs_dict_get(req, "accept");
3355 snac snac;
3356 xs *msg = NULL;
3357
3358 if (accept == NULL)
3359 return 0;
3360
3361 if (xs_str_in(accept, "application/activity+json") == -1 &&
3362 xs_str_in(accept, "application/ld+json") == -1)
3363 return 0;
3364
3365 xs *l = xs_split_n(q_path, "/", 2);
3366 const char *uid;
3367 const char *p_path;
3368
3369 uid = xs_list_get(l, 1);
3370 if (!user_open(&snac, uid)) {
3371 /* invalid user */
3372 srv_debug(1, xs_fmt("activitypub_get_handler bad user %s", uid));
3373 return HTTP_STATUS_NOT_FOUND;
3374 }
3375
3376 p_path = xs_list_get(l, 2);
3377
3378 *ctype = "application/activity+json";
3379
3380 int show_contact_metrics = xs_is_true(xs_dict_get(snac.config, "show_contact_metrics"));
3381
3382 if (p_path == NULL) {
3383 /* if there was no component after the user, it's an actor request */
3384 msg = msg_actor(&snac);
3385 *ctype = "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"";
3386
3387 const char *ua = xs_dict_get(req, "user-agent");
3388
3389 snac_debug(&snac, 0, xs_fmt("serving actor [%s]", ua ? ua : "No UA"));
3390 }
3391 else
3392 if (strcmp(p_path, "outbox") == 0 || strcmp(p_path, "featured") == 0) {
3393 xs *id = xs_fmt("%s/%s", snac.actor, p_path);
3394 xs *list = xs_list_new();
3395 const char *v;
3396 int cnt = xs_number_get(xs_dict_get_def(srv_config, "max_public_entries", "20"));
3397
3398 /* get the public outbox or the pinned list */
3399 xs *elems = *p_path == 'o' ? timeline_simple_list(&snac, "public", 0, cnt, NULL) : pinned_list(&snac);
3400
3401 xs_list_foreach(elems, v) {
3402 xs *i = NULL;
3403
3404 if (valid_status(object_get_by_md5(v, &i))) {
3405 const char *type = xs_dict_get(i, "type");
3406 const char *id = xs_dict_get(i, "id");
3407
3408 if (type && id && strcmp(type, "Note") == 0 && xs_startswith(id, snac.actor)) {
3409 xs *c_msg = msg_create(&snac, i);
3410 list = xs_list_append(list, c_msg);
3411 }
3412 }
3413 }
3414
3415 /* replace the 'orderedItems' with the latest posts */
3416 msg = msg_collection(&snac, id, xs_list_len(list));
3417 msg = xs_dict_set(msg, "orderedItems", list);
3418 }
3419 else
3420 if (strcmp(p_path, "followers") == 0) {
3421 int total = 0;
3422
3423 if (show_contact_metrics) {
3424 total = follower_list_len(&snac);
3425 }
3426
3427 xs *id = xs_fmt("%s/%s", snac.actor, p_path);
3428 msg = msg_collection(&snac, id, total);
3429 }
3430 else
3431 if (strcmp(p_path, "following") == 0) {
3432 int total = 0;
3433
3434 if (show_contact_metrics) {
3435 total = following_list_len(&snac);
3436 }
3437
3438 xs *id = xs_fmt("%s/%s", snac.actor, p_path);
3439 msg = msg_collection(&snac, id, total);
3440 }
3441 else
3442 if (xs_startswith(p_path, "p/")) {
3443 xs *id = xs_fmt("%s/%s", snac.actor, p_path);
3444
3445 status = object_get(id, &msg);
3446
3447 /* don't return non-public objects */
3448 if (valid_status(status) && !is_msg_public(msg))
3449 status = HTTP_STATUS_NOT_FOUND;
3450 }
3451 else
3452 if (xs_startswith(p_path, "r/")) {
3453 /* replies to a post */
3454 xs *s = xs_dup(p_path);
3455 s[0] = 'p';
3456
3457 xs *id = xs_fmt("%s/%s", snac.actor, s);
3458
3459 xs *obj = NULL;
3460 status = object_get(id, &obj);
3461
3462 /* don't return non-public objects */
3463 if (!valid_status(status))
3464 status = HTTP_STATUS_NOT_FOUND;
3465 else
3466 if (!is_msg_public(obj))
3467 status = HTTP_STATUS_NOT_FOUND;
3468 else
3469 msg = msg_replies(&snac, id, 1);
3470 }
3471 else
3472 status = HTTP_STATUS_NOT_FOUND;
3473
3474 if (status == HTTP_STATUS_OK && msg != NULL) {
3475 *body = xs_json_dumps(msg, 4);
3476 *b_size = strlen(*body);
3477 }
3478
3479 snac_debug(&snac, 1, xs_fmt("activitypub_get_handler serving %s %d", q_path, status));
3480
3481 user_free(&snac);
3482
3483 return status;
3484}
3485
3486
3487int activitypub_post_handler(const xs_dict *req, const char *q_path,
3488 char *payload, int p_size,
3489 char **body, int *b_size, char **ctype)
3490/* processes an input message */
3491{
3492 (void)b_size;
3493
3494 int status = HTTP_STATUS_ACCEPTED;
3495 const char *i_ctype = xs_dict_get(req, "content-type");
3496 snac snac;
3497 const char *v;
3498
3499 if (i_ctype == NULL) {
3500 *body = xs_str_new("no content-type");
3501 *ctype = "text/plain";
3502 return HTTP_STATUS_BAD_REQUEST;
3503 }
3504
3505 if (xs_is_null(payload)) {
3506 *body = xs_str_new("no payload");
3507 *ctype = "text/plain";
3508 return HTTP_STATUS_BAD_REQUEST;
3509 }
3510
3511 if (xs_str_in(i_ctype, "application/activity+json") == -1 &&
3512 xs_str_in(i_ctype, "application/ld+json") == -1)
3513 return 0;
3514
3515 /* decode the message */
3516 xs *msg = xs_json_loads(payload);
3517 const char *id = xs_dict_get(msg, "id");
3518
3519 if (msg == NULL) {
3520 srv_log(xs_fmt("activitypub_post_handler JSON error %s", q_path));
3521
3522 srv_archive_error("activitypub_post_handler", "JSON error", req, payload);
3523
3524 *body = xs_str_new("JSON error");
3525 *ctype = "text/plain";
3526 return HTTP_STATUS_BAD_REQUEST;
3527 }
3528
3529 if (id && is_instance_blocked(id)) {
3530 srv_debug(1, xs_fmt("full instance block for %s", id));
3531
3532 *body = xs_str_new("blocked");
3533 *ctype = "text/plain";
3534 return HTTP_STATUS_FORBIDDEN;
3535 }
3536
3537 /* get the user and path */
3538 xs *l = xs_split_n(q_path, "/", 2);
3539
3540 if (xs_list_len(l) == 2 && strcmp(xs_list_get(l, 1), "shared-inbox") == 0) {
3541 enqueue_shared_input(msg, req, 0);
3542 return HTTP_STATUS_ACCEPTED;
3543 }
3544
3545 if (xs_list_len(l) != 3 || strcmp(xs_list_get(l, 2), "inbox") != 0) {
3546 /* strange q_path */
3547 srv_debug(1, xs_fmt("activitypub_post_handler unsupported path %s", q_path));
3548 return HTTP_STATUS_NOT_FOUND;
3549 }
3550
3551 const char *uid = xs_list_get(l, 1);
3552 if (!user_open(&snac, uid)) {
3553 /* invalid user */
3554 srv_debug(1, xs_fmt("activitypub_post_handler bad user %s", uid));
3555 return HTTP_STATUS_NOT_FOUND;
3556 }
3557
3558 /* if it has a digest, check it now, because
3559 later the payload won't be exactly the same */
3560 if ((v = xs_dict_get(req, "digest")) != NULL) {
3561 xs *s1 = xs_sha256_base64(payload, p_size);
3562 xs *s2 = xs_fmt("SHA-256=%s", s1);
3563
3564 if (strcmp(s2, v) != 0) {
3565 srv_log(xs_fmt("digest check FAILED"));
3566
3567 *body = xs_str_new("bad digest");
3568 *ctype = "text/plain";
3569 status = HTTP_STATUS_BAD_REQUEST;
3570 }
3571 }
3572
3573 /* if the message is from a muted actor, reject it right now */
3574 if (!xs_is_null(v = xs_dict_get(msg, "actor")) && *v) {
3575 if (is_muted(&snac, v)) {
3576 snac_log(&snac, xs_fmt("rejected message from MUTEd actor %s", v));
3577
3578 *body = xs_str_new("rejected");
3579 *ctype = "text/plain";
3580 status = HTTP_STATUS_FORBIDDEN;
3581 }
3582 }
3583
3584 if (valid_status(status)) {
3585 enqueue_input(&snac, msg, req, 0);
3586 *ctype = "application/activity+json";
3587 }
3588
3589 user_free(&snac);
3590
3591 return status;
3592}