2.54 utils.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_io.h"
  6#include "xs_json.h"
  7#include "xs_time.h"
  8#include "xs_openssl.h"
  9#include "xs_random.h"
 10#include "xs_glob.h"
 11#include "xs_curl.h"
 12#include "xs_regex.h"
 13
 14#include "snac.h"
 15
 16#include <sys/stat.h>
 17#include <stdlib.h>
 18
 19static const char *default_srv_config = "{"
 20    "\"host\":                 \"\","
 21    "\"prefix\":               \"\","
 22    "\"address\":              \"127.0.0.1\","
 23    "\"port\":                 8001,"
 24    "\"layout\":               0.0,"
 25    "\"dbglevel\":             0,"
 26    "\"queue_retry_minutes\":  2,"
 27    "\"queue_retry_max\":      10,"
 28    "\"queue_timeout\":        6,"
 29    "\"queue_timeout_2\":      8,"
 30    "\"cssurls\":              [\"\"],"
 31    "\"max_timeline_entries\": 50,"
 32    "\"timeline_purge_days\":  120,"
 33    "\"local_purge_days\":     0,"
 34    "\"min_account_age\":      0,"
 35    "\"admin_email\":          \"\","
 36    "\"admin_account\":        \"\","
 37    "\"title\":                \"\","
 38    "\"short_description\":    \"\","
 39    "\"protocol\":             \"https\","
 40    "\"fastcgi\":              false"
 41    "}";
 42
 43static const char *default_css =
 44    "body { max-width: 48em; margin: auto; line-height: 1.5; padding: 0.8em; word-wrap: break-word; }\n"
 45    "pre { overflow-x: scroll; }\n"
 46    ".snac-embedded-video, img { max-width: 100% }\n"
 47    ".snac-origin { font-size: 85% }\n"
 48    ".snac-score { float: right; font-size: 85% }\n"
 49    ".snac-top-user { text-align: center; padding-bottom: 2em }\n"
 50    ".snac-top-user-name { font-size: 200% }\n"
 51    ".snac-top-user-id { font-size: 150% }\n"
 52    ".snac-announcement { border: black 1px solid; padding: 0.5em }\n"
 53    ".snac-avatar { float: left; height: 2.5em; width: 2.5em; padding: 0.25em }\n"
 54    ".snac-author { font-size: 90%; text-decoration: none }\n"
 55    ".snac-author-tag { font-size: 80% }\n"
 56    ".snac-pubdate { color: #a0a0a0; font-size: 90% }\n"
 57    ".snac-top-controls { padding-bottom: 1.5em }\n"
 58    ".snac-post { border-top: 1px solid #a0a0a0; }\n"
 59    ".snac-children { padding-left: 1em; border-left: 1px solid #a0a0a0; }\n"
 60    ".snac-textarea { font-family: inherit; width: 100% }\n"
 61    ".snac-history { border: 1px solid #606060; border-radius: 3px; margin: 2.5em 0; padding: 0 2em }\n"
 62    ".snac-btn-mute { float: right; margin-left: 0.5em }\n"
 63    ".snac-btn-unmute { float: right; margin-left: 0.5em }\n"
 64    ".snac-btn-follow { float: right; margin-left: 0.5em }\n"
 65    ".snac-btn-unfollow { float: right; margin-left: 0.5em }\n"
 66    ".snac-btn-hide { float: right; margin-left: 0.5em }\n"
 67    ".snac-btn-delete { float: right; margin-left: 0.5em }\n"
 68    ".snac-btn-limit { float: right; margin-left: 0.5em }\n"
 69    ".snac-btn-unlimit { float: right; margin-left: 0.5em }\n"
 70    ".snac-footer { margin-top: 2em; font-size: 75% }\n"
 71    ".snac-poll-result { margin-left: auto; margin-right: auto; }\n"
 72    "@media (prefers-color-scheme: dark) { \n"
 73    "  body, input, textarea { background-color: #000; color: #fff; }\n"
 74    "  a { color: #7799dd }\n"
 75    "  a:visited { color: #aa99dd }\n"
 76    "}\n"
 77;
 78
 79const char *snac_blurb =
 80    "<p><b>%host%</b> is a <a href=\"https:/"
 81    "/en.wikipedia.org/wiki/Fediverse\">Fediverse</a> "
 82    "instance that uses the <a href=\"https:/"
 83    "/en.wikipedia.org/wiki/ActivityPub\">ActivityPub</a> "
 84    "protocol. In other words, users at this host can communicate with people "
 85    "that use software like Mastodon, Pleroma, Friendica, etc. "
 86    "all around the world.</p>\n"
 87    "<p>This server runs the "
 88    "<a href=\"" WHAT_IS_SNAC_URL "\">snac</a> software and there is no "
 89    "automatic sign-up process.</p>\n"
 90;
 91
 92static const char *greeting_html =
 93    "<!DOCTYPE html>\n"
 94    "<html><head>\n"
 95    "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n"
 96    "<link rel=\"icon\" type=\"image/x-icon\" href=\"https://%host%/favicon.ico\"/>\n"
 97    "<title>Welcome to %host%</title>\n"
 98    "<body style=\"margin: auto; max-width: 50em\">\n"
 99    "%blurb%"
