activitypub.c 42 KB

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