1
0

data.c 112 KB

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