data.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910
  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/inboxes", 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. /** inbox collection **/
  992. void inbox_add(const char *inbox)
  993. /* collects a shared inbox */
  994. {
  995. xs *md5 = xs_md5_hex(inbox, strlen(inbox));
  996. xs *fn = xs_fmt("%s/inboxes/%s", srv_basedir, md5);
  997. FILE *f;
  998. if ((f = fopen(fn, "w")) != NULL) {
  999. pthread_mutex_lock(&data_mutex);
  1000. fprintf(f, "%s\n", inbox);
  1001. fclose(f);
  1002. pthread_mutex_unlock(&data_mutex);
  1003. }
  1004. }
  1005. void inbox_add_by_actor(const xs_dict *actor)
  1006. /* collects an actor's shared inbox, if it has one */
  1007. {
  1008. char *v;
  1009. if (!xs_is_null(v = xs_dict_get(actor, "endpoints")) &&
  1010. !xs_is_null(v = xs_dict_get(v, "sharedInbox")))
  1011. inbox_add(v);
  1012. }
  1013. /** the queue **/
  1014. static xs_dict *_enqueue_put(const char *fn, xs_dict *msg)
  1015. /* writes safely to the queue */
  1016. {
  1017. xs *tfn = xs_fmt("%s.tmp", fn);
  1018. FILE *f;
  1019. if ((f = fopen(tfn, "w")) != NULL) {
  1020. xs *j = xs_json_dumps_pp(msg, 4);
  1021. fwrite(j, strlen(j), 1, f);
  1022. fclose(f);
  1023. rename(tfn, fn);
  1024. }
  1025. return msg;
  1026. }
  1027. static xs_dict *_new_qmsg(const char *type, const xs_val *msg, int retries)
  1028. /* creates a queue message */
  1029. {
  1030. int qrt = xs_number_get(xs_dict_get(srv_config, "queue_retry_minutes"));
  1031. xs *ntid = tid(retries * 60 * qrt);
  1032. xs *rn = xs_number_new(retries);
  1033. xs_dict *qmsg = xs_dict_new();
  1034. qmsg = xs_dict_append(qmsg, "type", type);
  1035. qmsg = xs_dict_append(qmsg, "message", msg);
  1036. qmsg = xs_dict_append(qmsg, "retries", rn);
  1037. qmsg = xs_dict_append(qmsg, "ntid", ntid);
  1038. return qmsg;
  1039. }
  1040. void enqueue_input(snac *snac, xs_dict *msg, xs_dict *req, int retries)
  1041. /* enqueues an input message */
  1042. {
  1043. xs *qmsg = _new_qmsg("input", msg, retries);
  1044. char *ntid = xs_dict_get(qmsg, "ntid");
  1045. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  1046. qmsg = xs_dict_append(qmsg, "req", req);
  1047. qmsg = _enqueue_put(fn, qmsg);
  1048. snac_debug(snac, 1, xs_fmt("enqueue_input %s", fn));
  1049. }
  1050. void enqueue_output_raw(const char *keyid, const char *seckey,
  1051. xs_dict *msg, xs_str *inbox, int retries)
  1052. /* enqueues an output message to an inbox */
  1053. {
  1054. xs *qmsg = _new_qmsg("output", msg, retries);
  1055. char *ntid = xs_dict_get(qmsg, "ntid");
  1056. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  1057. qmsg = xs_dict_append(qmsg, "inbox", inbox);
  1058. qmsg = xs_dict_append(qmsg, "keyid", keyid);
  1059. qmsg = xs_dict_append(qmsg, "seckey", seckey);
  1060. /* if it's to be sent right now, bypass the disk queue and post the job */
  1061. if (retries == 0 && job_fifo_ready())
  1062. job_post(qmsg);
  1063. else {
  1064. qmsg = _enqueue_put(fn, qmsg);
  1065. srv_debug(1, xs_fmt("enqueue_output %s %s %d", inbox, fn, retries));
  1066. }
  1067. }
  1068. void enqueue_output(snac *snac, xs_dict *msg, xs_str *inbox, int retries)
  1069. /* enqueues an output message to an inbox */
  1070. {
  1071. if (xs_startswith(inbox, snac->actor)) {
  1072. snac_debug(snac, 1, xs_str_new("refusing enqueue to myself"));
  1073. return;
  1074. }
  1075. char *seckey = xs_dict_get(snac->key, "secret");
  1076. enqueue_output_raw(snac->actor, seckey, msg, inbox, retries);
  1077. }
  1078. void enqueue_output_by_actor(snac *snac, xs_dict *msg, xs_str *actor, int retries)
  1079. /* enqueues an output message for an actor */
  1080. {
  1081. xs *inbox = get_actor_inbox(snac, actor);
  1082. if (!xs_is_null(inbox))
  1083. enqueue_output(snac, msg, inbox, retries);
  1084. else
  1085. snac_log(snac, xs_fmt("enqueue_output_by_actor cannot get inbox %s", actor));
  1086. }
  1087. void enqueue_email(xs_str *msg, int retries)
  1088. /* enqueues an email message to be sent */
  1089. {
  1090. xs *qmsg = _new_qmsg("email", msg, retries);
  1091. char *ntid = xs_dict_get(qmsg, "ntid");
  1092. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  1093. qmsg = _enqueue_put(fn, qmsg);
  1094. srv_debug(1, xs_fmt("enqueue_email %d", retries));
  1095. }
  1096. void enqueue_telegram(const xs_str *msg, const char *bot, const char *chat_id)
  1097. /* enqueues a message to be sent via Telegram */
  1098. {
  1099. xs *qmsg = _new_qmsg("telegram", msg, 0);
  1100. char *ntid = xs_dict_get(qmsg, "ntid");
  1101. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  1102. qmsg = xs_dict_append(qmsg, "bot", bot);
  1103. qmsg = xs_dict_append(qmsg, "chat_id", chat_id);
  1104. qmsg = _enqueue_put(fn, qmsg);
  1105. srv_debug(1, xs_fmt("enqueue_email %s %s", bot, chat_id));
  1106. }
  1107. void enqueue_message(snac *snac, xs_dict *msg)
  1108. /* enqueues an output message */
  1109. {
  1110. xs *qmsg = _new_qmsg("message", msg, 0);
  1111. char *ntid = xs_dict_get(qmsg, "ntid");
  1112. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  1113. qmsg = _enqueue_put(fn, qmsg);
  1114. snac_debug(snac, 0, xs_fmt("enqueue_message %s", xs_dict_get(msg, "id")));
  1115. }
  1116. xs_list *user_queue(snac *snac)
  1117. /* returns a list with filenames that can be dequeued */
  1118. {
  1119. xs *spec = xs_fmt("%s/queue/" "*.json", snac->basedir);
  1120. xs_list *list = xs_list_new();
  1121. time_t t = time(NULL);
  1122. xs_list *p;
  1123. xs_val *v;
  1124. xs *fns = xs_glob(spec, 0, 0);
  1125. p = fns;
  1126. while (xs_list_iter(&p, &v)) {
  1127. /* get the retry time from the basename */
  1128. char *bn = strrchr(v, '/');
  1129. time_t t2 = atol(bn + 1);
  1130. if (t2 > t)
  1131. snac_debug(snac, 2, xs_fmt("user_queue not yet time for %s [%ld]", v, t));
  1132. else {
  1133. list = xs_list_append(list, v);
  1134. snac_debug(snac, 2, xs_fmt("user_queue ready for %s", v));
  1135. }
  1136. }
  1137. return list;
  1138. }
  1139. xs_list *queue(void)
  1140. /* returns a list with filenames that can be dequeued */
  1141. {
  1142. xs *spec = xs_fmt("%s/queue/" "*.json", srv_basedir);
  1143. xs_list *list = xs_list_new();
  1144. time_t t = time(NULL);
  1145. xs_list *p;
  1146. xs_val *v;
  1147. xs *fns = xs_glob(spec, 0, 0);
  1148. p = fns;
  1149. while (xs_list_iter(&p, &v)) {
  1150. /* get the retry time from the basename */
  1151. char *bn = strrchr(v, '/');
  1152. time_t t2 = atol(bn + 1);
  1153. if (t2 > t)
  1154. srv_debug(2, xs_fmt("queue not yet time for %s [%ld]", v, t));
  1155. else {
  1156. list = xs_list_append(list, v);
  1157. srv_debug(2, xs_fmt("queue ready for %s", v));
  1158. }
  1159. }
  1160. return list;
  1161. }
  1162. xs_dict *dequeue(const char *fn)
  1163. /* dequeues a message */
  1164. {
  1165. FILE *f;
  1166. xs_dict *obj = NULL;
  1167. if ((f = fopen(fn, "r")) != NULL) {
  1168. /* delete right now */
  1169. unlink(fn);
  1170. xs *j = xs_readall(f);
  1171. obj = xs_json_loads(j);
  1172. fclose(f);
  1173. }
  1174. return obj;
  1175. }
  1176. /** the purge **/
  1177. static int _purge_file(const char *fn, time_t mt)
  1178. /* purge fn if it's older than days */
  1179. {
  1180. int ret = 0;
  1181. if (mtime(fn) < mt) {
  1182. /* older than the minimum time: delete it */
  1183. unlink(fn);
  1184. srv_debug(1, xs_fmt("purged %s", fn));
  1185. ret = 1;
  1186. }
  1187. return ret;
  1188. }
  1189. static void _purge_subdir(snac *snac, const char *subdir, int days)
  1190. /* purges all files in subdir older than days */
  1191. {
  1192. int cnt = 0;
  1193. if (days) {
  1194. time_t mt = time(NULL) - days * 24 * 3600;
  1195. xs *spec = xs_fmt("%s/%s/" "*", snac->basedir, subdir);
  1196. xs *list = xs_glob(spec, 0, 0);
  1197. char *p, *v;
  1198. p = list;
  1199. while (xs_list_iter(&p, &v))
  1200. cnt += _purge_file(v, mt);
  1201. }
  1202. snac_debug(snac, 1, xs_fmt("purge: ~/%s/ %d", subdir, cnt));
  1203. }
  1204. void purge_server(void)
  1205. /* purge global server data */
  1206. {
  1207. xs *spec = xs_fmt("%s/object/??", srv_basedir);
  1208. xs *dirs = xs_glob(spec, 0, 0);
  1209. xs_list *p;
  1210. xs_str *v;
  1211. int cnt = 0;
  1212. int icnt = 0;
  1213. time_t mt = time(NULL) - 7 * 24 * 3600;
  1214. p = dirs;
  1215. while (xs_list_iter(&p, &v)) {
  1216. xs_list *p2;
  1217. xs_str *v2;
  1218. {
  1219. xs *spec2 = xs_fmt("%s/" "*.json", v);
  1220. xs *files = xs_glob(spec2, 0, 0);
  1221. p2 = files;
  1222. while (xs_list_iter(&p2, &v2)) {
  1223. int n_link;
  1224. /* old and with no hard links? */
  1225. if (mtime_nl(v2, &n_link) < mt && n_link < 2) {
  1226. xs *s1 = xs_replace(v2, ".json", "");
  1227. xs *l = xs_split(s1, "/");
  1228. char *md5 = xs_list_get(l, -1);
  1229. object_del_by_md5(md5);
  1230. cnt++;
  1231. }
  1232. }
  1233. }
  1234. {
  1235. /* look for stray indexes */
  1236. xs *speci = xs_fmt("%s/" "*_?.idx", v);
  1237. xs *idxfs = xs_glob(speci, 0, 0);
  1238. p2 = idxfs;
  1239. while (xs_list_iter(&p2, &v2)) {
  1240. /* old enough to consider? */
  1241. if (mtime(v2) < mt) {
  1242. /* check if the indexed object is here */
  1243. xs *o = xs_dup(v2);
  1244. char *ext = strchr(o, '_');
  1245. if (ext) {
  1246. *ext = '\0';
  1247. o = xs_str_cat(o, ".json");
  1248. if (mtime(o) == 0.0) {
  1249. /* delete */
  1250. unlink(v2);
  1251. srv_debug(1, xs_fmt("purged %s", v2));
  1252. icnt++;
  1253. }
  1254. }
  1255. }
  1256. }
  1257. }
  1258. }
  1259. srv_debug(1, xs_fmt("purge: global (obj: %d, idx: %d)", cnt, icnt));
  1260. }
  1261. void purge_user(snac *snac)
  1262. /* do the purge for this user */
  1263. {
  1264. int priv_days, pub_days, user_days = 0;
  1265. char *v;
  1266. int n;
  1267. priv_days = xs_number_get(xs_dict_get(srv_config, "timeline_purge_days"));
  1268. pub_days = xs_number_get(xs_dict_get(srv_config, "local_purge_days"));
  1269. if ((v = xs_dict_get(snac->config_o, "purge_days")) != NULL ||
  1270. (v = xs_dict_get(snac->config, "purge_days")) != NULL)
  1271. user_days = xs_number_get(v);
  1272. if (user_days) {
  1273. /* override admin settings only if they are lesser */
  1274. if (priv_days == 0 || user_days < priv_days)
  1275. priv_days = user_days;
  1276. if (pub_days == 0 || user_days < pub_days)
  1277. pub_days = user_days;
  1278. }
  1279. _purge_subdir(snac, "hidden", priv_days);
  1280. _purge_subdir(snac, "private", priv_days);
  1281. _purge_subdir(snac, "public", pub_days);
  1282. const char *idxs[] = { "followers.idx", "private.idx", "public.idx", NULL };
  1283. for (n = 0; idxs[n]; n++) {
  1284. xs *idx = xs_fmt("%s/%s", snac->basedir, idxs[n]);
  1285. int gc = index_gc(idx);
  1286. snac_debug(snac, 1, xs_fmt("purge: %s %d", idx, gc));
  1287. }
  1288. }
  1289. void purge_all(void)
  1290. /* purge all users */
  1291. {
  1292. snac snac;
  1293. xs *list = user_list();
  1294. char *p, *uid;
  1295. p = list;
  1296. while (xs_list_iter(&p, &uid)) {
  1297. if (user_open(&snac, uid)) {
  1298. purge_user(&snac);
  1299. user_free(&snac);
  1300. }
  1301. }
  1302. purge_server();
  1303. }
  1304. /** archive **/
  1305. void srv_archive(const char *direction, xs_dict *req,
  1306. const char *payload, int p_size,
  1307. int status, xs_dict *headers,
  1308. const char *body, int b_size)
  1309. /* archives a connection */
  1310. {
  1311. /* obsessive archiving */
  1312. xs *date = tid(0);
  1313. xs *dir = xs_fmt("%s/archive/%s_%s", srv_basedir, date, direction);
  1314. FILE *f;
  1315. if (mkdirx(dir) != -1) {
  1316. xs *meta_fn = xs_fmt("%s/_META", dir);
  1317. if ((f = fopen(meta_fn, "w")) != NULL) {
  1318. xs *j1 = xs_json_dumps_pp(req, 4);
  1319. xs *j2 = xs_json_dumps_pp(headers, 4);
  1320. fprintf(f, "dir: %s\n", direction);
  1321. fprintf(f, "req: %s\n", j1);
  1322. fprintf(f, "p_size: %d\n", p_size);
  1323. fprintf(f, "status: %d\n", status);
  1324. fprintf(f, "response: %s\n", j2);
  1325. fprintf(f, "b_size: %d\n", b_size);
  1326. fclose(f);
  1327. }
  1328. if (p_size && payload) {
  1329. xs *payload_fn = NULL;
  1330. xs *payload_fn_raw = NULL;
  1331. char *v = xs_dict_get(req, "content-type");
  1332. if (v && xs_str_in(v, "json") != -1) {
  1333. payload_fn = xs_fmt("%s/payload.json", dir);
  1334. if ((f = fopen(payload_fn, "w")) != NULL) {
  1335. xs *v1 = xs_json_loads(payload);
  1336. xs *j1 = NULL;
  1337. if (v1 != NULL)
  1338. j1 = xs_json_dumps_pp(v1, 4);
  1339. if (j1 != NULL)
  1340. fwrite(j1, strlen(j1), 1, f);
  1341. else
  1342. fwrite(payload, p_size, 1, f);
  1343. fclose(f);
  1344. }
  1345. }
  1346. payload_fn_raw = xs_fmt("%s/payload", dir);
  1347. if ((f = fopen(payload_fn_raw, "w")) != NULL) {
  1348. fwrite(payload, p_size, 1, f);
  1349. fclose(f);
  1350. }
  1351. }
  1352. if (b_size && body) {
  1353. xs *body_fn = NULL;
  1354. char *v = xs_dict_get(headers, "content-type");
  1355. if (v && xs_str_in(v, "json") != -1) {
  1356. body_fn = xs_fmt("%s/body.json", dir);
  1357. if ((f = fopen(body_fn, "w")) != NULL) {
  1358. xs *v1 = xs_json_loads(body);
  1359. xs *j1 = NULL;
  1360. if (v1 != NULL)
  1361. j1 = xs_json_dumps_pp(v1, 4);
  1362. if (j1 != NULL)
  1363. fwrite(j1, strlen(j1), 1, f);
  1364. else
  1365. fwrite(body, b_size, 1, f);
  1366. fclose(f);
  1367. }
  1368. }
  1369. else {
  1370. body_fn = xs_fmt("%s/body", dir);
  1371. if ((f = fopen(body_fn, "w")) != NULL) {
  1372. fwrite(body, b_size, 1, f);
  1373. fclose(f);
  1374. }
  1375. }
  1376. }
  1377. }
  1378. }
  1379. void srv_archive_error(const char *prefix, const xs_str *err,
  1380. const xs_dict *req, const xs_dict *data)
  1381. /* archives an error */
  1382. {
  1383. xs *ntid = tid(0);
  1384. xs *fn = xs_fmt("%s/error/%s_%s", srv_basedir, prefix, ntid);
  1385. FILE *f;
  1386. if ((f = fopen(fn, "w")) != NULL) {
  1387. fprintf(f, "Error: %s\n", err);
  1388. if (req) {
  1389. fprintf(f, "Request headers:\n");
  1390. xs *j = xs_json_dumps_pp(req, 4);
  1391. fwrite(j, strlen(j), 1, f);
  1392. }
  1393. if (data) {
  1394. fprintf(f, "Data:\n");
  1395. xs *j = xs_json_dumps_pp(data, 4);
  1396. fwrite(j, strlen(j), 1, f);
  1397. }
  1398. fclose(f);
  1399. }
  1400. }