1
0

data.c 120 KB

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