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