activitypub.c 45 KB

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