utils.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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. printf("\nUser password is %s\n", pwd);
  306. printf("\nGo to %s/%s and continue configuring your user there.\n", srv_baseurl, uid);
  307. return 0;
  308. }
  309. int resetpwd(snac *snac)
  310. /* creates a new password for the user */
  311. {
  312. xs *clear_pwd = NULL;
  313. xs *hashed_pwd = NULL;
  314. xs *fn = xs_fmt("%s/user.json", snac->basedir);
  315. FILE *f;
  316. int ret = 0;
  317. new_password(snac->uid, &clear_pwd, &hashed_pwd);
  318. snac->config = xs_dict_set(snac->config, "passwd", hashed_pwd);
  319. if ((f = fopen(fn, "w")) != NULL) {
  320. xs_json_dump(snac->config, 4, f);
  321. fclose(f);
  322. printf("New password for user %s is %s\n", snac->uid, clear_pwd);
  323. }
  324. else {
  325. printf("ERROR: cannot write to %s\n", fn);
  326. ret = 1;
  327. }
  328. return ret;
  329. }
  330. void rm_rf(const char *dir)
  331. /* does an rm -rf (yes, I'm also scared) */
  332. {
  333. xs *d = xs_str_cat(xs_dup(dir), "/" "*");
  334. xs *l = xs_glob(d, 0, 0);
  335. xs_list *p = l;
  336. const xs_str *v;
  337. if (dbglevel >= 1)
  338. printf("Deleting directory %s\n", dir);
  339. while (xs_list_iter(&p, &v)) {
  340. struct stat st;
  341. if (stat(v, &st) != -1) {
  342. if (st.st_mode & S_IFDIR) {
  343. rm_rf(v);
  344. }
  345. else {
  346. if (dbglevel >= 1)
  347. printf("Deleting file %s\n", v);
  348. if (unlink(v) == -1)
  349. printf("ERROR: cannot delete file %s\n", v);
  350. }
  351. }
  352. else
  353. printf("ERROR: stat() fail for %s\n", v);
  354. }
  355. if (rmdir(dir) == -1)
  356. printf("ERROR: cannot delete directory %s\n", dir);
  357. }
  358. int deluser(snac *user)
  359. /* deletes a user */
  360. {
  361. int ret = 0;
  362. xs *fwers = following_list(user);
  363. xs_list *p = fwers;
  364. const xs_str *v;
  365. while (xs_list_iter(&p, &v)) {
  366. xs *object = NULL;
  367. if (valid_status(following_get(user, v, &object))) {
  368. xs *msg = msg_undo(user, xs_dict_get(object, "object"));
  369. following_del(user, v);
  370. enqueue_output_by_actor(user, msg, v, 0);
  371. printf("Unfollowing actor %s\n", v);
  372. }
  373. }
  374. grave(user->uid, 1);
  375. rm_rf(user->basedir);
  376. return ret;
  377. }
  378. void verify_links(snac *user)
  379. /* verifies a user's links */
  380. {
  381. xs *metadata = NULL;
  382. const xs_dict *md = xs_dict_get(user->config, "metadata");
  383. const char *k, *v;
  384. int changed = 0;
  385. xs *headers = xs_dict_new();
  386. headers = xs_dict_append(headers, "accept", "text/html");
  387. headers = xs_dict_append(headers, "user-agent", USER_AGENT " (link verify)");
  388. if (xs_type(md) == XSTYPE_DICT)
  389. metadata = xs_dup(md);
  390. else
  391. if (xs_type(md) == XSTYPE_STRING) {
  392. /* convert to dict for easier iteration */
  393. metadata = xs_dict_new();
  394. xs *l = xs_split(md, "\n");
  395. const char *ll;
  396. xs_list_foreach(l, ll) {
  397. xs *kv = xs_split_n(ll, "=", 1);
  398. const char *k = xs_list_get(kv, 0);
  399. const char *v = xs_list_get(kv, 1);
  400. if (k && v) {
  401. xs *kk = xs_strip_i(xs_dup(k));
  402. xs *vv = xs_strip_i(xs_dup(v));
  403. metadata = xs_dict_set(metadata, kk, vv);
  404. }
  405. }
  406. }
  407. int c = 0;
  408. while (metadata && xs_dict_next(metadata, &k, &v, &c)) {
  409. xs *wfinger = NULL;
  410. const char *ov = NULL;
  411. /* is it an account handle? */
  412. if (*v == '@' && strchr(v + 1, '@')) {
  413. /* resolve it via webfinger */
  414. if (valid_status(webfinger_request(v, &wfinger, NULL)) && xs_is_string(wfinger)) {
  415. ov = v;
  416. v = wfinger;
  417. /* store the alias */
  418. if (user->links == NULL)
  419. user->links = xs_dict_new();
  420. user->links = xs_dict_set(user->links, ov, v);
  421. changed++;
  422. }
  423. }
  424. /* not an https link? skip */
  425. if (!xs_startswith(v, "https:/" "/"))
  426. continue;
  427. int status;
  428. xs *req = NULL;
  429. xs *payload = NULL;
  430. int p_size = 0;
  431. req = xs_http_request("GET", v, headers, NULL, 0, &status,
  432. &payload, &p_size, 0);
  433. if (!valid_status(status)) {
  434. snac_log(user, xs_fmt("link %s verify error %d", v, status));
  435. continue;
  436. }
  437. /* extract the links */
  438. xs *ls = xs_regex_select(payload, "< *(a|link) +[^>]+>");
  439. xs_list *lp = ls;
  440. const char *ll;
  441. int vfied = 0;
  442. while (!vfied && xs_list_iter(&lp, &ll)) {
  443. /* extract href and rel */
  444. xs *r = xs_regex_select(ll, "(href|rel) *= *(\"[^\"]*\"|'[^']*')");
  445. /* must have both attributes */
  446. if (xs_list_len(r) != 2)
  447. continue;
  448. xs *href = NULL;
  449. int is_rel_me = 0;
  450. xs_list *pr = r;
  451. const char *ar;
  452. while (xs_list_iter(&pr, &ar)) {
  453. xs *nq = xs_dup(ar);
  454. nq = xs_replace_i(nq, "\"", "");
  455. nq = xs_replace_i(nq, "'", "");
  456. xs *r2 = xs_split_n(nq, "=", 1);
  457. if (xs_list_len(r2) != 2)
  458. continue;
  459. xs *ak = xs_strip_i(xs_dup(xs_list_get(r2, 0)));
  460. xs *av = xs_strip_i(xs_dup(xs_list_get(r2, 1)));
  461. if (strcmp(ak, "href") == 0)
  462. href = xs_dup(av);
  463. else
  464. if (strcmp(ak, "rel") == 0) {
  465. /* split the value by spaces */
  466. xs *vbs = xs_split(av, " ");
  467. /* is any of it "me"? */
  468. if (xs_list_in(vbs, "me") != -1)
  469. is_rel_me = 1;
  470. }
  471. }
  472. /* after all this acrobatics, do we have an href and a rel="me"? */
  473. if (href != NULL && is_rel_me) {
  474. /* is it the same as the actor? */
  475. if (strcmp(href, user->actor) == 0) {
  476. /* got it! */
  477. xs *verified_time = xs_number_new((double)time(NULL));
  478. if (user->links == NULL)
  479. user->links = xs_dict_new();
  480. user->links = xs_dict_set(user->links, v, verified_time);
  481. vfied = 1;
  482. }
  483. else
  484. snac_debug(user, 1,
  485. xs_fmt("verify link %s rel='me' found but not related (%s)", v, href));
  486. }
  487. }
  488. if (vfied) {
  489. changed++;
  490. snac_log(user, xs_fmt("link %s verified", v));
  491. }
  492. else {
  493. snac_log(user, xs_fmt("link %s not verified (rel='me' not found)", v));
  494. }
  495. }
  496. if (changed) {
  497. FILE *f;
  498. /* update the links.json file */
  499. xs *fn = xs_fmt("%s/links.json", user->basedir);
  500. xs *bfn = xs_fmt("%s.bak", fn);
  501. rename(fn, bfn);
  502. if ((f = fopen(fn, "w")) != NULL) {
  503. xs_json_dump(user->links, 4, f);
  504. fclose(f);
  505. }
  506. else
  507. rename(bfn, fn);
  508. }
  509. }
  510. void export_csv(snac *user)
  511. /* exports user data to current directory in a way that pleases Mastodon */
  512. {
  513. FILE *f;
  514. xs *fn = NULL;
  515. fn = xs_fmt("%s/export/bookmarks.csv", user->basedir);
  516. if ((f = fopen(fn, "w")) != NULL) {
  517. snac_log(user, xs_fmt("Creating %s...", fn));
  518. xs *l = bookmark_list(user);
  519. const char *md5;
  520. xs_list_foreach(l, md5) {
  521. xs *post = NULL;
  522. if (valid_status(object_get_by_md5(md5, &post))) {
  523. const char *id = xs_dict_get(post, "id");
  524. if (xs_type(id) == XSTYPE_STRING)
  525. fprintf(f, "%s\n", id);
  526. }
  527. }
  528. fclose(f);
  529. }
  530. else
  531. snac_log(user, xs_fmt("Cannot create file %s", fn));
  532. xs_free(fn);
  533. fn = xs_fmt("%s/export/blocked_accounts.csv", user->basedir);
  534. if ((f = fopen(fn, "w")) != NULL) {
  535. snac_log(user, xs_fmt("Creating %s...", fn));
  536. xs *l = muted_list(user);
  537. const char *actor;
  538. xs_list_foreach(l, actor) {
  539. xs *uid = NULL;
  540. webfinger_request_fake(actor, NULL, &uid);
  541. fprintf(f, "%s\n", uid);
  542. }
  543. fclose(f);
  544. }
  545. else
  546. snac_log(user, xs_fmt("Cannot create file %s", fn));
  547. xs_free(fn);
  548. fn = xs_fmt("%s/export/lists.csv", user->basedir);
  549. if ((f = fopen(fn, "w")) != NULL) {
  550. snac_log(user, xs_fmt("Creating %s...", fn));
  551. xs *lol = list_maint(user, NULL, 0);
  552. const xs_list *li;
  553. xs_list_foreach(lol, li) {
  554. const char *lid = xs_list_get(li, 0);
  555. const char *ltitle = xs_list_get(li, 1);
  556. xs *actors = list_members(user, lid, NULL, 0);
  557. const char *md5;
  558. xs_list_foreach(actors, md5) {
  559. xs *actor = NULL;
  560. if (valid_status(object_get_by_md5(md5, &actor))) {
  561. const char *id = xs_dict_get(actor, "id");
  562. xs *uid = NULL;
  563. webfinger_request_fake(id, NULL, &uid);
  564. fprintf(f, "%s,%s\n", ltitle, uid);
  565. }
  566. }
  567. }
  568. fclose(f);
  569. }
  570. else
  571. snac_log(user, xs_fmt("Cannot create file %s", fn));
  572. xs_free(fn);
  573. fn = xs_fmt("%s/export/following_accounts.csv", user->basedir);
  574. if ((f = fopen(fn, "w")) != NULL) {
  575. snac_log(user, xs_fmt("Creating %s...", fn));
  576. fprintf(f, "Account address,Show boosts,Notify on new posts,Languages\n");
  577. xs *fwing = following_list(user);
  578. const char *actor;
  579. xs_list_foreach(fwing, actor) {
  580. xs *uid = NULL;
  581. webfinger_request_fake(actor, NULL, &uid);
  582. fprintf(f, "%s,%s,false,\n", uid, limited(user, actor, 0) ? "false" : "true");
  583. }
  584. fclose(f);
  585. }
  586. else
  587. snac_log(user, xs_fmt("Cannot create file %s", fn));
  588. }
  589. void export_posts(snac *user)
  590. /* exports all posts to an OrderedCollection */
  591. {
  592. xs *ifn = xs_fmt("%s/public.idx", user->basedir);
  593. xs *index = index_list(ifn, XS_ALL);
  594. xs *ofn = xs_fmt("%s/export/outbox.json", user->basedir);
  595. FILE *f;
  596. if ((f = fopen(ofn, "w")) == NULL) {
  597. snac_log(user, xs_fmt("Cannot create file %s", ofn));
  598. return;
  599. }
  600. int cnt = 0;
  601. /* raw output */
  602. fprintf(f, "{\"@context\": \"https:/" "/www.w3.org/ns/activitystreams\",");
  603. fprintf(f, "\"id\": \"outbox.json\",");
  604. fprintf(f, "\"type\": \"OrderedCollection\",");
  605. fprintf(f, "\"orderedItems\": [");
  606. const char *md5;
  607. snac_log(user, xs_fmt("Creating %s...", ofn));
  608. xs_list_foreach(index, md5) {
  609. xs *obj = NULL;
  610. if (!valid_status(object_get_by_md5(md5, &obj)))
  611. continue;
  612. const char *type = xs_dict_get(obj, "type");
  613. if (!xs_is_string(type) || strcmp(type, "Note"))
  614. continue;
  615. const char *atto = get_atto(obj);
  616. if (!xs_is_string(atto) || strcmp(atto, user->actor))
  617. continue;
  618. if (cnt)
  619. fprintf(f, ",");
  620. xs *c_msg = msg_create(user, obj);
  621. xs_json_dump(c_msg, 0, f);
  622. cnt++;
  623. }
  624. fprintf(f, "], \"totalItems\": %d}", cnt);
  625. fclose(f);
  626. }
  627. void import_blocked_accounts_csv(snac *user, const char *ifn)
  628. /* imports a Mastodon CSV file of blocked accounts */
  629. {
  630. FILE *f;
  631. xs *l = xs_split(ifn, "/");
  632. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  633. if ((f = fopen(fn, "r")) != NULL) {
  634. snac_log(user, xs_fmt("Importing from %s...", fn));
  635. while (!feof(f)) {
  636. xs *l = xs_strip_i(xs_readline(f));
  637. if (*l && strchr(l, '@') != NULL) {
  638. xs *url = NULL;
  639. xs *uid = NULL;
  640. if (valid_status(webfinger_request(l, &url, &uid))) {
  641. if (is_muted(user, url))
  642. snac_log(user, xs_fmt("Actor %s already MUTEd", url));
  643. else {
  644. mute(user, url);
  645. snac_log(user, xs_fmt("MUTEd actor %s", url));
  646. }
  647. }
  648. else
  649. snac_log(user, xs_fmt("Webfinger error for account %s", l));
  650. }
  651. }
  652. fclose(f);
  653. }
  654. else
  655. snac_log(user, xs_fmt("Cannot open file %s", fn));
  656. }
  657. void import_following_accounts_csv(snac *user, const char *ifn)
  658. /* imports a Mastodon CSV file of accounts to follow */
  659. {
  660. FILE *f;
  661. xs *l = xs_split(ifn, "/");
  662. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  663. if ((f = fopen(fn, "r")) != NULL) {
  664. snac_log(user, xs_fmt("Importing from %s...", fn));
  665. while (!feof(f)) {
  666. xs *l = xs_strip_i(xs_readline(f));
  667. if (*l) {
  668. xs *l2 = xs_split(l, ",");
  669. const char *acct = xs_list_get(l2, 0);
  670. const char *show = xs_list_get(l2, 1);
  671. if (acct) {
  672. /* not a valid account? skip (probably the CSV header) */
  673. if (strchr(acct, '@') == NULL)
  674. continue;
  675. xs *msg = msg_follow(user, acct);
  676. if (msg == NULL) {
  677. snac_log(user, xs_fmt("Cannot follow %s -- server down?", acct));
  678. continue;
  679. }
  680. const char *actor = xs_dict_get(msg, "object");
  681. if (following_check(user, actor))
  682. snac_log(user, xs_fmt("Actor %s already followed", actor));
  683. else {
  684. following_add(user, actor, msg);
  685. enqueue_output_by_actor(user, msg, actor, 0);
  686. snac_log(user, xs_fmt("Following %s", actor));
  687. }
  688. if (show && strcmp(show, "false") == 0) {
  689. limit(user, actor);
  690. snac_log(user, xs_fmt("Limiting boosts from actor %s", actor));
  691. }
  692. else {
  693. unlimit(user, actor);
  694. snac_log(user, xs_fmt("Unlimiting boosts from actor %s", actor));
  695. }
  696. }
  697. }
  698. }
  699. fclose(f);
  700. }
  701. else
  702. snac_log(user, xs_fmt("Cannot open file %s", fn));
  703. }
  704. void import_list_csv(snac *user, const char *ifn)
  705. /* imports a Mastodon CSV file list */
  706. {
  707. FILE *f;
  708. xs *l = xs_split(ifn, "/");
  709. xs *fn = xs_fmt("%s/import/%s", user->basedir, xs_list_get(l, -1));
  710. if ((f = fopen(fn, "r")) != NULL) {
  711. snac_log(user, xs_fmt("Importing from %s...", fn));
  712. while (!feof(f)) {
  713. xs *l = xs_strip_i(xs_readline(f));
  714. if (*l) {
  715. xs *l2 = xs_split(l, ",");
  716. const char *lname = xs_list_get(l2, 0);
  717. const char *acct = xs_list_get(l2, 1);
  718. if (lname && acct) {
  719. /* create the list */
  720. xs *list_id = list_maint(user, lname, 1);
  721. xs *url = NULL;
  722. xs *uid = NULL;
  723. if (valid_status(webfinger_request(acct, &url, &uid))) {
  724. xs *actor_md5 = xs_md5_hex(url, strlen(url));
  725. list_members(user, list_id, actor_md5, 1);
  726. snac_log(user, xs_fmt("Added %s to list %s", url, lname));
  727. if (!following_check(user, url)) {
  728. xs *msg = msg_follow(user, url);
  729. if (msg == NULL) {
  730. snac_log(user, xs_fmt("Cannot follow %s -- server down?", acct));
  731. continue;
  732. }
  733. following_add(user, url, msg);
  734. enqueue_output_by_actor(user, msg, url, 0);
  735. snac_log(user, xs_fmt("Following %s", url));
  736. }
  737. }
  738. else
  739. snac_log(user, xs_fmt("Webfinger error while adding %s to list %s", acct, lname));
  740. }
  741. }
  742. }
  743. fclose(f);
  744. }
  745. else
  746. snac_log(user, xs_fmt("Cannot open file %s", fn));
  747. }
  748. void import_csv(snac *user)
  749. /* import CSV files from Mastodon */
  750. {
  751. FILE *f;
  752. import_blocked_accounts_csv(user, "blocked_accounts.csv");
  753. import_following_accounts_csv(user, "following_accounts.csv");
  754. import_list_csv(user, "lists.csv");
  755. xs *fn = xs_fmt("%s/import/bookmarks.csv", user->basedir);
  756. if ((f = fopen(fn, "r")) != NULL) {
  757. snac_log(user, xs_fmt("Importing from %s...", fn));
  758. while (!feof(f)) {
  759. xs *l = xs_strip_i(xs_readline(f));
  760. if (*l) {
  761. xs *post = NULL;
  762. if (!valid_status(object_get(l, &post))) {
  763. if (!valid_status(activitypub_request(user, l, &post))) {
  764. snac_log(user, xs_fmt("Error getting object %s for bookmarking", l));
  765. continue;
  766. }
  767. }
  768. if (post == NULL)
  769. continue;
  770. /* request the actor that created the post */
  771. const char *actor = get_atto(post);
  772. if (xs_type(actor) == XSTYPE_STRING)
  773. actor_request(user, actor, NULL);
  774. object_add_ow(l, post);
  775. timeline_add(user, l, post);
  776. bookmark(user, l);
  777. snac_log(user, xs_fmt("Bookmarked %s", l));
  778. }
  779. }
  780. fclose(f);
  781. }
  782. else
  783. snac_log(user, xs_fmt("Cannot open file %s", fn));
  784. }
  785. static int top_ten_sort(const void *v1, const void *v2)
  786. {
  787. const xs_list *l1 = *(const xs_list **)v1;
  788. const xs_list *l2 = *(const xs_list **)v2;
  789. const char *c1 = xs_list_get(l1, 3);
  790. const char *c2 = xs_list_get(l2, 3);
  791. return xs_cmp(c2, c1);
  792. }
  793. xs_list *user_top_ten(snac *user, int count)
  794. /* returns the top ten more popular posts by a user */
  795. {
  796. xs *idx = xs_fmt("%s/private.idx", user->basedir);
  797. xs *list = index_list(idx, XS_ALL);
  798. xs *u_list = xs_list_new();
  799. xs_set u;
  800. xs_set_init(&u);
  801. const char *md5;
  802. xs_list_foreach(list, md5) {
  803. xs *obj = NULL;
  804. if (!valid_status(object_get_by_md5(md5, &obj)))
  805. continue;
  806. const char *id = xs_dict_get_def(obj, "id", "-");
  807. if (!is_msg_mine(user, id))
  808. continue;
  809. if (xs_set_add(&u, id) != 1)
  810. continue;
  811. /* get metrics */
  812. int ls = object_likes_len(id);
  813. int as = object_announces_len(id);
  814. /* build the entry and convert to list */
  815. xs *s = xs_fmt("%s\t%d\t%d\t%010d", id, ls, as, ls + as);
  816. xs *l = xs_split(s, "\t");
  817. u_list = xs_list_append(u_list, l);
  818. }
  819. /* sort by the sum of likes and boosts */
  820. xs *s_list = xs_list_sort(u_list, top_ten_sort);
  821. xs_list *r = xs_list_new();
  822. const xs_list *i;
  823. xs_list_foreach(s_list, i) {
  824. r = xs_list_append(r, i);
  825. if (--count <= 0)
  826. break;
  827. }
  828. xs_set_free(&u);
  829. return r;
  830. }
  831. static const struct {
  832. const char *proto;
  833. unsigned short default_port;
  834. } FALLBACK_PORTS[] = {
  835. /* caution: https > http, smpts > smtp */
  836. {"https", 443},
  837. {"http", 80},
  838. {"smtps", 465},
  839. {"smtp", 25}
  840. };
  841. int parse_port(const char *url, const char **errstr)
  842. {
  843. const char *col, *rcol;
  844. int tmp, ret = -1;
  845. if (errstr)
  846. *errstr = NULL;
  847. if (!(col = strchr(url, ':'))) {
  848. if (errstr)
  849. *errstr = "bad url";
  850. return -1;
  851. }
  852. for (size_t i = 0; i < sizeof(FALLBACK_PORTS) / sizeof(*FALLBACK_PORTS); ++i) {
  853. if (memcmp(url, FALLBACK_PORTS[i].proto, strlen(FALLBACK_PORTS[i].proto)) == 0) {
  854. ret = FALLBACK_PORTS[i].default_port;
  855. break;
  856. }
  857. }
  858. if (!(rcol = strchr(col + 1, ':')))
  859. rcol = col;
  860. if (rcol) {
  861. tmp = atoi(rcol + 1);
  862. if (tmp == 0) {
  863. if (ret != -1)
  864. return ret;
  865. if (errstr)
  866. *errstr = strerror(errno);
  867. return -1;
  868. }
  869. return tmp;
  870. }
  871. if (errstr)
  872. *errstr = "unknown protocol";
  873. return -1;
  874. }