data.c 111 KB

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