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