activitypub.c 55 KB

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