format.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 - 2026 grunfink et al. / MIT license */
  3. #include "xs.h"
  4. #include "xs_regex.h"
  5. #include "xs_mime.h"
  6. #include "xs_html.h"
  7. #include "xs_json.h"
  8. #include "xs_time.h"
  9. #include "xs_match.h"
  10. #include "xs_unicode.h"
  11. #include "snac.h"
  12. /* emoticons, people laughing and such */
  13. const char * const smileys[] = {
  14. ":-)", "🙂",
  15. ":-D", "😀",
  16. "X-D", "😆",
  17. ";-)", "😉",
  18. "B-)", "😎",
  19. ">:-(", "😡",
  20. ":-(", "😞",
  21. ":-*", "😘",
  22. ":-/", "😕",
  23. "8-o", "😲",
  24. "%-)", "🤪",
  25. ":_(", "😢",
  26. ":-|", "😐",
  27. "<3", "&#10084;&#65039;",
  28. ":facepalm:", "&#129318;",
  29. ":shrug:", "&#129335;",
  30. ":shrug2:", "&#175;\\_(&#12484;)_/&#175;",
  31. ":eyeroll:", "&#128580;",
  32. ":beer:", "&#127866;",
  33. ":beers:", "&#127867;",
  34. ":munch:", "&#128561;",
  35. ":thumb:", "&#128077;",
  36. NULL, NULL
  37. };
  38. xs_dict *emojis(void)
  39. /* returns a dict with the emojis */
  40. {
  41. xs *fn = xs_fmt("%s/emojis.json", srv_basedir);
  42. FILE *f;
  43. if (mtime(fn) == 0) {
  44. /* file does not exist; create it with the defaults */
  45. xs *d = xs_dict_new();
  46. const char * const *emo = smileys;
  47. while (*emo) {
  48. d = xs_dict_append(d, emo[0], emo[1]);
  49. emo += 2;
  50. }
  51. if ((f = fopen(fn, "w")) != NULL) {
  52. xs_json_dump(d, 4, f);
  53. fclose(f);
  54. }
  55. else
  56. srv_log(xs_fmt("Error creating '%s'", fn));
  57. }
  58. xs_dict *d = NULL;
  59. if ((f = fopen(fn, "r")) != NULL) {
  60. d = xs_json_load(f);
  61. fclose(f);
  62. if (d == NULL)
  63. srv_log(xs_fmt("JSON parse error in '%s'", fn));
  64. }
  65. else
  66. srv_log(xs_fmt("Error opening '%s'", fn));
  67. return d;
  68. }
  69. xs_dict *emojis_rm_categories(void) {
  70. xs *emjs = emojis();
  71. char *res = xs_dict_new();
  72. const char *k, *v;
  73. xs_dict_foreach(emjs, k, v) {
  74. if (xs_type(v) == XSTYPE_DICT) {
  75. const char *v2;
  76. xs_dict_foreach(v, k, v2)
  77. res = xs_dict_append(res, k, v2);
  78. }
  79. else
  80. res = xs_dict_append(res, k, v);
  81. }
  82. return res;
  83. }
  84. /* Non-whitespace without trailing comma, period or closing paren */
  85. #define NOSPACE "([^[:space:],.)]+|[,.)]+[^[:space:],.)])+"
  86. static xs_str *format_line(const char *line, xs_list **attach)
  87. /* formats a line */
  88. {
  89. xs_str *s = xs_str_new(NULL);
  90. char *p;
  91. const char *v;
  92. /* split by markup */
  93. xs *sm = xs_regex_split(line,
  94. "("
  95. "`[^`]+`" "|"
  96. "~~[^~]+~~" "|"
  97. "\\*\\*?\\*?[^\\*]+\\*?\\*?\\*" "|"
  98. "__[^_]+__" "|" //anzu
  99. "!\\[[^]]+\\]\\([^\\)]+\\)\\)?" "|"
  100. "\\[[^]]+\\]\\([^\\)]+\\)\\)?" "|"
  101. "[a-z]+:/" "/" NOSPACE "|"
  102. "(mailto|xmpp):[^@[:space:]]+@" NOSPACE
  103. ")");
  104. int n = 0;
  105. p = sm;
  106. while (xs_list_iter(&p, &v)) {
  107. if ((n & 0x1)) {
  108. /* markup */
  109. if (xs_startswith(v, "`")) {
  110. xs *s1 = xs_strip_chars_i(xs_dup(v), "`");
  111. xs *e1 = encode_html(s1);
  112. xs *s2 = xs_fmt("<code>%s</code>", e1);
  113. s = xs_str_cat(s, s2);
  114. }
  115. else
  116. if (xs_startswith(v, "***")) {
  117. xs *s1 = xs_strip_chars_i(xs_dup(v), "*");
  118. xs *s2 = xs_fmt("<b><i>%s</i></b>", s1);
  119. s = xs_str_cat(s, s2);
  120. }
  121. else
  122. if (xs_startswith(v, "**")) {
  123. xs *s1 = xs_strip_chars_i(xs_dup(v), "*");
  124. xs *s2 = xs_fmt("<b>%s</b>", s1);
  125. s = xs_str_cat(s, s2);
  126. }
  127. else
  128. if (xs_startswith(v, "*")) {
  129. xs *s1 = xs_strip_chars_i(xs_dup(v), "*");
  130. xs *s2 = xs_fmt("<i>%s</i>", s1);
  131. s = xs_str_cat(s, s2);
  132. }
  133. //anzu - begin
  134. else
  135. if (xs_startswith(v, "__")) {
  136. xs *s1 = xs_strip_chars_i(xs_dup(v), "_");
  137. xs *s2 = xs_fmt("<u>%s</u>", s1);
  138. s = xs_str_cat(s, s2);
  139. }
  140. //anzu - end
  141. else
  142. if (xs_startswith(v, "~~")) {
  143. xs *s1 = xs_strip_chars_i(xs_dup(v), "~");
  144. xs *e1 = encode_html(s1);
  145. xs *s2 = xs_fmt("<s>%s</s>", e1);
  146. s = xs_str_cat(s, s2);
  147. }
  148. else
  149. if (*v == '[') {
  150. /* markdown-like links [label](url) */
  151. xs *w = xs_replace_i(xs_replace(v, "#", "&#35;"), "@", "&#64;");
  152. xs *l = xs_split_n(w, "](", 1);
  153. if (xs_list_len(l) == 2) {
  154. xs *name = xs_dup(xs_list_get(l, 0));
  155. xs *url = xs_dup(xs_list_get(l, 1));
  156. name = xs_crop_i(name, 1, 0);
  157. url = xs_crop_i(url, 0, -1);
  158. xs *link = xs_fmt("<a href=\"%s\">%s</a>", url, name);
  159. s = xs_str_cat(s, link);
  160. }
  161. else
  162. s = xs_str_cat(s, v);
  163. }
  164. else
  165. if (*v == '!') {
  166. /* markdown-like images ![alt text](url to image) */
  167. xs *w = xs_replace_i(xs_replace(v, "#", "&#35;"), "@", "&#64;");
  168. xs *l = xs_split_n(w, "](", 1);
  169. if (xs_list_len(l) == 2) {
  170. xs *alt_text = xs_dup(xs_list_get(l, 0));
  171. xs *img_url = xs_dup(xs_list_get(l, 1));
  172. alt_text = xs_crop_i(alt_text, 2, 0);
  173. img_url = xs_crop_i(img_url, 0, -1);
  174. const char *mime = xs_mime_by_ext(img_url);
  175. if (attach != NULL && xs_startswith(mime, "image/")) {
  176. const xs_dict *ad;
  177. int add = 1;
  178. xs_list_foreach(*attach, ad) {
  179. if (strcmp(xs_dict_get_def(ad, "url", ""), img_url) == 0) {
  180. add = 0;
  181. break;
  182. }
  183. }
  184. if (add) {
  185. xs *d = xs_dict_new();
  186. d = xs_dict_append(d, "mediaType", mime);
  187. d = xs_dict_append(d, "url", img_url);
  188. d = xs_dict_append(d, "name", alt_text);
  189. d = xs_dict_append(d, "type", "Image");
  190. *attach = xs_list_append(*attach, d);
  191. }
  192. }
  193. else {
  194. xs *link = xs_fmt("<a href=\"%s\">%s</a>", img_url, alt_text);
  195. s = xs_str_cat(s, link);
  196. }
  197. }
  198. else
  199. s = xs_str_cat(s, v);
  200. }
  201. else
  202. if (xs_str_in(v, ":/" "/") != -1) {
  203. /* direct URLs in the post body */
  204. xs *u = xs_replace_i(xs_replace(v, "#", "&#35;"), "@", "&#64;");
  205. xs *v2 = xs_strip_chars_i(xs_dup(u), ".,)");
  206. const char *mime = xs_mime_by_ext(v2);
  207. if (attach != NULL && xs_startswith(mime, "image/")) {
  208. /* if it's a link to an image, insert it as an attachment */
  209. const xs_dict *ad;
  210. int add = 1;
  211. xs_list_foreach(*attach, ad) {
  212. if (strcmp(xs_dict_get_def(ad, "url", ""), v2) == 0) {
  213. add = 0;
  214. break;
  215. }
  216. }
  217. if (add) {
  218. xs *d = xs_dict_new();
  219. d = xs_dict_append(d, "mediaType", mime);
  220. d = xs_dict_append(d, "url", v2);
  221. d = xs_dict_append(d, "name", "");
  222. d = xs_dict_append(d, "type", "Image");
  223. *attach = xs_list_append(*attach, d);
  224. }
  225. }
  226. else {
  227. xs *s1 = xs_fmt("<a href=\"%s\" target=\"_blank\">%s</a>", v2, u);
  228. s = xs_str_cat(s, s1);
  229. }
  230. }
  231. else
  232. if (xs_match(v, "mailto*|xmpp*")) {
  233. xs *u = xs_replace_i(xs_replace(v, "#", "&#35;"), "@", "&#64;");
  234. xs *v2 = xs_strip_chars_i(xs_dup(u), ".,)");
  235. xs *s1 = xs_fmt("<a href=\"%s\" target=\"_blank\">%s</a>", v2, u);
  236. s = xs_str_cat(s, s1);
  237. }
  238. else
  239. s = xs_str_cat(s, v);
  240. }
  241. else
  242. /* surrounded text, copy directly */
  243. s = xs_str_cat(s, v);
  244. n++;
  245. }
  246. return s;
  247. }
  248. xs_str *not_really_markdown(const char *content, xs_list **attach, xs_list **tag)
  249. /* formats a content using some Markdown rules */
  250. {
  251. xs_str *s = xs_str_new(NULL);
  252. int in_pre = 0;
  253. int in_blq = 0;
  254. int in_ul = 0;
  255. xs *list;
  256. char *p;
  257. const char *v;
  258. /* work by lines */
  259. list = xs_split(content, "\n");
  260. p = list;
  261. while (xs_list_iter(&p, &v)) {
  262. xs *ss = NULL;
  263. if (strcmp(v, "```") == 0) {
  264. if (!in_pre)
  265. s = xs_str_cat(s, "<pre>");
  266. else
  267. s = xs_str_cat(s, "</pre>");
  268. in_pre = !in_pre;
  269. continue;
  270. }
  271. if (in_pre) {
  272. // Encode all HTML characters when we're in pre element until we are out.
  273. ss = encode_html(v);
  274. s = xs_str_cat(s, ss);
  275. s = xs_str_cat(s, "<br>");
  276. continue;
  277. }
  278. else
  279. ss = xs_strip_i(format_line(v, attach));
  280. if (xs_startswith(ss, "---")) {
  281. /* delete the --- */
  282. ss = xs_strip_i(xs_crop_i(ss, 3, 0));
  283. s = xs_str_cat(s, "<hr>");
  284. s = xs_str_cat(s, ss);
  285. continue;
  286. }
  287. //anzu - begin
  288. // h1 reserved for snac?
  289. if (xs_startswith(ss, "# ")) {
  290. ss = xs_strip_i(xs_crop_i(ss, 2, 0));
  291. s = xs_str_cat(s, "<h2>");
  292. s = xs_str_cat(s, ss);
  293. s = xs_str_cat(s, "</h2>");
  294. continue;
  295. }
  296. if (xs_startswith(ss, "## ")) {
  297. ss = xs_strip_i(xs_crop_i(ss, 3, 0));
  298. s = xs_str_cat(s, "<h2>");
  299. s = xs_str_cat(s, ss);
  300. s = xs_str_cat(s, "</h2>");
  301. continue;
  302. }
  303. if (xs_startswith(ss, "### ")) {
  304. ss = xs_strip_i(xs_crop_i(ss, 4, 0));
  305. s = xs_str_cat(s, "<h3>");
  306. s = xs_str_cat(s, ss);
  307. s = xs_str_cat(s, "</h3>");
  308. continue;
  309. }
  310. //anzu - end
  311. if (xs_startswith(ss, ">")) {
  312. /* delete the > and subsequent spaces */
  313. ss = xs_strip_i(xs_crop_i(ss, 1, 0));
  314. if (!in_blq) {
  315. s = xs_str_cat(s, "<blockquote>");
  316. in_blq = 1;
  317. }
  318. s = xs_str_cat(s, ss);
  319. s = xs_str_cat(s, "<br>");
  320. continue;
  321. }
  322. if (xs_startswith(ss, "* ") || xs_startswith(ss, "- ")) {
  323. /* unsorted list */
  324. ss = xs_strip_i(xs_crop_i(ss, 1, 0));
  325. if (!in_ul) {
  326. s = xs_str_cat(s, "<ul>");
  327. in_ul = 1;
  328. }
  329. s = xs_str_cat(s, "<li>", ss);
  330. continue;
  331. }
  332. if (in_blq) {
  333. s = xs_str_cat(s, "</blockquote>");
  334. in_blq = 0;
  335. }
  336. if (in_ul) {
  337. s = xs_str_cat(s, "</ul>");
  338. in_ul = 0;
  339. }
  340. s = xs_str_cat(s, ss);
  341. s = xs_str_cat(s, "<br>");
  342. }
  343. if (in_blq)
  344. s = xs_str_cat(s, "</blockquote>");
  345. if (in_pre)
  346. s = xs_str_cat(s, "</pre>");
  347. /* some beauty fixes */
  348. s = xs_replace_i(s, "<br><br><blockquote>", "<br><blockquote>");
  349. s = xs_replace_i(s, "</blockquote><br>", "</blockquote>");
  350. s = xs_replace_i(s, "</pre><br>", "</pre>");
  351. s = xs_replace_i(s, "</ul><br>", "</ul>");
  352. s = xs_replace_i(s, "</h2><br>", "</h2>"); //anzu ???
  353. s = xs_replace_i(s, "</h3><br>", "</h3>"); //anzu ???
  354. {
  355. /* traditional emoticons */
  356. xs *d = emojis_rm_categories();
  357. int c = 0;
  358. const char *k, *v;
  359. while (xs_dict_next(d, &k, &v, &c)) {
  360. const char *t = xs_mime_by_ext(v);
  361. /* is it an URL to an image? */
  362. if (xs_startswith(v, "https:/" "/") &&
  363. (xs_startswith(t, "image/") || strcmp(t, "application/octet-stream") == 0)) {
  364. if (tag && xs_str_in(s, k) != -1) {
  365. /* add the emoji to the tag list */
  366. xs *e = xs_dict_new();
  367. xs *i = xs_dict_new();
  368. xs *u = xs_str_utctime(0, ISO_DATE_SPEC);
  369. e = xs_dict_append(e, "id", v);
  370. e = xs_dict_append(e, "type", "Emoji");
  371. e = xs_dict_append(e, "name", k);
  372. e = xs_dict_append(e, "updated", u);
  373. i = xs_dict_append(i, "type", "Image");
  374. i = xs_dict_append(i, "mediaType", t);
  375. i = xs_dict_append(i, "url", v);
  376. e = xs_dict_append(e, "icon", i);
  377. *tag = xs_list_append(*tag, e);
  378. }
  379. }
  380. else
  381. s = xs_replace_i(s, k, v);
  382. }
  383. }
  384. return s;
  385. }
  386. const char * const valid_tags[] = {
  387. "a", "p", "br", "br/", "blockquote", "ul", "ol", "li", "cite", "small",
  388. "span", "i", "b", "u", "s", "pre", "code", "em", "strong", "hr", "img", "del", "bdi",
  389. "h2","h3", //anzu
  390. NULL
  391. };
  392. xs_str *sanitize(const char *content)
  393. /* cleans dangerous HTML output */
  394. {
  395. xs_str *s = xs_str_new(NULL);
  396. xs *sl;
  397. int n = 0;
  398. char *p;
  399. const char *v;
  400. if (!content)
  401. return NULL;
  402. sl = xs_regex_split(content, "</?[^>]+>");
  403. p = sl;
  404. n = 0;
  405. while (xs_list_iter(&p, &v)) {
  406. if (n & 0x1) {
  407. xs *s1 = xs_strip_i(xs_crop_i(xs_dup(v), v[1] == '/' ? 2 : 1, -1));
  408. xs *l1 = xs_split_n(s1, " ", 1);
  409. xs *tag = xs_utf8_to_lower(xs_list_get(l1, 0));
  410. xs *s2 = NULL;
  411. int i;
  412. /* check if it's one of the valid tags */
  413. for (i = 0; valid_tags[i]; i++) {
  414. if (strcmp(tag, valid_tags[i]) == 0)
  415. break;
  416. }
  417. if (valid_tags[i]) {
  418. /* accepted tag: rebuild it with only the accepted elements */
  419. xs *el = xs_regex_select(v, "(src|href|rel|class|target)=(\"[^\"]*\"|'[^']*')");
  420. xs *s3 = xs_join(el, " ");
  421. s2 = xs_fmt("<%s%s%s%s>",
  422. v[1] == '/' ? "/" : "", tag, xs_list_len(el) ? " " : "", s3);
  423. s = xs_str_cat(s, s2);
  424. } else {
  425. /* treat end of divs as paragraph breaks */
  426. if (strcmp(v, "</div>"))
  427. s = xs_str_cat(s, "<p>");
  428. }
  429. }
  430. else {
  431. /* non-tag */
  432. s = xs_str_cat(s, v);
  433. }
  434. n++;
  435. }
  436. return s;
  437. }
  438. xs_str *encode_html(const char *str)
  439. /* escapes html characters */
  440. {
  441. xs_str *encoded = xs_html_encode((char *)str);
  442. /* Restore only <br>. Probably safe. Let's hope nothing goes wrong with this. */
  443. encoded = xs_replace_i(encoded, "&lt;br&gt;", "<br>");
  444. return encoded;
  445. }