data.c 114 KB

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