data.c 46 KB

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