utils.c 30 KB

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