data.c 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
  3. #include "xs.h"
  4. #include "xs_hex.h"
  5. #include "xs_io.h"
  6. #include "xs_json.h"
  7. #include "xs_openssl.h"
  8. #include "xs_glob.h"
  9. #include "xs_set.h"
  10. #include "xs_time.h"
  11. #include "xs_regex.h"
  12. #include "xs_match.h"
  13. #include "snac.h"
  14. #include <time.h>
  15. #include <sys/stat.h>
  16. #include <sys/file.h>
  17. #include <sys/time.h>
  18. #include <fcntl.h>
  19. #include <pthread.h>
  20. double disk_layout = 2.7;
  21. /* storage serializer */
  22. pthread_mutex_t data_mutex = {0};
  23. int snac_upgrade(xs_str **error);
  24. int srv_open(char *basedir, int auto_upgrade)
  25. /* opens a server */
  26. {
  27. int ret = 0;
  28. xs *cfg_file = NULL;
  29. FILE *f;
  30. xs_str *error = NULL;
  31. pthread_mutex_init(&data_mutex, NULL);
  32. srv_basedir = xs_str_new(basedir);
  33. if (xs_endswith(srv_basedir, "/"))
  34. srv_basedir = xs_crop_i(srv_basedir, 0, -1);
  35. cfg_file = xs_fmt("%s/server.json", basedir);
  36. if ((f = fopen(cfg_file, "r")) == NULL)
  37. error = xs_fmt("ERROR: cannot opening '%s'", cfg_file);
  38. else {
  39. /* read full config file */
  40. srv_config = xs_json_load(f);
  41. fclose(f);
  42. /* parse */
  43. if (srv_config == NULL)
  44. error = xs_fmt("ERROR: cannot parse '%s'", cfg_file);
  45. else {
  46. char *host;
  47. char *prefix;
  48. char *dbglvl;
  49. char *proto;
  50. host = xs_dict_get(srv_config, "host");
  51. prefix = xs_dict_get(srv_config, "prefix");
  52. dbglvl = xs_dict_get(srv_config, "dbglevel");
  53. proto = xs_dict_get_def(srv_config, "protocol", "https");
  54. if (host == NULL || prefix == NULL)
  55. error = xs_str_new("ERROR: cannot get server data");
  56. else {
  57. srv_baseurl = xs_fmt("%s:/" "/%s%s", proto, host, prefix);
  58. dbglevel = (int) xs_number_get(dbglvl);
  59. if ((dbglvl = getenv("DEBUG")) != NULL) {
  60. dbglevel = atoi(dbglvl);
  61. error = xs_fmt("DEBUG level set to %d from environment", dbglevel);
  62. }
  63. if (auto_upgrade)
  64. ret = snac_upgrade(&error);
  65. else {
  66. if (xs_number_get(xs_dict_get(srv_config, "layout")) < disk_layout)
  67. error = xs_fmt("ERROR: disk layout changed - execute 'snac upgrade' first");
  68. else
  69. ret = 1;
  70. }
  71. }
  72. }
  73. }
  74. if (error != NULL)
  75. srv_log(error);
  76. /* create the queue/ subdir, just in case */
  77. xs *qdir = xs_fmt("%s/queue", srv_basedir);
  78. mkdirx(qdir);
  79. xs *ibdir = xs_fmt("%s/inbox", srv_basedir);
  80. mkdirx(ibdir);
  81. xs *tmpdir = xs_fmt("%s/tmp", srv_basedir);
  82. mkdirx(tmpdir);
  83. #ifdef __APPLE__
  84. /* Apple uses st_atimespec instead of st_atim etc */
  85. #define st_atim st_atimespec
  86. #define st_ctim st_ctimespec
  87. #define st_mtim st_mtimespec
  88. #endif
  89. #ifdef __OpenBSD__
  90. char *v = xs_dict_get(srv_config, "disable_openbsd_security");
  91. if (v && xs_type(v) == XSTYPE_TRUE) {
  92. srv_debug(1, xs_dup("OpenBSD security disabled by admin"));
  93. }
  94. else {
  95. int smail = xs_type(xs_dict_get(srv_config, "disable_email_notifications")) != XSTYPE_TRUE;
  96. srv_debug(1, xs_fmt("Calling unveil()"));
  97. unveil(basedir, "rwc");
  98. unveil("/tmp", "rwc");
  99. unveil("/etc/resolv.conf", "r");
  100. unveil("/etc/hosts", "r");
  101. unveil("/etc/ssl/openssl.cnf", "r");
  102. unveil("/etc/ssl/cert.pem", "r");
  103. unveil("/usr/share/zoneinfo", "r");
  104. if (smail)
  105. unveil("/usr/sbin/sendmail", "x");
  106. unveil(NULL, NULL);
  107. srv_debug(1, xs_fmt("Calling pledge()"));
  108. if (smail)
  109. pledge("stdio rpath wpath cpath flock inet proc exec dns fattr", NULL);
  110. else
  111. pledge("stdio rpath wpath cpath flock inet proc dns fattr", NULL);
  112. }
  113. #endif /* __OpenBSD__ */
  114. /* read (and drop) emojis.json, possibly creating it */
  115. xs_free(emojis());
  116. return ret;
  117. }
  118. void srv_free(void)
  119. {
  120. xs_free(srv_basedir);
  121. xs_free(srv_config);
  122. xs_free(srv_baseurl);
  123. pthread_mutex_destroy(&data_mutex);
  124. }
  125. void user_free(snac *snac)
  126. /* frees a user snac */
  127. {
  128. xs_free(snac->uid);
  129. xs_free(snac->basedir);
  130. xs_free(snac->config);
  131. xs_free(snac->config_o);
  132. xs_free(snac->key);
  133. xs_free(snac->links);
  134. xs_free(snac->actor);
  135. xs_free(snac->md5);
  136. }
  137. int user_open(snac *user, const char *uid)
  138. /* opens a user */
  139. {
  140. int ret = 0;
  141. *user = (snac){0};
  142. if (validate_uid(uid)) {
  143. xs *cfg_file = NULL;
  144. FILE *f;
  145. xs *t = xs_fmt("%s/user/%s", srv_basedir, uid);
  146. if (mtime(t) == 0.0) {
  147. /* user folder does not exist; try with a different case */
  148. xs *lcuid = xs_tolower_i(xs_dup(uid));
  149. xs *ulist = user_list();
  150. xs_list *p = ulist;
  151. xs_str *v;
  152. while (xs_list_iter(&p, &v)) {
  153. xs *v2 = xs_tolower_i(xs_dup(v));
  154. if (strcmp(lcuid, v2) == 0) {
  155. user->uid = xs_dup(v);
  156. break;
  157. }
  158. }
  159. }
  160. else
  161. user->uid = xs_str_new(uid);
  162. if (user->uid == NULL)
  163. return ret;
  164. user->basedir = xs_fmt("%s/user/%s", srv_basedir, user->uid);
  165. cfg_file = xs_fmt("%s/user.json", user->basedir);
  166. if ((f = fopen(cfg_file, "r")) != NULL) {
  167. /* read full config file */
  168. user->config = xs_json_load(f);
  169. fclose(f);
  170. if (user->config != NULL) {
  171. xs *key_file = xs_fmt("%s/key.json", user->basedir);
  172. if ((f = fopen(key_file, "r")) != NULL) {
  173. user->key = xs_json_load(f);
  174. fclose(f);
  175. if (user->key != NULL) {
  176. user->actor = xs_fmt("%s/%s", srv_baseurl, user->uid);
  177. user->md5 = xs_md5_hex(user->actor, strlen(user->actor));
  178. /* everything is ok right now */
  179. ret = 1;
  180. /* does it have a configuration override? */
  181. xs *cfg_file_o = xs_fmt("%s/user_o.json", user->basedir);
  182. if ((f = fopen(cfg_file_o, "r")) != NULL) {
  183. user->config_o = xs_json_load(f);
  184. fclose(f);
  185. if (user->config_o == NULL)
  186. srv_log(xs_fmt("error parsing '%s'", cfg_file_o));
  187. }
  188. if (user->config_o == NULL)
  189. user->config_o = xs_dict_new();
  190. }
  191. else
  192. srv_log(xs_fmt("error parsing '%s'", key_file));
  193. }
  194. else
  195. srv_log(xs_fmt("error opening '%s' %d", key_file, errno));
  196. }
  197. else
  198. srv_log(xs_fmt("error parsing '%s'", cfg_file));
  199. }
  200. else
  201. srv_debug(2, xs_fmt("error opening '%s' %d", cfg_file, errno));
  202. /* verified links */
  203. xs *links_file = xs_fmt("%s/links.json", user->basedir);
  204. if ((f = fopen(links_file, "r")) != NULL) {
  205. user->links = xs_json_load(f);
  206. fclose(f);
  207. }
  208. }
  209. else
  210. srv_debug(1, xs_fmt("invalid user '%s'", uid));
  211. if (!ret)
  212. user_free(user);
  213. return ret;
  214. }
  215. xs_list *user_list(void)
  216. /* returns the list of user ids */
  217. {
  218. xs *spec = xs_fmt("%s/user/" "*", srv_basedir);
  219. return xs_glob(spec, 1, 0);
  220. }
  221. int user_open_by_md5(snac *snac, const char *md5)
  222. /* iterates all users searching by md5 */
  223. {
  224. xs *ulist = user_list();
  225. xs_list *p = ulist;
  226. xs_str *v;
  227. while (xs_list_iter(&p, &v)) {
  228. user_open(snac, v);
  229. if (strcmp(snac->md5, md5) == 0)
  230. return 1;
  231. user_free(snac);
  232. }
  233. return 0;
  234. }
  235. double mtime_nl(const char *fn, int *n_link)
  236. /* returns the mtime and number of links of a file or directory, or 0.0 */
  237. {
  238. struct stat st;
  239. double r = 0.0;
  240. int n = 0;
  241. if (fn && stat(fn, &st) != -1) {
  242. r = (double) st.st_mtim.tv_sec;
  243. n = st.st_nlink;
  244. }
  245. if (n_link)
  246. *n_link = n;
  247. return r;
  248. }
  249. #define MIN(v1, v2) ((v1) < (v2) ? (v1) : (v2))
  250. double f_ctime(const char *fn)
  251. /* returns the ctime of a file or directory, or 0.0 */
  252. {
  253. struct stat st;
  254. double r = 0.0;
  255. if (fn && stat(fn, &st) != -1) {
  256. /* return the lowest of ctime and mtime;
  257. there are operations that change the ctime, like link() */
  258. r = (double) MIN(st.st_ctim.tv_sec, st.st_mtim.tv_sec);
  259. }
  260. return r;
  261. }
  262. int is_md5_hex(const char *md5)
  263. {
  264. return xs_is_hex(md5) && strlen(md5) == 32;
  265. }
  266. /** database 2.1+ **/
  267. /** indexes **/
  268. int index_add_md5(const char *fn, const char *md5)
  269. /* adds an md5 to an index */
  270. {
  271. int status = 201; /* Created */
  272. FILE *f;
  273. if (!is_md5_hex(md5)) {
  274. srv_log(xs_fmt("index_add_md5: bad md5 %s %s", fn, md5));
  275. return 400;
  276. }
  277. pthread_mutex_lock(&data_mutex);
  278. if ((f = fopen(fn, "a")) != NULL) {
  279. flock(fileno(f), LOCK_EX);
  280. /* ensure the position is at the end after getting the lock */
  281. fseek(f, 0, SEEK_END);
  282. fprintf(f, "%s\n", md5);
  283. fclose(f);
  284. }
  285. else
  286. status = 500;
  287. pthread_mutex_unlock(&data_mutex);
  288. return status;
  289. }
  290. int index_add(const char *fn, const char *id)
  291. /* adds an id to an index */
  292. {
  293. xs *md5 = xs_md5_hex(id, strlen(id));
  294. return index_add_md5(fn, md5);
  295. }
  296. int index_del_md5(const char *fn, const char *md5)
  297. /* deletes an md5 from an index */
  298. {
  299. int status = 404;
  300. FILE *f;
  301. pthread_mutex_lock(&data_mutex);
  302. if ((f = fopen(fn, "r+")) != NULL) {
  303. char line[256];
  304. while (fgets(line, sizeof(line), f) != NULL) {
  305. line[32] = '\0';
  306. if (strcmp(line, md5) == 0) {
  307. /* found! just rewind, overwrite it with garbage
  308. and an eventual call to index_gc() will clean it
  309. [yes: this breaks index_len()] */
  310. fseek(f, -33, SEEK_CUR);
  311. fwrite("-", 1, 1, f);
  312. status = 200;
  313. break;
  314. }
  315. }
  316. fclose(f);
  317. }
  318. else
  319. status = 410;
  320. pthread_mutex_unlock(&data_mutex);
  321. return status;
  322. }
  323. int index_del(const char *fn, const char *id)
  324. /* deletes an id from an index */
  325. {
  326. xs *md5 = xs_md5_hex(id, strlen(id));
  327. return index_del_md5(fn, md5);
  328. }
  329. int index_gc(const char *fn)
  330. /* garbage-collects an index, deleting objects that are not here */
  331. {
  332. FILE *i, *o;
  333. int gc = -1;
  334. pthread_mutex_lock(&data_mutex);
  335. if ((i = fopen(fn, "r")) != NULL) {
  336. xs *nfn = xs_fmt("%s.new", fn);
  337. char line[256];
  338. if ((o = fopen(nfn, "w")) != NULL) {
  339. gc = 0;
  340. while (fgets(line, sizeof(line), i) != NULL) {
  341. line[32] = '\0';
  342. if (line[0] != '-' && object_here_by_md5(line))
  343. fprintf(o, "%s\n", line);
  344. else
  345. gc++;
  346. }
  347. fclose(o);
  348. xs *ofn = xs_fmt("%s.bak", fn);
  349. unlink(ofn);
  350. link(fn, ofn);
  351. rename(nfn, fn);
  352. }
  353. fclose(i);
  354. }
  355. pthread_mutex_unlock(&data_mutex);
  356. return gc;
  357. }
  358. int index_in_md5(const char *fn, const char *md5)
  359. /* checks if the md5 is already in the index */
  360. {
  361. FILE *f;
  362. int ret = 0;
  363. if ((f = fopen(fn, "r")) != NULL) {
  364. flock(fileno(f), LOCK_SH);
  365. char line[256];
  366. while (!ret && fgets(line, sizeof(line), f) != NULL) {
  367. line[32] = '\0';
  368. if (strcmp(line, md5) == 0)
  369. ret = 1;
  370. }
  371. fclose(f);
  372. }
  373. return ret;
  374. }
  375. int index_in(const char *fn, const char *id)
  376. /* checks if the object id is already in the index */
  377. {
  378. xs *md5 = xs_md5_hex(id, strlen(id));
  379. return index_in_md5(fn, md5);
  380. }
  381. int index_first(const char *fn, char *line, int size)
  382. /* reads the first entry of an index */
  383. {
  384. FILE *f;
  385. int ret = 0;
  386. if ((f = fopen(fn, "r")) != NULL) {
  387. flock(fileno(f), LOCK_SH);
  388. if (fgets(line, size, f) != NULL) {
  389. line[32] = '\0';
  390. ret = 1;
  391. }
  392. fclose(f);
  393. }
  394. return ret;
  395. }
  396. int index_len(const char *fn)
  397. /* returns the number of elements in an index */
  398. {
  399. struct stat st;
  400. int len = 0;
  401. if (stat(fn, &st) != -1)
  402. len = st.st_size / 33;
  403. return len;
  404. }
  405. xs_list *index_list(const char *fn, int max)
  406. /* returns an index as a list */
  407. {
  408. xs_list *list = xs_list_new();
  409. FILE *f;
  410. int n = 0;
  411. if ((f = fopen(fn, "r")) != NULL) {
  412. flock(fileno(f), LOCK_SH);
  413. char line[256];
  414. while (n < max && fgets(line, sizeof(line), f) != NULL) {
  415. if (line[0] != '-') {
  416. line[32] = '\0';
  417. list = xs_list_append(list, line);
  418. n++;
  419. }
  420. }
  421. fclose(f);
  422. }
  423. return list;
  424. }
  425. xs_list *index_list_desc(const char *fn, int skip, int show)
  426. /* returns an index as a list, in reverse order */
  427. {
  428. xs_list *list = xs_list_new();
  429. FILE *f;
  430. int n = 0;
  431. if ((f = fopen(fn, "r")) != NULL) {
  432. flock(fileno(f), LOCK_SH);
  433. char line[256];
  434. /* move to the end minus one entry (or more, if skipping entries) */
  435. if (!fseek(f, 0, SEEK_END) && !fseek(f, (skip + 1) * -33, SEEK_CUR)) {
  436. while (n < show && fgets(line, sizeof(line), f) != NULL) {
  437. if (line[0] != '-') {
  438. line[32] = '\0';
  439. list = xs_list_append(list, line);
  440. n++;
  441. }
  442. /* move backwards 2 entries */
  443. if (fseek(f, -66, SEEK_CUR) == -1)
  444. break;
  445. }
  446. }
  447. fclose(f);
  448. }
  449. return list;
  450. }
  451. /** objects **/
  452. static xs_str *_object_fn_by_md5(const char *md5, const char *func)
  453. {
  454. xs *bfn = xs_fmt("%s/object/%c%c", srv_basedir, md5[0], md5[1]);
  455. xs_str *ret;
  456. int ok = 1;
  457. /* an object deleted from an index; fail but don't bark */
  458. if (md5[0] == '-')
  459. ok = 0;
  460. else
  461. if (!is_md5_hex(md5)) {
  462. srv_log(xs_fmt("_object_fn_by_md5() [from %s()]: bad md5 '%s'", func, md5));
  463. ok = 0;
  464. }
  465. if (ok) {
  466. mkdirx(bfn);
  467. ret = xs_fmt("%s/%s.json", bfn, md5);
  468. }
  469. else
  470. ret = xs_fmt("%s/object/invalid/invalid.json", srv_basedir);
  471. return ret;
  472. }
  473. static xs_str *_object_fn(const char *id)
  474. {
  475. xs *md5 = xs_md5_hex(id, strlen(id));
  476. return _object_fn_by_md5(md5, "_object_fn");
  477. }
  478. int object_here_by_md5(const char *id)
  479. /* checks if an object is already downloaded */
  480. {
  481. xs *fn = _object_fn_by_md5(id, "object_here_by_md5");
  482. return mtime(fn) > 0.0;
  483. }
  484. int object_here(const char *id)
  485. /* checks if an object is already downloaded */
  486. {
  487. xs *fn = _object_fn(id);
  488. return mtime(fn) > 0.0;
  489. }
  490. int object_get_by_md5(const char *md5, xs_dict **obj)
  491. /* returns a stored object, optionally of the requested type */
  492. {
  493. int status = 404;
  494. xs *fn = _object_fn_by_md5(md5, "object_get_by_md5");
  495. FILE *f;
  496. if ((f = fopen(fn, "r")) != NULL) {
  497. *obj = xs_json_load(f);
  498. fclose(f);
  499. if (*obj)
  500. status = 200;
  501. }
  502. else
  503. *obj = NULL;
  504. return status;
  505. }
  506. int object_get(const char *id, xs_dict **obj)
  507. /* returns a stored object, optionally of the requested type */
  508. {
  509. xs *md5 = xs_md5_hex(id, strlen(id));
  510. return object_get_by_md5(md5, obj);
  511. }
  512. int _object_add(const char *id, const xs_dict *obj, int ow)
  513. /* stores an object */
  514. {
  515. int status = 201; /* Created */
  516. xs *fn = _object_fn(id);
  517. FILE *f;
  518. if (mtime(fn) > 0.0) {
  519. if (!ow) {
  520. /* object already here */
  521. srv_debug(1, xs_fmt("object_add object already here %s", id));
  522. return 204; /* No content */
  523. }
  524. else
  525. status = 200;
  526. }
  527. if ((f = fopen(fn, "w")) != NULL) {
  528. flock(fileno(f), LOCK_EX);
  529. xs_json_dump(obj, 4, f);
  530. fclose(f);
  531. /* does this object has a parent? */
  532. char *in_reply_to = xs_dict_get(obj, "inReplyTo");
  533. if (!xs_is_null(in_reply_to) && *in_reply_to) {
  534. /* update the children index of the parent */
  535. xs *c_idx = _object_fn(in_reply_to);
  536. c_idx = xs_replace_i(c_idx, ".json", "_c.idx");
  537. if (!index_in(c_idx, id)) {
  538. index_add(c_idx, id);
  539. srv_debug(1, xs_fmt("object_add added child %s to %s", id, c_idx));
  540. }
  541. else
  542. srv_debug(1, xs_fmt("object_add %s child already in %s", id, c_idx));
  543. /* create a one-element index with the parent */
  544. xs *p_idx = xs_replace(fn, ".json", "_p.idx");
  545. if (mtime(p_idx) == 0.0) {
  546. index_add(p_idx, in_reply_to);
  547. srv_debug(1, xs_fmt("object_add added parent %s to %s", in_reply_to, p_idx));
  548. }
  549. }
  550. }
  551. else {
  552. srv_log(xs_fmt("object_add error writing %s (errno: %d)", fn, errno));
  553. status = 500;
  554. }
  555. srv_debug(1, xs_fmt("object_add %s %s %d", id, fn, status));
  556. return status;
  557. }
  558. int object_add(const char *id, const xs_dict *obj)
  559. /* stores an object */
  560. {
  561. return _object_add(id, obj, 0);
  562. }
  563. int object_add_ow(const char *id, const xs_dict *obj)
  564. /* stores an object (overwriting allowed) */
  565. {
  566. return _object_add(id, obj, 1);
  567. }
  568. int object_del_by_md5(const char *md5)
  569. /* deletes an object by its md5 */
  570. {
  571. int status = 404;
  572. xs *fn = _object_fn_by_md5(md5, "object_del_by_md5");
  573. if (unlink(fn) != -1) {
  574. status = 200;
  575. /* also delete associated indexes */
  576. xs *spec = xs_dup(fn);
  577. spec = xs_replace_i(spec, ".json", "*.idx");
  578. xs *files = xs_glob(spec, 0, 0);
  579. char *p, *v;
  580. p = files;
  581. while (xs_list_iter(&p, &v)) {
  582. srv_debug(1, xs_fmt("object_del index %s", v));
  583. unlink(v);
  584. }
  585. }
  586. srv_debug(1, xs_fmt("object_del %s %d", fn, status));
  587. return status;
  588. }
  589. int object_del(const char *id)
  590. /* deletes an object */
  591. {
  592. xs *md5 = xs_md5_hex(id, strlen(id));
  593. return object_del_by_md5(md5);
  594. }
  595. int object_del_if_unref(const char *id)
  596. /* deletes an object if its n_links < 2 */
  597. {
  598. xs *fn = _object_fn(id);
  599. int n_links;
  600. int ret = 0;
  601. if (mtime_nl(fn, &n_links) > 0.0 && n_links < 2)
  602. ret = object_del(id);
  603. return ret;
  604. }
  605. double object_ctime_by_md5(const char *md5)
  606. {
  607. xs *fn = _object_fn_by_md5(md5, "object_ctime_by_md5");
  608. return f_ctime(fn);
  609. }
  610. double object_ctime(const char *id)
  611. {
  612. xs *md5 = xs_md5_hex(id, strlen(id));
  613. return object_ctime_by_md5(md5);
  614. }
  615. double object_mtime_by_md5(const char *md5)
  616. {
  617. xs *fn = _object_fn_by_md5(md5, "object_mtime_by_md5");
  618. return mtime(fn);
  619. }
  620. double object_mtime(const char *id)
  621. {
  622. xs *md5 = xs_md5_hex(id, strlen(id));
  623. return object_mtime_by_md5(md5);
  624. }
  625. void object_touch(const char *id)
  626. {
  627. xs *md5 = xs_md5_hex(id, strlen(id));
  628. xs *fn = _object_fn_by_md5(md5, "object_touch");
  629. if (mtime(fn))
  630. utimes(fn, NULL);
  631. }
  632. xs_str *_object_index_fn(const char *id, const char *idxsfx)
  633. /* returns the filename of an object's index */
  634. {
  635. xs_str *fn = _object_fn(id);
  636. return xs_replace_i(fn, ".json", idxsfx);
  637. }
  638. int object_likes_len(const char *id)
  639. /* returns the number of likes (without reading the index) */
  640. {
  641. xs *fn = _object_index_fn(id, "_l.idx");
  642. return index_len(fn);
  643. }
  644. int object_announces_len(const char *id)
  645. /* returns the number of announces (without reading the index) */
  646. {
  647. xs *fn = _object_index_fn(id, "_a.idx");
  648. return index_len(fn);
  649. }
  650. xs_list *object_children(const char *id)
  651. /* returns the list of an object's children */
  652. {
  653. xs *fn = _object_index_fn(id, "_c.idx");
  654. return index_list(fn, XS_ALL);
  655. }
  656. xs_list *object_likes(const char *id)
  657. {
  658. xs *fn = _object_index_fn(id, "_l.idx");
  659. return index_list(fn, XS_ALL);
  660. }
  661. xs_list *object_announces(const char *id)
  662. {
  663. xs *fn = _object_index_fn(id, "_a.idx");
  664. return index_list(fn, XS_ALL);
  665. }
  666. int object_parent(const char *md5, char *buf, int size)
  667. /* returns the object parent, if any */
  668. {
  669. xs *fn = _object_fn_by_md5(md5, "object_parent");
  670. fn = xs_replace_i(fn, ".json", "_p.idx");
  671. return index_first(fn, buf, size);
  672. }
  673. int object_admire(const char *id, const char *actor, int like)
  674. /* actor likes or announces this object */
  675. {
  676. int status = 200;
  677. xs *fn = _object_fn(id);
  678. fn = xs_replace_i(fn, ".json", like ? "_l.idx" : "_a.idx");
  679. if (!index_in(fn, actor)) {
  680. status = index_add(fn, actor);
  681. srv_debug(1, xs_fmt("object_admire (%s) %s %s", like ? "Like" : "Announce", actor, fn));
  682. }
  683. return status;
  684. }
  685. int object_unadmire(const char *id, const char *actor, int like)
  686. /* actor no longer likes or announces this object */
  687. {
  688. int status;
  689. xs *fn = _object_fn(id);
  690. fn = xs_replace_i(fn, ".json", like ? "_l.idx" : "_a.idx");
  691. status = index_del(fn, actor);
  692. if (valid_status(status))
  693. index_gc(fn);
  694. srv_debug(0,
  695. xs_fmt("object_unadmire (%s) %s %s %d", like ? "Like" : "Announce", actor, fn, status));
  696. return status;
  697. }
  698. int _object_user_cache(snac *snac, const char *id, const char *cachedir, int del)
  699. /* adds or deletes from a user cache */
  700. {
  701. xs *ofn = _object_fn(id);
  702. xs *l = xs_split(ofn, "/");
  703. xs *cfn = xs_fmt("%s/%s/%s", snac->basedir, cachedir, xs_list_get(l, -1));
  704. xs *idx = xs_fmt("%s/%s.idx", snac->basedir, cachedir);
  705. int ret;
  706. if (del) {
  707. ret = unlink(cfn);
  708. index_del(idx, id);
  709. }
  710. else {
  711. if ((ret = link(ofn, cfn)) != -1)
  712. index_add(idx, id);
  713. }
  714. return ret;
  715. }
  716. int object_user_cache_add(snac *snac, const char *id, const char *cachedir)
  717. /* caches an object into a user cache */
  718. {
  719. return _object_user_cache(snac, id, cachedir, 0);
  720. }
  721. int object_user_cache_del(snac *snac, const char *id, const char *cachedir)
  722. /* deletes an object from a user cache */
  723. {
  724. return _object_user_cache(snac, id, cachedir, 1);
  725. }
  726. int object_user_cache_in(snac *snac, const char *id, const char *cachedir)
  727. /* checks if an object is stored in a cache */
  728. {
  729. xs *md5 = xs_md5_hex(id, strlen(id));
  730. xs *cfn = xs_fmt("%s/%s/%s.json", snac->basedir, cachedir, md5);
  731. return !!(mtime(cfn) != 0.0);
  732. }
  733. xs_list *object_user_cache_list(snac *snac, const char *cachedir, int max, int inv)
  734. /* returns the objects in a cache as a list */
  735. {
  736. xs *idx = xs_fmt("%s/%s.idx", snac->basedir, cachedir);
  737. return inv ? index_list_desc(idx, 0, max) : index_list(idx, max);
  738. }
  739. /** specialized functions **/
  740. /** followers **/
  741. int follower_add(snac *snac, const char *actor)
  742. /* adds a follower */
  743. {
  744. int ret = object_user_cache_add(snac, actor, "followers");
  745. snac_debug(snac, 2, xs_fmt("follower_add %s", actor));
  746. return ret == -1 ? 500 : 200;
  747. }
  748. int follower_del(snac *snac, const char *actor)
  749. /* deletes a follower */
  750. {
  751. int ret = object_user_cache_del(snac, actor, "followers");
  752. snac_debug(snac, 2, xs_fmt("follower_del %s", actor));
  753. return ret == -1 ? 404 : 200;
  754. }
  755. int follower_check(snac *snac, const char *actor)
  756. /* checks if someone is a follower */
  757. {
  758. return object_user_cache_in(snac, actor, "followers");
  759. }
  760. xs_list *follower_list(snac *snac)
  761. /* returns the list of followers */
  762. {
  763. xs *list = object_user_cache_list(snac, "followers", XS_ALL, 0);
  764. xs_list *fwers = xs_list_new();
  765. char *p, *v;
  766. /* resolve the list of md5 to be a list of actors */
  767. p = list;
  768. while (xs_list_iter(&p, &v)) {
  769. xs *a_obj = NULL;
  770. if (valid_status(object_get_by_md5(v, &a_obj))) {
  771. const char *actor = xs_dict_get(a_obj, "id");
  772. if (!xs_is_null(actor)) {
  773. /* check if the actor is still cached */
  774. xs *fn = xs_fmt("%s/followers/%s.json", snac->basedir, v);
  775. if (mtime(fn) > 0.0)
  776. fwers = xs_list_append(fwers, actor);
  777. }
  778. }
  779. }
  780. return fwers;
  781. }
  782. /** timeline **/
  783. double timeline_mtime(snac *snac)
  784. {
  785. xs *fn = xs_fmt("%s/private.idx", snac->basedir);
  786. return mtime(fn);
  787. }
  788. int timeline_touch(snac *snac)
  789. /* changes the date of the timeline index */
  790. {
  791. xs *fn = xs_fmt("%s/private.idx", snac->basedir);
  792. return utimes(fn, NULL);
  793. }
  794. xs_str *timeline_fn_by_md5(snac *snac, const char *md5)
  795. /* get the filename of an entry by md5 from any timeline */
  796. {
  797. xs_str *fn = NULL;
  798. if (xs_is_hex(md5) && strlen(md5) == 32) {
  799. fn = xs_fmt("%s/private/%s.json", snac->basedir, md5);
  800. if (mtime(fn) == 0.0) {
  801. fn = xs_free(fn);
  802. fn = xs_fmt("%s/public/%s.json", snac->basedir, md5);
  803. if (mtime(fn) == 0.0)
  804. fn = xs_free(fn);
  805. }
  806. }
  807. return fn;
  808. }
  809. int timeline_here(snac *snac, const char *md5)
  810. /* checks if an object is in the user cache */
  811. {
  812. xs *fn = timeline_fn_by_md5(snac, md5);
  813. return !(fn == NULL);
  814. }
  815. int timeline_get_by_md5(snac *snac, const char *md5, xs_dict **msg)
  816. /* gets a message from the timeline */
  817. {
  818. int status = 404;
  819. FILE *f = NULL;
  820. xs *fn = timeline_fn_by_md5(snac, md5);
  821. if (fn != NULL && (f = fopen(fn, "r")) != NULL) {
  822. *msg = xs_json_load(f);
  823. fclose(f);
  824. if (*msg != NULL)
  825. status = 200;
  826. }
  827. return status;
  828. }
  829. int timeline_del(snac *snac, char *id)
  830. /* deletes a message from the timeline */
  831. {
  832. /* delete from the user's caches */
  833. object_user_cache_del(snac, id, "public");
  834. object_user_cache_del(snac, id, "private");
  835. /* try to delete the object if it's not used elsewhere */
  836. return object_del_if_unref(id);
  837. }
  838. void timeline_update_indexes(snac *snac, const char *id)
  839. /* updates the indexes */
  840. {
  841. object_user_cache_add(snac, id, "private");
  842. if (xs_startswith(id, snac->actor)) {
  843. xs *msg = NULL;
  844. if (valid_status(object_get(id, &msg))) {
  845. /* if its ours and is public, also store in public */
  846. if (is_msg_public(msg)) {
  847. object_user_cache_add(snac, id, "public");
  848. /* also add it to the instance public timeline */
  849. xs *ipt = xs_fmt("%s/public.idx", srv_basedir);
  850. index_add(ipt, id);
  851. }
  852. }
  853. }
  854. }
  855. int timeline_add(snac *snac, const char *id, const xs_dict *o_msg)
  856. /* adds a message to the timeline */
  857. {
  858. int ret = object_add(id, o_msg);
  859. timeline_update_indexes(snac, id);
  860. tag_index(id, o_msg);
  861. list_distribute(snac, NULL, o_msg);
  862. snac_debug(snac, 1, xs_fmt("timeline_add %s", id));
  863. return ret;
  864. }
  865. int timeline_admire(snac *snac, const char *id, const char *admirer, int like)
  866. /* updates a timeline entry with a new admiration */
  867. {
  868. /* if we are admiring this, add to both timelines */
  869. if (!like && strcmp(admirer, snac->actor) == 0) {
  870. object_user_cache_add(snac, id, "public");
  871. object_user_cache_add(snac, id, "private");
  872. }
  873. int ret = object_admire(id, admirer, like);
  874. snac_debug(snac, 1, xs_fmt("timeline_admire (%s) %s %s",
  875. like ? "Like" : "Announce", id, admirer));
  876. return ret;
  877. }
  878. xs_list *timeline_top_level(snac *snac, xs_list *list)
  879. /* returns the top level md5 entries from this index */
  880. {
  881. xs_set seen;
  882. xs_list *p;
  883. xs_str *v;
  884. xs_set_init(&seen);
  885. p = list;
  886. while (xs_list_iter(&p, &v)) {
  887. char line[256] = "";
  888. strncpy(line, v, sizeof(line));
  889. for (;;) {
  890. char line2[256];
  891. /* if it doesn't have a parent, use this */
  892. if (!object_parent(line, line2, sizeof(line2)))
  893. break;
  894. /* well, there is a parent... but is it here? */
  895. if (!timeline_here(snac, line2))
  896. break;
  897. /* it's here! try again with its own parent */
  898. strncpy(line, line2, sizeof(line));
  899. }
  900. xs_set_add(&seen, line);
  901. }
  902. return xs_set_result(&seen);
  903. }
  904. xs_list *timeline_simple_list(snac *snac, const char *idx_name, int skip, int show)
  905. /* returns a timeline (with all entries) */
  906. {
  907. xs *idx = xs_fmt("%s/%s.idx", snac->basedir, idx_name);
  908. return index_list_desc(idx, skip, show);
  909. }
  910. xs_list *timeline_list(snac *snac, const char *idx_name, int skip, int show)
  911. /* returns a timeline (only top level entries) */
  912. {
  913. int c_max;
  914. /* maximum number of items in the timeline */
  915. c_max = xs_number_get(xs_dict_get(srv_config, "max_timeline_entries"));
  916. /* never more timeline entries than the configured maximum */
  917. if (show > c_max)
  918. show = c_max;
  919. xs *list = timeline_simple_list(snac, idx_name, skip, show);
  920. return timeline_top_level(snac, list);
  921. }
  922. xs_list *timeline_instance_list(int skip, int show)
  923. /* returns the timeline for the full instance */
  924. {
  925. xs *idx = xs_fmt("%s/public.idx", srv_basedir);
  926. return index_list_desc(idx, skip, show);
  927. }
  928. /** following **/
  929. /* this needs special treatment and cannot use the object db as is,
  930. with a link to a cached author, because we need the Follow object
  931. in case we need to unfollow (Undo + original Follow) */
  932. xs_str *_following_fn(snac *snac, const char *actor)
  933. {
  934. xs *md5 = xs_md5_hex(actor, strlen(actor));
  935. return xs_fmt("%s/following/%s.json", snac->basedir, md5);
  936. }
  937. int following_add(snac *snac, const char *actor, const xs_dict *msg)
  938. /* adds to the following list */
  939. {
  940. int ret = 201; /* created */
  941. xs *fn = _following_fn(snac, actor);
  942. FILE *f;
  943. xs *p_object = NULL;
  944. if (valid_status(following_get(snac, actor, &p_object))) {
  945. /* object already exists; if it's of type Accept,
  946. the actor is already being followed and confirmed,
  947. so do nothing */
  948. char *type = xs_dict_get(p_object, "type");
  949. if (!xs_is_null(type) && strcmp(type, "Accept") == 0) {
  950. snac_debug(snac, 1, xs_fmt("following_add actor already confirmed %s", actor));
  951. return 200;
  952. }
  953. }
  954. if ((f = fopen(fn, "w")) != NULL) {
  955. xs_json_dump(msg, 4, f);
  956. fclose(f);
  957. /* get the filename of the actor object */
  958. xs *actor_fn = _object_fn(actor);
  959. /* increase its reference count */
  960. fn = xs_replace_i(fn, ".json", "_a.json");
  961. link(actor_fn, fn);
  962. }
  963. else
  964. ret = 500;
  965. snac_debug(snac, 2, xs_fmt("following_add %s %s", actor, fn));
  966. return ret;
  967. }
  968. int following_del(snac *snac, const char *actor)
  969. /* we're not following this actor any longer */
  970. {
  971. xs *fn = _following_fn(snac, actor);
  972. snac_debug(snac, 2, xs_fmt("following_del %s %s", actor, fn));
  973. unlink(fn);
  974. /* also delete the reference to the author */
  975. fn = xs_replace_i(fn, ".json", "_a.json");
  976. unlink(fn);
  977. return 200;
  978. }
  979. int following_check(snac *snac, const char *actor)
  980. /* checks if we are following this actor */
  981. {
  982. xs *fn = _following_fn(snac, actor);
  983. return !!(mtime(fn) != 0.0);
  984. }
  985. int following_get(snac *snac, const char *actor, xs_dict **data)
  986. /* returns the 'Follow' object */
  987. {
  988. xs *fn = _following_fn(snac, actor);
  989. FILE *f;
  990. int status = 200;
  991. if ((f = fopen(fn, "r")) != NULL) {
  992. *data = xs_json_load(f);
  993. fclose(f);
  994. }
  995. else
  996. status = 404;
  997. return status;
  998. }
  999. xs_list *following_list(snac *snac)
  1000. /* returns the list of people being followed */
  1001. {
  1002. xs *spec = xs_fmt("%s/following/" "*.json", snac->basedir);
  1003. xs *glist = xs_glob(spec, 0, 0);
  1004. xs_list *p;
  1005. xs_str *v;
  1006. xs_list *list = xs_list_new();
  1007. /* iterate the list of files */
  1008. p = glist;
  1009. while (xs_list_iter(&p, &v)) {
  1010. FILE *f;
  1011. /* load the follower data */
  1012. if ((f = fopen(v, "r")) != NULL) {
  1013. xs *o = xs_json_load(f);
  1014. fclose(f);
  1015. if (o != NULL) {
  1016. const char *type = xs_dict_get(o, "type");
  1017. if (!xs_is_null(type) && strcmp(type, "Accept") == 0) {
  1018. const char *actor = xs_dict_get(o, "actor");
  1019. if (!xs_is_null(actor)) {
  1020. list = xs_list_append(list, actor);
  1021. /* check if there is a link to the actor object */
  1022. xs *v2 = xs_replace(v, ".json", "_a.json");
  1023. if (mtime(v2) == 0.0) {
  1024. /* no; add a link to it */
  1025. xs *actor_fn = _object_fn(actor);
  1026. link(actor_fn, v2);
  1027. }
  1028. }
  1029. }
  1030. }
  1031. }
  1032. }
  1033. return list;
  1034. }
  1035. xs_str *_muted_fn(snac *snac, const char *actor)
  1036. {
  1037. xs *md5 = xs_md5_hex(actor, strlen(actor));
  1038. return xs_fmt("%s/muted/%s", snac->basedir, md5);
  1039. }
  1040. void mute(snac *snac, const char *actor)
  1041. /* mutes a moron */
  1042. {
  1043. xs *fn = _muted_fn(snac, actor);
  1044. FILE *f;
  1045. if ((f = fopen(fn, "w")) != NULL) {
  1046. fprintf(f, "%s\n", actor);
  1047. fclose(f);
  1048. snac_debug(snac, 2, xs_fmt("muted %s %s", actor, fn));
  1049. }
  1050. }
  1051. void unmute(snac *snac, const char *actor)
  1052. /* actor is no longer a moron */
  1053. {
  1054. xs *fn = _muted_fn(snac, actor);
  1055. unlink(fn);
  1056. snac_debug(snac, 2, xs_fmt("unmuted %s %s", actor, fn));
  1057. }
  1058. int is_muted(snac *snac, const char *actor)
  1059. /* check if someone is muted */
  1060. {
  1061. xs *fn = _muted_fn(snac, actor);
  1062. return !!(mtime(fn) != 0.0);
  1063. }
  1064. /** pinning **/
  1065. xs_str *_pinned_fn(snac *user, const char *id)
  1066. {
  1067. xs *md5 = xs_md5_hex(id, strlen(id));
  1068. return xs_fmt("%s/pinned/%s.json", user->basedir, md5);
  1069. }
  1070. int is_pinned(snac *user, const char *id)
  1071. /* returns true if this note is pinned */
  1072. {
  1073. xs *fn = _pinned_fn(user, id);
  1074. return !!(mtime(fn) != 0.0);
  1075. }
  1076. int is_pinned_by_md5(snac *user, const char *md5)
  1077. {
  1078. xs *fn = xs_fmt("%s/pinned/%s.json", user->basedir, md5);
  1079. return !!(mtime(fn) != 0.0);
  1080. }
  1081. int pin(snac *user, const char *id)
  1082. /* pins a message */
  1083. {
  1084. int ret = -2;
  1085. if (xs_startswith(id, user->actor)) {
  1086. if (is_pinned(user, id))
  1087. ret = -3;
  1088. else {
  1089. /* create the subfolder, if it does not exist */
  1090. xs *fn = xs_fmt("%s/pinned/", user->basedir);
  1091. mkdirx(fn);
  1092. ret = object_user_cache_add(user, id, "pinned");
  1093. }
  1094. }
  1095. return ret;
  1096. }
  1097. int unpin(snac *user, const char *id)
  1098. /* unpin a message */
  1099. {
  1100. int ret = object_user_cache_del(user, id, "pinned");
  1101. if (ret != -1) {
  1102. /* delete from the index */
  1103. xs *idx = xs_fmt("%s/pinned.idx", user->basedir);
  1104. index_del(idx, id);
  1105. }
  1106. return ret;
  1107. }
  1108. xs_list *pinned_list(snac *user)
  1109. /* return the lists of pinned posts */
  1110. {
  1111. return object_user_cache_list(user, "pinned", XS_ALL, 1);
  1112. }
  1113. xs_str *_hidden_fn(snac *snac, const char *id)
  1114. {
  1115. xs *md5 = xs_md5_hex(id, strlen(id));
  1116. return xs_fmt("%s/hidden/%s", snac->basedir, md5);
  1117. }
  1118. void hide(snac *snac, const char *id)
  1119. /* hides a message tree */
  1120. {
  1121. xs *fn = _hidden_fn(snac, id);
  1122. FILE *f;
  1123. if ((f = fopen(fn, "w")) != NULL) {
  1124. fprintf(f, "%s\n", id);
  1125. fclose(f);
  1126. snac_debug(snac, 2, xs_fmt("hidden %s %s", id, fn));
  1127. /* hide all the children */
  1128. xs *chld = object_children(id);
  1129. char *p, *v;
  1130. p = chld;
  1131. while (xs_list_iter(&p, &v)) {
  1132. xs *co = NULL;
  1133. /* resolve to get the id */
  1134. if (valid_status(object_get_by_md5(v, &co))) {
  1135. if ((v = xs_dict_get(co, "id")) != NULL)
  1136. hide(snac, v);
  1137. }
  1138. }
  1139. }
  1140. }
  1141. int is_hidden(snac *snac, const char *id)
  1142. /* check is id is hidden */
  1143. {
  1144. xs *fn = _hidden_fn(snac, id);
  1145. return !!(mtime(fn) != 0.0);
  1146. }
  1147. int actor_add(const char *actor, xs_dict *msg)
  1148. /* adds an actor */
  1149. {
  1150. return object_add_ow(actor, msg);
  1151. }
  1152. int actor_get(const char *actor, xs_dict **data)
  1153. /* returns an already downloaded actor */
  1154. {
  1155. int status = 200;
  1156. xs_dict *d = NULL;
  1157. if (xs_startswith(actor, srv_baseurl)) {
  1158. /* it's a (possible) local user */
  1159. xs *l = xs_split(actor, "/");
  1160. const char *uid = xs_list_get(l, -1);
  1161. snac user;
  1162. if (!xs_is_null(uid) && user_open(&user, uid)) {
  1163. if (data)
  1164. *data = msg_actor(&user);
  1165. user_free(&user);
  1166. return 200;
  1167. }
  1168. else
  1169. return 404;
  1170. }
  1171. /* read the object */
  1172. if (!valid_status(status = object_get(actor, &d))) {
  1173. d = xs_free(d);
  1174. return status;
  1175. }
  1176. /* if the object is corrupted, discard it */
  1177. if (xs_is_null(xs_dict_get(d, "id")) || xs_is_null(xs_dict_get(d, "type"))) {
  1178. srv_debug(1, xs_fmt("corrupted actor object %s", actor));
  1179. d = xs_free(d);
  1180. return 404;
  1181. }
  1182. if (data)
  1183. *data = d;
  1184. else
  1185. d = xs_free(d);
  1186. xs *fn = _object_fn(actor);
  1187. double max_time;
  1188. /* maximum time for the actor data to be considered stale */
  1189. max_time = 3600.0 * 36.0;
  1190. if (mtime(fn) + max_time < (double) time(NULL)) {
  1191. /* actor data exists but also stinks */
  1192. status = 205; /* "205: Reset Content" "110: Response Is Stale" */
  1193. }
  1194. return status;
  1195. }
  1196. int actor_get_refresh(snac *user, const char *actor, xs_dict **data)
  1197. /* gets an actor and requests a refresh if it's stale */
  1198. {
  1199. int status = actor_get(actor, data);
  1200. if (status == 205 && user && !xs_startswith(actor, srv_baseurl))
  1201. enqueue_actor_refresh(user, actor, 0);
  1202. return status;
  1203. }
  1204. /** user limiting (announce blocks) **/
  1205. int limited(snac *user, const char *id, int cmd)
  1206. /* announce messages from a followed (0: check, 1: limit; 2: unlimit) */
  1207. {
  1208. int ret = 0;
  1209. xs *dir = xs_fmt("%s/limited", user->basedir);
  1210. xs *md5 = xs_md5_hex(id, strlen(id));
  1211. xs *fn = xs_fmt("%s/%s", dir, md5);
  1212. switch (cmd) {
  1213. case 0: /** check **/
  1214. ret = !!(mtime(fn) > 0.0);
  1215. break;
  1216. case 1: /** limit **/
  1217. mkdirx(dir);
  1218. if (mtime(fn) > 0.0)
  1219. ret = -1;
  1220. else {
  1221. FILE *f;
  1222. if ((f = fopen(fn, "w")) != NULL) {
  1223. fprintf(f, "%s\n", id);
  1224. fclose(f);
  1225. }
  1226. else
  1227. ret = -2;
  1228. }
  1229. break;
  1230. case 2: /** unlimit **/
  1231. if (mtime(fn) > 0.0)
  1232. ret = unlink(fn);
  1233. else
  1234. ret = -1;
  1235. break;
  1236. }
  1237. return ret;
  1238. }
  1239. /** tag indexing **/
  1240. void tag_index(const char *id, const xs_dict *obj)
  1241. /* update the tag indexes for this object */
  1242. {
  1243. xs_list *tags = xs_dict_get(obj, "tag");
  1244. if (is_msg_public(obj) && xs_type(tags) == XSTYPE_LIST && xs_list_len(tags) > 0) {
  1245. xs *g_tag_dir = xs_fmt("%s/tag", srv_basedir);
  1246. mkdirx(g_tag_dir);
  1247. xs_dict *v;
  1248. while (xs_list_iter(&tags, &v)) {
  1249. char *type = xs_dict_get(v, "type");
  1250. char *name = xs_dict_get(v, "name");
  1251. if (!xs_is_null(type) && !xs_is_null(name) && strcmp(type, "Hashtag") == 0) {
  1252. while (*name == '#' || *name == '@')
  1253. name++;
  1254. if (*name == '\0')
  1255. continue;
  1256. name = xs_tolower_i(name);
  1257. xs *md5_tag = xs_md5_hex(name, strlen(name));
  1258. xs *tag_dir = xs_fmt("%s/%c%c", g_tag_dir, md5_tag[0], md5_tag[1]);
  1259. mkdirx(tag_dir);
  1260. xs *g_tag_idx = xs_fmt("%s/%s.idx", tag_dir, md5_tag);
  1261. index_add(g_tag_idx, id);
  1262. FILE *f;
  1263. xs *g_tag_name = xs_replace(g_tag_idx, ".idx", ".tag");
  1264. if ((f = fopen(g_tag_name, "w")) != NULL) {
  1265. fprintf(f, "%s\n", name);
  1266. fclose(f);
  1267. }
  1268. srv_debug(0, xs_fmt("tagged %s #%s (#%s)", id, name, md5_tag));
  1269. }
  1270. }
  1271. }
  1272. }
  1273. xs_list *tag_search(char *tag, int skip, int show)
  1274. /* returns the list of posts tagged with tag */
  1275. {
  1276. if (*tag == '#')
  1277. tag++;
  1278. xs *lw_tag = xs_tolower_i(xs_dup(tag));
  1279. xs *md5 = xs_md5_hex(lw_tag, strlen(lw_tag));
  1280. xs *idx = xs_fmt("%s/tag/%c%c/%s.idx", srv_basedir, md5[0], md5[1], md5);
  1281. return index_list_desc(idx, skip, show);
  1282. }
  1283. /** lists **/
  1284. xs_val *list_maint(snac *user, const char *list, int op)
  1285. /* list maintenance */
  1286. {
  1287. xs_val *l = NULL;
  1288. switch (op) {
  1289. case 0: /** list of lists **/
  1290. {
  1291. FILE *f;
  1292. xs *spec = xs_fmt("%s/list/" "*.id", user->basedir);
  1293. xs *ls = xs_glob(spec, 0, 0);
  1294. int c = 0;
  1295. char *v;
  1296. l = xs_list_new();
  1297. while (xs_list_next(ls, &v, &c)) {
  1298. if ((f = fopen(v, "r")) != NULL) {
  1299. xs *title = xs_readline(f);
  1300. fclose(f);
  1301. title = xs_strip_i(title);
  1302. xs *v2 = xs_replace(v, ".id", "");
  1303. xs *l2 = xs_split(v2, "/");
  1304. /* return [ list_id, list_title ] */
  1305. l = xs_list_append(l, xs_list_append(xs_list_new(), xs_list_get(l2, -1), title));
  1306. }
  1307. }
  1308. }
  1309. break;
  1310. case 1: /** create new list (list is the name) **/
  1311. {
  1312. xs *lol = list_maint(user, NULL, 0);
  1313. int c = 0;
  1314. xs_list *v;
  1315. int add = 1;
  1316. /* check if this list name already exists */
  1317. while (xs_list_next(lol, &v, &c)) {
  1318. if (strcmp(xs_list_get(v, 1), list) == 0) {
  1319. add = 0;
  1320. break;
  1321. }
  1322. }
  1323. if (add) {
  1324. FILE *f;
  1325. xs *dir = xs_fmt("%s/list/", user->basedir);
  1326. xs *id = xs_fmt("%010x", time(NULL));
  1327. mkdirx(dir);
  1328. xs *fn = xs_fmt("%s%s.id", dir, id);
  1329. if ((f = fopen(fn, "w")) != NULL) {
  1330. fprintf(f, "%s\n", list);
  1331. fclose(f);
  1332. }
  1333. l = xs_stock(XSTYPE_TRUE);
  1334. }
  1335. else
  1336. l = xs_stock(XSTYPE_FALSE);
  1337. }
  1338. break;
  1339. case 2: /** delete list (list is the id) **/
  1340. {
  1341. if (xs_is_hex(list)) {
  1342. xs *fn = xs_fmt("%s/list/%s.id", user->basedir, list);
  1343. unlink(fn);
  1344. fn = xs_replace_i(fn, ".id", ".lst");
  1345. unlink(fn);
  1346. fn = xs_replace_i(fn, ".lst", ".idx");
  1347. unlink(fn);
  1348. }
  1349. }
  1350. break;
  1351. case 3: /** get list name **/
  1352. if (xs_is_hex(list)) {
  1353. FILE *f;
  1354. xs *fn = xs_fmt("%s/list/%s.id", user->basedir, list);
  1355. if ((f = fopen(fn, "r")) != NULL) {
  1356. l = xs_strip_i(xs_readline(f));
  1357. fclose(f);
  1358. }
  1359. }
  1360. break;
  1361. }
  1362. return l;
  1363. }
  1364. xs_list *list_timeline(snac *user, const char *list, int skip, int show)
  1365. /* returns the timeline of a list */
  1366. {
  1367. xs_list *l = NULL;
  1368. if (!xs_is_hex(list))
  1369. return NULL;
  1370. xs *fn = xs_fmt("%s/list/%s.idx", user->basedir, list);
  1371. if (mtime(fn) > 0.0)
  1372. l = index_list_desc(fn, skip, show);
  1373. return l;
  1374. }
  1375. xs_val *list_content(snac *user, const char *list, const char *actor_md5, int op)
  1376. /* list content management */
  1377. {
  1378. xs_val *l = NULL;
  1379. if (!xs_is_hex(list))
  1380. return NULL;
  1381. if (actor_md5 != NULL && !xs_is_hex(actor_md5))
  1382. return NULL;
  1383. xs *fn = xs_fmt("%s/list/%s.lst", user->basedir, list);
  1384. switch (op) {
  1385. case 0: /** list content **/
  1386. l = index_list(fn, XS_ALL);
  1387. break;
  1388. case 1: /** append actor to list **/
  1389. if (actor_md5 != NULL) {
  1390. if (!index_in(fn, actor_md5))
  1391. index_add_md5(fn, actor_md5);
  1392. }
  1393. break;
  1394. case 2: /** delete actor from list **/
  1395. if (actor_md5 != NULL)
  1396. index_del_md5(fn, actor_md5);
  1397. break;
  1398. default:
  1399. srv_log(xs_fmt("ERROR: list_content: bad op %d", op));
  1400. break;
  1401. }
  1402. return l;
  1403. }
  1404. void list_distribute(snac *user, const char *who, const xs_dict *post)
  1405. /* distributes the post to all appropriate lists */
  1406. {
  1407. char *id = xs_dict_get(post, "id");
  1408. /* if who is not set, use the attributedTo in the message */
  1409. if (xs_is_null(who))
  1410. who = get_atto(post);
  1411. if (xs_type(who) == XSTYPE_STRING && xs_type(id) == XSTYPE_STRING) {
  1412. xs *a_md5 = xs_md5_hex(who, strlen(who));
  1413. xs *i_md5 = xs_md5_hex(id, strlen(id));
  1414. xs *spec = xs_fmt("%s/list/" "*.lst", user->basedir);
  1415. xs *ls = xs_glob(spec, 0, 0);
  1416. int c = 0;
  1417. char *v;
  1418. while (xs_list_next(ls, &v, &c)) {
  1419. /* is the actor in this list? */
  1420. if (index_in_md5(v, a_md5)) {
  1421. /* it is; add post md5 to its timeline */
  1422. xs *idx = xs_replace(v, ".lst", ".idx");
  1423. index_add_md5(idx, i_md5);
  1424. snac_debug(user, 1, xs_fmt("listed post %s in %s", id, idx));
  1425. }
  1426. }
  1427. }
  1428. }
  1429. /** static data **/
  1430. static int _load_raw_file(const char *fn, xs_val **data, int *size,
  1431. const char *inm, xs_str **etag)
  1432. /* loads a cached file */
  1433. {
  1434. int status = 404;
  1435. if (fn) {
  1436. double tm = mtime(fn);
  1437. if (tm > 0.0) {
  1438. /* file exists; build the etag */
  1439. xs *e = xs_fmt("W/\"snac-%.0lf\"", tm);
  1440. /* if if-none-match is set, check if it's the same */
  1441. if (!xs_is_null(inm) && strcmp(e, inm) == 0) {
  1442. /* client has the newest version */
  1443. status = 304;
  1444. }
  1445. else {
  1446. /* newer or never downloaded; read the full file */
  1447. FILE *f;
  1448. if ((f = fopen(fn, "rb")) != NULL) {
  1449. *size = XS_ALL;
  1450. *data = xs_read(f, size);
  1451. fclose(f);
  1452. status = 200;
  1453. }
  1454. }
  1455. /* if caller wants the etag, return it */
  1456. if (etag != NULL)
  1457. *etag = xs_dup(e);
  1458. srv_debug(1, xs_fmt("_load_raw_file(): %s %d", fn, status));
  1459. }
  1460. }
  1461. return status;
  1462. }
  1463. xs_str *_static_fn(snac *snac, const char *id)
  1464. /* gets the filename for a static file */
  1465. {
  1466. if (strchr(id, '/'))
  1467. return NULL;
  1468. else
  1469. return xs_fmt("%s/static/%s", snac->basedir, id);
  1470. }
  1471. int static_get(snac *snac, const char *id, xs_val **data, int *size,
  1472. const char *inm, xs_str **etag)
  1473. /* returns static content */
  1474. {
  1475. xs *fn = _static_fn(snac, id);
  1476. return _load_raw_file(fn, data, size, inm, etag);
  1477. }
  1478. void static_put(snac *snac, const char *id, const char *data, int size)
  1479. /* writes status content */
  1480. {
  1481. xs *fn = _static_fn(snac, id);
  1482. FILE *f;
  1483. if (fn && (f = fopen(fn, "wb")) != NULL) {
  1484. fwrite(data, size, 1, f);
  1485. fclose(f);
  1486. }
  1487. }
  1488. void static_put_meta(snac *snac, const char *id, const char *str)
  1489. /* puts metadata (i.e. a media description string) to id */
  1490. {
  1491. xs *fn = _static_fn(snac, id);
  1492. if (fn) {
  1493. fn = xs_str_cat(fn, ".txt");
  1494. FILE *f;
  1495. if ((f = fopen(fn, "w")) != NULL) {
  1496. fprintf(f, "%s\n", str);
  1497. fclose(f);
  1498. }
  1499. }
  1500. }
  1501. xs_str *static_get_meta(snac *snac, const char *id)
  1502. /* gets metadata from a media */
  1503. {
  1504. xs *fn = _static_fn(snac, id);
  1505. xs_str *r = NULL;
  1506. if (fn) {
  1507. fn = xs_str_cat(fn, ".txt");
  1508. FILE *f;
  1509. if ((f = fopen(fn, "r")) != NULL) {
  1510. r = xs_strip_i(xs_readline(f));
  1511. fclose(f);
  1512. }
  1513. }
  1514. else
  1515. r = xs_str_new("");
  1516. return r;
  1517. }
  1518. /** history **/
  1519. xs_str *_history_fn(snac *snac, const char *id)
  1520. /* gets the filename for the history */
  1521. {
  1522. if (strchr(id, '/'))
  1523. return NULL;
  1524. else
  1525. return xs_fmt("%s/history/%s", snac->basedir, id);
  1526. }
  1527. double history_mtime(snac *snac, const char *id)
  1528. {
  1529. double t = 0.0;
  1530. xs *fn = _history_fn(snac, id);
  1531. if (fn != NULL)
  1532. t = mtime(fn);
  1533. return t;
  1534. }
  1535. void history_add(snac *snac, const char *id, const char *content, int size,
  1536. xs_str **etag)
  1537. /* adds something to the history */
  1538. {
  1539. xs *fn = _history_fn(snac, id);
  1540. FILE *f;
  1541. if (fn && (f = fopen(fn, "w")) != NULL) {
  1542. fwrite(content, size, 1, f);
  1543. fclose(f);
  1544. if (etag) {
  1545. double tm = mtime(fn);
  1546. *etag = xs_fmt("W/\"snac-%.0lf\"", tm);
  1547. }
  1548. }
  1549. }
  1550. int history_get(snac *snac, const char *id, xs_str **content, int *size,
  1551. const char *inm, xs_str **etag)
  1552. {
  1553. xs *fn = _history_fn(snac, id);
  1554. return _load_raw_file(fn, content, size, inm, etag);
  1555. }
  1556. int history_del(snac *snac, const char *id)
  1557. {
  1558. xs *fn = _history_fn(snac, id);
  1559. if (fn)
  1560. return unlink(fn);
  1561. else
  1562. return -1;
  1563. }
  1564. xs_list *history_list(snac *snac)
  1565. {
  1566. xs *spec = xs_fmt("%s/history/" "*.html", snac->basedir);
  1567. return xs_glob(spec, 1, 1);
  1568. }
  1569. void lastlog_write(snac *snac, const char *source)
  1570. /* writes the last time the user logged in */
  1571. {
  1572. xs *fn = xs_fmt("%s/lastlog.txt", snac->basedir);
  1573. FILE *f;
  1574. if ((f = fopen(fn, "w")) != NULL) {
  1575. fprintf(f, "%lf %s\n", ftime(), source);
  1576. fclose(f);
  1577. }
  1578. }
  1579. /** inbox collection **/
  1580. void inbox_add(const char *inbox)
  1581. /* collects a shared inbox */
  1582. {
  1583. /* don't collect ourselves */
  1584. if (xs_startswith(inbox, srv_baseurl))
  1585. return;
  1586. xs *md5 = xs_md5_hex(inbox, strlen(inbox));
  1587. xs *fn = xs_fmt("%s/inbox/%s", srv_basedir, md5);
  1588. FILE *f;
  1589. if ((f = fopen(fn, "w")) != NULL) {
  1590. fprintf(f, "%s\n", inbox);
  1591. fclose(f);
  1592. }
  1593. }
  1594. void inbox_add_by_actor(const xs_dict *actor)
  1595. /* collects an actor's shared inbox, if it has one */
  1596. {
  1597. char *v;
  1598. if (!xs_is_null(v = xs_dict_get(actor, "endpoints")) &&
  1599. !xs_is_null(v = xs_dict_get(v, "sharedInbox"))) {
  1600. /* only collect this inbox if its instance is not blocked */
  1601. if (!is_instance_blocked(v))
  1602. inbox_add(v);
  1603. }
  1604. }
  1605. xs_list *inbox_list(void)
  1606. /* returns the collected inboxes as a list */
  1607. {
  1608. xs_list *ibl = xs_list_new();
  1609. xs *spec = xs_fmt("%s/inbox/" "*", srv_basedir);
  1610. xs *files = xs_glob(spec, 0, 0);
  1611. xs_list *p = files;
  1612. xs_val *v;
  1613. while (xs_list_iter(&p, &v)) {
  1614. FILE *f;
  1615. if ((f = fopen(v, "r")) != NULL) {
  1616. xs *line = xs_readline(f);
  1617. if (line) {
  1618. line = xs_strip_i(line);
  1619. ibl = xs_list_append(ibl, line);
  1620. }
  1621. fclose(f);
  1622. }
  1623. }
  1624. return ibl;
  1625. }
  1626. /** instance-wide operations **/
  1627. xs_str *_instance_block_fn(const char *instance)
  1628. {
  1629. xs *s = xs_replace(instance, "http:/" "/", "");
  1630. xs *s1 = xs_replace(s, "https:/" "/", "");
  1631. xs *l = xs_split(s1, "/");
  1632. char *p = xs_list_get(l, 0);
  1633. xs *md5 = xs_md5_hex(p, strlen(p));
  1634. return xs_fmt("%s/block/%s", srv_basedir, md5);
  1635. }
  1636. int is_instance_blocked(const char *instance)
  1637. {
  1638. xs *fn = _instance_block_fn(instance);
  1639. return !!(mtime(fn) != 0.0);
  1640. }
  1641. int instance_block(const char *instance)
  1642. /* blocks a full instance */
  1643. {
  1644. int ret;
  1645. /* create the subdir */
  1646. xs *dir = xs_fmt("%s/block/", srv_basedir);
  1647. mkdirx(dir);
  1648. if (!is_instance_blocked(instance)) {
  1649. xs *fn = _instance_block_fn(instance);
  1650. FILE *f;
  1651. if ((f = fopen(fn, "w")) != NULL) {
  1652. fprintf(f, "%s\n", instance);
  1653. fclose(f);
  1654. ret = 0;
  1655. }
  1656. else
  1657. ret = -1;
  1658. }
  1659. else
  1660. ret = -2;
  1661. return ret;
  1662. }
  1663. int instance_unblock(const char *instance)
  1664. /* unblocks a full instance */
  1665. {
  1666. int ret;
  1667. if (is_instance_blocked(instance)) {
  1668. xs *fn = _instance_block_fn(instance);
  1669. ret = unlink(fn);
  1670. }
  1671. else
  1672. ret = -2;
  1673. return ret;
  1674. }
  1675. /** operations by content **/
  1676. int content_match(const char *file, const xs_dict *msg)
  1677. /* checks if a message's content matches any of the regexes in file */
  1678. /* file format: one regex per line */
  1679. {
  1680. xs *fn = xs_fmt("%s/%s", srv_basedir, file);
  1681. FILE *f;
  1682. int r = 0;
  1683. char *v = xs_dict_get(msg, "content");
  1684. if (xs_type(v) == XSTYPE_STRING && *v) {
  1685. if ((f = fopen(fn, "r")) != NULL) {
  1686. srv_debug(1, xs_fmt("content_match: loading regexes from %s", fn));
  1687. /* massage content (strip HTML tags, etc.) */
  1688. xs *c = xs_regex_replace(v, "<[^>]+>", " ");
  1689. c = xs_regex_replace_i(c, " {2,}", " ");
  1690. c = xs_tolower_i(c);
  1691. while (!r && !feof(f)) {
  1692. xs *rx = xs_strip_i(xs_readline(f));
  1693. if (*rx && xs_regex_match(c, rx)) {
  1694. srv_debug(1, xs_fmt("content_match: match for '%s'", rx));
  1695. r = 1;
  1696. }
  1697. }
  1698. fclose(f);
  1699. }
  1700. }
  1701. return r;
  1702. }
  1703. xs_list *content_search(snac *user, const char *regex,
  1704. int priv, int skip, int show, int max_secs, int *timeout)
  1705. /* returns a list of posts which content matches the regex */
  1706. {
  1707. if (regex == NULL || *regex == '\0')
  1708. return xs_list_new();
  1709. xs *i_regex = xs_tolower_i(xs_dup(regex));
  1710. xs_set seen;
  1711. xs_set_init(&seen);
  1712. if (max_secs == 0)
  1713. max_secs = 3;
  1714. time_t t = time(NULL) + max_secs;
  1715. *timeout = 0;
  1716. /* iterate all timelines simultaneously */
  1717. xs_list *tls[3] = {0};
  1718. char *md5s[3] = {0};
  1719. int c[3] = {0};
  1720. tls[0] = timeline_simple_list(user, "public", 0, XS_ALL); /* public */
  1721. tls[1] = timeline_instance_list(0, XS_ALL); /* instance */
  1722. tls[2] = priv ? timeline_simple_list(user, "private", 0, XS_ALL) : xs_list_new(); /* private or none */
  1723. /* first positioning */
  1724. for (int n = 0; n < 3; n++)
  1725. xs_list_next(tls[n], &md5s[n], &c[n]);
  1726. show += skip;
  1727. while (show > 0) {
  1728. /* timeout? */
  1729. if (time(NULL) > t) {
  1730. *timeout = 1;
  1731. break;
  1732. }
  1733. /* find the newest post */
  1734. int newest = -1;
  1735. double mtime = 0.0;
  1736. for (int n = 0; n < 3; n++) {
  1737. if (md5s[n] != NULL) {
  1738. xs *fn = _object_fn_by_md5(md5s[n], "content_search");
  1739. double mt = mtime(fn);
  1740. if (mt > mtime) {
  1741. newest = n;
  1742. mtime = mt;
  1743. }
  1744. }
  1745. }
  1746. if (newest == -1)
  1747. break;
  1748. char *md5 = md5s[newest];
  1749. /* advance the chosen timeline */
  1750. if (!xs_list_next(tls[newest], &md5s[newest], &c[newest]))
  1751. md5s[newest] = NULL;
  1752. xs *post = NULL;
  1753. if (!valid_status(object_get_by_md5(md5, &post)))
  1754. continue;
  1755. if (!xs_match(xs_dict_get_def(post, "type", "-"), POSTLIKE_OBJECT_TYPE))
  1756. continue;
  1757. const char *id = xs_dict_get(post, "id");
  1758. if (id == NULL || is_hidden(user, id))
  1759. continue;
  1760. char *content = xs_dict_get(post, "content");
  1761. if (xs_is_null(content))
  1762. continue;
  1763. /* strip HTML */
  1764. xs *c = xs_regex_replace(content, "<[^>]+>", " ");
  1765. c = xs_regex_replace_i(c, " {2,}", " ");
  1766. c = xs_tolower_i(c);
  1767. /* apply regex */
  1768. if (xs_regex_match(c, i_regex)) {
  1769. if (xs_set_add(&seen, md5) == 1)
  1770. show--;
  1771. }
  1772. }
  1773. xs_list *r = xs_set_result(&seen);
  1774. if (skip) {
  1775. /* BAD */
  1776. while (skip--) {
  1777. r = xs_list_del(r, 0);
  1778. }
  1779. }
  1780. xs_free(tls[0]);
  1781. xs_free(tls[1]);
  1782. xs_free(tls[2]);
  1783. return r;
  1784. }
  1785. /** notifications **/
  1786. xs_str *notify_check_time(snac *snac, int reset)
  1787. /* gets or resets the latest notification check time */
  1788. {
  1789. xs_str *t = NULL;
  1790. xs *fn = xs_fmt("%s/notifydate.txt", snac->basedir);
  1791. FILE *f;
  1792. if (reset) {
  1793. if ((f = fopen(fn, "w")) != NULL) {
  1794. t = tid(0);
  1795. fprintf(f, "%s\n", t);
  1796. fclose(f);
  1797. }
  1798. }
  1799. else {
  1800. if ((f = fopen(fn, "r")) != NULL) {
  1801. t = xs_readline(f);
  1802. fclose(f);
  1803. }
  1804. else
  1805. /* never set before */
  1806. t = xs_fmt("%16.6f", 0.0);
  1807. }
  1808. return t;
  1809. }
  1810. void notify_add(snac *snac, const char *type, const char *utype,
  1811. const char *actor, const char *objid)
  1812. /* adds a new notification */
  1813. {
  1814. xs *ntid = tid(0);
  1815. xs *fn = xs_fmt("%s/notify/", snac->basedir);
  1816. xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
  1817. FILE *f;
  1818. /* create the directory */
  1819. mkdirx(fn);
  1820. fn = xs_str_cat(fn, ntid);
  1821. fn = xs_str_cat(fn, ".json");
  1822. xs *noti = xs_dict_new();
  1823. noti = xs_dict_append(noti, "id", ntid);
  1824. noti = xs_dict_append(noti, "type", type);
  1825. noti = xs_dict_append(noti, "utype", utype);
  1826. noti = xs_dict_append(noti, "actor", actor);
  1827. noti = xs_dict_append(noti, "date", date);
  1828. if (!xs_is_null(objid))
  1829. noti = xs_dict_append(noti, "objid", objid);
  1830. if ((f = fopen(fn, "w")) != NULL) {
  1831. xs_json_dump(noti, 4, f);
  1832. fclose(f);
  1833. }
  1834. /* add it to the index if it already exists */
  1835. xs *idx = xs_fmt("%s/notify.idx", snac->basedir);
  1836. if (mtime(idx) != 0.0) {
  1837. pthread_mutex_lock(&data_mutex);
  1838. if ((f = fopen(idx, "a")) != NULL) {
  1839. fprintf(f, "%-32s\n", ntid);
  1840. fclose(f);
  1841. }
  1842. pthread_mutex_unlock(&data_mutex);
  1843. }
  1844. }
  1845. xs_dict *notify_get(snac *snac, const char *id)
  1846. /* gets a notification */
  1847. {
  1848. /* base file */
  1849. xs *fn = xs_fmt("%s/notify/%s", snac->basedir, id);
  1850. /* strip spaces and add extension */
  1851. fn = xs_strip_i(fn);
  1852. fn = xs_str_cat(fn, ".json");
  1853. FILE *f;
  1854. xs_dict *out = NULL;
  1855. if ((f = fopen(fn, "r")) != NULL) {
  1856. out = xs_json_load(f);
  1857. fclose(f);
  1858. }
  1859. return out;
  1860. }
  1861. xs_list *notify_list(snac *snac, int skip, int show)
  1862. /* returns a list of notification ids */
  1863. {
  1864. xs *idx = xs_fmt("%s/notify.idx", snac->basedir);
  1865. if (mtime(idx) == 0.0) {
  1866. /* create the index from scratch */
  1867. FILE *f;
  1868. pthread_mutex_lock(&data_mutex);
  1869. if ((f = fopen(idx, "w")) != NULL) {
  1870. xs *spec = xs_fmt("%s/notify/" "*.json", snac->basedir);
  1871. xs *lst = xs_glob(spec, 1, 0);
  1872. xs_list *p = lst;
  1873. char *v;
  1874. while (xs_list_iter(&p, &v)) {
  1875. char *p = strrchr(v, '.');
  1876. if (p) {
  1877. *p = '\0';
  1878. fprintf(f, "%-32s\n", v);
  1879. }
  1880. }
  1881. fclose(f);
  1882. }
  1883. pthread_mutex_unlock(&data_mutex);
  1884. }
  1885. return index_list_desc(idx, skip, show);
  1886. }
  1887. int notify_new_num(snac *snac)
  1888. /* counts the number of new notifications */
  1889. {
  1890. xs *t = notify_check_time(snac, 0);
  1891. xs *lst = notify_list(snac, 0, XS_ALL);
  1892. int cnt = 0;
  1893. xs_list *p = lst;
  1894. xs_str *v;
  1895. while (xs_list_iter(&p, &v)) {
  1896. xs *id = xs_strip_i(xs_dup(v));
  1897. /* old? count no more */
  1898. if (strcmp(id, t) < 0)
  1899. break;
  1900. cnt++;
  1901. }
  1902. return cnt;
  1903. }
  1904. void notify_clear(snac *snac)
  1905. /* clears all notifications */
  1906. {
  1907. xs *spec = xs_fmt("%s/notify/" "*", snac->basedir);
  1908. xs *lst = xs_glob(spec, 0, 0);
  1909. xs_list *p = lst;
  1910. xs_str *v;
  1911. while (xs_list_iter(&p, &v))
  1912. unlink(v);
  1913. xs *idx = xs_fmt("%s/notify.idx", snac->basedir);
  1914. if (mtime(idx) != 0.0) {
  1915. pthread_mutex_lock(&data_mutex);
  1916. truncate(idx, 0);
  1917. pthread_mutex_unlock(&data_mutex);
  1918. }
  1919. }
  1920. /** the queue **/
  1921. static xs_dict *_enqueue_put(const char *fn, xs_dict *msg)
  1922. /* writes safely to the queue */
  1923. {
  1924. xs *tfn = xs_fmt("%s.tmp", fn);
  1925. FILE *f;
  1926. if ((f = fopen(tfn, "w")) != NULL) {
  1927. xs_json_dump(msg, 4, f);
  1928. fclose(f);
  1929. rename(tfn, fn);
  1930. }
  1931. return msg;
  1932. }
  1933. static xs_dict *_new_qmsg(const char *type, const xs_val *msg, int retries)
  1934. /* creates a queue message */
  1935. {
  1936. int qrt = xs_number_get(xs_dict_get(srv_config, "queue_retry_minutes"));
  1937. xs *ntid = tid(retries * 60 * qrt);
  1938. xs *rn = xs_number_new(retries);
  1939. xs_dict *qmsg = xs_dict_new();
  1940. qmsg = xs_dict_append(qmsg, "type", type);
  1941. qmsg = xs_dict_append(qmsg, "message", msg);
  1942. qmsg = xs_dict_append(qmsg, "retries", rn);
  1943. qmsg = xs_dict_append(qmsg, "ntid", ntid);
  1944. return qmsg;
  1945. }
  1946. void enqueue_input(snac *snac, const xs_dict *msg, const xs_dict *req, int retries)
  1947. /* enqueues an input message */
  1948. {
  1949. xs *qmsg = _new_qmsg("input", msg, retries);
  1950. char *ntid = xs_dict_get(qmsg, "ntid");
  1951. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  1952. qmsg = xs_dict_append(qmsg, "req", req);
  1953. qmsg = _enqueue_put(fn, qmsg);
  1954. snac_debug(snac, 1, xs_fmt("enqueue_input %s", xs_dict_get(msg, "id")));
  1955. }
  1956. void enqueue_shared_input(const xs_dict *msg, const xs_dict *req, int retries)
  1957. /* enqueues an input message from the shared input */
  1958. {
  1959. xs *qmsg = _new_qmsg("input", msg, retries);
  1960. char *ntid = xs_dict_get(qmsg, "ntid");
  1961. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  1962. qmsg = xs_dict_append(qmsg, "req", req);
  1963. qmsg = _enqueue_put(fn, qmsg);
  1964. srv_debug(1, xs_fmt("enqueue_shared_input %s", xs_dict_get(msg, "id")));
  1965. }
  1966. void enqueue_output_raw(const char *keyid, const char *seckey,
  1967. xs_dict *msg, xs_str *inbox, int retries, int p_status)
  1968. /* enqueues an output message to an inbox */
  1969. {
  1970. xs *qmsg = _new_qmsg("output", msg, retries);
  1971. char *ntid = xs_dict_get(qmsg, "ntid");
  1972. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  1973. xs *ns = xs_number_new(p_status);
  1974. qmsg = xs_dict_append(qmsg, "p_status", ns);
  1975. qmsg = xs_dict_append(qmsg, "inbox", inbox);
  1976. qmsg = xs_dict_append(qmsg, "keyid", keyid);
  1977. qmsg = xs_dict_append(qmsg, "seckey", seckey);
  1978. /* if it's to be sent right now, bypass the disk queue and post the job */
  1979. if (retries == 0 && p_state != NULL)
  1980. job_post(qmsg, 0);
  1981. else {
  1982. qmsg = _enqueue_put(fn, qmsg);
  1983. srv_debug(1, xs_fmt("enqueue_output %s %s %d", inbox, fn, retries));
  1984. }
  1985. }
  1986. void enqueue_output(snac *snac, xs_dict *msg, xs_str *inbox, int retries, int p_status)
  1987. /* enqueues an output message to an inbox */
  1988. {
  1989. if (xs_startswith(inbox, snac->actor)) {
  1990. snac_debug(snac, 1, xs_str_new("refusing enqueue to myself"));
  1991. return;
  1992. }
  1993. char *seckey = xs_dict_get(snac->key, "secret");
  1994. enqueue_output_raw(snac->actor, seckey, msg, inbox, retries, p_status);
  1995. }
  1996. void enqueue_output_by_actor(snac *snac, xs_dict *msg, const xs_str *actor, int retries)
  1997. /* enqueues an output message for an actor */
  1998. {
  1999. xs *inbox = get_actor_inbox(actor);
  2000. if (!xs_is_null(inbox))
  2001. enqueue_output(snac, msg, inbox, retries, 0);
  2002. else
  2003. snac_log(snac, xs_fmt("enqueue_output_by_actor cannot get inbox %s", actor));
  2004. }
  2005. void enqueue_email(xs_str *msg, int retries)
  2006. /* enqueues an email message to be sent */
  2007. {
  2008. xs *qmsg = _new_qmsg("email", msg, retries);
  2009. char *ntid = xs_dict_get(qmsg, "ntid");
  2010. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  2011. qmsg = _enqueue_put(fn, qmsg);
  2012. srv_debug(1, xs_fmt("enqueue_email %d", retries));
  2013. }
  2014. void enqueue_telegram(const xs_str *msg, const char *bot, const char *chat_id)
  2015. /* enqueues a message to be sent via Telegram */
  2016. {
  2017. xs *qmsg = _new_qmsg("telegram", msg, 0);
  2018. char *ntid = xs_dict_get(qmsg, "ntid");
  2019. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  2020. qmsg = xs_dict_append(qmsg, "bot", bot);
  2021. qmsg = xs_dict_append(qmsg, "chat_id", chat_id);
  2022. qmsg = _enqueue_put(fn, qmsg);
  2023. srv_debug(1, xs_fmt("enqueue_telegram %s %s", bot, chat_id));
  2024. }
  2025. void enqueue_ntfy(const xs_str *msg, const char *ntfy_server, const char *ntfy_token)
  2026. /* enqueues a message to be sent via ntfy */
  2027. {
  2028. xs *qmsg = _new_qmsg("ntfy", msg, 0);
  2029. char *ntid = xs_dict_get(qmsg, "ntid");
  2030. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  2031. qmsg = xs_dict_append(qmsg, "ntfy_server", ntfy_server);
  2032. qmsg = xs_dict_append(qmsg, "ntfy_token", ntfy_token);
  2033. qmsg = _enqueue_put(fn, qmsg);
  2034. srv_debug(1, xs_fmt("enqueue_ntfy %s %s", ntfy_server, ntfy_token));
  2035. }
  2036. void enqueue_message(snac *snac, const xs_dict *msg)
  2037. /* enqueues an output message */
  2038. {
  2039. xs *qmsg = _new_qmsg("message", msg, 0);
  2040. char *ntid = xs_dict_get(qmsg, "ntid");
  2041. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  2042. qmsg = _enqueue_put(fn, qmsg);
  2043. snac_debug(snac, 0, xs_fmt("enqueue_message %s", xs_dict_get(msg, "id")));
  2044. }
  2045. void enqueue_close_question(snac *user, const char *id, int end_secs)
  2046. /* enqueues the closing of a question */
  2047. {
  2048. xs *qmsg = _new_qmsg("close_question", id, 0);
  2049. xs *ntid = tid(end_secs);
  2050. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2051. qmsg = xs_dict_set(qmsg, "ntid", ntid);
  2052. qmsg = _enqueue_put(fn, qmsg);
  2053. snac_debug(user, 0, xs_fmt("enqueue_close_question %s", id));
  2054. }
  2055. void enqueue_object_request(snac *user, const char *id, int forward_secs)
  2056. /* enqueues the request of an object in the future */
  2057. {
  2058. xs *qmsg = _new_qmsg("object_request", id, 0);
  2059. xs *ntid = tid(forward_secs);
  2060. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2061. qmsg = xs_dict_set(qmsg, "ntid", ntid);
  2062. qmsg = _enqueue_put(fn, qmsg);
  2063. snac_debug(user, 0, xs_fmt("enqueue_object_request %s %d", id, forward_secs));
  2064. }
  2065. void enqueue_verify_links(snac *user)
  2066. /* enqueues a link verification */
  2067. {
  2068. xs *qmsg = _new_qmsg("verify_links", "", 0);
  2069. char *ntid = xs_dict_get(qmsg, "ntid");
  2070. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2071. qmsg = _enqueue_put(fn, qmsg);
  2072. snac_debug(user, 1, xs_fmt("enqueue_verify_links %s", user->actor));
  2073. }
  2074. void enqueue_actor_refresh(snac *user, const char *actor, int forward_secs)
  2075. /* enqueues an actor refresh */
  2076. {
  2077. xs *qmsg = _new_qmsg("actor_refresh", "", 0);
  2078. xs *ntid = tid(forward_secs);
  2079. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2080. qmsg = xs_dict_set(qmsg, "ntid", ntid);
  2081. qmsg = xs_dict_append(qmsg, "actor", actor);
  2082. qmsg = _enqueue_put(fn, qmsg);
  2083. snac_debug(user, 1, xs_fmt("enqueue_actor_refresh %s", actor));
  2084. }
  2085. void enqueue_request_replies(snac *user, const char *id)
  2086. /* enqueues a request for the replies of a message */
  2087. {
  2088. /* test first if this precise request is already in the queue */
  2089. xs *queue = user_queue(user);
  2090. xs_list *p = queue;
  2091. xs_str *v;
  2092. while (xs_list_iter(&p, &v)) {
  2093. xs *q_item = queue_get(v);
  2094. if (q_item != NULL) {
  2095. const char *type = xs_dict_get(q_item, "type");
  2096. const char *msg = xs_dict_get(q_item, "message");
  2097. if (type && msg && strcmp(type, "request_replies") == 0 && strcmp(msg, id) == 0) {
  2098. /* don't requeue */
  2099. snac_debug(user, 1, xs_fmt("enqueue_request_replies already here %s", id));
  2100. return;
  2101. }
  2102. }
  2103. }
  2104. /* not there; enqueue the request with a small delay */
  2105. xs *qmsg = _new_qmsg("request_replies", id, 0);
  2106. xs *ntid = tid(10);
  2107. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2108. qmsg = xs_dict_set(qmsg, "ntid", ntid);
  2109. qmsg = _enqueue_put(fn, qmsg);
  2110. snac_debug(user, 2, xs_fmt("enqueue_request_replies %s", id));
  2111. }
  2112. int was_question_voted(snac *user, const char *id)
  2113. /* returns true if the user voted in this poll */
  2114. {
  2115. xs *children = object_children(id);
  2116. int voted = 0;
  2117. xs_list *p;
  2118. xs_str *md5;
  2119. p = children;
  2120. while (xs_list_iter(&p, &md5)) {
  2121. xs *obj = NULL;
  2122. if (valid_status(object_get_by_md5(md5, &obj))) {
  2123. char *atto = get_atto(obj);
  2124. if (atto && strcmp(atto, user->actor) == 0 &&
  2125. !xs_is_null(xs_dict_get(obj, "name"))) {
  2126. voted = 1;
  2127. break;
  2128. }
  2129. }
  2130. }
  2131. return voted;
  2132. }
  2133. xs_list *user_queue(snac *snac)
  2134. /* returns a list with filenames that can be dequeued */
  2135. {
  2136. xs *spec = xs_fmt("%s/queue/" "*.json", snac->basedir);
  2137. xs_list *list = xs_list_new();
  2138. time_t t = time(NULL);
  2139. xs_list *p;
  2140. xs_val *v;
  2141. xs *fns = xs_glob(spec, 0, 0);
  2142. p = fns;
  2143. while (xs_list_iter(&p, &v)) {
  2144. /* get the retry time from the basename */
  2145. char *bn = strrchr(v, '/');
  2146. time_t t2 = atol(bn + 1);
  2147. if (t2 > t)
  2148. snac_debug(snac, 2, xs_fmt("user_queue not yet time for %s [%ld]", v, t));
  2149. else {
  2150. list = xs_list_append(list, v);
  2151. snac_debug(snac, 2, xs_fmt("user_queue ready for %s", v));
  2152. }
  2153. }
  2154. return list;
  2155. }
  2156. xs_list *queue(void)
  2157. /* returns a list with filenames that can be dequeued */
  2158. {
  2159. xs *spec = xs_fmt("%s/queue/" "*.json", srv_basedir);
  2160. xs_list *list = xs_list_new();
  2161. time_t t = time(NULL);
  2162. xs_list *p;
  2163. xs_val *v;
  2164. xs *fns = xs_glob(spec, 0, 0);
  2165. p = fns;
  2166. while (xs_list_iter(&p, &v)) {
  2167. /* get the retry time from the basename */
  2168. char *bn = strrchr(v, '/');
  2169. time_t t2 = atol(bn + 1);
  2170. if (t2 > t)
  2171. srv_debug(2, xs_fmt("queue not yet time for %s [%ld]", v, t));
  2172. else {
  2173. list = xs_list_append(list, v);
  2174. srv_debug(2, xs_fmt("queue ready for %s", v));
  2175. }
  2176. }
  2177. return list;
  2178. }
  2179. xs_dict *queue_get(const char *fn)
  2180. /* gets a file from a queue */
  2181. {
  2182. FILE *f;
  2183. xs_dict *obj = NULL;
  2184. if ((f = fopen(fn, "r")) != NULL) {
  2185. obj = xs_json_load(f);
  2186. fclose(f);
  2187. }
  2188. return obj;
  2189. }
  2190. xs_dict *dequeue(const char *fn)
  2191. /* dequeues a message */
  2192. {
  2193. xs_dict *obj = queue_get(fn);
  2194. unlink(fn);
  2195. return obj;
  2196. }
  2197. /** the purge **/
  2198. static int _purge_file(const char *fn, time_t mt)
  2199. /* purge fn if it's older than days */
  2200. {
  2201. int ret = 0;
  2202. if (mtime(fn) < mt) {
  2203. /* older than the minimum time: delete it */
  2204. unlink(fn);
  2205. srv_debug(2, xs_fmt("purged %s", fn));
  2206. ret = 1;
  2207. }
  2208. return ret;
  2209. }
  2210. static void _purge_dir(const char *dir, int days)
  2211. /* purges all files in a directory older than days */
  2212. {
  2213. int cnt = 0;
  2214. if (days) {
  2215. time_t mt = time(NULL) - days * 24 * 3600;
  2216. xs *spec = xs_fmt("%s/" "*", dir);
  2217. xs *list = xs_glob(spec, 0, 0);
  2218. xs_list *p;
  2219. xs_str *v;
  2220. p = list;
  2221. while (xs_list_iter(&p, &v))
  2222. cnt += _purge_file(v, mt);
  2223. srv_debug(1, xs_fmt("purge: %s %d", dir, cnt));
  2224. }
  2225. }
  2226. static void _purge_user_subdir(snac *snac, const char *subdir, int days)
  2227. /* purges all files in a user subdir older than days */
  2228. {
  2229. xs *u_subdir = xs_fmt("%s/%s", snac->basedir, subdir);
  2230. _purge_dir(u_subdir, days);
  2231. }
  2232. void purge_server(void)
  2233. /* purge global server data */
  2234. {
  2235. xs *spec = xs_fmt("%s/object/??", srv_basedir);
  2236. xs *dirs = xs_glob(spec, 0, 0);
  2237. xs_list *p;
  2238. xs_str *v;
  2239. int cnt = 0;
  2240. int icnt = 0;
  2241. time_t mt = time(NULL) - 7 * 24 * 3600;
  2242. p = dirs;
  2243. while (xs_list_iter(&p, &v)) {
  2244. xs_list *p2;
  2245. xs_str *v2;
  2246. {
  2247. xs *spec2 = xs_fmt("%s/" "*.json", v);
  2248. xs *files = xs_glob(spec2, 0, 0);
  2249. p2 = files;
  2250. while (xs_list_iter(&p2, &v2)) {
  2251. int n_link;
  2252. /* old and with no hard links? */
  2253. if (mtime_nl(v2, &n_link) < mt && n_link < 2) {
  2254. xs *s1 = xs_replace(v2, ".json", "");
  2255. xs *l = xs_split(s1, "/");
  2256. char *md5 = xs_list_get(l, -1);
  2257. object_del_by_md5(md5);
  2258. cnt++;
  2259. }
  2260. }
  2261. }
  2262. {
  2263. /* look for stray indexes */
  2264. xs *speci = xs_fmt("%s/" "*_?.idx", v);
  2265. xs *idxfs = xs_glob(speci, 0, 0);
  2266. p2 = idxfs;
  2267. while (xs_list_iter(&p2, &v2)) {
  2268. /* old enough to consider? */
  2269. if (mtime(v2) < mt) {
  2270. /* check if the indexed object is here */
  2271. xs *o = xs_dup(v2);
  2272. char *ext = strchr(o, '_');
  2273. if (ext) {
  2274. *ext = '\0';
  2275. o = xs_str_cat(o, ".json");
  2276. if (mtime(o) == 0.0) {
  2277. /* delete */
  2278. unlink(v2);
  2279. srv_debug(1, xs_fmt("purged %s", v2));
  2280. icnt++;
  2281. }
  2282. }
  2283. }
  2284. }
  2285. /* delete index backups */
  2286. xs *specb = xs_fmt("%s/" "*.bak", v);
  2287. xs *bakfs = xs_glob(specb, 0, 0);
  2288. p2 = bakfs;
  2289. while (xs_list_iter(&p2, &v2)) {
  2290. unlink(v2);
  2291. srv_debug(1, xs_fmt("purged %s", v2));
  2292. }
  2293. }
  2294. }
  2295. /* purge collected inboxes */
  2296. xs *ib_dir = xs_fmt("%s/inbox", srv_basedir);
  2297. _purge_dir(ib_dir, 7);
  2298. /* purge the instance timeline */
  2299. xs *itl_fn = xs_fmt("%s/public.idx", srv_basedir);
  2300. int itl_gc = index_gc(itl_fn);
  2301. /* purge tag indexes */
  2302. xs *tag_spec = xs_fmt("%s/tag/??", srv_basedir);
  2303. xs *tag_dirs = xs_glob(tag_spec, 0, 0);
  2304. p = tag_dirs;
  2305. int tag_gc = 0;
  2306. while (xs_list_iter(&p, &v)) {
  2307. xs *spec2 = xs_fmt("%s/" "*.idx", v);
  2308. xs *files = xs_glob(spec2, 0, 0);
  2309. xs_list *p2;
  2310. xs_str *v2;
  2311. p2 = files;
  2312. while (xs_list_iter(&p2, &v2)) {
  2313. tag_gc += index_gc(v2);
  2314. xs *bak = xs_fmt("%s.bak", v2);
  2315. unlink(bak);
  2316. if (index_len(v2) == 0) {
  2317. /* there are no longer any entry with this tag;
  2318. purge it completely */
  2319. unlink(v2);
  2320. xs *dottag = xs_replace(v2, ".idx", ".tag");
  2321. unlink(dottag);
  2322. }
  2323. }
  2324. }
  2325. srv_debug(1, xs_fmt("purge: global "
  2326. "(obj: %d, idx: %d, itl: %d, tag: %d)", cnt, icnt, itl_gc, tag_gc));
  2327. }
  2328. void purge_user(snac *snac)
  2329. /* do the purge for this user */
  2330. {
  2331. int priv_days, pub_days, user_days = 0;
  2332. char *v;
  2333. int n;
  2334. priv_days = xs_number_get(xs_dict_get(srv_config, "timeline_purge_days"));
  2335. pub_days = xs_number_get(xs_dict_get(srv_config, "local_purge_days"));
  2336. if ((v = xs_dict_get(snac->config_o, "purge_days")) != NULL ||
  2337. (v = xs_dict_get(snac->config, "purge_days")) != NULL)
  2338. user_days = xs_number_get(v);
  2339. if (user_days) {
  2340. /* override admin settings only if they are lesser */
  2341. if (priv_days == 0 || user_days < priv_days)
  2342. priv_days = user_days;
  2343. if (pub_days == 0 || user_days < pub_days)
  2344. pub_days = user_days;
  2345. }
  2346. _purge_user_subdir(snac, "hidden", priv_days);
  2347. _purge_user_subdir(snac, "private", priv_days);
  2348. _purge_user_subdir(snac, "public", pub_days);
  2349. const char *idxs[] = { "followers.idx", "private.idx", "public.idx", "pinned.idx", NULL };
  2350. for (n = 0; idxs[n]; n++) {
  2351. xs *idx = xs_fmt("%s/%s", snac->basedir, idxs[n]);
  2352. int gc = index_gc(idx);
  2353. srv_debug(1, xs_fmt("purge: %s %d", idx, gc));
  2354. }
  2355. /* purge lists */
  2356. {
  2357. xs *spec = xs_fmt("%s/list/" "*.idx", snac->basedir);
  2358. xs *lol = xs_glob(spec, 0, 0);
  2359. int c = 0;
  2360. char *v;
  2361. while (xs_list_next(lol, &v, &c)) {
  2362. int gc = index_gc(v);
  2363. srv_debug(1, xs_fmt("purge: %s %d", v, gc));
  2364. }
  2365. }
  2366. /* unrelated to purging, but it's a janitorial process, so what the hell */
  2367. verify_links(snac);
  2368. }
  2369. void purge_all(void)
  2370. /* purge all users */
  2371. {
  2372. snac snac;
  2373. xs *list = user_list();
  2374. char *p, *uid;
  2375. p = list;
  2376. while (xs_list_iter(&p, &uid)) {
  2377. if (user_open(&snac, uid)) {
  2378. purge_user(&snac);
  2379. user_free(&snac);
  2380. }
  2381. }
  2382. purge_server();
  2383. #ifndef NO_MASTODON_API
  2384. mastoapi_purge();
  2385. #endif
  2386. }
  2387. /** archive **/
  2388. void srv_archive(const char *direction, const char *url, xs_dict *req,
  2389. const char *payload, int p_size,
  2390. int status, xs_dict *headers,
  2391. const char *body, int b_size)
  2392. /* archives a connection */
  2393. {
  2394. /* obsessive archiving */
  2395. xs *date = tid(0);
  2396. xs *dir = xs_fmt("%s/archive/%s_%s", srv_basedir, date, direction);
  2397. FILE *f;
  2398. if (mkdirx(dir) != -1) {
  2399. xs *meta_fn = xs_fmt("%s/_META", dir);
  2400. if ((f = fopen(meta_fn, "w")) != NULL) {
  2401. xs *j1 = xs_json_dumps(req, 4);
  2402. xs *j2 = xs_json_dumps(headers, 4);
  2403. fprintf(f, "dir: %s\n", direction);
  2404. if (url)
  2405. fprintf(f, "url: %s\n", url);
  2406. fprintf(f, "req: %s\n", j1);
  2407. fprintf(f, "p_size: %d\n", p_size);
  2408. fprintf(f, "status: %d\n", status);
  2409. fprintf(f, "response: %s\n", j2);
  2410. fprintf(f, "b_size: %d\n", b_size);
  2411. fclose(f);
  2412. }
  2413. if (p_size && payload) {
  2414. xs *payload_fn = NULL;
  2415. xs *payload_fn_raw = NULL;
  2416. char *v = xs_dict_get(req, "content-type");
  2417. if (v && xs_str_in(v, "json") != -1) {
  2418. payload_fn = xs_fmt("%s/payload.json", dir);
  2419. if ((f = fopen(payload_fn, "w")) != NULL) {
  2420. xs *v1 = xs_json_loads(payload);
  2421. xs *j1 = NULL;
  2422. if (v1 != NULL)
  2423. j1 = xs_json_dumps(v1, 4);
  2424. if (j1 != NULL)
  2425. fwrite(j1, strlen(j1), 1, f);
  2426. else
  2427. fwrite(payload, p_size, 1, f);
  2428. fclose(f);
  2429. }
  2430. }
  2431. payload_fn_raw = xs_fmt("%s/payload", dir);
  2432. if ((f = fopen(payload_fn_raw, "w")) != NULL) {
  2433. fwrite(payload, p_size, 1, f);
  2434. fclose(f);
  2435. }
  2436. }
  2437. if (b_size && body) {
  2438. xs *body_fn = NULL;
  2439. char *v = xs_dict_get(headers, "content-type");
  2440. if (v && xs_str_in(v, "json") != -1) {
  2441. body_fn = xs_fmt("%s/body.json", dir);
  2442. if ((f = fopen(body_fn, "w")) != NULL) {
  2443. xs *v1 = xs_json_loads(body);
  2444. xs *j1 = NULL;
  2445. if (v1 != NULL)
  2446. j1 = xs_json_dumps(v1, 4);
  2447. if (j1 != NULL)
  2448. fwrite(j1, strlen(j1), 1, f);
  2449. else
  2450. fwrite(body, b_size, 1, f);
  2451. fclose(f);
  2452. }
  2453. }
  2454. else {
  2455. body_fn = xs_fmt("%s/body", dir);
  2456. if ((f = fopen(body_fn, "w")) != NULL) {
  2457. fwrite(body, b_size, 1, f);
  2458. fclose(f);
  2459. }
  2460. }
  2461. }
  2462. }
  2463. }
  2464. void srv_archive_error(const char *prefix, const xs_str *err,
  2465. const xs_dict *req, const xs_val *data)
  2466. /* archives an error */
  2467. {
  2468. xs *ntid = tid(0);
  2469. xs *fn = xs_fmt("%s/error/%s_%s", srv_basedir, ntid, prefix);
  2470. FILE *f;
  2471. if ((f = fopen(fn, "w")) != NULL) {
  2472. fprintf(f, "Error: %s\n", err);
  2473. if (req) {
  2474. fprintf(f, "Request headers:\n");
  2475. xs_json_dump(req, 4, f);
  2476. fprintf(f, "\n");
  2477. }
  2478. if (data) {
  2479. fprintf(f, "Data:\n");
  2480. if (xs_type(data) == XSTYPE_LIST || xs_type(data) == XSTYPE_DICT) {
  2481. xs_json_dump(data, 4, f);
  2482. }
  2483. else
  2484. fprintf(f, "%s", data);
  2485. fprintf(f, "\n");
  2486. }
  2487. fclose(f);
  2488. }
  2489. }
  2490. void srv_archive_qitem(char *prefix, xs_dict *q_item)
  2491. /* archives a q_item in the error folder */
  2492. {
  2493. xs *ntid = tid(0);
  2494. xs *fn = xs_fmt("%s/error/%s_qitem_%s", srv_basedir, ntid, prefix);
  2495. FILE *f;
  2496. if ((f = fopen(fn, "w")) != NULL) {
  2497. xs_json_dump(q_item, 4, f);
  2498. fclose(f);
  2499. }
  2500. }