1
0

utils.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  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. rm_rf(user->basedir);
  367. return ret;
  368. }
  369. void verify_links(snac *user)
  370. /* verifies a user's links */
  371. {
  372. xs *metadata = NULL;
  373. const xs_dict *md = xs_dict_get(user->config, "metadata");
  374. const char *k, *v;
  375. int changed = 0;
  376. xs *headers = xs_dict_new();
  377. headers = xs_dict_append(headers, "accept", "text/html");
  378. headers = xs_dict_append(headers, "user-agent", USER_AGENT " (link verify)");
  379. if (xs_type(md) == XSTYPE_DICT)
  380. metadata = xs_dup(md);
  381. else
  382. if (xs_type(md) == XSTYPE_STRING) {
  383. /* convert to dict for easier iteration */
  384. metadata = xs_dict_new();
  385. xs *l = xs_split(md, "\n");
  386. const char *ll;
  387. xs_list_foreach(l, ll) {
  388. xs *kv = xs_split_n(ll, "=", 1);
  389. const char *k = xs_list_get(kv, 0);
  390. const char *v = xs_list_get(kv, 1);
  391. if (k && v) {
  392. xs *kk = xs_strip_i(xs_dup(k));
  393. xs *vv = xs_strip_i(xs_dup(v));
  394. metadata = xs_dict_set(metadata, kk, vv);
  395. }
  396. }
  397. }
  398. int c = 0;
  399. while (metadata && xs_dict_next(metadata, &k, &v, &c)) {
  400. xs *wfinger = NULL;
  401. const char *ov = NULL;
  402. /* is it an account handle? */
  403. if (*v == '@' && strchr(v + 1, '@')) {
  404. /* resolve it via webfinger */
  405. if (valid_status(webfinger_request(v, &wfinger, NULL)) && xs_is_string(wfinger)) {
  406. ov = v;
  407. v = wfinger;
  408. /* store the alias */
  409. if (user->links == NULL)
  410. user->links = xs_dict_new();
  411. user->links = xs_dict_set(user->links, ov, v);
  412. changed++;
  413. }
  414. }
  415. /* not an https link? skip */
  416. if (!xs_startswith(v, "https:/" "/"))
  417. continue;
  418. int status;
  419. xs *req = NULL;
  420. xs *payload = NULL;
  421. int p_size = 0;
  422. req = xs_http_request("GET", v, headers, NULL, 0, &status,
  423. &payload, &p_size, 0);
  424. if (!valid_status(status)) {
  425. snac_log(user, xs_fmt("link %s verify error %d", v, status));
  426. continue;
  427. }
  428. /* extract the links */
  429. xs *ls = xs_regex_select(payload, "< *(a|link) +[^>]+>");
  430. xs_list *lp = ls;
  431. const char *ll;
  432. int vfied = 0;
  433. while (!vfied && xs_list_iter(&lp, &ll)) {
  434. /* extract href and rel */
  435. xs *r = xs_regex_select(ll, "(href|rel) *= *(\"[^\"]*\"|'[^']*')");
  436. /* must have both attributes */
  437. if (xs_list_len(r) != 2)
  438. continue;
  439. xs *href = NULL;
  440. int is_rel_me = 0;
  441. xs_list *pr = r;
  442. const char *ar;
  443. while (xs_list_iter(&pr, &ar)) {
  444. xs *nq = xs_dup(ar);
  445. nq = xs_replace_i(nq, "\"", "");
  446. nq = xs_replace_i(nq, "'", "");
  447. xs *r2 = xs_split_n(nq, "=", 1);
  448. if (xs_list_len(r2) != 2)
  449. continue;
  450. xs *ak = xs_strip_i(xs_dup(xs_list_get(r2, 0)));
  451. xs *av = xs_strip_i(xs_dup(xs_list_get(r2, 1)));
  452. if (strcmp(ak, "href") == 0)
  453. href = xs_dup(av);
  454. else
  455. if (strcmp(ak, "rel") == 0) {
  456. /* split the value by spaces */
  457. xs *vbs = xs_split(av, " ");
  458. /* is any of it "me"? */
  459. if (xs_list_in(vbs, "me") != -1)
  460. is_rel_me = 1;
  461. }
  462. }
  463. /* after all this acrobatics, do we have an href and a rel="me"? */
  464. if (href != NULL && is_rel_me) {
  465. /* is it the same as the actor? */
  466. if (strcmp(href, user->actor) == 0) {
  467. /* got it! */
  468. xs *verified_time = xs_number_new((double)time(NULL));
  469. if (user->links == NULL)
  470. user->links = xs_dict_new();
  471. user->links = xs_dict_set(user->links, v, verified_time);
  472. vfied = 1;
  473. }
  474. else
  475. snac_debug(user, 1,
  476. xs_fmt("verify link %s rel='me' found but not related (%s)", v, href));
  477. }
  478. }
  479. if (vfied) {
  480. changed++;
  481. snac_log(user, xs_fmt("link %s verified", v));
  482. }
  483. else {
  484. snac_log(user, xs_fmt("link %s not verified (rel='me' not found)", v));
  485. }
  486. }
  487. if (changed) {
  488. FILE *f;
  489. /* update the links.json file */
  490. xs *fn = xs_fmt("%s/links.json", user->basedir);
  491. xs *bfn = xs_fmt("%s.bak", fn);
  492. rename(fn, bfn);
  493. if ((f = fopen(fn, "w")) != NULL) {
  494. xs_json_dump(user->links, 4, f);
  495. fclose(f);
  496. }
  497. else
  498. rename(bfn, fn);
  499. }
  500. }
  501. void export_csv(snac *user)
  502. /* exports user data to current directory in a way that pleases Mastodon */
  503. {
  504. FILE *f;
  505. xs *fn = NULL;
  506. fn = xs_fmt("%s/export/bookmarks.csv", user->basedir);
  507. if ((f = fopen(fn, "w")) != NULL) {
  508. snac_log(user, xs_fmt("Creating %s...", fn));
  509. xs *l = bookmark_list(user);
  510. const char *md5;
  511. xs_list_foreach(l, md5) {
  512. xs *post = NULL;
  513. if (valid_status(object_get_by_md5(md5, &post))) {
  514. const char *id = xs_dict_get(post, "id");
  515. if (xs_type(id) == XSTYPE_STRING)
  516. fprintf(f, "%s\n", id);
  517. }
  518. }
  519. fclose(f);
  520. }
  521. else
  522. snac_log(user, xs_fmt("Cannot create file %s", fn));
  523. xs_free(fn);
  524. fn = xs_fmt("%s/export/blocked_accounts.csv", user->basedir);
  525. if ((f = fopen(fn, "w")) != NULL) {
  526. snac_log(user, xs_fmt("Creating %s...", fn));
  527. xs *l = muted_list(user);
  528. const char *actor;
  529. xs_list_foreach(l, actor) {
  530. xs *uid = NULL;
  531. webfinger_request_fake(actor, NULL, &uid);
  532. fprintf(f, "%s\n", uid);
  533. }
  534. fclose(f);
  535. }
  536. else
  537. snac_log(user, xs_fmt("Cannot create file %s", fn));
  538. xs_free(fn);
  539. fn = xs_fmt("%s/export/lists.csv", user->basedir);
  540. if ((f = fopen(fn, "w")) != NULL) {
  541. snac_log(user, xs_fmt("Creating %s...", fn));
  542. xs *lol = list_maint(user, NULL, 0);
  543. const xs_list *li;
  544. xs_list_foreach(lol, li) {
  545. const char *lid = xs_list_get(li, 0);
  546. const char *ltitle = xs_list_get(li, 1);
  547. xs *actors = list_members(user, lid, NULL, 0);
  548. const char *md5;
  549. xs_list_foreach(actors, md5) {
  550. xs *actor = NULL;
  551. if (valid_status(object_get_by_md5(md5, &actor))) {
  552. const char *id = xs_dict_get(actor, "id");
  553. xs *uid = NULL;
  554. webfinger_request_fake(id, NULL, &uid);
  555. fprintf(f, "%s,%s\n", ltitle, uid);
  556. }
  557. }
  558. }
  559. fclose(f);
  560. }
  561. else
  562. snac_log(user, xs_fmt("Cannot create file %s", fn));
  563. xs_free(fn);
  564. fn = xs_fmt("%s/export/following_accounts.csv", user->basedir);
  565. if ((f = fopen(fn, "w")) != NULL) {
  566. snac_log(user, xs_fmt("Creating %s...", fn));
  567. fprintf(f, "Account address,Show boosts,Notify on new posts,Languages\n");
  568. xs *fwing = following_list(user);
  569. const char *actor;
  570. xs_list_foreach(fwing, actor) {
  571. xs *uid = NULL;
  572. webfinger_request_fake(actor, NULL, &uid);
  573. fprintf(f, "%s,%s,false,\n", uid, limited(user, actor, 0) ? "false" : "true");
  574. }
  575. fclose(f);
  576. }
  577. else
  578. snac_log(user, xs_fmt("Cannot create file %s", fn));
  579. }
  580. void export_posts(snac *user)
  581. /* exports all posts to an OrderedCollection */
  582. {
  583. xs *ifn = xs_fmt("%s/public.idx", user->basedir);
  584. xs *index = index_list(ifn, XS_ALL);
  585. xs *ofn = xs_fmt("%s/export/outbox.json", user->basedir);
  586. FILE *f;
  587. if ((f = fopen(ofn, "w")) == NULL) {
  588. snac_log(user, xs_fmt("Cannot create file %s", ofn));
  589. return;
  590. }
  591. int cnt = 0;
  592. /* raw output */
  593. fprintf(f, "{\"@context\": \"https:/" "/www.w3.org/ns/activitystreams\",");
  594. fprintf(f, "\"id\": \"outbox.json\",");
  595. fprintf(f, "\"type\": \"OrderedCollection\",");
  596. fprintf(f, "\"orderedItems\": [");
  597. const char *md5;
  598. snac_log(user, xs_fmt("Creating %s...", ofn));
  599. xs_list_foreach(index, md5) {
  600. xs *obj = NULL;
  601. if (!valid_status(object_get_by_md5(md5, &obj)))
  602. continue;
  603. const char *type = xs_dict_get(obj, "type");
  604. if (!xs_is_string(type) || strcmp(type, "Note"))
  605. continue;
  606. const char *atto = get_atto(obj);
  607. if (!xs_is_string(atto) || strcmp(atto, user->actor))
  608. continue;
  609. if (cnt)
  610. fprintf(f, ",");
  611. xs *c_msg = msg_create(user, obj);
  612. xs_json_dump(c_msg, 0, f);
  613. cnt++;
  614. }
  615. fprintf(f, "], \"totalItems\": %d}", cnt);
  616. fclose(f);
  617. }
  618. void import_blocked_accounts_csv(snac *user, const char *ifn)
  619. /* imports a Mastodon CSV file of blocked accounts */
  620. {
  621. FILE *f;
  622. xs *l = xs_split(ifn, "/");
  623. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  624. if ((f = fopen(fn, "r")) != NULL) {
  625. snac_log(user, xs_fmt("Importing from %s...", fn));
  626. while (!feof(f)) {
  627. xs *l = xs_strip_i(xs_readline(f));
  628. if (*l && strchr(l, '@') != NULL) {
  629. xs *url = NULL;
  630. xs *uid = NULL;
  631. if (valid_status(webfinger_request(l, &url, &uid))) {
  632. if (is_muted(user, url))
  633. snac_log(user, xs_fmt("Actor %s already MUTEd", url));
  634. else {
  635. mute(user, url);
  636. snac_log(user, xs_fmt("MUTEd actor %s", url));
  637. }
  638. }
  639. else
  640. snac_log(user, xs_fmt("Webfinger error for account %s", l));
  641. }
  642. }
  643. fclose(f);
  644. }
  645. else
  646. snac_log(user, xs_fmt("Cannot open file %s", fn));
  647. }
  648. void import_following_accounts_csv(snac *user, const char *ifn)
  649. /* imports a Mastodon CSV file of accounts to follow */
  650. {
  651. FILE *f;
  652. xs *l = xs_split(ifn, "/");
  653. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  654. if ((f = fopen(fn, "r")) != NULL) {
  655. snac_log(user, xs_fmt("Importing from %s...", fn));
  656. while (!feof(f)) {
  657. xs *l = xs_strip_i(xs_readline(f));
  658. if (*l) {
  659. xs *l2 = xs_split(l, ",");
  660. const char *acct = xs_list_get(l2, 0);
  661. const char *show = xs_list_get(l2, 1);
  662. if (acct) {
  663. /* not a valid account? skip (probably the CSV header) */
  664. if (strchr(acct, '@') == NULL)
  665. continue;
  666. xs *msg = msg_follow(user, acct);
  667. if (msg == NULL) {
  668. snac_log(user, xs_fmt("Cannot follow %s -- server down?", acct));
  669. continue;
  670. }
  671. const char *actor = xs_dict_get(msg, "object");
  672. if (following_check(user, actor))
  673. snac_log(user, xs_fmt("Actor %s already followed", actor));
  674. else {
  675. following_add(user, actor, msg);
  676. enqueue_output_by_actor(user, msg, actor, 0);
  677. snac_log(user, xs_fmt("Following %s", actor));
  678. }
  679. if (show && strcmp(show, "false") == 0) {
  680. limit(user, actor);
  681. snac_log(user, xs_fmt("Limiting boosts from actor %s", actor));
  682. }
  683. else {
  684. unlimit(user, actor);
  685. snac_log(user, xs_fmt("Unlimiting boosts from actor %s", actor));
  686. }
  687. }
  688. }
  689. }
  690. fclose(f);
  691. }
  692. else
  693. snac_log(user, xs_fmt("Cannot open file %s", fn));
  694. }
  695. void import_list_csv(snac *user, const char *ifn)
  696. /* imports a Mastodon CSV file list */
  697. {
  698. FILE *f;
  699. xs *l = xs_split(ifn, "/");
  700. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  701. if ((f = fopen(fn, "r")) != NULL) {
  702. snac_log(user, xs_fmt("Importing from %s...", fn));
  703. while (!feof(f)) {
  704. xs *l = xs_strip_i(xs_readline(f));
  705. if (*l) {
  706. xs *l2 = xs_split(l, ",");
  707. const char *lname = xs_list_get(l2, 0);
  708. const char *acct = xs_list_get(l2, 1);
  709. if (lname && acct) {
  710. /* create the list */
  711. xs *list_id = list_maint(user, lname, 1);
  712. xs *url = NULL;
  713. xs *uid = NULL;
  714. if (valid_status(webfinger_request(acct, &url, &uid))) {
  715. xs *actor_md5 = xs_md5_hex(url, strlen(url));
  716. list_members(user, list_id, actor_md5, 1);
  717. snac_log(user, xs_fmt("Added %s to list %s", url, lname));
  718. if (!following_check(user, url)) {
  719. xs *msg = msg_follow(user, url);
  720. if (msg == NULL) {
  721. snac_log(user, xs_fmt("Cannot follow %s -- server down?", acct));
  722. continue;
  723. }
  724. following_add(user, url, msg);
  725. enqueue_output_by_actor(user, msg, url, 0);
  726. snac_log(user, xs_fmt("Following %s", url));
  727. }
  728. }
  729. else
  730. snac_log(user, xs_fmt("Webfinger error while adding %s to list %s", acct, lname));
  731. }
  732. }
  733. }
  734. fclose(f);
  735. }
  736. else
  737. snac_log(user, xs_fmt("Cannot open file %s", fn));
  738. }
  739. void import_csv(snac *user)
  740. /* import CSV files from Mastodon */
  741. {
  742. FILE *f;
  743. import_blocked_accounts_csv(user, "blocked_accounts.csv");
  744. import_following_accounts_csv(user, "following_accounts.csv");
  745. import_list_csv(user, "lists.csv");
  746. xs *fn = xs_fmt("%s/import/bookmarks.csv", user->basedir);
  747. if ((f = fopen(fn, "r")) != NULL) {
  748. snac_log(user, xs_fmt("Importing from %s...", fn));
  749. while (!feof(f)) {
  750. xs *l = xs_strip_i(xs_readline(f));
  751. if (*l) {
  752. xs *post = NULL;
  753. if (!valid_status(object_get(l, &post))) {
  754. if (!valid_status(activitypub_request(user, l, &post))) {
  755. snac_log(user, xs_fmt("Error getting object %s for bookmarking", l));
  756. continue;
  757. }
  758. }
  759. if (post == NULL)
  760. continue;
  761. /* request the actor that created the post */
  762. const char *actor = get_atto(post);
  763. if (xs_type(actor) == XSTYPE_STRING)
  764. actor_request(user, actor, NULL);
  765. object_add_ow(l, post);
  766. timeline_add(user, l, post);
  767. bookmark(user, l);
  768. snac_log(user, xs_fmt("Bookmarked %s", l));
  769. }
  770. }
  771. fclose(f);
  772. }
  773. else
  774. snac_log(user, xs_fmt("Cannot open file %s", fn));
  775. }
  776. static const struct {
  777. const char *proto;
  778. unsigned short default_port;
  779. } FALLBACK_PORTS[] = {
  780. /* caution: https > http, smpts > smtp */
  781. {"https", 443},
  782. {"http", 80},
  783. {"smtps", 465},
  784. {"smtp", 25}
  785. };
  786. int parse_port(const char *url, const char **errstr)
  787. {
  788. const char *col, *rcol;
  789. int tmp, ret = -1;
  790. if (errstr)
  791. *errstr = NULL;
  792. if (!(col = strchr(url, ':'))) {
  793. if (errstr)
  794. *errstr = "bad url";
  795. return -1;
  796. }
  797. for (size_t i = 0; i < sizeof(FALLBACK_PORTS) / sizeof(*FALLBACK_PORTS); ++i) {
  798. if (memcmp(url, FALLBACK_PORTS[i].proto, strlen(FALLBACK_PORTS[i].proto)) == 0) {
  799. ret = FALLBACK_PORTS[i].default_port;
  800. break;
  801. }
  802. }
  803. if (!(rcol = strchr(col + 1, ':')))
  804. rcol = col;
  805. if (rcol) {
  806. tmp = atoi(rcol + 1);
  807. if (tmp == 0) {
  808. if (ret != -1)
  809. return ret;
  810. if (errstr)
  811. *errstr = strerror(errno);
  812. return -1;
  813. }
  814. return tmp;
  815. }
  816. if (errstr)
  817. *errstr = "unknown protocol";
  818. return -1;
  819. }