utils.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 - 2025 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. "\"def_timeline_entries\": 50,"
  28. "\"max_timeline_entries\": 50,"
  29. "\"timeline_purge_days\": 120,"
  30. "\"local_purge_days\": 0,"
  31. "\"min_account_age\": 0,"
  32. "\"admin_email\": \"\","
  33. "\"admin_account\": \"\","
  34. "\"title\": \"\","
  35. "\"short_description\": \"\","
  36. "\"short_description_raw\": false,"
  37. "\"protocol\": \"https\","
  38. "\"fastcgi\": false"
  39. "}";
  40. static const char *default_css =
  41. "body { max-width: 48em; margin: auto; line-height: 1.5; padding: 0.8em; word-wrap: break-word; }\n"
  42. "pre { overflow-x: scroll; }\n"
  43. "blockquote { font-style: italic; }\n"
  44. ".snac-embedded-video, img { max-width: 100% }\n"
  45. ".snac-origin { font-size: 85% }\n"
  46. ".snac-score { float: right; font-size: 85% }\n"
  47. ".snac-top-user { text-align: center; padding-bottom: 2em }\n"
  48. ".snac-top-user-name { font-size: 200% }\n"
  49. ".snac-top-user-id { font-size: 150% }\n"
  50. ".snac-announcement { border: black 1px solid; padding: 0.5em }\n"
  51. ".snac-avatar { float: left; height: 2.5em; width: 2.5em; padding: 0.25em }\n"
  52. ".snac-author { font-size: 90%; text-decoration: none }\n"
  53. ".snac-author-tag { font-size: 80% }\n"
  54. ".snac-pubdate { color: #a0a0a0; font-size: 90% }\n"
  55. ".snac-top-controls { padding-bottom: 1.5em }\n"
  56. ".snac-post { border-top: 1px solid #a0a0a0; padding-top: 0.5em; padding-bottom: 0.5em; }\n"
  57. ".snac-children { padding-left: 1em; border-left: 1px solid #a0a0a0; }\n"
  58. ".snac-thread-cont { border-top: 1px dashed #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. ".snac-list-of-lists { padding-left: 0; }\n"
  72. ".snac-list-of-lists li { display: inline; border: 1px solid #a0a0a0; border-radius: 25px;\n"
  73. " margin-right: 0.5em; padding-left: 0.5em; padding-right: 0.5em; }\n"
  74. ".snac-no-more-unseen-posts { border-top: 1px solid #a0a0a0; border-bottom: 1px solid #a0a0a0; padding: 0.5em 0; margin: 1em 0; }\n"
  75. "@media (prefers-color-scheme: dark) { \n"
  76. " body, input, textarea { background-color: #000; color: #fff; }\n"
  77. " a { color: #7799dd }\n"
  78. " a:visited { color: #aa99dd }\n"
  79. "}\n"
  80. ;
  81. const char *snac_blurb =
  82. "<p><b>%host%</b> is a <a href=\"https:/"
  83. "/en.wikipedia.org/wiki/Fediverse\">Fediverse</a> "
  84. "instance that uses the <a href=\"https:/"
  85. "/en.wikipedia.org/wiki/ActivityPub\">ActivityPub</a> "
  86. "protocol. In other words, users at this host can communicate with people "
  87. "that use software like Mastodon, Pleroma, Friendica, etc. "
  88. "all around the world.</p>\n"
  89. "<p>This server runs the "
  90. "<a href=\"" WHAT_IS_SNAC_URL "\">snac</a> software and there is no "
  91. "automatic sign-up process.</p>\n"
  92. ;
  93. static const char *greeting_html =
  94. "<!DOCTYPE html>\n"
  95. "<html><head>\n"
  96. "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n"
  97. "<link rel=\"icon\" type=\"image/x-icon\" href=\"https://%host%/favicon.ico\"/>\n"
  98. "<style>*{color-scheme:light dark}body{margin:auto;max-width:50em}</style>\n"
  99. "<title>Welcome to %host%</title>\n</head>\n"
  100. "<body>\n"
  101. "%blurb%"
  102. "<p>The following users are part of this community:</p>\n"
  103. "\n"
  104. "%userlist%\n"
  105. "\n"
  106. "<p>This site is powered by <abbr title=\"Social Networks Are Crap\">snac</abbr>.</p>\n"
  107. "</body></html>\n";
  108. int write_default_css(void)
  109. {
  110. FILE *f;
  111. xs *sfn = xs_fmt("%s/style.css", srv_basedir);
  112. if ((f = fopen(sfn, "w")) == NULL)
  113. return 1;
  114. fwrite(default_css, strlen(default_css), 1, f);
  115. fclose(f);
  116. return 0;
  117. }
  118. int snac_init(const char *basedir)
  119. {
  120. FILE *f;
  121. if (basedir == NULL) {
  122. printf("Base directory: "); fflush(stdout);
  123. srv_basedir = xs_strip_i(xs_readline(stdin));
  124. }
  125. else
  126. srv_basedir = xs_str_new(basedir);
  127. if (srv_basedir == NULL || *srv_basedir == '\0')
  128. return 1;
  129. if (xs_endswith(srv_basedir, "/"))
  130. srv_basedir = xs_crop_i(srv_basedir, 0, -1);
  131. if (mtime(srv_basedir) != 0.0) {
  132. printf("ERROR: directory '%s' must not exist.\n", srv_basedir);
  133. return 1;
  134. }
  135. srv_config = xs_json_loads(default_srv_config);
  136. xs *layout = xs_number_new(disk_layout);
  137. srv_config = xs_dict_set(srv_config, "layout", layout);
  138. int is_unix_socket = 0;
  139. printf("Network address or full path to unix socket [%s]: ", xs_dict_get(srv_config, "address")); fflush(stdout);
  140. {
  141. xs *i = xs_strip_i(xs_readline(stdin));
  142. if (*i) {
  143. srv_config = xs_dict_set(srv_config, "address", i);
  144. if (*i == '/')
  145. is_unix_socket = 1;
  146. }
  147. }
  148. if (!is_unix_socket) {
  149. printf("Network port [%d]: ", (int)xs_number_get(xs_dict_get(srv_config, "port"))); fflush(stdout);
  150. {
  151. xs *i = xs_strip_i(xs_readline(stdin));
  152. if (*i) {
  153. xs *n = xs_number_new(atoi(i));
  154. srv_config = xs_dict_set(srv_config, "port", n);
  155. }
  156. }
  157. }
  158. else {
  159. xs *n = xs_number_new(0);
  160. srv_config = xs_dict_set(srv_config, "port", n);
  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. srv_config = xs_dict_set(srv_config, "host", i);
  168. }
  169. printf("URL prefix: "); fflush(stdout);
  170. {
  171. xs *i = xs_strip_i(xs_readline(stdin));
  172. if (*i) {
  173. if (xs_endswith(i, "/"))
  174. i = xs_crop_i(i, 0, -1);
  175. srv_config = xs_dict_set(srv_config, "prefix", i);
  176. }
  177. }
  178. printf("Admin email address (optional): "); fflush(stdout);
  179. {
  180. xs *i = xs_strip_i(xs_readline(stdin));
  181. srv_config = xs_dict_set(srv_config, "admin_email", i);
  182. }
  183. if (mkdirx(srv_basedir) == -1) {
  184. printf("ERROR: cannot create directory '%s'\n", srv_basedir);
  185. return 1;
  186. }
  187. xs *udir = xs_fmt("%s/user", srv_basedir);
  188. mkdirx(udir);
  189. xs *odir = xs_fmt("%s/object", srv_basedir);
  190. mkdirx(odir);
  191. xs *qdir = xs_fmt("%s/queue", srv_basedir);
  192. mkdirx(qdir);
  193. xs *ibdir = xs_fmt("%s/inbox", srv_basedir);
  194. mkdirx(ibdir);
  195. xs *langdir = xs_fmt("%s/lang", srv_basedir);
  196. mkdirx(langdir);
  197. xs *gfn = xs_fmt("%s/greeting.html", srv_basedir);
  198. if ((f = fopen(gfn, "w")) == NULL) {
  199. printf("ERROR: cannot create '%s'\n", gfn);
  200. return 1;
  201. }
  202. xs *gh = xs_replace(greeting_html, "%blurb%", snac_blurb);
  203. fwrite(gh, strlen(gh), 1, f);
  204. fclose(f);
  205. if (write_default_css()) {
  206. printf("ERROR: cannot create style.css\n");
  207. return 1;
  208. }
  209. xs *cfn = xs_fmt("%s/server.json", srv_basedir);
  210. if ((f = fopen(cfn, "w")) == NULL) {
  211. printf("ERROR: cannot create '%s'\n", cfn);
  212. return 1;
  213. }
  214. xs_json_dump(srv_config, 4, f);
  215. fclose(f);
  216. printf("Done.\n\n");
  217. printf("Wanted web UI language files (.po) must be copied manually to %s\n", langdir);
  218. return 0;
  219. }
  220. void new_password(const char *uid, xs_str **clear_pwd, xs_str **hashed_pwd)
  221. /* creates a random password */
  222. {
  223. int rndbuf[3];
  224. xs_rnd_buf(rndbuf, sizeof(rndbuf));
  225. *clear_pwd = xs_base64_enc((char *)rndbuf, sizeof(rndbuf));
  226. *hashed_pwd = hash_password(uid, *clear_pwd, NULL);
  227. }
  228. int adduser(const char *uid)
  229. /* creates a new user */
  230. {
  231. snac snac;
  232. xs *config = xs_dict_new();
  233. xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
  234. xs *pwd = NULL;
  235. xs *pwd_f = NULL;
  236. xs *key = NULL;
  237. FILE *f;
  238. if (uid == NULL) {
  239. printf("Username: "); fflush(stdout);
  240. uid = xs_strip_i(xs_readline(stdin));
  241. }
  242. if (!validate_uid(uid)) {
  243. printf("ERROR: only alphanumeric characters and _ are allowed in user ids.\n");
  244. return 1;
  245. }
  246. if (user_open(&snac, uid)) {
  247. printf("ERROR: user '%s' already exists\n", snac.uid);
  248. return 1;
  249. }
  250. new_password(uid, &pwd, &pwd_f);
  251. config = xs_dict_append(config, "uid", uid);
  252. config = xs_dict_append(config, "name", uid);
  253. config = xs_dict_append(config, "avatar", "");
  254. config = xs_dict_append(config, "bio", "");
  255. config = xs_dict_append(config, "cw", "");
  256. config = xs_dict_append(config, "published", date);
  257. config = xs_dict_append(config, "passwd", pwd_f);
  258. xs *basedir = xs_fmt("%s/user/%s", srv_basedir, uid);
  259. if (mkdirx(basedir) == -1) {
  260. printf("ERROR: cannot create directory '%s'\n", basedir);
  261. return 0;
  262. }
  263. const char *dirs[] = {
  264. "followers", "following", "muted", "hidden",
  265. "public", "private", "queue", "history",
  266. "static", NULL };
  267. int n;
  268. for (n = 0; dirs[n]; n++) {
  269. xs *d = xs_fmt("%s/%s", basedir, dirs[n]);
  270. mkdirx(d);
  271. }
  272. /* add a specially short data retention time for the relay */
  273. if (strcmp(uid, "relay") == 0)
  274. config = xs_dict_set(config, "purge_days", xs_stock(1));
  275. xs *cfn = xs_fmt("%s/user.json", basedir);
  276. if ((f = fopen(cfn, "w")) == NULL) {
  277. printf("ERROR: cannot create '%s'\n", cfn);
  278. return 1;
  279. }
  280. else {
  281. xs_json_dump(config, 4, f);
  282. fclose(f);
  283. }
  284. printf("\nCreating RSA key...\n");
  285. key = xs_evp_genkey(2048);
  286. printf("Done.\n");
  287. xs *kfn = xs_fmt("%s/key.json", basedir);
  288. if ((f = fopen(kfn, "w")) == NULL) {
  289. printf("ERROR: cannot create '%s'\n", kfn);
  290. return 1;
  291. }
  292. else {
  293. xs_json_dump(key, 4, f);
  294. fclose(f);
  295. }
  296. printf("\nUser password is %s\n", pwd);
  297. printf("\nGo to %s/%s and continue configuring your user there.\n", srv_baseurl, uid);
  298. return 0;
  299. }
  300. int resetpwd(snac *snac)
  301. /* creates a new password for the user */
  302. {
  303. xs *clear_pwd = NULL;
  304. xs *hashed_pwd = NULL;
  305. xs *fn = xs_fmt("%s/user.json", snac->basedir);
  306. FILE *f;
  307. int ret = 0;
  308. new_password(snac->uid, &clear_pwd, &hashed_pwd);
  309. snac->config = xs_dict_set(snac->config, "passwd", hashed_pwd);
  310. if ((f = fopen(fn, "w")) != NULL) {
  311. xs_json_dump(snac->config, 4, f);
  312. fclose(f);
  313. printf("New password for user %s is %s\n", snac->uid, clear_pwd);
  314. }
  315. else {
  316. printf("ERROR: cannot write to %s\n", fn);
  317. ret = 1;
  318. }
  319. return ret;
  320. }
  321. void rm_rf(const char *dir)
  322. /* does an rm -rf (yes, I'm also scared) */
  323. {
  324. xs *d = xs_str_cat(xs_dup(dir), "/" "*");
  325. xs *l = xs_glob(d, 0, 0);
  326. xs_list *p = l;
  327. const xs_str *v;
  328. if (dbglevel >= 1)
  329. printf("Deleting directory %s\n", dir);
  330. while (xs_list_iter(&p, &v)) {
  331. struct stat st;
  332. if (stat(v, &st) != -1) {
  333. if (st.st_mode & S_IFDIR) {
  334. rm_rf(v);
  335. }
  336. else {
  337. if (dbglevel >= 1)
  338. printf("Deleting file %s\n", v);
  339. if (unlink(v) == -1)
  340. printf("ERROR: cannot delete file %s\n", v);
  341. }
  342. }
  343. else
  344. printf("ERROR: stat() fail for %s\n", v);
  345. }
  346. if (rmdir(dir) == -1)
  347. printf("ERROR: cannot delete directory %s\n", dir);
  348. }
  349. int deluser(snac *user)
  350. /* deletes a user */
  351. {
  352. int ret = 0;
  353. xs *fwers = following_list(user);
  354. xs_list *p = fwers;
  355. const xs_str *v;
  356. while (xs_list_iter(&p, &v)) {
  357. xs *object = NULL;
  358. if (valid_status(following_get(user, v, &object))) {
  359. xs *msg = msg_undo(user, xs_dict_get(object, "object"));
  360. following_del(user, v);
  361. enqueue_output_by_actor(user, msg, v, 0);
  362. printf("Unfollowing actor %s\n", v);
  363. }
  364. }
  365. rm_rf(user->basedir);
  366. return ret;
  367. }
  368. void verify_links(snac *user)
  369. /* verifies a user's links */
  370. {
  371. xs *metadata = NULL;
  372. const xs_dict *md = xs_dict_get(user->config, "metadata");
  373. const char *k, *v;
  374. int changed = 0;
  375. xs *headers = xs_dict_new();
  376. headers = xs_dict_append(headers, "accept", "text/html");
  377. headers = xs_dict_append(headers, "user-agent", USER_AGENT " (link verify)");
  378. if (xs_type(md) == XSTYPE_DICT)
  379. metadata = xs_dup(md);
  380. else
  381. if (xs_type(md) == XSTYPE_STRING) {
  382. /* convert to dict for easier iteration */
  383. metadata = xs_dict_new();
  384. xs *l = xs_split(md, "\n");
  385. const char *ll;
  386. xs_list_foreach(l, ll) {
  387. xs *kv = xs_split_n(ll, "=", 1);
  388. const char *k = xs_list_get(kv, 0);
  389. const char *v = xs_list_get(kv, 1);
  390. if (k && v) {
  391. xs *kk = xs_strip_i(xs_dup(k));
  392. xs *vv = xs_strip_i(xs_dup(v));
  393. metadata = xs_dict_set(metadata, kk, vv);
  394. }
  395. }
  396. }
  397. int c = 0;
  398. while (metadata && xs_dict_next(metadata, &k, &v, &c)) {
  399. xs *wfinger = NULL;
  400. const char *ov = NULL;
  401. /* is it an account handle? */
  402. if (*v == '@' && strchr(v + 1, '@')) {
  403. /* resolve it via webfinger */
  404. if (valid_status(webfinger_request(v, &wfinger, NULL)) && xs_is_string(wfinger)) {
  405. ov = v;
  406. v = wfinger;
  407. /* store the alias */
  408. if (user->links == NULL)
  409. user->links = xs_dict_new();
  410. user->links = xs_dict_set(user->links, ov, v);
  411. changed++;
  412. }
  413. }
  414. /* not an https link? skip */
  415. if (!xs_startswith(v, "https:/" "/"))
  416. continue;
  417. int status;
  418. xs *req = NULL;
  419. xs *payload = NULL;
  420. int p_size = 0;
  421. req = xs_http_request("GET", v, headers, NULL, 0, &status,
  422. &payload, &p_size, 0);
  423. if (!valid_status(status)) {
  424. snac_log(user, xs_fmt("link %s verify error %d", v, status));
  425. continue;
  426. }
  427. /* extract the links */
  428. xs *ls = xs_regex_select(payload, "< *(a|link) +[^>]+>");
  429. xs_list *lp = ls;
  430. const char *ll;
  431. int vfied = 0;
  432. while (!vfied && xs_list_iter(&lp, &ll)) {
  433. /* extract href and rel */
  434. xs *r = xs_regex_select(ll, "(href|rel) *= *(\"[^\"]*\"|'[^']*')");
  435. /* must have both attributes */
  436. if (xs_list_len(r) != 2)
  437. continue;
  438. xs *href = NULL;
  439. int is_rel_me = 0;
  440. xs_list *pr = r;
  441. const char *ar;
  442. while (xs_list_iter(&pr, &ar)) {
  443. xs *nq = xs_dup(ar);
  444. nq = xs_replace_i(nq, "\"", "");
  445. nq = xs_replace_i(nq, "'", "");
  446. xs *r2 = xs_split_n(nq, "=", 1);
  447. if (xs_list_len(r2) != 2)
  448. continue;
  449. xs *ak = xs_strip_i(xs_dup(xs_list_get(r2, 0)));
  450. xs *av = xs_strip_i(xs_dup(xs_list_get(r2, 1)));
  451. if (strcmp(ak, "href") == 0)
  452. href = xs_dup(av);
  453. else
  454. if (strcmp(ak, "rel") == 0) {
  455. /* split the value by spaces */
  456. xs *vbs = xs_split(av, " ");
  457. /* is any of it "me"? */
  458. if (xs_list_in(vbs, "me") != -1)
  459. is_rel_me = 1;
  460. }
  461. }
  462. /* after all this acrobatics, do we have an href and a rel="me"? */
  463. if (href != NULL && is_rel_me) {
  464. /* is it the same as the actor? */
  465. if (strcmp(href, user->actor) == 0) {
  466. /* got it! */
  467. xs *verified_time = xs_number_new((double)time(NULL));
  468. if (user->links == NULL)
  469. user->links = xs_dict_new();
  470. user->links = xs_dict_set(user->links, v, verified_time);
  471. vfied = 1;
  472. }
  473. else
  474. snac_debug(user, 1,
  475. xs_fmt("verify link %s rel='me' found but not related (%s)", v, href));
  476. }
  477. }
  478. if (vfied) {
  479. changed++;
  480. snac_log(user, xs_fmt("link %s verified", v));
  481. }
  482. else {
  483. snac_log(user, xs_fmt("link %s not verified (rel='me' not found)", v));
  484. }
  485. }
  486. if (changed) {
  487. FILE *f;
  488. /* update the links.json file */
  489. xs *fn = xs_fmt("%s/links.json", user->basedir);
  490. xs *bfn = xs_fmt("%s.bak", fn);
  491. rename(fn, bfn);
  492. if ((f = fopen(fn, "w")) != NULL) {
  493. xs_json_dump(user->links, 4, f);
  494. fclose(f);
  495. }
  496. else
  497. rename(bfn, fn);
  498. }
  499. }
  500. void export_csv(snac *user)
  501. /* exports user data to current directory in a way that pleases Mastodon */
  502. {
  503. FILE *f;
  504. xs *fn = NULL;
  505. fn = xs_fmt("%s/export/bookmarks.csv", user->basedir);
  506. if ((f = fopen(fn, "w")) != NULL) {
  507. snac_log(user, xs_fmt("Creating %s...", fn));
  508. xs *l = bookmark_list(user);
  509. const char *md5;
  510. xs_list_foreach(l, md5) {
  511. xs *post = NULL;
  512. if (valid_status(object_get_by_md5(md5, &post))) {
  513. const char *id = xs_dict_get(post, "id");
  514. if (xs_type(id) == XSTYPE_STRING)
  515. fprintf(f, "%s\n", id);
  516. }
  517. }
  518. fclose(f);
  519. }
  520. else
  521. snac_log(user, xs_fmt("Cannot create file %s", fn));
  522. xs_free(fn);
  523. fn = xs_fmt("%s/export/blocked_accounts.csv", user->basedir);
  524. if ((f = fopen(fn, "w")) != NULL) {
  525. snac_log(user, xs_fmt("Creating %s...", fn));
  526. xs *l = muted_list(user);
  527. const char *actor;
  528. xs_list_foreach(l, actor) {
  529. xs *uid = NULL;
  530. webfinger_request_fake(actor, NULL, &uid);
  531. fprintf(f, "%s\n", uid);
  532. }
  533. fclose(f);
  534. }
  535. else
  536. snac_log(user, xs_fmt("Cannot create file %s", fn));
  537. xs_free(fn);
  538. fn = xs_fmt("%s/export/lists.csv", user->basedir);
  539. if ((f = fopen(fn, "w")) != NULL) {
  540. snac_log(user, xs_fmt("Creating %s...", fn));
  541. xs *lol = list_maint(user, NULL, 0);
  542. const xs_list *li;
  543. xs_list_foreach(lol, li) {
  544. const char *lid = xs_list_get(li, 0);
  545. const char *ltitle = xs_list_get(li, 1);
  546. xs *actors = list_members(user, lid, NULL, 0);
  547. const char *md5;
  548. xs_list_foreach(actors, md5) {
  549. xs *actor = NULL;
  550. if (valid_status(object_get_by_md5(md5, &actor))) {
  551. const char *id = xs_dict_get(actor, "id");
  552. xs *uid = NULL;
  553. webfinger_request_fake(id, NULL, &uid);
  554. fprintf(f, "%s,%s\n", ltitle, uid);
  555. }
  556. }
  557. }
  558. fclose(f);
  559. }
  560. else
  561. snac_log(user, xs_fmt("Cannot create file %s", fn));
  562. xs_free(fn);
  563. fn = xs_fmt("%s/export/following_accounts.csv", user->basedir);
  564. if ((f = fopen(fn, "w")) != NULL) {
  565. snac_log(user, xs_fmt("Creating %s...", fn));
  566. fprintf(f, "Account address,Show boosts,Notify on new posts,Languages\n");
  567. xs *fwing = following_list(user);
  568. const char *actor;
  569. xs_list_foreach(fwing, actor) {
  570. xs *uid = NULL;
  571. webfinger_request_fake(actor, NULL, &uid);
  572. fprintf(f, "%s,%s,false,\n", uid, limited(user, actor, 0) ? "false" : "true");
  573. }
  574. fclose(f);
  575. }
  576. else
  577. snac_log(user, xs_fmt("Cannot create file %s", fn));
  578. }
  579. void export_posts(snac *user)
  580. /* exports all posts to an OrderedCollection */
  581. {
  582. xs *ifn = xs_fmt("%s/public.idx", user->basedir);
  583. xs *index = index_list(ifn, XS_ALL);
  584. xs *ofn = xs_fmt("%s/export/outbox.json", user->basedir);
  585. FILE *f;
  586. if ((f = fopen(ofn, "w")) == NULL) {
  587. snac_log(user, xs_fmt("Cannot create file %s", ofn));
  588. return;
  589. }
  590. int cnt = 0;
  591. /* raw output */
  592. fprintf(f, "{\"@context\": \"https:/" "/www.w3.org/ns/activitystreams\",");
  593. fprintf(f, "\"id\": \"outbox.json\",");
  594. fprintf(f, "\"type\": \"OrderedCollection\",");
  595. fprintf(f, "\"orderedItems\": [");
  596. const char *md5;
  597. snac_log(user, xs_fmt("Creating %s...", ofn));
  598. xs_list_foreach(index, md5) {
  599. xs *obj = NULL;
  600. if (!valid_status(object_get_by_md5(md5, &obj)))
  601. continue;
  602. const char *type = xs_dict_get(obj, "type");
  603. if (!xs_is_string(type) || strcmp(type, "Note"))
  604. continue;
  605. const char *atto = get_atto(obj);
  606. if (!xs_is_string(atto) || strcmp(atto, user->actor))
  607. continue;
  608. if (cnt)
  609. fprintf(f, ",");
  610. xs *c_msg = msg_create(user, obj);
  611. xs_json_dump(c_msg, 0, f);
  612. cnt++;
  613. }
  614. fprintf(f, "], \"totalItems\": %d}", cnt);
  615. fclose(f);
  616. }
  617. void import_blocked_accounts_csv(snac *user, const char *ifn)
  618. /* imports a Mastodon CSV file of blocked accounts */
  619. {
  620. FILE *f;
  621. xs *l = xs_split(ifn, "/");
  622. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  623. if ((f = fopen(fn, "r")) != NULL) {
  624. snac_log(user, xs_fmt("Importing from %s...", fn));
  625. while (!feof(f)) {
  626. xs *l = xs_strip_i(xs_readline(f));
  627. if (*l && strchr(l, '@') != NULL) {
  628. xs *url = NULL;
  629. xs *uid = NULL;
  630. if (valid_status(webfinger_request(l, &url, &uid))) {
  631. if (is_muted(user, url))
  632. snac_log(user, xs_fmt("Actor %s already MUTEd", url));
  633. else {
  634. mute(user, url);
  635. snac_log(user, xs_fmt("MUTEd actor %s", url));
  636. }
  637. }
  638. else
  639. snac_log(user, xs_fmt("Webfinger error for account %s", l));
  640. }
  641. }
  642. fclose(f);
  643. }
  644. else
  645. snac_log(user, xs_fmt("Cannot open file %s", fn));
  646. }
  647. void import_following_accounts_csv(snac *user, const char *ifn)
  648. /* imports a Mastodon CSV file of accounts to follow */
  649. {
  650. FILE *f;
  651. xs *l = xs_split(ifn, "/");
  652. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  653. if ((f = fopen(fn, "r")) != NULL) {
  654. snac_log(user, xs_fmt("Importing from %s...", fn));
  655. while (!feof(f)) {
  656. xs *l = xs_strip_i(xs_readline(f));
  657. if (*l) {
  658. xs *l2 = xs_split(l, ",");
  659. const char *acct = xs_list_get(l2, 0);
  660. const char *show = xs_list_get(l2, 1);
  661. if (acct) {
  662. /* not a valid account? skip (probably the CSV header) */
  663. if (strchr(acct, '@') == NULL)
  664. continue;
  665. xs *msg = msg_follow(user, acct);
  666. if (msg == NULL) {
  667. snac_log(user, xs_fmt("Cannot follow %s -- server down?", acct));
  668. continue;
  669. }
  670. const char *actor = xs_dict_get(msg, "object");
  671. if (following_check(user, actor))
  672. snac_log(user, xs_fmt("Actor %s already followed", actor));
  673. else {
  674. following_add(user, actor, msg);
  675. enqueue_output_by_actor(user, msg, actor, 0);
  676. snac_log(user, xs_fmt("Following %s", actor));
  677. }
  678. if (show && strcmp(show, "false") == 0) {
  679. limit(user, actor);
  680. snac_log(user, xs_fmt("Limiting boosts from actor %s", actor));
  681. }
  682. else {
  683. unlimit(user, actor);
  684. snac_log(user, xs_fmt("Unlimiting boosts from actor %s", actor));
  685. }
  686. }
  687. }
  688. }
  689. fclose(f);
  690. }
  691. else
  692. snac_log(user, xs_fmt("Cannot open file %s", fn));
  693. }
  694. void import_list_csv(snac *user, const char *ifn)
  695. /* imports a Mastodon CSV file list */
  696. {
  697. FILE *f;
  698. xs *l = xs_split(ifn, "/");
  699. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  700. if ((f = fopen(fn, "r")) != NULL) {
  701. snac_log(user, xs_fmt("Importing from %s...", fn));
  702. while (!feof(f)) {
  703. xs *l = xs_strip_i(xs_readline(f));
  704. if (*l) {
  705. xs *l2 = xs_split(l, ",");
  706. const char *lname = xs_list_get(l2, 0);
  707. const char *acct = xs_list_get(l2, 1);
  708. if (lname && acct) {
  709. /* create the list */
  710. xs *list_id = list_maint(user, lname, 1);
  711. xs *url = NULL;
  712. xs *uid = NULL;
  713. if (valid_status(webfinger_request(acct, &url, &uid))) {
  714. xs *actor_md5 = xs_md5_hex(url, strlen(url));
  715. list_members(user, list_id, actor_md5, 1);
  716. snac_log(user, xs_fmt("Added %s to list %s", url, lname));
  717. if (!following_check(user, url)) {
  718. xs *msg = msg_follow(user, url);
  719. if (msg == NULL) {
  720. snac_log(user, xs_fmt("Cannot follow %s -- server down?", acct));
  721. continue;
  722. }
  723. following_add(user, url, msg);
  724. enqueue_output_by_actor(user, msg, url, 0);
  725. snac_log(user, xs_fmt("Following %s", url));
  726. }
  727. }
  728. else
  729. snac_log(user, xs_fmt("Webfinger error while adding %s to list %s", acct, lname));
  730. }
  731. }
  732. }
  733. fclose(f);
  734. }
  735. else
  736. snac_log(user, xs_fmt("Cannot open file %s", fn));
  737. }
  738. void import_csv(snac *user)
  739. /* import CSV files from Mastodon */
  740. {
  741. FILE *f;
  742. import_blocked_accounts_csv(user, "blocked_accounts.csv");
  743. import_following_accounts_csv(user, "following_accounts.csv");
  744. import_list_csv(user, "lists.csv");
  745. xs *fn = xs_fmt("%s/import/bookmarks.csv", user->basedir);
  746. if ((f = fopen(fn, "r")) != NULL) {
  747. snac_log(user, xs_fmt("Importing from %s...", fn));
  748. while (!feof(f)) {
  749. xs *l = xs_strip_i(xs_readline(f));
  750. if (*l) {
  751. xs *post = NULL;
  752. if (!valid_status(object_get(l, &post))) {
  753. if (!valid_status(activitypub_request(user, l, &post))) {
  754. snac_log(user, xs_fmt("Error getting object %s for bookmarking", l));
  755. continue;
  756. }
  757. }
  758. if (post == NULL)
  759. continue;
  760. /* request the actor that created the post */
  761. const char *actor = get_atto(post);
  762. if (xs_type(actor) == XSTYPE_STRING)
  763. actor_request(user, actor, NULL);
  764. object_add_ow(l, post);
  765. timeline_add(user, l, post);
  766. bookmark(user, l);
  767. snac_log(user, xs_fmt("Bookmarked %s", l));
  768. }
  769. }
  770. fclose(f);
  771. }
  772. else
  773. snac_log(user, xs_fmt("Cannot open file %s", fn));
  774. }
  775. static const struct {
  776. const char *proto;
  777. unsigned short default_port;
  778. } FALLBACK_PORTS[] = {
  779. /* caution: https > http, smpts > smtp */
  780. {"https", 443},
  781. {"http", 80},
  782. {"smtps", 465},
  783. {"smtp", 25}
  784. };
  785. int parse_port(const char *url, const char **errstr)
  786. {
  787. const char *col, *rcol;
  788. int tmp, ret = -1;
  789. if (errstr)
  790. *errstr = NULL;
  791. if (!(col = strchr(url, ':'))) {
  792. if (errstr)
  793. *errstr = "bad url";
  794. return -1;
  795. }
  796. for (size_t i = 0; i < sizeof(FALLBACK_PORTS) / sizeof(*FALLBACK_PORTS); ++i) {
  797. if (memcmp(url, FALLBACK_PORTS[i].proto, strlen(FALLBACK_PORTS[i].proto)) == 0) {
  798. ret = FALLBACK_PORTS[i].default_port;
  799. break;
  800. }
  801. }
  802. if (!(rcol = strchr(col + 1, ':')))
  803. rcol = col;
  804. if (rcol) {
  805. tmp = atoi(rcol + 1);
  806. if (tmp == 0) {
  807. if (ret != -1)
  808. return ret;
  809. if (errstr)
  810. *errstr = strerror(errno);
  811. return -1;
  812. }
  813. return tmp;
  814. }
  815. if (errstr)
  816. *errstr = "unknown protocol";
  817. return -1;
  818. }