1
0

utils.c 29 KB

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