2.57
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 int is_unix_socket = 0;
135
136 printf("Network address or full path to unix socket [%s]: ", xs_dict_get(srv_config, "address")); fflush(stdout);
137 {
138 xs *i = xs_strip_i(xs_readline(stdin));
139 if (*i) {
140 srv_config = xs_dict_set(srv_config, "address", i);
141
142 if (*i == '/')
143 is_unix_socket = 1;
144 }
145 }
146
147 if (!is_unix_socket) {
148 printf("Network port [%d]: ", (int)xs_number_get(xs_dict_get(srv_config, "port"))); fflush(stdout);
149 {
150 xs *i = xs_strip_i(xs_readline(stdin));
151 if (*i) {
152 xs *n = xs_number_new(atoi(i));
153 srv_config = xs_dict_set(srv_config, "port", n);
154 }
155 }
156 }
157 else {
158 xs *n = xs_number_new(0);
159 srv_config = xs_dict_set(srv_config, "port", n);
160 }
161
162 printf("Host name: "); fflush(stdout);
163 {
164 xs *i = xs_strip_i(xs_readline(stdin));
165 if (*i == '\0')
166 return 1;
167
168 srv_config = xs_dict_set(srv_config, "host", i);
169 }
170
171 printf("URL prefix: "); fflush(stdout);
172 {
173 xs *i = xs_strip_i(xs_readline(stdin));
174
175 if (*i) {
176 if (xs_endswith(i, "/"))
177 i = xs_crop_i(i, 0, -1);
178
179 srv_config = xs_dict_set(srv_config, "prefix", i);
180 }
181 }
182
183 printf("Admin email address (optional): "); fflush(stdout);
184 {
185 xs *i = xs_strip_i(xs_readline(stdin));
186
187 srv_config = xs_dict_set(srv_config, "admin_email", i);
188 }
189
190 if (mkdirx(srv_basedir) == -1) {
191 printf("ERROR: cannot create directory '%s'\n", srv_basedir);
192 return 1;
193 }
194
195 xs *udir = xs_fmt("%s/user", srv_basedir);
196 mkdirx(udir);
197
198 xs *odir = xs_fmt("%s/object", srv_basedir);
199 mkdirx(odir);
200
201 xs *qdir = xs_fmt("%s/queue", srv_basedir);
202 mkdirx(qdir);
203
204 xs *ibdir = xs_fmt("%s/inbox", srv_basedir);
205 mkdirx(ibdir);
206
207 xs *gfn = xs_fmt("%s/greeting.html", srv_basedir);
208 if ((f = fopen(gfn, "w")) == NULL) {
209 printf("ERROR: cannot create '%s'\n", gfn);
210 return 1;
211 }
212
213 xs *gh = xs_replace(greeting_html, "%blurb%", snac_blurb);
214 fwrite(gh, strlen(gh), 1, f);
215 fclose(f);
216
217 xs *sfn = xs_fmt("%s/style.css", srv_basedir);
218 if ((f = fopen(sfn, "w")) == NULL) {
219 printf("ERROR: cannot create '%s'\n", sfn);
220 return 1;
221 }
222
223 fwrite(default_css, strlen(default_css), 1, f);
224 fclose(f);
225
226 xs *cfn = xs_fmt("%s/server.json", srv_basedir);
227 if ((f = fopen(cfn, "w")) == NULL) {
228 printf("ERROR: cannot create '%s'\n", cfn);
229 return 1;
230 }
231
232 xs_json_dump(srv_config, 4, f);
233 fclose(f);
234
235 printf("Done.\n");
236 return 0;
237}
238
239
240void new_password(const char *uid, xs_str **clear_pwd, xs_str **hashed_pwd)
241/* creates a random password */
242{
243 int rndbuf[3];
244
245 xs_rnd_buf(rndbuf, sizeof(rndbuf));
246
247 *clear_pwd = xs_base64_enc((char *)rndbuf, sizeof(rndbuf));
248 *hashed_pwd = hash_password(uid, *clear_pwd, NULL);
249}
250
251
252int adduser(const char *uid)
253/* creates a new user */
254{
255 snac snac;
256 xs *config = xs_dict_new();
257 xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
258 xs *pwd = NULL;
259 xs *pwd_f = NULL;
260 xs *key = NULL;
261 FILE *f;
262
263 if (uid == NULL) {
264 printf("Username: "); fflush(stdout);
265 uid = xs_strip_i(xs_readline(stdin));
266 }
267
268 if (!validate_uid(uid)) {
269 printf("ERROR: only alphanumeric characters and _ are allowed in user ids.\n");
270 return 1;
271 }
272
273 if (user_open(&snac, uid)) {
274 printf("ERROR: user '%s' already exists\n", snac.uid);
275 return 1;
276 }
277
278 new_password(uid, &pwd, &pwd_f);
279
280 config = xs_dict_append(config, "uid", uid);
281 config = xs_dict_append(config, "name", uid);
282 config = xs_dict_append(config, "avatar", "");
283 config = xs_dict_append(config, "bio", "");
284 config = xs_dict_append(config, "cw", "");
285 config = xs_dict_append(config, "published", date);
286 config = xs_dict_append(config, "passwd", pwd_f);
287
288 xs *basedir = xs_fmt("%s/user/%s", srv_basedir, uid);
289
290 if (mkdirx(basedir) == -1) {
291 printf("ERROR: cannot create directory '%s'\n", basedir);
292 return 0;
293 }
294
295 const char *dirs[] = {
296 "followers", "following", "muted", "hidden",
297 "public", "private", "queue", "history",
298 "static", NULL };
299 int n;
300
301 for (n = 0; dirs[n]; n++) {
302 xs *d = xs_fmt("%s/%s", basedir, dirs[n]);
303 mkdirx(d);
304 }
305
306 xs *cfn = xs_fmt("%s/user.json", basedir);
307
308 if ((f = fopen(cfn, "w")) == NULL) {
309 printf("ERROR: cannot create '%s'\n", cfn);
310 return 1;
311 }
312 else {
313 xs_json_dump(config, 4, f);
314 fclose(f);
315 }
316
317 printf("\nCreating RSA key...\n");
318 key = xs_evp_genkey(4096);
319 printf("Done.\n");
320
321 xs *kfn = xs_fmt("%s/key.json", basedir);
322
323 if ((f = fopen(kfn, "w")) == NULL) {
324 printf("ERROR: cannot create '%s'\n", kfn);
325 return 1;
326 }
327 else {
328 xs_json_dump(key, 4, f);
329 fclose(f);
330 }
331
332 printf("\nUser password is %s\n", pwd);
333
334 printf("\nGo to %s/%s and continue configuring your user there.\n", srv_baseurl, uid);
335
336 return 0;
337}
338
339
340int resetpwd(snac *snac)
341/* creates a new password for the user */
342{
343 xs *clear_pwd = NULL;
344 xs *hashed_pwd = NULL;
345 xs *fn = xs_fmt("%s/user.json", snac->basedir);
346 FILE *f;
347 int ret = 0;
348
349 new_password(snac->uid, &clear_pwd, &hashed_pwd);
350
351 snac->config = xs_dict_set(snac->config, "passwd", hashed_pwd);
352
353 if ((f = fopen(fn, "w")) != NULL) {
354 xs_json_dump(snac->config, 4, f);
355 fclose(f);
356
357 printf("New password for user %s is %s\n", snac->uid, clear_pwd);
358 }
359 else {
360 printf("ERROR: cannot write to %s\n", fn);
361 ret = 1;
362 }
363
364 return ret;
365}
366
367
368void rm_rf(const char *dir)
369/* does an rm -rf (yes, I'm also scared) */
370{
371 xs *d = xs_str_cat(xs_dup(dir), "/" "*");
372 xs *l = xs_glob(d, 0, 0);
373 xs_list *p = l;
374 const xs_str *v;
375
376 if (dbglevel >= 1)
377 printf("Deleting directory %s\n", dir);
378
379 while (xs_list_iter(&p, &v)) {
380 struct stat st;
381
382 if (stat(v, &st) != -1) {
383 if (st.st_mode & S_IFDIR) {
384 rm_rf(v);
385 }
386 else {
387 if (dbglevel >= 1)
388 printf("Deleting file %s\n", v);
389
390 if (unlink(v) == -1)
391 printf("ERROR: cannot delete file %s\n", v);
392 }
393 }
394 else
395 printf("ERROR: stat() fail for %s\n", v);
396 }
397
398 if (rmdir(dir) == -1)
399 printf("ERROR: cannot delete directory %s\n", dir);
400}
401
402
403int deluser(snac *user)
404/* deletes a user */
405{
406 int ret = 0;
407 xs *fwers = following_list(user);
408 xs_list *p = fwers;
409 const xs_str *v;
410
411 while (xs_list_iter(&p, &v)) {
412 xs *object = NULL;
413
414 if (valid_status(following_get(user, v, &object))) {
415 xs *msg = msg_undo(user, xs_dict_get(object, "object"));
416
417 following_del(user, v);
418
419 enqueue_output_by_actor(user, msg, v, 0);
420
421 printf("Unfollowing actor %s\n", v);
422 }
423 }
424
425 rm_rf(user->basedir);
426
427 return ret;
428}
429
430
431void verify_links(snac *user)
432/* verifies a user's links */
433{
434 const xs_dict *p = xs_dict_get(user->config, "metadata");
435 const char *k, *v;
436 int changed = 0;
437
438 xs *headers = xs_dict_new();
439 headers = xs_dict_append(headers, "accept", "text/html");
440 headers = xs_dict_append(headers, "user-agent", USER_AGENT " (link verify)");
441
442 int c = 0;
443 while (p && xs_dict_next(p, &k, &v, &c)) {
444 /* not an https link? skip */
445 if (!xs_startswith(v, "https:/" "/"))
446 continue;
447
448 int status;
449 xs *req = NULL;
450 xs *payload = NULL;
451 int p_size = 0;
452
453 req = xs_http_request("GET", v, headers, NULL, 0, &status,
454 &payload, &p_size, 0);
455
456 if (!valid_status(status)) {
457 snac_log(user, xs_fmt("link %s verify error %d", v, status));
458 continue;
459 }
460
461 /* extract the links */
462 xs *ls = xs_regex_select(payload, "< *(a|link) +[^>]+>");
463
464 xs_list *lp = ls;
465 const char *ll;
466 int vfied = 0;
467
468 while (!vfied && xs_list_iter(&lp, &ll)) {
469 /* extract href and rel */
470 xs *r = xs_regex_select(ll, "(href|rel) *= *(\"[^\"]*\"|'[^']*')");
471
472 /* must have both attributes */
473 if (xs_list_len(r) != 2)
474 continue;
475
476 xs *href = NULL;
477 int is_rel_me = 0;
478 xs_list *pr = r;
479 const char *ar;
480
481 while (xs_list_iter(&pr, &ar)) {
482 xs *nq = xs_dup(ar);
483
484 nq = xs_replace_i(nq, "\"", "");
485 nq = xs_replace_i(nq, "'", "");
486
487 xs *r2 = xs_split_n(nq, "=", 1);
488 if (xs_list_len(r2) != 2)
489 continue;
490
491 xs *ak = xs_strip_i(xs_dup(xs_list_get(r2, 0)));
492 xs *av = xs_strip_i(xs_dup(xs_list_get(r2, 1)));
493
494 if (strcmp(ak, "href") == 0)
495 href = xs_dup(av);
496 else
497 if (strcmp(ak, "rel") == 0) {
498 /* split the value by spaces */
499 xs *vbs = xs_split(av, " ");
500
501 /* is any of it "me"? */
502 if (xs_list_in(vbs, "me") != -1)
503 is_rel_me = 1;
504 }
505 }
506
507 /* after all this acrobatics, do we have an href and a rel="me"? */
508 if (href != NULL && is_rel_me) {
509 /* is it the same as the actor? */
510 if (strcmp(href, user->actor) == 0) {
511 /* got it! */
512 xs *verified_time = xs_number_new((double)time(NULL));
513
514 if (user->links == NULL)
515 user->links = xs_dict_new();
516
517 user->links = xs_dict_set(user->links, v, verified_time);
518
519 vfied = 1;
520 }
521 else
522 snac_debug(user, 1,
523 xs_fmt("verify link %s rel='me' found but not related (%s)", v, href));
524 }
525 }
526
527 if (vfied) {
528 changed++;
529 snac_log(user, xs_fmt("link %s verified", v));
530 }
531 else {
532 snac_log(user, xs_fmt("link %s not verified (rel='me' not found)", v));
533 }
534 }
535
536 if (changed) {
537 FILE *f;
538
539 /* update the links.json file */
540 xs *fn = xs_fmt("%s/links.json", user->basedir);
541 xs *bfn = xs_fmt("%s.bak", fn);
542
543 rename(fn, bfn);
544
545 if ((f = fopen(fn, "w")) != NULL) {
546 xs_json_dump(user->links, 4, f);
547 fclose(f);
548 }
549 else
550 rename(bfn, fn);
551 }
552}