100    "<p>The following users are part of this community:</p>\n"
101    "\n"
102    "%userlist%\n"
103    "\n"
104    "<p>This site is powered by <abbr title=\"Social Networks Are Crap\">snac</abbr>.</p>\n"
105    "</body></html>\n";
106
107int snac_init(const char *basedir)
108{
109    FILE *f;
110
111    if (basedir == NULL) {
112        printf("Base directory: "); fflush(stdout);
113        srv_basedir = xs_strip_i(xs_readline(stdin));
114    }
115    else
116        srv_basedir = xs_str_new(basedir);
117
118    if (srv_basedir == NULL || *srv_basedir == '\0')
119        return 1;
120
121    if (xs_endswith(srv_basedir, "/"))
122        srv_basedir = xs_crop_i(srv_basedir, 0, -1);
123
124    if (mtime(srv_basedir) != 0.0) {
125        printf("ERROR: directory '%s' must not exist.\n", srv_basedir);
126        return 1;
127    }
128
129    srv_config = xs_json_loads(default_srv_config);
130
131    xs *layout = xs_number_new(disk_layout);
132    srv_config = xs_dict_set(srv_config, "layout", layout);
133
134    printf("Network address [%s]: ", xs_dict_get(srv_config, "address")); fflush(stdout);
135    {
136        xs *i = xs_strip_i(xs_readline(stdin));
137        if (*i)
138            srv_config = xs_dict_set(srv_config, "address", i);
139    }
140
141    printf("Network port [%d]: ", (int)xs_number_get(xs_dict_get(srv_config, "port"))); fflush(stdout);
142    {
143        xs *i = xs_strip_i(xs_readline(stdin));
144        if (*i) {
145            xs *n = xs_number_new(atoi(i));
146            srv_config = xs_dict_set(srv_config, "port", n);
147        }
148    }
149
150    printf("Host name: "); fflush(stdout);
151    {
152        xs *i = xs_strip_i(xs_readline(stdin));
153        if (*i == '\0')
154            return 1;
155
156        srv_config = xs_dict_set(srv_config, "host", i);
157    }
158
159    printf("URL prefix: "); fflush(stdout);
160    {
161        xs *i = xs_strip_i(xs_readline(stdin));
162
163        if (*i) {
164            if (xs_endswith(i, "/"))
165                i = xs_crop_i(i, 0, -1);
166
167            srv_config = xs_dict_set(srv_config, "prefix", i);
168        }
169    }
170
171    printf("Admin email address (optional): "); fflush(stdout);
172    {
173        xs *i = xs_strip_i(xs_readline(stdin));
174
175        srv_config = xs_dict_set(srv_config, "admin_email", i);
176    }
177
178    if (mkdirx(srv_basedir) == -1) {
179        printf("ERROR: cannot create directory '%s'\n", srv_basedir);
180        return 1;
181    }
182
183    xs *udir = xs_fmt("%s/user", srv_basedir);
184    mkdirx(udir);
185
186    xs *odir = xs_fmt("%s/object", srv_basedir);
187    mkdirx(odir);
188
189    xs *qdir = xs_fmt("%s/queue", srv_basedir);
190    mkdirx(qdir);
191
192    xs *ibdir = xs_fmt("%s/inbox", srv_basedir);
193    mkdirx(ibdir);
194
195    xs *gfn = xs_fmt("%s/greeting.html", srv_basedir);
196    if ((f = fopen(gfn, "w")) == NULL) {
197        printf("ERROR: cannot create '%s'\n", gfn);
198        return 1;
199    }
200
201    xs *gh = xs_replace(greeting_html, "%blurb%", snac_blurb);
202    fwrite(gh, strlen(gh), 1, f);
203    fclose(f);
204
205    xs *sfn = xs_fmt("%s/style.css", srv_basedir);
206    if ((f = fopen(sfn, "w")) == NULL) {
207        printf("ERROR: cannot create '%s'\n", sfn);
208        return 1;
209    }
210
211    fwrite(default_css, strlen(default_css), 1, f);
212    fclose(f);
213
214    xs *cfn = xs_fmt("%s/server.json", srv_basedir);
215    if ((f = fopen(cfn, "w")) == NULL) {
216        printf("ERROR: cannot create '%s'\n", cfn);
217        return 1;
218    }
219
220    xs_json_dump(srv_config, 4, f);
221    fclose(f);
222
223    printf("Done.\n");
224    return 0;
225}
226
227
228void new_password(const char *uid, xs_str **clear_pwd, xs_str **hashed_pwd)
229/* creates a random password */
230{
231    int rndbuf[3];
232
233    xs_rnd_buf(rndbuf, sizeof(rndbuf));
234
235    *clear_pwd  = xs_base64_enc((char *)rndbuf, sizeof(rndbuf));
236    *hashed_pwd = hash_password(uid, *clear_pwd, NULL);
237}
238
239
240int adduser(const char *uid)
241/* creates a new user */
242{
243    snac snac;
244    xs *config = xs_dict_new();
245    xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
246    xs *pwd = NULL;
247    xs *pwd_f = NULL;
248    xs *key = NULL;
249    FILE *f;
250
251    if (uid == NULL) {
252        printf("Username: "); fflush(stdout);
253        uid = xs_strip_i(xs_readline(stdin));
254    }
255
256    if (!validate_uid(uid)) {
257        printf("ERROR: only alphanumeric characters and _ are allowed in user ids.\n");
258        return 1;
259    }
260
261    if (user_open(&snac, uid)) {
262        printf("ERROR: user '%s' already exists\n", snac.uid);
263        return 1;
264    }
265
266    new_password(uid, &pwd, &pwd_f);
267
268    config = xs_dict_append(config, "uid",       uid);
269    config = xs_dict_append(config, "name",      uid);
270    config = xs_dict_append(config, "avatar",    "");
271    config = xs_dict_append(config, "bio",       "");
272    config = xs_dict_append(config, "cw",        "");
273    config = xs_dict_append(config, "published", date);
274    config = xs_dict_append(config, "passwd",    pwd_f);
275
276    xs *basedir = xs_fmt("%s/user/%s", srv_basedir, uid);
277
278    if (mkdirx(basedir) == -1) {
279        printf("ERROR: cannot create directory '%s'\n", basedir);
280        return 0;
281    }
282
283    const char *dirs[] = {
284        "followers", "following", "muted", "hidden",
285        "public", "private", "queue", "history",
286        "static", NULL };
287    int n;
288
289    for (n = 0; dirs[n]; n++) {
290        xs *d = xs_fmt("%s/%s", basedir, dirs[n]);
291        mkdirx(d);
292    }
293
294    xs *cfn = xs_fmt("%s/user.json", basedir);
295
296    if ((f = fopen(cfn, "w")) == NULL) {
297        printf("ERROR: cannot create '%s'\n", cfn);
298        return 1;
299    }
300    else {
301        xs_json_dump(config, 4, f);
302        fclose(f);
303    }
304
305    printf("\nCreating RSA key...\n");
306    key = xs_evp_genkey(4096);
307    printf("Done.\n");
308
309    xs *kfn = xs_fmt("%s/key.json", basedir);
310
311    if ((f = fopen(kfn, "w")) == NULL) {
312        printf("ERROR: cannot create '%s'\n", kfn);
313        return 1;
314    }
315    else {
316        xs_json_dump(key, 4, f);
317        fclose(f);
318    }
319
320    printf("\nUser password is %s\n", pwd);
321
322    printf("\nGo to %s/%s and continue configuring your user there.\n", srv_baseurl, uid);
323
324    return 0;
325}
326
327
328int resetpwd(snac *snac)
329/* creates a new password for the user */
330{
331    xs *clear_pwd  = NULL;
332    xs *hashed_pwd = NULL;
333    xs *fn         = xs_fmt("%s/user.json", snac->basedir);
334    FILE *f;
335    int ret = 0;
336
337    new_password(snac->uid, &clear_pwd, &hashed_pwd);
338
339    snac->config = xs_dict_set(snac->config, "passwd", hashed_pwd);
340
341    if ((f = fopen(fn, "w")) != NULL) {
342        xs_json_dump(snac->config, 4, f);
343        fclose(f);
344
345        printf("New password for user %s is %s\n", snac->uid, clear_pwd);
346    }
347    else {
348        printf("ERROR: cannot write to %s\n", fn);
349        ret = 1;
350    }
351
352    return ret;
353}
354
355
356void rm_rf(const char *dir)
357/* does an rm -rf (yes, I'm also scared) */
358{
359    xs *d = xs_str_cat(xs_dup(dir), "/" "*");
360    xs *l = xs_glob(d, 0, 0);
361    xs_list *p = l;
362    const xs_str *v;
363
364    if (dbglevel >= 1)
365        printf("Deleting directory %s\n", dir);
366
367    while (xs_list_iter(&p, &v)) {
368        struct stat st;
369
370        if (stat(v, &st) != -1) {
371            if (st.st_mode & S_IFDIR) {
372                rm_rf(v);
373            }
374            else {
375                if (dbglevel >= 1)
376                    printf("Deleting file %s\n", v);
377
378                if (unlink(v) == -1)
379                    printf("ERROR: cannot delete file %s\n", v);
380            }
381        }
382        else
383            printf("ERROR: stat() fail for %s\n", v);
384    }
385
386    if (rmdir(dir) == -1)
387        printf("ERROR: cannot delete directory %s\n", dir);
388}
389
390
391int deluser(snac *user)
392/* deletes a user */
393{
394    int ret = 0;
395    xs *fwers = following_list(user);
396    xs_list *p = fwers;
397    const xs_str *v;
398
399    while (xs_list_iter(&p, &v)) {
400        xs *object = NULL;
401
402        if (valid_status(following_get(user, v, &object))) {
403            xs *msg = msg_undo(user, xs_dict_get(object, "object"));
404
405            following_del(user, v);
406
407            enqueue_output_by_actor(user, msg, v, 0);
408
409            printf("Unfollowing actor %s\n", v);
410        }
411    }
412
413    rm_rf(user->basedir);
414
415    return ret;
416}
417
418
419void verify_links(snac *user)
420/* verifies a user's links */
421{
422    const xs_dict *p = xs_dict_get(user->config, "metadata");
423    const char *k, *v;
424    int changed = 0;
425
426    xs *headers = xs_dict_new();
427    headers = xs_dict_append(headers, "accept", "text/html");
428    headers = xs_dict_append(headers, "user-agent", USER_AGENT " (link verify)");
429
430    int c = 0;
431    while (p && xs_dict_next(p, &k, &v, &c)) {
432        /* not an https link? skip */
433        if (!xs_startswith(v, "https:/" "/"))
434            continue;
435
436        int status;
437        xs *req = NULL;
438        xs *payload = NULL;
439        int p_size = 0;
440
441        req = xs_http_request("GET", v, headers, NULL, 0, &status,
442            &payload, &p_size, 0);
443
444        if (!valid_status(status)) {
445            snac_log(user, xs_fmt("link %s verify error %d", v, status));
446            continue;
447        }
448
449        /* extract the links */
450        xs *ls = xs_regex_select(payload, "< *(a|link) +[^>]+>");
451
452        xs_list *lp = ls;
453        const char *ll;
454        int vfied = 0;
455
456        while (!vfied && xs_list_iter(&lp, &ll)) {
457            /* extract href and rel */
458            xs *r = xs_regex_select(ll, "(href|rel) *= *(\"[^\"]*\"|'[^']*')");
459
460            /* must have both attributes */
461            if (xs_list_len(r) != 2)
462                continue;
463
464            xs *href = NULL;
465            int is_rel_me = 0;
466            xs_list *pr = r;
467            const char *ar;
468
469            while (xs_list_iter(&pr, &ar)) {
470                xs *nq = xs_dup(ar);
471
472                nq = xs_replace_i(nq, "\"", "");
473                nq = xs_replace_i(nq, "'", "");
474
475                xs *r2 = xs_split_n(nq, "=", 1);
476                if (xs_list_len(r2) != 2)
477                    continue;
478
479                xs *ak = xs_strip_i(xs_dup(xs_list_get(r2, 0)));
480                xs *av = xs_strip_i(xs_dup(xs_list_get(r2, 1)));
481
482                if (strcmp(ak, "href") == 0)
483                    href = xs_dup(av);
484                else
485                if (strcmp(ak, "rel") == 0) {
486                    /* split the value by spaces */
487                    xs *vbs = xs_split(av, " ");
488
489                    /* is any of it "me"? */
490                    if (xs_list_in(vbs, "me") != -1)
491                        is_rel_me = 1;
492                }
493            }
494
495            /* after all this acrobatics, do we have an href and a rel="me"? */
496            if (href != NULL && is_rel_me) {
497                /* is it the same as the actor? */
498                if (strcmp(href, user->actor) == 0) {
499                    /* got it! */
500                    xs *verified_time = xs_number_new((double)time(NULL));
501
502                    if (user->links == NULL)
503                        user->links = xs_dict_new();
504
505                    user->links = xs_dict_set(user->links, v, verified_time);
506
507                    vfied = 1;
508                }
509                else
510                    snac_debug(user, 1,
511                        xs_fmt("verify link %s rel='me' found but not related (%s)", v, href));
512            }
513        }
514
515        if (vfied) {
516            changed++;
517            snac_log(user, xs_fmt("link %s verified", v));
518        }
519        else {
520            snac_log(user, xs_fmt("link %s not verified (rel='me' not found)", v));
521        }
522    }
523
524    if (changed) {
525        FILE *f;
526
527        /* update the links.json file */
528        xs *fn = xs_fmt("%s/links.json", user->basedir);
529        xs *bfn = xs_fmt("%s.bak", fn);
530
531        rename(fn, bfn);
532
533        if ((f = fopen(fn, "w")) != NULL) {
534            xs_json_dump(user->links, 4, f);
535            fclose(f);
536        }
537        else
538            rename(bfn, fn);
539    }
540}