data.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 - 2023 grunfink / MIT license */
  3. #include "xs.h"
  4. #include "xs_io.h"
  5. #include "xs_json.h"
  6. #include "xs_openssl.h"
  7. #include "xs_glob.h"
  8. #include "xs_set.h"
  9. #include "snac.h"
  10. #include <time.h>
  11. #include <sys/stat.h>
  12. #include <sys/file.h>
  13. #include <fcntl.h>
  14. double disk_layout = 2.7;
  15. int snac_upgrade(d_char **error);
  16. int srv_open(char *basedir, int auto_upgrade)
  17. /* opens a server */
  18. {
  19. int ret = 0;
  20. xs *cfg_file = NULL;
  21. FILE *f;
  22. d_char *error = NULL;
  23. srv_basedir = xs_str_new(basedir);
  24. if (xs_endswith(srv_basedir, "/"))
  25. srv_basedir = xs_crop_i(srv_basedir, 0, -1);
  26. cfg_file = xs_fmt("%s/server.json", basedir);
  27. if ((f = fopen(cfg_file, "r")) == NULL)
  28. error = xs_fmt("ERROR: cannot opening '%s'", cfg_file);
  29. else {
  30. xs *cfg_data;
  31. /* read full config file */
  32. cfg_data = xs_readall(f);
  33. fclose(f);
  34. /* parse */
  35. srv_config = xs_json_loads(cfg_data);
  36. if (srv_config == NULL)
  37. error = xs_fmt("ERROR: cannot parse '%s'", cfg_file);
  38. else {
  39. char *host;
  40. char *prefix;
  41. char *dbglvl;
  42. host = xs_dict_get(srv_config, "host");
  43. prefix = xs_dict_get(srv_config, "prefix");
  44. dbglvl = xs_dict_get(srv_config, "dbglevel");
  45. if (host == NULL || prefix == NULL)
  46. error = xs_str_new("ERROR: cannot get server data");
  47. else {
  48. srv_baseurl = xs_fmt("https://%s%s", host, prefix);
  49. dbglevel = (int) xs_number_get(dbglvl);
  50. if ((dbglvl = getenv("DEBUG")) != NULL) {
  51. dbglevel = atoi(dbglvl);
  52. error = xs_fmt("DEBUG level set to %d from environment", dbglevel);
  53. }
  54. if (auto_upgrade)
  55. ret = snac_upgrade(&error);
  56. else {
  57. if (xs_number_get(xs_dict_get(srv_config, "layout")) < disk_layout)
  58. error = xs_fmt("ERROR: disk layout changed - execute 'snac upgrade' first");
  59. else
  60. ret = 1;
  61. }
  62. }
  63. }
  64. }
  65. if (error != NULL)
  66. srv_log(error);
  67. #ifdef __OpenBSD__
  68. char *v = xs_dict_get(srv_config, "disable_openbsd_security");
  69. if (v && xs_type(v) == XSTYPE_TRUE) {
  70. srv_debug(1, xs_dup("OpenBSD security disabled by admin"));
  71. }
  72. else {
  73. srv_debug(1, xs_fmt("Calling unveil()"));
  74. unveil(basedir, "rwc");
  75. unveil("/usr/sbin/sendmail", "x");
  76. unveil("/etc/resolv.conf", "r");
  77. unveil("/etc/hosts", "r");
  78. unveil("/etc/ssl/openssl.cnf", "r");
  79. unveil("/etc/ssl/cert.pem", "r");
  80. unveil("/usr/share/zoneinfo", "r");
  81. unveil(NULL, NULL);
  82. srv_debug(1, xs_fmt("Calling pledge()"));
  83. pledge("stdio rpath wpath cpath flock inet proc exec dns", NULL);
  84. }
  85. #endif /* __OpenBSD__ */
  86. return ret;
  87. }
  88. void srv_free(void)
  89. {
  90. xs_free(srv_basedir);
  91. xs_free(srv_config);
  92. xs_free(srv_baseurl);
  93. }
  94. void user_free(snac *snac)
  95. /* frees a user snac */
  96. {
  97. xs_free(snac->uid);
  98. xs_free(snac->basedir);
  99. xs_free(snac->config);
  100. xs_free(snac->key);
  101. xs_free(snac->actor);
  102. xs_free(snac->md5);
  103. }
  104. int user_open(snac *snac, const char *uid)
  105. /* opens a user */
  106. {
  107. int ret = 0;
  108. memset(snac, '\0', sizeof(struct _snac));
  109. if (validate_uid(uid)) {
  110. xs *cfg_file;
  111. FILE *f;
  112. snac->uid = xs_str_new(uid);
  113. snac->basedir = xs_fmt("%s/user/%s", srv_basedir, uid);
  114. cfg_file = xs_fmt("%s/user.json", snac->basedir);
  115. if ((f = fopen(cfg_file, "r")) != NULL) {
  116. xs *cfg_data;
  117. /* read full config file */
  118. cfg_data = xs_readall(f);
  119. fclose(f);
  120. if ((snac->config = xs_json_loads(cfg_data)) != NULL) {
  121. xs *key_file = xs_fmt("%s/key.json", snac->basedir);
  122. if ((f = fopen(key_file, "r")) != NULL) {
  123. xs *key_data;
  124. key_data = xs_readall(f);
  125. fclose(f);
  126. if ((snac->key = xs_json_loads(key_data)) != NULL) {
  127. snac->actor = xs_fmt("%s/%s", srv_baseurl, uid);
  128. snac->md5 = xs_md5_hex(snac->actor, strlen(snac->actor));
  129. ret = 1;
  130. }
  131. else
  132. srv_log(xs_fmt("cannot parse '%s'", key_file));
  133. }
  134. else
  135. srv_log(xs_fmt("error opening '%s'", key_file));
  136. }
  137. else
  138. srv_log(xs_fmt("cannot parse '%s'", cfg_file));
  139. }
  140. else
  141. srv_debug(2, xs_fmt("error opening '%s'", cfg_file));
  142. }
  143. else
  144. srv_log(xs_fmt("invalid user '%s'", uid));
  145. if (!ret)
  146. user_free(snac);
  147. return ret;
  148. }
  149. d_char *user_list(void)
  150. /* returns the list of user ids */
  151. {
  152. xs *spec = xs_fmt("%s/user/" "*", srv_basedir);
  153. return xs_glob(spec, 1, 0);
  154. }
  155. double mtime_nl(const char *fn, int *n_link)
  156. /* returns the mtime and number of links of a file or directory, or 0.0 */
  157. {
  158. struct stat st;
  159. double r = 0.0;
  160. int n = 0;
  161. if (fn && stat(fn, &st) != -1) {
  162. r = (double) st.st_mtim.tv_sec;
  163. n = st.st_nlink;
  164. }
  165. if (n_link)
  166. *n_link = n;
  167. return r;
  168. }
  169. /** database 2.1+ **/
  170. /** indexes **/
  171. int index_add_md5(const char *fn, const char *md5)
  172. /* adds an md5 to an index */
  173. {
  174. int status = 201; /* Created */
  175. FILE *f;
  176. if ((f = fopen(fn, "a")) != NULL) {
  177. flock(fileno(f), LOCK_EX);
  178. /* ensure the position is at the end after getting the lock */
  179. fseek(f, 0, SEEK_END);
  180. fprintf(f, "%s\n", md5);
  181. fclose(f);
  182. }
  183. else
  184. status = 500;
  185. return status;
  186. }
  187. int index_add(const char *fn, const char *id)
  188. /* adds an id to an index */
  189. {
  190. xs *md5 = xs_md5_hex(id, strlen(id));
  191. return index_add_md5(fn, md5);
  192. }
  193. int index_del_md5(const char *fn, const char *md5)
  194. /* deletes an md5 from an index */
  195. {
  196. int status = 404;
  197. FILE *i, *o;
  198. if ((i = fopen(fn, "r")) != NULL) {
  199. flock(fileno(i), LOCK_EX);
  200. xs *nfn = xs_fmt("%s.new", fn);
  201. char line[256];
  202. if ((o = fopen(nfn, "w")) != NULL) {
  203. while (fgets(line, sizeof(line), i) != NULL) {
  204. line[32] = '\0';
  205. if (memcmp(line, md5, 32) != 0)
  206. fprintf(o, "%s\n", line);
  207. }
  208. fclose(o);
  209. xs *ofn = xs_fmt("%s.bak", fn);
  210. link(fn, ofn);
  211. rename(nfn, fn);
  212. }
  213. else
  214. status = 500;
  215. fclose(i);
  216. }
  217. else
  218. status = 500;
  219. return status;
  220. }
  221. int index_del(const char *fn, const char *id)
  222. /* deletes an id from an index */
  223. {
  224. xs *md5 = xs_md5_hex(id, strlen(id));
  225. return index_del_md5(fn, md5);
  226. }
  227. int index_in_md5(const char *fn, const char *md5)
  228. /* checks if the md5 is already in the index */
  229. {
  230. FILE *f;
  231. int ret = 0;
  232. if ((f = fopen(fn, "r")) != NULL) {
  233. flock(fileno(f), LOCK_SH);
  234. char line[256];
  235. while (!ret && fgets(line, sizeof(line), f) != NULL) {
  236. line[32] = '\0';
  237. if (strcmp(line, md5) == 0)
  238. ret = 1;
  239. }
  240. fclose(f);
  241. }
  242. return ret;
  243. }
  244. int index_in(const char *fn, const char *id)
  245. /* checks if the object id is already in the index */
  246. {
  247. xs *md5 = xs_md5_hex(id, strlen(id));
  248. return index_in_md5(fn, md5);
  249. }
  250. int index_first(const char *fn, char *line, int size)
  251. /* reads the first entry of an index */
  252. {
  253. FILE *f;
  254. int ret = 0;
  255. if ((f = fopen(fn, "r")) != NULL) {
  256. flock(fileno(f), LOCK_SH);
  257. if (fgets(line, size, f) != NULL) {
  258. line[32] = '\0';
  259. ret = 1;
  260. }
  261. fclose(f);
  262. }
  263. return ret;
  264. }
  265. int index_len(const char *fn)
  266. /* returns the number of elements in an index */
  267. {
  268. struct stat st;
  269. int len = 0;
  270. if (stat(fn, &st) != -1)
  271. len = st.st_size / 33;
  272. return len;
  273. }
  274. d_char *index_list(const char *fn, int max)
  275. /* returns an index as a list */
  276. {
  277. d_char *list = NULL;
  278. FILE *f;
  279. int n = 0;
  280. if ((f = fopen(fn, "r")) != NULL) {
  281. flock(fileno(f), LOCK_SH);
  282. char line[256];
  283. list = xs_list_new();
  284. while (n < max && fgets(line, sizeof(line), f) != NULL) {
  285. line[32] = '\0';
  286. list = xs_list_append(list, line);
  287. n++;
  288. }
  289. fclose(f);
  290. }
  291. return list;
  292. }
  293. d_char *index_list_desc(const char *fn, int skip, int show)
  294. /* returns an index as a list, in reverse order */
  295. {
  296. d_char *list = NULL;
  297. FILE *f;
  298. int n = 0;
  299. if ((f = fopen(fn, "r")) != NULL) {
  300. flock(fileno(f), LOCK_SH);
  301. char line[256];
  302. list = xs_list_new();
  303. /* move to the end minus one entry (or more, if skipping entries) */
  304. if (!fseek(f, 0, SEEK_END) && !fseek(f, (skip + 1) * -33, SEEK_CUR)) {
  305. while (n < show && fgets(line, sizeof(line), f) != NULL) {
  306. line[32] = '\0';
  307. list = xs_list_append(list, line);
  308. n++;
  309. /* move backwards 2 entries */
  310. if (fseek(f, -66, SEEK_CUR) == -1)
  311. break;
  312. }
  313. }
  314. fclose(f);
  315. }
  316. return list;
  317. }
  318. /** objects **/
  319. d_char *_object_fn_by_md5(const char *md5)
  320. {
  321. xs *bfn = xs_fmt("%s/object/%c%c", srv_basedir, md5[0], md5[1]);
  322. mkdir(bfn, 0755);
  323. return xs_fmt("%s/%s.json", bfn, md5);
  324. }
  325. d_char *_object_fn(const char *id)
  326. {
  327. xs *md5 = xs_md5_hex(id, strlen(id));
  328. return _object_fn_by_md5(md5);
  329. }
  330. int object_here_by_md5(char *id)
  331. /* checks if an object is already downloaded */
  332. {
  333. xs *fn = _object_fn_by_md5(id);
  334. return mtime(fn) > 0.0;
  335. }
  336. int object_here(char *id)
  337. /* checks if an object is already downloaded */
  338. {
  339. xs *fn = _object_fn(id);
  340. return mtime(fn) > 0.0;
  341. }
  342. int object_get_by_md5(const char *md5, d_char **obj, const char *type)
  343. /* returns a stored object, optionally of the requested type */
  344. {
  345. int status = 404;
  346. xs *fn = _object_fn_by_md5(md5);
  347. FILE *f;
  348. if ((f = fopen(fn, "r")) != NULL) {
  349. flock(fileno(f), LOCK_SH);
  350. xs *j = xs_readall(f);
  351. fclose(f);
  352. *obj = xs_json_loads(j);
  353. if (*obj) {
  354. status = 200;
  355. /* specific type requested? */
  356. if (!xs_is_null(type)) {
  357. char *v = xs_dict_get(*obj, "type");
  358. if (xs_is_null(v) || strcmp(v, type) != 0) {
  359. status = 404;
  360. *obj = xs_free(*obj);
  361. }
  362. }
  363. }
  364. }
  365. else
  366. *obj = NULL;
  367. return status;
  368. }
  369. int object_get(const char *id, d_char **obj, const char *type)
  370. /* returns a stored object, optionally of the requested type */
  371. {
  372. xs *md5 = xs_md5_hex(id, strlen(id));
  373. return object_get_by_md5(md5, obj, type);
  374. }
  375. int _object_add(const char *id, d_char *obj, int ow)
  376. /* stores an object */
  377. {
  378. int status = 201; /* Created */
  379. xs *fn = _object_fn(id);
  380. FILE *f;
  381. if (!ow && mtime(fn) > 0.0) {
  382. /* object already here */
  383. srv_debug(1, xs_fmt("object_add object already here %s", id));
  384. return 204; /* No content */
  385. }
  386. if ((f = fopen(fn, "w")) != NULL) {
  387. flock(fileno(f), LOCK_EX);
  388. xs *j = xs_json_dumps_pp(obj, 4);
  389. fwrite(j, strlen(j), 1, f);
  390. fclose(f);
  391. /* does this object has a parent? */
  392. char *in_reply_to = xs_dict_get(obj, "inReplyTo");
  393. if (!xs_is_null(in_reply_to) && *in_reply_to) {
  394. /* update the children index of the parent */
  395. xs *c_idx = _object_fn(in_reply_to);
  396. c_idx = xs_replace_i(c_idx, ".json", "_c.idx");
  397. if (!index_in(c_idx, id)) {
  398. index_add(c_idx, id);
  399. srv_debug(1, xs_fmt("object_add added child %s to %s", id, c_idx));
  400. }
  401. else
  402. srv_debug(1, xs_fmt("object_add %s child already in %s", id, c_idx));
  403. /* create a one-element index with the parent */
  404. xs *p_idx = xs_replace(fn, ".json", "_p.idx");
  405. if (mtime(p_idx) == 0.0) {
  406. index_add(p_idx, in_reply_to);
  407. srv_debug(1, xs_fmt("object_add added parent %s to %s", in_reply_to, p_idx));
  408. }
  409. }
  410. }
  411. else {
  412. srv_log(xs_fmt("object_add error writing %s (errno: %d)", fn, errno));
  413. status = 500;
  414. }
  415. srv_debug(1, xs_fmt("object_add %s %s %d", id, fn, status));
  416. return status;
  417. }
  418. int object_add(const char *id, d_char *obj)
  419. /* stores an object */
  420. {
  421. return _object_add(id, obj, 0);
  422. }
  423. int object_add_ow(const char *id, d_char *obj)
  424. /* stores an object (overwriting allowed) */
  425. {
  426. return _object_add(id, obj, 1);
  427. }
  428. int object_del_by_md5(const char *md5)
  429. /* deletes an object by its md5 */
  430. {
  431. int status = 404;
  432. xs *fn = _object_fn_by_md5(md5);
  433. if (fn != NULL && unlink(fn) != -1) {
  434. status = 200;
  435. /* also delete associated indexes */
  436. xs *spec = xs_dup(fn);
  437. spec = xs_replace_i(spec, ".json", "*.idx");
  438. xs *files = xs_glob(spec, 0, 0);
  439. char *p, *v;
  440. p = files;
  441. while (xs_list_iter(&p, &v)) {
  442. srv_debug(1, xs_fmt("object_del index %s", v));
  443. unlink(v);
  444. }
  445. }
  446. srv_debug(1, xs_fmt("object_del %s %d", fn, status));
  447. return status;
  448. }
  449. int object_del(const char *id)
  450. /* deletes an object */
  451. {
  452. xs *md5 = xs_md5_hex(id, strlen(id));
  453. return object_del_by_md5(md5);
  454. }
  455. int object_del_if_unref(const char *id)
  456. /* deletes an object if its n_links < 2 */
  457. {
  458. xs *fn = _object_fn(id);
  459. int n_links;
  460. int ret = 0;
  461. if (mtime_nl(fn, &n_links) > 0.0 && n_links < 2)
  462. ret = object_del(id);
  463. return ret;
  464. }
  465. d_char *_object_index_fn(const char *id, const char *idxsfx)
  466. /* returns the filename of an object's index */
  467. {
  468. d_char *fn = _object_fn(id);
  469. return xs_replace_i(fn, ".json", idxsfx);
  470. }
  471. int object_likes_len(const char *id)
  472. /* returns the number of likes (without reading the index) */
  473. {
  474. xs *fn = _object_index_fn(id, "_l.idx");
  475. return index_len(fn);
  476. }
  477. int object_announces_len(const char *id)
  478. /* returns the number of announces (without reading the index) */
  479. {
  480. xs *fn = _object_index_fn(id, "_a.idx");
  481. return index_len(fn);
  482. }
  483. d_char *object_children(const char *id)
  484. /* returns the list of an object's children */
  485. {
  486. xs *fn = _object_index_fn(id, "_c.idx");
  487. return index_list(fn, XS_ALL);
  488. }
  489. d_char *object_likes(const char *id)
  490. {
  491. xs *fn = _object_index_fn(id, "_l.idx");
  492. return index_list(fn, XS_ALL);
  493. }
  494. d_char *object_announces(const char *id)
  495. {
  496. xs *fn = _object_index_fn(id, "_a.idx");
  497. return index_list(fn, XS_ALL);
  498. }
  499. int object_parent(const char *id, char *buf, int size)
  500. /* returns the object parent, if any */
  501. {
  502. xs *fn = _object_fn_by_md5(id);
  503. fn = xs_replace_i(fn, ".json", "_p.idx");
  504. return index_first(fn, buf, size);
  505. }
  506. int object_admire(const char *id, const char *actor, int like)
  507. /* actor likes or announces this object */
  508. {
  509. int status = 200;
  510. xs *fn = _object_fn(id);
  511. fn = xs_replace_i(fn, ".json", like ? "_l.idx" : "_a.idx");
  512. if (!index_in(fn, actor)) {
  513. status = index_add(fn, actor);
  514. srv_debug(1, xs_fmt("object_admire (%s) %s %s", like ? "Like" : "Announce", actor, fn));
  515. }
  516. return status;
  517. }
  518. int _object_user_cache(snac *snac, const char *id, const char *cachedir, int del)
  519. /* adds or deletes from a user cache */
  520. {
  521. xs *ofn = _object_fn(id);
  522. xs *l = xs_split(ofn, "/");
  523. xs *cfn = xs_fmt("%s/%s/%s", snac->basedir, cachedir, xs_list_get(l, -1));
  524. xs *idx = xs_fmt("%s/%s.idx", snac->basedir, cachedir);
  525. int ret;
  526. if (del) {
  527. if ((ret = unlink(cfn)) != -1)
  528. index_del(idx, id);
  529. }
  530. else {
  531. if ((ret = link(ofn, cfn)) != -1)
  532. index_add(idx, id);
  533. }
  534. return ret;
  535. }
  536. int object_user_cache_add(snac *snac, const char *id, const char *cachedir)
  537. /* caches an object into a user cache */
  538. {
  539. return _object_user_cache(snac, id, cachedir, 0);
  540. }
  541. int object_user_cache_del(snac *snac, const char *id, const char *cachedir)
  542. /* deletes an object from a user cache */
  543. {
  544. return _object_user_cache(snac, id, cachedir, 1);
  545. }
  546. int object_user_cache_in(snac *snac, const char *id, const char *cachedir)
  547. /* checks if an object is stored in a cache */
  548. {
  549. xs *md5 = xs_md5_hex(id, strlen(id));
  550. xs *cfn = xs_fmt("%s/%s/%s.json", snac->basedir, cachedir, md5);
  551. return !!(mtime(cfn) != 0.0);
  552. }
  553. d_char *object_user_cache_list(snac *snac, const char *cachedir, int max)
  554. /* returns the objects in a cache as a list */
  555. {
  556. xs *idx = xs_fmt("%s/%s.idx", snac->basedir, cachedir);
  557. return index_list(idx, max);
  558. }
  559. /** specialized functions **/
  560. /** followers **/
  561. int follower_add(snac *snac, const char *actor)
  562. /* adds a follower */
  563. {
  564. int ret = object_user_cache_add(snac, actor, "followers");
  565. snac_debug(snac, 2, xs_fmt("follower_add %s", actor));
  566. return ret == -1 ? 500 : 200;
  567. }
  568. int follower_del(snac *snac, const char *actor)
  569. /* deletes a follower */
  570. {
  571. int ret = object_user_cache_del(snac, actor, "followers");
  572. snac_debug(snac, 2, xs_fmt("follower_del %s", actor));
  573. return ret == -1 ? 404 : 200;
  574. }
  575. int follower_check(snac *snac, const char *actor)
  576. /* checks if someone is a follower */
  577. {
  578. return object_user_cache_in(snac, actor, "followers");
  579. }
  580. d_char *follower_list(snac *snac)
  581. /* returns the list of followers */
  582. {
  583. xs *list = object_user_cache_list(snac, "followers", XS_ALL);
  584. d_char *fwers = xs_list_new();
  585. char *p, *v;
  586. /* resolve the list of md5 to be a list of actors */
  587. p = list;
  588. while (xs_list_iter(&p, &v)) {
  589. xs *a_obj = NULL;
  590. if (valid_status(object_get_by_md5(v, &a_obj, NULL))) {
  591. char *actor = xs_dict_get(a_obj, "id");
  592. if (!xs_is_null(actor))
  593. fwers = xs_list_append(fwers, actor);
  594. }
  595. }
  596. return fwers;
  597. }
  598. /** timeline **/
  599. double timeline_mtime(snac *snac)
  600. {
  601. xs *fn = xs_fmt("%s/private.idx", snac->basedir);
  602. return mtime(fn);
  603. }
  604. int timeline_del(snac *snac, char *id)
  605. /* deletes a message from the timeline */
  606. {
  607. /* delete from the user's caches */
  608. object_user_cache_del(snac, id, "public");
  609. object_user_cache_del(snac, id, "private");
  610. /* try to delete the object if it's not used elsewhere */
  611. return object_del_if_unref(id);
  612. }
  613. void timeline_update_indexes(snac *snac, const char *id)
  614. /* updates the indexes */
  615. {
  616. object_user_cache_add(snac, id, "private");
  617. if (xs_startswith(id, snac->actor)) {
  618. xs *msg = NULL;
  619. if (valid_status(object_get(id, &msg, NULL))) {
  620. /* if its ours and is public, also store in public */
  621. if (is_msg_public(snac, msg))
  622. object_user_cache_add(snac, id, "public");
  623. }
  624. }
  625. }
  626. int timeline_add(snac *snac, char *id, char *o_msg)
  627. /* adds a message to the timeline */
  628. {
  629. int ret = object_add(id, o_msg);
  630. timeline_update_indexes(snac, id);
  631. snac_debug(snac, 1, xs_fmt("timeline_add %s", id));
  632. return ret;
  633. }
  634. void timeline_admire(snac *snac, char *id, char *admirer, int like)
  635. /* updates a timeline entry with a new admiration */
  636. {
  637. /* if we are admiring this, add to both timelines */
  638. if (!like && strcmp(admirer, snac->actor) == 0) {
  639. object_user_cache_add(snac, id, "public");
  640. object_user_cache_add(snac, id, "private");
  641. }
  642. object_admire(id, admirer, like);
  643. snac_debug(snac, 1, xs_fmt("timeline_admire (%s) %s %s",
  644. like ? "Like" : "Announce", id, admirer));
  645. }
  646. d_char *timeline_top_level(d_char *list)
  647. /* returns the top level md5 entries from this index */
  648. {
  649. xs_set seen;
  650. char *p, *v;
  651. xs_set_init(&seen);
  652. p = list;
  653. while (xs_list_iter(&p, &v)) {
  654. char line[256] = "";
  655. strcpy(line, v);
  656. for (;;) {
  657. char line2[256];
  658. /* if it doesn't have a parent, use this */
  659. if (!object_parent(line, line2, sizeof(line2)))
  660. break;
  661. /* well, there is a parent... but if it's not there, use this */
  662. if (!object_here_by_md5(line2))
  663. break;
  664. /* it's here! try again with its own parent */
  665. strcpy(line, line2);
  666. }
  667. xs_set_add(&seen, line);
  668. }
  669. return xs_set_result(&seen);
  670. }
  671. d_char *timeline_simple_list(snac *snac, const char *idx_name, int skip, int show)
  672. /* returns a timeline (with all entries) */
  673. {
  674. int c_max;
  675. /* maximum number of items in the timeline */
  676. c_max = xs_number_get(xs_dict_get(srv_config, "max_timeline_entries"));
  677. /* never more timeline entries than the configured maximum */
  678. if (show > c_max)
  679. show = c_max;
  680. xs *idx = xs_fmt("%s/%s.idx", snac->basedir, idx_name);
  681. return index_list_desc(idx, skip, show);
  682. }
  683. d_char *timeline_list(snac *snac, const char *idx_name, int skip, int show)
  684. /* returns a timeline (only top level entries) */
  685. {
  686. xs *list = timeline_simple_list(snac, idx_name, skip, show);
  687. return timeline_top_level(list);
  688. }
  689. /** following **/
  690. /* this needs special treatment and cannot use the object db as is,
  691. with a link to a cached author, because we need the Follow object
  692. in case we need to unfollow (Undo + original Follow) */
  693. d_char *_following_fn(snac *snac, char *actor)
  694. {
  695. xs *md5 = xs_md5_hex(actor, strlen(actor));
  696. return xs_fmt("%s/following/%s.json", snac->basedir, md5);
  697. }
  698. int following_add(snac *snac, char *actor, char *msg)
  699. /* adds to the following list */
  700. {
  701. int ret = 201; /* created */
  702. xs *fn = _following_fn(snac, actor);
  703. FILE *f;
  704. if ((f = fopen(fn, "w")) != NULL) {
  705. xs *j = xs_json_dumps_pp(msg, 4);
  706. fwrite(j, 1, strlen(j), f);
  707. fclose(f);
  708. }
  709. else
  710. ret = 500;
  711. snac_debug(snac, 2, xs_fmt("following_add %s %s", actor, fn));
  712. return ret;
  713. }
  714. int following_del(snac *snac, char *actor)
  715. /* we're not following this actor any longer */
  716. {
  717. xs *fn = _following_fn(snac, actor);
  718. unlink(fn);
  719. snac_debug(snac, 2, xs_fmt("following_del %s %s", actor, fn));
  720. return 200;
  721. }
  722. int following_check(snac *snac, char *actor)
  723. /* checks if we are following this actor */
  724. {
  725. xs *fn = _following_fn(snac, actor);
  726. return !!(mtime(fn) != 0.0);
  727. }
  728. int following_get(snac *snac, char *actor, d_char **data)
  729. /* returns the 'Follow' object */
  730. {
  731. xs *fn = _following_fn(snac, actor);
  732. FILE *f;
  733. int status = 200;
  734. if ((f = fopen(fn, "r")) != NULL) {
  735. xs *j = xs_readall(f);
  736. fclose(f);
  737. *data = xs_json_loads(j);
  738. }
  739. else
  740. status = 404;
  741. return status;
  742. }
  743. d_char *following_list(snac *snac)
  744. /* returns the list of people being followed */
  745. {
  746. xs *spec = xs_fmt("%s/following/" "*.json", snac->basedir);
  747. xs *glist = xs_glob(spec, 0, 0);
  748. char *p, *v;
  749. d_char *list = xs_list_new();
  750. /* iterate the list of files */
  751. p = glist;
  752. while (xs_list_iter(&p, &v)) {
  753. FILE *f;
  754. /* load the follower data */
  755. if ((f = fopen(v, "r")) != NULL) {
  756. xs *j = xs_readall(f);
  757. fclose(f);
  758. if (j != NULL) {
  759. xs *o = xs_json_loads(j);
  760. if (o != NULL) {
  761. char *type = xs_dict_get(o, "type");
  762. if (!xs_is_null(type) && strcmp(type, "Accept") == 0) {
  763. char *actor = xs_dict_get(o, "actor");
  764. if (!xs_is_null(actor))
  765. list = xs_list_append(list, actor);
  766. }
  767. }
  768. }
  769. }
  770. }
  771. return list;
  772. }
  773. d_char *_muted_fn(snac *snac, char *actor)
  774. {
  775. xs *md5 = xs_md5_hex(actor, strlen(actor));
  776. return xs_fmt("%s/muted/%s", snac->basedir, md5);
  777. }
  778. void mute(snac *snac, char *actor)
  779. /* mutes a moron */
  780. {
  781. xs *fn = _muted_fn(snac, actor);
  782. FILE *f;
  783. if ((f = fopen(fn, "w")) != NULL) {
  784. fprintf(f, "%s\n", actor);
  785. fclose(f);
  786. snac_debug(snac, 2, xs_fmt("muted %s %s", actor, fn));
  787. }
  788. }
  789. void unmute(snac *snac, char *actor)
  790. /* actor is no longer a moron */
  791. {
  792. xs *fn = _muted_fn(snac, actor);
  793. unlink(fn);
  794. snac_debug(snac, 2, xs_fmt("unmuted %s %s", actor, fn));
  795. }
  796. int is_muted(snac *snac, char *actor)
  797. /* check if someone is muted */
  798. {
  799. xs *fn = _muted_fn(snac, actor);
  800. return !!(mtime(fn) != 0.0);
  801. }
  802. d_char *_hidden_fn(snac *snac, const char *id)
  803. {
  804. xs *md5 = xs_md5_hex(id, strlen(id));
  805. return xs_fmt("%s/hidden/%s", snac->basedir, md5);
  806. }
  807. void hide(snac *snac, const char *id)
  808. /* hides a message tree */
  809. {
  810. xs *fn = _hidden_fn(snac, id);
  811. FILE *f;
  812. if ((f = fopen(fn, "w")) != NULL) {
  813. fprintf(f, "%s\n", id);
  814. fclose(f);
  815. snac_debug(snac, 2, xs_fmt("hidden %s %s", id, fn));
  816. /* hide all the children */
  817. xs *chld = object_children(id);
  818. char *p, *v;
  819. p = chld;
  820. while (xs_list_iter(&p, &v)) {
  821. xs *co = NULL;
  822. /* resolve to get the id */
  823. if (valid_status(object_get_by_md5(v, &co, NULL))) {
  824. if ((v = xs_dict_get(co, "id")) != NULL)
  825. hide(snac, v);
  826. }
  827. }
  828. }
  829. }
  830. int is_hidden(snac *snac, const char *id)
  831. /* check is id is hidden */
  832. {
  833. xs *fn = _hidden_fn(snac, id);
  834. return !!(mtime(fn) != 0.0);
  835. }
  836. int actor_add(snac *snac, const char *actor, d_char *msg)
  837. /* adds an actor */
  838. {
  839. return object_add_ow(actor, msg);
  840. }
  841. int actor_get(snac *snac, const char *actor, d_char **data)
  842. /* returns an already downloaded actor */
  843. {
  844. int status = 200;
  845. d_char *d;
  846. if (strcmp(actor, snac->actor) == 0) {
  847. /* this actor */
  848. if (data)
  849. *data = msg_actor(snac);
  850. return status;
  851. }
  852. /* read the object */
  853. if (!valid_status(status = object_get(actor, &d, NULL)))
  854. return status;
  855. if (data)
  856. *data = d;
  857. else
  858. d = xs_free(d);
  859. xs *fn = _object_fn(actor);
  860. double max_time;
  861. /* maximum time for the actor data to be considered stale */
  862. max_time = 3600.0 * 36.0;
  863. if (mtime(fn) + max_time < (double) time(NULL)) {
  864. /* actor data exists but also stinks */
  865. FILE *f;
  866. if ((f = fopen(fn, "a")) != NULL) {
  867. /* write a blank at the end to 'touch' the file */
  868. fwrite(" ", 1, 1, f);
  869. fclose(f);
  870. }
  871. status = 205; /* "205: Reset Content" "110: Response Is Stale" */
  872. }
  873. return status;
  874. }
  875. d_char *_static_fn(snac *snac, const char *id)
  876. /* gets the filename for a static file */
  877. {
  878. return xs_fmt("%s/static/%s", snac->basedir, id);
  879. }
  880. int static_get(snac *snac, const char *id, d_char **data, int *size)
  881. /* returns static content */
  882. {
  883. xs *fn = _static_fn(snac, id);
  884. FILE *f;
  885. int status = 404;
  886. *size = XS_ALL;
  887. if ((f = fopen(fn, "rb")) != NULL) {
  888. *data = xs_read(f, size);
  889. fclose(f);
  890. status = 200;
  891. }
  892. return status;
  893. }
  894. void static_put(snac *snac, const char *id, const char *data, int size)
  895. /* writes status content */
  896. {
  897. xs *fn = _static_fn(snac, id);
  898. FILE *f;
  899. if ((f = fopen(fn, "wb")) != NULL) {
  900. fwrite(data, size, 1, f);
  901. fclose(f);
  902. }
  903. }
  904. d_char *_history_fn(snac *snac, char *id)
  905. /* gets the filename for the history */
  906. {
  907. return xs_fmt("%s/history/%s", snac->basedir, id);
  908. }
  909. double history_mtime(snac *snac, char * id)
  910. {
  911. double t = 0.0;
  912. xs *fn = _history_fn(snac, id);
  913. if (fn != NULL)
  914. t = mtime(fn);
  915. return t;
  916. }
  917. void history_add(snac *snac, char *id, char *content, int size)
  918. /* adds something to the history */
  919. {
  920. xs *fn = _history_fn(snac, id);
  921. FILE *f;
  922. if ((f = fopen(fn, "w")) != NULL) {
  923. fwrite(content, size, 1, f);
  924. fclose(f);
  925. }
  926. }
  927. d_char *history_get(snac *snac, char *id)
  928. {
  929. d_char *content = NULL;
  930. xs *fn = _history_fn(snac, id);
  931. FILE *f;
  932. if ((f = fopen(fn, "r")) != NULL) {
  933. content = xs_readall(f);
  934. fclose(f);
  935. }
  936. return content;
  937. }
  938. int history_del(snac *snac, char *id)
  939. {
  940. xs *fn = _history_fn(snac, id);
  941. return unlink(fn);
  942. }
  943. d_char *history_list(snac *snac)
  944. {
  945. xs *spec = xs_fmt("%s/history/" "*.html", snac->basedir);
  946. return xs_glob(spec, 1, 0);
  947. }
  948. /** the queue **/
  949. static xs_dict *_enqueue_put(const char *fn, xs_dict *msg)
  950. /* writes safely to the queue */
  951. {
  952. xs *tfn = xs_fmt("%s.tmp", fn);
  953. FILE *f;
  954. if ((f = fopen(tfn, "w")) != NULL) {
  955. xs *j = xs_json_dumps_pp(msg, 4);
  956. fwrite(j, strlen(j), 1, f);
  957. fclose(f);
  958. rename(tfn, fn);
  959. }
  960. return msg;
  961. }
  962. static xs_dict *_new_qmsg(const char *type, const xs_val *msg, int retries)
  963. /* creates a queue message */
  964. {
  965. int qrt = xs_number_get(xs_dict_get(srv_config, "queue_retry_minutes"));
  966. xs *ntid = tid(retries * 60 * qrt);
  967. xs *rn = xs_number_new(retries);
  968. xs_dict *qmsg = xs_dict_new();
  969. qmsg = xs_dict_append(qmsg, "type", type);
  970. qmsg = xs_dict_append(qmsg, "message", msg);
  971. qmsg = xs_dict_append(qmsg, "retries", rn);
  972. qmsg = xs_dict_append(qmsg, "ntid", ntid);
  973. return qmsg;
  974. }
  975. void enqueue_input(snac *snac, xs_dict *msg, xs_dict *req, int retries)
  976. /* enqueues an input message */
  977. {
  978. xs *qmsg = _new_qmsg("input", msg, retries);
  979. char *ntid = xs_dict_get(qmsg, "ntid");
  980. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  981. qmsg = xs_dict_append(qmsg, "req", req);
  982. qmsg = _enqueue_put(fn, qmsg);
  983. snac_debug(snac, 1, xs_fmt("enqueue_input %s", fn));
  984. }
  985. void enqueue_output(snac *snac, xs_dict *msg, xs_str *inbox, int retries)
  986. /* enqueues an output message to an inbox */
  987. {
  988. if (xs_startswith(inbox, snac->actor)) {
  989. snac_debug(snac, 1, xs_str_new("refusing enqueue to myself"));
  990. return;
  991. }
  992. xs *qmsg = _new_qmsg("output", msg, retries);
  993. char *ntid = xs_dict_get(qmsg, "ntid");
  994. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  995. qmsg = xs_dict_append(qmsg, "inbox", inbox);
  996. qmsg = _enqueue_put(fn, qmsg);
  997. snac_debug(snac, 1, xs_fmt("enqueue_output %s %s %d", inbox, fn, retries));
  998. }
  999. void enqueue_output_by_actor(snac *snac, xs_dict *msg, xs_str *actor, int retries)
  1000. /* enqueues an output message for an actor */
  1001. {
  1002. xs *inbox = get_actor_inbox(snac, actor);
  1003. if (!xs_is_null(inbox))
  1004. enqueue_output(snac, msg, inbox, retries);
  1005. else
  1006. snac_log(snac, xs_fmt("enqueue_output_by_actor cannot get inbox %s", actor));
  1007. }
  1008. void enqueue_email(snac *snac, xs_str *msg, int retries)
  1009. /* enqueues an email message to be sent */
  1010. {
  1011. xs *qmsg = _new_qmsg("email", msg, retries);
  1012. char *ntid = xs_dict_get(qmsg, "ntid");
  1013. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  1014. qmsg = _enqueue_put(fn, qmsg);
  1015. snac_debug(snac, 1, xs_fmt("enqueue_email %d", retries));
  1016. }
  1017. void enqueue_message(snac *snac, xs_dict *msg)
  1018. /* enqueues an output message */
  1019. {
  1020. xs *qmsg = _new_qmsg("message", msg, 0);
  1021. char *ntid = xs_dict_get(qmsg, "ntid");
  1022. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  1023. qmsg = _enqueue_put(fn, qmsg);
  1024. snac_debug(snac, 0, xs_fmt("enqueue_message %s", xs_dict_get(msg, "id")));
  1025. }
  1026. d_char *queue(snac *snac)
  1027. /* returns a list with filenames that can be dequeued */
  1028. {
  1029. xs *spec = xs_fmt("%s/queue/" "*.json", snac->basedir);
  1030. d_char *list = xs_list_new();
  1031. time_t t = time(NULL);
  1032. char *p, *v;
  1033. xs *fns = xs_glob(spec, 0, 0);
  1034. p = fns;
  1035. while (xs_list_iter(&p, &v)) {
  1036. /* get the retry time from the basename */
  1037. char *bn = strrchr(v, '/');
  1038. time_t t2 = atol(bn + 1);
  1039. if (t2 > t)
  1040. snac_debug(snac, 2, xs_fmt("queue not yet time for %s [%ld]", v, t));
  1041. else {
  1042. list = xs_list_append(list, v);
  1043. snac_debug(snac, 2, xs_fmt("queue ready for %s", v));
  1044. }
  1045. }
  1046. return list;
  1047. }
  1048. d_char *dequeue(snac *snac, char *fn)
  1049. /* dequeues a message */
  1050. {
  1051. FILE *f;
  1052. d_char *obj = NULL;
  1053. if ((f = fopen(fn, "r")) != NULL) {
  1054. /* delete right now */
  1055. unlink(fn);
  1056. xs *j = xs_readall(f);
  1057. obj = xs_json_loads(j);
  1058. fclose(f);
  1059. }
  1060. return obj;
  1061. }
  1062. /** the purge **/
  1063. static void _purge_file(const char *fn, time_t mt)
  1064. /* purge fn if it's older than days */
  1065. {
  1066. if (mtime(fn) < mt) {
  1067. /* older than the minimum time: delete it */
  1068. unlink(fn);
  1069. srv_debug(1, xs_fmt("purged %s", fn));
  1070. }
  1071. }
  1072. static void _purge_subdir(snac *snac, const char *subdir, int days)
  1073. /* purges all files in subdir older than days */
  1074. {
  1075. if (days) {
  1076. time_t mt = time(NULL) - days * 24 * 3600;
  1077. xs *spec = xs_fmt("%s/%s/" "*", snac->basedir, subdir);
  1078. xs *list = xs_glob(spec, 0, 0);
  1079. char *p, *v;
  1080. p = list;
  1081. while (xs_list_iter(&p, &v))
  1082. _purge_file(v, mt);
  1083. }
  1084. }
  1085. void purge_server(void)
  1086. /* purge global server data */
  1087. {
  1088. xs *spec = xs_fmt("%s/object/??", srv_basedir);
  1089. xs *dirs = xs_glob(spec, 0, 0);
  1090. char *p, *v;
  1091. time_t mt = time(NULL) - 7 * 24 * 3600;
  1092. p = dirs;
  1093. while (xs_list_iter(&p, &v)) {
  1094. xs *spec2 = xs_fmt("%s/" "*.json", v);
  1095. xs *files = xs_glob(spec2, 0, 0);
  1096. char *p2, *v2;
  1097. p2 = files;
  1098. while (xs_list_iter(&p2, &v2)) {
  1099. int n_link;
  1100. /* old and with no hard links? */
  1101. if (mtime_nl(v2, &n_link) < mt && n_link < 2) {
  1102. xs *s1 = xs_replace(v2, ".json", "");
  1103. xs *l = xs_split(s1, "/");
  1104. char *md5 = xs_list_get(l, -1);
  1105. object_del_by_md5(md5);
  1106. }
  1107. }
  1108. }
  1109. }
  1110. void purge_user(snac *snac)
  1111. /* do the purge for this user */
  1112. {
  1113. int days;
  1114. days = xs_number_get(xs_dict_get(srv_config, "timeline_purge_days"));
  1115. _purge_subdir(snac, "hidden", days);
  1116. _purge_subdir(snac, "private", days);
  1117. days = xs_number_get(xs_dict_get(srv_config, "local_purge_days"));
  1118. _purge_subdir(snac, "public", days);
  1119. }
  1120. void purge_all(void)
  1121. /* purge all users */
  1122. {
  1123. snac snac;
  1124. xs *list = user_list();
  1125. char *p, *uid;
  1126. p = list;
  1127. while (xs_list_iter(&p, &uid)) {
  1128. if (user_open(&snac, uid)) {
  1129. purge_user(&snac);
  1130. user_free(&snac);
  1131. }
  1132. }
  1133. purge_server();
  1134. }