utils.c 32 KB

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