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