data.c 118 KB

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