data.c 117 KB

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