data.c 92 KB

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