data.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977
  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. #include <pthread.h>
  15. double disk_layout = 2.7;
  16. /* storage serializer */
  17. pthread_mutex_t data_mutex = {0};
  18. int snac_upgrade(d_char **error);
  19. int srv_open(char *basedir, int auto_upgrade)
  20. /* opens a server */
  21. {
  22. int ret = 0;
  23. xs *cfg_file = NULL;
  24. FILE *f;
  25. d_char *error = NULL;
  26. pthread_mutex_init(&data_mutex, NULL);
  27. srv_basedir = xs_str_new(basedir);
  28. if (xs_endswith(srv_basedir, "/"))
  29. srv_basedir = xs_crop_i(srv_basedir, 0, -1);
  30. cfg_file = xs_fmt("%s/server.json", basedir);
  31. if ((f = fopen(cfg_file, "r")) == NULL)
  32. error = xs_fmt("ERROR: cannot opening '%s'", cfg_file);
  33. else {
  34. xs *cfg_data;
  35. /* read full config file */
  36. cfg_data = xs_readall(f);
  37. fclose(f);
  38. /* parse */
  39. srv_config = xs_json_loads(cfg_data);
  40. if (srv_config == NULL)
  41. error = xs_fmt("ERROR: cannot parse '%s'", cfg_file);
  42. else {
  43. char *host;
  44. char *prefix;
  45. char *dbglvl;
  46. host = xs_dict_get(srv_config, "host");
  47. prefix = xs_dict_get(srv_config, "prefix");
  48. dbglvl = xs_dict_get(srv_config, "dbglevel");
  49. if (host == NULL || prefix == NULL)
  50. error = xs_str_new("ERROR: cannot get server data");
  51. else {
  52. srv_baseurl = xs_fmt("https://%s%s", host, prefix);
  53. dbglevel = (int) xs_number_get(dbglvl);
  54. if ((dbglvl = getenv("DEBUG")) != NULL) {
  55. dbglevel = atoi(dbglvl);
  56. error = xs_fmt("DEBUG level set to %d from environment", dbglevel);
  57. }
  58. if (auto_upgrade)
  59. ret = snac_upgrade(&error);
  60. else {
  61. if (xs_number_get(xs_dict_get(srv_config, "layout")) < disk_layout)
  62. error = xs_fmt("ERROR: disk layout changed - execute 'snac upgrade' first");
  63. else
  64. ret = 1;
  65. }
  66. }
  67. }
  68. }
  69. if (error != NULL)
  70. srv_log(error);
  71. /* create the queue/ subdir, just in case */
  72. xs *qdir = xs_fmt("%s/queue", srv_basedir);
  73. mkdirx(qdir);
  74. xs *ibdir = xs_fmt("%s/inbox", srv_basedir);
  75. mkdirx(ibdir);
  76. #ifdef __OpenBSD__
  77. char *v = xs_dict_get(srv_config, "disable_openbsd_security");
  78. if (v && xs_type(v) == XSTYPE_TRUE) {
  79. srv_debug(1, xs_dup("OpenBSD security disabled by admin"));
  80. }
  81. else {
  82. srv_debug(1, xs_fmt("Calling unveil()"));
  83. unveil(basedir, "rwc");
  84. unveil("/usr/sbin/sendmail", "x");
  85. unveil("/etc/resolv.conf", "r");
  86. unveil("/etc/hosts", "r");
  87. unveil("/etc/ssl/openssl.cnf", "r");
  88. unveil("/etc/ssl/cert.pem", "r");
  89. unveil("/usr/share/zoneinfo", "r");
  90. unveil(NULL, NULL);
  91. srv_debug(1, xs_fmt("Calling pledge()"));
  92. pledge("stdio rpath wpath cpath flock inet proc exec dns fattr", NULL);
  93. }
  94. #endif /* __OpenBSD__ */
  95. return ret;
  96. }
  97. void srv_free(void)
  98. {
  99. xs_free(srv_basedir);
  100. xs_free(srv_config);
  101. xs_free(srv_baseurl);
  102. pthread_mutex_destroy(&data_mutex);
  103. }
  104. void user_free(snac *snac)
  105. /* frees a user snac */
  106. {
  107. xs_free(snac->uid);
  108. xs_free(snac->basedir);
  109. xs_free(snac->config);
  110. xs_free(snac->config_o);
  111. xs_free(snac->key);
  112. xs_free(snac->actor);
  113. xs_free(snac->md5);
  114. }
  115. int user_open(snac *snac, const char *uid)
  116. /* opens a user */
  117. {
  118. int ret = 0;
  119. memset(snac, '\0', sizeof(struct _snac));
  120. if (validate_uid(uid)) {
  121. xs *cfg_file;
  122. FILE *f;
  123. snac->uid = xs_str_new(uid);
  124. snac->basedir = xs_fmt("%s/user/%s", srv_basedir, uid);
  125. cfg_file = xs_fmt("%s/user.json", snac->basedir);
  126. if ((f = fopen(cfg_file, "r")) != NULL) {
  127. xs *cfg_data;
  128. /* read full config file */
  129. cfg_data = xs_readall(f);
  130. fclose(f);
  131. if ((snac->config = xs_json_loads(cfg_data)) != NULL) {
  132. xs *key_file = xs_fmt("%s/key.json", snac->basedir);
  133. if ((f = fopen(key_file, "r")) != NULL) {
  134. xs *key_data;
  135. key_data = xs_readall(f);
  136. fclose(f);
  137. if ((snac->key = xs_json_loads(key_data)) != NULL) {
  138. snac->actor = xs_fmt("%s/%s", srv_baseurl, uid);
  139. snac->md5 = xs_md5_hex(snac->actor, strlen(snac->actor));
  140. /* everything is ok right now */
  141. ret = 1;
  142. /* does it have a configuration override? */
  143. xs *cfg_file_o = xs_fmt("%s/user_o.json", snac->basedir);
  144. if ((f = fopen(cfg_file_o, "r")) != NULL) {
  145. xs *j = xs_readall(f);
  146. fclose(f);
  147. if ((snac->config_o = xs_json_loads(j)) == NULL)
  148. srv_log(xs_fmt("error parsing '%s'", cfg_file_o));
  149. }
  150. if (snac->config_o == NULL)
  151. snac->config_o = xs_dict_new();
  152. }
  153. else
  154. srv_log(xs_fmt("error parsing '%s'", key_file));
  155. }
  156. else
  157. srv_log(xs_fmt("error opening '%s' %d", key_file, errno));
  158. }
  159. else
  160. srv_log(xs_fmt("error parsing '%s'", cfg_file));
  161. }
  162. else
  163. srv_debug(2, xs_fmt("error opening '%s' %d", cfg_file, errno));
  164. }
  165. else
  166. srv_debug(1, xs_fmt("invalid user '%s'", uid));
  167. if (!ret)
  168. user_free(snac);
  169. return ret;
  170. }
  171. d_char *user_list(void)
  172. /* returns the list of user ids */
  173. {
  174. xs *spec = xs_fmt("%s/user/" "*", srv_basedir);
  175. return xs_glob(spec, 1, 0);
  176. }
  177. double mtime_nl(const char *fn, int *n_link)
  178. /* returns the mtime and number of links of a file or directory, or 0.0 */
  179. {
  180. struct stat st;
  181. double r = 0.0;
  182. int n = 0;
  183. if (fn && stat(fn, &st) != -1) {
  184. r = (double) st.st_mtim.tv_sec;
  185. n = st.st_nlink;
  186. }
  187. if (n_link)
  188. *n_link = n;
  189. return r;
  190. }
  191. /** database 2.1+ **/
  192. /** indexes **/
  193. int index_add_md5(const char *fn, const char *md5)
  194. /* adds an md5 to an index */
  195. {
  196. int status = 201; /* Created */
  197. FILE *f;
  198. pthread_mutex_lock(&data_mutex);
  199. if ((f = fopen(fn, "a")) != NULL) {
  200. flock(fileno(f), LOCK_EX);
  201. /* ensure the position is at the end after getting the lock */
  202. fseek(f, 0, SEEK_END);
  203. fprintf(f, "%s\n", md5);
  204. fclose(f);
  205. }
  206. else
  207. status = 500;
  208. pthread_mutex_unlock(&data_mutex);
  209. return status;
  210. }
  211. int index_add(const char *fn, const char *id)
  212. /* adds an id to an index */
  213. {
  214. xs *md5 = xs_md5_hex(id, strlen(id));
  215. return index_add_md5(fn, md5);
  216. }
  217. int index_gc(const char *fn)
  218. /* garbage-collects an index, deleting objects that are not here */
  219. {
  220. FILE *i, *o;
  221. int gc = -1;
  222. pthread_mutex_lock(&data_mutex);
  223. if ((i = fopen(fn, "r")) != NULL) {
  224. xs *nfn = xs_fmt("%s.new", fn);
  225. char line[256];
  226. if ((o = fopen(nfn, "w")) != NULL) {
  227. gc = 0;
  228. while (fgets(line, sizeof(line), i) != NULL) {
  229. line[32] = '\0';
  230. if (object_here_by_md5(line))
  231. fprintf(o, "%s\n", line);
  232. else
  233. gc++;
  234. }
  235. fclose(o);
  236. xs *ofn = xs_fmt("%s.bak", fn);
  237. unlink(ofn);
  238. link(fn, ofn);
  239. rename(nfn, fn);
  240. }
  241. fclose(i);
  242. }
  243. pthread_mutex_unlock(&data_mutex);
  244. return gc;
  245. }
  246. int index_in_md5(const char *fn, const char *md5)
  247. /* checks if the md5 is already in the index */
  248. {
  249. FILE *f;
  250. int ret = 0;
  251. if ((f = fopen(fn, "r")) != NULL) {
  252. flock(fileno(f), LOCK_SH);
  253. char line[256];
  254. while (!ret && fgets(line, sizeof(line), f) != NULL) {
  255. line[32] = '\0';
  256. if (strcmp(line, md5) == 0)
  257. ret = 1;
  258. }
  259. fclose(f);
  260. }
  261. return ret;
  262. }
  263. int index_in(const char *fn, const char *id)
  264. /* checks if the object id is already in the index */
  265. {
  266. xs *md5 = xs_md5_hex(id, strlen(id));
  267. return index_in_md5(fn, md5);
  268. }
  269. int index_first(const char *fn, char *line, int size)
  270. /* reads the first entry of an index */
  271. {
  272. FILE *f;
  273. int ret = 0;
  274. if ((f = fopen(fn, "r")) != NULL) {
  275. flock(fileno(f), LOCK_SH);
  276. if (fgets(line, size, f) != NULL) {
  277. line[32] = '\0';
  278. ret = 1;
  279. }
  280. fclose(f);
  281. }
  282. return ret;
  283. }
  284. int index_len(const char *fn)
  285. /* returns the number of elements in an index */
  286. {
  287. struct stat st;
  288. int len = 0;
  289. if (stat(fn, &st) != -1)
  290. len = st.st_size / 33;
  291. return len;
  292. }
  293. d_char *index_list(const char *fn, int max)
  294. /* returns an index as a list */
  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. while (n < max && fgets(line, sizeof(line), f) != NULL) {
  304. line[32] = '\0';
  305. list = xs_list_append(list, line);
  306. n++;
  307. }
  308. fclose(f);
  309. }
  310. return list;
  311. }
  312. d_char *index_list_desc(const char *fn, int skip, int show)
  313. /* returns an index as a list, in reverse order */
  314. {
  315. d_char *list = NULL;
  316. FILE *f;
  317. int n = 0;
  318. if ((f = fopen(fn, "r")) != NULL) {
  319. flock(fileno(f), LOCK_SH);
  320. char line[256];
  321. list = xs_list_new();
  322. /* move to the end minus one entry (or more, if skipping entries) */
  323. if (!fseek(f, 0, SEEK_END) && !fseek(f, (skip + 1) * -33, SEEK_CUR)) {
  324. while (n < show && fgets(line, sizeof(line), f) != NULL) {
  325. line[32] = '\0';
  326. list = xs_list_append(list, line);
  327. n++;
  328. /* move backwards 2 entries */
  329. if (fseek(f, -66, SEEK_CUR) == -1)
  330. break;
  331. }
  332. }
  333. fclose(f);
  334. }
  335. return list;
  336. }
  337. /** objects **/
  338. d_char *_object_fn_by_md5(const char *md5)
  339. {
  340. xs *bfn = xs_fmt("%s/object/%c%c", srv_basedir, md5[0], md5[1]);
  341. mkdirx(bfn);
  342. return xs_fmt("%s/%s.json", bfn, md5);
  343. }
  344. d_char *_object_fn(const char *id)
  345. {
  346. xs *md5 = xs_md5_hex(id, strlen(id));
  347. return _object_fn_by_md5(md5);
  348. }
  349. int object_here_by_md5(char *id)
  350. /* checks if an object is already downloaded */
  351. {
  352. xs *fn = _object_fn_by_md5(id);
  353. return mtime(fn) > 0.0;
  354. }
  355. int object_here(char *id)
  356. /* checks if an object is already downloaded */
  357. {
  358. xs *fn = _object_fn(id);
  359. return mtime(fn) > 0.0;
  360. }
  361. int object_get_by_md5(const char *md5, xs_dict **obj)
  362. /* returns a stored object, optionally of the requested type */
  363. {
  364. int status = 404;
  365. xs *fn = _object_fn_by_md5(md5);
  366. FILE *f;
  367. if ((f = fopen(fn, "r")) != NULL) {
  368. flock(fileno(f), LOCK_SH);
  369. xs *j = xs_readall(f);
  370. fclose(f);
  371. *obj = xs_json_loads(j);
  372. if (*obj)
  373. status = 200;
  374. }
  375. else
  376. *obj = NULL;
  377. return status;
  378. }
  379. int object_get(const char *id, xs_dict **obj)
  380. /* returns a stored object, optionally of the requested type */
  381. {
  382. xs *md5 = xs_md5_hex(id, strlen(id));
  383. return object_get_by_md5(md5, obj);
  384. }
  385. int _object_add(const char *id, d_char *obj, int ow)
  386. /* stores an object */
  387. {
  388. int status = 201; /* Created */
  389. xs *fn = _object_fn(id);
  390. FILE *f;
  391. if (!ow && mtime(fn) > 0.0) {
  392. /* object already here */
  393. srv_debug(1, xs_fmt("object_add object already here %s", id));
  394. return 204; /* No content */
  395. }
  396. if ((f = fopen(fn, "w")) != NULL) {
  397. flock(fileno(f), LOCK_EX);
  398. xs *j = xs_json_dumps_pp(obj, 4);
  399. fwrite(j, strlen(j), 1, f);
  400. fclose(f);
  401. /* does this object has a parent? */
  402. char *in_reply_to = xs_dict_get(obj, "inReplyTo");
  403. if (!xs_is_null(in_reply_to) && *in_reply_to) {
  404. /* update the children index of the parent */
  405. xs *c_idx = _object_fn(in_reply_to);
  406. c_idx = xs_replace_i(c_idx, ".json", "_c.idx");
  407. if (!index_in(c_idx, id)) {
  408. index_add(c_idx, id);
  409. srv_debug(1, xs_fmt("object_add added child %s to %s", id, c_idx));
  410. }
  411. else
  412. srv_debug(1, xs_fmt("object_add %s child already in %s", id, c_idx));
  413. /* create a one-element index with the parent */
  414. xs *p_idx = xs_replace(fn, ".json", "_p.idx");
  415. if (mtime(p_idx) == 0.0) {
  416. index_add(p_idx, in_reply_to);
  417. srv_debug(1, xs_fmt("object_add added parent %s to %s", in_reply_to, p_idx));
  418. }
  419. }
  420. }
  421. else {
  422. srv_log(xs_fmt("object_add error writing %s (errno: %d)", fn, errno));
  423. status = 500;
  424. }
  425. srv_debug(1, xs_fmt("object_add %s %s %d", id, fn, status));
  426. return status;
  427. }
  428. int object_add(const char *id, d_char *obj)
  429. /* stores an object */
  430. {
  431. return _object_add(id, obj, 0);
  432. }
  433. int object_add_ow(const char *id, d_char *obj)
  434. /* stores an object (overwriting allowed) */
  435. {
  436. return _object_add(id, obj, 1);
  437. }
  438. int object_del_by_md5(const char *md5)
  439. /* deletes an object by its md5 */
  440. {
  441. int status = 404;
  442. xs *fn = _object_fn_by_md5(md5);
  443. if (unlink(fn) != -1) {
  444. status = 200;
  445. /* also delete associated indexes */
  446. xs *spec = xs_dup(fn);
  447. spec = xs_replace_i(spec, ".json", "*.idx");
  448. xs *files = xs_glob(spec, 0, 0);
  449. char *p, *v;
  450. p = files;
  451. while (xs_list_iter(&p, &v)) {
  452. srv_debug(1, xs_fmt("object_del index %s", v));
  453. unlink(v);
  454. }
  455. }
  456. srv_debug(1, xs_fmt("object_del %s %d", fn, status));
  457. return status;
  458. }
  459. int object_del(const char *id)
  460. /* deletes an object */
  461. {
  462. xs *md5 = xs_md5_hex(id, strlen(id));
  463. return object_del_by_md5(md5);
  464. }
  465. int object_del_if_unref(const char *id)
  466. /* deletes an object if its n_links < 2 */
  467. {
  468. xs *fn = _object_fn(id);
  469. int n_links;
  470. int ret = 0;
  471. if (mtime_nl(fn, &n_links) > 0.0 && n_links < 2)
  472. ret = object_del(id);
  473. return ret;
  474. }
  475. d_char *_object_index_fn(const char *id, const char *idxsfx)
  476. /* returns the filename of an object's index */
  477. {
  478. d_char *fn = _object_fn(id);
  479. return xs_replace_i(fn, ".json", idxsfx);
  480. }
  481. int object_likes_len(const char *id)
  482. /* returns the number of likes (without reading the index) */
  483. {
  484. xs *fn = _object_index_fn(id, "_l.idx");
  485. return index_len(fn);
  486. }
  487. int object_announces_len(const char *id)
  488. /* returns the number of announces (without reading the index) */
  489. {
  490. xs *fn = _object_index_fn(id, "_a.idx");
  491. return index_len(fn);
  492. }
  493. d_char *object_children(const char *id)
  494. /* returns the list of an object's children */
  495. {
  496. xs *fn = _object_index_fn(id, "_c.idx");
  497. return index_list(fn, XS_ALL);
  498. }
  499. d_char *object_likes(const char *id)
  500. {
  501. xs *fn = _object_index_fn(id, "_l.idx");
  502. return index_list(fn, XS_ALL);
  503. }
  504. d_char *object_announces(const char *id)
  505. {
  506. xs *fn = _object_index_fn(id, "_a.idx");
  507. return index_list(fn, XS_ALL);
  508. }
  509. int object_parent(const char *id, char *buf, int size)
  510. /* returns the object parent, if any */
  511. {
  512. xs *fn = _object_fn_by_md5(id);
  513. fn = xs_replace_i(fn, ".json", "_p.idx");
  514. return index_first(fn, buf, size);
  515. }
  516. int object_admire(const char *id, const char *actor, int like)
  517. /* actor likes or announces this object */
  518. {
  519. int status = 200;
  520. xs *fn = _object_fn(id);
  521. fn = xs_replace_i(fn, ".json", like ? "_l.idx" : "_a.idx");
  522. if (!index_in(fn, actor)) {
  523. status = index_add(fn, actor);
  524. srv_debug(1, xs_fmt("object_admire (%s) %s %s", like ? "Like" : "Announce", actor, fn));
  525. }
  526. return status;
  527. }
  528. int _object_user_cache(snac *snac, const char *id, const char *cachedir, int del)
  529. /* adds or deletes from a user cache */
  530. {
  531. xs *ofn = _object_fn(id);
  532. xs *l = xs_split(ofn, "/");
  533. xs *cfn = xs_fmt("%s/%s/%s", snac->basedir, cachedir, xs_list_get(l, -1));
  534. xs *idx = xs_fmt("%s/%s.idx", snac->basedir, cachedir);
  535. int ret;
  536. if (del) {
  537. ret = unlink(cfn);
  538. }
  539. else {
  540. if ((ret = link(ofn, cfn)) != -1)
  541. index_add(idx, id);
  542. }
  543. return ret;
  544. }
  545. int object_user_cache_add(snac *snac, const char *id, const char *cachedir)
  546. /* caches an object into a user cache */
  547. {
  548. return _object_user_cache(snac, id, cachedir, 0);
  549. }
  550. int object_user_cache_del(snac *snac, const char *id, const char *cachedir)
  551. /* deletes an object from a user cache */
  552. {
  553. return _object_user_cache(snac, id, cachedir, 1);
  554. }
  555. int object_user_cache_in(snac *snac, const char *id, const char *cachedir)
  556. /* checks if an object is stored in a cache */
  557. {
  558. xs *md5 = xs_md5_hex(id, strlen(id));
  559. xs *cfn = xs_fmt("%s/%s/%s.json", snac->basedir, cachedir, md5);
  560. return !!(mtime(cfn) != 0.0);
  561. }
  562. d_char *object_user_cache_list(snac *snac, const char *cachedir, int max)
  563. /* returns the objects in a cache as a list */
  564. {
  565. xs *idx = xs_fmt("%s/%s.idx", snac->basedir, cachedir);
  566. return index_list(idx, max);
  567. }
  568. /** specialized functions **/
  569. /** followers **/
  570. int follower_add(snac *snac, const char *actor)
  571. /* adds a follower */
  572. {
  573. int ret = object_user_cache_add(snac, actor, "followers");
  574. snac_debug(snac, 2, xs_fmt("follower_add %s", actor));
  575. return ret == -1 ? 500 : 200;
  576. }
  577. int follower_del(snac *snac, const char *actor)
  578. /* deletes a follower */
  579. {
  580. int ret = object_user_cache_del(snac, actor, "followers");
  581. snac_debug(snac, 2, xs_fmt("follower_del %s", actor));
  582. return ret == -1 ? 404 : 200;
  583. }
  584. int follower_check(snac *snac, const char *actor)
  585. /* checks if someone is a follower */
  586. {
  587. return object_user_cache_in(snac, actor, "followers");
  588. }
  589. d_char *follower_list(snac *snac)
  590. /* returns the list of followers */
  591. {
  592. xs *list = object_user_cache_list(snac, "followers", XS_ALL);
  593. d_char *fwers = xs_list_new();
  594. char *p, *v;
  595. /* resolve the list of md5 to be a list of actors */
  596. p = list;
  597. while (xs_list_iter(&p, &v)) {
  598. xs *a_obj = NULL;
  599. if (valid_status(object_get_by_md5(v, &a_obj))) {
  600. char *actor = xs_dict_get(a_obj, "id");
  601. if (!xs_is_null(actor))
  602. fwers = xs_list_append(fwers, actor);
  603. }
  604. }
  605. return fwers;
  606. }
  607. /** timeline **/
  608. double timeline_mtime(snac *snac)
  609. {
  610. xs *fn = xs_fmt("%s/private.idx", snac->basedir);
  611. return mtime(fn);
  612. }
  613. xs_str *timeline_fn_by_md5(snac *snac, const char *md5)
  614. /* get the filename of an entry by md5 from any timeline */
  615. {
  616. xs_str *fn = xs_fmt("%s/private/%s.json", snac->basedir, md5);
  617. if (mtime(fn) == 0.0) {
  618. fn = xs_free(fn);
  619. fn = xs_fmt("%s/public/%s.json", snac->basedir, md5);
  620. if (mtime(fn) == 0.0)
  621. fn = xs_free(fn);
  622. }
  623. return fn;
  624. }
  625. int timeline_here(snac *snac, const char *md5)
  626. /* checks if an object is in the user cache */
  627. {
  628. xs *fn = timeline_fn_by_md5(snac, md5);
  629. return !(fn == NULL);
  630. }
  631. int timeline_get_by_md5(snac *snac, const char *md5, xs_dict **msg)
  632. /* gets a message from the timeline */
  633. {
  634. int status = 404;
  635. FILE *f = NULL;
  636. xs *fn = timeline_fn_by_md5(snac, md5);
  637. if (fn != NULL && (f = fopen(fn, "r")) != NULL) {
  638. flock(fileno(f), LOCK_SH);
  639. xs *j = xs_readall(f);
  640. fclose(f);
  641. if ((*msg = xs_json_loads(j)) != NULL)
  642. status = 200;
  643. }
  644. return status;
  645. }
  646. int timeline_del(snac *snac, char *id)
  647. /* deletes a message from the timeline */
  648. {
  649. /* delete from the user's caches */
  650. object_user_cache_del(snac, id, "public");
  651. object_user_cache_del(snac, id, "private");
  652. /* try to delete the object if it's not used elsewhere */
  653. return object_del_if_unref(id);
  654. }
  655. void timeline_update_indexes(snac *snac, const char *id)
  656. /* updates the indexes */
  657. {
  658. object_user_cache_add(snac, id, "private");
  659. if (xs_startswith(id, snac->actor)) {
  660. xs *msg = NULL;
  661. if (valid_status(object_get(id, &msg))) {
  662. /* if its ours and is public, also store in public */
  663. if (is_msg_public(snac, msg))
  664. object_user_cache_add(snac, id, "public");
  665. }
  666. }
  667. }
  668. int timeline_add(snac *snac, char *id, char *o_msg)
  669. /* adds a message to the timeline */
  670. {
  671. int ret = object_add(id, o_msg);
  672. timeline_update_indexes(snac, id);
  673. snac_debug(snac, 1, xs_fmt("timeline_add %s", id));
  674. return ret;
  675. }
  676. void timeline_admire(snac *snac, char *id, char *admirer, int like)
  677. /* updates a timeline entry with a new admiration */
  678. {
  679. /* if we are admiring this, add to both timelines */
  680. if (!like && strcmp(admirer, snac->actor) == 0) {
  681. object_user_cache_add(snac, id, "public");
  682. object_user_cache_add(snac, id, "private");
  683. }
  684. object_admire(id, admirer, like);
  685. snac_debug(snac, 1, xs_fmt("timeline_admire (%s) %s %s",
  686. like ? "Like" : "Announce", id, admirer));
  687. }
  688. xs_list *timeline_top_level(snac *snac, xs_list *list)
  689. /* returns the top level md5 entries from this index */
  690. {
  691. xs_set seen;
  692. xs_list *p;
  693. xs_str *v;
  694. xs_set_init(&seen);
  695. p = list;
  696. while (xs_list_iter(&p, &v)) {
  697. char line[256] = "";
  698. strcpy(line, v);
  699. for (;;) {
  700. char line2[256];
  701. /* if it doesn't have a parent, use this */
  702. if (!object_parent(line, line2, sizeof(line2)))
  703. break;
  704. /* well, there is a parent... but is it here? */
  705. if (!timeline_here(snac, line2))
  706. break;
  707. /* it's here! try again with its own parent */
  708. strcpy(line, line2);
  709. }
  710. xs_set_add(&seen, line);
  711. }
  712. return xs_set_result(&seen);
  713. }
  714. d_char *timeline_simple_list(snac *snac, const char *idx_name, int skip, int show)
  715. /* returns a timeline (with all entries) */
  716. {
  717. int c_max;
  718. /* maximum number of items in the timeline */
  719. c_max = xs_number_get(xs_dict_get(srv_config, "max_timeline_entries"));
  720. /* never more timeline entries than the configured maximum */
  721. if (show > c_max)
  722. show = c_max;
  723. xs *idx = xs_fmt("%s/%s.idx", snac->basedir, idx_name);
  724. return index_list_desc(idx, skip, show);
  725. }
  726. d_char *timeline_list(snac *snac, const char *idx_name, int skip, int show)
  727. /* returns a timeline (only top level entries) */
  728. {
  729. xs *list = timeline_simple_list(snac, idx_name, skip, show);
  730. return timeline_top_level(snac, list);
  731. }
  732. /** following **/
  733. /* this needs special treatment and cannot use the object db as is,
  734. with a link to a cached author, because we need the Follow object
  735. in case we need to unfollow (Undo + original Follow) */
  736. d_char *_following_fn(snac *snac, char *actor)
  737. {
  738. xs *md5 = xs_md5_hex(actor, strlen(actor));
  739. return xs_fmt("%s/following/%s.json", snac->basedir, md5);
  740. }
  741. int following_add(snac *snac, char *actor, char *msg)
  742. /* adds to the following list */
  743. {
  744. int ret = 201; /* created */
  745. xs *fn = _following_fn(snac, actor);
  746. FILE *f;
  747. if ((f = fopen(fn, "w")) != NULL) {
  748. xs *j = xs_json_dumps_pp(msg, 4);
  749. fwrite(j, 1, strlen(j), f);
  750. fclose(f);
  751. }
  752. else
  753. ret = 500;
  754. snac_debug(snac, 2, xs_fmt("following_add %s %s", actor, fn));
  755. return ret;
  756. }
  757. int following_del(snac *snac, char *actor)
  758. /* we're not following this actor any longer */
  759. {
  760. xs *fn = _following_fn(snac, actor);
  761. unlink(fn);
  762. snac_debug(snac, 2, xs_fmt("following_del %s %s", actor, fn));
  763. return 200;
  764. }
  765. int following_check(snac *snac, char *actor)
  766. /* checks if we are following this actor */
  767. {
  768. xs *fn = _following_fn(snac, actor);
  769. return !!(mtime(fn) != 0.0);
  770. }
  771. int following_get(snac *snac, char *actor, d_char **data)
  772. /* returns the 'Follow' object */
  773. {
  774. xs *fn = _following_fn(snac, actor);
  775. FILE *f;
  776. int status = 200;
  777. if ((f = fopen(fn, "r")) != NULL) {
  778. xs *j = xs_readall(f);
  779. fclose(f);
  780. *data = xs_json_loads(j);
  781. }
  782. else
  783. status = 404;
  784. return status;
  785. }
  786. d_char *following_list(snac *snac)
  787. /* returns the list of people being followed */
  788. {
  789. xs *spec = xs_fmt("%s/following/" "*.json", snac->basedir);
  790. xs *glist = xs_glob(spec, 0, 0);
  791. char *p, *v;
  792. d_char *list = xs_list_new();
  793. /* iterate the list of files */
  794. p = glist;
  795. while (xs_list_iter(&p, &v)) {
  796. FILE *f;
  797. /* load the follower data */
  798. if ((f = fopen(v, "r")) != NULL) {
  799. xs *j = xs_readall(f);
  800. fclose(f);
  801. if (j != NULL) {
  802. xs *o = xs_json_loads(j);
  803. if (o != NULL) {
  804. char *type = xs_dict_get(o, "type");
  805. if (!xs_is_null(type) && strcmp(type, "Accept") == 0) {
  806. char *actor = xs_dict_get(o, "actor");
  807. if (!xs_is_null(actor))
  808. list = xs_list_append(list, actor);
  809. }
  810. }
  811. }
  812. }
  813. }
  814. return list;
  815. }
  816. d_char *_muted_fn(snac *snac, char *actor)
  817. {
  818. xs *md5 = xs_md5_hex(actor, strlen(actor));
  819. return xs_fmt("%s/muted/%s", snac->basedir, md5);
  820. }
  821. void mute(snac *snac, char *actor)
  822. /* mutes a moron */
  823. {
  824. xs *fn = _muted_fn(snac, actor);
  825. FILE *f;
  826. if ((f = fopen(fn, "w")) != NULL) {
  827. fprintf(f, "%s\n", actor);
  828. fclose(f);
  829. snac_debug(snac, 2, xs_fmt("muted %s %s", actor, fn));
  830. }
  831. }
  832. void unmute(snac *snac, char *actor)
  833. /* actor is no longer a moron */
  834. {
  835. xs *fn = _muted_fn(snac, actor);
  836. unlink(fn);
  837. snac_debug(snac, 2, xs_fmt("unmuted %s %s", actor, fn));
  838. }
  839. int is_muted(snac *snac, char *actor)
  840. /* check if someone is muted */
  841. {
  842. xs *fn = _muted_fn(snac, actor);
  843. return !!(mtime(fn) != 0.0);
  844. }
  845. d_char *_hidden_fn(snac *snac, const char *id)
  846. {
  847. xs *md5 = xs_md5_hex(id, strlen(id));
  848. return xs_fmt("%s/hidden/%s", snac->basedir, md5);
  849. }
  850. void hide(snac *snac, const char *id)
  851. /* hides a message tree */
  852. {
  853. xs *fn = _hidden_fn(snac, id);
  854. FILE *f;
  855. if ((f = fopen(fn, "w")) != NULL) {
  856. fprintf(f, "%s\n", id);
  857. fclose(f);
  858. snac_debug(snac, 2, xs_fmt("hidden %s %s", id, fn));
  859. /* hide all the children */
  860. xs *chld = object_children(id);
  861. char *p, *v;
  862. p = chld;
  863. while (xs_list_iter(&p, &v)) {
  864. xs *co = NULL;
  865. /* resolve to get the id */
  866. if (valid_status(object_get_by_md5(v, &co))) {
  867. if ((v = xs_dict_get(co, "id")) != NULL)
  868. hide(snac, v);
  869. }
  870. }
  871. }
  872. }
  873. int is_hidden(snac *snac, const char *id)
  874. /* check is id is hidden */
  875. {
  876. xs *fn = _hidden_fn(snac, id);
  877. return !!(mtime(fn) != 0.0);
  878. }
  879. int actor_add(snac *snac, const char *actor, d_char *msg)
  880. /* adds an actor */
  881. {
  882. return object_add_ow(actor, msg);
  883. }
  884. int actor_get(snac *snac, const char *actor, d_char **data)
  885. /* returns an already downloaded actor */
  886. {
  887. int status = 200;
  888. d_char *d;
  889. if (strcmp(actor, snac->actor) == 0) {
  890. /* this actor */
  891. if (data)
  892. *data = msg_actor(snac);
  893. return status;
  894. }
  895. /* read the object */
  896. if (!valid_status(status = object_get(actor, &d)))
  897. return status;
  898. if (data)
  899. *data = d;
  900. else
  901. d = xs_free(d);
  902. xs *fn = _object_fn(actor);
  903. double max_time;
  904. /* maximum time for the actor data to be considered stale */
  905. max_time = 3600.0 * 36.0;
  906. if (mtime(fn) + max_time < (double) time(NULL)) {
  907. /* actor data exists but also stinks */
  908. FILE *f;
  909. if ((f = fopen(fn, "a")) != NULL) {
  910. /* write a blank at the end to 'touch' the file */
  911. fwrite(" ", 1, 1, f);
  912. fclose(f);
  913. }
  914. status = 205; /* "205: Reset Content" "110: Response Is Stale" */
  915. }
  916. return status;
  917. }
  918. d_char *_static_fn(snac *snac, const char *id)
  919. /* gets the filename for a static file */
  920. {
  921. return xs_fmt("%s/static/%s", snac->basedir, id);
  922. }
  923. int static_get(snac *snac, const char *id, d_char **data, int *size)
  924. /* returns static content */
  925. {
  926. xs *fn = _static_fn(snac, id);
  927. FILE *f;
  928. int status = 404;
  929. *size = XS_ALL;
  930. if ((f = fopen(fn, "rb")) != NULL) {
  931. *data = xs_read(f, size);
  932. fclose(f);
  933. status = 200;
  934. }
  935. return status;
  936. }
  937. void static_put(snac *snac, const char *id, const char *data, int size)
  938. /* writes status content */
  939. {
  940. xs *fn = _static_fn(snac, id);
  941. FILE *f;
  942. if ((f = fopen(fn, "wb")) != NULL) {
  943. fwrite(data, size, 1, f);
  944. fclose(f);
  945. }
  946. }
  947. d_char *_history_fn(snac *snac, char *id)
  948. /* gets the filename for the history */
  949. {
  950. return xs_fmt("%s/history/%s", snac->basedir, id);
  951. }
  952. double history_mtime(snac *snac, char * id)
  953. {
  954. double t = 0.0;
  955. xs *fn = _history_fn(snac, id);
  956. if (fn != NULL)
  957. t = mtime(fn);
  958. return t;
  959. }
  960. void history_add(snac *snac, char *id, char *content, int size)
  961. /* adds something to the history */
  962. {
  963. xs *fn = _history_fn(snac, id);
  964. FILE *f;
  965. if ((f = fopen(fn, "w")) != NULL) {
  966. fwrite(content, size, 1, f);
  967. fclose(f);
  968. }
  969. }
  970. d_char *history_get(snac *snac, char *id)
  971. {
  972. d_char *content = NULL;
  973. xs *fn = _history_fn(snac, id);
  974. FILE *f;
  975. if ((f = fopen(fn, "r")) != NULL) {
  976. content = xs_readall(f);
  977. fclose(f);
  978. }
  979. return content;
  980. }
  981. int history_del(snac *snac, char *id)
  982. {
  983. xs *fn = _history_fn(snac, id);
  984. return unlink(fn);
  985. }
  986. d_char *history_list(snac *snac)
  987. {
  988. xs *spec = xs_fmt("%s/history/" "*.html", snac->basedir);
  989. return xs_glob(spec, 1, 0);
  990. }
  991. void lastlog_write(snac *snac)
  992. /* writes the last time the user logged in */
  993. {
  994. xs *fn = xs_fmt("%s/lastlog.txt", snac->basedir);
  995. FILE *f;
  996. if ((f = fopen(fn, "w")) != NULL) {
  997. fprintf(f, "%lf\n", ftime());
  998. fclose(f);
  999. }
  1000. }
  1001. /** inbox collection **/
  1002. void inbox_add(const char *inbox)
  1003. /* collects a shared inbox */
  1004. {
  1005. xs *md5 = xs_md5_hex(inbox, strlen(inbox));
  1006. xs *fn = xs_fmt("%s/inbox/%s", srv_basedir, md5);
  1007. FILE *f;
  1008. if (strlen(inbox) < 256 && (f = fopen(fn, "w")) != NULL) {
  1009. pthread_mutex_lock(&data_mutex);
  1010. fprintf(f, "%s\n", inbox);
  1011. fclose(f);
  1012. pthread_mutex_unlock(&data_mutex);
  1013. }
  1014. }
  1015. void inbox_add_by_actor(const xs_dict *actor)
  1016. /* collects an actor's shared inbox, if it has one */
  1017. {
  1018. char *v;
  1019. if (!xs_is_null(v = xs_dict_get(actor, "endpoints")) &&
  1020. !xs_is_null(v = xs_dict_get(v, "sharedInbox")))
  1021. inbox_add(v);
  1022. }
  1023. xs_list *inbox_list(void)
  1024. /* returns the collected inboxes as a list */
  1025. {
  1026. xs_list *ibl = xs_list_new();
  1027. xs *spec = xs_fmt("%s/inbox/" "*", srv_basedir);
  1028. xs *files = xs_glob(spec, 0, 0);
  1029. xs_list *p = files;
  1030. xs_val *v;
  1031. while (xs_list_iter(&p, &v)) {
  1032. FILE *f;
  1033. if ((f = fopen(v, "r")) != NULL) {
  1034. char line[256];
  1035. if (fgets(line, sizeof(line), f)) {
  1036. fclose(f);
  1037. int i = strlen(line);
  1038. if (i) {
  1039. line[i - 1] = '\0';
  1040. ibl = xs_list_append(ibl, line);
  1041. }
  1042. }
  1043. }
  1044. }
  1045. return ibl;
  1046. }
  1047. /** the queue **/
  1048. static xs_dict *_enqueue_put(const char *fn, xs_dict *msg)
  1049. /* writes safely to the queue */
  1050. {
  1051. xs *tfn = xs_fmt("%s.tmp", fn);
  1052. FILE *f;
  1053. if ((f = fopen(tfn, "w")) != NULL) {
  1054. xs *j = xs_json_dumps_pp(msg, 4);
  1055. fwrite(j, strlen(j), 1, f);
  1056. fclose(f);
  1057. rename(tfn, fn);
  1058. }
  1059. return msg;
  1060. }
  1061. static xs_dict *_new_qmsg(const char *type, const xs_val *msg, int retries)
  1062. /* creates a queue message */
  1063. {
  1064. int qrt = xs_number_get(xs_dict_get(srv_config, "queue_retry_minutes"));
  1065. xs *ntid = tid(retries * 60 * qrt);
  1066. xs *rn = xs_number_new(retries);
  1067. xs_dict *qmsg = xs_dict_new();
  1068. qmsg = xs_dict_append(qmsg, "type", type);
  1069. qmsg = xs_dict_append(qmsg, "message", msg);
  1070. qmsg = xs_dict_append(qmsg, "retries", rn);
  1071. qmsg = xs_dict_append(qmsg, "ntid", ntid);
  1072. return qmsg;
  1073. }
  1074. void enqueue_input(snac *snac, xs_dict *msg, xs_dict *req, int retries)
  1075. /* enqueues an input message */
  1076. {
  1077. xs *qmsg = _new_qmsg("input", msg, retries);
  1078. char *ntid = xs_dict_get(qmsg, "ntid");
  1079. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  1080. qmsg = xs_dict_append(qmsg, "req", req);
  1081. qmsg = _enqueue_put(fn, qmsg);
  1082. snac_debug(snac, 1, xs_fmt("enqueue_input %s", fn));
  1083. }
  1084. void enqueue_output_raw(const char *keyid, const char *seckey,
  1085. xs_dict *msg, xs_str *inbox, int retries)
  1086. /* enqueues an output message to an inbox */
  1087. {
  1088. xs *qmsg = _new_qmsg("output", msg, retries);
  1089. char *ntid = xs_dict_get(qmsg, "ntid");
  1090. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  1091. qmsg = xs_dict_append(qmsg, "inbox", inbox);
  1092. qmsg = xs_dict_append(qmsg, "keyid", keyid);
  1093. qmsg = xs_dict_append(qmsg, "seckey", seckey);
  1094. /* if it's to be sent right now, bypass the disk queue and post the job */
  1095. if (retries == 0 && job_fifo_ready())
  1096. job_post(qmsg, 0);
  1097. else {
  1098. qmsg = _enqueue_put(fn, qmsg);
  1099. srv_debug(1, xs_fmt("enqueue_output %s %s %d", inbox, fn, retries));
  1100. }
  1101. }
  1102. void enqueue_output(snac *snac, xs_dict *msg, xs_str *inbox, int retries)
  1103. /* enqueues an output message to an inbox */
  1104. {
  1105. if (xs_startswith(inbox, snac->actor)) {
  1106. snac_debug(snac, 1, xs_str_new("refusing enqueue to myself"));
  1107. return;
  1108. }
  1109. char *seckey = xs_dict_get(snac->key, "secret");
  1110. enqueue_output_raw(snac->actor, seckey, msg, inbox, retries);
  1111. }
  1112. void enqueue_output_by_actor(snac *snac, xs_dict *msg, xs_str *actor, int retries)
  1113. /* enqueues an output message for an actor */
  1114. {
  1115. xs *inbox = get_actor_inbox(snac, actor);
  1116. if (!xs_is_null(inbox))
  1117. enqueue_output(snac, msg, inbox, retries);
  1118. else
  1119. snac_log(snac, xs_fmt("enqueue_output_by_actor cannot get inbox %s", actor));
  1120. }
  1121. void enqueue_email(xs_str *msg, int retries)
  1122. /* enqueues an email message to be sent */
  1123. {
  1124. xs *qmsg = _new_qmsg("email", msg, retries);
  1125. char *ntid = xs_dict_get(qmsg, "ntid");
  1126. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  1127. qmsg = _enqueue_put(fn, qmsg);
  1128. srv_debug(1, xs_fmt("enqueue_email %d", retries));
  1129. }
  1130. void enqueue_telegram(const xs_str *msg, const char *bot, const char *chat_id)
  1131. /* enqueues a message to be sent via Telegram */
  1132. {
  1133. xs *qmsg = _new_qmsg("telegram", msg, 0);
  1134. char *ntid = xs_dict_get(qmsg, "ntid");
  1135. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  1136. qmsg = xs_dict_append(qmsg, "bot", bot);
  1137. qmsg = xs_dict_append(qmsg, "chat_id", chat_id);
  1138. qmsg = _enqueue_put(fn, qmsg);
  1139. srv_debug(1, xs_fmt("enqueue_email %s %s", bot, chat_id));
  1140. }
  1141. void enqueue_message(snac *snac, xs_dict *msg)
  1142. /* enqueues an output message */
  1143. {
  1144. xs *qmsg = _new_qmsg("message", msg, 0);
  1145. char *ntid = xs_dict_get(qmsg, "ntid");
  1146. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  1147. qmsg = _enqueue_put(fn, qmsg);
  1148. snac_debug(snac, 0, xs_fmt("enqueue_message %s", xs_dict_get(msg, "id")));
  1149. }
  1150. xs_list *user_queue(snac *snac)
  1151. /* returns a list with filenames that can be dequeued */
  1152. {
  1153. xs *spec = xs_fmt("%s/queue/" "*.json", snac->basedir);
  1154. xs_list *list = xs_list_new();
  1155. time_t t = time(NULL);
  1156. xs_list *p;
  1157. xs_val *v;
  1158. xs *fns = xs_glob(spec, 0, 0);
  1159. p = fns;
  1160. while (xs_list_iter(&p, &v)) {
  1161. /* get the retry time from the basename */
  1162. char *bn = strrchr(v, '/');
  1163. time_t t2 = atol(bn + 1);
  1164. if (t2 > t)
  1165. snac_debug(snac, 2, xs_fmt("user_queue not yet time for %s [%ld]", v, t));
  1166. else {
  1167. list = xs_list_append(list, v);
  1168. snac_debug(snac, 2, xs_fmt("user_queue ready for %s", v));
  1169. }
  1170. }
  1171. return list;
  1172. }
  1173. xs_list *queue(void)
  1174. /* returns a list with filenames that can be dequeued */
  1175. {
  1176. xs *spec = xs_fmt("%s/queue/" "*.json", srv_basedir);
  1177. xs_list *list = xs_list_new();
  1178. time_t t = time(NULL);
  1179. xs_list *p;
  1180. xs_val *v;
  1181. xs *fns = xs_glob(spec, 0, 0);
  1182. p = fns;
  1183. while (xs_list_iter(&p, &v)) {
  1184. /* get the retry time from the basename */
  1185. char *bn = strrchr(v, '/');
  1186. time_t t2 = atol(bn + 1);
  1187. if (t2 > t)
  1188. srv_debug(2, xs_fmt("queue not yet time for %s [%ld]", v, t));
  1189. else {
  1190. list = xs_list_append(list, v);
  1191. srv_debug(2, xs_fmt("queue ready for %s", v));
  1192. }
  1193. }
  1194. return list;
  1195. }
  1196. xs_dict *dequeue(const char *fn)
  1197. /* dequeues a message */
  1198. {
  1199. FILE *f;
  1200. xs_dict *obj = NULL;
  1201. if ((f = fopen(fn, "r")) != NULL) {
  1202. /* delete right now */
  1203. unlink(fn);
  1204. xs *j = xs_readall(f);
  1205. obj = xs_json_loads(j);
  1206. fclose(f);
  1207. }
  1208. return obj;
  1209. }
  1210. /** the purge **/
  1211. static int _purge_file(const char *fn, time_t mt)
  1212. /* purge fn if it's older than days */
  1213. {
  1214. int ret = 0;
  1215. if (mtime(fn) < mt) {
  1216. /* older than the minimum time: delete it */
  1217. unlink(fn);
  1218. srv_debug(2, xs_fmt("purged %s", fn));
  1219. ret = 1;
  1220. }
  1221. return ret;
  1222. }
  1223. static void _purge_dir(const char *dir, int days)
  1224. /* purges all files in a directory older than days */
  1225. {
  1226. int cnt = 0;
  1227. if (days) {
  1228. time_t mt = time(NULL) - days * 24 * 3600;
  1229. xs *spec = xs_fmt("%s/" "*", dir);
  1230. xs *list = xs_glob(spec, 0, 0);
  1231. xs_list *p;
  1232. xs_str *v;
  1233. p = list;
  1234. while (xs_list_iter(&p, &v))
  1235. cnt += _purge_file(v, mt);
  1236. srv_debug(1, xs_fmt("purge: %s %d", dir, cnt));
  1237. }
  1238. }
  1239. static void _purge_user_subdir(snac *snac, const char *subdir, int days)
  1240. /* purges all files in a user subdir older than days */
  1241. {
  1242. xs *u_subdir = xs_fmt("%s/%s", snac->basedir, subdir);
  1243. _purge_dir(u_subdir, days);
  1244. }
  1245. void purge_server(void)
  1246. /* purge global server data */
  1247. {
  1248. xs *spec = xs_fmt("%s/object/??", srv_basedir);
  1249. xs *dirs = xs_glob(spec, 0, 0);
  1250. xs_list *p;
  1251. xs_str *v;
  1252. int cnt = 0;
  1253. int icnt = 0;
  1254. time_t mt = time(NULL) - 7 * 24 * 3600;
  1255. p = dirs;
  1256. while (xs_list_iter(&p, &v)) {
  1257. xs_list *p2;
  1258. xs_str *v2;
  1259. {
  1260. xs *spec2 = xs_fmt("%s/" "*.json", v);
  1261. xs *files = xs_glob(spec2, 0, 0);
  1262. p2 = files;
  1263. while (xs_list_iter(&p2, &v2)) {
  1264. int n_link;
  1265. /* old and with no hard links? */
  1266. if (mtime_nl(v2, &n_link) < mt && n_link < 2) {
  1267. xs *s1 = xs_replace(v2, ".json", "");
  1268. xs *l = xs_split(s1, "/");
  1269. char *md5 = xs_list_get(l, -1);
  1270. object_del_by_md5(md5);
  1271. cnt++;
  1272. }
  1273. }
  1274. }
  1275. {
  1276. /* look for stray indexes */
  1277. xs *speci = xs_fmt("%s/" "*_?.idx", v);
  1278. xs *idxfs = xs_glob(speci, 0, 0);
  1279. p2 = idxfs;
  1280. while (xs_list_iter(&p2, &v2)) {
  1281. /* old enough to consider? */
  1282. if (mtime(v2) < mt) {
  1283. /* check if the indexed object is here */
  1284. xs *o = xs_dup(v2);
  1285. char *ext = strchr(o, '_');
  1286. if (ext) {
  1287. *ext = '\0';
  1288. o = xs_str_cat(o, ".json");
  1289. if (mtime(o) == 0.0) {
  1290. /* delete */
  1291. unlink(v2);
  1292. srv_debug(1, xs_fmt("purged %s", v2));
  1293. icnt++;
  1294. }
  1295. }
  1296. }
  1297. }
  1298. }
  1299. }
  1300. /* purge collected inboxes */
  1301. xs *ib_dir = xs_fmt("%s/inbox", srv_basedir);
  1302. _purge_dir(ib_dir, 7);
  1303. srv_debug(1, xs_fmt("purge: global (obj: %d, idx: %d)", cnt, icnt));
  1304. }
  1305. void purge_user(snac *snac)
  1306. /* do the purge for this user */
  1307. {
  1308. int priv_days, pub_days, user_days = 0;
  1309. char *v;
  1310. int n;
  1311. priv_days = xs_number_get(xs_dict_get(srv_config, "timeline_purge_days"));
  1312. pub_days = xs_number_get(xs_dict_get(srv_config, "local_purge_days"));
  1313. if ((v = xs_dict_get(snac->config_o, "purge_days")) != NULL ||
  1314. (v = xs_dict_get(snac->config, "purge_days")) != NULL)
  1315. user_days = xs_number_get(v);
  1316. if (user_days) {
  1317. /* override admin settings only if they are lesser */
  1318. if (priv_days == 0 || user_days < priv_days)
  1319. priv_days = user_days;
  1320. if (pub_days == 0 || user_days < pub_days)
  1321. pub_days = user_days;
  1322. }
  1323. _purge_user_subdir(snac, "hidden", priv_days);
  1324. _purge_user_subdir(snac, "private", priv_days);
  1325. _purge_user_subdir(snac, "public", pub_days);
  1326. const char *idxs[] = { "followers.idx", "private.idx", "public.idx", NULL };
  1327. for (n = 0; idxs[n]; n++) {
  1328. xs *idx = xs_fmt("%s/%s", snac->basedir, idxs[n]);
  1329. int gc = index_gc(idx);
  1330. snac_debug(snac, 1, xs_fmt("purge: %s %d", idx, gc));
  1331. }
  1332. }
  1333. void purge_all(void)
  1334. /* purge all users */
  1335. {
  1336. snac snac;
  1337. xs *list = user_list();
  1338. char *p, *uid;
  1339. p = list;
  1340. while (xs_list_iter(&p, &uid)) {
  1341. if (user_open(&snac, uid)) {
  1342. purge_user(&snac);
  1343. user_free(&snac);
  1344. }
  1345. }
  1346. purge_server();
  1347. }
  1348. /** archive **/
  1349. void srv_archive(const char *direction, const char *url, xs_dict *req,
  1350. const char *payload, int p_size,
  1351. int status, xs_dict *headers,
  1352. const char *body, int b_size)
  1353. /* archives a connection */
  1354. {
  1355. /* obsessive archiving */
  1356. xs *date = tid(0);
  1357. xs *dir = xs_fmt("%s/archive/%s_%s", srv_basedir, date, direction);
  1358. FILE *f;
  1359. if (mkdirx(dir) != -1) {
  1360. xs *meta_fn = xs_fmt("%s/_META", dir);
  1361. if ((f = fopen(meta_fn, "w")) != NULL) {
  1362. xs *j1 = xs_json_dumps_pp(req, 4);
  1363. xs *j2 = xs_json_dumps_pp(headers, 4);
  1364. fprintf(f, "dir: %s\n", direction);
  1365. if (url)
  1366. fprintf(f, "url: %s\n", url);
  1367. fprintf(f, "req: %s\n", j1);
  1368. fprintf(f, "p_size: %d\n", p_size);
  1369. fprintf(f, "status: %d\n", status);
  1370. fprintf(f, "response: %s\n", j2);
  1371. fprintf(f, "b_size: %d\n", b_size);
  1372. fclose(f);
  1373. }
  1374. if (p_size && payload) {
  1375. xs *payload_fn = NULL;
  1376. xs *payload_fn_raw = NULL;
  1377. char *v = xs_dict_get(req, "content-type");
  1378. if (v && xs_str_in(v, "json") != -1) {
  1379. payload_fn = xs_fmt("%s/payload.json", dir);
  1380. if ((f = fopen(payload_fn, "w")) != NULL) {
  1381. xs *v1 = xs_json_loads(payload);
  1382. xs *j1 = NULL;
  1383. if (v1 != NULL)
  1384. j1 = xs_json_dumps_pp(v1, 4);
  1385. if (j1 != NULL)
  1386. fwrite(j1, strlen(j1), 1, f);
  1387. else
  1388. fwrite(payload, p_size, 1, f);
  1389. fclose(f);
  1390. }
  1391. }
  1392. payload_fn_raw = xs_fmt("%s/payload", dir);
  1393. if ((f = fopen(payload_fn_raw, "w")) != NULL) {
  1394. fwrite(payload, p_size, 1, f);
  1395. fclose(f);
  1396. }
  1397. }
  1398. if (b_size && body) {
  1399. xs *body_fn = NULL;
  1400. char *v = xs_dict_get(headers, "content-type");
  1401. if (v && xs_str_in(v, "json") != -1) {
  1402. body_fn = xs_fmt("%s/body.json", dir);
  1403. if ((f = fopen(body_fn, "w")) != NULL) {
  1404. xs *v1 = xs_json_loads(body);
  1405. xs *j1 = NULL;
  1406. if (v1 != NULL)
  1407. j1 = xs_json_dumps_pp(v1, 4);
  1408. if (j1 != NULL)
  1409. fwrite(j1, strlen(j1), 1, f);
  1410. else
  1411. fwrite(body, b_size, 1, f);
  1412. fclose(f);
  1413. }
  1414. }
  1415. else {
  1416. body_fn = xs_fmt("%s/body", dir);
  1417. if ((f = fopen(body_fn, "w")) != NULL) {
  1418. fwrite(body, b_size, 1, f);
  1419. fclose(f);
  1420. }
  1421. }
  1422. }
  1423. }
  1424. }
  1425. void srv_archive_error(const char *prefix, const xs_str *err,
  1426. const xs_dict *req, const xs_dict *data)
  1427. /* archives an error */
  1428. {
  1429. xs *ntid = tid(0);
  1430. xs *fn = xs_fmt("%s/error/%s_%s", srv_basedir, prefix, ntid);
  1431. FILE *f;
  1432. if ((f = fopen(fn, "w")) != NULL) {
  1433. fprintf(f, "Error: %s\n", err);
  1434. if (req) {
  1435. fprintf(f, "Request headers:\n");
  1436. xs *j = xs_json_dumps_pp(req, 4);
  1437. fwrite(j, strlen(j), 1, f);
  1438. fprintf(f, "\n");
  1439. }
  1440. if (data) {
  1441. fprintf(f, "Data:\n");
  1442. xs *j = xs_json_dumps_pp(data, 4);
  1443. fwrite(j, strlen(j), 1, f);
  1444. fprintf(f, "\n");
  1445. }
  1446. fclose(f);
  1447. }
  1448. }