utils.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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 *gfn = xs_fmt("%s/greeting.html", srv_basedir);
  196. if ((f = fopen(gfn, "w")) == NULL) {
  197. printf("ERROR: cannot create '%s'\n", gfn);
  198. return 1;
  199. }
  200. xs *gh = xs_replace(greeting_html, "%blurb%", snac_blurb);
  201. fwrite(gh, strlen(gh), 1, f);
  202. fclose(f);
  203. if (write_default_css()) {
  204. printf("ERROR: cannot create style.css\n");
  205. return 1;
  206. }
  207. xs *cfn = xs_fmt("%s/server.json", srv_basedir);
  208. if ((f = fopen(cfn, "w")) == NULL) {
  209. printf("ERROR: cannot create '%s'\n", cfn);
  210. return 1;
  211. }
  212. xs_json_dump(srv_config, 4, f);
  213. fclose(f);
  214. printf("Done.\n");
  215. return 0;
  216. }
  217. void new_password(const char *uid, xs_str **clear_pwd, xs_str **hashed_pwd)
  218. /* creates a random password */
  219. {
  220. int rndbuf[3];
  221. xs_rnd_buf(rndbuf, sizeof(rndbuf));
  222. *clear_pwd = xs_base64_enc((char *)rndbuf, sizeof(rndbuf));
  223. *hashed_pwd = hash_password(uid, *clear_pwd, NULL);
  224. }
  225. int adduser(const char *uid)
  226. /* creates a new user */
  227. {
  228. snac snac;
  229. xs *config = xs_dict_new();
  230. xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
  231. xs *pwd = NULL;
  232. xs *pwd_f = NULL;
  233. xs *key = NULL;
  234. FILE *f;
  235. if (uid == NULL) {
  236. printf("Username: "); fflush(stdout);
  237. uid = xs_strip_i(xs_readline(stdin));
  238. }
  239. if (!validate_uid(uid)) {
  240. printf("ERROR: only alphanumeric characters and _ are allowed in user ids.\n");
  241. return 1;
  242. }
  243. if (user_open(&snac, uid)) {
  244. printf("ERROR: user '%s' already exists\n", snac.uid);
  245. return 1;
  246. }
  247. new_password(uid, &pwd, &pwd_f);
  248. config = xs_dict_append(config, "uid", uid);
  249. config = xs_dict_append(config, "name", uid);
  250. config = xs_dict_append(config, "avatar", "");
  251. config = xs_dict_append(config, "bio", "");
  252. config = xs_dict_append(config, "cw", "");
  253. config = xs_dict_append(config, "published", date);
  254. config = xs_dict_append(config, "passwd", pwd_f);
  255. xs *basedir = xs_fmt("%s/user/%s", srv_basedir, uid);
  256. if (mkdirx(basedir) == -1) {
  257. printf("ERROR: cannot create directory '%s'\n", basedir);
  258. return 0;
  259. }
  260. const char *dirs[] = {
  261. "followers", "following", "muted", "hidden",
  262. "public", "private", "queue", "history",
  263. "static", NULL };
  264. int n;
  265. for (n = 0; dirs[n]; n++) {
  266. xs *d = xs_fmt("%s/%s", basedir, dirs[n]);
  267. mkdirx(d);
  268. }
  269. /* add a specially short data retention time for the relay */
  270. if (strcmp(uid, "relay") == 0)
  271. config = xs_dict_set(config, "purge_days", xs_stock(1));
  272. xs *cfn = xs_fmt("%s/user.json", basedir);
  273. if ((f = fopen(cfn, "w")) == NULL) {
  274. printf("ERROR: cannot create '%s'\n", cfn);
  275. return 1;
  276. }
  277. else {
  278. xs_json_dump(config, 4, f);
  279. fclose(f);
  280. }
  281. printf("\nCreating RSA key...\n");
  282. key = xs_evp_genkey(2048);
  283. printf("Done.\n");
  284. xs *kfn = xs_fmt("%s/key.json", basedir);
  285. if ((f = fopen(kfn, "w")) == NULL) {
  286. printf("ERROR: cannot create '%s'\n", kfn);
  287. return 1;
  288. }
  289. else {
  290. xs_json_dump(key, 4, f);
  291. fclose(f);
  292. }
  293. printf("\nUser password is %s\n", pwd);
  294. printf("\nGo to %s/%s and continue configuring your user there.\n", srv_baseurl, uid);
  295. return 0;
  296. }
  297. int resetpwd(snac *snac)
  298. /* creates a new password for the user */
  299. {
  300. xs *clear_pwd = NULL;
  301. xs *hashed_pwd = NULL;
  302. xs *fn = xs_fmt("%s/user.json", snac->basedir);
  303. FILE *f;
  304. int ret = 0;
  305. new_password(snac->uid, &clear_pwd, &hashed_pwd);
  306. snac->config = xs_dict_set(snac->config, "passwd", hashed_pwd);
  307. if ((f = fopen(fn, "w")) != NULL) {
  308. xs_json_dump(snac->config, 4, f);
  309. fclose(f);
  310. printf("New password for user %s is %s\n", snac->uid, clear_pwd);
  311. }
  312. else {
  313. printf("ERROR: cannot write to %s\n", fn);
  314. ret = 1;
  315. }
  316. return ret;
  317. }
  318. void rm_rf(const char *dir)
  319. /* does an rm -rf (yes, I'm also scared) */
  320. {
  321. xs *d = xs_str_cat(xs_dup(dir), "/" "*");
  322. xs *l = xs_glob(d, 0, 0);
  323. xs_list *p = l;
  324. const xs_str *v;
  325. if (dbglevel >= 1)
  326. printf("Deleting directory %s\n", dir);
  327. while (xs_list_iter(&p, &v)) {
  328. struct stat st;
  329. if (stat(v, &st) != -1) {
  330. if (st.st_mode & S_IFDIR) {
  331. rm_rf(v);
  332. }
  333. else {
  334. if (dbglevel >= 1)
  335. printf("Deleting file %s\n", v);
  336. if (unlink(v) == -1)
  337. printf("ERROR: cannot delete file %s\n", v);
  338. }
  339. }
  340. else
  341. printf("ERROR: stat() fail for %s\n", v);
  342. }
  343. if (rmdir(dir) == -1)
  344. printf("ERROR: cannot delete directory %s\n", dir);
  345. }
  346. int deluser(snac *user)
  347. /* deletes a user */
  348. {
  349. int ret = 0;
  350. xs *fwers = following_list(user);
  351. xs_list *p = fwers;
  352. const xs_str *v;
  353. while (xs_list_iter(&p, &v)) {
  354. xs *object = NULL;
  355. if (valid_status(following_get(user, v, &object))) {
  356. xs *msg = msg_undo(user, xs_dict_get(object, "object"));
  357. following_del(user, v);
  358. enqueue_output_by_actor(user, msg, v, 0);
  359. printf("Unfollowing actor %s\n", v);
  360. }
  361. }
  362. rm_rf(user->basedir);
  363. return ret;
  364. }
  365. void verify_links(snac *user)
  366. /* verifies a user's links */
  367. {
  368. xs *metadata = NULL;
  369. const xs_dict *md = xs_dict_get(user->config, "metadata");
  370. const char *k, *v;
  371. int changed = 0;
  372. xs *headers = xs_dict_new();
  373. headers = xs_dict_append(headers, "accept", "text/html");
  374. headers = xs_dict_append(headers, "user-agent", USER_AGENT " (link verify)");
  375. if (xs_type(md) == XSTYPE_DICT)
  376. metadata = xs_dup(md);
  377. else
  378. if (xs_type(md) == XSTYPE_STRING) {
  379. /* convert to dict for easier iteration */
  380. metadata = xs_dict_new();
  381. xs *l = xs_split(md, "\n");
  382. const char *ll;
  383. xs_list_foreach(l, ll) {
  384. xs *kv = xs_split_n(ll, "=", 1);
  385. const char *k = xs_list_get(kv, 0);
  386. const char *v = xs_list_get(kv, 1);
  387. if (k && v) {
  388. xs *kk = xs_strip_i(xs_dup(k));
  389. xs *vv = xs_strip_i(xs_dup(v));
  390. metadata = xs_dict_set(metadata, kk, vv);
  391. }
  392. }
  393. }
  394. int c = 0;
  395. while (metadata && xs_dict_next(metadata, &k, &v, &c)) {
  396. xs *wfinger = NULL;
  397. const char *ov = NULL;
  398. /* is it an account handle? */
  399. if (*v == '@' && strchr(v + 1, '@')) {
  400. /* resolve it via webfinger */
  401. if (valid_status(webfinger_request(v, &wfinger, NULL)) && xs_is_string(wfinger)) {
  402. ov = v;
  403. v = wfinger;
  404. /* store the alias */
  405. if (user->links == NULL)
  406. user->links = xs_dict_new();
  407. user->links = xs_dict_set(user->links, ov, v);
  408. changed++;
  409. }
  410. }
  411. /* not an https link? skip */
  412. if (!xs_startswith(v, "https:/" "/"))
  413. continue;
  414. int status;
  415. xs *req = NULL;
  416. xs *payload = NULL;
  417. int p_size = 0;
  418. req = xs_http_request("GET", v, headers, NULL, 0, &status,
  419. &payload, &p_size, 0);
  420. if (!valid_status(status)) {
  421. snac_log(user, xs_fmt("link %s verify error %d", v, status));
  422. continue;
  423. }
  424. /* extract the links */
  425. xs *ls = xs_regex_select(payload, "< *(a|link) +[^>]+>");
  426. xs_list *lp = ls;
  427. const char *ll;
  428. int vfied = 0;
  429. while (!vfied && xs_list_iter(&lp, &ll)) {
  430. /* extract href and rel */
  431. xs *r = xs_regex_select(ll, "(href|rel) *= *(\"[^\"]*\"|'[^']*')");
  432. /* must have both attributes */
  433. if (xs_list_len(r) != 2)
  434. continue;
  435. xs *href = NULL;
  436. int is_rel_me = 0;
  437. xs_list *pr = r;
  438. const char *ar;
  439. while (xs_list_iter(&pr, &ar)) {
  440. xs *nq = xs_dup(ar);
  441. nq = xs_replace_i(nq, "\"", "");
  442. nq = xs_replace_i(nq, "'", "");
  443. xs *r2 = xs_split_n(nq, "=", 1);
  444. if (xs_list_len(r2) != 2)
  445. continue;
  446. xs *ak = xs_strip_i(xs_dup(xs_list_get(r2, 0)));
  447. xs *av = xs_strip_i(xs_dup(xs_list_get(r2, 1)));
  448. if (strcmp(ak, "href") == 0)
  449. href = xs_dup(av);
  450. else
  451. if (strcmp(ak, "rel") == 0) {
  452. /* split the value by spaces */
  453. xs *vbs = xs_split(av, " ");
  454. /* is any of it "me"? */
  455. if (xs_list_in(vbs, "me") != -1)
  456. is_rel_me = 1;
  457. }
  458. }
  459. /* after all this acrobatics, do we have an href and a rel="me"? */
  460. if (href != NULL && is_rel_me) {
  461. /* is it the same as the actor? */
  462. if (strcmp(href, user->actor) == 0) {
  463. /* got it! */
  464. xs *verified_time = xs_number_new((double)time(NULL));
  465. if (user->links == NULL)
  466. user->links = xs_dict_new();
  467. user->links = xs_dict_set(user->links, v, verified_time);
  468. vfied = 1;
  469. }
  470. else
  471. snac_debug(user, 1,
  472. xs_fmt("verify link %s rel='me' found but not related (%s)", v, href));
  473. }
  474. }
  475. if (vfied) {
  476. changed++;
  477. snac_log(user, xs_fmt("link %s verified", v));
  478. }
  479. else {
  480. snac_log(user, xs_fmt("link %s not verified (rel='me' not found)", v));
  481. }
  482. }
  483. if (changed) {
  484. FILE *f;
  485. /* update the links.json file */
  486. xs *fn = xs_fmt("%s/links.json", user->basedir);
  487. xs *bfn = xs_fmt("%s.bak", fn);
  488. rename(fn, bfn);
  489. if ((f = fopen(fn, "w")) != NULL) {
  490. xs_json_dump(user->links, 4, f);
  491. fclose(f);
  492. }
  493. else
  494. rename(bfn, fn);
  495. }
  496. }
  497. void export_csv(snac *user)
  498. /* exports user data to current directory in a way that pleases Mastodon */
  499. {
  500. FILE *f;
  501. xs *fn = NULL;
  502. fn = xs_fmt("%s/export/bookmarks.csv", user->basedir);
  503. if ((f = fopen(fn, "w")) != NULL) {
  504. snac_log(user, xs_fmt("Creating %s...", fn));
  505. xs *l = bookmark_list(user);
  506. const char *md5;
  507. xs_list_foreach(l, md5) {
  508. xs *post = NULL;
  509. if (valid_status(object_get_by_md5(md5, &post))) {
  510. const char *id = xs_dict_get(post, "id");
  511. if (xs_type(id) == XSTYPE_STRING)
  512. fprintf(f, "%s\n", id);
  513. }
  514. }
  515. fclose(f);
  516. }
  517. else
  518. snac_log(user, xs_fmt("Cannot create file %s", fn));
  519. xs_free(fn);
  520. fn = xs_fmt("%s/export/blocked_accounts.csv", user->basedir);
  521. if ((f = fopen(fn, "w")) != NULL) {
  522. snac_log(user, xs_fmt("Creating %s...", fn));
  523. xs *l = muted_list(user);
  524. const char *actor;
  525. xs_list_foreach(l, actor) {
  526. xs *uid = NULL;
  527. webfinger_request_fake(actor, NULL, &uid);
  528. fprintf(f, "%s\n", uid);
  529. }
  530. fclose(f);
  531. }
  532. else
  533. snac_log(user, xs_fmt("Cannot create file %s", fn));
  534. xs_free(fn);
  535. fn = xs_fmt("%s/export/lists.csv", user->basedir);
  536. if ((f = fopen(fn, "w")) != NULL) {
  537. snac_log(user, xs_fmt("Creating %s...", fn));
  538. xs *lol = list_maint(user, NULL, 0);
  539. const xs_list *li;
  540. xs_list_foreach(lol, li) {
  541. const char *lid = xs_list_get(li, 0);
  542. const char *ltitle = xs_list_get(li, 1);
  543. xs *actors = list_content(user, lid, NULL, 0);
  544. const char *md5;
  545. xs_list_foreach(actors, md5) {
  546. xs *actor = NULL;
  547. if (valid_status(object_get_by_md5(md5, &actor))) {
  548. const char *id = xs_dict_get(actor, "id");
  549. xs *uid = NULL;
  550. webfinger_request_fake(id, NULL, &uid);
  551. fprintf(f, "%s,%s\n", ltitle, uid);
  552. }
  553. }
  554. }
  555. fclose(f);
  556. }
  557. else
  558. snac_log(user, xs_fmt("Cannot create file %s", fn));
  559. xs_free(fn);
  560. fn = xs_fmt("%s/export/following_accounts.csv", user->basedir);
  561. if ((f = fopen(fn, "w")) != NULL) {
  562. snac_log(user, xs_fmt("Creating %s...", fn));
  563. fprintf(f, "Account address,Show boosts,Notify on new posts,Languages\n");
  564. xs *fwing = following_list(user);
  565. const char *actor;
  566. xs_list_foreach(fwing, actor) {
  567. xs *uid = NULL;
  568. webfinger_request_fake(actor, NULL, &uid);
  569. fprintf(f, "%s,%s,false,\n", uid, limited(user, actor, 0) ? "false" : "true");
  570. }
  571. fclose(f);
  572. }
  573. else
  574. snac_log(user, xs_fmt("Cannot create file %s", fn));
  575. }
  576. void export_posts(snac *user)
  577. /* exports all posts to an OrderedCollection */
  578. {
  579. xs *ifn = xs_fmt("%s/public.idx", user->basedir);
  580. xs *index = index_list(ifn, XS_ALL);
  581. xs *ofn = xs_fmt("%s/export/outbox.json", user->basedir);
  582. FILE *f;
  583. if ((f = fopen(ofn, "w")) == NULL) {
  584. snac_log(user, xs_fmt("Cannot create file %s", ofn));
  585. return;
  586. }
  587. int cnt = 0;
  588. /* raw output */
  589. fprintf(f, "{\"@context\": \"https:/" "/www.w3.org/ns/activitystreams\",");
  590. fprintf(f, "\"id\": \"outbox.json\",");
  591. fprintf(f, "\"type\": \"OrderedCollection\",");
  592. fprintf(f, "\"orderedItems\": [");
  593. const char *md5;
  594. snac_log(user, xs_fmt("Creating %s...", ofn));
  595. xs_list_foreach(index, md5) {
  596. xs *obj = NULL;
  597. if (!valid_status(object_get_by_md5(md5, &obj)))
  598. continue;
  599. const char *type = xs_dict_get(obj, "type");
  600. if (!xs_is_string(type) || strcmp(type, "Note"))
  601. continue;
  602. const char *atto = get_atto(obj);
  603. if (!xs_is_string(atto) || strcmp(atto, user->actor))
  604. continue;
  605. if (cnt)
  606. fprintf(f, ",");
  607. xs *c_msg = msg_create(user, obj);
  608. xs_json_dump(c_msg, 0, f);
  609. cnt++;
  610. }
  611. fprintf(f, "], \"totalItems\": %d}", cnt);
  612. fclose(f);
  613. }
  614. void import_blocked_accounts_csv(snac *user, const char *ifn)
  615. /* imports a Mastodon CSV file of blocked accounts */
  616. {
  617. FILE *f;
  618. xs *l = xs_split(ifn, "/");
  619. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  620. if ((f = fopen(fn, "r")) != NULL) {
  621. snac_log(user, xs_fmt("Importing from %s...", fn));
  622. while (!feof(f)) {
  623. xs *l = xs_strip_i(xs_readline(f));
  624. if (*l && strchr(l, '@') != NULL) {
  625. xs *url = NULL;
  626. xs *uid = NULL;
  627. if (valid_status(webfinger_request(l, &url, &uid))) {
  628. if (is_muted(user, url))
  629. snac_log(user, xs_fmt("Actor %s already MUTEd", url));
  630. else {
  631. mute(user, url);
  632. snac_log(user, xs_fmt("MUTEd actor %s", url));
  633. }
  634. }
  635. else
  636. snac_log(user, xs_fmt("Webfinger error for account %s", l));
  637. }
  638. }
  639. fclose(f);
  640. }
  641. else
  642. snac_log(user, xs_fmt("Cannot open file %s", fn));
  643. }
  644. void import_following_accounts_csv(snac *user, const char *ifn)
  645. /* imports a Mastodon CSV file of accounts to follow */
  646. {
  647. FILE *f;
  648. xs *l = xs_split(ifn, "/");
  649. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  650. if ((f = fopen(fn, "r")) != NULL) {
  651. snac_log(user, xs_fmt("Importing from %s...", fn));
  652. while (!feof(f)) {
  653. xs *l = xs_strip_i(xs_readline(f));
  654. if (*l) {
  655. xs *l2 = xs_split(l, ",");
  656. const char *acct = xs_list_get(l2, 0);
  657. const char *show = xs_list_get(l2, 1);
  658. if (acct) {
  659. /* not a valid account? skip (probably the CSV header) */
  660. if (strchr(acct, '@') == NULL)
  661. continue;
  662. xs *msg = msg_follow(user, acct);
  663. if (msg == NULL) {
  664. snac_log(user, xs_fmt("Cannot follow %s -- server down?", acct));
  665. continue;
  666. }
  667. const char *actor = xs_dict_get(msg, "object");
  668. if (following_check(user, actor))
  669. snac_log(user, xs_fmt("Actor %s already followed", actor));
  670. else {
  671. following_add(user, actor, msg);
  672. enqueue_output_by_actor(user, msg, actor, 0);
  673. snac_log(user, xs_fmt("Following %s", actor));
  674. }
  675. if (show && strcmp(show, "false") == 0) {
  676. limit(user, actor);
  677. snac_log(user, xs_fmt("Limiting boosts from actor %s", actor));
  678. }
  679. else {
  680. unlimit(user, actor);
  681. snac_log(user, xs_fmt("Unlimiting boosts from actor %s", actor));
  682. }
  683. }
  684. }
  685. }
  686. fclose(f);
  687. }
  688. else
  689. snac_log(user, xs_fmt("Cannot open file %s", fn));
  690. }
  691. void import_list_csv(snac *user, const char *ifn)
  692. /* imports a Mastodon CSV file list */
  693. {
  694. FILE *f;
  695. xs *l = xs_split(ifn, "/");
  696. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  697. if ((f = fopen(fn, "r")) != NULL) {
  698. snac_log(user, xs_fmt("Importing from %s...", fn));
  699. while (!feof(f)) {
  700. xs *l = xs_strip_i(xs_readline(f));
  701. if (*l) {
  702. xs *l2 = xs_split(l, ",");
  703. const char *lname = xs_list_get(l2, 0);
  704. const char *acct = xs_list_get(l2, 1);
  705. if (lname && acct) {
  706. /* create the list */
  707. xs *list_id = list_maint(user, lname, 1);
  708. xs *url = NULL;
  709. xs *uid = NULL;
  710. if (valid_status(webfinger_request(acct, &url, &uid))) {
  711. xs *actor_md5 = xs_md5_hex(url, strlen(url));
  712. list_content(user, list_id, actor_md5, 1);
  713. snac_log(user, xs_fmt("Added %s to list %s", url, lname));
  714. if (!following_check(user, url)) {
  715. xs *msg = msg_follow(user, url);
  716. if (msg == NULL) {
  717. snac_log(user, xs_fmt("Cannot follow %s -- server down?", acct));
  718. continue;
  719. }
  720. following_add(user, url, msg);
  721. enqueue_output_by_actor(user, msg, url, 0);
  722. snac_log(user, xs_fmt("Following %s", url));
  723. }
  724. }
  725. else
  726. snac_log(user, xs_fmt("Webfinger error while adding %s to list %s", acct, lname));
  727. }
  728. }
  729. }
  730. fclose(f);
  731. }
  732. else
  733. snac_log(user, xs_fmt("Cannot open file %s", fn));
  734. }
  735. void import_csv(snac *user)
  736. /* import CSV files from Mastodon */
  737. {
  738. FILE *f;
  739. import_blocked_accounts_csv(user, "blocked_accounts.csv");
  740. import_following_accounts_csv(user, "following_accounts.csv");
  741. import_list_csv(user, "lists.csv");
  742. xs *fn = xs_fmt("%s/import/bookmarks.csv", user->basedir);
  743. if ((f = fopen(fn, "r")) != NULL) {
  744. snac_log(user, xs_fmt("Importing from %s...", fn));
  745. while (!feof(f)) {
  746. xs *l = xs_strip_i(xs_readline(f));
  747. if (*l) {
  748. xs *post = NULL;
  749. if (!valid_status(object_get(l, &post))) {
  750. if (!valid_status(activitypub_request(user, l, &post))) {
  751. snac_log(user, xs_fmt("Error getting object %s for bookmarking", l));
  752. continue;
  753. }
  754. }
  755. if (post == NULL)
  756. continue;
  757. /* request the actor that created the post */
  758. const char *actor = get_atto(post);
  759. if (xs_type(actor) == XSTYPE_STRING)
  760. actor_request(user, actor, NULL);
  761. object_add_ow(l, post);
  762. timeline_add(user, l, post);
  763. bookmark(user, l);
  764. snac_log(user, xs_fmt("Bookmarked %s", l));
  765. }
  766. }
  767. fclose(f);
  768. }
  769. else
  770. snac_log(user, xs_fmt("Cannot open file %s", fn));
  771. }
  772. static const struct {
  773. const char *proto;
  774. unsigned short default_port;
  775. } FALLBACK_PORTS[] = {
  776. /* caution: https > http, smpts > smtp */
  777. {"https", 443},
  778. {"http", 80},
  779. {"smtps", 465},
  780. {"smtp", 25}
  781. };
  782. int parse_port(const char *url, const char **errstr)
  783. {
  784. const char *col, *rcol;
  785. int tmp, ret = -1;
  786. if (errstr)
  787. *errstr = NULL;
  788. if (!(col = strchr(url, ':'))) {
  789. if (errstr)
  790. *errstr = "bad url";
  791. return -1;
  792. }
  793. for (size_t i = 0; i < sizeof(FALLBACK_PORTS) / sizeof(*FALLBACK_PORTS); ++i) {
  794. if (memcmp(url, FALLBACK_PORTS[i].proto, strlen(FALLBACK_PORTS[i].proto)) == 0) {
  795. ret = FALLBACK_PORTS[i].default_port;
  796. break;
  797. }
  798. }
  799. if (!(rcol = strchr(col + 1, ':')))
  800. rcol = col;
  801. if (rcol) {
  802. tmp = atoi(rcol + 1);
  803. if (tmp == 0) {
  804. if (ret != -1)
  805. return ret;
  806. if (errstr)
  807. *errstr = strerror(errno);
  808. return -1;
  809. }
  810. return tmp;
  811. }
  812. if (errstr)
  813. *errstr = "unknown protocol";
  814. return -1;
  815. }