utils.c 16 KB

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