data.c 114 KB

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