activitypub.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 - 2023 grunfink / MIT license */
  3. #include "xs.h"
  4. #include "xs_json.h"
  5. #include "xs_curl.h"
  6. #include "xs_mime.h"
  7. #include "xs_openssl.h"
  8. #include "xs_regex.h"
  9. #include "xs_time.h"
  10. #include "xs_set.h"
  11. #include "snac.h"
  12. #include <sys/wait.h>
  13. const char *public_address = "https:/" "/www.w3.org/ns/activitystreams#Public";
  14. /* susie.png */
  15. const char *susie =
  16. "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  17. "CEkxzAAAAUUlEQVQoz43R0QkAMQwCUDdw/y3dwE"
  18. "vsvzlL4X1IoQkAisKmwfAFT3RgJHbQezpSRoXEq"
  19. "eqCL9BJBf7h3QbOCCxV5EVWMEMwG7K1/WODtlvx"
  20. "AYTtEsDU9F34AAAAAElFTkSuQmCC";
  21. const char *susie_cool =
  22. "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  23. "CEkxzAAAAV0lEQVQoz43RwQ3AMAwCQDZg/y3ZgN"
  24. "qo3+JaedwDOUQBQFHYaTB8wTM6sGl2cMPu+DFzn"
  25. "+ZcgN7wF7ZVihXkfSlWIVzIA6dbQzaygllpNuTX"
  26. "ZmmFNlvxADX1+o0cUPMbAAAAAElFTkSuQmCC";
  27. const char *susie_muertos =
  28. "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  29. "CEkxzAAAAV0lEQVQoz4XQsQ0AMQxCUW/A/lv+DT"
  30. "ic6zGRolekIMyMELNp8PiCEw6Q4w4NoAt53IH5m"
  31. "xXksrZYgZwJrIox+Z8vJAfe2lCxG6AK7eKkWcEb"
  32. "QHbF617xAQatAAD7jJHUAAAAAElFTkSuQmCC";
  33. const char *default_avatar_base64(void)
  34. /* returns the default avatar in base64 */
  35. {
  36. time_t t = time(NULL);
  37. struct tm tm;
  38. const char *p = susie;
  39. gmtime_r(&t, &tm);
  40. if (tm.tm_mon == 10 && tm.tm_mday == 2)
  41. p = susie_muertos;
  42. else
  43. if (tm.tm_wday == 0 || tm.tm_wday == 6)
  44. p = susie_cool;
  45. return p;
  46. }
  47. int activitypub_request(snac *snac, const char *url, xs_dict **data)
  48. /* request an object */
  49. {
  50. int status;
  51. xs *response = NULL;
  52. xs *payload = NULL;
  53. int p_size;
  54. char *ctype;
  55. /* get from the net */
  56. response = http_signed_request(snac, "GET", url,
  57. NULL, NULL, 0, &status, &payload, &p_size, 0);
  58. if (status == 0 || (status >= 500 && status <= 599)) {
  59. /* I found an instance running Misskey that returned
  60. 500 on signed messages but returned the object
  61. perfectly without signing (?), so why not try */
  62. xs_free(response);
  63. xs *hdrs = xs_dict_new();
  64. hdrs = xs_dict_append(hdrs, "accept", "application/activity+json");
  65. hdrs = xs_dict_append(hdrs, "user-agent", USER_AGENT);
  66. response = xs_http_request("GET", url, hdrs,
  67. NULL, 0, &status, &payload, &p_size, 0);
  68. }
  69. if (valid_status(status)) {
  70. /* ensure it's ActivityPub data */
  71. ctype = xs_dict_get(response, "content-type");
  72. if (xs_str_in(ctype, "application/activity+json") != -1 ||
  73. xs_str_in(ctype, "application/ld+json") != -1)
  74. *data = xs_json_loads(payload);
  75. else
  76. status = 500;
  77. }
  78. if (!valid_status(status))
  79. *data = NULL;
  80. return status;
  81. }
  82. int actor_request(snac *snac, const char *actor, xs_dict **data)
  83. /* request an actor */
  84. {
  85. int status, status2;
  86. xs *payload = NULL;
  87. if (data)
  88. *data = NULL;
  89. /* get from disk first */
  90. status = actor_get(snac, actor, data);
  91. if (status != 200) {
  92. /* actor data non-existent or stale: get from the net */
  93. status2 = activitypub_request(snac, actor, &payload);
  94. if (valid_status(status2)) {
  95. /* renew data */
  96. status = actor_add(actor, payload);
  97. if (data != NULL) {
  98. *data = payload;
  99. payload = NULL;
  100. }
  101. }
  102. }
  103. /* collect the (presumed) shared inbox in this actor */
  104. if (xs_type(xs_dict_get(srv_config, "disable_inbox_collection")) != XSTYPE_TRUE) {
  105. if (valid_status(status) && data && *data)
  106. inbox_add_by_actor(*data);
  107. }
  108. else
  109. srv_log(xs_fmt("NOT collected"));
  110. return status;
  111. }
  112. int timeline_request(snac *snac, char **id, d_char **wrk)
  113. /* ensures that an entry and its ancestors are in the timeline */
  114. {
  115. int status = 0;
  116. if (!xs_is_null(*id)) {
  117. /* is the admired object already there? */
  118. if (!object_here(*id)) {
  119. xs *object = NULL;
  120. /* no; download it */
  121. status = activitypub_request(snac, *id, &object);
  122. if (valid_status(status)) {
  123. char *type = xs_dict_get(object, "type");
  124. /* get the id again from the object, as it may be different */
  125. char *nid = xs_dict_get(object, "id");
  126. if (wrk && strcmp(nid, *id) != 0) {
  127. snac_debug(snac, 1,
  128. xs_fmt("timeline_request canonical id for %s is %s", *id, nid));
  129. *wrk = xs_dup(nid);
  130. *id = *wrk;
  131. }
  132. if (!xs_is_null(type) && strcmp(type, "Note") == 0) {
  133. char *actor = xs_dict_get(object, "attributedTo");
  134. /* request (and drop) the actor for this entry */
  135. if (!xs_is_null(actor))
  136. actor_request(snac, actor, NULL);
  137. /* does it have an ancestor? */
  138. char *in_reply_to = xs_dict_get(object, "inReplyTo");
  139. /* recurse! */
  140. timeline_request(snac, &in_reply_to, NULL);
  141. /* finally store */
  142. timeline_add(snac, *id, object);
  143. }
  144. }
  145. }
  146. }
  147. return status;
  148. }
  149. int send_to_inbox_raw(const char *keyid, const char *seckey,
  150. const xs_str *inbox, const xs_dict *msg,
  151. xs_val **payload, int *p_size, int timeout)
  152. /* sends a message to an Inbox */
  153. {
  154. int status;
  155. xs_dict *response;
  156. xs *j_msg = xs_json_dumps_pp((xs_dict *)msg, 4);
  157. response = http_signed_request_raw(keyid, seckey, "POST", inbox,
  158. NULL, j_msg, strlen(j_msg), &status, payload, p_size, timeout);
  159. xs_free(response);
  160. return status;
  161. }
  162. int send_to_inbox(snac *snac, const xs_str *inbox, const xs_dict *msg,
  163. xs_val **payload, int *p_size, int timeout)
  164. /* sends a message to an Inbox */
  165. {
  166. char *seckey = xs_dict_get(snac->key, "secret");
  167. return send_to_inbox_raw(snac->actor, seckey, inbox, msg, payload, p_size, timeout);
  168. }
  169. d_char *get_actor_inbox(snac *snac, const char *actor)
  170. /* gets an actor's inbox */
  171. {
  172. xs *data = NULL;
  173. char *v = NULL;
  174. if (valid_status(actor_request(snac, actor, &data))) {
  175. /* try first endpoints/sharedInbox */
  176. if ((v = xs_dict_get(data, "endpoints")))
  177. v = xs_dict_get(v, "sharedInbox");
  178. /* try then the regular inbox */
  179. if (xs_is_null(v))
  180. v = xs_dict_get(data, "inbox");
  181. }
  182. return xs_is_null(v) ? NULL : xs_dup(v);
  183. }
  184. int send_to_actor(snac *snac, char *actor, char *msg, d_char **payload, int *p_size, int timeout)
  185. /* sends a message to an actor */
  186. {
  187. int status = 400;
  188. xs *inbox = get_actor_inbox(snac, actor);
  189. if (!xs_is_null(inbox))
  190. status = send_to_inbox(snac, inbox, msg, payload, p_size, timeout);
  191. return status;
  192. }
  193. xs_list *recipient_list(snac *snac, const xs_dict *msg, int expand_public)
  194. /* returns the list of recipients for a message */
  195. {
  196. char *to = xs_dict_get(msg, "to");
  197. char *cc = xs_dict_get(msg, "cc");
  198. xs_set rcpts;
  199. int n;
  200. xs_set_init(&rcpts);
  201. char *lists[] = { to, cc, NULL };
  202. for (n = 0; lists[n]; n++) {
  203. char *l = lists[n];
  204. char *v;
  205. xs *tl = NULL;
  206. /* if it's a string, create a list with only one element */
  207. if (xs_type(l) == XSTYPE_STRING) {
  208. tl = xs_list_new();
  209. tl = xs_list_append(tl, l);
  210. l = tl;
  211. }
  212. while (xs_list_iter(&l, &v)) {
  213. if (expand_public && strcmp(v, public_address) == 0) {
  214. /* iterate the followers and add them */
  215. xs *fwers = follower_list(snac);
  216. char *actor;
  217. char *p = fwers;
  218. while (xs_list_iter(&p, &actor))
  219. xs_set_add(&rcpts, actor);
  220. }
  221. else
  222. xs_set_add(&rcpts, v);
  223. }
  224. }
  225. return xs_set_result(&rcpts);
  226. }
  227. int is_msg_public(snac *snac, const xs_dict *msg)
  228. /* checks if a message is public */
  229. {
  230. xs *rcpts = recipient_list(snac, msg, 0);
  231. return xs_list_in(rcpts, public_address) != -1;
  232. }
  233. int is_msg_for_me(snac *snac, const xs_dict *c_msg)
  234. /* checks if this message is for me */
  235. {
  236. const char *type = xs_dict_get(c_msg, "type");
  237. if (strcmp(type, "Announce") == 0) {
  238. const char *object = xs_dict_get(c_msg, "object");
  239. if (xs_type(object) == XSTYPE_DICT)
  240. object = xs_dict_get(object, "id");
  241. /* if it's about one of our posts, accept it */
  242. if (xs_startswith(object, snac->actor))
  243. return 2;
  244. /* if it's by someone we don't follow, reject */
  245. if (!following_check(snac, xs_dict_get(c_msg, "actor")))
  246. return 0;
  247. }
  248. /* if it's not a Create, allow */
  249. if (strcmp(type, "Create") != 0)
  250. return 1;
  251. xs_dict *msg = xs_dict_get(c_msg, "object");
  252. xs *rcpts = recipient_list(snac, msg, 0);
  253. xs_list *p = rcpts;
  254. xs_str *v;
  255. while(xs_list_iter(&p, &v)) {
  256. /* explicitly for me? accept */
  257. if (strcmp(v, snac->actor) == 0)
  258. return 2;
  259. /* for someone we follow? (probably cc'ed) accept */
  260. if (following_check(snac, v))
  261. return 5;
  262. }
  263. /* accept if it's by someone we follow */
  264. char *atto = xs_dict_get(msg, "attributedTo");
  265. if (!xs_is_null(atto) && following_check(snac, atto))
  266. return 3;
  267. /* is this message a reply to another? */
  268. char *irt = xs_dict_get(msg, "inReplyTo");
  269. if (!xs_is_null(irt)) {
  270. xs *r_msg = NULL;
  271. /* try to get the replied message */
  272. if (valid_status(object_get(irt, &r_msg))) {
  273. atto = xs_dict_get(r_msg, "attributedTo");
  274. /* accept if the replied message is from someone we follow */
  275. if (!xs_is_null(atto) && following_check(snac, atto))
  276. return 4;
  277. }
  278. }
  279. return 0;
  280. }
  281. void process_tags(snac *snac, const char *content, xs_str **n_content, xs_list **tag)
  282. /* parses mentions and tags from content */
  283. {
  284. xs_str *nc = xs_str_new(NULL);
  285. xs_list *tl = *tag;
  286. xs *split;
  287. xs_list *p;
  288. xs_val *v;
  289. int n = 0;
  290. /* create a default server for incomplete mentions */
  291. xs *def_srv = NULL;
  292. if (xs_list_len(tl)) {
  293. /* if there are any mentions, get the server from
  294. the first one, which is the inReplyTo author */
  295. p = tl;
  296. while (xs_list_iter(&p, &v)) {
  297. const char *type = xs_dict_get(v, "type");
  298. const char *name = xs_dict_get(v, "name");
  299. if (type && name && strcmp(type, "Mention") == 0) {
  300. xs *l = xs_split(name, "@");
  301. def_srv = xs_dup(xs_list_get(l, -1));
  302. break;
  303. }
  304. }
  305. }
  306. if (xs_is_null(def_srv))
  307. /* use this same server */
  308. def_srv = xs_dup(xs_dict_get(srv_config, "host"));
  309. split = xs_regex_split(content, "(@[A-Za-z0-9_]+(@[A-Za-z0-9\\.-]+)?|&#[0-9]+;|#[^ ,\\.:;<]+)");
  310. p = split;
  311. while (xs_list_iter(&p, &v)) {
  312. if ((n & 0x1)) {
  313. if (*v == '@') {
  314. xs *link = NULL;
  315. xs *wuid = NULL;
  316. if (strchr(v + 1, '@') == NULL) {
  317. /* only one @? it's a dumb Mastodon-like mention
  318. without server; add the default one */
  319. wuid = xs_fmt("%s@%s", v, def_srv);
  320. snac_debug(snac, 2, xs_fmt("mention without server '%s' '%s'", v, wuid));
  321. }
  322. else
  323. wuid = xs_dup(v);
  324. /* query the webfinger about this fellow */
  325. xs *actor = NULL;
  326. xs *uid = NULL;
  327. int status;
  328. status = webfinger_request(wuid, &actor, &uid);
  329. if (valid_status(status)) {
  330. xs *d = xs_dict_new();
  331. xs *n = xs_fmt("@%s", uid);
  332. d = xs_dict_append(d, "type", "Mention");
  333. d = xs_dict_append(d, "href", actor);
  334. d = xs_dict_append(d, "name", n);
  335. tl = xs_list_append(tl, d);
  336. link = xs_fmt("<a href=\"%s\" class=\"u-url mention\">%s</a>", actor, n);
  337. }
  338. if (!xs_is_null(link))
  339. nc = xs_str_cat(nc, link);
  340. else
  341. nc = xs_str_cat(nc, v);
  342. }
  343. else
  344. if (*v == '#') {
  345. /* hashtag */
  346. xs *d = xs_dict_new();
  347. xs *n = xs_tolower_i(xs_dup(v));
  348. xs *h = xs_fmt("%s%s", snac->actor, n);
  349. xs *l = xs_fmt("<a href=\"%s\" class=\"mention hashtag\" rel=\"tag\">%s</a>", h, v);
  350. d = xs_dict_append(d, "type", "Hashtag");
  351. d = xs_dict_append(d, "href", h);
  352. d = xs_dict_append(d, "name", n);
  353. tl = xs_list_append(tl, d);
  354. /* add the code */
  355. nc = xs_str_cat(nc, l);
  356. }
  357. else
  358. if (*v == '&') {
  359. /* HTML Unicode entity, probably part of an emoji */
  360. /* write as is */
  361. nc = xs_str_cat(nc, v);
  362. }
  363. }
  364. else
  365. nc = xs_str_cat(nc, v);
  366. n++;
  367. }
  368. *n_content = nc;
  369. *tag = tl;
  370. }
  371. void notify(snac *snac, const char *type, const char *utype, const char *actor, const xs_dict *msg)
  372. /* notifies the user of relevant events */
  373. {
  374. if (strcmp(type, "Create") == 0) {
  375. /* only notify of notes specifically for us */
  376. xs *rcpts = recipient_list(snac, msg, 0);
  377. if (xs_list_in(rcpts, snac->actor) == -1)
  378. return;
  379. /* discard votes */
  380. if (!xs_is_null(xs_dict_get(msg, "name")))
  381. return;
  382. }
  383. if (strcmp(type, "Undo") == 0 && strcmp(utype, "Follow") != 0)
  384. return;
  385. /* get the object id */
  386. const char *objid = xs_dict_get(msg, "object");
  387. if (xs_type(objid) == XSTYPE_DICT)
  388. objid = xs_dict_get(objid, "id");
  389. else
  390. objid = xs_dict_get(msg, "id");
  391. if (strcmp(type, "Like") == 0 || strcmp(type, "Announce") == 0) {
  392. /* if it's not an admiration about something by us, done */
  393. if (xs_is_null(objid) || !xs_startswith(objid, snac->actor))
  394. return;
  395. }
  396. /* user will love to know about this! */
  397. /* prepare message body */
  398. xs *body = xs_fmt("User : @%s@%s\n",
  399. xs_dict_get(snac->config, "uid"),
  400. xs_dict_get(srv_config, "host")
  401. );
  402. if (strcmp(utype, "(null)") != 0) {
  403. xs *s1 = xs_fmt("Type : %s + %s\n", type, utype);
  404. body = xs_str_cat(body, s1);
  405. }
  406. else {
  407. xs *s1 = xs_fmt("Type : %s\n", type);
  408. body = xs_str_cat(body, s1);
  409. }
  410. {
  411. xs *s1 = xs_fmt("Actor : %s\n", actor);
  412. body = xs_str_cat(body, s1);
  413. }
  414. if (objid != NULL) {
  415. xs *s1 = xs_fmt("Object: %s\n", objid);
  416. body = xs_str_cat(body, s1);
  417. }
  418. /* email */
  419. const char *email = "[disabled by admin]";
  420. if (xs_type(xs_dict_get(srv_config, "disable_email_notifications")) != XSTYPE_TRUE) {
  421. email = xs_dict_get(snac->config_o, "email");
  422. if (xs_is_null(email)) {
  423. email = xs_dict_get(snac->config, "email");
  424. if (xs_is_null(email))
  425. email = "[empty]";
  426. }
  427. }
  428. if (*email != '\0' && *email != '[') {
  429. snac_debug(snac, 1, xs_fmt("email notify %s %s %s", type, utype, actor));
  430. xs *subject = xs_fmt("snac notify for @%s@%s",
  431. xs_dict_get(snac->config, "uid"), xs_dict_get(srv_config, "host"));
  432. xs *from = xs_fmt("snac-daemon <snac-daemon@%s>", xs_dict_get(srv_config, "host"));
  433. xs *header = xs_fmt(
  434. "From: %s\n"
  435. "To: %s\n"
  436. "Subject: %s\n"
  437. "\n",
  438. from, email, subject);
  439. xs *email_body = xs_fmt("%s%s", header, body);
  440. enqueue_email(email_body, 0);
  441. }
  442. /* telegram */
  443. char *bot = xs_dict_get(snac->config, "telegram_bot");
  444. char *chat_id = xs_dict_get(snac->config, "telegram_chat_id");
  445. if (!xs_is_null(bot) && !xs_is_null(chat_id) && *bot && *chat_id)
  446. enqueue_telegram(body, bot, chat_id);
  447. /* finally, store it in the notification folder */
  448. if (strcmp(type, "Follow") == 0)
  449. objid = xs_dict_get(msg, "id");
  450. notify_add(snac, type, utype, actor, objid);
  451. }
  452. /** messages **/
  453. xs_dict *msg_base(snac *snac, const char *type, const char *id,
  454. const char *actor, const char *date, const char *object)
  455. /* creates a base ActivityPub message */
  456. {
  457. xs *did = NULL;
  458. xs *published = NULL;
  459. xs *ntid = tid(0);
  460. /* generated values */
  461. if (date && strcmp(date, "@now") == 0) {
  462. published = xs_str_utctime(0, ISO_DATE_SPEC);
  463. date = published;
  464. }
  465. if (id != NULL) {
  466. if (strcmp(id, "@dummy") == 0) {
  467. did = xs_fmt("%s/d/%s/%s", snac->actor, ntid, type);
  468. id = did;
  469. }
  470. else
  471. if (strcmp(id, "@object") == 0) {
  472. if (object != NULL) {
  473. did = xs_fmt("%s/%s_%s", xs_dict_get(object, "id"), type, ntid);
  474. id = did;
  475. }
  476. else
  477. id = NULL;
  478. }
  479. }
  480. xs_dict *msg = xs_dict_new();
  481. msg = xs_dict_append(msg, "@context", "https:/" "/www.w3.org/ns/activitystreams");
  482. msg = xs_dict_append(msg, "type", type);
  483. if (id != NULL)
  484. msg = xs_dict_append(msg, "id", id);
  485. if (actor != NULL)
  486. msg = xs_dict_append(msg, "actor", actor);
  487. if (date != NULL)
  488. msg = xs_dict_append(msg, "published", date);
  489. if (object != NULL)
  490. msg = xs_dict_append(msg, "object", object);
  491. return msg;
  492. }
  493. d_char *msg_collection(snac *snac, char *id)
  494. /* creates an empty OrderedCollection message */
  495. {
  496. d_char *msg = msg_base(snac, "OrderedCollection", id, NULL, NULL, NULL);
  497. xs *ol = xs_list_new();
  498. xs *nz = xs_number_new(0);
  499. msg = xs_dict_append(msg, "attributedTo", snac->actor);
  500. msg = xs_dict_append(msg, "orderedItems", ol);
  501. msg = xs_dict_append(msg, "totalItems", nz);
  502. return msg;
  503. }
  504. d_char *msg_accept(snac *snac, char *object, char *to)
  505. /* creates an Accept message (as a response to a Follow) */
  506. {
  507. d_char *msg = msg_base(snac, "Accept", "@dummy", snac->actor, NULL, object);
  508. msg = xs_dict_append(msg, "to", to);
  509. return msg;
  510. }
  511. xs_dict *msg_update(snac *snac, xs_dict *object)
  512. /* creates an Update message */
  513. {
  514. xs_dict *msg = msg_base(snac, "Update", "@object", snac->actor, "@now", object);
  515. char *type = xs_dict_get(object, "type");
  516. if (strcmp(type, "Note") == 0) {
  517. msg = xs_dict_append(msg, "to", xs_dict_get(object, "to"));
  518. msg = xs_dict_append(msg, "cc", xs_dict_get(object, "cc"));
  519. }
  520. else
  521. if (strcmp(type, "Person") == 0) {
  522. msg = xs_dict_append(msg, "to", public_address);
  523. /* also spam the people being followed, so that
  524. they have the newest information about who we are */
  525. xs *cc = following_list(snac);
  526. msg = xs_dict_append(msg, "cc", cc);
  527. }
  528. else
  529. msg = xs_dict_append(msg, "to", public_address);
  530. return msg;
  531. }
  532. d_char *msg_admiration(snac *snac, char *object, char *type)
  533. /* creates a Like or Announce message */
  534. {
  535. xs *a_msg = NULL;
  536. d_char *msg = NULL;
  537. xs *wrk = NULL;
  538. /* call the object */
  539. timeline_request(snac, &object, &wrk);
  540. if (valid_status(object_get(object, &a_msg))) {
  541. xs *rcpts = xs_list_new();
  542. msg = msg_base(snac, type, "@dummy", snac->actor, "@now", object);
  543. if (is_msg_public(snac, a_msg))
  544. rcpts = xs_list_append(rcpts, public_address);
  545. rcpts = xs_list_append(rcpts, xs_dict_get(a_msg, "attributedTo"));
  546. msg = xs_dict_append(msg, "to", rcpts);
  547. }
  548. else
  549. snac_log(snac, xs_fmt("msg_admiration cannot retrieve object %s", object));
  550. return msg;
  551. }
  552. d_char *msg_actor(snac *snac)
  553. /* create a Person message for this actor */
  554. {
  555. xs *ctxt = xs_list_new();
  556. xs *icon = xs_dict_new();
  557. xs *keys = xs_dict_new();
  558. xs *avtr = NULL;
  559. xs *kid = NULL;
  560. xs *f_bio = NULL;
  561. d_char *msg = msg_base(snac, "Person", snac->actor, NULL, NULL, NULL);
  562. char *p;
  563. int n;
  564. /* change the @context (is this really necessary?) */
  565. ctxt = xs_list_append(ctxt, "https:/" "/www.w3.org/ns/activitystreams");
  566. ctxt = xs_list_append(ctxt, "https:/" "/w3id.org/security/v1");
  567. msg = xs_dict_set(msg, "@context", ctxt);
  568. msg = xs_dict_set(msg, "url", snac->actor);
  569. msg = xs_dict_set(msg, "name", xs_dict_get(snac->config, "name"));
  570. msg = xs_dict_set(msg, "preferredUsername", snac->uid);
  571. msg = xs_dict_set(msg, "published", xs_dict_get(snac->config, "published"));
  572. f_bio = not_really_markdown(xs_dict_get(snac->config, "bio"), NULL);
  573. msg = xs_dict_set(msg, "summary", f_bio);
  574. char *folders[] = { "inbox", "outbox", "followers", "following", NULL };
  575. for (n = 0; folders[n]; n++) {
  576. xs *f = xs_fmt("%s/%s", snac->actor, folders[n]);
  577. msg = xs_dict_set(msg, folders[n], f);
  578. }
  579. p = xs_dict_get(snac->config, "avatar");
  580. if (*p == '\0')
  581. avtr = xs_fmt("%s/susie.png", srv_baseurl);
  582. else
  583. avtr = xs_dup(p);
  584. icon = xs_dict_append(icon, "type", "Image");
  585. icon = xs_dict_append(icon, "mediaType", xs_mime_by_ext(avtr));
  586. icon = xs_dict_append(icon, "url", avtr);
  587. msg = xs_dict_set(msg, "icon", icon);
  588. kid = xs_fmt("%s#main-key", snac->actor);
  589. keys = xs_dict_append(keys, "id", kid);
  590. keys = xs_dict_append(keys, "owner", snac->actor);
  591. keys = xs_dict_append(keys, "publicKeyPem", xs_dict_get(snac->key, "public"));
  592. msg = xs_dict_set(msg, "publicKey", keys);
  593. return msg;
  594. }
  595. xs_dict *msg_create(snac *snac, const xs_dict *object)
  596. /* creates a 'Create' message */
  597. {
  598. xs_dict *msg = msg_base(snac, "Create", "@object", snac->actor, "@now", object);
  599. xs_val *v;
  600. if ((v = xs_dict_get(object, "attributedTo")))
  601. msg = xs_dict_append(msg, "attributedTo", v);
  602. if ((v = xs_dict_get(object, "cc")))
  603. msg = xs_dict_append(msg, "cc", v);
  604. if ((v = xs_dict_get(object, "to")))
  605. msg = xs_dict_append(msg, "to", v);
  606. else
  607. msg = xs_dict_append(msg, "to", public_address);
  608. return msg;
  609. }
  610. d_char *msg_undo(snac *snac, char *object)
  611. /* creates an 'Undo' message */
  612. {
  613. d_char *msg = msg_base(snac, "Undo", "@object", snac->actor, "@now", object);
  614. msg = xs_dict_append(msg, "to", xs_dict_get(object, "object"));
  615. return msg;
  616. }
  617. d_char *msg_delete(snac *snac, char *id)
  618. /* creates a 'Delete' + 'Tombstone' for a local entry */
  619. {
  620. xs *tomb = xs_dict_new();
  621. d_char *msg = NULL;
  622. /* sculpt the tombstone */
  623. tomb = xs_dict_append(tomb, "type", "Tombstone");
  624. tomb = xs_dict_append(tomb, "id", id);
  625. /* now create the Delete */
  626. msg = msg_base(snac, "Delete", "@object", snac->actor, "@now", tomb);
  627. msg = xs_dict_append(msg, "to", public_address);
  628. return msg;
  629. }
  630. xs_dict *msg_follow(snac *snac, const char *q)
  631. /* creates a 'Follow' message */
  632. {
  633. xs *actor_o = NULL;
  634. xs *actor = NULL;
  635. d_char *msg = NULL;
  636. int status;
  637. xs *url_or_uid = xs_strip_i(xs_str_new(q));
  638. if (xs_startswith(url_or_uid, "https:/"))
  639. actor = xs_dup(url_or_uid);
  640. else
  641. if (!valid_status(webfinger_request(url_or_uid, &actor, NULL)) || actor == NULL) {
  642. snac_log(snac, xs_fmt("cannot resolve user %s to follow", url_or_uid));
  643. return NULL;
  644. }
  645. /* request the actor */
  646. status = actor_request(snac, actor, &actor_o);
  647. if (valid_status(status)) {
  648. /* check if the actor is an alias */
  649. char *r_actor = xs_dict_get(actor_o, "id");
  650. if (r_actor && strcmp(actor, r_actor) != 0) {
  651. snac_log(snac, xs_fmt("actor to follow is an alias %s -> %s", actor, r_actor));
  652. }
  653. msg = msg_base(snac, "Follow", "@dummy", snac->actor, NULL, r_actor);
  654. }
  655. else
  656. snac_log(snac, xs_fmt("cannot get actor to follow %s %d", actor, status));
  657. return msg;
  658. }
  659. xs_dict *msg_note(snac *snac, const xs_str *content, const xs_val *rcpts,
  660. xs_str *in_reply_to, xs_list *attach, int priv)
  661. /* creates a 'Note' message */
  662. {
  663. xs *ntid = tid(0);
  664. xs *id = xs_fmt("%s/p/%s", snac->actor, ntid);
  665. xs *ctxt = NULL;
  666. xs *fc2 = NULL;
  667. xs *fc1 = NULL;
  668. xs *to = NULL;
  669. xs *cc = xs_list_new();
  670. xs *irt = NULL;
  671. xs *tag = xs_list_new();
  672. xs *atls = xs_list_new();
  673. xs_dict *msg = msg_base(snac, "Note", id, NULL, "@now", NULL);
  674. xs_list *p;
  675. xs_val *v;
  676. if (rcpts == NULL)
  677. to = xs_list_new();
  678. else {
  679. if (xs_type(rcpts) == XSTYPE_STRING) {
  680. to = xs_list_new();
  681. to = xs_list_append(to, rcpts);
  682. }
  683. else
  684. to = xs_dup(rcpts);
  685. }
  686. /* format the content */
  687. fc2 = not_really_markdown(content, &atls);
  688. if (in_reply_to != NULL && *in_reply_to) {
  689. xs *p_msg = NULL;
  690. xs *wrk = NULL;
  691. /* demand this thing */
  692. timeline_request(snac, &in_reply_to, &wrk);
  693. if (valid_status(object_get(in_reply_to, &p_msg))) {
  694. /* add this author as recipient */
  695. char *a, *v;
  696. if ((a = xs_dict_get(p_msg, "attributedTo")) && xs_list_in(to, a) == -1)
  697. to = xs_list_append(to, a);
  698. /* add this author to the tag list as a mention */
  699. xs *t_href = NULL;
  700. xs *t_name = NULL;
  701. if (!xs_is_null(a) && valid_status(webfinger_request(a, &t_href, &t_name))) {
  702. xs *t = xs_dict_new();
  703. t = xs_dict_append(t, "type", "Mention");
  704. t = xs_dict_append(t, "href", t_href);
  705. t = xs_dict_append(t, "name", t_name);
  706. tag = xs_list_append(tag, t);
  707. }
  708. /* get the context, if there is one */
  709. if ((v = xs_dict_get(p_msg, "context")))
  710. ctxt = xs_dup(v);
  711. /* if this message is public, ours will also be */
  712. if (!priv && is_msg_public(snac, p_msg) && xs_list_in(to, public_address) == -1)
  713. to = xs_list_append(to, public_address);
  714. }
  715. irt = xs_dup(in_reply_to);
  716. }
  717. else
  718. irt = xs_val_new(XSTYPE_NULL);
  719. /* extract the mentions and hashtags and convert the content */
  720. process_tags(snac, fc2, &fc1, &tag);
  721. /* create the attachment list, if there are any */
  722. if (!xs_is_null(attach)) {
  723. while (xs_list_iter(&attach, &v)) {
  724. xs *d = xs_dict_new();
  725. char *url = xs_list_get(v, 0);
  726. char *alt = xs_list_get(v, 1);
  727. char *mime = xs_mime_by_ext(url);
  728. d = xs_dict_append(d, "mediaType", mime);
  729. d = xs_dict_append(d, "url", url);
  730. d = xs_dict_append(d, "name", alt);
  731. d = xs_dict_append(d, "type",
  732. xs_startswith(mime, "image/") ? "Image" : "Document");
  733. atls = xs_list_append(atls, d);
  734. }
  735. }
  736. if (ctxt == NULL)
  737. ctxt = xs_fmt("%s#ctxt", id);
  738. /* add all mentions to the cc */
  739. p = tag;
  740. while (xs_list_iter(&p, &v)) {
  741. if (xs_type(v) == XSTYPE_DICT) {
  742. char *t;
  743. if ((t = xs_dict_get(v, "type")) != NULL && strcmp(t, "Mention") == 0) {
  744. if ((t = xs_dict_get(v, "href")) != NULL)
  745. cc = xs_list_append(cc, t);
  746. }
  747. }
  748. }
  749. /* no recipients? must be for everybody */
  750. if (!priv && xs_list_len(to) == 0)
  751. to = xs_list_append(to, public_address);
  752. /* delete all cc recipients that also are in the to */
  753. p = to;
  754. while (xs_list_iter(&p, &v)) {
  755. int i;
  756. if ((i = xs_list_in(cc, v)) != -1)
  757. cc = xs_list_del(cc, i);
  758. }
  759. msg = xs_dict_append(msg, "attributedTo", snac->actor);
  760. msg = xs_dict_append(msg, "summary", "");
  761. msg = xs_dict_append(msg, "content", fc1);
  762. msg = xs_dict_append(msg, "context", ctxt);
  763. msg = xs_dict_append(msg, "url", id);
  764. msg = xs_dict_append(msg, "to", to);
  765. msg = xs_dict_append(msg, "cc", cc);
  766. msg = xs_dict_append(msg, "inReplyTo", irt);
  767. msg = xs_dict_append(msg, "tag", tag);
  768. msg = xs_dict_append(msg, "sourceContent", content);
  769. if (xs_list_len(atls))
  770. msg = xs_dict_append(msg, "attachment", atls);
  771. return msg;
  772. }
  773. xs_dict *msg_ping(snac *user, const char *rcpt)
  774. /* creates a Ping message (https://humungus.tedunangst.com/r/honk/v/tip/f/docs/ping.txt) */
  775. {
  776. xs_dict *msg = msg_base(user, "Ping", "@dummy", user->actor, NULL, NULL);
  777. msg = xs_dict_append(msg, "to", rcpt);
  778. return msg;
  779. }
  780. xs_dict *msg_pong(snac *user, const char *rcpt, const char *object)
  781. /* creates a Pong message (https://humungus.tedunangst.com/r/honk/v/tip/f/docs/ping.txt) */
  782. {
  783. xs_dict *msg = msg_base(user, "Pong", "@dummy", user->actor, NULL, object);
  784. msg = xs_dict_append(msg, "to", rcpt);
  785. return msg;
  786. }
  787. xs_dict *msg_question(snac *user, const char *content, xs_list *attach,
  788. const xs_list *opts, int multiple, int end_secs)
  789. /* creates a Question message */
  790. {
  791. xs *ntid = tid(0);
  792. xs_dict *msg = msg_note(user, content, NULL, NULL, attach, 0);
  793. int max = 8;
  794. msg = xs_dict_set(msg, "type", "Question");
  795. /* make it non-editable */
  796. msg = xs_dict_del(msg, "sourceContent");
  797. xs *o = xs_list_new();
  798. xs_list *p = (xs_list *)opts;
  799. xs_str *v;
  800. xs *replies = xs_json_loads("{\"type\":\"Collection\",\"totalItems\":0}");
  801. while (max-- && xs_list_iter(&p, &v)) {
  802. xs *v2 = xs_dup(v);
  803. xs *d = xs_dict_new();
  804. if (strlen(v2) > 60) {
  805. v2[60] = '\0';
  806. v2 = xs_str_cat(v2, "...");
  807. }
  808. d = xs_dict_append(d, "name", v2);
  809. d = xs_dict_append(d, "replies", replies);
  810. o = xs_list_append(o, d);
  811. }
  812. msg = xs_dict_append(msg, multiple ? "anyOf" : "oneOf", o);
  813. /* set the end time */
  814. time_t t = time(NULL) + end_secs;
  815. xs *et = xs_str_utctime(t, ISO_DATE_SPEC);
  816. msg = xs_dict_append(msg, "endTime", et);
  817. return msg;
  818. }
  819. int update_question(snac *user, const char *id)
  820. /* updates the poll counts */
  821. {
  822. xs *msg = NULL;
  823. xs *rcnt = xs_dict_new();
  824. xs *z = xs_number_new(0);
  825. xs *rcpts = xs_list_new();
  826. xs *lopts = xs_list_new();
  827. xs_list *opts;
  828. xs_list *p;
  829. xs_val *v;
  830. /* get the object */
  831. if (!valid_status(object_get(id, &msg)))
  832. return -1;
  833. /* closed? do nothing more */
  834. if (xs_dict_get(msg, "closed"))
  835. return -2;
  836. /* get the options */
  837. if ((opts = xs_dict_get(msg, "oneOf")) == NULL &&
  838. (opts = xs_dict_get(msg, "anyOf")) == NULL)
  839. return -3;
  840. /* fill the initial count */
  841. p = opts;
  842. while (xs_list_iter(&p, &v)) {
  843. const char *name = xs_dict_get(v, "name");
  844. if (name) {
  845. lopts = xs_list_append(lopts, name);
  846. rcnt = xs_dict_set(rcnt, name, z);
  847. }
  848. }
  849. /* iterate now the children (the votes) */
  850. xs *chld = object_children(id);
  851. p = chld;
  852. while (xs_list_iter(&p, &v)) {
  853. xs *obj = NULL;
  854. if (!valid_status(object_get_by_md5(v, &obj)))
  855. continue;
  856. const char *name = xs_dict_get(obj, "name");
  857. const char *atto = xs_dict_get(obj, "attributedTo");
  858. if (name && atto) {
  859. /* get the current count */
  860. const xs_number *cnt = xs_dict_get(rcnt, name);
  861. if (xs_type(cnt) == XSTYPE_NUMBER) {
  862. /* if it exists, increment */
  863. xs *ucnt = xs_number_new(xs_number_get(cnt) + 1);
  864. rcnt = xs_dict_set(rcnt, name, ucnt);
  865. rcpts = xs_list_append(rcpts, atto);
  866. }
  867. }
  868. }
  869. /* create a new list of options with their new counts */
  870. xs *nopts = xs_list_new();
  871. p = lopts;
  872. while (xs_list_iter(&p, &v)) {
  873. const xs_number *cnt = xs_dict_get(rcnt, v);
  874. if (xs_type(cnt) == XSTYPE_NUMBER) {
  875. xs *d1 = xs_dict_new();
  876. xs *d2 = xs_dict_new();
  877. d2 = xs_dict_append(d2, "type", "Collection");
  878. d2 = xs_dict_append(d2, "totalItems", cnt);
  879. d1 = xs_dict_append(d1, "type", "Note");
  880. d1 = xs_dict_append(d1, "name", v);
  881. d1 = xs_dict_append(d1, "replies", d2);
  882. nopts = xs_list_append(nopts, d1);
  883. }
  884. }
  885. /* update the list */
  886. msg = xs_dict_set(msg, xs_dict_get(msg, "oneOf") != NULL ? "oneOf" : "anyOf", nopts);
  887. /* due date? */
  888. const char *end_time = xs_dict_get(msg, "endTime");
  889. if (!xs_is_null(end_time)) {
  890. xs *now = xs_str_utctime(0, ISO_DATE_SPEC);
  891. /* it's now greater than the endTime? */
  892. if (strcmp(now, end_time) >= 0) {
  893. xs *et = xs_dup(end_time);
  894. msg = xs_dict_set(msg, "closed", et);
  895. notify(user, "Update", "Question", user->actor, msg);
  896. }
  897. }
  898. /* update the count of voters */
  899. xs *vcnt = xs_number_new(xs_list_len(rcpts));
  900. msg = xs_dict_set(msg, "votersCount", vcnt);
  901. /* store */
  902. object_add_ow(id, msg);
  903. snac_debug(user, 1, xs_fmt("recounted poll %s", id));
  904. timeline_touch(user);
  905. /* send an update message to all voters */
  906. xs *u_msg = msg_update(user, msg);
  907. u_msg = xs_dict_set(u_msg, "cc", rcpts);
  908. enqueue_message(user, u_msg);
  909. return 0;
  910. }
  911. /** queues **/
  912. int process_input_message(snac *snac, xs_dict *msg, xs_dict *req)
  913. /* processes an ActivityPub message from the input queue */
  914. {
  915. /* actor and type exist, were checked previously */
  916. char *actor = xs_dict_get(msg, "actor");
  917. char *type = xs_dict_get(msg, "type");
  918. xs *actor_o = NULL;
  919. int a_status;
  920. int do_notify = 0;
  921. /* question votes may not have a type */
  922. if (xs_is_null(type))
  923. type = "Note";
  924. if (xs_is_null(actor)) {
  925. snac_debug(snac, 0, xs_fmt("malformed message"));
  926. return 1;
  927. }
  928. char *object, *utype;
  929. object = xs_dict_get(msg, "object");
  930. if (object != NULL && xs_type(object) == XSTYPE_DICT)
  931. utype = xs_dict_get(object, "type");
  932. else
  933. utype = "(null)";
  934. /* reject messages that are not for this user */
  935. if (!is_msg_for_me(snac, msg)) {
  936. snac_debug(snac, 0, xs_fmt("message from %s of type '%s' not for us", actor, type));
  937. return 1;
  938. }
  939. /* if it's a DM from someone we don't follow, reject the message */
  940. if (xs_type(xs_dict_get(snac->config, "drop_dm_from_unknown")) == XSTYPE_TRUE) {
  941. if (strcmp(utype, "Note") == 0 && !is_msg_public(snac, msg) &&
  942. !following_check(snac, actor)) {
  943. snac_log(snac, xs_fmt("DM rejected from unknown actor %s", actor));
  944. return 1;
  945. }
  946. }
  947. /* bring the actor */
  948. a_status = actor_request(snac, actor, &actor_o);
  949. /* if the actor does not explicitly exist, discard */
  950. if (a_status == 404 || a_status == 410) {
  951. snac_debug(snac, 1,
  952. xs_fmt("dropping message due to actor error %s %d", actor, a_status));
  953. return 1;
  954. }
  955. if (!valid_status(a_status)) {
  956. /* other actor download errors may need a retry */
  957. snac_debug(snac, 1,
  958. xs_fmt("error requesting actor %s %d -- retry later", actor, a_status));
  959. return 0;
  960. }
  961. /* check the signature */
  962. xs *sig_err = NULL;
  963. if (!check_signature(snac, req, &sig_err)) {
  964. snac_log(snac, xs_fmt("bad signature %s (%s)", actor, sig_err));
  965. srv_archive_error("check_signature", sig_err, req, msg);
  966. return 1;
  967. }
  968. if (strcmp(type, "Follow") == 0) { /** **/
  969. if (!follower_check(snac, actor)) {
  970. xs *f_msg = xs_dup(msg);
  971. xs *reply = msg_accept(snac, f_msg, actor);
  972. enqueue_message(snac, reply);
  973. if (xs_is_null(xs_dict_get(f_msg, "published"))) {
  974. /* add a date if it doesn't include one (Mastodon) */
  975. xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
  976. f_msg = xs_dict_set(f_msg, "published", date);
  977. }
  978. timeline_add(snac, xs_dict_get(f_msg, "id"), f_msg);
  979. follower_add(snac, actor);
  980. snac_log(snac, xs_fmt("new follower %s", actor));
  981. do_notify = 1;
  982. }
  983. else
  984. snac_log(snac, xs_fmt("repeated 'Follow' from %s", actor));
  985. }
  986. else
  987. if (strcmp(type, "Undo") == 0) { /** **/
  988. if (strcmp(utype, "Follow") == 0) { /** **/
  989. if (valid_status(follower_del(snac, actor))) {
  990. snac_log(snac, xs_fmt("no longer following us %s", actor));
  991. do_notify = 1;
  992. }
  993. else
  994. snac_log(snac, xs_fmt("error deleting follower %s", actor));
  995. }
  996. else
  997. snac_debug(snac, 1, xs_fmt("ignored 'Undo' for object type '%s'", utype));
  998. }
  999. else
  1000. if (strcmp(type, "Create") == 0) { /** **/
  1001. if (is_muted(snac, actor))
  1002. snac_log(snac, xs_fmt("ignored 'Create' + '%s' from muted actor %s", utype, actor));
  1003. if (strcmp(utype, "Note") == 0) { /** **/
  1004. char *id = xs_dict_get(object, "id");
  1005. char *in_reply_to = xs_dict_get(object, "inReplyTo");
  1006. xs *wrk = NULL;
  1007. timeline_request(snac, &in_reply_to, &wrk);
  1008. if (timeline_add(snac, id, object)) {
  1009. snac_log(snac, xs_fmt("new 'Note' %s %s", actor, id));
  1010. do_notify = 1;
  1011. }
  1012. /* if it has a "name" field, it may be a vote for a question */
  1013. const char *name = xs_dict_get(object, "name");
  1014. if (!xs_is_null(name) && *name && !xs_is_null(in_reply_to) && *in_reply_to)
  1015. update_question(snac, in_reply_to);
  1016. }
  1017. else
  1018. if (strcmp(utype, "Question") == 0) { /** **/
  1019. char *id = xs_dict_get(object, "id");
  1020. if (timeline_add(snac, id, object))
  1021. snac_log(snac, xs_fmt("new 'Question' %s %s", actor, id));
  1022. }
  1023. else
  1024. snac_debug(snac, 1, xs_fmt("ignored 'Create' for object type '%s'", utype));
  1025. }
  1026. else
  1027. if (strcmp(type, "Accept") == 0) { /** **/
  1028. if (strcmp(utype, "Follow") == 0) { /** **/
  1029. if (following_check(snac, actor)) {
  1030. following_add(snac, actor, msg);
  1031. snac_log(snac, xs_fmt("confirmed follow from %s", actor));
  1032. }
  1033. else
  1034. snac_log(snac, xs_fmt("spurious follow accept from %s", actor));
  1035. }
  1036. else
  1037. snac_debug(snac, 1, xs_fmt("ignored 'Accept' for object type '%s'", utype));
  1038. }
  1039. else
  1040. if (strcmp(type, "Like") == 0) { /** **/
  1041. if (xs_type(object) == XSTYPE_DICT)
  1042. object = xs_dict_get(object, "id");
  1043. timeline_admire(snac, object, actor, 1);
  1044. snac_log(snac, xs_fmt("new 'Like' %s %s", actor, object));
  1045. do_notify = 1;
  1046. }
  1047. else
  1048. if (strcmp(type, "Announce") == 0) { /** **/
  1049. xs *a_msg = NULL;
  1050. xs *wrk = NULL;
  1051. if (xs_type(object) == XSTYPE_DICT)
  1052. object = xs_dict_get(object, "id");
  1053. timeline_request(snac, &object, &wrk);
  1054. if (valid_status(object_get(object, &a_msg))) {
  1055. char *who = xs_dict_get(a_msg, "attributedTo");
  1056. if (who && !is_muted(snac, who)) {
  1057. /* bring the actor */
  1058. xs *who_o = NULL;
  1059. if (valid_status(actor_request(snac, who, &who_o))) {
  1060. timeline_admire(snac, object, actor, 0);
  1061. snac_log(snac, xs_fmt("new 'Announce' %s %s", actor, object));
  1062. do_notify = 1;
  1063. }
  1064. else
  1065. snac_log(snac, xs_fmt("dropped 'Announce' on actor request error %s", who));
  1066. }
  1067. else
  1068. snac_log(snac, xs_fmt("ignored 'Announce' about muted actor %s", who));
  1069. }
  1070. else
  1071. snac_log(snac, xs_fmt("error requesting 'Announce' object %s", object));
  1072. }
  1073. else
  1074. if (strcmp(type, "Update") == 0) { /** **/
  1075. if (strcmp(utype, "Person") == 0) {
  1076. actor_add(actor, xs_dict_get(msg, "object"));
  1077. timeline_touch(snac);
  1078. snac_log(snac, xs_fmt("updated actor %s", actor));
  1079. }
  1080. else
  1081. if (strcmp(utype, "Note") == 0) { /** **/
  1082. const char *id = xs_dict_get(object, "id");
  1083. object_add_ow(id, object);
  1084. timeline_touch(snac);
  1085. snac_log(snac, xs_fmt("updated post %s", id));
  1086. }
  1087. else
  1088. if (strcmp(utype, "Question") == 0) { /** **/
  1089. const char *id = xs_dict_get(object, "id");
  1090. const char *closed = xs_dict_get(object, "closed");
  1091. object_add_ow(id, object);
  1092. timeline_touch(snac);
  1093. snac_log(snac, xs_fmt("%s poll %s", closed == NULL ? "updated" : "closed", id));
  1094. if (closed != NULL)
  1095. do_notify = 1;
  1096. }
  1097. else
  1098. snac_log(snac, xs_fmt("ignored 'Update' for object type '%s'", utype));
  1099. }
  1100. else
  1101. if (strcmp(type, "Delete") == 0) { /** **/
  1102. if (xs_type(object) == XSTYPE_DICT)
  1103. object = xs_dict_get(object, "id");
  1104. if (valid_status(timeline_del(snac, object)))
  1105. snac_debug(snac, 1, xs_fmt("new 'Delete' %s %s", actor, object));
  1106. else
  1107. snac_debug(snac, 1, xs_fmt("ignored 'Delete' for unknown object %s", object));
  1108. }
  1109. else
  1110. if (strcmp(type, "Pong") == 0) { /** **/
  1111. snac_log(snac, xs_fmt("'Pong' received from %s", actor));
  1112. }
  1113. else
  1114. if (strcmp(type, "Ping") == 0) { /** **/
  1115. snac_log(snac, xs_fmt("'Ping' requested from %s", actor));
  1116. xs *rsp = msg_pong(snac, actor, xs_dict_get(msg, "id"));
  1117. enqueue_output_by_actor(snac, rsp, actor, 0);
  1118. }
  1119. else
  1120. snac_debug(snac, 1, xs_fmt("process_input_message type '%s' ignored", type));
  1121. if (do_notify) {
  1122. notify(snac, type, utype, actor, msg);
  1123. timeline_touch(snac);
  1124. }
  1125. return 1;
  1126. }
  1127. int send_email(char *msg)
  1128. /* invoke sendmail with email headers and body in msg */
  1129. {
  1130. FILE *f;
  1131. int status;
  1132. int fds[2];
  1133. pid_t pid;
  1134. if (pipe(fds) == -1) return -1;
  1135. pid = vfork();
  1136. if (pid == -1) return -1;
  1137. else if (pid == 0) {
  1138. dup2(fds[0], 0);
  1139. close(fds[0]);
  1140. close(fds[1]);
  1141. execl("/usr/sbin/sendmail", "sendmail", "-t", (char *) NULL);
  1142. _exit(1);
  1143. }
  1144. close(fds[0]);
  1145. if ((f = fdopen(fds[1], "w")) == NULL) {
  1146. close(fds[1]);
  1147. return -1;
  1148. }
  1149. fprintf(f, "%s\n", msg);
  1150. fclose(f);
  1151. if (waitpid(pid, &status, 0) == -1) return -1;
  1152. return status;
  1153. }
  1154. void process_user_queue_item(snac *snac, xs_dict *q_item)
  1155. /* processes an item from the user queue */
  1156. {
  1157. char *type;
  1158. int queue_retry_max = xs_number_get(xs_dict_get(srv_config, "queue_retry_max"));
  1159. if ((type = xs_dict_get(q_item, "type")) == NULL)
  1160. type = "output";
  1161. if (strcmp(type, "message") == 0) {
  1162. xs_dict *msg = xs_dict_get(q_item, "message");
  1163. xs *rcpts = recipient_list(snac, msg, 1);
  1164. xs_set inboxes;
  1165. xs_list *p;
  1166. xs_str *actor;
  1167. xs_set_init(&inboxes);
  1168. /* iterate the recipients */
  1169. p = rcpts;
  1170. while (xs_list_iter(&p, &actor)) {
  1171. xs *inbox = get_actor_inbox(snac, actor);
  1172. if (inbox != NULL) {
  1173. /* add to the set and, if it's not there, send message */
  1174. if (xs_set_add(&inboxes, inbox) == 1)
  1175. enqueue_output(snac, msg, inbox, 0);
  1176. }
  1177. else
  1178. snac_log(snac, xs_fmt("cannot find inbox for %s", actor));
  1179. }
  1180. /* if it's public, send to the collected inboxes */
  1181. if (is_msg_public(snac, msg)) {
  1182. xs *shibx = inbox_list();
  1183. xs_str *inbox;
  1184. p = shibx;
  1185. while (xs_list_iter(&p, &inbox)) {
  1186. if (xs_set_add(&inboxes, inbox) == 1)
  1187. enqueue_output(snac, msg, inbox, 0);
  1188. }
  1189. }
  1190. xs_set_free(&inboxes);
  1191. }
  1192. else
  1193. if (strcmp(type, "input") == 0) {
  1194. /* process the message */
  1195. xs_dict *msg = xs_dict_get(q_item, "message");
  1196. xs_dict *req = xs_dict_get(q_item, "req");
  1197. int retries = xs_number_get(xs_dict_get(q_item, "retries"));
  1198. if (xs_is_null(msg))
  1199. return;
  1200. if (!process_input_message(snac, msg, req)) {
  1201. if (retries > queue_retry_max)
  1202. snac_log(snac, xs_fmt("input giving up"));
  1203. else {
  1204. /* reenqueue */
  1205. enqueue_input(snac, msg, req, retries + 1);
  1206. snac_log(snac, xs_fmt("input requeue #%d", retries + 1));
  1207. }
  1208. }
  1209. }
  1210. else
  1211. if (strcmp(type, "close_question") == 0) {
  1212. /* the time for this question has ended */
  1213. const char *id = xs_dict_get(q_item, "message");
  1214. if (!xs_is_null(id))
  1215. update_question(snac, id);
  1216. }
  1217. else
  1218. snac_log(snac, xs_fmt("unexpected q_item type '%s'", type));
  1219. }
  1220. int process_user_queue(snac *snac)
  1221. /* processes a user's queue */
  1222. {
  1223. int cnt = 0;
  1224. xs *list = user_queue(snac);
  1225. xs_list *p = list;
  1226. xs_str *fn;
  1227. while (xs_list_iter(&p, &fn)) {
  1228. xs *q_item = dequeue(fn);
  1229. if (q_item == NULL) {
  1230. snac_log(snac, xs_fmt("process_user_queue q_item error"));
  1231. continue;
  1232. }
  1233. process_user_queue_item(snac, q_item);
  1234. cnt++;
  1235. }
  1236. return cnt;
  1237. }
  1238. void process_queue_item(xs_dict *q_item)
  1239. /* processes an item from the global queue */
  1240. {
  1241. char *type = xs_dict_get(q_item, "type");
  1242. int queue_retry_max = xs_number_get(xs_dict_get(srv_config, "queue_retry_max"));
  1243. if (strcmp(type, "output") == 0) {
  1244. int status;
  1245. xs_str *inbox = xs_dict_get(q_item, "inbox");
  1246. xs_str *keyid = xs_dict_get(q_item, "keyid");
  1247. xs_str *seckey = xs_dict_get(q_item, "seckey");
  1248. xs_dict *msg = xs_dict_get(q_item, "message");
  1249. int retries = xs_number_get(xs_dict_get(q_item, "retries"));
  1250. xs *payload = NULL;
  1251. int p_size = 0;
  1252. if (xs_is_null(inbox) || xs_is_null(msg) || xs_is_null(keyid) || xs_is_null(seckey)) {
  1253. srv_log(xs_fmt("output message error: missing fields"));
  1254. return;
  1255. }
  1256. /* deliver */
  1257. status = send_to_inbox_raw(keyid, seckey, inbox, msg, &payload, &p_size, retries == 0 ? 3 : 8);
  1258. if (payload) {
  1259. if (p_size > 64) {
  1260. /* trim the message */
  1261. payload[64] = '\0';
  1262. payload = xs_str_cat(payload, "...");
  1263. }
  1264. /* strip ugly control characters */
  1265. payload = xs_replace_i(payload, "\n", "");
  1266. payload = xs_replace_i(payload, "\r", "");
  1267. if (*payload)
  1268. payload = xs_str_wrap_i(" [", payload, "]");
  1269. }
  1270. else
  1271. payload = xs_str_new(NULL);
  1272. srv_log(xs_fmt("output message: sent to inbox %s %d%s", inbox, status, payload));
  1273. if (!valid_status(status)) {
  1274. retries++;
  1275. /* error sending; requeue? */
  1276. if (status == 404 || status == 410)
  1277. /* explicit error: discard */
  1278. srv_log(xs_fmt("output message: fatal error %s %d", inbox, status));
  1279. else
  1280. if (retries > queue_retry_max)
  1281. srv_log(xs_fmt("output message: giving up %s %d", inbox, status));
  1282. else {
  1283. /* requeue */
  1284. enqueue_output_raw(keyid, seckey, msg, inbox, retries);
  1285. srv_log(xs_fmt("output message: requeue %s #%d", inbox, retries));
  1286. }
  1287. }
  1288. }
  1289. else
  1290. if (strcmp(type, "email") == 0) {
  1291. /* send this email */
  1292. xs_str *msg = xs_dict_get(q_item, "message");
  1293. int retries = xs_number_get(xs_dict_get(q_item, "retries"));
  1294. if (!send_email(msg))
  1295. srv_debug(1, xs_fmt("email message sent"));
  1296. else {
  1297. retries++;
  1298. if (retries > queue_retry_max)
  1299. srv_log(xs_fmt("email giving up (errno: %d)", errno));
  1300. else {
  1301. /* requeue */
  1302. srv_log(xs_fmt(
  1303. "email requeue #%d (errno: %d)", retries, errno));
  1304. enqueue_email(msg, retries);
  1305. }
  1306. }
  1307. }
  1308. else
  1309. if (strcmp(type, "telegram") == 0) {
  1310. /* send this via telegram */
  1311. char *bot = xs_dict_get(q_item, "bot");
  1312. char *msg = xs_dict_get(q_item, "message");
  1313. xs *chat_id = xs_dup(xs_dict_get(q_item, "chat_id"));
  1314. int status = 0;
  1315. /* chat_id must start with a - */
  1316. if (!xs_startswith(chat_id, "-"))
  1317. chat_id = xs_str_wrap_i("-", chat_id, NULL);
  1318. xs *url = xs_fmt("https:/" "/api.telegram.org/bot%s/sendMessage", bot);
  1319. xs *body = xs_fmt("{\"chat_id\":%s,\"text\":\"%s\"}", chat_id, msg);
  1320. xs *headers = xs_dict_new();
  1321. headers = xs_dict_append(headers, "content-type", "application/json");
  1322. xs *rsp = xs_http_request("POST", url, headers,
  1323. body, strlen(body), &status, NULL, NULL, 0);
  1324. rsp = xs_free(rsp);
  1325. srv_debug(0, xs_fmt("telegram post %d", status));
  1326. }
  1327. else
  1328. if (strcmp(type, "purge") == 0) {
  1329. srv_log(xs_dup("purge start"));
  1330. purge_all();
  1331. srv_log(xs_dup("purge end"));
  1332. }
  1333. else
  1334. srv_log(xs_fmt("unexpected q_item type '%s'", type));
  1335. }
  1336. int process_queue(void)
  1337. /* processes the global queue */
  1338. {
  1339. int cnt = 0;
  1340. xs *list = queue();
  1341. xs_list *p = list;
  1342. xs_str *fn;
  1343. while (xs_list_iter(&p, &fn)) {
  1344. xs *q_item = dequeue(fn);
  1345. if (q_item != NULL) {
  1346. job_post(q_item, 0);
  1347. cnt++;
  1348. }
  1349. }
  1350. return cnt;
  1351. }
  1352. /** HTTP handlers */
  1353. int activitypub_get_handler(const xs_dict *req, const char *q_path,
  1354. char **body, int *b_size, char **ctype)
  1355. {
  1356. int status = 200;
  1357. char *accept = xs_dict_get(req, "accept");
  1358. snac snac;
  1359. xs *msg = NULL;
  1360. if (accept == NULL)
  1361. return 0;
  1362. if (xs_str_in(accept, "application/activity+json") == -1 &&
  1363. xs_str_in(accept, "application/ld+json") == -1)
  1364. return 0;
  1365. xs *l = xs_split_n(q_path, "/", 2);
  1366. char *uid, *p_path;
  1367. uid = xs_list_get(l, 1);
  1368. if (!user_open(&snac, uid)) {
  1369. /* invalid user */
  1370. srv_debug(1, xs_fmt("activitypub_get_handler bad user %s", uid));
  1371. return 404;
  1372. }
  1373. p_path = xs_list_get(l, 2);
  1374. *ctype = "application/activity+json";
  1375. if (p_path == NULL) {
  1376. /* if there was no component after the user, it's an actor request */
  1377. msg = msg_actor(&snac);
  1378. *ctype = "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"";
  1379. char *ua = xs_dict_get(req, "user-agent");
  1380. snac_debug(&snac, 0, xs_fmt("serving actor [%s]", ua ? ua : "No UA"));
  1381. }
  1382. else
  1383. if (strcmp(p_path, "outbox") == 0) {
  1384. xs *id = xs_fmt("%s/outbox", snac.actor);
  1385. xs *elems = timeline_simple_list(&snac, "public", 0, 20);
  1386. xs *list = xs_list_new();
  1387. msg = msg_collection(&snac, id);
  1388. char *p, *v;
  1389. p = elems;
  1390. while (xs_list_iter(&p, &v)) {
  1391. xs *i = NULL;
  1392. if (valid_status(object_get_by_md5(v, &i))) {
  1393. char *type = xs_dict_get(i, "type");
  1394. char *id = xs_dict_get(i, "id");
  1395. if (type && id && strcmp(type, "Note") == 0 && xs_startswith(id, snac.actor)) {
  1396. i = xs_dict_del(i, "_snac");
  1397. list = xs_list_append(list, i);
  1398. }
  1399. }
  1400. }
  1401. /* replace the 'orderedItems' with the latest posts */
  1402. xs *items = xs_number_new(xs_list_len(list));
  1403. msg = xs_dict_set(msg, "orderedItems", list);
  1404. msg = xs_dict_set(msg, "totalItems", items);
  1405. }
  1406. else
  1407. if (strcmp(p_path, "followers") == 0 || strcmp(p_path, "following") == 0) {
  1408. xs *id = xs_fmt("%s/%s", snac.actor, p_path);
  1409. msg = msg_collection(&snac, id);
  1410. }
  1411. else
  1412. if (xs_startswith(p_path, "p/")) {
  1413. xs *id = xs_fmt("%s/%s", snac.actor, p_path);
  1414. status = object_get(id, &msg);
  1415. }
  1416. else
  1417. status = 404;
  1418. if (status == 200 && msg != NULL) {
  1419. *body = xs_json_dumps_pp(msg, 4);
  1420. *b_size = strlen(*body);
  1421. }
  1422. snac_debug(&snac, 1, xs_fmt("activitypub_get_handler serving %s %d", q_path, status));
  1423. user_free(&snac);
  1424. return status;
  1425. }
  1426. int activitypub_post_handler(const xs_dict *req, const char *q_path,
  1427. char *payload, int p_size,
  1428. char **body, int *b_size, char **ctype)
  1429. /* processes an input message */
  1430. {
  1431. (void)b_size;
  1432. int status = 202; /* accepted */
  1433. char *i_ctype = xs_dict_get(req, "content-type");
  1434. snac snac;
  1435. char *v;
  1436. if (i_ctype == NULL) {
  1437. *body = xs_str_new("no content-type");
  1438. *ctype = "text/plain";
  1439. return 400;
  1440. }
  1441. if (xs_str_in(i_ctype, "application/activity+json") == -1 &&
  1442. xs_str_in(i_ctype, "application/ld+json") == -1)
  1443. return 0;
  1444. /* decode the message */
  1445. xs *msg = xs_json_loads(payload);
  1446. if (msg == NULL) {
  1447. srv_log(xs_fmt("activitypub_post_handler JSON error %s", q_path));
  1448. *body = xs_str_new("JSON error");
  1449. *ctype = "text/plain";
  1450. status = 400;
  1451. }
  1452. /* get the user and path */
  1453. xs *l = xs_split_n(q_path, "/", 2);
  1454. char *uid;
  1455. if (xs_list_len(l) != 3 || strcmp(xs_list_get(l, 2), "inbox") != 0) {
  1456. /* strange q_path */
  1457. srv_debug(1, xs_fmt("activitypub_post_handler unsupported path %s", q_path));
  1458. return 404;
  1459. }
  1460. uid = xs_list_get(l, 1);
  1461. if (!user_open(&snac, uid)) {
  1462. /* invalid user */
  1463. srv_debug(1, xs_fmt("activitypub_post_handler bad user %s", uid));
  1464. return 404;
  1465. }
  1466. /* if it has a digest, check it now, because
  1467. later the payload won't be exactly the same */
  1468. if ((v = xs_dict_get(req, "digest")) != NULL) {
  1469. xs *s1 = xs_sha256_base64(payload, p_size);
  1470. xs *s2 = xs_fmt("SHA-256=%s", s1);
  1471. if (strcmp(s2, v) != 0) {
  1472. srv_log(xs_fmt("digest check FAILED"));
  1473. *body = xs_str_new("bad digest");
  1474. *ctype = "text/plain";
  1475. status = 400;
  1476. }
  1477. }
  1478. /* if the message is from a muted actor, reject it right now */
  1479. if (!xs_is_null(v = xs_dict_get(msg, "actor")) && *v) {
  1480. if (is_muted(&snac, v)) {
  1481. snac_log(&snac, xs_fmt("rejected message from MUTEd actor %s", v));
  1482. *body = xs_str_new("rejected");
  1483. *ctype = "text/plain";
  1484. status = 403;
  1485. }
  1486. }
  1487. if (valid_status(status)) {
  1488. enqueue_input(&snac, msg, req, 0);
  1489. *ctype = "application/activity+json";
  1490. }
  1491. user_free(&snac);
  1492. return status;
  1493. }