data.c 123 KB

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