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