mastoapi.c 166 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 - 2026 grunfink et al. / MIT license */
  3. #ifndef NO_MASTODON_API
  4. #include "xs.h"
  5. #include "xs_hex.h"
  6. #include "xs_openssl.h"
  7. #include "xs_json.h"
  8. #include "xs_io.h"
  9. #include "xs_time.h"
  10. #include "xs_glob.h"
  11. #include "xs_set.h"
  12. #include "xs_random.h"
  13. #include "xs_url.h"
  14. #include "xs_mime.h"
  15. #include "xs_match.h"
  16. #include "xs_unicode.h"
  17. #include "xs_http.h"
  18. #include "snac.h"
  19. #include <sys/time.h>
  20. static xs_str *random_str(void)
  21. /* just what is says in the tin */
  22. {
  23. unsigned int data[4] = {0};
  24. xs_rnd_buf(data, sizeof(data));
  25. return xs_hex_enc((char *)data, sizeof(data));
  26. }
  27. int app_add(const char *id, const xs_dict *app)
  28. /* stores an app */
  29. {
  30. if (!xs_is_hex(id))
  31. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  32. int status = HTTP_STATUS_CREATED;
  33. xs *fn = xs_fmt("%s/app/", srv_basedir);
  34. FILE *f;
  35. mkdirx(fn);
  36. fn = xs_str_cat(fn, id);
  37. fn = xs_str_cat(fn, ".json");
  38. if ((f = fopen(fn, "w")) != NULL) {
  39. xs_json_dump(app, 4, f);
  40. fclose(f);
  41. }
  42. else
  43. status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
  44. return status;
  45. }
  46. xs_str *_app_fn(const char *id)
  47. {
  48. return xs_fmt("%s/app/%s.json", srv_basedir, id);
  49. }
  50. xs_dict *app_get(const char *id)
  51. /* gets an app */
  52. {
  53. if (!xs_is_hex(id))
  54. return NULL;
  55. xs *fn = _app_fn(id);
  56. xs_dict *app = NULL;
  57. FILE *f;
  58. if ((f = fopen(fn, "r")) != NULL) {
  59. app = xs_json_load(f);
  60. fclose(f);
  61. }
  62. return app;
  63. }
  64. int app_del(const char *id)
  65. /* deletes an app */
  66. {
  67. if (!xs_is_hex(id))
  68. return -1;
  69. xs *fn = _app_fn(id);
  70. return unlink(fn);
  71. }
  72. int token_add(const char *id, const xs_dict *token)
  73. /* stores a token */
  74. {
  75. if (!xs_is_hex(id))
  76. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  77. int status = HTTP_STATUS_CREATED;
  78. xs *fn = xs_fmt("%s/token/", srv_basedir);
  79. FILE *f;
  80. mkdirx(fn);
  81. fn = xs_str_cat(fn, id);
  82. fn = xs_str_cat(fn, ".json");
  83. if ((f = fopen(fn, "w")) != NULL) {
  84. xs_json_dump(token, 4, f);
  85. fclose(f);
  86. }
  87. else
  88. status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
  89. return status;
  90. }
  91. xs_dict *token_get(const char *id)
  92. /* gets a token */
  93. {
  94. if (!xs_is_hex(id))
  95. return NULL;
  96. xs *fn = xs_fmt("%s/token/%s.json", srv_basedir, id);
  97. xs_dict *token = NULL;
  98. FILE *f;
  99. if ((f = fopen(fn, "r")) != NULL) {
  100. token = xs_json_load(f);
  101. fclose(f);
  102. /* 'touch' the file */
  103. utimes(fn, NULL);
  104. /* also 'touch' the app */
  105. const char *app_id = xs_dict_get(token, "client_id");
  106. if (app_id) {
  107. xs *afn = xs_fmt("%s/app/%s.json", srv_basedir, app_id);
  108. utimes(afn, NULL);
  109. }
  110. }
  111. return token;
  112. }
  113. int token_del(const char *id)
  114. /* deletes a token */
  115. {
  116. if (!xs_is_hex(id))
  117. return -1;
  118. xs *fn = xs_fmt("%s/token/%s.json", srv_basedir, id);
  119. return unlink(fn);
  120. }
  121. const char * const login_page = ""
  122. "<!DOCTYPE html>\n"
  123. "<html>\n"
  124. "<head>\n"
  125. "<title>%s OAuth - Snac2</title>\n"
  126. "<meta content=\"width=device-width, initial-scale=1, minimum-scale=1, user-scalable=no\" name=\"viewport\">"
  127. "<style>:root {color-scheme: light dark}</style>\n"
  128. "</head>\n"
  129. "<body><h1>%s OAuth identify</h1>\n"
  130. "<div style=\"background-color: red; color: white\">%s</div>\n"
  131. "<form method=\"post\" action=\"%s:/" "/%s/%s\">\n"
  132. "<p>Login: <input type=\"text\" name=\"login\" autocapitalize=\"off\"></p>\n"
  133. "<p>Password: <input type=\"password\" name=\"passwd\"></p>\n"
  134. "<input type=\"hidden\" name=\"redir\" value=\"%s\">\n"
  135. "<input type=\"hidden\" name=\"cid\" value=\"%s\">\n"
  136. "<input type=\"hidden\" name=\"state\" value=\"%s\">\n"
  137. "<input type=\"submit\" value=\"OK\">\n"
  138. "</form><p>%s</p></body></html>\n"
  139. "";
  140. int oauth_get_handler(const xs_dict *req, const char *q_path,
  141. char **body, int *b_size, char **ctype)
  142. {
  143. (void)b_size;
  144. if (!xs_startswith(q_path, "/oauth/"))
  145. return 0;
  146. int status = HTTP_STATUS_NOT_FOUND;
  147. const xs_dict *msg = xs_dict_get(req, "q_vars");
  148. xs *cmd = xs_replace_n(q_path, "/oauth", "", 1);
  149. srv_debug(1, xs_fmt("oauth_get_handler %s", q_path));
  150. if (strcmp(cmd, "/authorize") == 0) { /** **/
  151. const char *cid = xs_dict_get(msg, "client_id");
  152. const char *ruri = xs_dict_get(msg, "redirect_uri");
  153. const char *rtype = xs_dict_get(msg, "response_type");
  154. const char *state = xs_dict_get(msg, "state");
  155. status = HTTP_STATUS_BAD_REQUEST;
  156. if (cid && ruri && rtype && strcmp(rtype, "code") == 0) {
  157. xs *app = app_get(cid);
  158. if (app != NULL) {
  159. const char *host = xs_dict_get(srv_config, "host");
  160. const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
  161. if (xs_is_null(state))
  162. state = "";
  163. *body = xs_fmt(login_page, host, host, "", proto, host, "oauth/x-snac-login",
  164. ruri, cid, state, USER_AGENT);
  165. *ctype = "text/html";
  166. status = HTTP_STATUS_OK;
  167. srv_debug(1, xs_fmt("oauth authorize: generating login page"));
  168. }
  169. else
  170. srv_debug(1, xs_fmt("oauth authorize: bad client_id %s", cid));
  171. }
  172. else
  173. srv_debug(1, xs_fmt("oauth authorize: invalid or unset arguments"));
  174. }
  175. else
  176. if (strcmp(cmd, "/x-snac-get-token") == 0) { /** **/
  177. const char *host = xs_dict_get(srv_config, "host");
  178. const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
  179. *body = xs_fmt(login_page, host, host, "", proto, host, "oauth/x-snac-get-token",
  180. "", "", "", USER_AGENT);
  181. *ctype = "text/html";
  182. status = HTTP_STATUS_OK;
  183. }
  184. return status;
  185. }
  186. int oauth_post_handler(const xs_dict *req, const char *q_path,
  187. const char *payload, int p_size,
  188. char **body, int *b_size, char **ctype)
  189. {
  190. (void)p_size;
  191. (void)b_size;
  192. if (!xs_startswith(q_path, "/oauth/"))
  193. return 0;
  194. int status = HTTP_STATUS_NOT_FOUND;
  195. const char *i_ctype = xs_dict_get(req, "content-type");
  196. xs *args = NULL;
  197. if (i_ctype && xs_startswith(i_ctype, "application/json")) {
  198. if (!xs_is_null(payload))
  199. args = xs_json_loads(payload);
  200. }
  201. else
  202. if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded") && payload) {
  203. args = xs_url_vars(payload);
  204. }
  205. else
  206. args = xs_dup(xs_dict_get(req, "p_vars"));
  207. if (args == NULL)
  208. return HTTP_STATUS_BAD_REQUEST;
  209. xs *cmd = xs_replace_n(q_path, "/oauth", "", 1);
  210. srv_debug(1, xs_fmt("oauth_post_handler %s", q_path));
  211. if (strcmp(cmd, "/x-snac-login") == 0) { /** **/
  212. const char *login = xs_dict_get(args, "login");
  213. const char *passwd = xs_dict_get(args, "passwd");
  214. const char *redir = xs_dict_get(args, "redir");
  215. const char *cid = xs_dict_get(args, "cid");
  216. const char *state = xs_dict_get(args, "state");
  217. const char *host = xs_dict_get(srv_config, "host");
  218. const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
  219. /* by default, generate another login form with an error */
  220. *body = xs_fmt(login_page, host, host, "LOGIN INCORRECT", proto, host, "oauth/x-snac-login",
  221. redir, cid, state, USER_AGENT);
  222. *ctype = "text/html";
  223. status = HTTP_STATUS_OK;
  224. if (login && passwd && redir && cid) {
  225. snac snac;
  226. if (user_open(&snac, login)) {
  227. const char *addr = xs_or(xs_dict_get(req, "remote-addr"),
  228. xs_dict_get(req, "x-forwarded-for"));
  229. if (badlogin_check(login, addr)) {
  230. /* check the login + password */
  231. if (check_password(login, passwd, xs_dict_get(snac.config, "passwd"))) {
  232. /* success! redirect to the desired uri */
  233. xs *code = random_str();
  234. xs_free(*body);
  235. if (strcmp(redir, "urn:ietf:wg:oauth:2.0:oob") == 0) {
  236. *body = xs_dup(code);
  237. }
  238. else {
  239. if (xs_str_in(redir, "?") != -1)
  240. *body = xs_fmt("%s&code=%s", redir, code);
  241. else
  242. *body = xs_fmt("%s?code=%s", redir, code);
  243. status = HTTP_STATUS_SEE_OTHER;
  244. }
  245. /* if there is a state, add it */
  246. if (!xs_is_null(state) && *state) {
  247. *body = xs_str_cat(*body, "&state=");
  248. *body = xs_str_cat(*body, state);
  249. }
  250. srv_log(xs_fmt("oauth x-snac-login: '%s' success, redirect to %s",
  251. login, *body));
  252. /* assign the login to the app */
  253. xs *app = app_get(cid);
  254. if (app != NULL) {
  255. app = xs_dict_set(app, "uid", login);
  256. app = xs_dict_set(app, "code", code);
  257. app_add(cid, app);
  258. }
  259. else
  260. srv_log(xs_fmt("oauth x-snac-login: error getting app %s", cid));
  261. }
  262. else {
  263. srv_debug(1, xs_fmt("oauth x-snac-login: login '%s' incorrect", login));
  264. badlogin_inc(login, addr);
  265. }
  266. }
  267. user_free(&snac);
  268. }
  269. else
  270. srv_debug(1, xs_fmt("oauth x-snac-login: bad user '%s'", login));
  271. }
  272. else
  273. srv_debug(1, xs_fmt("oauth x-snac-login: invalid or unset arguments"));
  274. }
  275. else
  276. if (strcmp(cmd, "/token") == 0) { /** **/
  277. xs *wrk = NULL;
  278. xs *codewrk = NULL;
  279. const char *gtype = xs_dict_get(args, "grant_type");
  280. const char *code = xs_dict_get(args, "code");
  281. const char *cid = xs_dict_get(args, "client_id");
  282. const char *csec = xs_dict_get(args, "client_secret");
  283. const char *ruri = xs_dict_get(args, "redirect_uri");
  284. const char *scope = xs_dict_get(args, "scope");
  285. /* no client_secret? check if it's inside an authorization header
  286. (AndStatus does it this way) */
  287. if (xs_is_null(csec)) {
  288. const char *auhdr = xs_dict_get(req, "authorization");
  289. if (!xs_is_null(auhdr) && xs_startswith(auhdr, "Basic ")) {
  290. xs *s1 = xs_replace_n(auhdr, "Basic ", "", 1);
  291. int size;
  292. xs *s2 = xs_base64_dec(s1, &size);
  293. if (!xs_is_null(s2)) {
  294. xs *l1 = xs_split(s2, ":");
  295. if (xs_list_len(l1) == 2) {
  296. wrk = xs_dup(xs_list_get(l1, 1));
  297. csec = wrk;
  298. }
  299. }
  300. }
  301. }
  302. /* no code?
  303. I'm not sure of the impacts of this right now, but Subway Tooter does not
  304. provide a code so one must be generated */
  305. if (xs_is_null(code)){
  306. code = codewrk = random_str();
  307. }
  308. if (gtype && code && cid && csec && ruri) {
  309. xs *app = app_get(cid);
  310. if (app == NULL) {
  311. status = HTTP_STATUS_UNAUTHORIZED;
  312. srv_log(xs_fmt("oauth token: invalid app %s", cid));
  313. }
  314. else
  315. if (strcmp(csec, xs_dict_get(app, "client_secret")) != 0) {
  316. status = HTTP_STATUS_UNAUTHORIZED;
  317. srv_log(xs_fmt("oauth token: invalid client_secret for app %s", cid));
  318. }
  319. else {
  320. xs *rsp = xs_dict_new();
  321. xs *cat = xs_number_new(time(NULL));
  322. xs *tokid = random_str();
  323. rsp = xs_dict_append(rsp, "access_token", tokid);
  324. rsp = xs_dict_append(rsp, "token_type", "Bearer");
  325. rsp = xs_dict_append(rsp, "created_at", cat);
  326. if (!xs_is_null(scope))
  327. rsp = xs_dict_append(rsp, "scope", scope);
  328. else
  329. rsp = xs_dict_append(rsp, "scope", "");
  330. const char *uid = xs_dict_get(app, "uid");
  331. if (xs_is_string(uid)) {
  332. srv_debug(1, xs_fmt("oauth token: "
  333. "successful login for %s, new token %s", uid, tokid));
  334. xs *token = xs_dict_new();
  335. token = xs_dict_append(token, "token", tokid);
  336. token = xs_dict_append(token, "client_id", cid);
  337. token = xs_dict_append(token, "client_secret", csec);
  338. token = xs_dict_append(token, "uid", uid);
  339. token = xs_dict_append(token, "code", code);
  340. token_add(tokid, token);
  341. *body = xs_json_dumps(rsp, 4);
  342. *ctype = "application/json";
  343. status = HTTP_STATUS_OK;
  344. }
  345. else {
  346. srv_debug(1, xs_fmt("oauth token: invalid uid"));
  347. app_del(cid);
  348. status = HTTP_STATUS_BAD_REQUEST;
  349. }
  350. }
  351. }
  352. else {
  353. srv_debug(1, xs_fmt("oauth token: invalid or unset arguments"));
  354. status = HTTP_STATUS_BAD_REQUEST;
  355. }
  356. }
  357. else
  358. if (strcmp(cmd, "/revoke") == 0) { /** **/
  359. const char *cid = xs_dict_get(args, "client_id");
  360. const char *csec = xs_dict_get(args, "client_secret");
  361. const char *tokid = xs_dict_get(args, "token");
  362. if (cid && csec && tokid) {
  363. xs *token = token_get(tokid);
  364. *body = xs_str_new("{}");
  365. *ctype = "application/json";
  366. if (token == NULL || strcmp(csec, xs_dict_get(token, "client_secret")) != 0) {
  367. srv_debug(1, xs_fmt("oauth revoke: bad secret for token %s", tokid));
  368. status = HTTP_STATUS_FORBIDDEN;
  369. }
  370. else {
  371. token_del(tokid);
  372. srv_debug(1, xs_fmt("oauth revoke: revoked token %s", tokid));
  373. status = HTTP_STATUS_OK;
  374. /* also delete the app, as it serves no purpose from now on */
  375. app_del(cid);
  376. }
  377. }
  378. else {
  379. srv_debug(1, xs_fmt("oauth revoke: invalid or unset arguments"));
  380. status = HTTP_STATUS_FORBIDDEN;
  381. }
  382. }
  383. if (strcmp(cmd, "/x-snac-get-token") == 0) { /** **/
  384. const char *login = xs_dict_get(args, "login");
  385. const char *passwd = xs_dict_get(args, "passwd");
  386. const char *host = xs_dict_get(srv_config, "host");
  387. const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
  388. /* by default, generate another login form with an error */
  389. *body = xs_fmt(login_page, host, host, "LOGIN INCORRECT", proto, host, "oauth/x-snac-get-token",
  390. "", "", "", USER_AGENT);
  391. *ctype = "text/html";
  392. status = HTTP_STATUS_OK;
  393. if (login && passwd) {
  394. snac user;
  395. if (user_open(&user, login)) {
  396. const char *addr = xs_or(xs_dict_get(req, "remote-addr"),
  397. xs_dict_get(req, "x-forwarded-for"));
  398. if (badlogin_check(login, addr)) {
  399. /* check the login + password */
  400. if (check_password(login, passwd, xs_dict_get(user.config, "passwd"))) {
  401. /* success! create a new token */
  402. xs *tokid = random_str();
  403. srv_debug(1, xs_fmt("x-snac-new-token: "
  404. "successful login for %s, new token %s", login, tokid));
  405. xs *token = xs_dict_new();
  406. token = xs_dict_append(token, "token", tokid);
  407. token = xs_dict_append(token, "client_id", "snac-client");
  408. token = xs_dict_append(token, "client_secret", "");
  409. token = xs_dict_append(token, "uid", login);
  410. token = xs_dict_append(token, "code", "");
  411. token_add(tokid, token);
  412. *ctype = "text/plain";
  413. xs_free(*body);
  414. *body = xs_dup(tokid);
  415. }
  416. else
  417. badlogin_inc(login, addr);
  418. user_free(&user);
  419. }
  420. }
  421. }
  422. }
  423. return status;
  424. }
  425. xs_str *mastoapi_id(const xs_dict *msg)
  426. /* returns a somewhat Mastodon-compatible status id */
  427. {
  428. const char *id = xs_dict_get(msg, "id");
  429. xs *md5 = xs_md5_hex(id, strlen(id));
  430. return xs_fmt("%10.0f%s", object_ctime_by_md5(md5), md5);
  431. }
  432. #define MID_TO_MD5(id) (id + 10)
  433. static xs_val *get_count_from_actor(const xs_dict *actor, const char *field_names[], const char *collection_url_field)
  434. /* helper to extract count from actor dict using various field name variations or from cached collection */
  435. {
  436. xs_val *count = NULL;
  437. /* try direct field name variations first */
  438. for (int i = 0; field_names[i] && xs_type(count) != XSTYPE_NUMBER; i++) {
  439. const xs_number *val = xs_dict_get(actor, field_names[i]);
  440. if (xs_type(val) == XSTYPE_NUMBER)
  441. count = xs_dup(val);
  442. }
  443. /* if not found directly, try to get from cached collection object */
  444. if (xs_type(count) != XSTYPE_NUMBER) {
  445. const char *url = xs_dict_get(actor, collection_url_field);
  446. if (!xs_is_null(url)) {
  447. xs *coll = NULL;
  448. if (valid_status(object_get(url, &coll))) {
  449. const xs_number *total = xs_dict_get(coll, "totalItems");
  450. if (xs_type(total) == XSTYPE_NUMBER)
  451. count = xs_dup(total);
  452. }
  453. }
  454. }
  455. return count;
  456. }
  457. static const xs_list *get_collection_items(snac *snac, const char *collection_url,
  458. xs_dict **out_collection, xs_dict **out_page)
  459. /* fetches items from an ActivityPub collection (outbox, etc) with minimal HTTP requests */
  460. {
  461. const xs_list *items = NULL;
  462. xs_dict *collection = NULL;
  463. if (valid_status(activitypub_request(snac, collection_url, &collection))) {
  464. /* check if items are directly embedded */
  465. items = xs_dict_get(collection, "orderedItems");
  466. if (xs_is_null(items))
  467. items = xs_dict_get(collection, "items");
  468. if (!xs_is_null(items)) {
  469. /* items found in main collection - transfer ownership to keep items valid */
  470. if (out_collection)
  471. *out_collection = collection;
  472. return items;
  473. }
  474. /* if no items, try fetching first page (only 1 extra request) */
  475. const char *first_url = xs_dict_get(collection, "first");
  476. if (!xs_is_null(first_url)) {
  477. xs_dict *first_page = NULL;
  478. if (valid_status(activitypub_request(snac, first_url, &first_page))) {
  479. items = xs_dict_get(first_page, "orderedItems");
  480. if (xs_is_null(items))
  481. items = xs_dict_get(first_page, "items");
  482. if (!xs_is_null(items)) {
  483. /* items found in first page - transfer ownership to keep items valid */
  484. if (out_page)
  485. *out_page = first_page;
  486. xs_free(collection);
  487. return items;
  488. }
  489. xs_free(first_page);
  490. }
  491. }
  492. xs_free(collection);
  493. }
  494. return NULL;
  495. }
  496. static const xs_dict *extract_post_from_item(const xs_val *item)
  497. /* extracts the post object from an outbox item, handling Create/Announce wrappers */
  498. {
  499. if (xs_type(item) != XSTYPE_DICT)
  500. return NULL;
  501. const char *item_type = xs_dict_get(item, "type");
  502. const xs_dict *post = item;
  503. /* if it's an activity, try to get embedded object */
  504. if (!xs_is_null(item_type) &&
  505. (strcmp(item_type, "Create") == 0 || strcmp(item_type, "Announce") == 0)) {
  506. const xs_val *obj = xs_dict_get(item, "object");
  507. /* only use embedded objects, skip URL references (would need HTTP fetch) */
  508. if (!xs_is_null(obj) && xs_type(obj) == XSTYPE_DICT)
  509. post = obj;
  510. else
  511. return NULL;
  512. }
  513. return post;
  514. }
  515. static int is_valid_post_type(const char *post_type)
  516. /* checks if a type is a valid post type for timeline display */
  517. {
  518. return !xs_is_null(post_type) &&
  519. (strcmp(post_type, "Note") == 0 ||
  520. strcmp(post_type, "Article") == 0 ||
  521. strcmp(post_type, "Question") == 0 ||
  522. strcmp(post_type, "Page") == 0);
  523. }
  524. xs_dict *mastoapi_account(snac *logged, const xs_dict *actor)
  525. /* converts an ActivityPub actor to a Mastodon account */
  526. {
  527. const char *id = xs_dict_get(actor, "id");
  528. const char *pub = xs_dict_get(actor, "published");
  529. const char *proxy = NULL;
  530. if (xs_type(id) != XSTYPE_STRING)
  531. return NULL;
  532. if (logged && xs_is_true(xs_dict_get(srv_config, "proxy_media")))
  533. proxy = logged->actor;
  534. const char *prefu = xs_dict_get(actor, "preferredUsername");
  535. const char *display_name = xs_dict_get(actor, "name");
  536. if (xs_is_null(display_name) || *display_name == '\0')
  537. display_name = prefu;
  538. xs_dict *acct = xs_dict_new();
  539. xs *acct_md5 = xs_md5_hex(id, strlen(id));
  540. acct = xs_dict_append(acct, "id", acct_md5);
  541. acct = xs_dict_append(acct, "username", prefu);
  542. acct = xs_dict_append(acct, "display_name", display_name);
  543. acct = xs_dict_append(acct, "discoverable", xs_stock(XSTYPE_TRUE));
  544. acct = xs_dict_append(acct, "group", xs_stock(XSTYPE_FALSE));
  545. acct = xs_dict_append(acct, "hide_collections", xs_stock(XSTYPE_FALSE));
  546. acct = xs_dict_append(acct, "indexable", xs_stock(XSTYPE_TRUE));
  547. acct = xs_dict_append(acct, "noindex", xs_stock(XSTYPE_FALSE));
  548. acct = xs_dict_append(acct, "roles", xs_stock(XSTYPE_LIST));
  549. {
  550. /* create the acct field as user@host */
  551. xs *l = xs_split(id, "/");
  552. xs *fquid = xs_fmt("%s@%s", prefu, xs_list_get(l, 2));
  553. acct = xs_dict_append(acct, "acct", fquid);
  554. }
  555. if (pub)
  556. acct = xs_dict_append(acct, "created_at", pub);
  557. else {
  558. /* unset created_at crashes Tusky, so lie like a mf */
  559. xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
  560. acct = xs_dict_append(acct, "created_at", date);
  561. }
  562. xs *last_status_at = xs_str_utctime(0, "%Y-%m-%d");
  563. acct = xs_dict_append(acct, "last_status_at", last_status_at);
  564. const char *note = xs_dict_get(actor, "summary");
  565. if (xs_is_null(note))
  566. note = "";
  567. if (strcmp(xs_dict_get(actor, "type"), "Service") == 0)
  568. acct = xs_dict_append(acct, "bot", xs_stock(XSTYPE_TRUE));
  569. else
  570. acct = xs_dict_append(acct, "bot", xs_stock(XSTYPE_FALSE));
  571. acct = xs_dict_append(acct, "note", note);
  572. acct = xs_dict_append(acct, "url", id);
  573. acct = xs_dict_append(acct, "uri", id);
  574. xs *avatar = NULL;
  575. const xs_dict *av = xs_dict_get(actor, "icon");
  576. if (xs_type(av) == XSTYPE_DICT) {
  577. const char *url = xs_dict_get(av, "url");
  578. if (url != NULL)
  579. avatar = make_url(url, proxy, 1);
  580. }
  581. if (avatar == NULL)
  582. avatar = xs_fmt("%s/susie.png", srv_baseurl);
  583. acct = xs_dict_append(acct, "avatar", avatar);
  584. acct = xs_dict_append(acct, "avatar_static", avatar);
  585. xs *header = NULL;
  586. const xs_dict *hd = xs_dict_get(actor, "image");
  587. if (xs_type(hd) == XSTYPE_DICT)
  588. header = make_url(xs_dict_get(hd, "url"), proxy, 1);
  589. if (xs_is_null(header))
  590. header = xs_str_new(NULL);
  591. acct = xs_dict_append(acct, "header", header);
  592. acct = xs_dict_append(acct, "header_static", header);
  593. /* emojis */
  594. const xs_list *p;
  595. if (!xs_is_null(p = xs_dict_get(actor, "tag"))) {
  596. xs *eml = xs_list_new();
  597. const xs_dict *v;
  598. int c = 0;
  599. while (xs_list_next(p, &v, &c)) {
  600. const char *type = xs_dict_get(v, "type");
  601. if (!xs_is_null(type) && strcmp(type, "Emoji") == 0) {
  602. const char *name = xs_dict_get(v, "name");
  603. const xs_dict *icon = xs_dict_get(v, "icon");
  604. if (!xs_is_null(name) && !xs_is_null(icon)) {
  605. const char *o_url = xs_dict_get(icon, "url");
  606. if (!xs_is_null(o_url)) {
  607. xs *url = make_url(o_url, proxy, 1);
  608. xs *nm = xs_strip_chars_i(xs_dup(name), ":");
  609. xs *d1 = xs_dict_new();
  610. d1 = xs_dict_append(d1, "shortcode", nm);
  611. d1 = xs_dict_append(d1, "url", url);
  612. d1 = xs_dict_append(d1, "static_url", url);
  613. d1 = xs_dict_append(d1, "visible_in_picker", xs_stock(XSTYPE_TRUE));
  614. eml = xs_list_append(eml, d1);
  615. }
  616. }
  617. }
  618. }
  619. acct = xs_dict_append(acct, "emojis", eml);
  620. }
  621. acct = xs_dict_append(acct, "locked", xs_stock(XSTYPE_FALSE));
  622. /* try to get counts from actor object if available (some servers include these) */
  623. const char *fcount_fields[] = { "followersCount", "followers_count", NULL };
  624. const char *gcount_fields[] = { "followingCount", "following_count", NULL };
  625. const char *scount_fields[] = { "statusesCount", "statuses_count", "totalItems", NULL };
  626. xs *followers_count = get_count_from_actor(actor, fcount_fields, "followers");
  627. xs *following_count = get_count_from_actor(actor, gcount_fields, "following");
  628. xs *statuses_count = get_count_from_actor(actor, scount_fields, "outbox");
  629. acct = xs_dict_append(acct, "followers_count",
  630. xs_type(followers_count) == XSTYPE_NUMBER ? followers_count : xs_stock(0));
  631. acct = xs_dict_append(acct, "following_count",
  632. xs_type(following_count) == XSTYPE_NUMBER ? following_count : xs_stock(0));
  633. acct = xs_dict_append(acct, "statuses_count",
  634. xs_type(statuses_count) == XSTYPE_NUMBER ? statuses_count : xs_stock(0));
  635. xs *fields = xs_list_new();
  636. p = xs_dict_get(actor, "attachment");
  637. const xs_dict *v;
  638. /* dict of validated links */
  639. xs_dict *val_links = NULL;
  640. const xs_dict *metadata = xs_stock(XSTYPE_DICT);
  641. snac user = {0};
  642. if (xs_startswith(id, srv_baseurl)) {
  643. /* if it's a local user, open it and pick its validated links */
  644. if (user_open(&user, prefu)) {
  645. val_links = user.links;
  646. metadata = xs_dict_get_def(user.config, "metadata", xs_stock(XSTYPE_DICT));
  647. /* does this user want to publish their contact metrics? */
  648. if (xs_is_true(xs_dict_get(user.config, "show_contact_metrics"))) {
  649. int fwing = following_list_len(&user);
  650. int fwers = follower_list_len(&user);
  651. xs *ni = xs_number_new(fwing);
  652. xs *ne = xs_number_new(fwers);
  653. acct = xs_dict_append(acct, "followers_count", ne);
  654. acct = xs_dict_append(acct, "following_count", ni);
  655. }
  656. }
  657. }
  658. if (xs_is_null(val_links))
  659. val_links = xs_stock(XSTYPE_DICT);
  660. int c = 0;
  661. while (xs_list_next(p, &v, &c)) {
  662. const char *type = xs_dict_get(v, "type");
  663. const char *name = xs_dict_get(v, "name");
  664. const char *value = xs_dict_get(v, "value");
  665. if (!xs_is_null(type) && !xs_is_null(name) &&
  666. !xs_is_null(value) && strcmp(type, "PropertyValue") == 0) {
  667. xs *val_date = NULL;
  668. const char *url = xs_dict_get(metadata, name);
  669. if (!xs_is_null(url) && xs_startswith(url, "https:/" "/")) {
  670. const xs_number *verified_time = xs_dict_get(val_links, url);
  671. if (xs_type(verified_time) == XSTYPE_NUMBER) {
  672. time_t t = xs_number_get(verified_time);
  673. if (t > 0)
  674. val_date = xs_str_utctime(t, ISO_DATE_SPEC);
  675. }
  676. }
  677. xs *d = xs_dict_new();
  678. d = xs_dict_append(d, "name", name);
  679. d = xs_dict_append(d, "value", value);
  680. d = xs_dict_append(d, "verified_at",
  681. xs_type(val_date) == XSTYPE_STRING && *val_date ?
  682. val_date : xs_stock(XSTYPE_NULL));
  683. fields = xs_list_append(fields, d);
  684. }
  685. }
  686. user_free(&user);
  687. acct = xs_dict_append(acct, "fields", fields);
  688. return acct;
  689. }
  690. xs_str *mastoapi_date(const char *date)
  691. /* converts an ISO 8601 date to whatever format Mastodon uses */
  692. {
  693. xs_str *s = xs_crop_i(xs_dup(date), 0, 19);
  694. s = xs_str_cat(s, ".000Z");
  695. return s;
  696. }
  697. xs_str *rfctime(int offset, struct timeval *tv)
  698. /* returns an RFC3339 format (with fractional seconds) compliant with Mastodon datetime */
  699. {
  700. struct timeval tv2;
  701. if (tv == NULL) {
  702. gettimeofday(&tv2, NULL);
  703. tv = &tv2;
  704. }
  705. xs_str *iso_date = xs_str_utctime((long)(*tv).tv_sec + (long)offset, "%Y-%m-%dT%H:%M:%S");
  706. xs_str *date_with_ms =xs_fmt("%s.%03ldZ", iso_date, (long)(*tv).tv_usec/1000L);
  707. xs_free(iso_date);
  708. return date_with_ms;
  709. }
  710. xs_dict *markers_get(snac *snac, const xs_list *markers)
  711. {
  712. xs *data = NULL;
  713. xs_dict *returns = xs_dict_new();
  714. xs *fn = xs_fmt("%s/markers.json", snac->basedir);
  715. const xs_str *v = NULL;
  716. FILE *f;
  717. if ((f = fopen(fn, "r")) != NULL) {
  718. data = xs_json_load(f);
  719. fclose(f);
  720. }
  721. if (xs_is_null(data))
  722. data = xs_dict_new();
  723. xs_list_foreach(markers, v) {
  724. const xs_dict *mark = xs_dict_get(data, v);
  725. if (!xs_is_null(mark)) {
  726. xs *copy = xs_dup(mark);
  727. const xs_val *datetime = xs_dict_get(mark, "updated_at");
  728. if (!xs_is_null(datetime) && datetime[0] != '2') {
  729. /* fix wrong timestamp format */
  730. struct timeval tv;
  731. if (sscanf(datetime, "%lu.%lu", (unsigned long *)&(tv.tv_sec), (unsigned long *)&(tv.tv_usec))==2)
  732. copy = xs_dict_set(copy, "updated_at", rfctime(0, &tv));
  733. }
  734. returns = xs_dict_append(returns, v, copy);
  735. }
  736. }
  737. return returns;
  738. }
  739. xs_dict *markers_set(snac *snac, const char *home_marker, const char *notify_marker)
  740. /* gets or sets notification marker */
  741. {
  742. xs *data = NULL;
  743. xs_dict *written = xs_dict_new();
  744. xs *fn = xs_fmt("%s/markers.json", snac->basedir);
  745. FILE *f;
  746. if ((f = fopen(fn, "r")) != NULL) {
  747. data = xs_json_load(f);
  748. fclose(f);
  749. }
  750. if (xs_is_null(data))
  751. data = xs_dict_new();
  752. if (!xs_is_null(home_marker)) {
  753. xs *home = xs_dict_new();
  754. xs *s_datetime = rfctime(0, NULL);
  755. home = xs_dict_append(home, "last_read_id", home_marker);
  756. home = xs_dict_append(home, "version", xs_stock(0));
  757. home = xs_dict_append(home, "updated_at", s_datetime);
  758. data = xs_dict_set(data, "home", home);
  759. written = xs_dict_append(written, "home", home);
  760. }
  761. if (!xs_is_null(notify_marker)) {
  762. xs *notify = xs_dict_new();
  763. xs *s_datetime = rfctime(0, NULL);
  764. notify = xs_dict_append(notify, "last_read_id", notify_marker);
  765. notify = xs_dict_append(notify, "version", xs_stock(0));
  766. notify = xs_dict_append(notify, "updated_at", s_datetime);
  767. data = xs_dict_set(data, "notifications", notify);
  768. written = xs_dict_append(written, "notifications", notify);
  769. }
  770. if ((f = fopen(fn, "w")) != NULL) {
  771. xs_json_dump(data, 4, f);
  772. fclose(f);
  773. }
  774. return written;
  775. }
  776. xs_dict *mastoapi_poll(snac *snac, const xs_dict *msg)
  777. /* creates a mastoapi Poll object */
  778. {
  779. xs_dict *poll = xs_dict_new();
  780. xs *mid = mastoapi_id(msg);
  781. const xs_list *opts = NULL;
  782. const xs_val *v;
  783. int num_votes = 0;
  784. xs *options = xs_list_new();
  785. poll = xs_dict_append(poll, "id", mid);
  786. const char *date = xs_dict_get(msg, "endTime");
  787. if (date == NULL)
  788. date = xs_dict_get(msg, "closed");
  789. if (date == NULL)
  790. return NULL;
  791. xs *fd = mastoapi_date(date);
  792. poll = xs_dict_append(poll, "expires_at", fd);
  793. date = xs_dict_get(msg, "closed");
  794. time_t t = 0;
  795. if (date != NULL)
  796. t = xs_parse_iso_date(date, 0);
  797. poll = xs_dict_append(poll, "expired",
  798. t < time(NULL) ? xs_stock(XSTYPE_FALSE) : xs_stock(XSTYPE_TRUE));
  799. if ((opts = xs_dict_get(msg, "oneOf")) != NULL)
  800. poll = xs_dict_append(poll, "multiple", xs_stock(XSTYPE_FALSE));
  801. else {
  802. opts = xs_dict_get(msg, "anyOf");
  803. poll = xs_dict_append(poll, "multiple", xs_stock(XSTYPE_TRUE));
  804. }
  805. int c = 0;
  806. while (xs_list_next(opts, &v, &c)) {
  807. const char *title = xs_dict_get(v, "name");
  808. const char *replies = xs_dict_get(v, "replies");
  809. if (title && replies) {
  810. const char *votes_count = xs_dict_get(replies, "totalItems");
  811. if (xs_type(votes_count) == XSTYPE_NUMBER) {
  812. xs *d = xs_dict_new();
  813. d = xs_dict_append(d, "title", title);
  814. d = xs_dict_append(d, "votes_count", votes_count);
  815. options = xs_list_append(options, d);
  816. num_votes += xs_number_get(votes_count);
  817. }
  818. }
  819. }
  820. poll = xs_dict_append(poll, "options", options);
  821. xs *vc = xs_number_new(num_votes);
  822. poll = xs_dict_append(poll, "votes_count", vc);
  823. poll = xs_dict_append(poll, "emojis", xs_stock(XSTYPE_LIST));
  824. poll = xs_dict_append(poll, "voted",
  825. (snac && was_question_voted(snac, xs_dict_get(msg, "id"))) ?
  826. xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  827. return poll;
  828. }
  829. xs_dict *mastoapi_status(snac *snac, const xs_dict *msg)
  830. /* converts an ActivityPub note to a Mastodon status */
  831. {
  832. xs *actor = NULL;
  833. actor_get_refresh(snac, get_atto(msg), &actor);
  834. const char *proxy = NULL;
  835. /* if the author is not here, discard */
  836. if (actor == NULL)
  837. return NULL;
  838. if (snac && xs_is_true(xs_dict_get(srv_config, "proxy_media")))
  839. proxy = snac->actor;
  840. const char *type = xs_dict_get(msg, "type");
  841. const char *id = xs_dict_get(msg, "id");
  842. /* fail if it's not a valid actor */
  843. if (xs_is_null(type) || xs_is_null(id))
  844. return NULL;
  845. xs *acct = mastoapi_account(snac, actor);
  846. if (acct == NULL)
  847. return NULL;
  848. xs *idx = NULL;
  849. xs *ixc = NULL;
  850. const char *tmp;
  851. xs *mid = mastoapi_id(msg);
  852. xs_dict *st = xs_dict_new();
  853. st = xs_dict_append(st, "id", mid);
  854. st = xs_dict_append(st, "uri", id);
  855. st = xs_dict_append(st, "url", id);
  856. st = xs_dict_append(st, "account", acct);
  857. const char *published = xs_dict_get(msg, "published");
  858. xs *fd = NULL;
  859. if (published)
  860. fd = mastoapi_date(published);
  861. else {
  862. xs *p = xs_str_iso_date(0);
  863. fd = mastoapi_date(p);
  864. }
  865. st = xs_dict_append(st, "created_at", fd);
  866. {
  867. const char *content = xs_dict_get(msg, "content");
  868. const char *name = xs_dict_get(msg, "name");
  869. xs *s1 = NULL;
  870. if (name && content)
  871. s1 = xs_fmt("%s<br><br>%s", name, content);
  872. else
  873. if (name)
  874. s1 = xs_dup(name);
  875. else
  876. if (content)
  877. s1 = xs_dup(content);
  878. else
  879. s1 = xs_str_new(NULL);
  880. st = xs_dict_append(st, "content", s1);
  881. }
  882. /* determine visibility: https://docs.joinmastodon.org/entities/Status/#visibility */
  883. const int scope = get_msg_visibility(msg);
  884. if (scope == SCOPE_PUBLIC)
  885. st = xs_dict_append(st, "visibility", "public");
  886. else if (scope == SCOPE_FOLLOWERS)
  887. st = xs_dict_append(st, "visibility", "private");
  888. else if (scope == SCOPE_MENTIONED)
  889. st = xs_dict_append(st, "visibility", "direct");
  890. else if (scope == SCOPE_UNLISTED)
  891. st = xs_dict_append(st, "visibility", "unlisted");
  892. tmp = xs_dict_get(msg, "sensitive");
  893. if (xs_is_null(tmp))
  894. tmp = xs_stock(XSTYPE_FALSE);
  895. st = xs_dict_append(st, "sensitive", tmp);
  896. tmp = xs_dict_get(msg, "summary");
  897. if (xs_is_null(tmp))
  898. tmp = "";
  899. st = xs_dict_append(st, "spoiler_text", tmp);
  900. /* create the list of attachments */
  901. xs *attach = get_attachments(msg);
  902. {
  903. xs_list *p = attach;
  904. const xs_dict *v;
  905. xs *matt = xs_list_new();
  906. while (xs_list_iter(&p, &v)) {
  907. const char *type = xs_dict_get(v, "type");
  908. const char *o_href = xs_dict_get(v, "href");
  909. const char *name = xs_dict_get(v, "name");
  910. if (xs_match(type, "image/*|video/*|audio/*|Image|Video")) { /* */
  911. xs *matteid = xs_fmt("%s_%d", id, xs_list_len(matt));
  912. xs *href = make_url(o_href, proxy, 1);
  913. xs *d = xs_dict_new();
  914. d = xs_dict_append(d, "id", matteid);
  915. d = xs_dict_append(d, "url", href);
  916. d = xs_dict_append(d, "preview_url", href);
  917. d = xs_dict_append(d, "remote_url", href);
  918. d = xs_dict_append(d, "description", name);
  919. d = xs_dict_append(d, "type", (*type == 'v' || *type == 'V') ? "video" :
  920. (*type == 'a' || *type == 'A') ? "audio" : "image");
  921. matt = xs_list_append(matt, d);
  922. }
  923. }
  924. st = xs_dict_append(st, "media_attachments", matt);
  925. }
  926. {
  927. xs *ml = xs_list_new();
  928. xs *htl = xs_list_new();
  929. xs *eml = xs_list_new();
  930. const xs_list *tag = xs_dict_get(msg, "tag");
  931. int n = 0;
  932. xs *tag_list = NULL;
  933. if (xs_type(tag) == XSTYPE_DICT) {
  934. tag_list = xs_list_new();
  935. tag_list = xs_list_append(tag_list, tag);
  936. }
  937. else
  938. if (xs_type(tag) == XSTYPE_LIST)
  939. tag_list = xs_dup(tag);
  940. else
  941. tag_list = xs_list_new();
  942. tag = tag_list;
  943. const xs_dict *v;
  944. int c = 0;
  945. while (xs_list_next(tag, &v, &c)) {
  946. const char *type = xs_dict_get(v, "type");
  947. if (xs_is_null(type))
  948. continue;
  949. xs *d1 = xs_dict_new();
  950. if (strcmp(type, "Mention") == 0) {
  951. const char *name = xs_dict_get(v, "name");
  952. const char *href = xs_dict_get(v, "href");
  953. if (!xs_is_null(name) && !xs_is_null(href) &&
  954. (snac == NULL || strcmp(href, snac->actor) != 0)) {
  955. xs *nm = xs_strip_chars_i(xs_dup(name), "@");
  956. xs *id = xs_fmt("%d", n++);
  957. d1 = xs_dict_append(d1, "id", id);
  958. d1 = xs_dict_append(d1, "username", nm);
  959. d1 = xs_dict_append(d1, "acct", nm);
  960. d1 = xs_dict_append(d1, "url", href);
  961. ml = xs_list_append(ml, d1);
  962. }
  963. }
  964. else
  965. if (strcmp(type, "Hashtag") == 0) {
  966. const char *name = xs_dict_get(v, "name");
  967. const char *href = xs_dict_get(v, "href");
  968. if (!xs_is_null(name) && !xs_is_null(href)) {
  969. xs *nm = xs_strip_chars_i(xs_dup(name), "#");
  970. d1 = xs_dict_append(d1, "name", nm);
  971. d1 = xs_dict_append(d1, "url", href);
  972. htl = xs_list_append(htl, d1);
  973. }
  974. }
  975. else
  976. if (strcmp(type, "Emoji") == 0) {
  977. const char *name = xs_dict_get(v, "name");
  978. const xs_dict *icon = xs_dict_get(v, "icon");
  979. if (!xs_is_null(name) && !xs_is_null(icon)) {
  980. const char *o_url = xs_dict_get(icon, "url");
  981. if (!xs_is_null(o_url)) {
  982. xs *url = make_url(o_url, snac ? snac->actor : NULL, 1);
  983. xs *nm = xs_strip_chars_i(xs_dup(name), ":");
  984. d1 = xs_dict_append(d1, "shortcode", nm);
  985. d1 = xs_dict_append(d1, "url", url);
  986. d1 = xs_dict_append(d1, "static_url", url);
  987. d1 = xs_dict_append(d1, "visible_in_picker", xs_stock(XSTYPE_TRUE));
  988. d1 = xs_dict_append(d1, "category", "Emojis");
  989. eml = xs_list_append(eml, d1);
  990. }
  991. }
  992. }
  993. }
  994. st = xs_dict_append(st, "mentions", ml);
  995. st = xs_dict_append(st, "tags", htl);
  996. st = xs_dict_append(st, "emojis", eml);
  997. }
  998. {
  999. xs *rl = object_get_emoji_reacts(id);
  1000. xs *frl = xs_list_new(); /* final */
  1001. xs *sfrl = xs_dict_new(); /* seen */
  1002. int c = 0;
  1003. const char *v;
  1004. while (xs_list_next(rl, &v, &c)) {
  1005. xs *msg = NULL;
  1006. if (valid_status(object_get_by_md5(v, &msg))) {
  1007. const char *content = xs_dict_get(msg, "content");
  1008. const char *actor = xs_dict_get(msg, "actor");
  1009. const xs_list *contentl = xs_dict_get(sfrl, content);
  1010. if ((snac && is_muted(snac, actor)) || is_instance_blocked(actor))
  1011. continue;
  1012. /* NOTE: idk when there are no actor, but i encountered that bug.
  1013. * Probably because of one of my previous attempts.
  1014. * Keeping this just in case, can remove later */
  1015. const char *me = actor && snac && strcmp(actor, snac->actor) == 0 ?
  1016. xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE);
  1017. int count = 1;
  1018. if (contentl) {
  1019. count = xs_number_get(xs_list_get(contentl, 0)) + 1;
  1020. if (strncmp(xs_list_get(contentl, 1), xs_stock(XSTYPE_TRUE), 1) == 0)
  1021. me = xs_stock(XSTYPE_TRUE);
  1022. }
  1023. xs *fl = xs_list_new();
  1024. xs *c1 = xs_number_new(count);
  1025. fl = xs_list_append(fl, c1, me);
  1026. sfrl = xs_dict_append(sfrl, content, fl);
  1027. }
  1028. }
  1029. c = 0;
  1030. while (xs_list_next(rl, &v, &c)) {
  1031. xs *msg = NULL;
  1032. if (valid_status(object_get_by_md5(v, &msg))) {
  1033. xs *d1 = xs_dict_new();
  1034. const xs_dict *icon = xs_dict_get(xs_list_get(xs_dict_get(msg, "tag"), 0), "icon");
  1035. const char *o_url = xs_dict_get(icon, "url");
  1036. const char *name = xs_dict_get(msg, "content");
  1037. const char *actor = xs_dict_get(msg, "actor");
  1038. xs *nm = xs_dup(name);
  1039. xs *url = NULL;
  1040. if (!xs_is_null(o_url)) {
  1041. if (actor && snac && !strcmp(actor, snac->actor))
  1042. url = make_url(o_url, NULL, 1);
  1043. else
  1044. url = xs_dup(o_url);
  1045. }
  1046. xs *accounts = xs_list_new();
  1047. if (actor) {
  1048. xs *d2 = NULL;
  1049. if (valid_status(object_get(actor, &d2))) {
  1050. xs *e_acct = mastoapi_account(snac, d2);
  1051. accounts = xs_list_append(accounts, e_acct);
  1052. }
  1053. }
  1054. const xs_list *item = xs_dict_get(sfrl, nm);
  1055. const xs_str *nb = xs_list_get(item, 0);
  1056. const xs_val *me = xs_list_get(item, 1);
  1057. if (item == NULL)
  1058. continue;
  1059. if (nm && strcmp(nm, "")) {
  1060. if (url && strcmp(url, "")) {
  1061. d1 = xs_dict_append(d1, "name", nm);
  1062. d1 = xs_dict_append(d1, "shortcode", nm);
  1063. d1 = xs_dict_append(d1, "accounts", accounts);
  1064. d1 = xs_dict_append(d1, "me", me);
  1065. d1 = xs_dict_append(d1, "url", url);
  1066. d1 = xs_dict_append(d1, "static_url", url);
  1067. d1 = xs_dict_append(d1, "visible_in_picker", xs_stock(XSTYPE_TRUE));
  1068. d1 = xs_dict_append(d1, "count", nb);
  1069. } else {
  1070. d1 = xs_dict_append(d1, "name", nm);
  1071. d1 = xs_dict_append(d1, "count", nb);
  1072. d1 = xs_dict_append(d1, "me", me);
  1073. d1 = xs_dict_append(d1, "visible_in_picker", xs_stock(XSTYPE_TRUE));
  1074. }
  1075. sfrl = xs_dict_del(sfrl, nm);
  1076. frl = xs_list_append(frl, d1);
  1077. }
  1078. }
  1079. }
  1080. st = xs_dict_append(st, "reactions", frl);
  1081. }
  1082. xs_free(idx);
  1083. xs_free(ixc);
  1084. idx = object_likes(id);
  1085. ixc = xs_number_new(xs_list_len(idx));
  1086. st = xs_dict_append(st, "favourites_count", ixc);
  1087. st = xs_dict_append(st, "favourited",
  1088. (snac && xs_list_in(idx, snac->md5) != -1) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  1089. xs_free(idx);
  1090. xs_free(ixc);
  1091. idx = object_announces(id);
  1092. ixc = xs_number_new(xs_list_len(idx));
  1093. st = xs_dict_append(st, "reblogs_count", ixc);
  1094. st = xs_dict_append(st, "reblogged",
  1095. (snac && xs_list_in(idx, snac->md5) != -1) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  1096. /* get the last person who boosted this */
  1097. xs *boosted_by_md5 = NULL;
  1098. if (xs_list_len(idx))
  1099. boosted_by_md5 = xs_dup(xs_list_get(idx, -1));
  1100. xs_free(idx);
  1101. xs_free(ixc);
  1102. idx = object_children(id);
  1103. ixc = xs_number_new(xs_list_len(idx));
  1104. st = xs_dict_append(st, "replies_count", ixc);
  1105. /* default in_reply_to values */
  1106. st = xs_dict_append(st, "in_reply_to_id", xs_stock(XSTYPE_NULL));
  1107. st = xs_dict_append(st, "in_reply_to_account_id", xs_stock(XSTYPE_NULL));
  1108. tmp = get_in_reply_to(msg);
  1109. if (!xs_is_null(tmp)) {
  1110. xs *irto = NULL;
  1111. if (valid_status(object_get(tmp, &irto))) {
  1112. xs *irt_mid = mastoapi_id(irto);
  1113. st = xs_dict_set(st, "in_reply_to_id", irt_mid);
  1114. const char *at = NULL;
  1115. if (!xs_is_null(at = get_atto(irto))) {
  1116. xs *at_md5 = xs_md5_hex(at, strlen(at));
  1117. st = xs_dict_set(st, "in_reply_to_account_id", at_md5);
  1118. }
  1119. }
  1120. }
  1121. st = xs_dict_append(st, "reblog", xs_stock(XSTYPE_NULL));
  1122. st = xs_dict_append(st, "card", xs_stock(XSTYPE_NULL));
  1123. st = xs_dict_append(st, "language", "en");
  1124. st = xs_dict_append(st, "filtered", xs_stock(XSTYPE_LIST));
  1125. st = xs_dict_append(st, "muted", xs_stock(XSTYPE_FALSE));
  1126. tmp = xs_dict_get(msg, "sourceContent");
  1127. if (xs_is_null(tmp))
  1128. tmp = "";
  1129. st = xs_dict_append(st, "text", tmp);
  1130. tmp = xs_dict_get(msg, "updated");
  1131. xs *fd2 = NULL;
  1132. if (xs_is_null(tmp))
  1133. tmp = xs_stock(XSTYPE_NULL);
  1134. else {
  1135. fd2 = mastoapi_date(tmp);
  1136. tmp = fd2;
  1137. }
  1138. st = xs_dict_append(st, "edited_at", tmp);
  1139. if (strcmp(type, "Question") == 0) {
  1140. xs *poll = mastoapi_poll(snac, msg);
  1141. st = xs_dict_append(st, "poll", poll);
  1142. }
  1143. else
  1144. st = xs_dict_append(st, "poll", xs_stock(XSTYPE_NULL));
  1145. st = xs_dict_append(st, "bookmarked",
  1146. (snac && is_bookmarked(snac, id)) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  1147. st = xs_dict_append(st, "pinned",
  1148. (snac && is_pinned(snac, id)) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  1149. /* is it a boost? */
  1150. if (!xs_is_null(boosted_by_md5)) {
  1151. /* create a new dummy status, using st as the 'reblog' field */
  1152. xs_dict *bst = xs_dup(st);
  1153. xs *b_actor = NULL;
  1154. if (valid_status(object_get_by_md5(boosted_by_md5, &b_actor))) {
  1155. xs *b_acct = mastoapi_account(snac, b_actor);
  1156. xs *fake_uri = NULL;
  1157. if (snac)
  1158. fake_uri = xs_fmt("%s/d/%s/Announce", snac->actor, mid);
  1159. else
  1160. fake_uri = xs_fmt("%s#%s", srv_baseurl, mid);
  1161. bst = xs_dict_set(bst, "uri", fake_uri);
  1162. bst = xs_dict_set(bst, "url", fake_uri);
  1163. bst = xs_dict_set(bst, "account", b_acct);
  1164. bst = xs_dict_set(bst, "content", "");
  1165. bst = xs_dict_set(bst, "reblog", st);
  1166. xs *b_id = xs_toupper_i(xs_dup(xs_dict_get(st, "id")));
  1167. bst = xs_dict_set(bst, "id", b_id);
  1168. xs_free(st);
  1169. st = bst;
  1170. }
  1171. else
  1172. xs_free(bst);
  1173. }
  1174. return st;
  1175. }
  1176. xs_dict *mastoapi_relationship(snac *snac, const char *md5)
  1177. {
  1178. xs_dict *rel = NULL;
  1179. xs *actor_o = NULL;
  1180. if (valid_status(object_get_by_md5(md5, &actor_o))) {
  1181. rel = xs_dict_new();
  1182. const char *actor = xs_dict_get(actor_o, "id");
  1183. rel = xs_dict_append(rel, "id", md5);
  1184. rel = xs_dict_append(rel, "following",
  1185. following_check(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  1186. rel = xs_dict_append(rel, "showing_reblogs", xs_stock(XSTYPE_TRUE));
  1187. rel = xs_dict_append(rel, "notifying", xs_stock(XSTYPE_FALSE));
  1188. rel = xs_dict_append(rel, "followed_by",
  1189. follower_check(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  1190. rel = xs_dict_append(rel, "requested_by",
  1191. pending_check(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  1192. rel = xs_dict_append(rel, "blocking",
  1193. is_muted(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  1194. rel = xs_dict_append(rel, "muting", xs_stock(XSTYPE_FALSE));
  1195. rel = xs_dict_append(rel, "muting_notifications", xs_stock(XSTYPE_FALSE));
  1196. rel = xs_dict_append(rel, "requested", xs_stock(XSTYPE_FALSE));
  1197. rel = xs_dict_append(rel, "domain_blocking", xs_stock(XSTYPE_FALSE));
  1198. rel = xs_dict_append(rel, "endorsed", xs_stock(XSTYPE_FALSE));
  1199. rel = xs_dict_append(rel, "note", "");
  1200. }
  1201. return rel;
  1202. }
  1203. int process_auth_token(snac *snac, const xs_dict *req)
  1204. /* processes an authorization token, if there is one */
  1205. {
  1206. int logged_in = 0;
  1207. const char *v;
  1208. /* if there is an authorization field, try to validate it */
  1209. if (!xs_is_null(v = xs_dict_get(req, "authorization")) && xs_startswith(v, "Bearer ")) {
  1210. xs *tokid = xs_replace_n(v, "Bearer ", "", 1);
  1211. xs *token = token_get(tokid);
  1212. if (token != NULL) {
  1213. const char *uid = xs_dict_get(token, "uid");
  1214. if (!xs_is_null(uid) && user_open(snac, uid)) {
  1215. logged_in = 1;
  1216. /* this counts as a 'login' */
  1217. lastlog_write(snac, "mastoapi");
  1218. srv_debug(2, xs_fmt("mastoapi auth: valid token for user '%s'", uid));
  1219. }
  1220. else
  1221. srv_log(xs_fmt("mastoapi auth: corrupted token '%s'", tokid));
  1222. }
  1223. else
  1224. srv_log(xs_fmt("mastoapi auth: invalid token '%s'", tokid));
  1225. }
  1226. return logged_in;
  1227. }
  1228. void credentials_get(char **body, char **ctype, int *status, snac snac)
  1229. {
  1230. xs *acct = xs_dict_new();
  1231. const xs_val *bot = xs_dict_get(snac.config, "bot");
  1232. acct = xs_dict_append(acct, "id", snac.md5);
  1233. acct = xs_dict_append(acct, "username", xs_dict_get(snac.config, "uid"));
  1234. acct = xs_dict_append(acct, "acct", xs_dict_get(snac.config, "uid"));
  1235. acct = xs_dict_append(acct, "display_name", xs_dict_get(snac.config, "name"));
  1236. acct = xs_dict_append(acct, "created_at", xs_dict_get(snac.config, "published"));
  1237. acct = xs_dict_append(acct, "last_status_at", xs_dict_get(snac.config, "published"));
  1238. acct = xs_dict_append(acct, "note", xs_dict_get(snac.config, "bio"));
  1239. acct = xs_dict_append(acct, "url", snac.actor);
  1240. acct = xs_dict_append(acct, "uri", snac.actor);
  1241. acct = xs_dict_append(acct, "locked",
  1242. xs_stock(xs_is_true(xs_dict_get(snac.config, "approve_followers")) ? XSTYPE_TRUE : XSTYPE_FALSE));
  1243. acct = xs_dict_append(acct, "bot", xs_stock(xs_is_true(bot) ? XSTYPE_TRUE : XSTYPE_FALSE));
  1244. acct = xs_dict_append(acct, "emojis", xs_stock(XSTYPE_LIST));
  1245. xs *src = xs_json_loads("{\"privacy\":\"public\", \"language\":\"en\","
  1246. "\"follow_requests_count\": 0,"
  1247. "\"sensitive\":false,\"fields\":[],\"note\":\"\"}");
  1248. /* some apps take the note from the source object */
  1249. src = xs_dict_set(src, "note", xs_dict_get(snac.config, "bio"));
  1250. src = xs_dict_set(src, "privacy", xs_type(xs_dict_get(snac.config, "private")) == XSTYPE_TRUE ? "private" : "public");
  1251. const xs_str *cw = xs_dict_get(snac.config, "cw");
  1252. src = xs_dict_set(src, "sensitive",
  1253. strcmp(cw, "open") == 0 ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  1254. src = xs_dict_set(src, "bot", xs_stock(xs_is_true(bot) ? XSTYPE_TRUE : XSTYPE_FALSE));
  1255. xs *avatar = NULL;
  1256. const char *av = xs_dict_get(snac.config, "avatar");
  1257. if (xs_is_null(av) || *av == '\0')
  1258. avatar = xs_fmt("%s/susie.png", srv_baseurl);
  1259. else
  1260. avatar = xs_dup(av);
  1261. acct = xs_dict_append(acct, "avatar", avatar);
  1262. acct = xs_dict_append(acct, "avatar_static", avatar);
  1263. xs *header = NULL;
  1264. const char *hd = xs_dict_get(snac.config, "header");
  1265. if (!xs_is_null(hd))
  1266. header = xs_dup(hd);
  1267. else
  1268. header = xs_str_new(NULL);
  1269. acct = xs_dict_append(acct, "header", header);
  1270. acct = xs_dict_append(acct, "header_static", header);
  1271. xs *metadata = NULL;
  1272. const xs_dict *md = xs_dict_get(snac.config, "metadata");
  1273. if (xs_is_dict(md))
  1274. metadata = xs_dup(md);
  1275. else
  1276. if (xs_is_string(md)) {
  1277. metadata = xs_dict_new();
  1278. xs *l = xs_split(md, "\n");
  1279. const char *ll;
  1280. xs_list_foreach(l, ll) {
  1281. xs *kv = xs_split_n(ll, "=", 1);
  1282. const char *k = xs_list_get(kv, 0);
  1283. const char *v = xs_list_get(kv, 1);
  1284. if (k && v) {
  1285. xs *kk = xs_strip_i(xs_dup(k));
  1286. xs *vv = xs_strip_i(xs_dup(v));
  1287. metadata = xs_dict_set(metadata, kk, vv);
  1288. }
  1289. }
  1290. }
  1291. if (xs_is_dict(metadata)) {
  1292. xs *fields = xs_list_new();
  1293. const xs_str *k;
  1294. const xs_str *v;
  1295. xs_dict *val_links = snac.links;
  1296. if (xs_is_null(val_links))
  1297. val_links = xs_stock(XSTYPE_DICT);
  1298. int c = 0;
  1299. while (xs_dict_next(metadata, &k, &v, &c)) {
  1300. xs *val_date = NULL;
  1301. const xs_number *verified_time = xs_dict_get(val_links, v);
  1302. if (xs_type(verified_time) == XSTYPE_NUMBER) {
  1303. time_t t = xs_number_get(verified_time);
  1304. if (t > 0)
  1305. val_date = xs_str_utctime(t, ISO_DATE_SPEC);
  1306. }
  1307. xs *d = xs_dict_new();
  1308. d = xs_dict_append(d, "name", k);
  1309. d = xs_dict_append(d, "value", v);
  1310. d = xs_dict_append(d, "verified_at",
  1311. xs_type(val_date) == XSTYPE_STRING && *val_date ? val_date : xs_stock(XSTYPE_NULL));
  1312. fields = xs_list_append(fields, d);
  1313. }
  1314. acct = xs_dict_set(acct, "fields", fields);
  1315. /* some apps take the fields from the source object */
  1316. src = xs_dict_set(src, "fields", fields);
  1317. }
  1318. acct = xs_dict_append(acct, "source", src);
  1319. acct = xs_dict_append(acct, "followers_count", xs_stock(0));
  1320. acct = xs_dict_append(acct, "following_count", xs_stock(0));
  1321. acct = xs_dict_append(acct, "statuses_count", xs_stock(0));
  1322. /* does this user want to publish their contact metrics? */
  1323. if (xs_is_true(xs_dict_get(snac.config, "show_contact_metrics"))) {
  1324. int fwing = following_list_len(&snac);
  1325. int fwers = follower_list_len(&snac);
  1326. xs *ni = xs_number_new(fwing);
  1327. xs *ne = xs_number_new(fwers);
  1328. acct = xs_dict_append(acct, "followers_count", ne);
  1329. acct = xs_dict_append(acct, "following_count", ni);
  1330. }
  1331. *body = xs_json_dumps(acct, 4);
  1332. *ctype = "application/json";
  1333. *status = HTTP_STATUS_OK;
  1334. }
  1335. xs_list *mastoapi_timeline(snac *user, const xs_dict *args, const char *index_fn)
  1336. {
  1337. xs_list *out = xs_list_new();
  1338. FILE *f;
  1339. char md5[MD5_HEX_SIZE];
  1340. if (dbglevel) {
  1341. xs *js = xs_json_dumps(args, 0);
  1342. srv_debug(1, xs_fmt("mastoapi_timeline args %s", js));
  1343. }
  1344. if ((f = fopen(index_fn, "r")) == NULL)
  1345. return out;
  1346. const char *o_max_id = xs_dict_get(args, "max_id");
  1347. const char *o_since_id = xs_dict_get(args, "since_id");
  1348. const char *o_min_id = xs_dict_get(args, "min_id"); /* unsupported old-to-new navigation */
  1349. const char *limit_s = xs_dict_get(args, "limit");
  1350. int (*iterator)(FILE *, char *);
  1351. int initial_status = 0;
  1352. int ascending = 0;
  1353. int limit = 0;
  1354. int cnt = 0;
  1355. xs *max_id = o_max_id ? xs_tolower_i(xs_dup(o_max_id)) : NULL;
  1356. xs *since_id = o_since_id ? xs_tolower_i(xs_dup(o_since_id)) : NULL;
  1357. xs *min_id = o_min_id ? xs_tolower_i(xs_dup(o_min_id)) : NULL;
  1358. if (!xs_is_null(limit_s))
  1359. limit = atoi(limit_s);
  1360. if (limit == 0)
  1361. limit = 20;
  1362. if (min_id) {
  1363. iterator = &index_asc_next;
  1364. initial_status = index_asc_first(f, md5, MID_TO_MD5(min_id));
  1365. ascending = 1;
  1366. }
  1367. else {
  1368. iterator = &index_desc_next;
  1369. initial_status = index_desc_first(f, md5, 0);
  1370. }
  1371. xs_set entries;
  1372. xs_set_init(&entries);
  1373. if (initial_status) {
  1374. do {
  1375. xs *msg = NULL;
  1376. /* only return entries older that max_id */
  1377. if (max_id) {
  1378. if (strcmp(md5, MID_TO_MD5(max_id)) == 0) {
  1379. max_id = xs_free(max_id);
  1380. if (ascending)
  1381. break;
  1382. }
  1383. if (!ascending)
  1384. continue;
  1385. }
  1386. /* only returns entries newer than since_id */
  1387. if (since_id) {
  1388. if (strcmp(md5, MID_TO_MD5(since_id)) == 0) {
  1389. if (!ascending)
  1390. break;
  1391. since_id = xs_free(since_id);
  1392. }
  1393. if (ascending)
  1394. continue;
  1395. }
  1396. /* get the entry */
  1397. if (user) {
  1398. if (!valid_status(timeline_get_by_md5(user, md5, &msg)))
  1399. continue;
  1400. }
  1401. else {
  1402. if (!valid_status(object_get_by_md5(md5, &msg)))
  1403. continue;
  1404. }
  1405. /* discard non-Notes */
  1406. const char *id = xs_dict_get(msg, "id");
  1407. const char *type = xs_dict_get(msg, "type");
  1408. if (!xs_match(type, POSTLIKE_OBJECT_TYPE))
  1409. continue;
  1410. if (id && is_instance_blocked(id))
  1411. continue;
  1412. const char *from = NULL;
  1413. if (strcmp(type, "Page") == 0)
  1414. from = xs_dict_get(msg, "audience");
  1415. if (from == NULL)
  1416. from = get_atto(msg);
  1417. if (from == NULL)
  1418. continue;
  1419. if (user) {
  1420. /* is this message from a person we don't follow? */
  1421. if (strcmp(from, user->actor) && !following_check(user, from)) {
  1422. /* discard if it was not boosted */
  1423. xs *idx = object_announces(id);
  1424. if (xs_list_len(idx) == 0)
  1425. continue;
  1426. }
  1427. /* discard notes from muted morons */
  1428. if (is_muted(user, from))
  1429. continue;
  1430. /* discard hidden notes */
  1431. if (is_hidden(user, id))
  1432. continue;
  1433. /* muted words? */
  1434. if (words_in_content(xs_dict_get(user->config, "muted_words"),
  1435. xs_dict_get(msg, "content")))
  1436. continue;
  1437. if (blocked_hashtag_check(user, msg))
  1438. continue;
  1439. }
  1440. else {
  1441. /* skip non-public messages */
  1442. if (!is_msg_public(msg))
  1443. continue;
  1444. /* discard messages from private users */
  1445. if (is_msg_from_private_user(msg))
  1446. continue;
  1447. }
  1448. /* if it has a name and it's not an object that may have one,
  1449. it's a poll vote, so discard it */
  1450. if (!xs_is_null(xs_dict_get(msg, "name")) && !xs_match(type, "Page|Video|Audio|Event"))
  1451. continue;
  1452. /* convert the Note into a Mastodon status */
  1453. xs *st = mastoapi_status(user, msg);
  1454. if (st != NULL && xs_set_add(&entries, md5) == 1) {
  1455. if (ascending)
  1456. out = xs_list_insert(out, 0, st);
  1457. else
  1458. out = xs_list_append(out, st);
  1459. cnt++;
  1460. }
  1461. } while ((cnt < limit) && (*iterator)(f, md5));
  1462. }
  1463. xs_set_free(&entries);
  1464. int more = index_desc_next(f, md5);
  1465. fclose(f);
  1466. srv_debug(1, xs_fmt("mastoapi_timeline ret %d%s", cnt, more ? " (+)" : ""));
  1467. return out;
  1468. }
  1469. xs_str *timeline_link_header(const char *endpoint, xs_list *timeline)
  1470. /* returns a Link header with paging information */
  1471. {
  1472. xs_str *s = NULL;
  1473. if (xs_list_len(timeline) == 0)
  1474. return NULL;
  1475. const xs_dict *first_st = xs_list_get(timeline, 0);
  1476. const xs_dict *last_st = xs_list_get(timeline, -1);
  1477. const char *first_id = xs_dict_get(first_st, "id");
  1478. const char *last_id = xs_dict_get(last_st, "id");
  1479. const char *host = xs_dict_get(srv_config, "host");
  1480. const char *protocol = xs_dict_get_def(srv_config, "protocol", "https");
  1481. s = xs_fmt(
  1482. "<%s:/" "/%s%s?max_id=%s>; rel=\"next\", "
  1483. "<%s:/" "/%s%s?since_id=%s>; rel=\"prev\"",
  1484. protocol, host, endpoint, last_id,
  1485. protocol, host, endpoint, first_id);
  1486. srv_debug(1, xs_fmt("timeline_link_header %s", s));
  1487. return s;
  1488. }
  1489. xs_list *mastoapi_account_lists(snac *user, const char *uid)
  1490. /* returns the list of list an user is in */
  1491. {
  1492. xs_list *out = xs_list_new();
  1493. xs *actor_md5 = NULL;
  1494. xs *lol = list_maint(user, NULL, OP_LIST);
  1495. if (uid) {
  1496. if (!xs_is_hex(uid))
  1497. actor_md5 = xs_md5_hex(uid, strlen(uid));
  1498. else
  1499. actor_md5 = xs_dup(uid);
  1500. }
  1501. const xs_list *li;
  1502. xs_list_foreach(lol, li) {
  1503. const char *list_id = xs_list_get(li, 0);
  1504. const char *list_title = xs_list_get(li, 1);
  1505. if (uid) {
  1506. xs *users = list_members(user, list_id, NULL, OP_LIST);
  1507. if (xs_list_in(users, actor_md5) == -1)
  1508. continue;
  1509. }
  1510. xs *d = xs_dict_new();
  1511. d = xs_dict_append(d, "id", list_id);
  1512. d = xs_dict_append(d, "title", list_title);
  1513. d = xs_dict_append(d, "replies_policy", "list");
  1514. d = xs_dict_append(d, "exclusive", xs_stock(XSTYPE_FALSE));
  1515. out = xs_list_append(out, d);
  1516. }
  1517. return out;
  1518. }
  1519. xs_list *build_childrens(const xs_dict *msg, snac *snac1) {
  1520. xs_list *ret = xs_list_new();
  1521. xs *children = object_children(xs_dict_get(msg, "id"));
  1522. char *p = children;
  1523. const xs_str *v;
  1524. while (xs_list_iter(&p, &v)) {
  1525. xs *m2 = NULL;
  1526. if (valid_status(timeline_get_by_md5(snac1, v, &m2))) {
  1527. if (xs_is_null(xs_dict_get(m2, "name"))) {
  1528. xs *st = mastoapi_status(snac1, m2);
  1529. if (st) {
  1530. /* childrens children */
  1531. xs *childs = build_childrens(m2, snac1);
  1532. ret = xs_list_append(ret, st);
  1533. if (xs_list_len(childs)) {
  1534. char *p2 = childs;
  1535. while (xs_list_iter(&p2, &v))
  1536. ret = xs_list_append(ret, v);
  1537. }
  1538. }
  1539. }
  1540. }
  1541. }
  1542. return ret;
  1543. }
  1544. int mastoapi_get_handler(const xs_dict *req, const char *q_path,
  1545. char **body, int *b_size, char **ctype, xs_str **link)
  1546. {
  1547. (void)b_size;
  1548. if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
  1549. return 0;
  1550. int status = HTTP_STATUS_NOT_FOUND;
  1551. const xs_dict *args = xs_dict_get(req, "q_vars");
  1552. xs *cmd = xs_replace_n(q_path, "/api", "", 1);
  1553. snac snac1 = {0};
  1554. int logged_in = process_auth_token(&snac1, req);
  1555. if (strcmp(cmd, "/v1/accounts/verify_credentials") == 0) { /** **/
  1556. if (logged_in) {
  1557. credentials_get(body, ctype, &status, snac1);
  1558. }
  1559. else {
  1560. status = HTTP_STATUS_UNPROCESSABLE_CONTENT; // (no login)
  1561. }
  1562. }
  1563. else
  1564. if (strcmp(cmd, "/v1/accounts/relationships") == 0) { /** **/
  1565. /* find if an account is followed, blocked, etc. */
  1566. /* the account to get relationships about is in args "id[]" */
  1567. if (logged_in) {
  1568. xs *res = xs_list_new();
  1569. const char *md5 = xs_dict_get(args, "id[]");
  1570. if (xs_is_null(md5))
  1571. md5 = xs_dict_get(args, "id");
  1572. if (!xs_is_null(md5)) {
  1573. if (xs_type(md5) == XSTYPE_LIST)
  1574. md5 = xs_list_get(md5, 0);
  1575. xs *rel = mastoapi_relationship(&snac1, md5);
  1576. if (rel != NULL)
  1577. res = xs_list_append(res, rel);
  1578. }
  1579. *body = xs_json_dumps(res, 4);
  1580. *ctype = "application/json";
  1581. status = HTTP_STATUS_OK;
  1582. }
  1583. else
  1584. status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
  1585. }
  1586. else
  1587. if (strcmp(cmd, "/v1/accounts/lookup") == 0) { /** **/
  1588. /* lookup an account */
  1589. const char *acct = xs_dict_get(args, "acct");
  1590. if (!xs_is_null(acct)) {
  1591. xs *s = xs_strip_chars_i(xs_dup(acct), "@");
  1592. xs *l = xs_split_n(s, "@", 1);
  1593. const char *uid = xs_list_get(l, 0);
  1594. const char *host = xs_list_get(l, 1);
  1595. if (uid && (!host || strcmp(host, xs_dict_get(srv_config, "host")) == 0)) {
  1596. snac user;
  1597. if (user_open(&user, uid)) {
  1598. xs *actor = msg_actor(&user);
  1599. xs *macct = mastoapi_account(NULL, actor);
  1600. *body = xs_json_dumps(macct, 4);
  1601. *ctype = "application/json";
  1602. status = HTTP_STATUS_OK;
  1603. user_free(&user);
  1604. }
  1605. }
  1606. }
  1607. }
  1608. else
  1609. if (xs_startswith(cmd, "/v1/accounts/")) { /** **/
  1610. /* account-related information */
  1611. xs *l = xs_split(cmd, "/");
  1612. const char *uid = xs_list_get(l, 3);
  1613. const char *opt = xs_list_get(l, 4);
  1614. if (uid != NULL) {
  1615. snac snac2;
  1616. xs *out = NULL;
  1617. xs *actor = NULL;
  1618. if (logged_in && strcmp(uid, "familiar_followers") == 0) { /** **/
  1619. /* familiar followers endpoint - return empty array */
  1620. out = xs_list_new();
  1621. }
  1622. else
  1623. if (logged_in && strcmp(uid, "search") == 0) { /** **/
  1624. /* search for accounts starting with q */
  1625. const char *aq = xs_dict_get(args, "q");
  1626. if (!xs_is_null(aq)) {
  1627. xs *q = xs_utf8_tolower(aq);
  1628. out = xs_list_new();
  1629. xs *wing = following_list(&snac1);
  1630. xs *wers = follower_list(&snac1);
  1631. xs *ulst = user_list();
  1632. xs_list *p;
  1633. const xs_str *v;
  1634. xs_set seen;
  1635. xs_set_init(&seen);
  1636. /* user relations */
  1637. xs_list *lsts[] = { wing, wers, NULL };
  1638. int n;
  1639. for (n = 0; (p = lsts[n]) != NULL; n++) {
  1640. while (xs_list_iter(&p, &v)) {
  1641. /* already seen? skip */
  1642. if (xs_set_add(&seen, v) == 0)
  1643. continue;
  1644. xs *actor = NULL;
  1645. if (valid_status(object_get(v, &actor))) {
  1646. const char *uname = xs_dict_get(actor, "preferredUsername");
  1647. if (!xs_is_null(uname)) {
  1648. xs *luname = xs_tolower_i(xs_dup(uname));
  1649. if (xs_startswith(luname, q)) {
  1650. xs *acct = mastoapi_account(&snac1, actor);
  1651. out = xs_list_append(out, acct);
  1652. }
  1653. }
  1654. }
  1655. }
  1656. }
  1657. /* local users */
  1658. p = ulst;
  1659. while (xs_list_iter(&p, &v)) {
  1660. snac user;
  1661. /* skip this same user */
  1662. if (strcmp(v, xs_dict_get(snac1.config, "uid")) == 0)
  1663. continue;
  1664. /* skip if the uid does not start with the query */
  1665. xs *v2 = xs_tolower_i(xs_dup(v));
  1666. if (!xs_startswith(v2, q))
  1667. continue;
  1668. if (user_open(&user, v)) {
  1669. /* if it's not already seen, add it */
  1670. if (xs_set_add(&seen, user.actor) == 1) {
  1671. xs *actor = msg_actor(&user);
  1672. xs *acct = mastoapi_account(&snac1, actor);
  1673. out = xs_list_append(out, acct);
  1674. }
  1675. user_free(&user);
  1676. }
  1677. }
  1678. xs_set_free(&seen);
  1679. }
  1680. }
  1681. else
  1682. /* is it a local user? */
  1683. if (user_open(&snac2, uid) || user_open_by_md5(&snac2, uid)) {
  1684. if (opt == NULL) {
  1685. /* account information */
  1686. actor = msg_actor(&snac2);
  1687. out = mastoapi_account(NULL, actor);
  1688. }
  1689. else
  1690. if (strcmp(opt, "statuses") == 0) { /** **/
  1691. if (logged_in || xs_type(xs_dict_get(snac2.config, "private")) == XSTYPE_FALSE) {
  1692. /* the public list of posts of a user */
  1693. const char *limit_s = xs_dict_get(args, "limit");
  1694. const char *o_max_id = xs_dict_get(args, "max_id");
  1695. int limit = limit_s ? atoi(limit_s) : 20;
  1696. xs *max_id = o_max_id ? xs_tolower_i(xs_dup(o_max_id)) : NULL;
  1697. srv_debug(1, xs_fmt("account statuses: max_id=%s limit=%d", max_id ? max_id : "(null)", limit));
  1698. xs *timeline = timeline_simple_list(&snac2, "public", 0, 256, NULL);
  1699. xs_list *p = timeline;
  1700. const xs_str *v;
  1701. xs_set seen;
  1702. int cnt = 0;
  1703. int skip_until_max = max_id != NULL;
  1704. out = xs_list_new();
  1705. xs_set_init(&seen);
  1706. while (xs_list_iter(&p, &v) && cnt < limit) {
  1707. xs *msg = NULL;
  1708. if (valid_status(timeline_get_by_md5(&snac2, v, &msg))) {
  1709. const char *msg_id = xs_dict_get(msg, "id");
  1710. /* add only posts by the author */
  1711. if (!xs_is_null(msg_id) &&
  1712. strcmp(xs_dict_get(msg, "type"), "Note") == 0 &&
  1713. is_msg_mine(&snac2, xs_dict_get(msg, "id")) && is_msg_public(msg)) {
  1714. /* if max_id is set, skip entries until we find it */
  1715. if (skip_until_max) {
  1716. xs *mid = mastoapi_id(msg);
  1717. if (strcmp(mid, max_id) == 0) {
  1718. skip_until_max = 0;
  1719. srv_debug(2, xs_fmt("account statuses: found max_id, starting from next post"));
  1720. }
  1721. continue;
  1722. }
  1723. /* deduplicate by message id */
  1724. if (xs_set_add(&seen, msg_id) == 1) {
  1725. xs *st = mastoapi_status(&snac2, msg);
  1726. if (st) {
  1727. out = xs_list_append(out, st);
  1728. cnt++;
  1729. }
  1730. }
  1731. }
  1732. }
  1733. }
  1734. srv_debug(1, xs_fmt("account statuses: returning %d posts (requested %d)", cnt, limit));
  1735. xs_set_free(&seen);
  1736. }
  1737. else
  1738. status = HTTP_STATUS_UNAUTHORIZED;
  1739. }
  1740. else
  1741. if (strcmp(opt, "featured_tags") == 0) {
  1742. /* snac doesn't have features tags, yet? */
  1743. /* implement empty response so apps like Tokodon don't show an error */
  1744. out = xs_list_new();
  1745. }
  1746. else
  1747. if (strcmp(opt, "following") == 0) {
  1748. xs *wing = following_list(&snac1);
  1749. out = xs_list_new();
  1750. int c = 0;
  1751. const char *v;
  1752. while (xs_list_next(wing, &v, &c)) {
  1753. xs *actor = NULL;
  1754. if (valid_status(object_get(v, &actor))) {
  1755. xs *acct = mastoapi_account(NULL, actor);
  1756. out = xs_list_append(out, acct);
  1757. }
  1758. }
  1759. }
  1760. else
  1761. if (strcmp(opt, "followers") == 0) {
  1762. xs *wing = follower_list(&snac1);
  1763. out = xs_list_new();
  1764. int c = 0;
  1765. const char *v;
  1766. while (xs_list_next(wing, &v, &c)) {
  1767. xs *actor = NULL;
  1768. if (valid_status(object_get(v, &actor))) {
  1769. xs *acct = mastoapi_account(NULL, actor);
  1770. out = xs_list_append(out, acct);
  1771. }
  1772. }
  1773. }
  1774. else
  1775. if (strcmp(opt, "lists") == 0) {
  1776. out = mastoapi_account_lists(&snac1, uid);
  1777. }
  1778. else
  1779. if (strcmp(opt, "familiar_followers") == 0) {
  1780. /* familiar followers - not implemented, return empty array */
  1781. out = xs_list_new();
  1782. }
  1783. user_free(&snac2);
  1784. }
  1785. else {
  1786. /* try the uid as the md5 of a possibly loaded actor */
  1787. if (logged_in && valid_status(object_get_by_md5(uid, &actor))) {
  1788. if (opt == NULL) {
  1789. /* account information */
  1790. out = mastoapi_account(&snac1, actor);
  1791. }
  1792. else
  1793. if (strcmp(opt, "statuses") == 0) {
  1794. /* fetch statuses from remote outbox */
  1795. out = xs_list_new();
  1796. const char *outbox_url = xs_dict_get(actor, "outbox");
  1797. if (!xs_is_null(outbox_url)) {
  1798. /* extract query parameters */
  1799. const char *limit_s = xs_dict_get(args, "limit");
  1800. const char *exclude_replies_s = xs_dict_get(args, "exclude_replies");
  1801. const char *o_max_id = xs_dict_get(args, "max_id");
  1802. int limit = 20;
  1803. if (!xs_is_null(limit_s))
  1804. limit = atoi(limit_s);
  1805. if (limit == 0 || limit > 40)
  1806. limit = 20;
  1807. int exclude_replies = !xs_is_null(exclude_replies_s) &&
  1808. strcmp(exclude_replies_s, "true") == 0;
  1809. xs *max_id = o_max_id ? xs_tolower_i(xs_dup(o_max_id)) : NULL;
  1810. int skip_until_max = max_id != NULL;
  1811. srv_debug(1, xs_fmt("remote account statuses: fetching from %s (max_id=%s limit=%d)",
  1812. outbox_url, max_id ? max_id : "(null)", limit));
  1813. /* fetch first page only - safer for memory on large instances */
  1814. xs *outbox_collection = NULL;
  1815. xs *first_page = NULL;
  1816. const xs_list *items = get_collection_items(&snac1, outbox_url,
  1817. &outbox_collection, &first_page);
  1818. int count = 0;
  1819. int processed = 0;
  1820. if (!xs_is_null(items) && xs_type(items) == XSTYPE_LIST) {
  1821. int total_items = xs_list_len(items);
  1822. srv_debug(1, xs_fmt("remote account statuses: got %d items from outbox", total_items));
  1823. const xs_val *item;
  1824. xs_list_foreach(items, item) {
  1825. processed++;
  1826. if (count >= limit)
  1827. break;
  1828. const xs_dict *post = extract_post_from_item(item);
  1829. if (!post)
  1830. continue;
  1831. const char *post_type = xs_dict_get(post, "type");
  1832. const char *in_reply_to = xs_dict_get(post, "inReplyTo");
  1833. /* apply filters */
  1834. if (exclude_replies && !xs_is_null(in_reply_to))
  1835. continue;
  1836. if (is_valid_post_type(post_type)) {
  1837. /* store object locally so mastoapi_id() can generate valid IDs */
  1838. const char *post_id = xs_dict_get(post, "id");
  1839. if (!xs_is_null(post_id))
  1840. object_add(post_id, post);
  1841. /* handle pagination with max_id */
  1842. if (skip_until_max) {
  1843. xs *mid = mastoapi_id(post);
  1844. if (!xs_is_null(mid) && strcmp(mid, max_id) == 0) {
  1845. skip_until_max = 0;
  1846. srv_debug(2, xs_fmt("remote account statuses: found max_id at position %d", processed));
  1847. }
  1848. continue;
  1849. }
  1850. /* pass logged-in user context to enable media proxying if configured */
  1851. xs *st = mastoapi_status(&snac1, post);
  1852. if (st) {
  1853. out = xs_list_append(out, st);
  1854. count++;
  1855. }
  1856. }
  1857. }
  1858. }
  1859. else {
  1860. srv_debug(1, xs_fmt("remote account statuses: no items found in outbox"));
  1861. }
  1862. srv_debug(1, xs_fmt("remote account statuses: processed %d items, returning %d posts (requested %d)",
  1863. processed, count, limit));
  1864. }
  1865. }
  1866. else
  1867. if (strcmp(opt, "featured_tags") == 0) {
  1868. /* snac doesn't have features tags, yet? */
  1869. /* implement empty response so apps like Tokodon don't show an error */
  1870. out = xs_list_new();
  1871. }
  1872. else
  1873. if (strcmp(opt, "lists") == 0) {
  1874. out = mastoapi_account_lists(&snac1, uid);
  1875. }
  1876. else
  1877. if (strcmp(opt, "familiar_followers") == 0) {
  1878. /* familiar followers - not implemented, return empty array */
  1879. out = xs_list_new();
  1880. }
  1881. }
  1882. }
  1883. if (out != NULL) {
  1884. *body = xs_json_dumps(out, 4);
  1885. *ctype = "application/json";
  1886. status = HTTP_STATUS_OK;
  1887. }
  1888. }
  1889. }
  1890. else
  1891. if (strcmp(cmd, "/v1/timelines/home") == 0) { /** **/
  1892. /* the private timeline */
  1893. if (logged_in) {
  1894. xs *ifn = user_index_fn(&snac1, "private");
  1895. xs *out = mastoapi_timeline(&snac1, args, ifn);
  1896. *link = timeline_link_header("/api/v1/timelines/home", out);
  1897. *body = xs_json_dumps(out, 4);
  1898. *ctype = "application/json";
  1899. status = HTTP_STATUS_OK;
  1900. srv_debug(2, xs_fmt("mastoapi timeline: returned %d entries", xs_list_len(out)));
  1901. }
  1902. else {
  1903. status = HTTP_STATUS_UNAUTHORIZED;
  1904. }
  1905. }
  1906. else
  1907. if (strcmp(cmd, "/v1/timelines/public") == 0) { /** **/
  1908. /* the instance public timeline (public timelines for all users) */
  1909. xs *ifn = instance_index_fn();
  1910. xs *out = mastoapi_timeline(NULL, args, ifn);
  1911. *body = xs_json_dumps(out, 4);
  1912. *ctype = "application/json";
  1913. status = HTTP_STATUS_OK;
  1914. }
  1915. else
  1916. if (xs_startswith(cmd, "/v1/timelines/tag/")) { /** **/
  1917. /* get the tag */
  1918. xs *l = xs_split(cmd, "/");
  1919. const char *tag = xs_list_get(l, -1);
  1920. xs *ifn = tag_fn(tag);
  1921. xs *out = mastoapi_timeline(NULL, args, ifn);
  1922. *body = xs_json_dumps(out, 4);
  1923. *ctype = "application/json";
  1924. status = HTTP_STATUS_OK;
  1925. }
  1926. else
  1927. if (xs_startswith(cmd, "/v1/timelines/list/")) { /** **/
  1928. /* get the list id */
  1929. if (logged_in) {
  1930. xs *l = xs_split(cmd, "/");
  1931. const char *list = xs_list_get(l, -1);
  1932. xs *ifn = list_timeline_fn(&snac1, list);
  1933. xs *out = mastoapi_timeline(NULL, args, ifn);
  1934. *body = xs_json_dumps(out, 4);
  1935. *ctype = "application/json";
  1936. status = HTTP_STATUS_OK;
  1937. }
  1938. else
  1939. status = HTTP_STATUS_MISDIRECTED_REQUEST;
  1940. }
  1941. else
  1942. if (strcmp(cmd, "/v1/conversations") == 0) { /** **/
  1943. if (logged_in) {
  1944. *body = xs_dup("[]");
  1945. *ctype = "application/json";
  1946. status = HTTP_STATUS_OK;
  1947. }
  1948. else
  1949. status = HTTP_STATUS_UNAUTHORIZED;
  1950. }
  1951. else
  1952. if (strcmp(cmd, "/v1/notifications") == 0) { /** **/
  1953. if (logged_in) {
  1954. xs *l = notify_list(&snac1, 0, 64);
  1955. xs *out = xs_list_new();
  1956. const char *v;
  1957. const xs_list *excl = xs_dict_get(args, "exclude_types[]");
  1958. const xs_list *incl = xs_dict_get(args, "types[]");
  1959. const char *min_id = xs_dict_get(args, "min_id");
  1960. const char *max_id = xs_dict_get(args, "max_id");
  1961. const char *limit = xs_dict_get(args, "limit");
  1962. int limit_count = 0;
  1963. if (xs_is_string(limit)) {
  1964. limit_count = atoi(limit);
  1965. }
  1966. if (dbglevel) {
  1967. xs *js = xs_json_dumps(args, 0);
  1968. srv_debug(1, xs_fmt("mastoapi_notifications args %s", js));
  1969. }
  1970. xs_list_foreach(l, v) {
  1971. xs *noti = notify_get(&snac1, v);
  1972. if (noti == NULL)
  1973. continue;
  1974. const xs_dict *tag = xs_list_get(xs_dict_get_path(noti, "msg.tag"), 0);
  1975. const char *type = xs_dict_get(noti, "type");
  1976. const char *utype = xs_dict_get(noti, "utype");
  1977. const char *objid = xs_dict_get(noti, "objid");
  1978. const char *id = xs_dict_get(noti, "id");
  1979. const char *actid = xs_dict_get(noti, "actor");
  1980. int isEmoji = 0;
  1981. xs *fid = xs_replace(id, ".", "");
  1982. xs *actor = NULL;
  1983. xs *entry = NULL;
  1984. if (tag) {
  1985. isEmoji = strcmp(xs_dict_get(tag, "type"), "Emoji") ? 0 : 1;
  1986. }
  1987. if (!valid_status(actor_get(actid, &actor)))
  1988. continue;
  1989. if (objid != NULL && !valid_status(object_get(objid, &entry)))
  1990. continue;
  1991. if (is_hidden(&snac1, objid))
  1992. continue;
  1993. if (max_id) {
  1994. if (strcmp(fid, max_id) == 0)
  1995. max_id = NULL;
  1996. continue;
  1997. }
  1998. if (min_id) {
  1999. if (strcmp(fid, min_id) <= 0) {
  2000. continue;
  2001. }
  2002. }
  2003. /* convert the type */
  2004. if (strcmp(type, "Like") == 0 && !isEmoji)
  2005. type = "favourite";
  2006. else
  2007. if (isEmoji || strcmp(type, "EmojiReact") == 0)
  2008. type = "reaction";
  2009. else
  2010. if (strcmp(type, "Announce") == 0)
  2011. type = "reblog";
  2012. else
  2013. if (strcmp(type, "Follow") == 0)
  2014. type = "follow";
  2015. else
  2016. if (strcmp(type, "Create") == 0) {
  2017. const xs_dict *obj = xs_dict_get_path(noti, "msg.object");
  2018. if (xs_is_dict(obj) && was_mentioned(&snac1, obj))
  2019. type = "mention";
  2020. else
  2021. type = "status";
  2022. }
  2023. else
  2024. if (strcmp(type, "Update") == 0 && strcmp(utype, "Question") == 0)
  2025. type = "poll";
  2026. else
  2027. continue;
  2028. /* excluded type? */
  2029. if (xs_is_list(excl) && xs_list_in(excl, type) != -1)
  2030. continue;
  2031. /* included type? */
  2032. if (xs_is_list(incl) && xs_list_in(incl, type) == -1)
  2033. continue;
  2034. xs *mn = xs_dict_new();
  2035. mn = xs_dict_append(mn, "type", type);
  2036. mn = xs_dict_append(mn, "id", fid);
  2037. mn = xs_dict_append(mn, "created_at", xs_dict_get(noti, "date"));
  2038. xs *acct = mastoapi_account(&snac1, actor);
  2039. if (acct == NULL)
  2040. continue;
  2041. mn = xs_dict_append(mn, "account", acct);
  2042. if (strcmp(type, "follow") != 0 && !xs_is_null(objid)) {
  2043. xs *st = mastoapi_status(&snac1, entry);
  2044. if (st) {
  2045. mn = xs_dict_append(mn, "status", st);
  2046. if (strcmp(type, "reaction") == 0 && !xs_is_null(objid)) {
  2047. const char *eid = NULL;
  2048. const char *url = NULL;
  2049. int utf = 0;
  2050. const xs_dict *tag = xs_list_get(xs_dict_get_path(noti, "msg.tag"), 0);
  2051. const char *content = xs_dict_get_path(noti, "msg.content");
  2052. url = xs_dict_get(xs_dict_get(tag, "icon"), "url");
  2053. eid = xs_dict_get(tag, "name");
  2054. if (eid && url) {
  2055. mn = xs_dict_append(mn, "emoji", eid);
  2056. mn = xs_dict_append(mn, "emoji_url", url);
  2057. }
  2058. if (xs_is_emoji((utf = xs_utf8_dec(&content)))) {
  2059. xs *s1 = xs_fmt("&#%d;", utf);
  2060. mn = xs_dict_append(mn, "name", s1);
  2061. }
  2062. }
  2063. }
  2064. }
  2065. out = xs_list_append(out, mn);
  2066. if (--limit_count <= 0)
  2067. break;
  2068. }
  2069. srv_debug(1, xs_fmt("mastoapi_notifications count %d", xs_list_len(out)));
  2070. *body = xs_json_dumps(out, 4);
  2071. *ctype = "application/json";
  2072. status = HTTP_STATUS_OK;
  2073. }
  2074. else
  2075. status = HTTP_STATUS_UNAUTHORIZED;
  2076. }
  2077. else
  2078. if (strcmp(cmd, "/v1/filters") == 0) { /** **/
  2079. /* snac will never have filters */
  2080. if (logged_in) {
  2081. *body = xs_dup("[]");
  2082. *ctype = "application/json";
  2083. status = HTTP_STATUS_OK;
  2084. }
  2085. else
  2086. status = HTTP_STATUS_UNAUTHORIZED;
  2087. }
  2088. else
  2089. if (strcmp(cmd, "/v2/filters") == 0) { /** **/
  2090. /* snac will never have filters
  2091. * but still, without a v2 endpoint a short delay is introduced
  2092. * in some apps */
  2093. if (logged_in) {
  2094. *body = xs_dup("[]");
  2095. *ctype = "application/json";
  2096. status = HTTP_STATUS_OK;
  2097. }
  2098. else
  2099. status = HTTP_STATUS_UNAUTHORIZED;
  2100. }
  2101. else
  2102. if (strcmp(cmd, "/v1/favourites") == 0) { /** **/
  2103. /* snac will never support a list of favourites */
  2104. if (logged_in) {
  2105. *body = xs_dup("[]");
  2106. *ctype = "application/json";
  2107. status = HTTP_STATUS_OK;
  2108. }
  2109. else
  2110. status = HTTP_STATUS_UNAUTHORIZED;
  2111. }
  2112. else
  2113. if (strcmp(cmd, "/v1/bookmarks") == 0) { /** **/
  2114. if (logged_in) {
  2115. xs *ifn = bookmark_index_fn(&snac1);
  2116. xs *out = mastoapi_timeline(&snac1, args, ifn);
  2117. *body = xs_json_dumps(out, 4);
  2118. *ctype = "application/json";
  2119. status = HTTP_STATUS_OK;
  2120. }
  2121. else
  2122. status = HTTP_STATUS_UNAUTHORIZED;
  2123. }
  2124. else
  2125. if (strcmp(cmd, "/v1/lists") == 0) { /** list of lists **/
  2126. if (logged_in) {
  2127. xs *l = mastoapi_account_lists(&snac1, NULL);
  2128. *body = xs_json_dumps(l, 4);
  2129. *ctype = "application/json";
  2130. status = HTTP_STATUS_OK;
  2131. }
  2132. else
  2133. status = HTTP_STATUS_UNAUTHORIZED;
  2134. }
  2135. else
  2136. if (xs_startswith(cmd, "/v1/lists/")) { /** list information **/
  2137. if (logged_in) {
  2138. xs *l = xs_split(cmd, "/");
  2139. const char *p = xs_list_get(l, -1);
  2140. if (p) {
  2141. if (strcmp(p, "accounts") == 0) {
  2142. p = xs_list_get(l, -2);
  2143. if (p && xs_is_hex(p)) {
  2144. xs *actors = list_members(&snac1, p, NULL, OP_LIST);
  2145. xs *out = xs_list_new();
  2146. int c = 0;
  2147. const char *v;
  2148. while (xs_list_next(actors, &v, &c)) {
  2149. xs *actor = NULL;
  2150. if (valid_status(object_get_by_md5(v, &actor))) {
  2151. xs *acct = mastoapi_account(&snac1, actor);
  2152. out = xs_list_append(out, acct);
  2153. }
  2154. }
  2155. *body = xs_json_dumps(out, 4);
  2156. *ctype = "application/json";
  2157. status = HTTP_STATUS_OK;
  2158. }
  2159. }
  2160. else
  2161. if (xs_is_hex(p)) {
  2162. xs *out = xs_list_new();
  2163. xs *lol = list_maint(&snac1, NULL, OP_LIST);
  2164. int c = 0;
  2165. const xs_list *v;
  2166. while (xs_list_next(lol, &v, &c)) {
  2167. const char *id = xs_list_get(v, 0);
  2168. if (id && strcmp(id, p) == 0) {
  2169. xs *d = xs_dict_new();
  2170. d = xs_dict_append(d, "id", p);
  2171. d = xs_dict_append(d, "title", xs_list_get(v, 1));
  2172. d = xs_dict_append(d, "replies_policy", "list");
  2173. d = xs_dict_append(d, "exclusive", xs_stock(XSTYPE_FALSE));
  2174. out = xs_dup(d);
  2175. break;
  2176. }
  2177. }
  2178. *body = xs_json_dumps(out, 4);
  2179. *ctype = "application/json";
  2180. status = HTTP_STATUS_OK;
  2181. }
  2182. }
  2183. }
  2184. else
  2185. status = HTTP_STATUS_UNAUTHORIZED;
  2186. }
  2187. else
  2188. if (strcmp(cmd, "/v1/scheduled_statuses") == 0) { /** **/
  2189. if (logged_in) {
  2190. *body = xs_dup("[]");
  2191. *ctype = "application/json";
  2192. status = HTTP_STATUS_OK;
  2193. }
  2194. else
  2195. status = HTTP_STATUS_UNAUTHORIZED;
  2196. }
  2197. else
  2198. if (strcmp(cmd, "/v1/follow_requests") == 0) { /** **/
  2199. if (logged_in) {
  2200. xs *pend = pending_list(&snac1);
  2201. xs *resp = xs_list_new();
  2202. const char *id;
  2203. xs_list_foreach(pend, id) {
  2204. xs *actor = NULL;
  2205. if (valid_status(object_get(id, &actor))) {
  2206. xs *acct = mastoapi_account(&snac1, actor);
  2207. if (acct)
  2208. resp = xs_list_append(resp, acct);
  2209. }
  2210. }
  2211. *body = xs_json_dumps(resp, 4);
  2212. *ctype = "application/json";
  2213. status = HTTP_STATUS_OK;
  2214. }
  2215. }
  2216. else
  2217. if (strcmp(cmd, "/v1/announcements") == 0) { /** **/
  2218. if (logged_in) {
  2219. xs *resp = xs_list_new();
  2220. double la = 0.0;
  2221. xs *user_la = xs_dup(xs_dict_get(snac1.config, "last_announcement"));
  2222. if (user_la != NULL)
  2223. la = xs_number_get(user_la);
  2224. xs *val_date = xs_str_utctime(la, ISO_DATE_SPEC);
  2225. /* contrary to html, we always send the announcement and set the read flag instead */
  2226. const t_announcement *annce = announcement(la);
  2227. if (annce != NULL && annce->text != NULL) {
  2228. xs *an = xs_dict_new();
  2229. xs *id = xs_fmt("%d", annce->timestamp);
  2230. xs *ct = xs_fmt("<p>%s</p>", annce->text);
  2231. an = xs_dict_set(an, "id", id);
  2232. an = xs_dict_set(an, "content", ct);
  2233. an = xs_dict_set(an, "starts_at", xs_stock(XSTYPE_NULL));
  2234. an = xs_dict_set(an, "ends_at", xs_stock(XSTYPE_NULL));
  2235. an = xs_dict_set(an, "all_day", xs_stock(XSTYPE_TRUE));
  2236. an = xs_dict_set(an, "published_at", val_date);
  2237. an = xs_dict_set(an, "updated_at", val_date);
  2238. an = xs_dict_set(an, "read", (annce->timestamp >= la)
  2239. ? xs_stock(XSTYPE_FALSE) : xs_stock(XSTYPE_TRUE));
  2240. an = xs_dict_set(an, "mentions", xs_stock(XSTYPE_LIST));
  2241. an = xs_dict_set(an, "statuses", xs_stock(XSTYPE_LIST));
  2242. an = xs_dict_set(an, "tags", xs_stock(XSTYPE_LIST));
  2243. an = xs_dict_set(an, "emojis", xs_stock(XSTYPE_LIST));
  2244. an = xs_dict_set(an, "reactions", xs_stock(XSTYPE_LIST));
  2245. resp = xs_list_append(resp, an);
  2246. }
  2247. *body = xs_json_dumps(resp, 4);
  2248. *ctype = "application/json";
  2249. status = HTTP_STATUS_OK;
  2250. }
  2251. }
  2252. else
  2253. if (strcmp(cmd, "/v1/custom_emojis") == 0) { /** **/
  2254. xs *emo = emojis();
  2255. xs *list = xs_list_new();
  2256. const xs_str *k;
  2257. const xs_val *v;
  2258. xs_dict_foreach(emo, k, v) {
  2259. xs *current = xs_dict_new();
  2260. if ((xs_startswith(v, "https://") && xs_startswith((xs_mime_by_ext(v)), "image/")) || xs_type(v) == XSTYPE_DICT) {
  2261. /* remove first and last colon */
  2262. if (xs_type(v) == XSTYPE_DICT) {
  2263. const char *v2;
  2264. const char *cat = k;
  2265. xs_dict_foreach(v, k, v2) {
  2266. xs *shortcode = xs_replace(k, ":", "");
  2267. current = xs_dict_append(current, "shortcode", shortcode);
  2268. current = xs_dict_append(current, "url", v2);
  2269. current = xs_dict_append(current, "static_url", v2);
  2270. current = xs_dict_append(current, "visible_in_picker", xs_stock(XSTYPE_TRUE));
  2271. current = xs_dict_append(current, "category", cat);
  2272. list = xs_list_append(list, current);
  2273. }
  2274. }
  2275. else {
  2276. xs *shortcode = xs_replace(k, ":", "");
  2277. current = xs_dict_append(current, "shortcode", shortcode);
  2278. current = xs_dict_append(current, "url", v);
  2279. current = xs_dict_append(current, "static_url", v);
  2280. current = xs_dict_append(current, "visible_in_picker", xs_stock(XSTYPE_TRUE));
  2281. list = xs_list_append(list, current);
  2282. }
  2283. }
  2284. }
  2285. *body = xs_json_dumps(list, 0);
  2286. *ctype = "application/json";
  2287. status = HTTP_STATUS_OK;
  2288. }
  2289. else
  2290. if (strcmp(cmd, "/v1/instance") == 0) { /** **/
  2291. /* returns an instance object */
  2292. xs *ins = xs_dict_new();
  2293. const char *host = xs_dict_get(srv_config, "host");
  2294. const char *title = xs_dict_get(srv_config, "title");
  2295. const char *sdesc = xs_dict_get(srv_config, "short_description");
  2296. ins = xs_dict_append(ins, "uri", host);
  2297. ins = xs_dict_append(ins, "domain", host);
  2298. ins = xs_dict_append(ins, "title", title && *title ? title : host);
  2299. ins = xs_dict_append(ins, "version", "4.0.0 (not true; really " USER_AGENT ")");
  2300. ins = xs_dict_append(ins, "source_url", WHAT_IS_SNAC_URL);
  2301. ins = xs_dict_append(ins, "description", host);
  2302. ins = xs_dict_append(ins, "short_description", sdesc && *sdesc ? sdesc : host);
  2303. xs *susie = xs_fmt("%s/susie.png", srv_baseurl);
  2304. ins = xs_dict_append(ins, "thumbnail", susie);
  2305. const char *v = xs_dict_get(srv_config, "admin_email");
  2306. if (xs_is_null(v) || *v == '\0')
  2307. v = "admin@localhost";
  2308. ins = xs_dict_append(ins, "email", v);
  2309. ins = xs_dict_append(ins, "rules", xs_stock(XSTYPE_LIST));
  2310. xs *l1 = xs_list_append(xs_list_new(), "en");
  2311. ins = xs_dict_append(ins, "languages", l1);
  2312. xs *wss = xs_fmt("wss:/" "/%s", xs_dict_get(srv_config, "host"));
  2313. xs *urls = xs_dict_new();
  2314. urls = xs_dict_append(urls, "streaming_api", wss);
  2315. ins = xs_dict_append(ins, "urls", urls);
  2316. xs *d2 = xs_dict_append(xs_dict_new(), "user_count", xs_stock(0));
  2317. d2 = xs_dict_append(d2, "status_count", xs_stock(0));
  2318. d2 = xs_dict_append(d2, "domain_count", xs_stock(0));
  2319. ins = xs_dict_append(ins, "stats", d2);
  2320. ins = xs_dict_append(ins, "registrations", xs_stock(XSTYPE_FALSE));
  2321. ins = xs_dict_append(ins, "approval_required", xs_stock(XSTYPE_FALSE));
  2322. ins = xs_dict_append(ins, "invites_enabled", xs_stock(XSTYPE_FALSE));
  2323. xs *cfg = xs_dict_new();
  2324. {
  2325. xs *d11 = xs_json_loads("{\"characters_reserved_per_url\":32,"
  2326. "\"max_characters\":100000,\"max_media_attachments\":4}");
  2327. const xs_number *max_attachments = xs_dict_get(srv_config, "max_attachments");
  2328. if (xs_type(max_attachments) == XSTYPE_NUMBER)
  2329. d11 = xs_dict_set(d11, "max_media_attachments", max_attachments);
  2330. cfg = xs_dict_append(cfg, "statuses", d11);
  2331. xs *d12 = xs_json_loads("{\"max_featured_tags\":0}");
  2332. cfg = xs_dict_append(cfg, "accounts", d12);
  2333. xs *d13 = xs_json_loads("{\"image_matrix_limit\":33177600,"
  2334. "\"image_size_limit\":16777216,"
  2335. "\"video_frame_rate_limit\":120,"
  2336. "\"video_matrix_limit\":8294400,"
  2337. "\"video_size_limit\":103809024}"
  2338. );
  2339. {
  2340. /* get the supported mime types from the internal list */
  2341. const char **p = xs_mime_types;
  2342. xs_set mtypes;
  2343. xs_set_init(&mtypes);
  2344. while (*p) {
  2345. const char *type = p[1];
  2346. if (xs_startswith(type, "image/") ||
  2347. xs_startswith(type, "video/") ||
  2348. xs_startswith(type, "audio/"))
  2349. xs_set_add(&mtypes, type);
  2350. p += 2;
  2351. }
  2352. xs *l = xs_set_result(&mtypes);
  2353. d13 = xs_dict_append(d13, "supported_mime_types", l);
  2354. }
  2355. cfg = xs_dict_append(cfg, "media_attachments", d13);
  2356. xs *d14 = xs_json_loads("{\"max_characters_per_option\":50,"
  2357. "\"max_expiration\":2629746,"
  2358. "\"max_options\":8,\"min_expiration\":300}");
  2359. cfg = xs_dict_append(cfg, "polls", d14);
  2360. xs *d15 = xs_json_loads("{\"max_reactions\":50}");
  2361. cfg = xs_dict_append(cfg, "reactions", d15);
  2362. }
  2363. ins = xs_dict_append(ins, "configuration", cfg);
  2364. const char *admin_account = xs_dict_get(srv_config, "admin_account");
  2365. if (!xs_is_null(admin_account) && *admin_account) {
  2366. snac admin;
  2367. if (user_open(&admin, admin_account)) {
  2368. xs *actor = msg_actor(&admin);
  2369. xs *acct = mastoapi_account(NULL, actor);
  2370. ins = xs_dict_append(ins, "contact_account", acct);
  2371. user_free(&admin);
  2372. }
  2373. }
  2374. *body = xs_json_dumps(ins, 4);
  2375. *ctype = "application/json";
  2376. status = HTTP_STATUS_OK;
  2377. }
  2378. else
  2379. if (strcmp(cmd, "/v1/instance/peers") == 0) { /** **/
  2380. /* get the collected inbox list as the instances "this domain is aware of" */
  2381. xs *list = inbox_list();
  2382. xs *peers = xs_list_new();
  2383. const char *inbox;
  2384. xs_list_foreach(list, inbox) {
  2385. xs *l = xs_split(inbox, "/");
  2386. const char *domain = xs_list_get(l, 2);
  2387. if (xs_is_string(domain))
  2388. peers = xs_list_append(peers, domain);
  2389. }
  2390. *body = xs_json_dumps(peers, 4);
  2391. *ctype = "application/json";
  2392. status = HTTP_STATUS_OK;
  2393. }
  2394. else
  2395. if (strcmp(cmd, "/v1/instance/extended_description") == 0) { /** **/
  2396. xs *d = xs_dict_new();
  2397. xs *greeting = xs_fmt("%s/greeting.html", srv_basedir);
  2398. time_t t = mtime(greeting);
  2399. xs *updated_at = xs_str_iso_date(t);
  2400. xs *content = xs_replace(snac_blurb, "%host%", xs_dict_get(srv_config, "host"));
  2401. d = xs_dict_set(d, "updated_at", updated_at);
  2402. d = xs_dict_set(d, "content", content);
  2403. *body = xs_json_dumps(d, 4);
  2404. *ctype = "application/json";
  2405. status = HTTP_STATUS_OK;
  2406. }
  2407. else
  2408. if (xs_startswith(cmd, "/v1/statuses/")) { /** **/
  2409. /* information about a status */
  2410. if (logged_in) {
  2411. xs *l = xs_split(cmd, "/");
  2412. const char *oid = xs_list_get(l, 3);
  2413. const char *op = xs_list_get(l, 4);
  2414. if (!xs_is_null(oid)) {
  2415. xs *msg = NULL;
  2416. xs *out = NULL;
  2417. /* skip the 'fake' part of the id */
  2418. oid = MID_TO_MD5(oid);
  2419. xs *id = xs_tolower_i(xs_dup(oid));
  2420. if (valid_status(object_get_by_md5(id, &msg))) {
  2421. if (op == NULL) {
  2422. if (!is_muted(&snac1, get_atto(msg))) {
  2423. /* return the status itself */
  2424. out = mastoapi_status(&snac1, msg);
  2425. }
  2426. }
  2427. else
  2428. if (strcmp(op, "context") == 0) { /** **/
  2429. /* return ancestors and children */
  2430. xs *anc = xs_list_new();
  2431. xs *des = xs_list_new();
  2432. char pid[MD5_HEX_SIZE];
  2433. /* build the [grand]parent list, moving up */
  2434. strncpy(pid, id, sizeof(pid));
  2435. while (object_parent(pid, pid)) {
  2436. xs *m2 = NULL;
  2437. if (valid_status(timeline_get_by_md5(&snac1, pid, &m2))) {
  2438. xs *st = mastoapi_status(&snac1, m2);
  2439. if (st)
  2440. anc = xs_list_insert(anc, 0, st);
  2441. }
  2442. else
  2443. break;
  2444. }
  2445. /* build the children list */
  2446. xs *childs = build_childrens(msg, &snac1);
  2447. if (xs_list_len(childs) > 0)
  2448. des = xs_list_cat(des, childs);
  2449. out = xs_dict_new();
  2450. out = xs_dict_append(out, "ancestors", anc);
  2451. out = xs_dict_append(out, "descendants", des);
  2452. }
  2453. else
  2454. if (strcmp(op, "reblogged_by") == 0 || /** **/
  2455. strcmp(op, "favourited_by") == 0) { /** **/
  2456. /* return the list of people who liked or boosted this */
  2457. out = xs_list_new();
  2458. xs *l = NULL;
  2459. if (op[0] == 'r')
  2460. l = object_announces(xs_dict_get(msg, "id"));
  2461. else
  2462. l = object_likes(xs_dict_get(msg, "id"));
  2463. xs_list *p = l;
  2464. const xs_str *v;
  2465. while (xs_list_iter(&p, &v)) {
  2466. xs *actor2 = NULL;
  2467. if (valid_status(object_get_by_md5(v, &actor2))) {
  2468. xs *acct2 = mastoapi_account(&snac1, actor2);
  2469. out = xs_list_append(out, acct2);
  2470. }
  2471. }
  2472. }
  2473. else
  2474. if (strcmp(op, "source") == 0) { /** **/
  2475. out = xs_dict_new();
  2476. /* get the mastoapi status id */
  2477. out = xs_dict_append(out, "id", xs_list_get(l, 3));
  2478. out = xs_dict_append(out, "text", xs_dict_get(msg, "sourceContent"));
  2479. out = xs_dict_append(out, "spoiler_text", xs_dict_get(msg, "summary"));
  2480. }
  2481. }
  2482. else
  2483. srv_debug(1, xs_fmt("mastoapi status: bad id %s", id));
  2484. if (out != NULL) {
  2485. *body = xs_json_dumps(out, 4);
  2486. *ctype = "application/json";
  2487. status = HTTP_STATUS_OK;
  2488. }
  2489. }
  2490. }
  2491. else
  2492. status = HTTP_STATUS_UNAUTHORIZED;
  2493. }
  2494. else
  2495. if (strcmp(cmd, "/v1/preferences") == 0) { /** **/
  2496. /* TBD */
  2497. if (logged_in) {
  2498. *body = xs_dup("{}");
  2499. *ctype = "application/json";
  2500. status = HTTP_STATUS_OK;
  2501. }
  2502. else
  2503. status = HTTP_STATUS_UNAUTHORIZED;
  2504. }
  2505. else
  2506. if (strcmp(cmd, "/v1/markers") == 0) { /** **/
  2507. if (logged_in) {
  2508. const xs_list *timeline = xs_dict_get(args, "timeline[]");
  2509. xs_str *json = NULL;
  2510. if (!xs_is_null(timeline))
  2511. json = xs_json_dumps(markers_get(&snac1, timeline), 4);
  2512. if (!xs_is_null(json))
  2513. *body = json;
  2514. else
  2515. *body = xs_dup("{}");
  2516. *ctype = "application/json";
  2517. status = HTTP_STATUS_OK;
  2518. }
  2519. else
  2520. status = HTTP_STATUS_UNAUTHORIZED;
  2521. }
  2522. else
  2523. if (strcmp(cmd, "/v1/followed_tags") == 0) { /** **/
  2524. if (logged_in) {
  2525. xs *r = xs_list_new();
  2526. const xs_list *followed_hashtags = xs_dict_get_def(snac1.config,
  2527. "followed_hashtags", xs_stock(XSTYPE_LIST));
  2528. const char *hashtag;
  2529. xs_list_foreach(followed_hashtags, hashtag) {
  2530. if (*hashtag == '#') {
  2531. xs *d = xs_dict_new();
  2532. xs *s = xs_fmt("%s?t=%s", srv_baseurl, hashtag + 1);
  2533. d = xs_dict_set(d, "name", hashtag + 1);
  2534. d = xs_dict_set(d, "url", s);
  2535. d = xs_dict_set(d, "history", xs_stock(XSTYPE_LIST));
  2536. r = xs_list_append(r, d);
  2537. }
  2538. }
  2539. *body = xs_json_dumps(r, 4);
  2540. *ctype = "application/json";
  2541. status = HTTP_STATUS_OK;
  2542. }
  2543. else
  2544. status = HTTP_STATUS_UNAUTHORIZED;
  2545. }
  2546. else
  2547. if (strcmp(cmd, "/v1/blocks") == 0) { /** **/
  2548. if (logged_in) {
  2549. *body = xs_dup("[]");
  2550. *ctype = "application/json";
  2551. status = HTTP_STATUS_OK;
  2552. }
  2553. else
  2554. status = HTTP_STATUS_UNAUTHORIZED;
  2555. }
  2556. else
  2557. if (strcmp(cmd, "/v1/mutes") == 0) { /** **/
  2558. if (logged_in) {
  2559. *body = xs_dup("[]");
  2560. *ctype = "application/json";
  2561. status = HTTP_STATUS_OK;
  2562. }
  2563. else
  2564. status = HTTP_STATUS_UNAUTHORIZED;
  2565. }
  2566. else
  2567. if (strcmp(cmd, "/v1/trends/tags") == 0) { /** **/
  2568. *body = xs_dup("[]");
  2569. *ctype = "application/json";
  2570. status = HTTP_STATUS_OK;
  2571. }
  2572. else
  2573. if (strcmp(cmd, "/v1/trends/statuses") == 0) { /** **/
  2574. *body = xs_dup("[]");
  2575. *ctype = "application/json";
  2576. status = HTTP_STATUS_OK;
  2577. }
  2578. else
  2579. if (strcmp(cmd, "/v2/search") == 0) { /** **/
  2580. if (logged_in) {
  2581. const char *q = xs_dict_get(args, "q");
  2582. const char *type = xs_dict_get(args, "type");
  2583. const char *offset = xs_dict_get(args, "offset");
  2584. xs *acl = xs_list_new();
  2585. xs *stl = xs_list_new();
  2586. xs *htl = xs_list_new();
  2587. xs *res = xs_dict_new();
  2588. if (xs_is_null(offset) || strcmp(offset, "0") == 0) {
  2589. /* reply something only for offset 0; otherwise,
  2590. apps like Tusky keep asking again and again */
  2591. if (xs_startswith(q, "https://")) {
  2592. if (!timeline_here(&snac1, q)) {
  2593. xs *object = NULL;
  2594. int status;
  2595. status = activitypub_request(&snac1, q, &object);
  2596. snac_debug(&snac1, 1, xs_fmt("Request searched URL %s %d", q, status));
  2597. if (valid_status(status)) {
  2598. /* got it; also request the actor */
  2599. const char *attr_to = get_atto(object);
  2600. xs *actor_obj = NULL;
  2601. if (!xs_is_null(attr_to)) {
  2602. status = actor_request(&snac1, attr_to, &actor_obj);
  2603. snac_debug(&snac1, 1, xs_fmt("Request author %s of %s %d", attr_to, q, status));
  2604. if (valid_status(status)) {
  2605. /* add the actor */
  2606. actor_add(attr_to, actor_obj);
  2607. /* add the post to the timeline */
  2608. timeline_add(&snac1, q, object);
  2609. }
  2610. }
  2611. }
  2612. }
  2613. }
  2614. if (!xs_is_null(q)) {
  2615. if (xs_is_null(type) || strcmp(type, "accounts") == 0) {
  2616. /* do a webfinger query */
  2617. char *actor = NULL;
  2618. char *user = NULL;
  2619. if (valid_status(webfinger_request(q, &actor, &user)) && actor) {
  2620. xs *actor_o = NULL;
  2621. if (valid_status(actor_request(&snac1, actor, &actor_o))) {
  2622. xs *acct = mastoapi_account(NULL, actor_o);
  2623. acl = xs_list_append(acl, acct);
  2624. if (!object_here(actor))
  2625. object_add(actor, actor_o);
  2626. }
  2627. }
  2628. }
  2629. if (xs_is_null(type) || strcmp(type, "hashtags") == 0) {
  2630. /* search this tag */
  2631. xs *tl = tag_search((char *)q, 0, 1);
  2632. if (xs_list_len(tl)) {
  2633. xs *d = xs_dict_new();
  2634. d = xs_dict_append(d, "name", q);
  2635. xs *url = xs_fmt("%s?t=%s", srv_baseurl, q);
  2636. d = xs_dict_append(d, "url", url);
  2637. d = xs_dict_append(d, "history", xs_stock(XSTYPE_LIST));
  2638. htl = xs_list_append(htl, d);
  2639. }
  2640. }
  2641. if (xs_is_null(type) || strcmp(type, "statuses") == 0) {
  2642. int to = 0;
  2643. int cnt = 40;
  2644. xs *tl = content_search(&snac1, q, 1, 0, cnt, 0, &to);
  2645. int c = 0;
  2646. const char *v;
  2647. while (xs_list_next(tl, &v, &c) && --cnt) {
  2648. xs *post = NULL;
  2649. if (!valid_status(timeline_get_by_md5(&snac1, v, &post)))
  2650. continue;
  2651. xs *s = mastoapi_status(&snac1, post);
  2652. if (!xs_is_null(s))
  2653. stl = xs_list_append(stl, s);
  2654. }
  2655. }
  2656. }
  2657. }
  2658. res = xs_dict_append(res, "accounts", acl);
  2659. res = xs_dict_append(res, "statuses", stl);
  2660. res = xs_dict_append(res, "hashtags", htl);
  2661. *body = xs_json_dumps(res, 4);
  2662. *ctype = "application/json";
  2663. status = HTTP_STATUS_OK;
  2664. }
  2665. else
  2666. status = HTTP_STATUS_UNAUTHORIZED;
  2667. }
  2668. else
  2669. if (xs_startswith(cmd, "/v1/media/") || xs_startswith(cmd, "/v2/media/")) { /** **/
  2670. if (logged_in) {
  2671. xs *p = xs_split(cmd, "/");
  2672. const char *id = xs_list_get(p, -1);
  2673. if (xs_is_string(id)) {
  2674. xs *filename = xs_fmt("%s/static/%s", snac1.basedir, id);
  2675. if (mtime(filename)) {
  2676. /* file exists */
  2677. xs *alt = static_get_meta(&snac1, id);
  2678. xs *url = xs_fmt("%s/s/%s", snac1.actor, id);
  2679. xs *mime = xs_split(xs_mime_by_ext(filename), "/");
  2680. const char *type = xs_list_get(mime, 0);
  2681. if (!xs_match(type, "image|video|audio"))
  2682. type = "unknown";
  2683. xs *d = xs_dict_new();
  2684. d = xs_dict_set(d, "id", id);
  2685. d = xs_dict_set(d, "url", url);
  2686. d = xs_dict_set(d, "preview_url", url);
  2687. d = xs_dict_set(d, "remote_url", url);
  2688. d = xs_dict_set(d, "type", type);
  2689. d = xs_dict_set(d, "description", xs_or(alt, ""));
  2690. *body = xs_json_dumps(d, 4);
  2691. *ctype = "application/json";
  2692. status = HTTP_STATUS_OK;
  2693. }
  2694. }
  2695. }
  2696. else
  2697. status = HTTP_STATUS_UNAUTHORIZED;
  2698. }
  2699. /* user cleanup */
  2700. if (logged_in)
  2701. user_free(&snac1);
  2702. srv_debug(1, xs_fmt("mastoapi_get_handler %s %d", q_path, status));
  2703. return status;
  2704. }
  2705. int mastoapi_post_handler(const xs_dict *req, const char *q_path,
  2706. const char *payload, int p_size,
  2707. char **body, int *b_size, char **ctype)
  2708. {
  2709. (void)p_size;
  2710. (void)b_size;
  2711. if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
  2712. return 0;
  2713. int status = HTTP_STATUS_NOT_FOUND;
  2714. xs *args = NULL;
  2715. const char *i_ctype = xs_dict_get(req, "content-type");
  2716. if (i_ctype && xs_startswith(i_ctype, "application/json")) {
  2717. if (!xs_is_null(payload)) {
  2718. args = xs_json_loads(payload);
  2719. }
  2720. }
  2721. else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
  2722. {
  2723. // Some apps send form data instead of json so we should cater for those
  2724. if (!xs_is_null(payload)) {
  2725. args = xs_url_vars(payload);
  2726. }
  2727. }
  2728. else if (i_ctype && xs_startswith(i_ctype, "multipart/form-data"))
  2729. {
  2730. // Handle multipart/form-data by using p_vars (already parsed by httpd)
  2731. args = xs_dup(xs_dict_get(req, "p_vars"));
  2732. }
  2733. /* if args still NULL, try falling back to p_vars or q_vars */
  2734. if (args == NULL)
  2735. args = xs_dup(xs_dict_get(req, "p_vars"));
  2736. if (args == NULL)
  2737. args = xs_dup(xs_dict_get(req, "q_vars"));
  2738. if (args == NULL) {
  2739. srv_debug(1, xs_fmt("mastoapi_post_handler: failed to parse args for %s, content-type: %s",
  2740. q_path, i_ctype ? i_ctype : "(null)"));
  2741. return HTTP_STATUS_BAD_REQUEST;
  2742. }
  2743. xs *cmd = xs_replace_n(q_path, "/api", "", 1);
  2744. snac snac = {0};
  2745. int logged_in = process_auth_token(&snac, req);
  2746. if (strcmp(cmd, "/v1/apps") == 0) { /** **/
  2747. const char *name = xs_dict_get(args, "client_name");
  2748. const char *ruri = xs_dict_get(args, "redirect_uris");
  2749. const char *scope = xs_dict_get(args, "scopes");
  2750. /* Ice Cubes sends these values as query parameters, so try these */
  2751. if (name == NULL && ruri == NULL && scope == NULL) {
  2752. xs_free(args);
  2753. args = xs_dup(xs_dict_get(req, "q_vars"));
  2754. name = xs_dict_get(args, "client_name");
  2755. ruri = xs_dict_get(args, "redirect_uris");
  2756. scope = xs_dict_get(args, "scopes");
  2757. }
  2758. if (xs_type(ruri) == XSTYPE_LIST)
  2759. ruri = xs_dict_get(ruri, 0);
  2760. if (name && ruri) {
  2761. xs *app = xs_dict_new();
  2762. xs *id = xs_replace_i(tid(0), ".", "");
  2763. xs *csec = random_str();
  2764. xs *vkey = xs_dup(xs_dict_get(srv_config, "vkey"));
  2765. if (vkey == NULL)
  2766. vkey = random_str();
  2767. xs *cid = NULL;
  2768. /* pick a non-existent random cid */
  2769. for (;;) {
  2770. cid = random_str();
  2771. xs *p_app = app_get(cid);
  2772. if (p_app == NULL)
  2773. break;
  2774. xs_free(cid);
  2775. }
  2776. app = xs_dict_append(app, "name", name);
  2777. app = xs_dict_append(app, "redirect_uri", ruri);
  2778. app = xs_dict_append(app, "client_id", cid);
  2779. app = xs_dict_append(app, "client_secret", csec);
  2780. app = xs_dict_append(app, "vapid_key", vkey);
  2781. app = xs_dict_append(app, "id", id);
  2782. app = xs_dict_append(app, "client_secret_expires_at", xs_stock(0));
  2783. if (xs_is_string(scope)) {
  2784. xs *l = xs_split(scope, " ");
  2785. app = xs_dict_append(app, "scopes", l);
  2786. }
  2787. *body = xs_json_dumps(app, 4);
  2788. *ctype = "application/json";
  2789. status = HTTP_STATUS_OK;
  2790. app = xs_dict_append(app, "code", "");
  2791. app = xs_dict_append(app, "user-agent", xs_dict_get(req, "user-agent"));
  2792. app = xs_dict_append(app, "remote-addr", xs_or(
  2793. xs_dict_get(req, "remote-addr"),
  2794. xs_dict_get(req, "x-forwarded-for")));
  2795. app_add(cid, app);
  2796. srv_debug(1, xs_fmt("mastoapi apps: new app %s", cid));
  2797. }
  2798. }
  2799. else
  2800. if (strcmp(cmd, "/v1/statuses") == 0) { /** **/
  2801. if (logged_in) {
  2802. /* post a new Note */
  2803. const char *content = xs_dict_get(args, "status");
  2804. const char *mid = xs_dict_get(args, "in_reply_to_id");
  2805. const char *visibility = xs_dict_get(args, "visibility");
  2806. const char *summary = xs_dict_get(args, "spoiler_text");
  2807. const char *poll_opts = xs_dict_get(args, "poll[options][]");
  2808. const char *poll_end_secs = xs_dict_get(args, "poll[expires_in]");
  2809. const char *poll_multiple = xs_dict_get(args, "poll[multiple]");
  2810. // const char *poll_hide_totals = xs_dict_get(args, "poll[hide_totals]");
  2811. const char *media_ids = xs_dict_get(args, "media_ids");
  2812. const char *language = xs_dict_get(args, "language");
  2813. if (xs_is_null(media_ids))
  2814. media_ids = xs_dict_get(args, "media_ids[]");
  2815. if (xs_is_null(media_ids))
  2816. media_ids = xs_dict_get(args, "media_ids");
  2817. if (xs_is_null(visibility))
  2818. visibility = "public";
  2819. xs *attach_list = xs_list_new();
  2820. xs *irt = NULL;
  2821. /* is it a reply? */
  2822. if (mid != NULL) {
  2823. xs *r_msg = NULL;
  2824. const char *md5 = MID_TO_MD5(mid);
  2825. if (valid_status(object_get_by_md5(md5, &r_msg)))
  2826. irt = xs_dup(xs_dict_get(r_msg, "id"));
  2827. }
  2828. /* does it have attachments (and no poll)? */
  2829. if (!xs_is_null(media_ids) && xs_is_null(poll_end_secs) && xs_is_null(poll_opts)) {
  2830. xs *mi = NULL;
  2831. if (xs_type(media_ids) == XSTYPE_LIST)
  2832. mi = xs_dup(media_ids);
  2833. else {
  2834. mi = xs_list_new();
  2835. mi = xs_list_append(mi, media_ids);
  2836. }
  2837. xs_list *p = mi;
  2838. const xs_str *v;
  2839. while (xs_list_iter(&p, &v)) {
  2840. xs *l = xs_list_new();
  2841. xs *url = xs_fmt("%s/s/%s", snac.actor, v);
  2842. xs *desc = static_get_meta(&snac, v);
  2843. l = xs_list_append(l, url);
  2844. l = xs_list_append(l, desc);
  2845. attach_list = xs_list_append(attach_list, l);
  2846. }
  2847. }
  2848. /* prepare the message */
  2849. xs *msg = NULL;
  2850. int scope = SCOPE_MENTIONED;
  2851. if (strcmp(visibility, "unlisted") == 0)
  2852. scope = SCOPE_UNLISTED;
  2853. else
  2854. if (strcmp(visibility, "public") == 0)
  2855. scope = SCOPE_PUBLIC;
  2856. else
  2857. if (strcmp(visibility, "private") == 0)
  2858. scope = SCOPE_FOLLOWERS;
  2859. /* does it have a poll? */
  2860. if (!xs_is_null(poll_opts) && !xs_is_null(poll_end_secs)) {
  2861. xs *po = NULL;
  2862. int end_secs = atoi(poll_end_secs);
  2863. int multiple = 0;
  2864. if (xs_type(poll_opts) == XSTYPE_LIST)
  2865. po = xs_dup(poll_opts);
  2866. else {
  2867. po = xs_list_new();
  2868. po = xs_list_append(po, poll_opts);
  2869. }
  2870. if (!xs_is_null(poll_multiple) && strcmp(poll_multiple, "true") == 0)
  2871. multiple = 1;
  2872. msg = msg_question(&snac, content, attach_list,
  2873. poll_opts, multiple, end_secs);
  2874. enqueue_close_question(&snac, xs_dict_get(msg, "id"), end_secs);
  2875. }
  2876. else
  2877. msg = msg_note(&snac, content, NULL, irt, attach_list, scope, language, NULL);
  2878. if (!xs_is_null(summary) && *summary) {
  2879. msg = xs_dict_set(msg, "sensitive", xs_stock(XSTYPE_TRUE));
  2880. msg = xs_dict_set(msg, "summary", summary);
  2881. }
  2882. /* scheduled? */
  2883. const char *scheduled_at = xs_dict_get(args, "scheduled_at");
  2884. if (xs_is_string(scheduled_at) && *scheduled_at) {
  2885. msg = xs_dict_set(msg, "published", scheduled_at);
  2886. schedule_add(&snac, xs_dict_get(msg, "id"), msg);
  2887. }
  2888. else {
  2889. /* store */
  2890. timeline_add(&snac, xs_dict_get(msg, "id"), msg);
  2891. /* 'Create' message */
  2892. xs *c_msg = msg_create(&snac, msg);
  2893. enqueue_message(&snac, c_msg);
  2894. timeline_touch(&snac);
  2895. }
  2896. /* convert to a mastodon status as a response code */
  2897. xs *st = mastoapi_status(&snac, msg);
  2898. *body = xs_json_dumps(st, 4);
  2899. *ctype = "application/json";
  2900. status = HTTP_STATUS_OK;
  2901. }
  2902. else
  2903. status = HTTP_STATUS_UNAUTHORIZED;
  2904. }
  2905. else
  2906. if (xs_startswith(cmd, "/v1/statuses")) { /** **/
  2907. if (logged_in) {
  2908. /* operations on a status */
  2909. xs *l = xs_split(cmd, "/");
  2910. const char *mid = xs_list_get(l, 3);
  2911. const char *op = xs_list_get(l, 4);
  2912. if (!xs_is_null(mid)) {
  2913. xs *msg = NULL;
  2914. xs *out = NULL;
  2915. /* skip the 'fake' part of the id */
  2916. mid = MID_TO_MD5(mid);
  2917. /* try timeline first, then global object store for remote posts */
  2918. int found = valid_status(timeline_get_by_md5(&snac, mid, &msg));
  2919. if (!found)
  2920. found = valid_status(object_get_by_md5(mid, &msg));
  2921. if (found) {
  2922. const char *id = xs_dict_get(msg, "id");
  2923. if (op == NULL) {
  2924. /* no operation (?) */
  2925. }
  2926. else
  2927. if (strcmp(op, "favourite") == 0) { /** **/
  2928. xs *n_msg = msg_admiration(&snac, id, "Like");
  2929. if (n_msg != NULL) {
  2930. enqueue_message(&snac, n_msg);
  2931. timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 1, msg);
  2932. out = mastoapi_status(&snac, msg);
  2933. }
  2934. }
  2935. else
  2936. if (strcmp(op, "unfavourite") == 0) { /** **/
  2937. xs *n_msg = msg_repulsion(&snac, id, "Like");
  2938. if (n_msg != NULL) {
  2939. object_user_cache_del(&snac, id, "admire");
  2940. enqueue_message(&snac, n_msg);
  2941. out = mastoapi_status(&snac, msg);
  2942. }
  2943. }
  2944. else
  2945. if (strcmp(op, "react") == 0) { /** **/
  2946. const char *eid = xs_list_get(l, 5);
  2947. xs *n_msg = msg_emoji_init(&snac, id, eid);
  2948. if (n_msg)
  2949. out = mastoapi_status(&snac, n_msg);
  2950. }
  2951. else
  2952. if (strcmp(op, "unreact") == 0) { /** **/
  2953. const char *eid = xs_list_get(l, 5);
  2954. xs *content = xs_fmt("%s", eid);
  2955. if (eid) {
  2956. xs *n_msg = msg_emoji_unreact(&snac, id, content);
  2957. if (n_msg != NULL) {
  2958. object_user_cache_del(&snac, id, "admire");
  2959. enqueue_message(&snac, n_msg);
  2960. out = mastoapi_status(&snac, msg);
  2961. }
  2962. }
  2963. }
  2964. else
  2965. if (strcmp(op, "reblog") == 0) { /** **/
  2966. xs *n_msg = msg_admiration(&snac, id, "Announce");
  2967. if (n_msg != NULL) {
  2968. enqueue_message(&snac, n_msg);
  2969. timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 0, msg);
  2970. out = mastoapi_status(&snac, msg);
  2971. }
  2972. }
  2973. else
  2974. if (strcmp(op, "unreblog") == 0) { /** **/
  2975. xs *n_msg = msg_repulsion(&snac, id, "Announce");
  2976. if (n_msg != NULL) {
  2977. enqueue_message(&snac, n_msg);
  2978. out = mastoapi_status(&snac, msg);
  2979. }
  2980. }
  2981. else
  2982. if (strcmp(op, "bookmark") == 0) { /** **/
  2983. /* bookmark this message */
  2984. if (bookmark(&snac, id) == 0)
  2985. out = mastoapi_status(&snac, msg);
  2986. else
  2987. status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
  2988. }
  2989. else
  2990. if (strcmp(op, "unbookmark") == 0) { /** **/
  2991. /* unbookmark this message */
  2992. unbookmark(&snac, id);
  2993. out = mastoapi_status(&snac, msg);
  2994. }
  2995. else
  2996. if (strcmp(op, "pin") == 0) { /** **/
  2997. /* pin this message */
  2998. if (pin(&snac, id) == 0)
  2999. out = mastoapi_status(&snac, msg);
  3000. else
  3001. status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
  3002. }
  3003. else
  3004. if (strcmp(op, "unpin") == 0) { /** **/
  3005. /* unpin this message */
  3006. unpin(&snac, id);
  3007. out = mastoapi_status(&snac, msg);
  3008. }
  3009. else
  3010. if (strcmp(op, "mute") == 0) { /** **/
  3011. /* Mastodon's mute is snac's hide */
  3012. }
  3013. else
  3014. if (strcmp(op, "unmute") == 0) { /** **/
  3015. /* Mastodon's unmute is snac's unhide */
  3016. }
  3017. }
  3018. if (out != NULL) {
  3019. *body = xs_json_dumps(out, 4);
  3020. *ctype = "application/json";
  3021. status = HTTP_STATUS_OK;
  3022. }
  3023. }
  3024. }
  3025. else
  3026. status = HTTP_STATUS_UNAUTHORIZED;
  3027. }
  3028. else
  3029. if (strcmp(cmd, "/v1/notifications/clear") == 0) { /** **/
  3030. if (logged_in) {
  3031. notify_clear(&snac);
  3032. timeline_touch(&snac);
  3033. *body = xs_dup("{}");
  3034. *ctype = "application/json";
  3035. status = HTTP_STATUS_OK;
  3036. }
  3037. else
  3038. status = HTTP_STATUS_UNAUTHORIZED;
  3039. }
  3040. else
  3041. if (strcmp(cmd, "/v1/push/subscription") == 0) { /** **/
  3042. /* I don't know what I'm doing */
  3043. if (logged_in) {
  3044. const char *v;
  3045. xs *wpush = xs_dict_new();
  3046. wpush = xs_dict_append(wpush, "id", "1");
  3047. v = xs_dict_get(args, "data");
  3048. v = xs_dict_get(v, "alerts");
  3049. wpush = xs_dict_append(wpush, "alerts", v);
  3050. v = xs_dict_get(args, "subscription");
  3051. v = xs_dict_get(v, "endpoint");
  3052. wpush = xs_dict_append(wpush, "endpoint", v);
  3053. xs *server_key = random_str();
  3054. wpush = xs_dict_append(wpush, "server_key", server_key);
  3055. *body = xs_json_dumps(wpush, 4);
  3056. *ctype = "application/json";
  3057. status = HTTP_STATUS_OK;
  3058. }
  3059. else
  3060. status = HTTP_STATUS_UNAUTHORIZED;
  3061. }
  3062. else
  3063. if (strcmp(cmd, "/v1/media") == 0 || strcmp(cmd, "/v2/media") == 0) { /** **/
  3064. if (logged_in) {
  3065. const xs_list *file = xs_dict_get(args, "file");
  3066. const char *desc = xs_dict_get(args, "description");
  3067. if (xs_is_null(desc))
  3068. desc = "";
  3069. status = HTTP_STATUS_BAD_REQUEST;
  3070. if (xs_type(file) == XSTYPE_LIST) {
  3071. const char *fn = xs_list_get(file, 0);
  3072. if (*fn != '\0') {
  3073. char *ext = strrchr(fn, '.');
  3074. char rnd[32];
  3075. xs_rnd_buf(rnd, sizeof(rnd));
  3076. xs *hash = xs_md5_hex(rnd, sizeof(rnd));
  3077. xs *id = xs_fmt("post-%s%s", hash, ext ? ext : "");
  3078. xs *url = xs_fmt("%s/s/%s", snac.actor, id);
  3079. int fo = xs_number_get(xs_list_get(file, 1));
  3080. int fs = xs_number_get(xs_list_get(file, 2));
  3081. /* store */
  3082. static_put(&snac, id, payload + fo, fs);
  3083. static_put_meta(&snac, id, desc);
  3084. /* prepare a response */
  3085. xs *rsp = xs_dict_new();
  3086. rsp = xs_dict_append(rsp, "id", id);
  3087. rsp = xs_dict_append(rsp, "type", "image");
  3088. rsp = xs_dict_append(rsp, "url", url);
  3089. rsp = xs_dict_append(rsp, "preview_url", url);
  3090. rsp = xs_dict_append(rsp, "remote_url", url);
  3091. rsp = xs_dict_append(rsp, "description", desc);
  3092. *body = xs_json_dumps(rsp, 4);
  3093. *ctype = "application/json";
  3094. status = HTTP_STATUS_OK;
  3095. }
  3096. }
  3097. }
  3098. else
  3099. status = HTTP_STATUS_UNAUTHORIZED;
  3100. }
  3101. else
  3102. if (xs_startswith(cmd, "/v1/accounts")) { /** **/
  3103. if (logged_in) {
  3104. /* account-related information */
  3105. xs *l = xs_split(cmd, "/");
  3106. const char *md5 = xs_list_get(l, 3);
  3107. const char *opt = xs_list_get(l, 4);
  3108. xs *rsp = NULL;
  3109. if (!xs_is_null(md5) && *md5) {
  3110. xs *actor_o = NULL;
  3111. if (xs_is_null(opt)) {
  3112. /* ? */
  3113. }
  3114. else
  3115. if (strcmp(opt, "follow") == 0) { /** **/
  3116. if (valid_status(object_get_by_md5(md5, &actor_o))) {
  3117. const char *actor = xs_dict_get(actor_o, "id");
  3118. xs *msg = msg_follow(&snac, actor);
  3119. if (msg != NULL) {
  3120. /* reload the actor from the message, in may be different */
  3121. actor = xs_dict_get(msg, "object");
  3122. following_add(&snac, actor, msg);
  3123. enqueue_output_by_actor(&snac, msg, actor, 0);
  3124. rsp = mastoapi_relationship(&snac, md5);
  3125. }
  3126. }
  3127. }
  3128. else
  3129. if (strcmp(opt, "unfollow") == 0) { /** **/
  3130. if (valid_status(object_get_by_md5(md5, &actor_o))) {
  3131. const char *actor = xs_dict_get(actor_o, "id");
  3132. /* get the following object */
  3133. xs *object = NULL;
  3134. if (valid_status(following_get(&snac, actor, &object))) {
  3135. xs *msg = msg_undo(&snac, xs_dict_get(object, "object"));
  3136. following_del(&snac, actor);
  3137. enqueue_output_by_actor(&snac, msg, actor, 0);
  3138. rsp = mastoapi_relationship(&snac, md5);
  3139. }
  3140. }
  3141. }
  3142. else
  3143. if (strcmp(opt, "block") == 0) { /** **/
  3144. if (valid_status(object_get_by_md5(md5, &actor_o))) {
  3145. const char *actor = xs_dict_get(actor_o, "id");
  3146. mute(&snac, actor);
  3147. rsp = mastoapi_relationship(&snac, md5);
  3148. }
  3149. }
  3150. else
  3151. if (strcmp(opt, "unblock") == 0) { /** **/
  3152. if (valid_status(object_get_by_md5(md5, &actor_o))) {
  3153. const char *actor = xs_dict_get(actor_o, "id");
  3154. unmute(&snac, actor);
  3155. rsp = mastoapi_relationship(&snac, md5);
  3156. }
  3157. }
  3158. }
  3159. if (rsp != NULL) {
  3160. *body = xs_json_dumps(rsp, 4);
  3161. *ctype = "application/json";
  3162. status = HTTP_STATUS_OK;
  3163. }
  3164. }
  3165. else
  3166. status = HTTP_STATUS_UNAUTHORIZED;
  3167. }
  3168. else
  3169. if (xs_startswith(cmd, "/v1/polls")) { /** **/
  3170. if (logged_in) {
  3171. /* operations on a status */
  3172. xs *l = xs_split(cmd, "/");
  3173. const char *mid = xs_list_get(l, 3);
  3174. const char *op = xs_list_get(l, 4);
  3175. if (!xs_is_null(mid)) {
  3176. xs *msg = NULL;
  3177. xs *out = NULL;
  3178. /* skip the 'fake' part of the id */
  3179. mid = MID_TO_MD5(mid);
  3180. /* try timeline first, then global object store for remote posts */
  3181. int found = valid_status(timeline_get_by_md5(&snac, mid, &msg));
  3182. if (!found)
  3183. found = valid_status(object_get_by_md5(mid, &msg));
  3184. if (found) {
  3185. const char *id = xs_dict_get(msg, "id");
  3186. const char *atto = get_atto(msg);
  3187. int closed = 0;
  3188. const char *f_closed = NULL;
  3189. if ((f_closed = xs_dict_get(msg, "closed")) != NULL) {
  3190. /* it has a closed date... but is it in the past? */
  3191. time_t t0 = time(NULL);
  3192. time_t t1 = xs_parse_iso_date(f_closed, 0);
  3193. if (t1 < t0)
  3194. closed = 1;
  3195. }
  3196. if (closed || was_question_voted(&snac, id))
  3197. status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
  3198. else {
  3199. const xs_list *opts = xs_dict_get(msg, "oneOf");
  3200. if (opts == NULL)
  3201. opts = xs_dict_get(msg, "anyOf");
  3202. if (op == NULL) {
  3203. }
  3204. else {
  3205. if (strcmp(op, "votes") == 0) {
  3206. const xs_list *choices = xs_dict_get(args, "choices[]");
  3207. if (xs_is_null(choices))
  3208. choices = xs_dict_get(args, "choices");
  3209. if (xs_type(choices) == XSTYPE_LIST) {
  3210. const xs_str *v;
  3211. int c = 0;
  3212. while (xs_list_next(choices, &v, &c)) {
  3213. int io = xs_number_get_l(v);
  3214. const xs_dict *o = xs_list_get(opts, io);
  3215. if (o) {
  3216. const char *name = xs_dict_get(o, "name");
  3217. xs *msg = msg_note(&snac, "", atto, (char *)id, NULL, 1, NULL, NULL);
  3218. msg = xs_dict_append(msg, "name", name);
  3219. xs *c_msg = msg_create(&snac, msg);
  3220. enqueue_message(&snac, c_msg);
  3221. timeline_add(&snac, xs_dict_get(msg, "id"), msg);
  3222. }
  3223. }
  3224. out = mastoapi_poll(&snac, msg);
  3225. }
  3226. }
  3227. }
  3228. }
  3229. }
  3230. if (out != NULL) {
  3231. *body = xs_json_dumps(out, 4);
  3232. *ctype = "application/json";
  3233. status = HTTP_STATUS_OK;
  3234. }
  3235. }
  3236. }
  3237. else
  3238. status = HTTP_STATUS_UNAUTHORIZED;
  3239. }
  3240. else
  3241. if (strcmp(cmd, "/v1/lists") == 0) {
  3242. if (logged_in) {
  3243. const char *title = xs_dict_get(args, "title");
  3244. if (xs_type(title) == XSTYPE_STRING) {
  3245. /* add the list */
  3246. xs *out = xs_dict_new();
  3247. xs *lid = list_maint(&snac, title, OP_ADD);
  3248. if (!xs_is_null(lid)) {
  3249. out = xs_dict_append(out, "id", lid);
  3250. out = xs_dict_append(out, "title", title);
  3251. out = xs_dict_append(out, "replies_policy", xs_dict_get_def(args, "replies_policy", "list"));
  3252. out = xs_dict_append(out, "exclusive", xs_stock(XSTYPE_FALSE));
  3253. status = HTTP_STATUS_OK;
  3254. }
  3255. else {
  3256. out = xs_dict_append(out, "error", "cannot create list");
  3257. status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
  3258. }
  3259. *body = xs_json_dumps(out, 4);
  3260. *ctype = "application/json";
  3261. }
  3262. else
  3263. status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
  3264. }
  3265. }
  3266. else
  3267. if (xs_startswith(cmd, "/v1/lists/")) { /** list maintenance **/
  3268. if (logged_in) {
  3269. xs *l = xs_split(cmd, "/");
  3270. const char *op = xs_list_get(l, -1);
  3271. const char *id = xs_list_get(l, -2);
  3272. if (op && id && xs_is_hex(id)) {
  3273. if (strcmp(op, "accounts") == 0) {
  3274. const xs_list *accts = xs_dict_get(args, "account_ids[]");
  3275. if (xs_is_null(accts))
  3276. accts = xs_dict_get(args, "account_ids");
  3277. int c = 0;
  3278. const char *v;
  3279. while (xs_list_next(accts, &v, &c)) {
  3280. list_members(&snac, id, v, OP_ADD);
  3281. }
  3282. xs *out = xs_dict_new();
  3283. *body = xs_json_dumps(out, 4);
  3284. *ctype = "application/json";
  3285. status = HTTP_STATUS_OK;
  3286. }
  3287. }
  3288. }
  3289. }
  3290. else if (strcmp(cmd, "/v1/markers") == 0) { /** **/
  3291. xs_str *json = NULL;
  3292. if (logged_in) {
  3293. const xs_str *home_marker = xs_dict_get(args, "home[last_read_id]");
  3294. if (xs_is_null(home_marker)) {
  3295. const xs_dict *home = xs_dict_get(args, "home");
  3296. if (!xs_is_null(home))
  3297. home_marker = xs_dict_get(home, "last_read_id");
  3298. }
  3299. const xs_str *notify_marker = xs_dict_get(args, "notifications[last_read_id]");
  3300. if (xs_is_null(notify_marker)) {
  3301. const xs_dict *notify = xs_dict_get(args, "notifications");
  3302. if (!xs_is_null(notify))
  3303. notify_marker = xs_dict_get(notify, "last_read_id");
  3304. }
  3305. json = xs_json_dumps(markers_set(&snac, home_marker, notify_marker), 4);
  3306. }
  3307. if (!xs_is_null(json))
  3308. *body = json;
  3309. else
  3310. *body = xs_dup("{}");
  3311. *ctype = "application/json";
  3312. status = HTTP_STATUS_OK;
  3313. }
  3314. else
  3315. if (xs_startswith(cmd, "/v1/follow_requests")) { /** **/
  3316. if (logged_in) {
  3317. /* "authorize" or "reject" */
  3318. xs *rel = NULL;
  3319. xs *l = xs_split(cmd, "/");
  3320. const char *md5 = xs_list_get(l, -2);
  3321. const char *s_cmd = xs_list_get(l, -1);
  3322. if (xs_is_string(md5) && xs_is_string(s_cmd)) {
  3323. xs *actor = NULL;
  3324. if (valid_status(object_get_by_md5(md5, &actor))) {
  3325. const char *actor_id = xs_dict_get(actor, "id");
  3326. if (strcmp(s_cmd, "authorize") == 0) {
  3327. xs *fwreq = pending_get(&snac, actor_id);
  3328. if (fwreq != NULL) {
  3329. xs *reply = msg_accept(&snac, fwreq, actor_id);
  3330. enqueue_message(&snac, reply);
  3331. if (xs_is_null(xs_dict_get(fwreq, "published"))) {
  3332. xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
  3333. fwreq = xs_dict_set(fwreq, "published", date);
  3334. }
  3335. timeline_add(&snac, xs_dict_get(fwreq, "id"), fwreq);
  3336. follower_add(&snac, actor_id);
  3337. pending_del(&snac, actor_id);
  3338. rel = mastoapi_relationship(&snac, md5);
  3339. }
  3340. }
  3341. else
  3342. if (strcmp(s_cmd, "reject") == 0) {
  3343. pending_del(&snac, actor_id);
  3344. rel = mastoapi_relationship(&snac, md5);
  3345. }
  3346. }
  3347. }
  3348. if (rel != NULL) {
  3349. *body = xs_json_dumps(rel, 4);
  3350. *ctype = "application/json";
  3351. status = HTTP_STATUS_OK;
  3352. }
  3353. }
  3354. }
  3355. else
  3356. if (xs_startswith(cmd, "/v1/tags/")) { /** **/
  3357. if (logged_in) {
  3358. xs *l = xs_split(cmd, "/");
  3359. const char *i_tag = xs_list_get(l, 3);
  3360. const char *cmd = xs_list_get(l, 4);
  3361. status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
  3362. if (xs_is_string(i_tag) && xs_is_string(cmd)) {
  3363. int ok = 0;
  3364. xs *tag = xs_fmt("#%s", i_tag);
  3365. xs *followed_hashtags = xs_dup(xs_dict_get_def(snac.config,
  3366. "followed_hashtags", xs_stock(XSTYPE_LIST)));
  3367. if (strcmp(cmd, "follow") == 0) {
  3368. followed_hashtags = xs_list_append(followed_hashtags, tag);
  3369. ok = 1;
  3370. }
  3371. else
  3372. if (strcmp(cmd, "unfollow") == 0) {
  3373. int off = xs_list_in(followed_hashtags, tag);
  3374. if (off != -1)
  3375. followed_hashtags = xs_list_del(followed_hashtags, off);
  3376. ok = 1;
  3377. }
  3378. if (ok) {
  3379. /* update */
  3380. xs_dict_set(snac.config, "followed_hashtags", followed_hashtags);
  3381. user_persist(&snac, 0);
  3382. xs *d = xs_dict_new();
  3383. xs *s = xs_fmt("%s?t=%s", srv_baseurl, i_tag);
  3384. d = xs_dict_set(d, "name", i_tag);
  3385. d = xs_dict_set(d, "url", s);
  3386. d = xs_dict_set(d, "history", xs_stock(XSTYPE_LIST));
  3387. *body = xs_json_dumps(d, 4);
  3388. *ctype = "application/json";
  3389. status = HTTP_STATUS_OK;
  3390. }
  3391. }
  3392. }
  3393. }
  3394. else
  3395. status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
  3396. /* user cleanup */
  3397. if (logged_in)
  3398. user_free(&snac);
  3399. srv_debug(1, xs_fmt("mastoapi_post_handler %s %d", q_path, status));
  3400. return status;
  3401. }
  3402. int mastoapi_delete_handler(const xs_dict *req, const char *q_path,
  3403. const char *payload, int p_size,
  3404. char **body, int *b_size, char **ctype)
  3405. {
  3406. (void)p_size;
  3407. (void)b_size;
  3408. (void)ctype;
  3409. if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
  3410. return 0;
  3411. int status = HTTP_STATUS_NOT_FOUND;
  3412. xs *args = NULL;
  3413. const char *i_ctype = xs_dict_get(req, "content-type");
  3414. if (i_ctype && xs_startswith(i_ctype, "application/json")) {
  3415. if (!xs_is_null(payload))
  3416. args = xs_json_loads(payload);
  3417. }
  3418. else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
  3419. {
  3420. // Some apps send form data instead of json so we should cater for those
  3421. if (!xs_is_null(payload)) {
  3422. args = xs_url_vars(payload);
  3423. }
  3424. }
  3425. else
  3426. args = xs_dup(xs_dict_get(req, "p_vars"));
  3427. if (args == NULL)
  3428. return HTTP_STATUS_BAD_REQUEST;
  3429. snac snac = {0};
  3430. int logged_in = process_auth_token(&snac, req);
  3431. xs *cmd = xs_replace_n(q_path, "/api", "", 1);
  3432. if (xs_startswith(cmd, "/v1/push/subscription") || xs_startswith(cmd, "/v2/push/subscription")) { /** **/
  3433. // pretend we deleted it, since it doesn't exist anyway
  3434. status = HTTP_STATUS_OK;
  3435. }
  3436. else
  3437. if (xs_startswith(cmd, "/v1/lists/")) {
  3438. if (logged_in) {
  3439. xs *l = xs_split(cmd, "/");
  3440. const char *p = xs_list_get(l, -1);
  3441. if (p) {
  3442. if (strcmp(p, "accounts") == 0) {
  3443. /* delete account from list */
  3444. p = xs_list_get(l, -2);
  3445. const xs_list *accts = xs_dict_get(args, "account_ids[]");
  3446. if (xs_is_null(accts))
  3447. accts = xs_dict_get(args, "account_ids");
  3448. int c = 0;
  3449. const char *v;
  3450. while (xs_list_next(accts, &v, &c)) {
  3451. list_members(&snac, p, v, OP_DEL);
  3452. }
  3453. }
  3454. else {
  3455. /* delete list */
  3456. if (xs_is_hex(p)) {
  3457. list_maint(&snac, p, OP_DEL);
  3458. }
  3459. }
  3460. }
  3461. *ctype = "application/json";
  3462. status = HTTP_STATUS_OK;
  3463. }
  3464. else
  3465. status = HTTP_STATUS_UNAUTHORIZED;
  3466. }
  3467. else
  3468. if (xs_startswith(cmd, "/v1/statuses/")) {
  3469. if (logged_in) {
  3470. xs *l = xs_split(cmd, "/");
  3471. const char *p = xs_list_get(l, -1);
  3472. p = MID_TO_MD5(p);
  3473. xs *obj = NULL;
  3474. if (valid_status(object_get_by_md5(p, &obj))) {
  3475. const char *id = xs_dict_get(obj, "id");
  3476. if (xs_is_string(id) && is_msg_mine(&snac, id)) {
  3477. xs *out = mastoapi_status(&snac, obj);
  3478. xs *msg = msg_delete(&snac, id);
  3479. enqueue_message(&snac, msg);
  3480. timeline_del(&snac, id);
  3481. draft_del(&snac, id);
  3482. schedule_del(&snac, id);
  3483. snac_log(&snac, xs_fmt("deleted entry %s", id));
  3484. *body = xs_json_dumps(out, 4);
  3485. *ctype = "application/json";
  3486. status = HTTP_STATUS_OK;
  3487. }
  3488. }
  3489. }
  3490. else
  3491. status = HTTP_STATUS_UNAUTHORIZED;
  3492. }
  3493. else
  3494. if (xs_startswith(cmd, "/v1/profile/")) {
  3495. if (logged_in) {
  3496. xs *l = xs_split(cmd, "/");
  3497. const char *p = xs_list_get(l, -1);
  3498. if (strcmp(p, "avatar") == 0 || strcmp(p, "header") == 0) {
  3499. snac.config = xs_dict_set(snac.config, p, "");
  3500. if (user_persist(&snac, 1) == 0)
  3501. credentials_get(body, ctype, &status, snac);
  3502. else
  3503. status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
  3504. }
  3505. }
  3506. else
  3507. status = HTTP_STATUS_UNAUTHORIZED;
  3508. }
  3509. /* user cleanup */
  3510. if (logged_in)
  3511. user_free(&snac);
  3512. srv_debug(1, xs_fmt("mastoapi_delete_handler %s %d", q_path, status));
  3513. return status;
  3514. }
  3515. int mastoapi_put_handler(const xs_dict *req, const char *q_path,
  3516. const char *payload, int p_size,
  3517. char **body, int *b_size, char **ctype)
  3518. {
  3519. (void)p_size;
  3520. (void)b_size;
  3521. if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
  3522. return 0;
  3523. int status = HTTP_STATUS_NOT_FOUND;
  3524. xs *args = NULL;
  3525. const char *i_ctype = xs_dict_get(req, "content-type");
  3526. if (i_ctype && xs_startswith(i_ctype, "application/json")) {
  3527. if (!xs_is_null(payload))
  3528. args = xs_json_loads(payload);
  3529. }
  3530. else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
  3531. {
  3532. // Some apps send form data instead of json so we should cater for those
  3533. if (!xs_is_null(payload)) {
  3534. args = xs_url_vars(payload);
  3535. }
  3536. }
  3537. else if (i_ctype && xs_startswith(i_ctype, "multipart/form-data"))
  3538. {
  3539. // Handle multipart/form-data by using p_vars (already parsed by httpd)
  3540. args = xs_dup(xs_dict_get(req, "p_vars"));
  3541. }
  3542. /* if args still NULL, try falling back to p_vars or q_vars */
  3543. if (args == NULL)
  3544. args = xs_dup(xs_dict_get(req, "p_vars"));
  3545. if (args == NULL)
  3546. args = xs_dup(xs_dict_get(req, "q_vars"));
  3547. if (args == NULL) {
  3548. srv_debug(1, xs_fmt("mastoapi_put_handler: failed to parse args for %s, content-type: %s",
  3549. q_path, i_ctype ? i_ctype : "(null)"));
  3550. return HTTP_STATUS_BAD_REQUEST;
  3551. }
  3552. xs *cmd = xs_replace_n(q_path, "/api", "", 1);
  3553. snac snac = {0};
  3554. int logged_in = process_auth_token(&snac, req);
  3555. if (xs_startswith(cmd, "/v1/media") || xs_startswith(cmd, "/v2/media")) { /** **/
  3556. if (logged_in) {
  3557. xs *l = xs_split(cmd, "/");
  3558. const char *stid = xs_list_get(l, 3);
  3559. if (!xs_is_null(stid)) {
  3560. const char *desc = xs_dict_get(args, "description");
  3561. /* set the image metadata */
  3562. static_put_meta(&snac, stid, desc);
  3563. /* prepare a response */
  3564. xs *rsp = xs_dict_new();
  3565. xs *url = xs_fmt("%s/s/%s", snac.actor, stid);
  3566. rsp = xs_dict_append(rsp, "id", stid);
  3567. rsp = xs_dict_append(rsp, "type", "image");
  3568. rsp = xs_dict_append(rsp, "url", url);
  3569. rsp = xs_dict_append(rsp, "preview_url", url);
  3570. rsp = xs_dict_append(rsp, "remote_url", url);
  3571. rsp = xs_dict_append(rsp, "description", desc);
  3572. *body = xs_json_dumps(rsp, 4);
  3573. *ctype = "application/json";
  3574. status = HTTP_STATUS_OK;
  3575. }
  3576. }
  3577. else
  3578. status = HTTP_STATUS_UNAUTHORIZED;
  3579. }
  3580. else
  3581. if (xs_startswith(cmd, "/v1/statuses")) {
  3582. if (logged_in) {
  3583. xs *l = xs_split(cmd, "/");
  3584. const char *mid = xs_list_get(l, 3);
  3585. if (!xs_is_null(mid)) {
  3586. const char *md5 = MID_TO_MD5(mid);
  3587. xs *rsp = NULL;
  3588. xs *msg = NULL;
  3589. if (valid_status(timeline_get_by_md5(&snac, md5, &msg))) {
  3590. const char *content = xs_dict_get(args, "status");
  3591. xs *atls = xs_list_new();
  3592. xs *tag = xs_list_new();
  3593. xs *f_content0 = not_really_markdown(content, &atls, &tag);
  3594. xs *f_content = process_tags(&snac, f_content0, &tag);
  3595. /* replace fields with new content */
  3596. msg = xs_dict_set(msg, "sourceContent", content);
  3597. msg = xs_dict_set(msg, "content", f_content);
  3598. xs *content_map = xs_dup(xs_dict_get(msg, "contentMap"));
  3599. if (xs_is_dict(content_map)) {
  3600. /* get the first pair */
  3601. const char *k, *v;
  3602. int c = 0;
  3603. if (xs_dict_next(content_map, &k, &v, &c)) {
  3604. content_map = xs_dict_set(content_map, k, f_content);
  3605. msg = xs_dict_set(msg, "contentMap", content_map);
  3606. }
  3607. }
  3608. xs *updated = xs_str_utctime(0, ISO_DATE_SPEC);
  3609. msg = xs_dict_set(msg, "updated", updated);
  3610. msg = xs_dict_set(msg, "tag", tag);
  3611. if (xs_is_true(xs_dict_get(args, "sensitive"))) {
  3612. const char *spoiler_text = xs_dict_get(args, "spoiler_text");
  3613. msg = xs_dict_set(msg, "summary", spoiler_text);
  3614. msg = xs_dict_set(msg, "sensitive", xs_stock(XSTYPE_TRUE));
  3615. }
  3616. else {
  3617. msg = xs_dict_set(msg, "summary", "");
  3618. msg = xs_dict_set(msg, "sensitive", xs_stock(XSTYPE_FALSE));
  3619. }
  3620. const xs_list *media_attrs = xs_dict_get(args, "media_attributes");
  3621. if (xs_is_list(media_attrs)) {
  3622. /* change alt texts */
  3623. xs *n_att = xs_dup(xs_dict_get(msg, "attachment"));
  3624. if (xs_is_list(n_att)) {
  3625. const xs_dict *d;
  3626. xs_list_foreach(media_attrs, d) {
  3627. if (xs_is_dict(d)) {
  3628. const char *id = xs_dict_get(d, "id");
  3629. const char *desc = xs_dict_get(d, "description");
  3630. if (xs_is_string(id) && xs_is_string(desc)) {
  3631. /* we build these ids with post name + _N,
  3632. so split by _ and get the last item as index */
  3633. xs *l = xs_split(id, "_");
  3634. int n = atoi(xs_or(xs_list_get(l, -1), "0"));
  3635. xs *na = xs_dup(xs_list_get(n_att, n));
  3636. na = xs_dict_set(na, "name", desc);
  3637. n_att = xs_list_set(n_att, n, na);
  3638. }
  3639. }
  3640. }
  3641. msg = xs_dict_set(msg, "attachment", n_att);
  3642. }
  3643. }
  3644. /* overwrite object, not updating the indexes */
  3645. const char *id = xs_dict_get(msg, "id");
  3646. object_add_ow(id, msg);
  3647. tag_index(id, msg);
  3648. /* update message */
  3649. xs *c_msg = msg_update(&snac, msg);
  3650. enqueue_message(&snac, c_msg);
  3651. rsp = mastoapi_status(&snac, msg);
  3652. }
  3653. if (rsp != NULL) {
  3654. *body = xs_json_dumps(rsp, 4);
  3655. *ctype = "application/json";
  3656. status = HTTP_STATUS_OK;
  3657. }
  3658. }
  3659. }
  3660. else
  3661. status = HTTP_STATUS_UNAUTHORIZED;
  3662. }
  3663. /* user cleanup */
  3664. if (logged_in)
  3665. user_free(&snac);
  3666. srv_debug(1, xs_fmt("mastoapi_put_handler %s %d", q_path, status));
  3667. return status;
  3668. }
  3669. void persist_image(const char *key, const xs_val *data, const char *payload, snac *snac)
  3670. /* Store header or avatar */
  3671. {
  3672. if (data != NULL) {
  3673. if (xs_type(data) == XSTYPE_LIST) {
  3674. const char *fn = xs_list_get(data, 0);
  3675. if (fn && *fn) {
  3676. const char *ext = strrchr(fn, '.');
  3677. /* Mona iOS sends always jpg as application/octet-stream with no filename */
  3678. if (ext == NULL || strcmp(fn, key) == 0) {
  3679. ext = ".jpg";
  3680. }
  3681. /* Make sure we have a unique file name, otherwise updated images will not be
  3682. * re-loaded by clients. */
  3683. xs *rnd = random_str();
  3684. xs *hash = xs_md5_hex(rnd, strlen(rnd));
  3685. xs *id = xs_fmt("%s%s", hash, ext);
  3686. xs *url = xs_fmt("%s/s/%s", snac->actor, id);
  3687. int fo = xs_number_get(xs_list_get(data, 1));
  3688. int fs = xs_number_get(xs_list_get(data, 2));
  3689. /* store */
  3690. static_put(snac, id, payload + fo, fs);
  3691. snac->config = xs_dict_set(snac->config, key, url);
  3692. }
  3693. }
  3694. }
  3695. }
  3696. int mastoapi_patch_handler(const xs_dict *req, const char *q_path,
  3697. const char *payload, int p_size,
  3698. char **body, int *b_size, char **ctype)
  3699. /* Handle profile updates */
  3700. {
  3701. (void)p_size;
  3702. (void)b_size;
  3703. if (!xs_startswith(q_path, "/api/v1/"))
  3704. return 0;
  3705. int status = HTTP_STATUS_NOT_FOUND;
  3706. xs *args = NULL;
  3707. const char *i_ctype = xs_dict_get(req, "content-type");
  3708. if (i_ctype && xs_startswith(i_ctype, "application/json")) {
  3709. if (!xs_is_null(payload))
  3710. args = xs_json_loads(payload);
  3711. }
  3712. else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
  3713. {
  3714. // Some apps send form data instead of json so we should cater for those
  3715. if (!xs_is_null(payload)) {
  3716. args = xs_url_vars(payload);
  3717. }
  3718. }
  3719. else if (i_ctype && xs_startswith(i_ctype, "multipart/form-data"))
  3720. {
  3721. // Handle multipart/form-data by using p_vars (already parsed by httpd)
  3722. args = xs_dup(xs_dict_get(req, "p_vars"));
  3723. }
  3724. /* if args still NULL, try falling back to p_vars or q_vars */
  3725. if (args == NULL)
  3726. args = xs_dup(xs_dict_get(req, "p_vars"));
  3727. if (args == NULL)
  3728. args = xs_dup(xs_dict_get(req, "q_vars"));
  3729. if (args == NULL) {
  3730. srv_debug(1, xs_fmt("mastoapi_patch_handler: failed to parse args for %s, content-type: %s",
  3731. q_path, i_ctype ? i_ctype : "(null)"));
  3732. return HTTP_STATUS_BAD_REQUEST;
  3733. }
  3734. xs *cmd = xs_replace_n(q_path, "/api", "", 1);
  3735. snac snac = {0};
  3736. int logged_in = process_auth_token(&snac, req);
  3737. if (xs_startswith(cmd, "/v1/accounts/update_credentials")) { /** **/
  3738. /* Update user profile fields */
  3739. if (logged_in) {
  3740. int c = 0;
  3741. const xs_str *k;
  3742. const xs_val *v;
  3743. const xs_str *field_name = NULL;
  3744. xs *new_fields = xs_dict_new();
  3745. while (xs_dict_next(args, &k, &v, &c)) {
  3746. if (strcmp(k, "display_name") == 0) {
  3747. if (v != NULL)
  3748. snac.config = xs_dict_set(snac.config, "name", v);
  3749. }
  3750. else
  3751. if (strcmp(k, "note") == 0) {
  3752. if (v != NULL)
  3753. snac.config = xs_dict_set(snac.config, "bio", v);
  3754. }
  3755. else
  3756. if (strcmp(k, "bot") == 0) {
  3757. if (v != NULL)
  3758. snac.config = xs_dict_set(snac.config, "bot",
  3759. (strcmp(v, "true") == 0 ||
  3760. strcmp(v, "1") == 0) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  3761. }
  3762. else
  3763. if (strcmp(k, "source[sensitive]") == 0) {
  3764. if (v != NULL)
  3765. snac.config = xs_dict_set(snac.config, "cw",
  3766. strcmp(v, "true") == 0 ? "open" : "");
  3767. }
  3768. else
  3769. if (strcmp(k, "source[privacy]") == 0) {
  3770. if (v != NULL)
  3771. snac.config = xs_dict_set(snac.config, "private",
  3772. strcmp(v, "private") == 0 ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
  3773. }
  3774. else
  3775. if (strcmp(k, "header") == 0) {
  3776. persist_image("header", v, payload, &snac);
  3777. }
  3778. else
  3779. if (strcmp(k, "avatar") == 0) {
  3780. persist_image("avatar", v, payload, &snac);
  3781. }
  3782. else
  3783. if (xs_between("fields_attributes", k, "[name]")) {
  3784. field_name = strcmp(v, "") != 0 ? v : NULL;
  3785. }
  3786. else
  3787. if (xs_between("fields_attributes", k, "[value]")) {
  3788. if (field_name != NULL) {
  3789. new_fields = xs_dict_set(new_fields, field_name, v);
  3790. snac.config = xs_dict_set(snac.config, "metadata", new_fields);
  3791. }
  3792. }
  3793. else
  3794. if (strcmp(k, "locked") == 0) {
  3795. snac.config = xs_dict_set(snac.config, "approve_followers",
  3796. xs_stock(strcmp(v, "true") == 0 ? XSTYPE_TRUE : XSTYPE_FALSE));
  3797. }
  3798. /* we don't have support for the following options, yet
  3799. - discoverable (0/1)
  3800. */
  3801. }
  3802. /* Persist profile */
  3803. if (user_persist(&snac, 1) == 0)
  3804. credentials_get(body, ctype, &status, snac);
  3805. else
  3806. status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
  3807. }
  3808. else
  3809. status = HTTP_STATUS_UNAUTHORIZED;
  3810. }
  3811. /* user cleanup */
  3812. if (logged_in)
  3813. user_free(&snac);
  3814. srv_debug(1, xs_fmt("mastoapi_patch_handler %s %d", q_path, status));
  3815. return status;
  3816. }
  3817. void mastoapi_purge(void)
  3818. {
  3819. xs *spec = xs_fmt("%s/app/" "*.json", srv_basedir);
  3820. xs *files = xs_glob(spec, 1, 0);
  3821. xs_list *p = files;
  3822. const xs_str *v;
  3823. time_t mt = time(NULL) - 3600;
  3824. time_t yo = time(NULL) - 3600 * 24 * 365;
  3825. while (xs_list_iter(&p, &v)) {
  3826. xs *cid = xs_replace(v, ".json", "");
  3827. xs *fn = _app_fn(cid);
  3828. double d = mtime(fn);
  3829. if (d < yo) {
  3830. unlink(fn);
  3831. srv_debug(1, xs_fmt("purge stale app: %s", fn));
  3832. }
  3833. else
  3834. if (d < mt) {
  3835. /* get the app */
  3836. xs *app = app_get(cid);
  3837. if (app) {
  3838. /* old apps with no uid are incomplete cruft */
  3839. const char *uid = xs_dict_get(app, "uid");
  3840. if (xs_is_null(uid) || *uid == '\0') {
  3841. unlink(fn);
  3842. srv_debug(1, xs_fmt("purge incomplete app: %s", fn));
  3843. }
  3844. }
  3845. }
  3846. }
  3847. /* tokens */
  3848. {
  3849. xs *spec = xs_fmt("%s/token/" "*.json", srv_basedir);
  3850. xs *files = xs_glob(spec, 1, 0);
  3851. const char *v;
  3852. xs_list_foreach(files, v) {
  3853. FILE *f;
  3854. xs *fn = xs_fmt("%s/token/%s", srv_basedir, v);
  3855. double d = mtime(fn);
  3856. if (d < yo) {
  3857. unlink(fn);
  3858. srv_debug(1, xs_fmt("purge stale token: %s", fn));
  3859. }
  3860. else
  3861. if (d < mt) {
  3862. if ((f = fopen(fn, "r")) != NULL) {
  3863. xs *token = xs_json_load(f);
  3864. fclose(f);
  3865. const char *uid = xs_dict_get(token, "uid");
  3866. if (xs_is_null(uid) || *uid == '\0') {
  3867. unlink(fn);
  3868. srv_debug(1, xs_fmt("purge incomplete token: %s", v));
  3869. }
  3870. }
  3871. }
  3872. }
  3873. }
  3874. }
  3875. #endif /* #ifndef NO_MASTODON_API */