data.c 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894
  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 */
  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. /* use utf <3 as a like, as it is ugly */
  1195. if (type && xs_match(type, "Like|EmojiReact|Emoji") &&
  1196. content && strcmp(content, "❤") != 0) {
  1197. ret = timeline_emoji_react(snac->actor, id, msg);
  1198. snac_debug(snac, 1, xs_fmt("timeline_emoji_react %s", id));
  1199. }
  1200. else {
  1201. ret = object_admire(id, admirer, like);
  1202. snac_debug(snac, 1, xs_fmt("timeline_admire (%s) %s %s",
  1203. like ? "Like" : "Announce", id, admirer));
  1204. }
  1205. return ret;
  1206. }
  1207. xs_list *timeline_top_level(snac *snac, const xs_list *list)
  1208. /* returns the top level md5 entries from this index */
  1209. {
  1210. xs_set seen;
  1211. const xs_str *v;
  1212. xs_set_init(&seen);
  1213. int c = 0;
  1214. while (xs_list_next(list, &v, &c)) {
  1215. char line[MD5_HEX_SIZE] = "";
  1216. strncpy(line, v, sizeof(line));
  1217. for (;;) {
  1218. char line2[MD5_HEX_SIZE];
  1219. /* if it doesn't have a parent, use this */
  1220. if (!object_parent(line, line2))
  1221. break;
  1222. /* well, there is a parent... but is it here? */
  1223. if (!timeline_here_by_md5(snac, line2))
  1224. break;
  1225. /* it's here! try again with its own parent */
  1226. strncpy(line, line2, sizeof(line));
  1227. }
  1228. xs_set_add(&seen, line);
  1229. }
  1230. return xs_set_result(&seen);
  1231. }
  1232. xs_str *user_index_fn(snac *user, const char *idx_name)
  1233. /* returns the filename of a user index */
  1234. {
  1235. return xs_fmt("%s/%s.idx", user->basedir, idx_name);
  1236. }
  1237. xs_list *timeline_simple_list(snac *user, const char *idx_name, int skip, int show, int *more)
  1238. /* returns a timeline (with all entries) */
  1239. {
  1240. xs *idx = user_index_fn(user, idx_name);
  1241. /* if a more flag is sent, request one more */
  1242. xs_list *lst = index_list_desc(idx, skip, show + (more != NULL ? 1 : 0));
  1243. if (more != NULL) {
  1244. if (xs_list_len(lst) > show) {
  1245. *more = 1;
  1246. lst = xs_list_del(lst, -1);
  1247. }
  1248. else
  1249. *more = 0;
  1250. }
  1251. return lst;
  1252. }
  1253. xs_list *timeline_list(snac *snac, const char *idx_name, int skip, int show, int *more)
  1254. /* returns a timeline (only top level entries) */
  1255. {
  1256. int c_max;
  1257. /* maximum number of items in the timeline */
  1258. c_max = xs_number_get(xs_dict_get(srv_config, "max_timeline_entries"));
  1259. /* never more timeline entries than the configured maximum */
  1260. if (show > c_max)
  1261. show = c_max;
  1262. xs *list = timeline_simple_list(snac, idx_name, skip, show, more);
  1263. return timeline_top_level(snac, list);
  1264. }
  1265. void timeline_add_mark(snac *user)
  1266. /* adds an "already seen" mark to the private timeline */
  1267. {
  1268. xs *fn = xs_fmt("%s/private.idx", user->basedir);
  1269. char last_entry[MD5_HEX_SIZE] = "";
  1270. FILE *f;
  1271. /* get the last entry in the index */
  1272. if ((f = fopen(fn, "r")) != NULL) {
  1273. index_desc_first(f, last_entry, 0);
  1274. fclose(f);
  1275. }
  1276. /* is the last entry *not* a mark? */
  1277. if (strcmp(last_entry, MD5_ALREADY_SEEN_MARK) != 0) {
  1278. /* add it */
  1279. index_add_md5(fn, MD5_ALREADY_SEEN_MARK);
  1280. }
  1281. }
  1282. xs_str *instance_index_fn(void)
  1283. {
  1284. return xs_fmt("%s/public.idx", srv_basedir);
  1285. }
  1286. xs_list *timeline_instance_list(int skip, int show)
  1287. /* returns the timeline for the full instance */
  1288. {
  1289. xs *idx = instance_index_fn();
  1290. xs *lst = index_list_desc(idx, skip, show);
  1291. /* make the list unique */
  1292. xs_set rep;
  1293. xs_set_init(&rep);
  1294. const char *md5;
  1295. xs_list_foreach(lst, md5)
  1296. xs_set_add(&rep, md5);
  1297. return xs_set_result(&rep);
  1298. }
  1299. /** following **/
  1300. /* this needs special treatment and cannot use the object db as is,
  1301. with a link to a cached author, because we need the Follow object
  1302. in case we need to unfollow (Undo + original Follow) */
  1303. xs_str *_following_fn(snac *snac, const char *actor)
  1304. {
  1305. xs *md5 = xs_md5_hex(actor, strlen(actor));
  1306. return xs_fmt("%s/following/%s.json", snac->basedir, md5);
  1307. }
  1308. int following_add(snac *snac, const char *actor, const xs_dict *msg)
  1309. /* adds to the following list */
  1310. {
  1311. int ret = HTTP_STATUS_CREATED;
  1312. xs *fn = _following_fn(snac, actor);
  1313. FILE *f;
  1314. xs *p_object = NULL;
  1315. if (valid_status(following_get(snac, actor, &p_object))) {
  1316. /* object already exists; if it's of type Accept,
  1317. the actor is already being followed and confirmed,
  1318. so do nothing */
  1319. const char *type = xs_dict_get(p_object, "type");
  1320. if (!xs_is_null(type) && strcmp(type, "Accept") == 0) {
  1321. snac_debug(snac, 1, xs_fmt("following_add actor already confirmed %s", actor));
  1322. return HTTP_STATUS_OK;
  1323. }
  1324. }
  1325. if ((f = fopen(fn, "w")) != NULL) {
  1326. xs_json_dump(msg, 4, f);
  1327. fclose(f);
  1328. /* get the filename of the actor object */
  1329. xs *actor_fn = _object_fn(actor);
  1330. /* increase its reference count */
  1331. fn = xs_replace_i(fn, ".json", "_a.json");
  1332. link(actor_fn, fn);
  1333. }
  1334. else
  1335. ret = HTTP_STATUS_INTERNAL_SERVER_ERROR;
  1336. snac_debug(snac, 2, xs_fmt("following_add %s %s", actor, fn));
  1337. return ret;
  1338. }
  1339. int following_del(snac *snac, const char *actor)
  1340. /* we're not following this actor any longer */
  1341. {
  1342. xs *fn = _following_fn(snac, actor);
  1343. snac_debug(snac, 2, xs_fmt("following_del %s %s", actor, fn));
  1344. unlink(fn);
  1345. /* also delete the reference to the author */
  1346. fn = xs_replace_i(fn, ".json", "_a.json");
  1347. unlink(fn);
  1348. return HTTP_STATUS_OK;
  1349. }
  1350. int following_check(snac *snac, const char *actor)
  1351. /* checks if we are following this actor */
  1352. {
  1353. xs *fn = _following_fn(snac, actor);
  1354. return !!(mtime(fn) != 0.0);
  1355. }
  1356. int following_get(snac *snac, const char *actor, xs_dict **data)
  1357. /* returns the 'Follow' object */
  1358. {
  1359. xs *fn = _following_fn(snac, actor);
  1360. FILE *f;
  1361. int status = HTTP_STATUS_OK;
  1362. if ((f = fopen(fn, "r")) != NULL) {
  1363. *data = xs_json_load(f);
  1364. fclose(f);
  1365. }
  1366. else
  1367. status = HTTP_STATUS_NOT_FOUND;
  1368. return status;
  1369. }
  1370. int following_list_len(snac *snac)
  1371. /* returns number of people being followed */
  1372. {
  1373. xs *spec = xs_fmt("%s/following/" "*_a.json", snac->basedir);
  1374. xs *glist = xs_glob(spec, 0, 0);
  1375. return xs_list_len(glist);
  1376. }
  1377. xs_list *following_list(snac *snac)
  1378. /* returns the list of people being followed */
  1379. {
  1380. xs *spec = xs_fmt("%s/following/" "*.json", snac->basedir);
  1381. xs *glist = xs_glob(spec, 0, 0);
  1382. xs_list *p;
  1383. const xs_str *v;
  1384. xs_list *list = xs_list_new();
  1385. /* iterate the list of files */
  1386. p = glist;
  1387. while (xs_list_iter(&p, &v)) {
  1388. FILE *f;
  1389. /* load the follower data */
  1390. if ((f = fopen(v, "r")) != NULL) {
  1391. xs *o = xs_json_load(f);
  1392. fclose(f);
  1393. if (o != NULL) {
  1394. const char *type = xs_dict_get(o, "type");
  1395. if (!xs_is_null(type) && strcmp(type, "Accept") == 0) {
  1396. const char *actor = xs_dict_get(o, "actor");
  1397. if (!xs_is_null(actor)) {
  1398. list = xs_list_append(list, actor);
  1399. /* check if there is a link to the actor object */
  1400. xs *v2 = xs_replace(v, ".json", "_a.json");
  1401. if (mtime(v2) == 0.0) {
  1402. /* no; add a link to it */
  1403. xs *actor_fn = _object_fn(actor);
  1404. link(actor_fn, v2);
  1405. }
  1406. }
  1407. }
  1408. }
  1409. }
  1410. }
  1411. return list;
  1412. }
  1413. xs_str *_muted_fn(snac *snac, const char *actor)
  1414. {
  1415. xs *md5 = xs_md5_hex(actor, strlen(actor));
  1416. return xs_fmt("%s/muted/%s", snac->basedir, md5);
  1417. }
  1418. void mute(snac *snac, const char *actor)
  1419. /* mutes a moron */
  1420. {
  1421. xs *fn = _muted_fn(snac, actor);
  1422. FILE *f;
  1423. if ((f = fopen(fn, "w")) != NULL) {
  1424. fprintf(f, "%s\n", actor);
  1425. fclose(f);
  1426. snac_debug(snac, 2, xs_fmt("muted %s %s", actor, fn));
  1427. }
  1428. }
  1429. void unmute(snac *snac, const char *actor)
  1430. /* actor is no longer a moron */
  1431. {
  1432. xs *fn = _muted_fn(snac, actor);
  1433. unlink(fn);
  1434. snac_debug(snac, 2, xs_fmt("unmuted %s %s", actor, fn));
  1435. }
  1436. int is_muted(snac *snac, const char *actor)
  1437. /* check if someone is muted */
  1438. {
  1439. xs *fn = _muted_fn(snac, actor);
  1440. return !!(mtime(fn) != 0.0);
  1441. }
  1442. xs_list *muted_list(snac *user)
  1443. /* returns the list (actor URLs) of the muted morons */
  1444. {
  1445. xs_list *l = xs_list_new();
  1446. xs *spec = xs_fmt("%s/muted/" "*", user->basedir);
  1447. xs *files = xs_glob(spec, 0, 0);
  1448. const char *fn;
  1449. xs_list_foreach(files, fn) {
  1450. FILE *f;
  1451. if ((f = fopen(fn, "r")) != NULL) {
  1452. xs *actor = xs_strip_i(xs_readline(f));
  1453. fclose(f);
  1454. l = xs_list_append(l, actor);
  1455. }
  1456. }
  1457. return l;
  1458. }
  1459. /** emojis react **/
  1460. xs_str *emoji_reacted(snac *user, const char *id)
  1461. /* returns the emoji an user reacted to a message */
  1462. {
  1463. xs *emojis = object_get_emoji_reacts(id);
  1464. int c = 0;
  1465. const char *v;
  1466. while (xs_list_next(emojis, &v, &c)) {
  1467. xs *msg = NULL;
  1468. if (object_get_by_md5(v, &msg)) {
  1469. const xs_val *act = xs_dict_get(msg, "actor");
  1470. if (act && strcmp(act, user->actor) == 0)
  1471. return xs_dup(xs_dict_get(msg, "content"));
  1472. }
  1473. }
  1474. return NULL;
  1475. }
  1476. /** bookmarking **/
  1477. int is_bookmarked(snac *user, const char *id)
  1478. /* returns true if this note is bookmarked */
  1479. {
  1480. return object_user_cache_in(user, id, "bookmark");
  1481. }
  1482. int bookmark(snac *user, const char *id)
  1483. /* bookmarks a post */
  1484. {
  1485. if (is_bookmarked(user, id))
  1486. return -3;
  1487. return object_user_cache_add(user, id, "bookmark");
  1488. }
  1489. int unbookmark(snac *user, const char *id)
  1490. /* unbookmarks a post */
  1491. {
  1492. return object_user_cache_del(user, id, "bookmark");
  1493. }
  1494. xs_list *bookmark_list(snac *user)
  1495. /* return the lists of bookmarked posts */
  1496. {
  1497. return object_user_cache_list(user, "bookmark", XS_ALL, 1);
  1498. }
  1499. xs_str *bookmark_index_fn(snac *user)
  1500. {
  1501. return object_user_cache_index_fn(user, "bookmark");
  1502. }
  1503. /** pinning **/
  1504. int is_pinned(snac *user, const char *id)
  1505. /* returns true if this note is pinned */
  1506. {
  1507. return object_user_cache_in(user, id, "pinned");
  1508. }
  1509. int is_pinned_by_md5(snac *user, const char *md5)
  1510. {
  1511. return object_user_cache_in_by_md5(user, md5, "pinned");
  1512. }
  1513. int pin(snac *user, const char *id)
  1514. /* pins a message */
  1515. {
  1516. int ret = -2;
  1517. if (is_msg_mine(user, id)) {
  1518. if (is_pinned(user, id))
  1519. ret = -3;
  1520. else
  1521. ret = object_user_cache_add(user, id, "pinned");
  1522. }
  1523. return ret;
  1524. }
  1525. int unpin(snac *user, const char *id)
  1526. /* unpin a message */
  1527. {
  1528. return object_user_cache_del(user, id, "pinned");
  1529. }
  1530. xs_list *pinned_list(snac *user)
  1531. /* return the lists of pinned posts */
  1532. {
  1533. return object_user_cache_list(user, "pinned", XS_ALL, 1);
  1534. }
  1535. /** drafts **/
  1536. int is_draft(snac *user, const char *id)
  1537. /* returns true if this note is a draft */
  1538. {
  1539. return object_user_cache_in(user, id, "draft");
  1540. }
  1541. void draft_del(snac *user, const char *id)
  1542. /* delete a message from the draft cache */
  1543. {
  1544. object_user_cache_del(user, id, "draft");
  1545. }
  1546. void draft_add(snac *user, const char *id, const xs_dict *msg)
  1547. /* store the message as a draft */
  1548. {
  1549. /* delete from the index, in case it was already there */
  1550. draft_del(user, id);
  1551. /* overwrite object */
  1552. object_add_ow(id, msg);
  1553. /* [re]add to the index */
  1554. object_user_cache_add(user, id, "draft");
  1555. }
  1556. xs_list *draft_list(snac *user)
  1557. /* return the lists of drafts */
  1558. {
  1559. return object_user_cache_list(user, "draft", XS_ALL, 1);
  1560. }
  1561. /** scheduled posts **/
  1562. int is_scheduled(snac *user, const char *id)
  1563. /* returns true if this note is scheduled for future sending */
  1564. {
  1565. return object_user_cache_in(user, id, "sched");
  1566. }
  1567. void schedule_del(snac *user, const char *id)
  1568. /* deletes an scheduled post */
  1569. {
  1570. object_user_cache_del(user, id, "sched");
  1571. }
  1572. void schedule_add(snac *user, const char *id, const xs_dict *msg)
  1573. /* schedules this post for later */
  1574. {
  1575. /* delete from the index, in case it was already there */
  1576. schedule_del(user, id);
  1577. /* overwrite object */
  1578. object_add_ow(id, msg);
  1579. /* [re]add to the index */
  1580. object_user_cache_add(user, id, "sched");
  1581. }
  1582. xs_list *scheduled_list(snac *user)
  1583. /* return the list of scheduled posts */
  1584. {
  1585. return object_user_cache_list(user, "sched", XS_ALL, 1);
  1586. }
  1587. void scheduled_process(snac *user)
  1588. /* processes the scheduled list, sending those ready to be sent */
  1589. {
  1590. xs *posts = scheduled_list(user);
  1591. const char *md5;
  1592. xs *right_now = xs_str_utctime(0, ISO_DATE_SPEC);
  1593. xs_list_foreach(posts, md5) {
  1594. xs *msg = NULL;
  1595. if (valid_status(object_get_by_md5(md5, &msg))) {
  1596. if (strcmp(xs_dict_get(msg, "published"), right_now) < 0) {
  1597. /* due date! */
  1598. const char *id = xs_dict_get(msg, "id");
  1599. timeline_add(user, id, msg);
  1600. xs *c_msg = msg_create(user, msg);
  1601. enqueue_message(user, c_msg);
  1602. schedule_del(user, id);
  1603. }
  1604. }
  1605. }
  1606. }
  1607. /** hiding **/
  1608. xs_str *_hidden_fn(snac *snac, const char *id)
  1609. {
  1610. xs *md5 = xs_md5_hex(id, strlen(id));
  1611. return xs_fmt("%s/hidden/%s", snac->basedir, md5);
  1612. }
  1613. void hide(snac *snac, const char *id)
  1614. /* hides an object and its children (if it's a post) */
  1615. {
  1616. xs *fn = _hidden_fn(snac, id);
  1617. FILE *f;
  1618. if ((f = fopen(fn, "w")) != NULL) {
  1619. fprintf(f, "%s\n", id);
  1620. fclose(f);
  1621. snac_debug(snac, 2, xs_fmt("hidden %s %s", id, fn));
  1622. /* hide all the children */
  1623. xs *chld = object_children(id);
  1624. char *p;
  1625. const char *v;
  1626. p = chld;
  1627. while (xs_list_iter(&p, &v)) {
  1628. xs *co = NULL;
  1629. /* resolve to get the id */
  1630. if (valid_status(object_get_by_md5(v, &co))) {
  1631. const char *id = xs_dict_get(co, "id");
  1632. if (id != NULL)
  1633. hide(snac, id);
  1634. }
  1635. }
  1636. }
  1637. }
  1638. int is_hidden(snac *snac, const char *id)
  1639. /* check is id is hidden */
  1640. {
  1641. xs *fn = _hidden_fn(snac, id);
  1642. return !!(mtime(fn) != 0.0);
  1643. }
  1644. int unhide(snac *user, const char *id)
  1645. /* unhides an object */
  1646. {
  1647. xs *fn = _hidden_fn(user, id);
  1648. return unlink(fn);
  1649. }
  1650. int actor_add(const char *actor, const xs_dict *msg)
  1651. /* adds an actor */
  1652. {
  1653. return object_add_ow(actor, msg);
  1654. }
  1655. int actor_get(const char *actor, xs_dict **data)
  1656. /* returns an already downloaded actor */
  1657. {
  1658. int status = HTTP_STATUS_OK;
  1659. xs_dict *d = NULL;
  1660. if (xs_startswith(actor, srv_baseurl)) {
  1661. /* it's a (possible) local user */
  1662. xs *l = xs_split(actor, "/");
  1663. const char *uid = xs_list_get(l, -1);
  1664. snac user;
  1665. if (!xs_is_null(uid) && user_open(&user, uid)) {
  1666. if (data)
  1667. *data = msg_actor(&user);
  1668. user_free(&user);
  1669. return HTTP_STATUS_OK;
  1670. }
  1671. else
  1672. return HTTP_STATUS_NOT_FOUND;
  1673. }
  1674. /* read the object */
  1675. if (!valid_status(status = object_get(actor, &d))) {
  1676. d = xs_free(d);
  1677. return status;
  1678. }
  1679. /* if the object is corrupted, discard it */
  1680. if (xs_is_null(xs_dict_get(d, "id")) || xs_is_null(xs_dict_get(d, "type"))) {
  1681. srv_debug(1, xs_fmt("corrupted actor object %s", actor));
  1682. d = xs_free(d);
  1683. return HTTP_STATUS_NOT_FOUND;
  1684. }
  1685. if (data)
  1686. *data = d;
  1687. else
  1688. d = xs_free(d);
  1689. xs *fn = _object_fn(actor);
  1690. double max_time;
  1691. /* maximum time for the actor data to be considered stale */
  1692. max_time = 3600.0 * 36.0;
  1693. if (mtime(fn) + max_time < (double) time(NULL)) {
  1694. /* actor data exists but also stinks */
  1695. status = HTTP_STATUS_RESET_CONTENT; /* "110: Response Is Stale" */
  1696. }
  1697. return status;
  1698. }
  1699. int actor_get_refresh(snac *user, const char *actor, xs_dict **data)
  1700. /* gets an actor and requests a refresh if it's stale */
  1701. {
  1702. int status = actor_get(actor, data);
  1703. if (status == HTTP_STATUS_RESET_CONTENT && user && !xs_startswith(actor, srv_baseurl))
  1704. enqueue_actor_refresh(user, actor, 0);
  1705. return status;
  1706. }
  1707. /** user limiting (announce blocks) **/
  1708. int limited(snac *user, const char *id, int cmd)
  1709. /* announce messages from a followed (0: check, 1: limit; 2: unlimit) */
  1710. {
  1711. int ret = 0;
  1712. xs *dir = xs_fmt("%s/limited", user->basedir);
  1713. xs *md5 = xs_md5_hex(id, strlen(id));
  1714. xs *fn = xs_fmt("%s/%s", dir, md5);
  1715. switch (cmd) {
  1716. case 0: /** check **/
  1717. ret = !!(mtime(fn) > 0.0);
  1718. break;
  1719. case 1: /** limit **/
  1720. mkdirx(dir);
  1721. if (mtime(fn) > 0.0)
  1722. ret = -1;
  1723. else {
  1724. FILE *f;
  1725. if ((f = fopen(fn, "w")) != NULL) {
  1726. fprintf(f, "%s\n", id);
  1727. fclose(f);
  1728. }
  1729. else
  1730. ret = -2;
  1731. }
  1732. break;
  1733. case 2: /** unlimit **/
  1734. if (mtime(fn) > 0.0)
  1735. ret = unlink(fn);
  1736. else
  1737. ret = -1;
  1738. break;
  1739. }
  1740. return ret;
  1741. }
  1742. /** tag indexing **/
  1743. void tag_index(const char *id, const xs_dict *obj)
  1744. /* update the tag indexes for this object */
  1745. {
  1746. const xs_list *tags = xs_dict_get(obj, "tag");
  1747. xs *md5_id = xs_md5_hex(id, strlen(id));
  1748. if (get_msg_visibility(obj) != SCOPE_PUBLIC)
  1749. return;
  1750. if (xs_type(tags) == XSTYPE_LIST && xs_list_len(tags) > 0) {
  1751. xs *g_tag_dir = xs_fmt("%s/tag", srv_basedir);
  1752. mkdirx(g_tag_dir);
  1753. const xs_dict *v;
  1754. int ct = 0;
  1755. while (xs_list_next(tags, &v, &ct)) {
  1756. const char *type = xs_dict_get(v, "type");
  1757. const char *name = xs_dict_get(v, "name");
  1758. if (!xs_is_null(type) && !xs_is_null(name) && strcmp(type, "Hashtag") == 0) {
  1759. while (*name == '#' || *name == '@')
  1760. name++;
  1761. if (*name == '\0')
  1762. continue;
  1763. xs* name_cased = xs_utf8_to_lower((xs_str *)name);
  1764. xs *md5_tag = xs_md5_hex(name_cased, strlen(name_cased));
  1765. xs *tag_dir = xs_fmt("%s/%c%c", g_tag_dir, md5_tag[0], md5_tag[1]);
  1766. mkdirx(tag_dir);
  1767. xs *g_tag_idx = xs_fmt("%s/%s.idx", tag_dir, md5_tag);
  1768. if (!index_in_md5(g_tag_idx, md5_id))
  1769. index_add_md5(g_tag_idx, md5_id);
  1770. FILE *f;
  1771. xs *g_tag_name = xs_replace(g_tag_idx, ".idx", ".tag");
  1772. if ((f = fopen(g_tag_name, "w")) != NULL) {
  1773. fprintf(f, "%s\n", name_cased);
  1774. fclose(f);
  1775. }
  1776. srv_debug(1, xs_fmt("tagged %s #%s (#%s)", id, name, md5_tag));
  1777. }
  1778. }
  1779. }
  1780. }
  1781. xs_str *tag_fn(const char *tag)
  1782. {
  1783. if (*tag == '#')
  1784. tag++;
  1785. xs *lw_tag = xs_utf8_to_lower(tag);
  1786. xs *md5 = xs_md5_hex(lw_tag, strlen(lw_tag));
  1787. return xs_fmt("%s/tag/%c%c/%s.idx", srv_basedir, md5[0], md5[1], md5);
  1788. }
  1789. xs_list *tag_search(const char *tag, int skip, int show)
  1790. /* returns the list of posts tagged with tag */
  1791. {
  1792. xs *idx = tag_fn(tag);
  1793. return index_list_desc(idx, skip, show);
  1794. }
  1795. /** lists **/
  1796. xs_val *list_maint(snac *user, const char *list, int op)
  1797. /* list maintenance */
  1798. {
  1799. xs_val *l = NULL;
  1800. switch (op) {
  1801. case 0: /** list of lists **/
  1802. {
  1803. FILE *f;
  1804. xs *spec = xs_fmt("%s/list/" "*.id", user->basedir);
  1805. xs *ls = xs_glob(spec, 0, 0);
  1806. int c = 0;
  1807. const char *v;
  1808. l = xs_list_new();
  1809. while (xs_list_next(ls, &v, &c)) {
  1810. if ((f = fopen(v, "r")) != NULL) {
  1811. xs *title = xs_readline(f);
  1812. fclose(f);
  1813. title = xs_strip_i(title);
  1814. xs *v2 = xs_replace(v, ".id", "");
  1815. xs *l2 = xs_split(v2, "/");
  1816. /* return [ list_id, list_title ] */
  1817. xs *tmp_list = xs_list_append(xs_list_new(), xs_list_get(l2, -1), title);
  1818. l = xs_list_append(l, tmp_list);
  1819. }
  1820. }
  1821. }
  1822. break;
  1823. case 1: /** create new list (list is the name) **/
  1824. {
  1825. xs *lol = list_maint(user, NULL, 0);
  1826. int c = 0;
  1827. const xs_list *v;
  1828. int add = 1;
  1829. /* check if this list name already exists */
  1830. while (xs_list_next(lol, &v, &c)) {
  1831. if (strcmp(xs_list_get(v, 1), list) == 0) {
  1832. add = 0;
  1833. l = xs_dup(xs_list_get(v, 0));
  1834. break;
  1835. }
  1836. }
  1837. if (add) {
  1838. FILE *f;
  1839. xs *dir = xs_fmt("%s/list/", user->basedir);
  1840. l = xs_fmt("%010x", time(NULL));
  1841. mkdirx(dir);
  1842. xs *fn = xs_fmt("%s%s.id", dir, l);
  1843. if ((f = fopen(fn, "w")) != NULL) {
  1844. fprintf(f, "%s\n", list);
  1845. fclose(f);
  1846. }
  1847. }
  1848. }
  1849. break;
  1850. case 2: /** delete list (list is the id) **/
  1851. {
  1852. if (xs_is_hex(list)) {
  1853. xs *fn = xs_fmt("%s/list/%s.id", user->basedir, list);
  1854. unlink(fn);
  1855. fn = xs_replace_i(fn, ".id", ".lst");
  1856. unlink(fn);
  1857. fn = xs_replace_i(fn, ".lst", ".idx");
  1858. unlink(fn);
  1859. fn = xs_str_cat(fn, ".bak");
  1860. unlink(fn);
  1861. }
  1862. }
  1863. break;
  1864. case 3: /** get list name **/
  1865. if (xs_is_hex(list)) {
  1866. FILE *f;
  1867. xs *fn = xs_fmt("%s/list/%s.id", user->basedir, list);
  1868. if ((f = fopen(fn, "r")) != NULL) {
  1869. l = xs_strip_i(xs_readline(f));
  1870. fclose(f);
  1871. }
  1872. }
  1873. break;
  1874. case 4: /** find list id by name **/
  1875. if (xs_is_string(list)) {
  1876. xs *lol = list_maint(user, NULL, 0);
  1877. const xs_list *li;
  1878. xs_list_foreach(lol, li) {
  1879. if (strcmp(list, xs_list_get(li, 1)) == 0) {
  1880. l = xs_dup(xs_list_get(li, 0));
  1881. break;
  1882. }
  1883. }
  1884. }
  1885. }
  1886. return l;
  1887. }
  1888. xs_str *list_timeline_fn(snac *user, const char *list)
  1889. {
  1890. return xs_fmt("%s/list/%s.idx", user->basedir, list);
  1891. }
  1892. xs_list *list_timeline(snac *user, const char *list, int skip, int show)
  1893. /* returns the timeline of a list */
  1894. {
  1895. xs_list *l = NULL;
  1896. if (!xs_is_hex(list))
  1897. return NULL;
  1898. xs *fn = list_timeline_fn(user, list);
  1899. if (mtime(fn) > 0.0)
  1900. l = index_list_desc(fn, skip, show);
  1901. else
  1902. l = xs_list_new();
  1903. return l;
  1904. }
  1905. xs_val *list_members(snac *user, const char *list, const char *actor_md5, int op)
  1906. /* list member management */
  1907. {
  1908. xs_val *l = NULL;
  1909. if (!xs_is_hex(list))
  1910. return NULL;
  1911. if (actor_md5 != NULL && !xs_is_hex(actor_md5))
  1912. return NULL;
  1913. xs *fn = xs_fmt("%s/list/%s.lst", user->basedir, list);
  1914. switch (op) {
  1915. case 0: /** list members **/
  1916. l = index_list(fn, XS_ALL);
  1917. break;
  1918. case 1: /** append actor to list **/
  1919. if (xs_is_string(actor_md5) && xs_is_hex(actor_md5)) {
  1920. if (!index_in_md5(fn, actor_md5))
  1921. index_add_md5(fn, actor_md5);
  1922. }
  1923. break;
  1924. case 2: /** delete actor from list **/
  1925. if (xs_is_string(actor_md5) && xs_is_hex(actor_md5))
  1926. index_del_md5(fn, actor_md5);
  1927. break;
  1928. default:
  1929. srv_log(xs_fmt("ERROR: list_content: bad op %d", op));
  1930. break;
  1931. }
  1932. return l;
  1933. }
  1934. void list_distribute(snac *user, const char *who, const xs_dict *post)
  1935. /* distributes the post to all appropriate lists */
  1936. {
  1937. const char *id = xs_dict_get(post, "id");
  1938. /* if who is not set, use the attributedTo in the message */
  1939. if (xs_is_null(who))
  1940. who = get_atto(post);
  1941. if (xs_type(who) == XSTYPE_STRING && xs_type(id) == XSTYPE_STRING) {
  1942. xs *a_md5 = xs_md5_hex(who, strlen(who));
  1943. xs *i_md5 = xs_md5_hex(id, strlen(id));
  1944. xs *spec = xs_fmt("%s/list/" "*.lst", user->basedir);
  1945. xs *ls = xs_glob(spec, 0, 0);
  1946. int c = 0;
  1947. const char *v;
  1948. while (xs_list_next(ls, &v, &c)) {
  1949. /* is the actor in this list? */
  1950. if (index_in_md5(v, a_md5)) {
  1951. /* it is; add post md5 to its timeline */
  1952. xs *idx = xs_replace(v, ".lst", ".idx");
  1953. index_add_md5(idx, i_md5);
  1954. snac_debug(user, 1, xs_fmt("listed post %s in %s", id, idx));
  1955. }
  1956. }
  1957. }
  1958. }
  1959. /** static data **/
  1960. static int _load_raw_file(const char *fn, xs_val **data, int *size,
  1961. const char *inm, xs_str **etag)
  1962. /* loads a cached file */
  1963. {
  1964. int status = HTTP_STATUS_NOT_FOUND;
  1965. if (fn) {
  1966. double tm = mtime(fn);
  1967. if (tm > 0.0) {
  1968. /* file exists; build the etag */
  1969. xs *e = xs_fmt("W/\"snac-%.0lf\"", tm);
  1970. /* if if-none-match is set, check if it's the same */
  1971. if (!xs_is_null(inm) && strcmp(e, inm) == 0) {
  1972. /* client has the newest version */
  1973. status = HTTP_STATUS_NOT_MODIFIED;
  1974. }
  1975. else {
  1976. /* newer or never downloaded; read the full file */
  1977. struct stat sb;
  1978. FILE *f;
  1979. if (lstat(fn, &sb) == 0 && (sb.st_mode&S_IFMT) == S_IFREG) {
  1980. if ((f = fopen(fn, "rb")) != NULL) {
  1981. *size = XS_ALL;
  1982. *data = xs_read(f, size);
  1983. fclose(f);
  1984. status = HTTP_STATUS_OK;
  1985. }
  1986. }
  1987. }
  1988. /* if caller wants the etag, return it */
  1989. if (etag != NULL)
  1990. *etag = xs_dup(e);
  1991. srv_debug(1, xs_fmt("_load_raw_file(): %s %d", fn, status));
  1992. }
  1993. }
  1994. return status;
  1995. }
  1996. xs_str *_static_fn(snac *snac, const char *id)
  1997. /* gets the filename for a static file */
  1998. {
  1999. if (strstr(id, ".."))
  2000. return NULL;
  2001. else
  2002. return xs_fmt("%s/static/%s", snac->basedir, id);
  2003. }
  2004. int static_get(snac *snac, const char *id, xs_val **data, int *size,
  2005. const char *inm, xs_str **etag)
  2006. /* returns static content */
  2007. {
  2008. xs *fn = _static_fn(snac, id);
  2009. return _load_raw_file(fn, data, size, inm, etag);
  2010. }
  2011. void static_put(snac *snac, const char *id, const char *data, int size)
  2012. /* writes status content */
  2013. {
  2014. xs *fn = _static_fn(snac, id);
  2015. FILE *f;
  2016. if (fn && (f = fopen(fn, "wb")) != NULL) {
  2017. fwrite(data, size, 1, f);
  2018. fclose(f);
  2019. strip_media(fn);
  2020. }
  2021. }
  2022. void static_put_meta(snac *snac, const char *id, const char *str)
  2023. /* puts metadata (i.e. a media description string) to id */
  2024. {
  2025. xs *fn = _static_fn(snac, id);
  2026. if (fn) {
  2027. fn = xs_str_cat(fn, ".txt");
  2028. FILE *f;
  2029. if ((f = fopen(fn, "w")) != NULL) {
  2030. fprintf(f, "%s\n", str);
  2031. fclose(f);
  2032. }
  2033. }
  2034. }
  2035. xs_str *static_get_meta(snac *snac, const char *id)
  2036. /* gets metadata from a media */
  2037. {
  2038. xs *fn = _static_fn(snac, id);
  2039. xs_str *r = NULL;
  2040. if (fn) {
  2041. fn = xs_str_cat(fn, ".txt");
  2042. FILE *f;
  2043. if ((f = fopen(fn, "r")) != NULL) {
  2044. r = xs_strip_i(xs_readline(f));
  2045. fclose(f);
  2046. }
  2047. }
  2048. else
  2049. r = xs_str_new("");
  2050. return r;
  2051. }
  2052. /** history **/
  2053. xs_str *_history_fn(snac *snac, const char *id)
  2054. /* gets the filename for the history */
  2055. {
  2056. if (strchr(id, '/'))
  2057. return NULL;
  2058. else
  2059. return xs_fmt("%s/history/%s", snac->basedir, id);
  2060. }
  2061. double history_mtime(snac *snac, const char *id)
  2062. {
  2063. double t = 0.0;
  2064. xs *fn = _history_fn(snac, id);
  2065. if (fn != NULL)
  2066. t = mtime(fn);
  2067. return t;
  2068. }
  2069. void history_add(snac *snac, const char *id, const char *content, int size,
  2070. xs_str **etag)
  2071. /* adds something to the history */
  2072. {
  2073. xs *fn = _history_fn(snac, id);
  2074. FILE *f;
  2075. if (fn && (f = fopen(fn, "w")) != NULL) {
  2076. fwrite(content, size, 1, f);
  2077. fclose(f);
  2078. if (etag) {
  2079. double tm = mtime(fn);
  2080. *etag = xs_fmt("W/\"snac-%.0lf\"", tm);
  2081. }
  2082. }
  2083. }
  2084. int history_get(snac *snac, const char *id, xs_str **content, int *size,
  2085. const char *inm, xs_str **etag)
  2086. {
  2087. xs *fn = _history_fn(snac, id);
  2088. return _load_raw_file(fn, content, size, inm, etag);
  2089. }
  2090. int history_del(snac *snac, const char *id)
  2091. {
  2092. xs *fn = _history_fn(snac, id);
  2093. if (fn)
  2094. return unlink(fn);
  2095. else
  2096. return -1;
  2097. }
  2098. xs_list *history_list(snac *snac)
  2099. {
  2100. xs *spec = xs_fmt("%s/history/" "*.html", snac->basedir);
  2101. return xs_glob(spec, 1, 1);
  2102. }
  2103. void lastlog_write(snac *snac, const char *source)
  2104. /* writes the last time the user logged in */
  2105. {
  2106. xs *fn = xs_fmt("%s/lastlog.txt", snac->basedir);
  2107. FILE *f;
  2108. if ((f = fopen(fn, "w")) != NULL) {
  2109. fprintf(f, "%lf %s\n", ftime(), source);
  2110. fclose(f);
  2111. }
  2112. }
  2113. /** inbox collection **/
  2114. void inbox_add(const char *inbox)
  2115. /* collects a shared inbox */
  2116. {
  2117. /* don't collect ourselves */
  2118. if (xs_startswith(inbox, srv_baseurl))
  2119. return;
  2120. xs *md5 = xs_md5_hex(inbox, strlen(inbox));
  2121. xs *fn = xs_fmt("%s/inbox/%s", srv_basedir, md5);
  2122. FILE *f;
  2123. if ((f = fopen(fn, "w")) != NULL) {
  2124. fprintf(f, "%s\n", inbox);
  2125. fclose(f);
  2126. }
  2127. }
  2128. void inbox_add_by_actor(const xs_dict *actor)
  2129. /* collects an actor's shared inbox, if it has one */
  2130. {
  2131. const char *v;
  2132. if (!xs_is_null(v = xs_dict_get(actor, "endpoints")) &&
  2133. !xs_is_null(v = xs_dict_get(v, "sharedInbox"))) {
  2134. /* only collect this inbox if its instance is not blocked */
  2135. if (!is_instance_blocked(v))
  2136. inbox_add(v);
  2137. }
  2138. }
  2139. xs_list *inbox_list(void)
  2140. /* returns the collected inboxes as a list */
  2141. {
  2142. xs_list *ibl = xs_list_new();
  2143. xs *spec = xs_fmt("%s/inbox/" "*", srv_basedir);
  2144. xs *files = xs_glob(spec, 0, 0);
  2145. const xs_val *v;
  2146. xs_list_foreach(files, v) {
  2147. FILE *f;
  2148. if ((f = fopen(v, "r")) != NULL) {
  2149. xs *line = xs_readline(f);
  2150. if (line && *line) {
  2151. line = xs_strip_i(line);
  2152. if (!is_instance_blocked(line))
  2153. ibl = xs_list_append(ibl, line);
  2154. }
  2155. fclose(f);
  2156. }
  2157. }
  2158. return ibl;
  2159. }
  2160. /** instance-wide operations **/
  2161. xs_str *_instance_block_fn(const char *instance)
  2162. {
  2163. xs *s = xs_replace(instance, "http:/" "/", "");
  2164. xs *s1 = xs_replace(s, "https:/" "/", "");
  2165. xs *l = xs_split(s1, "/");
  2166. const char *p = xs_list_get(l, 0);
  2167. xs *md5 = xs_md5_hex(p, strlen(p));
  2168. return xs_fmt("%s/block/%s", srv_basedir, md5);
  2169. }
  2170. int is_instance_blocked(const char *instance)
  2171. {
  2172. xs *fn = _instance_block_fn(instance);
  2173. return !!(mtime(fn) != 0.0);
  2174. }
  2175. int instance_block(const char *instance)
  2176. /* blocks a full instance */
  2177. {
  2178. int ret;
  2179. /* create the subdir */
  2180. xs *dir = xs_fmt("%s/block/", srv_basedir);
  2181. mkdirx(dir);
  2182. if (!is_instance_blocked(instance)) {
  2183. xs *fn = _instance_block_fn(instance);
  2184. FILE *f;
  2185. if ((f = fopen(fn, "w")) != NULL) {
  2186. fprintf(f, "%s\n", instance);
  2187. fclose(f);
  2188. ret = 0;
  2189. }
  2190. else
  2191. ret = -1;
  2192. }
  2193. else
  2194. ret = -2;
  2195. return ret;
  2196. }
  2197. int instance_unblock(const char *instance)
  2198. /* unblocks a full instance */
  2199. {
  2200. int ret;
  2201. if (is_instance_blocked(instance)) {
  2202. xs *fn = _instance_block_fn(instance);
  2203. ret = unlink(fn);
  2204. }
  2205. else
  2206. ret = -2;
  2207. return ret;
  2208. }
  2209. /** operations by content **/
  2210. int content_match(const char *file, const xs_dict *msg)
  2211. /* checks if a message's content matches any of the regexes in file */
  2212. /* file format: one regex per line */
  2213. {
  2214. xs *fn = xs_fmt("%s/%s", srv_basedir, file);
  2215. FILE *f;
  2216. int r = 0;
  2217. const char *v = xs_dict_get(msg, "content");
  2218. if (xs_type(v) == XSTYPE_STRING && *v) {
  2219. if ((f = fopen(fn, "r")) != NULL) {
  2220. srv_debug(1, xs_fmt("content_match: loading regexes from %s", fn));
  2221. /* massage content (strip HTML tags, etc.) */
  2222. xs *c1 = xs_regex_replace(v, "<[^>]+>", " ");
  2223. c1 = xs_regex_replace_i(c1, " {2,}", " ");
  2224. xs *c = xs_utf8_to_lower(c1);
  2225. while (!r && !feof(f)) {
  2226. xs *rx = xs_strip_i(xs_readline(f));
  2227. if (*rx && xs_regex_match(c, rx)) {
  2228. srv_debug(1, xs_fmt("content_match: match for '%s'", rx));
  2229. r = 1;
  2230. }
  2231. }
  2232. fclose(f);
  2233. }
  2234. }
  2235. return r;
  2236. }
  2237. xs_list *content_search(snac *user, const char *regex,
  2238. int priv, int skip, int show, int max_secs, int *timeout)
  2239. /* returns a list of posts which content matches the regex */
  2240. {
  2241. if (regex == NULL || *regex == '\0')
  2242. return xs_list_new();
  2243. xs *i_regex = xs_utf8_to_lower(regex);
  2244. xs_set seen;
  2245. xs_set_init(&seen);
  2246. if (max_secs == 0)
  2247. max_secs = 3;
  2248. time_t t = time(NULL) + max_secs;
  2249. *timeout = 0;
  2250. /* iterate all timelines simultaneously */
  2251. xs_list *tls[3] = {0};
  2252. const char *md5s[3] = {0};
  2253. int c[3] = {0};
  2254. tls[0] = timeline_simple_list(user, "public", 0, XS_ALL, NULL); /* public */
  2255. tls[1] = timeline_instance_list(0, XS_ALL); /* instance */
  2256. tls[2] = priv ? timeline_simple_list(user, "private", 0, XS_ALL, NULL) : xs_list_new(); /* private or none */
  2257. /* first positioning */
  2258. for (int n = 0; n < 3; n++)
  2259. xs_list_next(tls[n], &md5s[n], &c[n]);
  2260. show += skip;
  2261. while (show > 0) {
  2262. /* timeout? */
  2263. if (time(NULL) > t) {
  2264. *timeout = 1;
  2265. break;
  2266. }
  2267. /* find the newest post */
  2268. int newest = -1;
  2269. double mtime = 0.0;
  2270. for (int n = 0; n < 3; n++) {
  2271. if (md5s[n] != NULL) {
  2272. xs *fn = _object_fn_by_md5(md5s[n], "content_search");
  2273. double mt;
  2274. while ((mt = mtime(fn)) == 0 && md5s[n] != NULL) {
  2275. /* object is not here: move to the next one */
  2276. if (xs_list_next(tls[n], &md5s[n], &c[n])) {
  2277. xs_free(fn);
  2278. fn = _object_fn_by_md5(md5s[n], "content_search_2");
  2279. }
  2280. else
  2281. md5s[n] = NULL;
  2282. }
  2283. if (mt > mtime) {
  2284. newest = n;
  2285. mtime = mt;
  2286. }
  2287. }
  2288. }
  2289. if (newest == -1)
  2290. break;
  2291. const char *md5 = md5s[newest];
  2292. /* advance the chosen timeline */
  2293. if (!xs_list_next(tls[newest], &md5s[newest], &c[newest]))
  2294. md5s[newest] = NULL;
  2295. xs *post = NULL;
  2296. if (!valid_status(object_get_by_md5(md5, &post)))
  2297. continue;
  2298. if (!xs_match(xs_dict_get_def(post, "type", "-"), POSTLIKE_OBJECT_TYPE))
  2299. continue;
  2300. const char *id = xs_dict_get(post, "id");
  2301. if (id == NULL || is_hidden(user, id))
  2302. continue;
  2303. /* recalculate the md5 id to be sure it's not repeated
  2304. (it may have been searched by the "url" field instead of "id") */
  2305. xs *new_md5 = xs_md5_hex(id, strlen(id));
  2306. md5 = new_md5;
  2307. /* test for the post URL */
  2308. if (strcmp(id, regex) == 0) {
  2309. if (xs_set_add(&seen, md5) == 1)
  2310. show--;
  2311. continue;
  2312. }
  2313. /* test for the alternate post id */
  2314. const char *url = xs_dict_get(post, "url");
  2315. if (xs_type(url) == XSTYPE_STRING && strcmp(url, regex) == 0) {
  2316. if (xs_set_add(&seen, md5) == 1)
  2317. show--;
  2318. continue;
  2319. }
  2320. xs *c = xs_str_new(NULL);
  2321. const char *content = xs_dict_get(post, "content");
  2322. const char *name = xs_dict_get(post, "name");
  2323. const char *atto = get_atto(post);
  2324. if (!xs_is_null(content))
  2325. c = xs_str_cat(c, content);
  2326. if (!xs_is_null(name))
  2327. c = xs_str_cat(c, " ", name);
  2328. if (!xs_is_null(atto))
  2329. c = xs_str_cat(c, " ", atto);
  2330. /* add alt-texts from attachments */
  2331. const xs_list *atts = xs_dict_get(post, "attachment");
  2332. int tc = 0;
  2333. const xs_dict *att;
  2334. while (xs_list_next(atts, &att, &tc)) {
  2335. const char *name = xs_dict_get(att, "name");
  2336. if (name != NULL)
  2337. c = xs_str_cat(c, " ", name);
  2338. }
  2339. /* strip HTML */
  2340. c = xs_regex_replace_i(c, "<[^>]+>", " ");
  2341. c = xs_regex_replace_i(c, " {2,}", " ");
  2342. /* convert to lowercase */
  2343. xs *lc = xs_utf8_to_lower(c);
  2344. /* apply regex */
  2345. if (xs_regex_match(lc, i_regex)) {
  2346. if (xs_set_add(&seen, md5) == 1)
  2347. show--;
  2348. }
  2349. }
  2350. xs_list *r = xs_set_result(&seen);
  2351. if (skip) {
  2352. /* BAD */
  2353. while (skip--) {
  2354. r = xs_list_del(r, 0);
  2355. }
  2356. }
  2357. xs_free(tls[0]);
  2358. xs_free(tls[1]);
  2359. xs_free(tls[2]);
  2360. return r;
  2361. }
  2362. int actor_failure(const char *actor, int op)
  2363. /* actor failure maintenance */
  2364. {
  2365. int ret = 0;
  2366. xs *md5 = xs_md5_hex(actor, strlen(actor));
  2367. xs *fn = xs_fmt("%s/failure/%s", srv_basedir, md5);
  2368. switch (op) {
  2369. case 0: /** check **/
  2370. if (mtime(fn))
  2371. ret = -1;
  2372. break;
  2373. case 1: /** register a failure **/
  2374. if (mtime(fn) == 0.0) {
  2375. FILE *f;
  2376. /* only create once, as the date will be used */
  2377. if ((f = fopen(fn, "w")) != NULL) {
  2378. fprintf(f, "%s\n", actor);
  2379. fclose(f);
  2380. }
  2381. }
  2382. break;
  2383. case 2: /** clear a failure **/
  2384. /* called whenever a message comes from this instance */
  2385. unlink(fn);
  2386. break;
  2387. }
  2388. return ret;
  2389. }
  2390. int instance_failure(const char *url, int op)
  2391. /* do some checks and accounting on instance failures */
  2392. {
  2393. int ret = 0;
  2394. xs *l = xs_split(url, "/");
  2395. const char *hostname = xs_list_get(l, 2);
  2396. double mt;
  2397. if (!xs_is_string(hostname))
  2398. return 0;
  2399. xs *md5 = xs_md5_hex(hostname, strlen(hostname));
  2400. xs *fn = xs_fmt("%s/failure/%s", srv_basedir, md5);
  2401. switch (op) {
  2402. case 0: /** check **/
  2403. if ((mt = mtime(fn)) != 0.0) {
  2404. /* grace time */
  2405. double seconds_failing = xs_number_get(xs_dict_get_def(srv_config, "max_failing_days", "15"))
  2406. * (24 * 60 * 60);
  2407. if ((double)time(NULL) - mt > seconds_failing)
  2408. ret = -1;
  2409. }
  2410. break;
  2411. case 1: /** register a failure **/
  2412. if (mtime(fn) == 0.0) {
  2413. FILE *f;
  2414. /* only create once, as the date will be used */
  2415. if ((f = fopen(fn, "w")) != NULL) {
  2416. fprintf(f, "%s\n", hostname);
  2417. fclose(f);
  2418. }
  2419. }
  2420. break;
  2421. case 2: /** clear a failure **/
  2422. /* called whenever a message comes from this instance */
  2423. unlink(fn);
  2424. break;
  2425. }
  2426. return ret;
  2427. }
  2428. int grave(const char *objid, int op)
  2429. /* the graveyeard of deleted objects */
  2430. {
  2431. int ret = 0;
  2432. xs *dir = xs_fmt("%s/grave", srv_basedir);
  2433. xs *md5 = xs_md5_hex(objid, strlen(objid));
  2434. xs *fn = xs_fmt("%s/%s", dir, md5);
  2435. FILE *f;
  2436. switch (op) {
  2437. case 0: /** check **/
  2438. ret = mtime(fn) > 0.0 ? 1 : 0;
  2439. break;
  2440. case 1: /** add **/
  2441. mkdirx(dir);
  2442. if ((f = fopen(fn, "w")) != NULL) {
  2443. fprintf(f, "%s\n", objid);
  2444. fclose(f);
  2445. }
  2446. break;
  2447. case 2: /** del **/
  2448. unlink(fn);
  2449. break;
  2450. }
  2451. return ret;
  2452. }
  2453. /** notifications **/
  2454. xs_str *notify_check_time(snac *snac, int reset)
  2455. /* gets or resets the latest notification check time */
  2456. {
  2457. xs_str *t = NULL;
  2458. xs *fn = xs_fmt("%s/notifydate.txt", snac->basedir);
  2459. FILE *f;
  2460. if (reset) {
  2461. if ((f = fopen(fn, "w")) != NULL) {
  2462. t = tid(0);
  2463. fprintf(f, "%s\n", t);
  2464. fclose(f);
  2465. }
  2466. }
  2467. else {
  2468. if ((f = fopen(fn, "r")) != NULL) {
  2469. t = xs_readline(f);
  2470. fclose(f);
  2471. }
  2472. else
  2473. /* never set before */
  2474. t = xs_fmt("%16.6f", 0.0);
  2475. }
  2476. return t;
  2477. }
  2478. xs_dict *markers_get(snac *snac, const xs_list *markers)
  2479. {
  2480. xs *data = NULL;
  2481. xs_dict *returns = xs_dict_new();
  2482. xs *fn = xs_fmt("%s/markers.json", snac->basedir);
  2483. const xs_str *v = NULL;
  2484. FILE *f;
  2485. if ((f = fopen(fn, "r")) != NULL) {
  2486. data = xs_json_load(f);
  2487. fclose(f);
  2488. }
  2489. if (xs_is_null(data))
  2490. data = xs_dict_new();
  2491. xs_list_foreach(markers, v) {
  2492. const xs_dict *mark = xs_dict_get(data, v);
  2493. if (!xs_is_null(mark)) {
  2494. returns = xs_dict_append(returns, v, mark);
  2495. }
  2496. }
  2497. return returns;
  2498. }
  2499. xs_dict *markers_set(snac *snac, const char *home_marker, const char *notify_marker)
  2500. /* gets or sets notification marker */
  2501. {
  2502. xs *data = NULL;
  2503. xs_dict *written = xs_dict_new();
  2504. xs *fn = xs_fmt("%s/markers.json", snac->basedir);
  2505. FILE *f;
  2506. if ((f = fopen(fn, "r")) != NULL) {
  2507. data = xs_json_load(f);
  2508. fclose(f);
  2509. }
  2510. if (xs_is_null(data))
  2511. data = xs_dict_new();
  2512. if (!xs_is_null(home_marker)) {
  2513. xs *home = xs_dict_new();
  2514. xs *s_tid = tid(0);
  2515. home = xs_dict_append(home, "last_read_id", home_marker);
  2516. home = xs_dict_append(home, "version", xs_stock(0));
  2517. home = xs_dict_append(home, "updated_at", s_tid);
  2518. data = xs_dict_set(data, "home", home);
  2519. written = xs_dict_append(written, "home", home);
  2520. }
  2521. if (!xs_is_null(notify_marker)) {
  2522. xs *notify = xs_dict_new();
  2523. xs *s_tid = tid(0);
  2524. notify = xs_dict_append(notify, "last_read_id", notify_marker);
  2525. notify = xs_dict_append(notify, "version", xs_stock(0));
  2526. notify = xs_dict_append(notify, "updated_at", s_tid);
  2527. data = xs_dict_set(data, "notifications", notify);
  2528. written = xs_dict_append(written, "notifications", notify);
  2529. }
  2530. if ((f = fopen(fn, "w")) != NULL) {
  2531. xs_json_dump(data, 4, f);
  2532. fclose(f);
  2533. }
  2534. return written;
  2535. }
  2536. void notify_add(snac *snac, const char *type, const char *utype,
  2537. const char *actor, const char *objid, const xs_dict *msg)
  2538. /* adds a new notification */
  2539. {
  2540. xs *ntid = tid(0);
  2541. xs *fn = xs_fmt("%s/notify/", snac->basedir);
  2542. xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
  2543. FILE *f;
  2544. /* create the directory */
  2545. mkdirx(fn);
  2546. fn = xs_str_cat(fn, ntid);
  2547. fn = xs_str_cat(fn, ".json");
  2548. xs *noti = xs_dict_new();
  2549. noti = xs_dict_append(noti, "id", ntid);
  2550. noti = xs_dict_append(noti, "type", type);
  2551. noti = xs_dict_append(noti, "utype", utype);
  2552. noti = xs_dict_append(noti, "actor", actor);
  2553. noti = xs_dict_append(noti, "date", date);
  2554. noti = xs_dict_append(noti, "msg", msg);
  2555. if (!xs_is_null(objid))
  2556. noti = xs_dict_append(noti, "objid", objid);
  2557. if ((f = fopen(fn, "w")) != NULL) {
  2558. xs_json_dump(noti, 4, f);
  2559. fclose(f);
  2560. }
  2561. /* add it to the index if it already exists */
  2562. xs *idx = xs_fmt("%s/notify.idx", snac->basedir);
  2563. if (mtime(idx) != 0.0) {
  2564. pthread_mutex_lock(&data_mutex);
  2565. if ((f = fopen(idx, "a")) != NULL) {
  2566. fprintf(f, "%-32s\n", ntid);
  2567. fclose(f);
  2568. }
  2569. pthread_mutex_unlock(&data_mutex);
  2570. }
  2571. if (!xs_is_true(xs_dict_get(srv_config, "disable_notify_webhook")))
  2572. enqueue_notify_webhook(snac, noti, 0);
  2573. }
  2574. xs_dict *notify_get(snac *snac, const char *id)
  2575. /* gets a notification */
  2576. {
  2577. /* base file */
  2578. xs *fn = xs_fmt("%s/notify/%s", snac->basedir, id);
  2579. /* strip spaces and add extension */
  2580. fn = xs_strip_i(fn);
  2581. fn = xs_str_cat(fn, ".json");
  2582. FILE *f;
  2583. xs_dict *out = NULL;
  2584. if ((f = fopen(fn, "r")) != NULL) {
  2585. out = xs_json_load(f);
  2586. fclose(f);
  2587. }
  2588. return out;
  2589. }
  2590. xs_list *notify_list(snac *snac, int skip, int show)
  2591. /* returns a list of notification ids */
  2592. {
  2593. xs *idx = xs_fmt("%s/notify.idx", snac->basedir);
  2594. if (mtime(idx) == 0.0) {
  2595. /* create the index from scratch */
  2596. FILE *f;
  2597. pthread_mutex_lock(&data_mutex);
  2598. if ((f = fopen(idx, "w")) != NULL) {
  2599. xs *spec = xs_fmt("%s/notify/" "*.json", snac->basedir);
  2600. xs *lst = xs_glob(spec, 1, 0);
  2601. xs_list *p = lst;
  2602. const char *v;
  2603. while (xs_list_iter(&p, &v)) {
  2604. char *p = strrchr(v, '.');
  2605. if (p) {
  2606. *p = '\0';
  2607. fprintf(f, "%-32s\n", v);
  2608. }
  2609. }
  2610. fclose(f);
  2611. }
  2612. pthread_mutex_unlock(&data_mutex);
  2613. }
  2614. return index_list_desc(idx, skip, show);
  2615. }
  2616. xs_list *notify_filter_list(snac *snac, xs_list *notifs)
  2617. /* apply user-defined notification filter to IDs */
  2618. {
  2619. const xs_dict *n_filter = xs_dict_get(snac->config, "notify_filter");
  2620. if (!n_filter) {
  2621. return xs_dup(notifs);
  2622. }
  2623. const xs_val *n_def = xs_stock( XSTYPE_TRUE );
  2624. int n_likes_on = xs_is_true(xs_dict_get_def(n_filter, "likes", n_def));
  2625. int n_reacts_on = xs_is_true(xs_dict_get_def(n_filter, "reacts", n_def));
  2626. int n_ments_on = xs_is_true(xs_dict_get_def(n_filter, "mentions", n_def));
  2627. int n_ann_on = xs_is_true(xs_dict_get_def(n_filter, "announces", n_def));
  2628. int n_fol_on = xs_is_true(xs_dict_get_def(n_filter, "follows", n_def));
  2629. int n_unfol_on = xs_is_true(xs_dict_get_def(n_filter, "unfollows", n_def));
  2630. int n_folreq_on = xs_is_true(xs_dict_get_def(n_filter, "folreqs", n_def));
  2631. int n_blocks_on = xs_is_true(xs_dict_get_def(n_filter, "blocks", n_def));
  2632. int n_polls_on = xs_is_true(xs_dict_get_def(n_filter, "polls", n_def));
  2633. const xs_str *v;
  2634. xs_list *flt = xs_list_new();
  2635. xs_list_foreach(notifs, v) {
  2636. xs *noti = notify_get(snac, v);
  2637. if (noti == NULL)
  2638. continue;
  2639. const char *type = xs_dict_get(noti, "type");
  2640. const char *utype = xs_dict_get(noti, "utype");
  2641. const char *actor_id = xs_dict_get(noti, "actor");
  2642. if (strcmp(type, "EmojiReact") == 0 && xs_is_true(xs_dict_get(srv_config, "disable_emojireact")))
  2643. continue;
  2644. if (strcmp(type, "Create") == 0 && !n_ments_on)
  2645. continue;
  2646. if (strcmp(type, "Update") == 0 && strcmp(utype, "Question") == 0 && !n_polls_on)
  2647. continue;
  2648. if (strcmp(type, "Undo") == 0 && strcmp(utype, "Follow") == 0 && !n_unfol_on)
  2649. continue;
  2650. if (strcmp(type, "EmojiReact") == 0 || strcmp(type, "Like") == 0) {
  2651. if (strcmp(type, "Like") == 0 && !n_likes_on)
  2652. continue;
  2653. if (strcmp(type, "EmojiReact") == 0 && !n_reacts_on)
  2654. continue;
  2655. }
  2656. if (strcmp(type, "Follow") == 0) {
  2657. if (pending_check(snac, actor_id)) {
  2658. if (!n_folreq_on)
  2659. continue;
  2660. }
  2661. else
  2662. if (!n_fol_on)
  2663. continue;
  2664. }
  2665. if (strcmp(type, "Block") == 0 && !n_blocks_on)
  2666. continue;
  2667. if (strcmp(type, "Announce") == 0 && !n_ann_on)
  2668. continue;
  2669. flt = xs_list_append(flt, v);
  2670. }
  2671. return flt;
  2672. }
  2673. int notify_new_num(snac *snac)
  2674. /* counts the number of new notifications */
  2675. {
  2676. xs *t = notify_check_time(snac, 0);
  2677. xs *lst_unfilt = notify_list(snac, 0, XS_ALL);
  2678. xs *lst = notify_filter_list(snac, lst_unfilt);
  2679. int cnt = 0;
  2680. xs_list *p = lst;
  2681. const xs_str *v;
  2682. while (xs_list_iter(&p, &v)) {
  2683. xs *id = xs_strip_i(xs_dup(v));
  2684. /* old? count no more */
  2685. if (strcmp(id, t) < 0)
  2686. break;
  2687. cnt++;
  2688. }
  2689. return cnt;
  2690. }
  2691. void notify_clear(snac *snac)
  2692. /* clears all notifications */
  2693. {
  2694. xs *spec = xs_fmt("%s/notify/" "*", snac->basedir);
  2695. xs *lst = xs_glob(spec, 0, 0);
  2696. xs_list *p = lst;
  2697. const xs_str *v;
  2698. while (xs_list_iter(&p, &v))
  2699. unlink(v);
  2700. xs *idx = xs_fmt("%s/notify.idx", snac->basedir);
  2701. if (mtime(idx) != 0.0) {
  2702. pthread_mutex_lock(&data_mutex);
  2703. truncate(idx, 0);
  2704. pthread_mutex_unlock(&data_mutex);
  2705. }
  2706. }
  2707. /** the queue **/
  2708. static xs_dict *_enqueue_put(const char *fn, xs_dict *msg)
  2709. /* writes safely to the queue */
  2710. {
  2711. xs *tfn = xs_fmt("%s.tmp", fn);
  2712. FILE *f;
  2713. if ((f = fopen(tfn, "w")) != NULL) {
  2714. xs_json_dump(msg, 4, f);
  2715. fclose(f);
  2716. rename(tfn, fn);
  2717. }
  2718. return msg;
  2719. }
  2720. static xs_dict *_new_qmsg(const char *type, const xs_val *msg, int retries)
  2721. /* creates a queue message */
  2722. {
  2723. int qrt = xs_number_get(xs_dict_get(srv_config, "queue_retry_minutes"));
  2724. xs *ntid = tid(retries * 60 * qrt);
  2725. xs *rn = xs_number_new(retries);
  2726. xs_dict *qmsg = xs_dict_new();
  2727. qmsg = xs_dict_append(qmsg, "type", type);
  2728. qmsg = xs_dict_append(qmsg, "message", msg);
  2729. qmsg = xs_dict_append(qmsg, "retries", rn);
  2730. qmsg = xs_dict_append(qmsg, "ntid", ntid);
  2731. return qmsg;
  2732. }
  2733. void enqueue_input(snac *snac, const xs_dict *msg, const xs_dict *req, int retries)
  2734. /* enqueues an input message */
  2735. {
  2736. xs *qmsg = _new_qmsg("input", msg, retries);
  2737. const char *ntid = xs_dict_get(qmsg, "ntid");
  2738. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  2739. qmsg = xs_dict_append(qmsg, "req", req);
  2740. qmsg = _enqueue_put(fn, qmsg);
  2741. snac_debug(snac, 1, xs_fmt("enqueue_input %s", xs_dict_get(msg, "id")));
  2742. }
  2743. void enqueue_shared_input(const xs_dict *msg, const xs_dict *req, int retries)
  2744. /* enqueues an input message from the shared input */
  2745. {
  2746. xs *qmsg = _new_qmsg("input", msg, retries);
  2747. const char *ntid = xs_dict_get(qmsg, "ntid");
  2748. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  2749. qmsg = xs_dict_append(qmsg, "req", req);
  2750. qmsg = _enqueue_put(fn, qmsg);
  2751. srv_debug(1, xs_fmt("enqueue_shared_input %s", xs_dict_get(msg, "id")));
  2752. }
  2753. void enqueue_output_raw(const char *keyid, const char *seckey,
  2754. const xs_dict *msg, const xs_str *inbox,
  2755. int retries, int p_status)
  2756. /* enqueues an output message to an inbox */
  2757. {
  2758. xs *qmsg = _new_qmsg("output", msg, retries);
  2759. const char *ntid = xs_dict_get(qmsg, "ntid");
  2760. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  2761. xs *ns = xs_number_new(p_status);
  2762. qmsg = xs_dict_append(qmsg, "p_status", ns);
  2763. qmsg = xs_dict_append(qmsg, "inbox", inbox);
  2764. qmsg = xs_dict_append(qmsg, "keyid", keyid);
  2765. qmsg = xs_dict_append(qmsg, "seckey", seckey);
  2766. /* if it's to be sent right now, bypass the disk queue and post the job */
  2767. if (retries == 0 && p_state != NULL)
  2768. job_post(qmsg, 0);
  2769. else {
  2770. qmsg = _enqueue_put(fn, qmsg);
  2771. srv_debug(1, xs_fmt("enqueue_output %s %s %d", inbox, fn, retries));
  2772. }
  2773. }
  2774. void enqueue_output(snac *snac, const xs_dict *msg,
  2775. const xs_str *inbox, int retries, int p_status)
  2776. /* enqueues an output message to an inbox */
  2777. {
  2778. if (is_msg_mine(snac, inbox)) {
  2779. snac_debug(snac, 1, xs_str_new("refusing enqueue to myself"));
  2780. return;
  2781. }
  2782. const char *seckey = xs_dict_get(snac->key, "secret");
  2783. enqueue_output_raw(snac->actor, seckey, msg, inbox, retries, p_status);
  2784. }
  2785. void enqueue_output_by_actor(snac *snac, const xs_dict *msg,
  2786. const xs_str *actor, int retries)
  2787. /* enqueues an output message for an actor */
  2788. {
  2789. xs *inbox = get_actor_inbox(actor, 1);
  2790. if (!xs_is_null(inbox))
  2791. enqueue_output(snac, msg, inbox, retries, 0);
  2792. else
  2793. snac_log(snac, xs_fmt("enqueue_output_by_actor cannot get inbox %s", actor));
  2794. }
  2795. void enqueue_email(const xs_dict *msg, int retries)
  2796. /* enqueues an email message to be sent */
  2797. {
  2798. xs *qmsg = _new_qmsg("email", msg, retries);
  2799. const char *ntid = xs_dict_get(qmsg, "ntid");
  2800. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  2801. qmsg = _enqueue_put(fn, qmsg);
  2802. srv_debug(1, xs_fmt("enqueue_email %d", retries));
  2803. }
  2804. void enqueue_telegram(const xs_str *msg, const char *bot, const char *chat_id)
  2805. /* enqueues a message to be sent via Telegram */
  2806. {
  2807. xs *qmsg = _new_qmsg("telegram", msg, 0);
  2808. const char *ntid = xs_dict_get(qmsg, "ntid");
  2809. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  2810. qmsg = xs_dict_append(qmsg, "bot", bot);
  2811. qmsg = xs_dict_append(qmsg, "chat_id", chat_id);
  2812. qmsg = _enqueue_put(fn, qmsg);
  2813. srv_debug(1, xs_fmt("enqueue_telegram %s %s", bot, chat_id));
  2814. }
  2815. void enqueue_ntfy(const xs_str *msg, const char *ntfy_server, const char *ntfy_token)
  2816. /* enqueues a message to be sent via ntfy */
  2817. {
  2818. xs *qmsg = _new_qmsg("ntfy", msg, 0);
  2819. const char *ntid = xs_dict_get(qmsg, "ntid");
  2820. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  2821. qmsg = xs_dict_append(qmsg, "ntfy_server", ntfy_server);
  2822. qmsg = xs_dict_append(qmsg, "ntfy_token", ntfy_token);
  2823. qmsg = _enqueue_put(fn, qmsg);
  2824. srv_debug(1, xs_fmt("enqueue_ntfy %s %s", ntfy_server, ntfy_token));
  2825. }
  2826. void enqueue_message(snac *snac, const xs_dict *msg)
  2827. /* enqueues an output message */
  2828. {
  2829. xs *qmsg = _new_qmsg("message", msg, 0);
  2830. const char *ntid = xs_dict_get(qmsg, "ntid");
  2831. xs *fn = xs_fmt("%s/queue/%s.json", snac->basedir, ntid);
  2832. qmsg = _enqueue_put(fn, qmsg);
  2833. snac_debug(snac, 0, xs_fmt("enqueue_message %s", xs_dict_get(msg, "id")));
  2834. }
  2835. void enqueue_close_question(snac *user, const char *id, int end_secs)
  2836. /* enqueues the closing of a question */
  2837. {
  2838. xs *qmsg = _new_qmsg("close_question", id, 0);
  2839. xs *ntid = tid(end_secs);
  2840. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2841. qmsg = xs_dict_set(qmsg, "ntid", ntid);
  2842. qmsg = _enqueue_put(fn, qmsg);
  2843. snac_debug(user, 0, xs_fmt("enqueue_close_question %s", id));
  2844. }
  2845. void enqueue_object_request(snac *user, const char *id, int forward_secs)
  2846. /* enqueues the request of an object in the future */
  2847. {
  2848. xs *qmsg = _new_qmsg("object_request", id, 0);
  2849. xs *ntid = tid(forward_secs);
  2850. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2851. qmsg = xs_dict_set(qmsg, "ntid", ntid);
  2852. qmsg = _enqueue_put(fn, qmsg);
  2853. snac_debug(user, 0, xs_fmt("enqueue_object_request %s %d", id, forward_secs));
  2854. }
  2855. void enqueue_verify_links(snac *user)
  2856. /* enqueues a link verification */
  2857. {
  2858. xs *qmsg = _new_qmsg("verify_links", "", 0);
  2859. const char *ntid = xs_dict_get(qmsg, "ntid");
  2860. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2861. qmsg = _enqueue_put(fn, qmsg);
  2862. snac_debug(user, 1, xs_fmt("enqueue_verify_links %s", user->actor));
  2863. }
  2864. void enqueue_actor_refresh(snac *user, const char *actor, int forward_secs)
  2865. /* enqueues an actor refresh */
  2866. {
  2867. xs *qmsg = _new_qmsg("actor_refresh", "", 0);
  2868. xs *ntid = tid(forward_secs);
  2869. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2870. qmsg = xs_dict_set(qmsg, "ntid", ntid);
  2871. qmsg = xs_dict_append(qmsg, "actor", actor);
  2872. qmsg = _enqueue_put(fn, qmsg);
  2873. snac_debug(user, 1, xs_fmt("enqueue_actor_refresh %s", actor));
  2874. }
  2875. void enqueue_webmention(const xs_dict *msg)
  2876. /* enqueues a webmention for the post */
  2877. {
  2878. xs *qmsg = _new_qmsg("webmention", msg, 0);
  2879. const char *ntid = xs_dict_get(qmsg, "ntid");
  2880. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  2881. qmsg = _enqueue_put(fn, qmsg);
  2882. srv_debug(1, xs_fmt("enqueue_webmention"));
  2883. }
  2884. void enqueue_notify_webhook(snac *user, const xs_dict *noti, int retries)
  2885. /* enqueues a notification webhook */
  2886. {
  2887. const char *webhook = xs_dict_get(user->config, "notify_webhook");
  2888. if (xs_is_string(webhook) && xs_match(webhook, "https://*|http://*")) { /** **/
  2889. xs *msg = xs_dup(noti);
  2890. /* add more data */
  2891. msg = xs_dict_set(msg, "target", user->actor);
  2892. msg = xs_dict_set(msg, "uid", user->uid);
  2893. msg = xs_dict_set(msg, "basedir", srv_basedir);
  2894. msg = xs_dict_set(msg, "baseurl", srv_baseurl);
  2895. xs *actor_obj = NULL;
  2896. if (valid_status(object_get(xs_dict_get(noti, "actor"), &actor_obj)) && actor_obj)
  2897. msg = xs_dict_set(msg, "account", actor_obj);
  2898. /* if this post is a reply, also add the inReplyTo object */
  2899. const char *in_reply_to = xs_dict_get_path(msg, "msg.object.inReplyTo");
  2900. if (xs_is_string(in_reply_to)) {
  2901. xs *irt_obj = NULL;
  2902. if (valid_status(object_get(in_reply_to, &irt_obj)))
  2903. msg = xs_dict_set(msg, "reply", irt_obj);
  2904. }
  2905. xs *qmsg = _new_qmsg("notify_webhook", msg, retries);
  2906. const char *ntid = xs_dict_get(qmsg, "ntid");
  2907. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2908. qmsg = _enqueue_put(fn, qmsg);
  2909. snac_debug(user, 1, xs_fmt("notify_webhook"));
  2910. }
  2911. }
  2912. void enqueue_collect_replies(snac *user, const char *post)
  2913. /* enqueues a collect replies request */
  2914. {
  2915. xs *qmsg = _new_qmsg("collect_replies", post, 0);
  2916. const char *ntid = xs_dict_get(qmsg, "ntid");
  2917. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2918. qmsg = _enqueue_put(fn, qmsg);
  2919. snac_debug(user, 1, xs_fmt("enqueue_collect_replies %s", post));
  2920. }
  2921. void enqueue_collect_outbox(snac *user, const char *actor_id)
  2922. /* enqueues a collect outbox request */
  2923. {
  2924. xs *qmsg = _new_qmsg("collect_outbox", actor_id, 0);
  2925. const char *ntid = xs_dict_get(qmsg, "ntid");
  2926. xs *fn = xs_fmt("%s/queue/%s.json", user->basedir, ntid);
  2927. qmsg = _enqueue_put(fn, qmsg);
  2928. snac_debug(user, 1, xs_fmt("enqueue_collect_outbox %s", actor_id));
  2929. }
  2930. void enqueue_fsck(void)
  2931. /* enqueues an fsck */
  2932. {
  2933. xs *qmsg = _new_qmsg("fsck", "", 0);
  2934. const char *ntid = xs_dict_get(qmsg, "ntid");
  2935. xs *fn = xs_fmt("%s/queue/%s.json", srv_basedir, ntid);
  2936. qmsg = _enqueue_put(fn, qmsg);
  2937. }
  2938. int was_question_voted(snac *user, const char *id)
  2939. /* returns true if the user voted in this poll */
  2940. {
  2941. xs *children = object_children(id);
  2942. int voted = 0;
  2943. xs_list *p;
  2944. const xs_str *md5;
  2945. p = children;
  2946. while (xs_list_iter(&p, &md5)) {
  2947. xs *obj = NULL;
  2948. if (valid_status(object_get_by_md5(md5, &obj))) {
  2949. const char *atto = get_atto(obj);
  2950. if (atto && strcmp(atto, user->actor) == 0 &&
  2951. !xs_is_null(xs_dict_get(obj, "name"))) {
  2952. voted = 1;
  2953. break;
  2954. }
  2955. }
  2956. }
  2957. return voted;
  2958. }
  2959. xs_list *user_queue(snac *snac)
  2960. /* returns a list with filenames that can be dequeued */
  2961. {
  2962. xs *spec = xs_fmt("%s/queue/" "*.json", snac->basedir);
  2963. xs_list *list = xs_list_new();
  2964. time_t t = time(NULL);
  2965. xs_list *p;
  2966. const xs_val *v;
  2967. xs *fns = xs_glob(spec, 0, 0);
  2968. p = fns;
  2969. while (xs_list_iter(&p, &v)) {
  2970. /* get the retry time from the basename */
  2971. char *bn = strrchr(v, '/');
  2972. time_t t2 = atol(bn + 1);
  2973. if (t2 > t)
  2974. snac_debug(snac, 2, xs_fmt("user_queue not yet time for %s [%ld]", v, t));
  2975. else {
  2976. list = xs_list_append(list, v);
  2977. snac_debug(snac, 2, xs_fmt("user_queue ready for %s", v));
  2978. }
  2979. }
  2980. return list;
  2981. }
  2982. xs_list *queue(void)
  2983. /* returns a list with filenames that can be dequeued */
  2984. {
  2985. xs *spec = xs_fmt("%s/queue/" "*.json", srv_basedir);
  2986. xs_list *list = xs_list_new();
  2987. time_t t = time(NULL);
  2988. xs_list *p;
  2989. const xs_val *v;
  2990. xs *fns = xs_glob(spec, 0, 0);
  2991. p = fns;
  2992. while (xs_list_iter(&p, &v)) {
  2993. /* get the retry time from the basename */
  2994. char *bn = strrchr(v, '/');
  2995. time_t t2 = atol(bn + 1);
  2996. if (t2 > t)
  2997. srv_debug(2, xs_fmt("queue not yet time for %s [%ld]", v, t));
  2998. else {
  2999. list = xs_list_append(list, v);
  3000. srv_debug(2, xs_fmt("queue ready for %s", v));
  3001. }
  3002. }
  3003. return list;
  3004. }
  3005. xs_dict *queue_get(const char *fn)
  3006. /* gets a file from a queue */
  3007. {
  3008. FILE *f;
  3009. xs_dict *obj = NULL;
  3010. if ((f = fopen(fn, "r")) != NULL) {
  3011. obj = xs_json_load(f);
  3012. fclose(f);
  3013. }
  3014. return obj;
  3015. }
  3016. xs_dict *dequeue(const char *fn)
  3017. /* dequeues a message */
  3018. {
  3019. xs_dict *obj = queue_get(fn);
  3020. unlink(fn);
  3021. return obj;
  3022. }
  3023. /** the purge **/
  3024. static int _purge_file(const char *fn, time_t mt)
  3025. /* purge fn if it's older than days */
  3026. {
  3027. int ret = 0;
  3028. if (mtime(fn) < mt) {
  3029. /* older than the minimum time: delete it */
  3030. unlink(fn);
  3031. srv_debug(2, xs_fmt("purged %s", fn));
  3032. ret = 1;
  3033. }
  3034. return ret;
  3035. }
  3036. static void _purge_dir(const char *dir, int days)
  3037. /* purges all files in a directory older than days */
  3038. {
  3039. int cnt = 0;
  3040. if (days) {
  3041. time_t mt = time(NULL) - days * 24 * 3600;
  3042. xs *spec = xs_fmt("%s/" "*", dir);
  3043. xs *list = xs_glob(spec, 0, 0);
  3044. xs_list *p;
  3045. const xs_str *v;
  3046. p = list;
  3047. while (xs_list_iter(&p, &v))
  3048. cnt += _purge_file(v, mt);
  3049. srv_debug(1, xs_fmt("purge: %s %d", dir, cnt));
  3050. }
  3051. }
  3052. static void _purge_user_subdir(snac *snac, const char *subdir, int days)
  3053. /* purges all files in a user subdir older than days */
  3054. {
  3055. xs *u_subdir = xs_fmt("%s/%s", snac->basedir, subdir);
  3056. _purge_dir(u_subdir, days);
  3057. }
  3058. void purge_server(void)
  3059. /* purge global server data */
  3060. {
  3061. xs *spec = xs_fmt("%s/object/??", srv_basedir);
  3062. xs *dirs = xs_glob(spec, 0, 0);
  3063. xs_list *p;
  3064. const xs_str *v;
  3065. int cnt = 0;
  3066. int icnt = 0;
  3067. time_t mt = time(NULL) - 7 * 24 * 3600;
  3068. p = dirs;
  3069. while (xs_list_iter(&p, &v)) {
  3070. xs_list *p2;
  3071. const xs_str *v2;
  3072. {
  3073. xs *spec2 = xs_fmt("%s/" "*.json", v);
  3074. xs *files = xs_glob(spec2, 0, 0);
  3075. p2 = files;
  3076. while (xs_list_iter(&p2, &v2)) {
  3077. int n_link;
  3078. /* old and with no hard links? */
  3079. if (mtime_nl(v2, &n_link) < mt && n_link < 2) {
  3080. xs *s1 = xs_replace(v2, ".json", "");
  3081. xs *l = xs_split(s1, "/");
  3082. const char *md5 = xs_list_get(l, -1);
  3083. object_del_by_md5(md5);
  3084. cnt++;
  3085. }
  3086. }
  3087. }
  3088. {
  3089. /* look for stray indexes */
  3090. xs *speci = xs_fmt("%s/" "*_?.idx", v);
  3091. xs *idxfs = xs_glob(speci, 0, 0);
  3092. p2 = idxfs;
  3093. while (xs_list_iter(&p2, &v2)) {
  3094. /* old enough to consider? */
  3095. if (mtime(v2) < mt) {
  3096. /* check if the indexed object is here */
  3097. xs *o = xs_dup(v2);
  3098. char *ext = strchr(o, '_');
  3099. if (ext) {
  3100. *ext = '\0';
  3101. o = xs_str_cat(o, ".json");
  3102. if (mtime(o) == 0.0) {
  3103. /* delete */
  3104. unlink(v2);
  3105. srv_debug(1, xs_fmt("purged %s", v2));
  3106. icnt++;
  3107. }
  3108. }
  3109. }
  3110. }
  3111. /* delete index backups */
  3112. xs *specb = xs_fmt("%s/" "*.bak", v);
  3113. xs *bakfs = xs_glob(specb, 0, 0);
  3114. p2 = bakfs;
  3115. while (xs_list_iter(&p2, &v2)) {
  3116. unlink(v2);
  3117. srv_debug(1, xs_fmt("purged %s", v2));
  3118. }
  3119. }
  3120. }
  3121. /* purge collected inboxes */
  3122. xs *ib_dir = xs_fmt("%s/inbox", srv_basedir);
  3123. _purge_dir(ib_dir, 7);
  3124. /* purge the instance timeline */
  3125. xs *itl_fn = xs_fmt("%s/public.idx", srv_basedir);
  3126. int itl_gc = index_gc(itl_fn);
  3127. /* purge tag indexes */
  3128. xs *tag_spec = xs_fmt("%s/tag/??", srv_basedir);
  3129. xs *tag_dirs = xs_glob(tag_spec, 0, 0);
  3130. p = tag_dirs;
  3131. int tag_gc = 0;
  3132. while (xs_list_iter(&p, &v)) {
  3133. xs *spec2 = xs_fmt("%s/" "*.idx", v);
  3134. xs *files = xs_glob(spec2, 0, 0);
  3135. xs_list *p2;
  3136. const xs_str *v2;
  3137. p2 = files;
  3138. while (xs_list_iter(&p2, &v2)) {
  3139. tag_gc += index_gc(v2);
  3140. xs *bak = xs_fmt("%s.bak", v2);
  3141. unlink(bak);
  3142. if (index_len(v2) == 0) {
  3143. /* there are no longer any entry with this tag;
  3144. purge it completely */
  3145. unlink(v2);
  3146. xs *dottag = xs_replace(v2, ".idx", ".tag");
  3147. unlink(dottag);
  3148. }
  3149. }
  3150. }
  3151. srv_debug(1, xs_fmt("purge: global "
  3152. "(obj: %d, idx: %d, itl: %d, tag: %d)", cnt, icnt, itl_gc, tag_gc));
  3153. }
  3154. void delete_purged_posts(snac *user, int days)
  3155. /* enqueues Delete activities for local purged messages */
  3156. {
  3157. if (days == 0)
  3158. return;
  3159. time_t mt = time(NULL) - days * 24 * 3600;
  3160. xs *spec = xs_fmt("%s/public/" "*.json", user->basedir);
  3161. xs *list = xs_glob(spec, 0, 0);
  3162. const char *v;
  3163. xs_list_foreach(list, v) {
  3164. if (mtime(v) < mt) {
  3165. /* to be purged; is it a Note by us? */
  3166. FILE *f;
  3167. if ((f = fopen(v, "r")) != NULL) {
  3168. xs *msg = xs_json_load(f);
  3169. fclose(f);
  3170. if (xs_is_dict(msg)) {
  3171. const char *id = xs_dict_get(msg, "id");
  3172. if (xs_is_string(id) && is_msg_mine(user, id)) {
  3173. xs *d_msg = msg_delete(user, id);
  3174. enqueue_message(user, d_msg);
  3175. snac_log(user, xs_fmt("enqueued Delete for purged message %s", id));
  3176. }
  3177. }
  3178. }
  3179. }
  3180. }
  3181. }
  3182. void purge_static(snac *user)
  3183. /* purges the static directory of a user */
  3184. {
  3185. xs *spec = xs_fmt("%s/static/""*", user->basedir);
  3186. xs *fns = xs_glob(spec, 1, 0);
  3187. xs *files = xs_dict_new();
  3188. const char *k, *v;
  3189. int cnt = 0;
  3190. /* fill a dict with the static resource urls */
  3191. xs_list_foreach(fns, v) {
  3192. if (strcmp(v, "style.css") == 0) {
  3193. snac_debug(user, 2, xs_fmt("purge_static: excluding '%s'", v));
  3194. continue;
  3195. }
  3196. xs *s = xs_fmt("%s/s/%s", user->actor, v);
  3197. xs *fn = xs_fmt("%s/static/%s", user->basedir, v);
  3198. struct stat st;
  3199. /* exclude non-files */
  3200. if (stat(fn, &st) == -1 || (st.st_mode & S_IFMT) != S_IFREG) {
  3201. snac_debug(user, 2, xs_fmt("purge_static: excluding non-file '%s'", v));
  3202. continue;
  3203. }
  3204. files = xs_dict_set(files, s, v);
  3205. cnt++;
  3206. }
  3207. /* don't purge avatars nor headers */
  3208. if (xs_is_string(v = xs_dict_get(user->config, "avatar")) && xs_dict_get(files, v)) {
  3209. files = xs_dict_del(files, v);
  3210. cnt--;
  3211. snac_debug(user, 2, xs_fmt("purge_static: excluding '%s'", v));
  3212. }
  3213. if (xs_is_string(v = xs_dict_get(user->config, "header")) && xs_dict_get(files, v)) {
  3214. files = xs_dict_del(files, v);
  3215. cnt--;
  3216. snac_debug(user, 2, xs_fmt("purge_static: excluding '%s'", v));
  3217. }
  3218. if (xs_is_string(v = xs_dict_get(srv_config, "favicon_url")) && xs_dict_get(files, v)) {
  3219. files = xs_dict_del(files, v);
  3220. cnt--;
  3221. snac_debug(user, 2, xs_fmt("purge_static: excluding '%s'", v));
  3222. }
  3223. /* exclude emojis served from the static directory */
  3224. xs *emo = emojis();
  3225. xs_dict_foreach(emo, k, v) {
  3226. if (xs_dict_get(files, v)) {
  3227. files = xs_dict_del(files, v);
  3228. cnt--;
  3229. snac_debug(user, 2, xs_fmt("purge_static: excluding '%s'", v));
  3230. }
  3231. }
  3232. if (cnt <= 0)
  3233. return;
  3234. xs *tl = timeline_simple_list(user, "public", 0, XS_ALL, NULL);
  3235. const char *md5;
  3236. xs_list_foreach(tl, md5) {
  3237. if (cnt <= 0)
  3238. break;
  3239. xs *msg = NULL;
  3240. if (!valid_status(object_get_by_md5(md5, &msg)))
  3241. continue;
  3242. if (!is_msg_mine(user, xs_dict_get_def(msg, "id", "")))
  3243. continue;
  3244. const xs_list *atts = xs_dict_get(msg, "attachment");
  3245. if (!xs_is_list(atts))
  3246. continue;
  3247. const xs_dict *d;
  3248. xs_list_foreach(atts, d) {
  3249. const char *url;
  3250. if (xs_is_dict(d) && xs_is_string(url = xs_dict_get(d, "url"))) {
  3251. if (xs_dict_get(files, url)) {
  3252. files = xs_dict_del(files, url);
  3253. cnt--;
  3254. snac_debug(user, 2, xs_fmt("purge_static: excluding '%s'", url));
  3255. xs *alt_text = xs_fmt("%s.txt", url);
  3256. if (xs_dict_get(files, alt_text)) {
  3257. files = xs_dict_del(files, alt_text);
  3258. cnt--;
  3259. snac_debug(user, 2, xs_fmt("purge_static: excluding alt_text '%s'", alt_text));
  3260. }
  3261. }
  3262. }
  3263. }
  3264. }
  3265. /* what is left in the files dict is not referenced anywhere */
  3266. xs_dict_foreach(files, k, v) {
  3267. xs *s = xs_fmt("%s/static/%s", user->basedir, v);
  3268. snac_debug(user, 1, xs_fmt("purge_static: %s", s));
  3269. unlink(s);
  3270. }
  3271. }
  3272. void purge_user(snac *snac)
  3273. /* do the purge for this user */
  3274. {
  3275. int priv_days, pub_days, user_days = 0;
  3276. const char *v;
  3277. int n;
  3278. priv_days = xs_number_get(xs_dict_get(srv_config, "timeline_purge_days"));
  3279. pub_days = xs_number_get(xs_dict_get(srv_config, "local_purge_days"));
  3280. if ((v = xs_dict_get(snac->config_o, "purge_days")) != NULL ||
  3281. (v = xs_dict_get(snac->config, "purge_days")) != NULL)
  3282. user_days = xs_number_get(v);
  3283. if (user_days) {
  3284. /* override admin settings only if they are lesser */
  3285. if (priv_days == 0 || user_days < priv_days)
  3286. priv_days = user_days;
  3287. if (pub_days == 0 || user_days < pub_days)
  3288. pub_days = user_days;
  3289. }
  3290. if (xs_is_true(xs_dict_get(srv_config, "propagate_local_purge")))
  3291. delete_purged_posts(snac, pub_days);
  3292. _purge_user_subdir(snac, "hidden", priv_days);
  3293. _purge_user_subdir(snac, "private", priv_days);
  3294. _purge_user_subdir(snac, "pending", priv_days);
  3295. _purge_user_subdir(snac, "public", pub_days);
  3296. const char *idxs[] = { "followers.idx", "private.idx", "public.idx",
  3297. "pinned.idx", "bookmark.idx", "draft.idx", "sched.idx", NULL };
  3298. for (n = 0; idxs[n]; n++) {
  3299. xs *idx = xs_fmt("%s/%s", snac->basedir, idxs[n]);
  3300. int gc = index_gc(idx);
  3301. srv_debug(1, xs_fmt("purge: %s %d", idx, gc));
  3302. }
  3303. /* purge lists */
  3304. {
  3305. xs *spec = xs_fmt("%s/list/" "*.idx", snac->basedir);
  3306. xs *lol = xs_glob(spec, 0, 0);
  3307. int c = 0;
  3308. const char *v;
  3309. while (xs_list_next(lol, &v, &c)) {
  3310. int gc = index_gc(v);
  3311. srv_debug(1, xs_fmt("purge: %s %d", v, gc));
  3312. }
  3313. }
  3314. /* purge static directories, if so desired */
  3315. if (xs_is_true(xs_dict_get(srv_config, "purge_static")))
  3316. purge_static(snac);
  3317. /* unrelated to purging, but it's a janitorial process, so what the hell */
  3318. verify_links(snac);
  3319. }
  3320. void purge_all(void)
  3321. /* purge all users */
  3322. {
  3323. snac snac;
  3324. xs *list = user_list();
  3325. char *p;
  3326. const char *uid;
  3327. p = list;
  3328. while (xs_list_iter(&p, &uid)) {
  3329. if (user_open(&snac, uid)) {
  3330. purge_user(&snac);
  3331. user_free(&snac);
  3332. }
  3333. }
  3334. purge_server();
  3335. #ifndef NO_MASTODON_API
  3336. mastoapi_purge();
  3337. #endif
  3338. }
  3339. /** archive **/
  3340. void srv_archive(const char *direction, const char *url, xs_dict *req,
  3341. const char *payload, int p_size,
  3342. int status, xs_dict *headers,
  3343. const char *body, int b_size)
  3344. /* archives a connection */
  3345. {
  3346. /* obsessive archiving */
  3347. xs *date = tid(0);
  3348. xs *dir = xs_fmt("%s/archive/%s_%s", srv_basedir, date, direction);
  3349. FILE *f;
  3350. if (mkdirx(dir) != -1) {
  3351. xs *meta_fn = xs_fmt("%s/_META", dir);
  3352. if ((f = fopen(meta_fn, "w")) != NULL) {
  3353. xs *j1 = xs_json_dumps(req, 4);
  3354. xs *j2 = xs_json_dumps(headers, 4);
  3355. fprintf(f, "dir: %s\n", direction);
  3356. if (url)
  3357. fprintf(f, "url: %s\n", url);
  3358. fprintf(f, "req: %s\n", j1);
  3359. fprintf(f, "p_size: %d\n", p_size);
  3360. fprintf(f, "status: %d\n", status);
  3361. fprintf(f, "response: %s\n", j2);
  3362. fprintf(f, "b_size: %d\n", b_size);
  3363. fclose(f);
  3364. }
  3365. if (p_size && payload) {
  3366. xs *payload_fn = NULL;
  3367. xs *payload_fn_raw = NULL;
  3368. const char *v = xs_dict_get(req, "content-type");
  3369. if (v && xs_str_in(v, "json") != -1) {
  3370. payload_fn = xs_fmt("%s/payload.json", dir);
  3371. if ((f = fopen(payload_fn, "w")) != NULL) {
  3372. xs *v1 = xs_json_loads(payload);
  3373. xs *j1 = NULL;
  3374. if (v1 != NULL)
  3375. j1 = xs_json_dumps(v1, 4);
  3376. if (j1 != NULL)
  3377. fwrite(j1, strlen(j1), 1, f);
  3378. else
  3379. fwrite(payload, p_size, 1, f);
  3380. fclose(f);
  3381. }
  3382. }
  3383. payload_fn_raw = xs_fmt("%s/payload", dir);
  3384. if ((f = fopen(payload_fn_raw, "w")) != NULL) {
  3385. fwrite(payload, p_size, 1, f);
  3386. fclose(f);
  3387. }
  3388. }
  3389. if (b_size && body) {
  3390. xs *body_fn = NULL;
  3391. const char *v = xs_dict_get(headers, "content-type");
  3392. if (v && xs_str_in(v, "json") != -1) {
  3393. body_fn = xs_fmt("%s/body.json", dir);
  3394. if ((f = fopen(body_fn, "w")) != NULL) {
  3395. xs *v1 = xs_json_loads(body);
  3396. xs *j1 = NULL;
  3397. if (v1 != NULL)
  3398. j1 = xs_json_dumps(v1, 4);
  3399. if (j1 != NULL)
  3400. fwrite(j1, strlen(j1), 1, f);
  3401. else
  3402. fwrite(body, b_size, 1, f);
  3403. fclose(f);
  3404. }
  3405. }
  3406. else {
  3407. body_fn = xs_fmt("%s/body", dir);
  3408. if ((f = fopen(body_fn, "w")) != NULL) {
  3409. fwrite(body, b_size, 1, f);
  3410. fclose(f);
  3411. }
  3412. }
  3413. }
  3414. }
  3415. }
  3416. void srv_archive_error(const char *prefix, const xs_str *err,
  3417. const xs_dict *req, const xs_val *data)
  3418. /* archives an error */
  3419. {
  3420. xs *ntid = tid(0);
  3421. xs *fn = xs_fmt("%s/error/%s_%s", srv_basedir, ntid, prefix);
  3422. FILE *f;
  3423. if ((f = fopen(fn, "w")) != NULL) {
  3424. fprintf(f, "Error: %s\n", err);
  3425. if (req) {
  3426. fprintf(f, "Request headers:\n");
  3427. xs_json_dump(req, 4, f);
  3428. fprintf(f, "\n");
  3429. }
  3430. if (data) {
  3431. fprintf(f, "Data:\n");
  3432. if (xs_type(data) == XSTYPE_LIST || xs_type(data) == XSTYPE_DICT) {
  3433. xs_json_dump(data, 4, f);
  3434. }
  3435. else
  3436. fprintf(f, "%s", data);
  3437. fprintf(f, "\n");
  3438. }
  3439. fclose(f);
  3440. }
  3441. }
  3442. void srv_archive_qitem(const char *prefix, xs_dict *q_item)
  3443. /* archives a q_item in the error folder */
  3444. {
  3445. xs *ntid = tid(0);
  3446. xs *fn = xs_fmt("%s/error/%s_qitem_%s", srv_basedir, ntid, prefix);
  3447. FILE *f;
  3448. if ((f = fopen(fn, "w")) != NULL) {
  3449. xs_json_dump(q_item, 4, f);
  3450. fclose(f);
  3451. }
  3452. }
  3453. t_announcement *announcement(const double after)
  3454. /* returns announcement text or NULL if none exists or it is olde than "after" */
  3455. {
  3456. static const long int MAX_SIZE = 2048;
  3457. static t_announcement a = {
  3458. .text = NULL,
  3459. .timestamp = 0.0,
  3460. };
  3461. static xs_str *fn = NULL;
  3462. if (fn == NULL)
  3463. fn = xs_fmt("%s/announcement.txt", srv_basedir);
  3464. const double ts = mtime(fn);
  3465. /* file does not exist or other than what was requested */
  3466. if (ts == 0.0 || ts <= after)
  3467. return NULL;
  3468. /* nothing changed, just return the current announcement */
  3469. if (a.text != NULL && ts <= a.timestamp)
  3470. return &a;
  3471. /* read and store new announcement */
  3472. FILE *f;
  3473. if ((f = fopen(fn, "r")) != NULL) {
  3474. fseek (f, 0, SEEK_END);
  3475. const long int length = ftell(f);
  3476. if (length > MAX_SIZE) {
  3477. /* this is probably unintentional */
  3478. srv_log(xs_fmt("announcement.txt too big: %ld bytes, max is %ld, ignoring.", length, MAX_SIZE));
  3479. }
  3480. else
  3481. if (length > 0) {
  3482. fseek (f, 0, SEEK_SET);
  3483. char *buffer = malloc(length + 1);
  3484. if (buffer) {
  3485. fread(buffer, 1, length, f);
  3486. buffer[length] = '\0';
  3487. free(a.text);
  3488. a.text = buffer;
  3489. a.timestamp = ts;
  3490. }
  3491. else {
  3492. srv_log("Error allocating memory for announcement");
  3493. }
  3494. }
  3495. else {
  3496. /* an empty file means no announcement */
  3497. free(a.text);
  3498. a.text = NULL;
  3499. a.timestamp = 0.0;
  3500. }
  3501. fclose (f);
  3502. }
  3503. if (a.text != NULL)
  3504. return &a;
  3505. return NULL;
  3506. }
  3507. xs_str *make_url(const char *href, const char *proxy, int by_token)
  3508. /* makes an URL, possibly including proxying */
  3509. {
  3510. xs_str *url = NULL;
  3511. if (proxy && !xs_startswith(href, srv_baseurl)) {
  3512. xs *p = NULL;
  3513. if (by_token) {
  3514. xs *tks = xs_fmt("%s:%s", srv_proxy_token_seed, proxy);
  3515. xs *tk = xs_md5_hex(tks, strlen(tks));
  3516. p = xs_fmt("%s/y/%s/", proxy, tk);
  3517. }
  3518. else
  3519. p = xs_fmt("%s/x/", proxy);
  3520. url = xs_replace(href, "https:/" "/", p);
  3521. }
  3522. else
  3523. url = xs_dup(href);
  3524. return url;
  3525. }
  3526. /** bad login throttle **/
  3527. xs_str *_badlogin_fn(const char *addr)
  3528. {
  3529. xs *md5 = xs_md5_hex(addr, strlen(addr));
  3530. xs *dir = xs_fmt("%s/badlogin", srv_basedir);
  3531. mkdirx(dir);
  3532. return xs_fmt("%s/%s", dir, md5);
  3533. }
  3534. int _badlogin_read(const char *fn, int *failures)
  3535. /* reads a badlogin file */
  3536. {
  3537. int ok = 0;
  3538. FILE *f;
  3539. pthread_mutex_lock(&data_mutex);
  3540. if ((f = fopen(fn, "r")) != NULL) {
  3541. xs *l = xs_readline(f);
  3542. fclose(f);
  3543. if (sscanf(l, "%d", failures) == 1)
  3544. ok = 1;
  3545. }
  3546. pthread_mutex_unlock(&data_mutex);
  3547. return ok;
  3548. }
  3549. int badlogin_check(const char *user, const char *addr)
  3550. /* checks if this address is authorized to try a login */
  3551. {
  3552. int valid = 1;
  3553. if (xs_type(addr) == XSTYPE_STRING) {
  3554. xs *fn = _badlogin_fn(addr);
  3555. double mt = mtime(fn);
  3556. if (mt > 0) {
  3557. int badlogin_expire = xs_number_get(xs_dict_get_def(srv_config,
  3558. "badlogin_expire", "300"));
  3559. mt += badlogin_expire;
  3560. /* if file is expired, delete and give pass */
  3561. if (mt < time(NULL)) {
  3562. srv_debug(1, xs_fmt("Login from %s for %s allowed again", addr, user));
  3563. unlink(fn);
  3564. }
  3565. else {
  3566. int failures;
  3567. if (_badlogin_read(fn, &failures)) {
  3568. int badlogin_max = xs_number_get(xs_dict_get_def(srv_config,
  3569. "badlogin_retries", "5"));
  3570. if (failures >= badlogin_max) {
  3571. valid = 0;
  3572. xs *d = xs_str_iso_date((time_t) mt);
  3573. srv_debug(1,
  3574. xs_fmt("Login from %s for %s forbidden until %s", addr, user, d));
  3575. }
  3576. }
  3577. }
  3578. }
  3579. }
  3580. return valid;
  3581. }
  3582. void badlogin_inc(const char *user, const char *addr)
  3583. /* increments a bad login from this address */
  3584. {
  3585. if (xs_type(addr) == XSTYPE_STRING) {
  3586. int failures = 0;
  3587. xs *fn = _badlogin_fn(addr);
  3588. FILE *f;
  3589. _badlogin_read(fn, &failures);
  3590. pthread_mutex_lock(&data_mutex);
  3591. if ((f = fopen(fn, "w")) != NULL) {
  3592. failures++;
  3593. fprintf(f, "%d %s %s\n", failures, addr, user);
  3594. fclose(f);
  3595. srv_log(xs_fmt("Registered %d login failure(s) from %s for %s", failures, addr, user));
  3596. }
  3597. pthread_mutex_unlock(&data_mutex);
  3598. }
  3599. }
  3600. /** language strings **/
  3601. const char *lang_str(const char *str, const snac *user)
  3602. /* returns a translated string */
  3603. {
  3604. const char *n_str = str;
  3605. if (user && xs_is_dict(user->lang) && xs_is_string(str)) {
  3606. n_str = xs_dict_get(user->lang, str);
  3607. if (xs_is_null(n_str) || *n_str == '\0')
  3608. n_str = str;
  3609. }
  3610. return n_str;
  3611. }
  3612. /** integrity checks **/
  3613. void data_fsck(void)
  3614. {
  3615. xs *list = user_list();
  3616. const char *uid;
  3617. xs_list_foreach(list, uid) {
  3618. snac user;
  3619. if (!user_open(&user, uid))
  3620. continue;
  3621. {
  3622. /* iterate all private posts and check that non-public posts
  3623. from this user are also linked into the public directory,
  3624. to avoid the don't-fucking-delete-my-own-private-posts purge bug */
  3625. xs *priv_spec = xs_fmt("%s/private/""*.json", user.basedir);
  3626. xs *posts = xs_glob(priv_spec, 0, 0);
  3627. const char *priv_fn;
  3628. xs_list_foreach(posts, priv_fn) {
  3629. xs *pub_fn = xs_replace(priv_fn, "/private/", "/public/");
  3630. /* already there? look no more */
  3631. if (mtime(pub_fn))
  3632. continue;
  3633. /* read the post */
  3634. FILE *f;
  3635. if ((f = fopen(priv_fn, "r")) == NULL)
  3636. continue;
  3637. xs *post = xs_json_load(f);
  3638. fclose(f);
  3639. if (!xs_is_dict(post))
  3640. continue;
  3641. const char *attr_to = get_atto(post);
  3642. if (!xs_is_string(attr_to) || strcmp(attr_to, user.actor) != 0) {
  3643. /* not from this user */
  3644. continue;
  3645. }
  3646. /* link */
  3647. snac_debug(&user, 1, xs_fmt("fsck: fixed missing link %s", xs_dict_get(post, "id")));
  3648. link(priv_fn, pub_fn);
  3649. }
  3650. }
  3651. user_free(&user);
  3652. }
  3653. }