mastoapi.c 165 KB

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