1
0

data.c 121 KB

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