data.c 95 KB

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