data.c 94 KB

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