utils.c 16 KB

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