data.c 123 KB

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