activitypub.c 71 KB

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