activitypub.c 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 - 2026 grunfink et al. / MIT license */
  3. #include "xs.h"
  4. #include "xs_json.h"
  5. #include "xs_curl.h"
  6. #include "xs_url.h"
  7. #include "xs_mime.h"
  8. #include "xs_openssl.h"
  9. #include "xs_regex.h"
  10. #include "xs_time.h"
  11. #include "xs_set.h"
  12. #include "xs_match.h"
  13. #include "xs_unicode.h"
  14. #include "xs_webmention.h"
  15. #include "xs_http.h"
  16. #include "snac.h"
  17. #include <stddef.h>
  18. #include <sys/wait.h>
  19. const char * const public_address = "https:/" "/www.w3.org/ns/activitystreams#Public";
  20. /* susie.png */
  21. const char * const susie =
  22. "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  23. "CEkxzAAAAUUlEQVQoz43R0QkAMQwCUDdw/y3dwE"
  24. "vsvzlL4X1IoQkAisKmwfAFT3RgJHbQezpSRoXEq"
  25. "eqCL9BJBf7h3QbOCCxV5EVWMEMwG7K1/WODtlvx"
  26. "AYTtEsDU9F34AAAAAElFTkSuQmCC";
  27. const char * const susie_cool =
  28. "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  29. "CEkxzAAAAV0lEQVQoz43RwQ3AMAwCQDZg/y3ZgN"
  30. "qo3+JaedwDOUQBQFHYaTB8wTM6sGl2cMPu+DFzn"
  31. "+ZcgN7wF7ZVihXkfSlWIVzIA6dbQzaygllpNuTX"
  32. "ZmmFNlvxADX1+o0cUPMbAAAAAElFTkSuQmCC";
  33. const char * const susie_muertos =
  34. "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  35. "CEkxzAAAAV0lEQVQoz4XQsQ0AMQxCUW/A/lv+DT"
  36. "ic6zGRolekIMyMELNp8PiCEw6Q4w4NoAt53IH5m"
  37. "xXksrZYgZwJrIox+Z8vJAfe2lCxG6AK7eKkWcEb"
  38. "QHbF617xAQatAAD7jJHUAAAAAElFTkSuQmCC";
  39. const char *default_avatar_base64(void)
  40. /* returns the default avatar in base64 */
  41. {
  42. time_t t = time(NULL);
  43. struct tm tm;
  44. const char *p = susie;
  45. gmtime_r(&t, &tm);
  46. if (tm.tm_mon == 10 && tm.tm_mday == 2)
  47. p = susie_muertos;
  48. else
  49. if (tm.tm_wday == 0 || tm.tm_wday == 6)
  50. p = susie_cool;
  51. return p;
  52. }
  53. int activitypub_request(snac *user, const char *url, xs_dict **data)
  54. /* request an object */
  55. {
  56. int status = 0;
  57. xs *response = NULL;
  58. xs *payload = NULL;
  59. int p_size;
  60. const char *ctype;
  61. *data = NULL;
  62. if (user != NULL) {
  63. /* get from the net */
  64. response = http_signed_request(user, "GET", url,
  65. NULL, NULL, 0, &status, &payload, &p_size, 0);
  66. }
  67. if (status == 0 || (status >= 500 && status <= 599)) {
  68. /* I found an instance running Misskey that returned
  69. 500 on signed messages but returned the object
  70. perfectly without signing (?), so why not try */
  71. xs_free(response);
  72. xs *hdrs = xs_dict_new();
  73. hdrs = xs_dict_append(hdrs, "accept", "application/activity+json");
  74. hdrs = xs_dict_append(hdrs, "user-agent", USER_AGENT);
  75. response = xs_http_request("GET", url, hdrs,
  76. NULL, 0, &status, &payload, &p_size, 0);
  77. }
  78. if (p_size >= 100000)
  79. return HTTP_STATUS_BAD_REQUEST;
  80. if (valid_status(status)) {
  81. /* ensure it's ActivityPub data */
  82. ctype = xs_dict_get(response, "content-type");
  83. if (xs_is_null(ctype))
  84. status = HTTP_STATUS_BAD_REQUEST;
  85. else
  86. if (xs_str_in(ctype, "application/activity+json") != -1 ||
  87. xs_str_in(ctype, "application/ld+json") != -1) {
  88. /* if there is no payload, fail */
  89. if (xs_is_null(payload))
  90. status = HTTP_STATUS_BAD_REQUEST;
  91. else
  92. *data = xs_json_loads(payload);
  93. }
  94. else
  95. status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
  96. }
  97. return status;
  98. }
  99. static xs_dict *actor_get_collections(snac *user, xs_dict *actor, int throttle)
  100. /* fetches follower/following/statuses counts from an actor's collections and adds them to the actor object */
  101. {
  102. /* only fetch if counts are not already present in the actor object */
  103. const xs_number *existing_followers = xs_dict_get(actor, "followers_count");
  104. const xs_number *existing_following = xs_dict_get(actor, "following_count");
  105. const xs_number *existing_statuses = xs_dict_get(actor, "statuses_count");
  106. /* skip if we already have all counts */
  107. if (xs_type(existing_followers) == XSTYPE_NUMBER &&
  108. xs_type(existing_following) == XSTYPE_NUMBER &&
  109. xs_type(existing_statuses) == XSTYPE_NUMBER) {
  110. return actor;
  111. }
  112. /* CRITICAL: duplicate URLs BEFORE any xs_dict_set calls, as xs_dict_set can reallocate the dict */
  113. xs *followers_url = xs_dup(xs_dict_get(actor, "followers"));
  114. xs *following_url = xs_dup(xs_dict_get(actor, "following"));
  115. xs *outbox_url = xs_dup(xs_dict_get(actor, "outbox"));
  116. /* only fetch followers count if not already present */
  117. if (xs_type(existing_followers) != XSTYPE_NUMBER && !xs_is_null(followers_url)) {
  118. xs *followers_coll = NULL;
  119. if (valid_status(activitypub_request(user, followers_url, &followers_coll))) {
  120. const xs_number *total = xs_dict_get(followers_coll, "totalItems");
  121. if (xs_type(total) == XSTYPE_NUMBER) {
  122. xs *total_copy = xs_dup(total);
  123. actor = xs_dict_set(actor, "followers_count", total_copy);
  124. }
  125. }
  126. /* throttle to prevent resource exhaustion on low-power devices */
  127. if (throttle)
  128. usleep(100000); /* 100ms delay between requests */
  129. }
  130. /* only fetch following count if not already present */
  131. if (xs_type(existing_following) != XSTYPE_NUMBER && !xs_is_null(following_url)) {
  132. xs *following_coll = NULL;
  133. if (valid_status(activitypub_request(user, following_url, &following_coll))) {
  134. const xs_number *total = xs_dict_get(following_coll, "totalItems");
  135. if (xs_type(total) == XSTYPE_NUMBER) {
  136. xs *total_copy = xs_dup(total);
  137. actor = xs_dict_set(actor, "following_count", total_copy);
  138. }
  139. }
  140. /* throttle to prevent resource exhaustion on low-power devices */
  141. if (throttle)
  142. usleep(100000); /* 100ms delay between requests */
  143. }
  144. /* only fetch statuses count if not already present */
  145. if (xs_type(existing_statuses) != XSTYPE_NUMBER && !xs_is_null(outbox_url)) {
  146. xs *outbox_coll = NULL;
  147. if (valid_status(activitypub_request(user, outbox_url, &outbox_coll))) {
  148. const xs_number *total = xs_dict_get(outbox_coll, "totalItems");
  149. if (xs_type(total) == XSTYPE_NUMBER) {
  150. xs *total_copy = xs_dup(total);
  151. actor = xs_dict_set(actor, "statuses_count", total_copy);
  152. }
  153. }
  154. /* throttle to prevent resource exhaustion on low-power devices */
  155. if (throttle)
  156. usleep(100000); /* 100ms delay between requests */
  157. }
  158. return actor;
  159. }
  160. int actor_request(snac *user, const char *actor, xs_dict **data)
  161. /* request an actor */
  162. {
  163. int status;
  164. xs *payload = NULL;
  165. if (data)
  166. *data = NULL;
  167. /* get from disk first */
  168. status = actor_get_refresh(user, actor, data);
  169. if (!valid_status(status)) {
  170. /* actor data non-existent: get from the net */
  171. status = activitypub_request(user, actor, &payload);
  172. if (valid_status(status)) {
  173. /* fetch collection counts when initially fetching an actor (no throttle) */
  174. payload = actor_get_collections(user, payload, 0);
  175. /* renew data */
  176. status = actor_add(actor, payload);
  177. if (data != NULL) {
  178. *data = payload;
  179. payload = NULL;
  180. }
  181. }
  182. else
  183. srv_debug(1, xs_fmt("actor_request error %s %d", actor, status));
  184. }
  185. /* collect the (presumed) shared inbox in this actor */
  186. if (xs_type(xs_dict_get(srv_config, "disable_inbox_collection")) != XSTYPE_TRUE) {
  187. if (valid_status(status) && data && *data)
  188. inbox_add_by_actor(*data);
  189. }
  190. return status;
  191. }
  192. const char *get_atto(const xs_dict *msg)
  193. /* gets the attributedTo field (an actor) */
  194. {
  195. const xs_val *actor = xs_dict_get(msg, "attributedTo");
  196. /* if the actor is a list of objects (like on Peertube videos), pick the Person */
  197. if (xs_type(actor) == XSTYPE_LIST) {
  198. const xs_list *p = actor;
  199. int c = 0;
  200. const xs_dict *v;
  201. actor = NULL;
  202. while (actor == NULL && xs_list_next(p, &v, &c)) {
  203. if (xs_type(v) == XSTYPE_DICT) {
  204. const char *type = xs_dict_get(v, "type");
  205. if (xs_type(type) == XSTYPE_STRING && strcmp(type, "Person") == 0) {
  206. actor = xs_dict_get(v, "id");
  207. if (xs_type(actor) != XSTYPE_STRING)
  208. actor = NULL;
  209. }
  210. }
  211. }
  212. }
  213. else
  214. if (xs_type(actor) == XSTYPE_DICT) {
  215. /* bandwagon.fm returns this */
  216. actor = xs_dict_get(actor, "id");
  217. }
  218. return actor;
  219. }
  220. const char *get_in_reply_to(const xs_dict *msg)
  221. /* gets the inReplyTo id */
  222. {
  223. const xs_val *in_reply_to = xs_dict_get(msg, "inReplyTo");
  224. if (xs_type(in_reply_to) == XSTYPE_DICT)
  225. in_reply_to = xs_dict_get(in_reply_to, "id");
  226. return in_reply_to;
  227. }
  228. xs_list *get_attachments(const xs_dict *msg)
  229. /* unify the garbage fire that are the attachments */
  230. {
  231. xs_list *l = xs_list_new();
  232. const xs_list *p;
  233. /* try first the attachments list */
  234. if (!xs_is_null(p = xs_dict_get(msg, "attachment"))) {
  235. xs *attach = NULL;
  236. const xs_val *v;
  237. /* ensure it's a list */
  238. if (xs_type(p) == XSTYPE_DICT) {
  239. attach = xs_list_new();
  240. attach = xs_list_append(attach, p);
  241. }
  242. else
  243. attach = xs_dup(p);
  244. if (xs_type(attach) == XSTYPE_LIST && xs_list_len(attach) == 0) {
  245. /* does the message have an image? */
  246. const xs_dict *d = xs_dict_get(msg, "image");
  247. if (xs_type(d) == XSTYPE_DICT) {
  248. /* add it to the attachment list */
  249. attach = xs_list_append(attach, d);
  250. }
  251. }
  252. /* now iterate the list */
  253. int c = 0;
  254. while (xs_list_next(attach, &v, &c)) {
  255. const char *type = xs_dict_get(v, "mediaType");
  256. if (xs_is_null(type))
  257. type = xs_dict_get(v, "type");
  258. if (xs_is_null(type))
  259. continue;
  260. const char *href = xs_dict_get(v, "url");
  261. if (xs_is_null(href))
  262. href = xs_dict_get(v, "href");
  263. if (xs_is_null(href))
  264. continue;
  265. /* infer MIME type from non-specific attachments */
  266. if (xs_list_len(attach) < 2 && xs_match(type, "Link|Document")) {
  267. char *mt = (char *)xs_mime_by_ext(href);
  268. if (xs_match(mt, "image/*|audio/*|video/*")) /* */
  269. type = mt;
  270. }
  271. const char *name = xs_dict_get(v, "name");
  272. if (xs_is_null(name))
  273. name = xs_dict_get(msg, "name");
  274. if (xs_is_null(name))
  275. name = "";
  276. xs *d = xs_dict_new();
  277. d = xs_dict_append(d, "type", type);
  278. d = xs_dict_append(d, "href", href);
  279. d = xs_dict_append(d, "name", name);
  280. const xs_dict *icon = xs_dict_get(v, "icon");
  281. if (xs_type(icon) == XSTYPE_DICT)
  282. d = xs_dict_append(d, "icon", icon);
  283. l = xs_list_append(l, d);
  284. }
  285. }
  286. /** urls (attachments from Peertube) **/
  287. p = xs_dict_get(msg, "url");
  288. if (xs_type(p) == XSTYPE_LIST) {
  289. const char *href = NULL;
  290. const char *type = NULL;
  291. int c = 0;
  292. const xs_val *v;
  293. while (href == NULL && xs_list_next(p, &v, &c)) {
  294. if (xs_type(v) == XSTYPE_DICT) {
  295. const char *mtype = xs_dict_get(v, "type");
  296. if (xs_type(mtype) == XSTYPE_STRING && strcmp(mtype, "Link") == 0) {
  297. mtype = xs_dict_get(v, "mediaType");
  298. const xs_list *tag = xs_dict_get(v, "tag");
  299. if (xs_type(mtype) == XSTYPE_STRING &&
  300. strcmp(mtype, "application/x-mpegURL") == 0 &&
  301. xs_type(tag) == XSTYPE_LIST) {
  302. /* now iterate the tag list, looking for a video URL */
  303. const xs_dict *d;
  304. int c = 0;
  305. while (href == NULL && xs_list_next(tag, &d, &c)) {
  306. if (xs_type(d) == XSTYPE_DICT) {
  307. if (xs_type(mtype = xs_dict_get(d, "mediaType")) == XSTYPE_STRING &&
  308. xs_startswith(mtype, "video/")) {
  309. const char *h = xs_dict_get(d, "href");
  310. /* this is probably it */
  311. if (xs_type(h) == XSTYPE_STRING) {
  312. href = h;
  313. type = mtype;
  314. }
  315. }
  316. }
  317. }
  318. }
  319. }
  320. }
  321. }
  322. if (href && type) {
  323. xs *d = xs_dict_new();
  324. d = xs_dict_append(d, "href", href);
  325. d = xs_dict_append(d, "type", type);
  326. d = xs_dict_append(d, "name", "---");
  327. l = xs_list_append(l, d);
  328. }
  329. }
  330. return l;
  331. }
  332. int hashtag_in_msg(const xs_list *hashtags, const xs_dict *msg)
  333. /* returns 1 if the message contains any of the list of hashtags */
  334. {
  335. if (xs_is_list(hashtags) && xs_is_dict(msg)) {
  336. const xs_list *tags_in_msg = xs_dict_get(msg, "tag");
  337. if (xs_is_list(tags_in_msg)) {
  338. const xs_dict *te;
  339. /* iterate the tags in the message */
  340. xs_list_foreach(tags_in_msg, te) {
  341. if (xs_is_dict(te)) {
  342. const char *type = xs_dict_get(te, "type");
  343. const char *name = xs_dict_get(te, "name");
  344. if (xs_is_string(type) && xs_is_string(name)) {
  345. if (strcmp(type, "Hashtag") == 0) {
  346. xs *lc_name = xs_utf8_tolower(name);
  347. if (xs_list_in(hashtags, lc_name) != -1)
  348. return 1;
  349. }
  350. }
  351. }
  352. }
  353. }
  354. }
  355. return 0;
  356. }
  357. int followed_hashtag_check(snac *user, const xs_dict *msg)
  358. /* returns 1 if this message contains a hashtag followed by me */
  359. {
  360. return hashtag_in_msg(xs_dict_get(user->config, "followed_hashtags"), msg);
  361. }
  362. int blocked_hashtag_check(snac *user, const xs_dict *msg)
  363. /* returns 1 if this message contains a hashtag blocked by me */
  364. {
  365. return hashtag_in_msg(xs_dict_get(user->config, "blocked_hashtags"), msg);
  366. }
  367. int timeline_request(snac *snac, const char **id, xs_str **wrk, int level)
  368. /* ensures that an entry and its ancestors are in the timeline */
  369. {
  370. int status = 0;
  371. if (level < MAX_CONVERSATION_LEVELS && !xs_is_null(*id)) {
  372. xs *msg = NULL;
  373. /* from a blocked instance? discard and break */
  374. if (is_instance_blocked(*id)) {
  375. snac_debug(snac, 1, xs_fmt("timeline_request blocked instance %s", *id));
  376. return status;
  377. }
  378. /* is the object already there? */
  379. if (!valid_status((status = object_get(*id, &msg)))) {
  380. /* no; download it */
  381. status = activitypub_request(snac, *id, &msg);
  382. }
  383. if (valid_status(status)) {
  384. const xs_dict *object = msg;
  385. const char *type = xs_dict_get(object, "type");
  386. /* get the id again from the object, as it may be different */
  387. const char *nid = xs_dict_get(object, "id");
  388. if (xs_type(nid) != XSTYPE_STRING)
  389. return 0;
  390. if (wrk && strcmp(nid, *id) != 0) {
  391. snac_debug(snac, 1,
  392. xs_fmt("timeline_request canonical id for %s is %s", *id, nid));
  393. *wrk = xs_dup(nid);
  394. *id = *wrk;
  395. }
  396. if (xs_is_null(type))
  397. type = "(null)";
  398. srv_debug(2, xs_fmt("timeline_request type %s '%s'", nid, type));
  399. if (strcmp(type, "Create") == 0) {
  400. /* some software like lemmy nest Announce + Create + Note */
  401. if (!xs_is_null(object = xs_dict_get(object, "object"))) {
  402. type = xs_dict_get(object, "type");
  403. nid = xs_dict_get(object, "id");
  404. }
  405. else
  406. type = "(null)";
  407. }
  408. if (xs_match(type, POSTLIKE_OBJECT_TYPE)) {
  409. if (content_match("filter_reject.txt", object))
  410. snac_log(snac, xs_fmt("timeline_request rejected by content %s", nid));
  411. else
  412. if (blocked_hashtag_check(snac, object))
  413. snac_log(snac, xs_fmt("timeline_request rejected by hashtag %s", nid));
  414. else {
  415. const char *actor = get_atto(object);
  416. if (!xs_is_null(actor)) {
  417. /* request (and drop) the actor for this entry */
  418. if (!valid_status(actor_request(snac, actor, NULL))) {
  419. /* failed? retry later */
  420. enqueue_actor_refresh(snac, actor, 60);
  421. }
  422. /* does it have an ancestor? */
  423. const char *in_reply_to = get_in_reply_to(object);
  424. /* store */
  425. timeline_add(snac, nid, object);
  426. /* redistribute to lists for this user */
  427. list_distribute(snac, actor, object);
  428. /* recurse! */
  429. timeline_request(snac, &in_reply_to, NULL, level + 1);
  430. }
  431. }
  432. }
  433. }
  434. }
  435. return status;
  436. }
  437. int send_to_inbox_raw(const char *keyid, const char *seckey,
  438. const xs_str *inbox, const xs_dict *msg,
  439. xs_val **payload, int *p_size, int timeout)
  440. /* sends a message to an Inbox */
  441. {
  442. int status;
  443. xs_dict *response;
  444. xs *j_msg = xs_json_dumps((xs_dict *)msg, 4);
  445. response = http_signed_request_raw(keyid, seckey, "POST", inbox,
  446. NULL, j_msg, strlen(j_msg), &status, payload, p_size, timeout);
  447. xs_free(response);
  448. return status;
  449. }
  450. int send_to_inbox(snac *snac, const xs_str *inbox, const xs_dict *msg,
  451. xs_val **payload, int *p_size, int timeout)
  452. /* sends a message to an Inbox */
  453. {
  454. const char *seckey = xs_dict_get(snac->key, "secret");
  455. return send_to_inbox_raw(snac->actor, seckey, inbox, msg, payload, p_size, timeout);
  456. }
  457. xs_str *get_actor_inbox(const char *actor, int shared)
  458. /* gets an actor's inbox */
  459. {
  460. xs *data = NULL;
  461. const char *v = NULL;
  462. if (valid_status(actor_request(NULL, actor, &data))) {
  463. /* try first endpoints/sharedInbox */
  464. if (shared && (v = xs_dict_get(data, "endpoints")))
  465. v = xs_dict_get(v, "sharedInbox");
  466. /* try then the regular inbox */
  467. if (xs_is_null(v))
  468. v = xs_dict_get(data, "inbox");
  469. }
  470. return xs_is_null(v) ? NULL : xs_dup(v);
  471. }
  472. int send_to_actor(snac *snac, const char *actor, const xs_dict *msg,
  473. xs_val **payload, int *p_size, int timeout)
  474. /* sends a message to an actor */
  475. {
  476. int status = HTTP_STATUS_BAD_REQUEST;
  477. xs *inbox = get_actor_inbox(actor, 1);
  478. if (!xs_is_null(inbox))
  479. status = send_to_inbox(snac, inbox, msg, payload, p_size, timeout);
  480. return status;
  481. }
  482. void post_message(snac *snac, const char *actor, const xs_dict *msg)
  483. /* posts a message immediately (bypassing the output queues) */
  484. {
  485. xs *payload = NULL;
  486. int p_size;
  487. int status = send_to_actor(snac, actor, msg, &payload, &p_size, 3);
  488. srv_log(xs_fmt("post_message to actor %s %d", actor, status));
  489. if (!valid_status(status))
  490. /* cannot send right now, enqueue */
  491. enqueue_message(snac, msg);
  492. }
  493. xs_list *recipient_list(snac *snac, const xs_dict *msg, int expand_public)
  494. /* returns the list of recipients for a message */
  495. {
  496. const xs_val *to = xs_dict_get(msg, "to");
  497. const xs_val *cc = xs_dict_get(msg, "cc");
  498. xs_set rcpts;
  499. int n;
  500. xs_set_init(&rcpts);
  501. const xs_list *lists[] = { to, cc, NULL };
  502. for (n = 0; lists[n]; n++) {
  503. xs_list *l = (xs_list *)lists[n];
  504. const char *v;
  505. xs *tl = NULL;
  506. /* if it's a string, create a list with only one element */
  507. if (xs_type(l) == XSTYPE_STRING) {
  508. tl = xs_list_new();
  509. tl = xs_list_append(tl, l);
  510. l = tl;
  511. }
  512. while (xs_list_iter(&l, &v)) {
  513. if (expand_public) {
  514. xs *followers_url = xs_fmt("%s/followers", snac->actor);
  515. if (strcmp(v, public_address) == 0 ||
  516. /* check if it's a followers collection URL */
  517. (xs_type(v) == XSTYPE_STRING &&
  518. strcmp(v, followers_url) == 0) ||
  519. (xs_type(v) == XSTYPE_LIST &&
  520. xs_list_in(v, followers_url) != -1)) {
  521. /* iterate the followers and add them */
  522. xs *fwers = follower_list(snac);
  523. const char *actor;
  524. char *p = fwers;
  525. while (xs_list_iter(&p, &actor))
  526. xs_set_add(&rcpts, actor);
  527. }
  528. else
  529. xs_set_add(&rcpts, v);
  530. }
  531. else
  532. xs_set_add(&rcpts, v);
  533. }
  534. }
  535. return xs_set_result(&rcpts);
  536. }
  537. int is_msg_public(const xs_dict *msg)
  538. /* checks if a message is public */
  539. {
  540. const char *to = xs_dict_get(msg, "to");
  541. const char *cc = xs_dict_get(msg, "cc");
  542. int n;
  543. const char *lists[] = { to, cc, NULL };
  544. for (n = 0; lists[n]; n++) {
  545. const xs_val *l = lists[n];
  546. if (xs_type(l) == XSTYPE_STRING) {
  547. if (strcmp(l, public_address) == 0)
  548. return 1;
  549. }
  550. else
  551. if (xs_type(l) == XSTYPE_LIST) {
  552. if (xs_list_in(l, public_address) != -1)
  553. return 1;
  554. }
  555. }
  556. return 0;
  557. }
  558. int is_msg_from_private_user(const xs_dict *msg)
  559. /* checks if a message is from a local, private user */
  560. {
  561. int ret = 0;
  562. /* is this message from a local user? */
  563. if (xs_startswith(xs_dict_get(msg, "id"), srv_baseurl)) {
  564. const char *atto = get_atto(msg);
  565. xs *l = xs_split(atto, "/");
  566. const char *uid = xs_list_get(l, -1);
  567. snac user;
  568. if (uid && user_open(&user, uid)) {
  569. if (xs_type(xs_dict_get(user.config, "private")) == XSTYPE_TRUE)
  570. ret = 1;
  571. user_free(&user);
  572. }
  573. }
  574. return ret;
  575. }
  576. void followed_hashtag_distribute(const xs_dict *msg)
  577. /* distribute this post to all users following the included hashtags */
  578. {
  579. const char *id = xs_dict_get(msg, "id");
  580. const xs_list *tags_in_msg = xs_dict_get(msg, "tag");
  581. if (!xs_is_string(id) || !xs_is_list(tags_in_msg) || xs_list_len(tags_in_msg) == 0)
  582. return;
  583. srv_debug(1, xs_fmt("followed_hashtag_distribute check for %s", id));
  584. xs *users = user_list();
  585. const char *uid;
  586. xs_list_foreach(users, uid) {
  587. snac user;
  588. if (user_open(&user, uid)) {
  589. if (followed_hashtag_check(&user, msg)) {
  590. timeline_add(&user, id, msg);
  591. snac_log(&user, xs_fmt("followed hashtag in %s", id));
  592. }
  593. user_free(&user);
  594. }
  595. }
  596. }
  597. int was_mentioned(snac *user, const xs_dict *msg)
  598. /* checks if user was mentioned here */
  599. {
  600. const xs_list *l = xs_dict_get_def(msg, "tag", xs_stock(XSTYPE_LIST));
  601. const xs_dict *d;
  602. xs_list_foreach(l, d) {
  603. const char *type = xs_dict_get_def(d, "type", "");
  604. const char *href = xs_dict_get_def(d, "href", "");
  605. if (strcmp(type, "Mention") == 0 && strcmp(href, user->actor) == 0)
  606. return 1;
  607. }
  608. return 0;
  609. }
  610. int is_msg_for_me(snac *snac, const xs_dict *c_msg)
  611. /* checks if this message is for me */
  612. {
  613. const char *type = xs_dict_get(c_msg, "type");
  614. const char *actor = xs_dict_get(c_msg, "actor");
  615. if (strcmp(actor, snac->actor) == 0) {
  616. /* message by myself? (most probably via the shared-inbox) reject */
  617. snac_debug(snac, 1, xs_fmt("ignoring message by myself"));
  618. return 0;
  619. }
  620. if (xs_match(type, "Like|Announce|EmojiReact")) {
  621. const char *object = xs_dict_get(c_msg, "object");
  622. xs *obj = NULL;
  623. if (xs_is_dict(object)) {
  624. obj = xs_dup(object);
  625. object = xs_dict_get(object, "id");
  626. }
  627. /* bad object id? reject */
  628. if (!xs_is_string(object))
  629. return 0;
  630. /* try to get the object */
  631. if (!xs_is_dict(obj))
  632. object_get(object, &obj);
  633. /* if it's about one of our posts, accept it */
  634. if (is_msg_mine(snac, object))
  635. return 2;
  636. /* blocked by hashtag? */
  637. if (blocked_hashtag_check(snac, obj))
  638. return 0;
  639. /* if it's by someone we follow, accept it */
  640. if (following_check(snac, actor))
  641. return 1;
  642. /* do we follow any hashtag? */
  643. if (followed_hashtag_check(snac, obj))
  644. return 7;
  645. return 0;
  646. }
  647. /* if it's an Undo, it must be from someone related to us */
  648. if (xs_match(type, "Undo")) {
  649. return follower_check(snac, actor) || following_check(snac, actor);
  650. }
  651. /* if it's an Accept + Follow, it must be for a Follow we created */
  652. if (xs_match(type, "Accept")) {
  653. return following_check(snac, actor);
  654. }
  655. /* if it's a Follow, it must be explicitly for us */
  656. if (xs_match(type, "Follow")) {
  657. const char *object = xs_dict_get(c_msg, "object");
  658. return !xs_is_null(object) && (strcmp(snac->actor, object) == 0 || strcmp(snac->actor_alt, object) == 0);
  659. }
  660. /* only accept Ping directed to us */
  661. if (xs_match(type, "Ping")) {
  662. const char *dest = xs_dict_get(c_msg, "to");
  663. return !xs_is_null(dest) && (strcmp(snac->actor, dest) == 0 || strcmp(snac->actor_alt, dest) == 0);
  664. }
  665. /* if it's not a Create or Update, allow as is */
  666. if (!xs_match(type, "Create|Update")) {
  667. return 1;
  668. }
  669. const xs_dict *msg = xs_dict_get(c_msg, "object");
  670. /* any blocked hashtag? reject */
  671. if (blocked_hashtag_check(snac, msg)) {
  672. snac_debug(snac, 1, xs_fmt("blocked by hashtag %s", xs_dict_get(msg, "id")));
  673. return 0;
  674. }
  675. int pub_msg = is_msg_public(c_msg);
  676. /* if this message is public and we follow the actor of this post, allow */
  677. if (pub_msg && following_check(snac, actor))
  678. return 1;
  679. xs *rcpts = recipient_list(snac, msg, 0);
  680. xs_list *p = rcpts;
  681. const xs_str *v;
  682. xs *actor_followers = NULL;
  683. if (!pub_msg) {
  684. /* not a public message; get the actor and its followers list */
  685. xs *actor_obj = NULL;
  686. if (valid_status(object_get(actor, &actor_obj))) {
  687. const xs_val *fw = xs_dict_get(actor_obj, "followers");
  688. if (fw)
  689. actor_followers = xs_dup(fw);
  690. }
  691. }
  692. while(xs_list_iter(&p, &v)) {
  693. /* explicitly for me? accept */
  694. if (strcmp(v, snac->actor) == 0 || strcmp(v, snac->actor_alt) == 0)
  695. return 2;
  696. if (pub_msg) {
  697. /* a public message for someone we follow? (probably cc'ed) accept */
  698. if (strcmp(v, public_address) != 0 && following_check(snac, v))
  699. return 5;
  700. }
  701. else
  702. if (actor_followers && strcmp(v, actor_followers) == 0) {
  703. /* if this message is for this actor's followers, are we one of them? */
  704. if (following_check(snac, actor))
  705. return 6;
  706. }
  707. }
  708. /* accept if it's by someone we follow */
  709. const char *atto = get_atto(msg);
  710. if (pub_msg && !xs_is_null(atto) && following_check(snac, atto))
  711. return 3;
  712. /* is this message a reply to another? */
  713. const char *irt = get_in_reply_to(msg);
  714. if (!xs_is_null(irt)) {
  715. xs *r_msg = NULL;
  716. /* try to get the replied message */
  717. if (valid_status(object_get(irt, &r_msg))) {
  718. atto = get_atto(r_msg);
  719. /* accept if the replied message is from someone we follow */
  720. if (pub_msg && !xs_is_null(atto) && following_check(snac, atto))
  721. return 4;
  722. }
  723. }
  724. /* does this message contain a tag we are following? */
  725. if (pub_msg && followed_hashtag_check(snac, msg))
  726. return 7;
  727. return 0;
  728. }
  729. xs_str *process_tags(snac *snac, const char *content, xs_list **tag)
  730. /* parses mentions and tags from content */
  731. {
  732. xs_str *nc = xs_str_new(NULL);
  733. xs_list *tl = *tag;
  734. xs *split;
  735. xs_list *p;
  736. const xs_val *v;
  737. int n = 0;
  738. /* create a default server for incomplete mentions */
  739. xs *def_srv = NULL;
  740. if (xs_list_len(tl)) {
  741. /* if there are any mentions, get the server from
  742. the first one, which is the inReplyTo author */
  743. p = tl;
  744. while (xs_list_iter(&p, &v)) {
  745. const char *type = xs_dict_get(v, "type");
  746. const char *name = xs_dict_get(v, "name");
  747. if (type && name && strcmp(type, "Mention") == 0) {
  748. xs *l = xs_split(name, "@");
  749. def_srv = xs_dup(xs_list_get(l, -1));
  750. break;
  751. }
  752. }
  753. }
  754. if (xs_is_null(def_srv))
  755. /* use this same server */
  756. def_srv = xs_dup(xs_dict_get(srv_config, "host"));
  757. split = xs_regex_split(content, "(@[A-Za-z0-9_-]+(@[A-Za-z0-9\\.-]+)?|&#[0-9]+;|#(_|[^[:punct:][:space:]])+)");
  758. p = split;
  759. while (xs_list_iter(&p, &v)) {
  760. if ((n & 0x1)) {
  761. if (*v == '@') {
  762. xs *link = NULL;
  763. xs *wuid = NULL;
  764. if (strchr(v + 1, '@') == NULL) {
  765. /* only one @? it's a dumb Mastodon-like mention
  766. without server; add the default one */
  767. wuid = xs_fmt("%s@%s", v, def_srv);
  768. snac_debug(snac, 2, xs_fmt("mention without server '%s' '%s'", v, wuid));
  769. }
  770. else
  771. wuid = xs_dup(v);
  772. /* query the webfinger about this fellow */
  773. xs *actor = NULL;
  774. xs *uid = NULL;
  775. int status;
  776. status = webfinger_request(wuid, &actor, &uid);
  777. if (valid_status(status) && actor && uid) {
  778. xs *d = xs_dict_new();
  779. xs *n = xs_fmt("@%s", uid);
  780. d = xs_dict_append(d, "type", "Mention");
  781. d = xs_dict_append(d, "href", actor);
  782. d = xs_dict_append(d, "name", n);
  783. tl = xs_list_append(tl, d);
  784. link = xs_fmt("<span class=\"h-card\"><a href=\"%s\" class=\"u-url mention\">%s</a></span>", actor, n);
  785. }
  786. if (!xs_is_null(link))
  787. nc = xs_str_cat(nc, link);
  788. else
  789. nc = xs_str_cat(nc, v);
  790. }
  791. else
  792. if (*v == '#') {
  793. /* hashtag */
  794. xs *d = xs_dict_new();
  795. xs *n = xs_utf8_tolower(v);
  796. xs *h = xs_fmt("%s?t=%s", srv_baseurl, n + 1);
  797. xs *l = xs_fmt("<a href=\"%s\" class=\"mention hashtag\" rel=\"tag\">%s</a>", h, v);
  798. d = xs_dict_append(d, "type", "Hashtag");
  799. d = xs_dict_append(d, "href", h);
  800. d = xs_dict_append(d, "name", n);
  801. tl = xs_list_append(tl, d);
  802. /* add the code */
  803. nc = xs_str_cat(nc, l);
  804. }
  805. else
  806. if (*v == '&') {
  807. /* HTML Unicode entity, probably part of an emoji */
  808. /* write as is */
  809. nc = xs_str_cat(nc, v);
  810. }
  811. }
  812. else
  813. nc = xs_str_cat(nc, v);
  814. n++;
  815. }
  816. *tag = tl;
  817. return nc;
  818. }
  819. void collect_replies(snac *user, const char *id)
  820. /* collects all replies for a post */
  821. {
  822. xs *obj = NULL;
  823. if (!valid_status(object_get(id, &obj))) {
  824. snac_debug(user, 1, xs_fmt("collect_replies: object '%s' is not here", id));
  825. return;
  826. }
  827. const xs_dict *replies_first = xs_dict_get_path(obj, "replies.first");
  828. if (!xs_is_dict(replies_first)) {
  829. snac_debug(user, 1, xs_fmt("collect_replies: object '%s' does not have replies.first", id));
  830. return;
  831. }
  832. const xs_list *level0_replies = xs_dict_get(replies_first, "items");
  833. const xs_list *level1_replies = NULL;
  834. const char *next = xs_dict_get(replies_first, "next");
  835. xs *reply_obj = NULL;
  836. if (xs_is_string(next) && !valid_status(activitypub_request(user, next, &reply_obj))) {
  837. snac_debug(user, 1, xs_fmt("collect_replies: error getting next replies object '%s'", next));
  838. return;
  839. }
  840. if (xs_is_dict(reply_obj))
  841. level1_replies = xs_dict_get(reply_obj, "items");
  842. xs *items = xs_list_new();
  843. if (xs_is_list(level0_replies))
  844. items = xs_list_cat(items, level0_replies);
  845. if (xs_is_list(level1_replies))
  846. items = xs_list_cat(items, level1_replies);
  847. const xs_val *v;
  848. xs_list_foreach(items, v) {
  849. xs *reply = NULL;
  850. if (xs_is_string(v)) {
  851. /* request the object */
  852. if (!valid_status(object_get(v, &reply))) {
  853. if (!valid_status(activitypub_request(user, v, &reply))) {
  854. snac_debug(user, 1, xs_fmt("collect_replies: error requesting object '%s'", v));
  855. continue;
  856. }
  857. }
  858. }
  859. else
  860. if (xs_is_dict(v)) {
  861. /* actually the post object */
  862. reply = xs_dup(v);
  863. }
  864. if (!xs_is_dict(reply))
  865. continue;
  866. const char *id = xs_dict_get(reply, "id");
  867. const char *type = xs_dict_get(reply, "type");
  868. const char *attr_to = get_atto(reply);
  869. if (!xs_is_string(id) || !xs_is_string(type) || !xs_is_string(attr_to))
  870. continue;
  871. if (!xs_match(type, POSTLIKE_OBJECT_TYPE))
  872. continue;
  873. if (timeline_here(user, id)) {
  874. snac_debug(user, 1, xs_fmt("collect_replies: item already in timeline %s", id));
  875. continue;
  876. }
  877. enqueue_actor_refresh(user, attr_to, 0);
  878. timeline_add(user, id, reply);
  879. snac_log(user, xs_fmt("new '%s' (collect_replies) %s %s", type, attr_to, id));
  880. }
  881. }
  882. void collect_outbox(snac *user, const char *actor_id)
  883. /* gets an actor's outbox and inserts a bunch of posts in a user's timeline */
  884. {
  885. int status;
  886. xs *actor = NULL;
  887. if (!valid_status(status = actor_request(user, actor_id, &actor))) {
  888. snac_debug(user, 1, xs_fmt("collect_outbox: cannot get actor object '%s' %d", actor_id, status));
  889. return;
  890. }
  891. xs *outbox = NULL;
  892. const char *outbox_url = xs_dict_get(actor, "outbox");
  893. if (!xs_is_string(outbox_url))
  894. return;
  895. if (!valid_status(status = activitypub_request(user, outbox_url, &outbox))) {
  896. snac_debug(user, 1, xs_fmt("collect_outbox: cannot get actor outbox '%s' %d", outbox_url, status));
  897. return;
  898. }
  899. const xs_list *ordered_items = xs_dict_get(outbox, "orderedItems");
  900. if (!xs_is_list(ordered_items)) {
  901. /* the list is not here; does it have a 'first'? */
  902. const char *first = xs_dict_get(outbox, "first");
  903. if (xs_is_string(first)) {
  904. /* download this instead */
  905. xs *first2 = xs_dup(first);
  906. xs_free(outbox);
  907. if (!valid_status(status = activitypub_request(user, first2, &outbox))) {
  908. snac_debug(user, 1, xs_fmt("collect_outbox: cannot get first page of outbox '%s' %d", first2, status));
  909. return;
  910. }
  911. /* last chance */
  912. ordered_items = xs_dict_get(outbox, "orderedItems");
  913. }
  914. }
  915. if (!xs_is_list(ordered_items)) {
  916. snac_debug(user, 1, xs_fmt("collect_outbox: cannot get list of posts for actor '%s' outbox", actor_id));
  917. return;
  918. }
  919. /* well, ok, then */
  920. int max = 4;
  921. const xs_val *v;
  922. xs_list_foreach(ordered_items, v) {
  923. if (max == 0)
  924. break;
  925. xs *post = NULL;
  926. if (xs_is_string(v)) {
  927. /* it's probably the post url */
  928. if (!valid_status(activitypub_request(user, v, &post)))
  929. continue;
  930. }
  931. else
  932. if (xs_is_dict(v))
  933. post = xs_dup(v);
  934. if (post == NULL)
  935. continue;
  936. const char *type = xs_dict_get(post, "type");
  937. if (!xs_is_string(type) || strcmp(type, "Create")) {
  938. /* not a post */
  939. continue;
  940. }
  941. if (is_msg_for_me(user, post) == 0) {
  942. /* not for us */
  943. continue;
  944. }
  945. const xs_dict *object = xs_dict_get(post, "object");
  946. if (!xs_is_dict(object))
  947. continue;
  948. type = xs_dict_get(object, "type");
  949. const char *id = xs_dict_get(object, "id");
  950. const char *attr_to = get_atto(object);
  951. if (!xs_is_string(type) || !xs_is_string(id) || !xs_is_string(attr_to))
  952. continue;
  953. if (!timeline_here(user, id)) {
  954. timeline_add(user, id, object);
  955. snac_log(user, xs_fmt("new '%s' (collect_outbox) %s %s", type, attr_to, id));
  956. }
  957. else
  958. snac_debug(user, 1, xs_fmt("collect_outbox: post '%s' already here", id));
  959. max--;
  960. }
  961. }
  962. void notify(snac *snac, const char *type, const char *utype, const char *actor, const xs_dict *msg)
  963. /* notifies the user of relevant events */
  964. {
  965. /* skip our own notifications */
  966. if (strcmp(snac->actor, actor) == 0)
  967. return;
  968. const char *id = xs_dict_get(msg, "id");
  969. if (strcmp(type, "Create") == 0) {
  970. /* only notify of notes specifically for us */
  971. xs *rcpts = recipient_list(snac, msg, 0);
  972. if (xs_list_in(rcpts, snac->actor) == -1 && !cool(snac, actor, OP_CHECK))
  973. return;
  974. /* discard votes */
  975. const xs_dict *note = xs_dict_get(msg, "object");
  976. if (note && !xs_is_null(xs_dict_get(note, "name")))
  977. return;
  978. }
  979. if (strcmp(type, "Undo") == 0 && strcmp(utype, "Follow") != 0)
  980. return;
  981. /* get the object id */
  982. const char *objid = xs_dict_get(msg, "object");
  983. if (xs_type(objid) == XSTYPE_DICT)
  984. objid = xs_dict_get(objid, "id");
  985. if (xs_match(type, "Like|Announce|EmojiReact")) {
  986. /* if it's not an admiration about something by us, done */
  987. if (xs_is_null(objid) || !is_msg_mine(snac, objid))
  988. return;
  989. /* if it's an announce by our own relay, done */
  990. xs *relay_id = xs_fmt("%s/relay", srv_baseurl);
  991. if (xs_startswith(id, relay_id))
  992. return;
  993. }
  994. /* updated poll? */
  995. if (strcmp(type, "Update") == 0 && strcmp(utype, "Question") == 0) {
  996. const xs_dict *poll;
  997. const char *poll_id;
  998. if ((poll = xs_dict_get(msg, "object")) == NULL)
  999. return;
  1000. /* if it's not closed, discard */
  1001. if (xs_is_null(xs_dict_get(poll, "closed")))
  1002. return;
  1003. if ((poll_id = xs_dict_get(poll, "id")) == NULL)
  1004. return;
  1005. /* if it's not ours and we didn't vote, discard */
  1006. if (!is_msg_mine(snac, poll_id) && !was_question_voted(snac, poll_id))
  1007. return;
  1008. }
  1009. /* user will love to know about this! */
  1010. /* prepare message body */
  1011. xs *body = xs_fmt("User : @%s@%s\n",
  1012. xs_dict_get(snac->config, "uid"),
  1013. xs_dict_get(srv_config, "host")
  1014. );
  1015. if (strcmp(utype, "(null)") != 0) {
  1016. xs *s1 = xs_fmt("Type : %s + %s\n", type, utype);
  1017. body = xs_str_cat(body, s1);
  1018. }
  1019. else {
  1020. xs *s1 = xs_fmt("Type : %s\n", type);
  1021. body = xs_str_cat(body, s1);
  1022. }
  1023. {
  1024. xs *s1 = xs_fmt("Actor : %s\n", actor);
  1025. body = xs_str_cat(body, s1);
  1026. }
  1027. if (objid != NULL) {
  1028. xs *s1 = xs_fmt("Object: %s\n", objid);
  1029. body = xs_str_cat(body, s1);
  1030. }
  1031. /* email */
  1032. const char *email = "[disabled by admin]";
  1033. if (xs_type(xs_dict_get(srv_config, "disable_email_notifications")) != XSTYPE_TRUE) {
  1034. email = xs_dict_get(snac->config_o, "email");
  1035. if (xs_is_null(email)) {
  1036. email = xs_dict_get(snac->config, "email");
  1037. if (xs_is_null(email))
  1038. email = "[empty]";
  1039. }
  1040. }
  1041. if (*email != '\0' && *email != '[') {
  1042. snac_debug(snac, 1, xs_fmt("email notify %s %s %s", type, utype, actor));
  1043. xs *subject = xs_fmt("snac notify for @%s@%s",
  1044. xs_dict_get(snac->config, "uid"), xs_dict_get(srv_config, "host"));
  1045. xs *from = xs_fmt("<snac-daemon@%s>", xs_dict_get(srv_config, "host"));
  1046. xs *header = xs_fmt(
  1047. "From: snac-daemon %s\n"
  1048. "To: %s\n"
  1049. "Subject: %s\n"
  1050. "\n",
  1051. from, email, subject);
  1052. xs *mailinfo = xs_dict_new();
  1053. xs *bd = xs_fmt("%s%s", header, body);
  1054. mailinfo = xs_dict_append(mailinfo, "from", from);
  1055. mailinfo = xs_dict_append(mailinfo, "to", email);
  1056. mailinfo = xs_dict_append(mailinfo, "body", bd);
  1057. enqueue_email(mailinfo, 0);
  1058. }
  1059. /* telegram */
  1060. const char *bot = xs_dict_get(snac->config, "telegram_bot");
  1061. const char *chat_id = xs_dict_get(snac->config, "telegram_chat_id");
  1062. if (!xs_is_null(bot) && !xs_is_null(chat_id) && *bot && *chat_id)
  1063. enqueue_telegram(body, bot, chat_id);
  1064. /* ntfy */
  1065. const char *ntfy_server = xs_dict_get(snac->config, "ntfy_server");
  1066. const char *ntfy_token = xs_dict_get(snac->config, "ntfy_token");
  1067. if (!xs_is_null(ntfy_server) && *ntfy_server)
  1068. enqueue_ntfy(body, ntfy_server, ntfy_token);
  1069. /* auto boost */
  1070. if (xs_match(type, "Create") && xs_is_true(xs_dict_get(snac->config, "auto_boost"))) {
  1071. xs *msg = msg_admiration(snac, objid, "Announce");
  1072. enqueue_message(snac, msg);
  1073. snac_debug(snac, 1, xs_fmt("auto boosted %s", objid));
  1074. }
  1075. /* finally, store it in the notification folder */
  1076. if (strcmp(type, "Follow") == 0)
  1077. objid = id;
  1078. else
  1079. if (strcmp(utype, "Follow") == 0)
  1080. objid = actor;
  1081. notify_add(snac, type, utype, actor, objid != NULL ? objid : id, msg);
  1082. }
  1083. /** messages **/
  1084. xs_dict *msg_base(snac *snac, const char *type, const char *id,
  1085. const char *actor, const char *date, const char *object)
  1086. /* creates a base ActivityPub message */
  1087. {
  1088. xs *did = NULL;
  1089. xs *published = NULL;
  1090. xs *ntid = tid(0);
  1091. const char *obj_id;
  1092. if (xs_type(object) == XSTYPE_DICT)
  1093. obj_id = xs_dict_get(object, "id");
  1094. else
  1095. obj_id = object;
  1096. /* generated values */
  1097. if (date && strcmp(date, "@now") == 0) {
  1098. published = xs_str_utctime(0, ISO_DATE_SPEC);
  1099. date = published;
  1100. }
  1101. if (id != NULL) {
  1102. if (strcmp(id, "@dummy") == 0) {
  1103. did = xs_fmt("%s/d/%s/%s", snac->actor, ntid, type);
  1104. id = did;
  1105. }
  1106. else
  1107. if (strcmp(id, "@object") == 0) {
  1108. if (obj_id != NULL) {
  1109. did = xs_fmt("%s/%s_%s", obj_id, type, ntid);
  1110. id = did;
  1111. }
  1112. else
  1113. id = NULL;
  1114. }
  1115. else
  1116. if (strcmp(id, "@wrapper") == 0) {
  1117. /* like @object, but always generate the same id */
  1118. if (object != NULL) {
  1119. date = xs_dict_get(object, "published");
  1120. did = xs_fmt("%s/%s", obj_id, type);
  1121. id = did;
  1122. }
  1123. else
  1124. id = NULL;
  1125. }
  1126. }
  1127. xs_dict *msg = xs_dict_new();
  1128. msg = xs_dict_append(msg, "@context", "https:/" "/www.w3.org/ns/activitystreams");
  1129. msg = xs_dict_append(msg, "type", type);
  1130. if (id != NULL)
  1131. msg = xs_dict_append(msg, "id", id);
  1132. if (actor != NULL)
  1133. msg = xs_dict_append(msg, "actor", actor);
  1134. if (date != NULL)
  1135. msg = xs_dict_append(msg, "published", date);
  1136. if (object != NULL)
  1137. msg = xs_dict_append(msg, "object", object);
  1138. return msg;
  1139. }
  1140. xs_dict *msg_collection(snac *snac, const char *id, int items)
  1141. /* creates an empty OrderedCollection message */
  1142. {
  1143. xs_dict *msg = msg_base(snac, "OrderedCollection", id, NULL, NULL, NULL);
  1144. xs *n = xs_number_new(items);
  1145. msg = xs_dict_append(msg, "attributedTo", snac->actor);
  1146. msg = xs_dict_append(msg, "totalItems", n);
  1147. return msg;
  1148. }
  1149. xs_dict *msg_replies(snac *user, const char *id, int fill)
  1150. /* creates a CollectionPage with replies of id */
  1151. {
  1152. xs *r_id = xs_replace(id, "/p/", "/r/");
  1153. xs *r_idp = xs_fmt("%s?page=true", r_id);
  1154. xs *r_idh = xs_fmt("%s", r_id);
  1155. xs_dict *msg = msg_base(user, "CollectionPage", r_idp, NULL, NULL, NULL);
  1156. msg = xs_dict_set(msg, "partOf", r_idh);
  1157. xs *items = xs_list_new();
  1158. if (fill) {
  1159. xs *children = object_children(id);
  1160. const char *md5;
  1161. xs_list_foreach(children, md5) {
  1162. xs *obj = NULL;
  1163. if (valid_status(object_get_by_md5(md5, &obj)) && is_msg_public(obj)) {
  1164. const char *c_id = xs_dict_get(obj, "id");
  1165. if (xs_is_string(c_id))
  1166. items = xs_list_append(items, c_id);
  1167. }
  1168. }
  1169. }
  1170. else {
  1171. msg = xs_dict_del(msg, "@context");
  1172. msg = xs_dict_del(msg, "id");
  1173. msg = xs_dict_set(msg, "next", r_idp);
  1174. }
  1175. msg = xs_dict_set(msg, "items", items);
  1176. return msg;
  1177. }
  1178. xs_dict *msg_accept(snac *snac, const xs_val *object, const char *to)
  1179. /* creates an Accept message (as a response to a Follow) */
  1180. {
  1181. xs_dict *msg = msg_base(snac, "Accept", "@dummy", snac->actor, NULL, object);
  1182. msg = xs_dict_append(msg, "to", to);
  1183. return msg;
  1184. }
  1185. xs_dict *msg_update(snac *snac, const xs_dict *object)
  1186. /* creates an Update message */
  1187. {
  1188. xs_dict *msg = msg_base(snac, "Update", "@object", snac->actor, "@now", object);
  1189. const char *type = xs_dict_get(object, "type");
  1190. if (strcmp(type, "Note") == 0) {
  1191. msg = xs_dict_append(msg, "to", xs_dict_get(object, "to"));
  1192. msg = xs_dict_append(msg, "cc", xs_dict_get(object, "cc"));
  1193. }
  1194. else
  1195. if (strcmp(type, "Person") == 0) {
  1196. msg = xs_dict_append(msg, "to", public_address);
  1197. /* also spam the people being followed, so that
  1198. they have the newest information about who we are */
  1199. xs *cc = following_list(snac);
  1200. msg = xs_dict_append(msg, "cc", cc);
  1201. }
  1202. else
  1203. msg = xs_dict_append(msg, "to", public_address);
  1204. return msg;
  1205. }
  1206. xs_dict *msg_admiration(snac *snac, const char *object, const char *type)
  1207. /* creates a Like, Announce or EmojiReact message */
  1208. {
  1209. xs *a_msg = NULL;
  1210. xs_dict *msg = NULL;
  1211. xs *wrk = NULL;
  1212. char t = 0;
  1213. switch (*type) {
  1214. case 'L':
  1215. t = 'l';
  1216. break;
  1217. case 'A':
  1218. t = 'a';
  1219. break;
  1220. case 'E':
  1221. t = 'e';
  1222. break;
  1223. }
  1224. /* call the object */
  1225. timeline_request(snac, &object, &wrk, 0);
  1226. if (valid_status(object_get(object, &a_msg))) {
  1227. xs *rcpts = xs_list_new();
  1228. xs *o_md5 = xs_md5_hex(object, strlen(object));
  1229. xs *id = xs_fmt("%s/%c/%s", snac->actor, t, o_md5);
  1230. msg = msg_base(snac, type, id, snac->actor, "@now", object);
  1231. if (is_msg_public(a_msg))
  1232. rcpts = xs_list_append(rcpts, public_address);
  1233. rcpts = xs_list_append(rcpts, get_atto(a_msg));
  1234. msg = xs_dict_append(msg, "to", rcpts);
  1235. }
  1236. else
  1237. snac_log(snac, xs_fmt("msg_admiration cannot retrieve object %s", object));
  1238. return msg;
  1239. }
  1240. xs_dict *msg_repulsion(snac *user, const char *id, const char *type)
  1241. /* creates an Undo + admiration message */
  1242. {
  1243. xs *a_msg = NULL;
  1244. xs_dict *msg = NULL;
  1245. if (valid_status(object_get(id, &a_msg))) {
  1246. /* create a clone of the original admiration message */
  1247. xs *object = msg_admiration(user, id, type);
  1248. /* delete the published date */
  1249. object = xs_dict_del(object, "published");
  1250. /* create an undo message for this object */
  1251. msg = msg_undo(user, object);
  1252. /* copy the 'to' field */
  1253. msg = xs_dict_set(msg, "to", xs_dict_get(object, "to"));
  1254. }
  1255. /* now we despise this */
  1256. object_unadmire(id, user->actor, *type == 'L' ? 1 : 0);
  1257. return msg;
  1258. }
  1259. xs_dict *msg_emoji_init(snac *snac, const char *mid, const char *eid_o)
  1260. /* creates an emoji reaction from a local user */
  1261. {
  1262. xs_dict *n_msg = msg_admiration(snac, mid, "EmojiReact");
  1263. xs *eid = xs_dup(eid_o);
  1264. xs *content = NULL;
  1265. xs *tag = xs_list_new();
  1266. xs *dict = xs_dict_new();
  1267. xs *icon = xs_dict_new();
  1268. xs *accounts = xs_list_new();
  1269. xs *emjs = emojis_rm_categories();
  1270. /* may be a default emoji */
  1271. xs *eidd = xs_dup(eid);
  1272. const char *eidda = eid;
  1273. if (xs_is_emoji(xs_utf8_dec(&eidda)))
  1274. content = xs_dup(eid);
  1275. else if (*eid == '%') {
  1276. content = xs_url_dec_emoji(eid);
  1277. if (content == NULL) {
  1278. xs_free(n_msg);
  1279. return NULL;
  1280. }
  1281. }
  1282. else {
  1283. content = xs_dup(eid);
  1284. const char *emo = xs_dict_get(emjs, content);
  1285. if (emo == NULL) {
  1286. xs_free(n_msg);
  1287. return NULL;
  1288. }
  1289. if (xs_match(emo, "https://*|http://*")) { /* emoji is an URL to an image */
  1290. icon = xs_dict_set(icon, "type", "Image");
  1291. icon = xs_dict_set(icon, "url", emo);
  1292. dict = xs_dict_set(dict, "icon", icon);
  1293. dict = xs_dict_set(dict, "id", emo);
  1294. dict = xs_dict_set(dict, "name", content);
  1295. dict = xs_dict_set(dict, "type", "Emoji");
  1296. tag = xs_list_append(tag, dict);
  1297. }
  1298. else
  1299. if (xs_startswith(emo, "&#")) {
  1300. /* snac default emoji as an HTML entity: decode */
  1301. content = xs_free(content);
  1302. xs *s1 = xs_strip_chars_i(xs_dup(emo), "&#");
  1303. unsigned int cpoint = 0;
  1304. sscanf(s1, "%u;", &cpoint);
  1305. if (cpoint)
  1306. content = xs_utf8_cat(xs_str_new(NULL), cpoint);
  1307. else
  1308. content = xs_dup(emo);
  1309. }
  1310. else {
  1311. /* use as it is and hope for the best */
  1312. xs_free(content);
  1313. content = xs_dup(emo);
  1314. }
  1315. }
  1316. accounts = xs_list_append(accounts, snac->actor);
  1317. xs *to_duplicate = xs_dup(xs_list_get(xs_dict_get(n_msg, "to"), 1));
  1318. n_msg = xs_dict_set(n_msg, "content", content);
  1319. n_msg = xs_dict_set(n_msg, "accounts", accounts);
  1320. n_msg = xs_dict_set(n_msg, "attributedTo", to_duplicate);
  1321. n_msg = xs_dict_set(n_msg, "accountId", snac->uid);
  1322. n_msg = xs_dict_set(n_msg, "tag", tag);
  1323. int ret = timeline_admire(snac, xs_dict_get(n_msg, "object"), snac->actor, 1, n_msg);
  1324. if (ret == 200 || ret == 201) {
  1325. enqueue_message(snac, n_msg);
  1326. return n_msg;
  1327. }
  1328. xs_free(n_msg);
  1329. return NULL;
  1330. }
  1331. xs_dict *msg_emoji_unreact(snac *user, const char *mid, const char *eid)
  1332. /* creates an Undo + emoji reaction message */
  1333. {
  1334. xs *a_msg = NULL;
  1335. xs_dict *msg = NULL;
  1336. if (valid_status(object_get(mid, &a_msg))) {
  1337. /* create a clone of the original admiration message */
  1338. xs *object = msg_admiration(user, mid, "EmojiReact");
  1339. /* delete the published date */
  1340. object = xs_dict_del(object, "published");
  1341. /* create an undo message for this object */
  1342. msg = msg_undo(user, object);
  1343. /* copy the 'to' field */
  1344. msg = xs_dict_set(msg, "to", xs_dict_get(object, "to"));
  1345. }
  1346. xs *emotes = object_get_emoji_reacts(mid);
  1347. const char *v;
  1348. int c = 0;
  1349. /* may be a default emoji */
  1350. if (strlen(eid) == 12 && *eid == '%') {
  1351. eid = xs_url_dec(eid);
  1352. if (eid == NULL) {
  1353. xs_free(msg);
  1354. return NULL;
  1355. }
  1356. }
  1357. /* lets get all emotes for this msg, and compare it to our content */
  1358. while (xs_list_next(emotes, &v, &c)) {
  1359. xs *e = NULL;
  1360. if (valid_status(object_get_by_md5(v, &e))) {
  1361. const char *content = xs_dict_get(e, "content");
  1362. const char *id = xs_dict_get(e, "id");
  1363. const char *actor = xs_dict_get(e, "actor");
  1364. /* maybe formated as :{emoteName}: too */
  1365. if (xs_str_in(eid, content) != -1)
  1366. if (strcmp(user->actor, actor) == 0) {
  1367. object_rm_emoji_react(mid, id);
  1368. return msg;
  1369. }
  1370. }
  1371. }
  1372. xs_free(msg);
  1373. return NULL;
  1374. }
  1375. xs_dict *msg_actor_place(snac *user, const char *label)
  1376. /* creates a Place object, if the user has a location defined */
  1377. {
  1378. xs_dict *place = NULL;
  1379. const char *latitude = xs_dict_get_def(user->config, "latitude", "");
  1380. const char *longitude = xs_dict_get_def(user->config, "longitude", "");
  1381. if (*latitude && *longitude) {
  1382. xs *d_la = xs_number_new(atof(latitude));
  1383. xs *d_lo = xs_number_new(atof(longitude));
  1384. place = msg_base(user, "Place", NULL, user->actor, NULL, NULL);
  1385. place = xs_dict_set(place, "name", label);
  1386. place = xs_dict_set(place, "latitude", d_la);
  1387. place = xs_dict_set(place, "longitude", d_lo);
  1388. }
  1389. return place;
  1390. }
  1391. xs_dict *msg_actor(snac *snac)
  1392. /* create a Person message for this actor */
  1393. {
  1394. xs *ctxt = xs_list_new();
  1395. xs *icon = xs_dict_new();
  1396. xs *keys = xs_dict_new();
  1397. xs *tags = xs_list_new();
  1398. xs *avtr = NULL;
  1399. xs *kid = NULL;
  1400. xs *f_bio = NULL;
  1401. xs_dict *msg = NULL;
  1402. const char *p;
  1403. int n;
  1404. /* everybody loves some caching */
  1405. if (time(NULL) - object_mtime(snac->actor) < 3 * 3600 &&
  1406. valid_status(object_get(snac->actor, &msg))) {
  1407. snac_debug(snac, 2, xs_fmt("Returning cached actor %s", snac->actor));
  1408. return msg;
  1409. }
  1410. msg = msg_base(snac, "Person", snac->actor, NULL, NULL, NULL);
  1411. /* change the @context (is this really necessary?) */
  1412. ctxt = xs_list_append(ctxt, "https:/" "/www.w3.org/ns/activitystreams");
  1413. ctxt = xs_list_append(ctxt, "https:/" "/w3id.org/security/v1");
  1414. msg = xs_dict_set(msg, "@context", ctxt);
  1415. msg = xs_dict_set(msg, "url", snac->actor);
  1416. msg = xs_dict_set(msg, "name", xs_dict_get(snac->config, "name"));
  1417. msg = xs_dict_set(msg, "preferredUsername", snac->uid);
  1418. msg = xs_dict_set(msg, "published", xs_dict_get(snac->config, "published"));
  1419. // this exists so we get the emoji tags from our name too.
  1420. // and then we just throw away the result, because it's kinda useless to have markdown in the display name.
  1421. xs *name_dummy = not_really_markdown(xs_dict_get(snac->config, "name"), NULL, &tags);
  1422. xs *f_bio_2 = not_really_markdown(xs_dict_get(snac->config, "bio"), NULL, &tags);
  1423. f_bio = process_tags(snac, f_bio_2, &tags);
  1424. msg = xs_dict_set(msg, "summary", f_bio);
  1425. msg = xs_dict_set(msg, "tag", tags);
  1426. char *folders[] = { "inbox", "outbox", "followers", "following", "featured", NULL };
  1427. for (n = 0; folders[n]; n++) {
  1428. xs *f = xs_fmt("%s/%s", snac->actor, folders[n]);
  1429. msg = xs_dict_set(msg, folders[n], f);
  1430. }
  1431. p = xs_dict_get(snac->config, "avatar");
  1432. if (*p == '\0')
  1433. avtr = xs_fmt("%s/susie.png", srv_baseurl);
  1434. else
  1435. avtr = xs_dup(p);
  1436. icon = xs_dict_append(icon, "type", "Image");
  1437. icon = xs_dict_append(icon, "mediaType", xs_mime_by_ext(avtr));
  1438. icon = xs_dict_append(icon, "url", avtr);
  1439. msg = xs_dict_set(msg, "icon", icon);
  1440. kid = xs_fmt("%s#main-key", snac->actor);
  1441. keys = xs_dict_append(keys, "id", kid);
  1442. keys = xs_dict_append(keys, "owner", snac->actor);
  1443. xs *public_key_pem = xs_dup(xs_dict_get(snac->key, "public"));
  1444. if (xs_is_string(public_key_pem)) {
  1445. /* crop any garbage after the PEM */
  1446. const char *pem_trailer = "\n-----END PUBLIC KEY-----\n";
  1447. int i = xs_str_in(public_key_pem, pem_trailer);
  1448. if (i > 0)
  1449. public_key_pem[i + strlen(pem_trailer)] = '\0';
  1450. }
  1451. keys = xs_dict_append(keys, "publicKeyPem", public_key_pem);
  1452. msg = xs_dict_set(msg, "publicKey", keys);
  1453. /* if the "bot" config field is set to true, change type to "Service" */
  1454. if (xs_type(xs_dict_get(snac->config, "bot")) == XSTYPE_TRUE)
  1455. msg = xs_dict_set(msg, "type", "Service");
  1456. /* if it's named "relay", then identify as an "Application" */
  1457. if (strcmp(snac->uid, "relay") == 0)
  1458. msg = xs_dict_set(msg, "type", "Application");
  1459. /* add the header image, if there is one defined */
  1460. const char *header = xs_dict_get(snac->config, "header");
  1461. if (!xs_is_null(header)) {
  1462. xs *d = xs_dict_new();
  1463. d = xs_dict_append(d, "type", "Image");
  1464. d = xs_dict_append(d, "mediaType", xs_mime_by_ext(header));
  1465. d = xs_dict_append(d, "url", header);
  1466. msg = xs_dict_set(msg, "image", d);
  1467. }
  1468. /* add the metadata as attachments of PropertyValue */
  1469. xs *metadata = NULL;
  1470. const xs_dict *md = xs_dict_get(snac->config, "metadata");
  1471. if (xs_type(md) == XSTYPE_DICT)
  1472. metadata = xs_dup(md);
  1473. else
  1474. if (xs_type(md) == XSTYPE_STRING) {
  1475. metadata = xs_dict_new();
  1476. xs *l = xs_split(md, "\n");
  1477. const char *ll;
  1478. xs_list_foreach(l, ll) {
  1479. xs *kv = xs_split_n(ll, "=", 1);
  1480. const char *k = xs_list_get(kv, 0);
  1481. const char *v = xs_list_get(kv, 1);
  1482. if (k && v) {
  1483. xs *kk = xs_strip_i(xs_dup(k));
  1484. xs *vv = xs_strip_i(xs_dup(v));
  1485. metadata = xs_dict_set(metadata, kk, vv);
  1486. }
  1487. }
  1488. }
  1489. if (xs_type(metadata) == XSTYPE_DICT) {
  1490. xs *attach = xs_list_new();
  1491. const xs_str *k;
  1492. const xs_str *v;
  1493. int c = 0;
  1494. while (xs_dict_next(metadata, &k, &v, &c)) {
  1495. xs *d = xs_dict_new();
  1496. xs *k2 = encode_html(k);
  1497. xs *v2 = NULL;
  1498. if (xs_startswith(v, "https:/") || xs_startswith(v, "http:/")) {
  1499. xs *t = encode_html(v);
  1500. v2 = xs_fmt("<a href=\"%s\" rel=\"me\">%s</a>", t, t);
  1501. }
  1502. else
  1503. v2 = encode_html(v);
  1504. d = xs_dict_append(d, "type", "PropertyValue");
  1505. d = xs_dict_append(d, "name", k2);
  1506. d = xs_dict_append(d, "value", v2);
  1507. attach = xs_list_append(attach, d);
  1508. }
  1509. msg = xs_dict_set(msg, "attachment", attach);
  1510. }
  1511. /* use shared inboxes? */
  1512. if (xs_is_true(xs_dict_get(srv_config, "shared_inboxes")) || strcmp(snac->uid, "relay") == 0) {
  1513. xs *d = xs_dict_new();
  1514. xs *si = xs_fmt("%s/shared-inbox", srv_baseurl);
  1515. d = xs_dict_append(d, "sharedInbox", si);
  1516. msg = xs_dict_set(msg, "endpoints", d);
  1517. }
  1518. /* does this user have an aka? */
  1519. const char *aka = xs_dict_get(snac->config, "alias");
  1520. if (xs_type(aka) == XSTYPE_STRING && *aka) {
  1521. xs *loaka = xs_list_append(xs_list_new(), aka);
  1522. msg = xs_dict_set(msg, "alsoKnownAs", loaka);
  1523. }
  1524. const xs_val *manually = xs_dict_get(snac->config, "approve_followers");
  1525. msg = xs_dict_set(msg, "manuallyApprovesFollowers",
  1526. xs_stock(xs_is_true(manually) ? XSTYPE_TRUE : XSTYPE_FALSE));
  1527. /* if there are location coords, create a Place object */
  1528. xs *location = msg_actor_place(snac, "Home");
  1529. if (xs_type(location) == XSTYPE_DICT)
  1530. msg = xs_dict_set(msg, "location", location);
  1531. xs *webfinger = xs_fmt("%s@%s", snac->uid, xs_dict_get(srv_config, "host"));
  1532. msg = xs_dict_set(msg, "webfinger", webfinger);
  1533. if (xs_is_true(xs_dict_get(snac->config, "show_contact_metrics"))) {
  1534. xs *fwing = xs_number_new_l(following_list_len(snac));
  1535. xs *fwers = xs_number_new_l(follower_list_len(snac));
  1536. msg = xs_dict_set(msg, "following_count", fwing);
  1537. msg = xs_dict_set(msg, "followers_count", fwers);
  1538. }
  1539. /* cache it */
  1540. snac_debug(snac, 1, xs_fmt("Caching actor %s", snac->actor));
  1541. object_add_ow(snac->actor, msg);
  1542. return msg;
  1543. }
  1544. xs_dict *msg_create(snac *snac, const xs_dict *object)
  1545. /* creates a 'Create' message */
  1546. {
  1547. xs_dict *msg = msg_base(snac, "Create", "@wrapper", snac->actor, NULL, object);
  1548. const xs_val *v;
  1549. if ((v = get_atto(object)))
  1550. msg = xs_dict_append(msg, "attributedTo", v);
  1551. if ((v = xs_dict_get(object, "cc")))
  1552. msg = xs_dict_append(msg, "cc", v);
  1553. if ((v = xs_dict_get(object, "to")))
  1554. msg = xs_dict_append(msg, "to", v);
  1555. else
  1556. msg = xs_dict_append(msg, "to", public_address);
  1557. return msg;
  1558. }
  1559. xs_dict *msg_undo(snac *snac, const xs_val *object)
  1560. /* creates an 'Undo' message */
  1561. {
  1562. xs_dict *msg = msg_base(snac, "Undo", "@object", snac->actor, "@now", object);
  1563. const char *to;
  1564. if (xs_type(object) == XSTYPE_DICT && (to = xs_dict_get(object, "object")))
  1565. msg = xs_dict_append(msg, "to", to);
  1566. return msg;
  1567. }
  1568. xs_dict *msg_delete(snac *snac, const char *id)
  1569. /* creates a 'Delete' + 'Tombstone' for a local entry */
  1570. {
  1571. xs *tomb = xs_dict_new();
  1572. xs_dict *msg = NULL;
  1573. /* sculpt the tombstone */
  1574. tomb = xs_dict_append(tomb, "type", "Tombstone");
  1575. tomb = xs_dict_append(tomb, "id", id);
  1576. /* now create the Delete */
  1577. msg = msg_base(snac, "Delete", "@object", snac->actor, "@now", tomb);
  1578. xs *to = xs_list_new();
  1579. xs *involved = object_likes(id);
  1580. xs *boosts = object_announces(id);
  1581. xs *children = object_children(id);
  1582. const char *md5;
  1583. involved = xs_list_cat(involved, boosts);
  1584. involved = xs_list_cat(involved, children);
  1585. /* add everybody */
  1586. to = xs_list_append(to, public_address);
  1587. /* add actors that liked, boosted or replied to this */
  1588. xs_list_foreach(involved, md5) {
  1589. xs *actor = NULL;
  1590. if (valid_status(object_get_by_md5(md5, &actor))) {
  1591. const char *id = xs_dict_get(actor, "id");
  1592. const char *atto = get_atto(actor);
  1593. if (xs_is_string(atto))
  1594. to = xs_list_append(to, atto);
  1595. else
  1596. if (xs_is_string(id))
  1597. to = xs_list_append(to, id);
  1598. }
  1599. }
  1600. msg = xs_dict_append(msg, "to", to);
  1601. return msg;
  1602. }
  1603. xs_dict *msg_follow(snac *snac, const char *q)
  1604. /* creates a 'Follow' message */
  1605. {
  1606. xs *actor_o = NULL;
  1607. xs *actor = NULL;
  1608. xs_dict *msg = NULL;
  1609. int status;
  1610. xs *url_or_uid = xs_strip_i(xs_str_new(q));
  1611. if (xs_startswith(url_or_uid, "https:/") || xs_startswith(url_or_uid, "http:/"))
  1612. actor = xs_dup(url_or_uid);
  1613. else
  1614. if (!valid_status(webfinger_request(url_or_uid, &actor, NULL)) || actor == NULL) {
  1615. snac_log(snac, xs_fmt("cannot resolve user %s to follow", url_or_uid));
  1616. return NULL;
  1617. }
  1618. /* request the actor */
  1619. status = actor_request(snac, actor, &actor_o);
  1620. if (valid_status(status)) {
  1621. /* check if the actor is an alias */
  1622. const char *r_actor = xs_dict_get(actor_o, "id");
  1623. if (r_actor && strcmp(actor, r_actor) != 0) {
  1624. snac_log(snac, xs_fmt("actor to follow is an alias %s -> %s", actor, r_actor));
  1625. }
  1626. msg = msg_base(snac, "Follow", "@dummy", snac->actor, NULL, r_actor);
  1627. }
  1628. else
  1629. snac_log(snac, xs_fmt("cannot get actor to follow %s %d", actor, status));
  1630. return msg;
  1631. }
  1632. xs_dict *msg_note(snac *snac, const xs_str *content, const xs_val *rcpts,
  1633. const xs_str *in_reply_to, const xs_list *attach,
  1634. int scope, const char *lang_str, const char *msg_date)
  1635. /* creates a 'Note' message */
  1636. /* scope: 0, public; 1, private (mentioned only); 2, "quiet public"; 3, followers only */
  1637. {
  1638. xs *ntid = tid(0);
  1639. xs *id = xs_fmt("%s/p/%s", snac->actor, ntid);
  1640. xs *ctxt = NULL;
  1641. xs *fc2 = NULL;
  1642. xs *fc1 = NULL;
  1643. xs *to = NULL;
  1644. xs *cc = xs_list_new();
  1645. xs *irt = NULL;
  1646. xs *tag = xs_list_new();
  1647. xs *atls = xs_list_new();
  1648. /* discard non-parseable dates */
  1649. if (!xs_is_string(msg_date) || xs_parse_iso_date(msg_date, 0) == 0)
  1650. msg_date = NULL;
  1651. xs_dict *msg = msg_base(snac, "Note", id, NULL, xs_or(msg_date, "@now"), NULL);
  1652. xs_list *p;
  1653. const xs_val *v;
  1654. const int priv = (scope == SCOPE_MENTIONED || scope == SCOPE_FOLLOWERS);
  1655. if (rcpts == NULL)
  1656. to = xs_list_new();
  1657. else {
  1658. if (xs_type(rcpts) == XSTYPE_STRING) {
  1659. to = xs_list_new();
  1660. to = xs_list_append(to, rcpts);
  1661. }
  1662. else
  1663. to = xs_dup(rcpts);
  1664. }
  1665. /* format the content */
  1666. fc2 = not_really_markdown(content, &atls, &tag);
  1667. if (in_reply_to != NULL && *in_reply_to) {
  1668. xs *p_msg = NULL;
  1669. xs *wrk = NULL;
  1670. /* demand this thing */
  1671. timeline_request(snac, &in_reply_to, &wrk, 0);
  1672. if (valid_status(object_get(in_reply_to, &p_msg))) {
  1673. /* add this author as recipient */
  1674. const char *a, *v;
  1675. if ((a = get_atto(p_msg)) && xs_list_in(to, a) == -1)
  1676. to = xs_list_append(to, a);
  1677. /* add this author to the tag list as a mention */
  1678. if (!xs_is_null(a)) {
  1679. xs *l = xs_split(a, "/");
  1680. xs *actor_o = NULL;
  1681. if (xs_list_len(l) > 3 && valid_status(object_get(a, &actor_o))) {
  1682. const char *uname = xs_dict_get(actor_o, "preferredUsername");
  1683. if (!xs_is_null(uname) && *uname) {
  1684. xs *handle = xs_fmt("@%s@%s", uname, xs_list_get(l, 2));
  1685. xs *t = xs_dict_new();
  1686. t = xs_dict_append(t, "type", "Mention");
  1687. t = xs_dict_append(t, "href", a);
  1688. t = xs_dict_append(t, "name", handle);
  1689. tag = xs_list_append(tag, t);
  1690. }
  1691. }
  1692. }
  1693. /* get the context, if there is one */
  1694. if ((v = xs_dict_get(p_msg, "context")))
  1695. ctxt = xs_dup(v);
  1696. /* propagate the conversation field, if there is one */
  1697. if ((v = xs_dict_get(p_msg, "conversation")))
  1698. msg = xs_dict_append(msg, "conversation", v);
  1699. /* if this message is public or unlisted, ours will also be */
  1700. const int orig_scope = get_msg_visibility(p_msg);
  1701. if (!priv && orig_scope == SCOPE_PUBLIC && xs_list_in(to, public_address) == -1)
  1702. to = xs_list_append(to, public_address);
  1703. else
  1704. if (!priv && orig_scope == SCOPE_UNLISTED && xs_list_in(cc, public_address) == -1)
  1705. cc = xs_list_append(cc, public_address);
  1706. }
  1707. irt = xs_dup(in_reply_to);
  1708. }
  1709. else
  1710. irt = xs_val_new(XSTYPE_NULL);
  1711. /* extract the mentions and hashtags and convert the content */
  1712. fc1 = process_tags(snac, fc2, &tag);
  1713. /* create the attachment list, if there are any */
  1714. if (!xs_is_null(attach)) {
  1715. xs_list_foreach(attach, v) {
  1716. const char *url = xs_list_get(v, 0);
  1717. const char *alt = xs_list_get(v, 1);
  1718. const char *mime = xs_mime_by_ext(url);
  1719. int add = 1;
  1720. /* check if it's already here */
  1721. const xs_dict *ad;
  1722. xs_list_foreach(atls, ad) {
  1723. if (strcmp(xs_dict_get_def(ad, "url", ""), url) == 0) {
  1724. add = 0;
  1725. break;
  1726. }
  1727. }
  1728. if (add) {
  1729. xs *d = xs_dict_new();
  1730. d = xs_dict_append(d, "mediaType", mime);
  1731. d = xs_dict_append(d, "url", url);
  1732. d = xs_dict_append(d, "name", alt);
  1733. d = xs_dict_append(d, "type",
  1734. xs_startswith(mime, "image/") ? "Image" : "Document");
  1735. atls = xs_list_append(atls, d);
  1736. }
  1737. }
  1738. }
  1739. if (ctxt == NULL)
  1740. ctxt = xs_fmt("%s#ctxt", id);
  1741. /* add all mentions to the appropriate field */
  1742. p = tag;
  1743. while (xs_list_iter(&p, &v)) {
  1744. if (xs_type(v) == XSTYPE_DICT) {
  1745. const char *t;
  1746. if (!xs_is_null(t = xs_dict_get(v, "type")) && strcmp(t, "Mention") == 0) {
  1747. if (!xs_is_null(t = xs_dict_get(v, "href"))) {
  1748. if (scope == SCOPE_MENTIONED) {
  1749. /* for DMs, mentions go to 'to' */
  1750. to = xs_list_append(to, t);
  1751. } else {
  1752. /* for other visibility levels, mentions go to 'cc' */
  1753. cc = xs_list_append(cc, t);
  1754. }
  1755. }
  1756. }
  1757. }
  1758. }
  1759. if (scope == SCOPE_UNLISTED) {
  1760. /* Mastodon's "quiet public": remove from to, add public address to cc */
  1761. int idx;
  1762. if ((idx = xs_list_in(to, public_address)) != -1)
  1763. to = xs_list_del(to, idx);
  1764. if (xs_list_in(cc, public_address) == -1)
  1765. cc = xs_list_append(cc, public_address);
  1766. }
  1767. else
  1768. if (scope == SCOPE_FOLLOWERS) {
  1769. /* followers-only: add followers collection to to */
  1770. xs *followers_url = xs_fmt("%s/followers", snac->actor);
  1771. if (xs_list_in(to, followers_url) == -1)
  1772. to = xs_list_append(to, followers_url);
  1773. }
  1774. else
  1775. if (scope == SCOPE_PUBLIC) {
  1776. /* public: ensure public address is in to and not in cc */
  1777. int idx;
  1778. if ((idx = xs_list_in(cc, public_address)) != -1)
  1779. cc = xs_list_del(cc, idx);
  1780. if (xs_list_in(to, public_address) == -1)
  1781. to = xs_list_append(to, public_address);
  1782. }
  1783. /* delete all cc recipients that also are in the to */
  1784. p = to;
  1785. while (xs_list_iter(&p, &v)) {
  1786. int i;
  1787. if ((i = xs_list_in(cc, v)) != -1)
  1788. cc = xs_list_del(cc, i);
  1789. }
  1790. msg = xs_dict_append(msg, "attributedTo", snac->actor);
  1791. msg = xs_dict_append(msg, "summary", "");
  1792. msg = xs_dict_append(msg, "content", fc1);
  1793. msg = xs_dict_append(msg, "context", ctxt);
  1794. msg = xs_dict_append(msg, "url", id);
  1795. msg = xs_dict_append(msg, "to", to);
  1796. msg = xs_dict_append(msg, "cc", cc);
  1797. msg = xs_dict_append(msg, "inReplyTo", irt);
  1798. msg = xs_dict_append(msg, "tag", tag);
  1799. msg = xs_dict_append(msg, "sourceContent", content);
  1800. if (xs_list_len(atls))
  1801. msg = xs_dict_append(msg, "attachment", atls);
  1802. /* set language content map */
  1803. if (xs_type(lang_str) == XSTYPE_STRING) {
  1804. /* split at the first _ */
  1805. xs *l0 = xs_split(lang_str, "_");
  1806. const char *lang = xs_list_get(l0, 0);
  1807. if (xs_type(lang) == XSTYPE_STRING && strlen(lang) == 2) {
  1808. /* a valid ISO language id */
  1809. xs *cmap = xs_dict_new();
  1810. cmap = xs_dict_set(cmap, lang, xs_dict_get(msg, "content"));
  1811. msg = xs_dict_set(msg, "contentMap", cmap);
  1812. }
  1813. }
  1814. if (!priv) {
  1815. /* create the replies object */
  1816. xs *replies = xs_dict_new();
  1817. xs *r_id = xs_replace(id, "/p/", "/r/");
  1818. xs *h_id = xs_fmt("%s", r_id);
  1819. xs *rp = msg_replies(snac, id, 0);
  1820. replies = xs_dict_set(replies, "id", h_id);
  1821. replies = xs_dict_set(replies, "type", "Collection");
  1822. replies = xs_dict_set(replies, "first", rp);
  1823. msg = xs_dict_set(msg, "replies", replies);
  1824. }
  1825. {
  1826. /* quote-posting your own posts */
  1827. xs *own_link = xs_regex_select_n(content, "RE: https?:/" "/[^ \r\n]+", 1);
  1828. if (xs_list_len(own_link) >= 1) {
  1829. /* strip the RE: */
  1830. xs *url = xs_replace_n(xs_list_get(own_link, 0), "RE: ", "", 1);
  1831. /* get the object */
  1832. xs *obj = NULL;
  1833. if (valid_status(object_get(url, &obj))) {
  1834. /* only allowed with your own posts */
  1835. const char *atto = get_atto(obj);
  1836. const char *id = xs_dict_get(obj, "id");
  1837. if (xs_is_string(atto) && xs_is_string(id) && strcmp(atto, snac->actor) == 0) {
  1838. msg = xs_dict_set(msg, "quoteUri", id);
  1839. msg = xs_dict_set(msg, "quoteUrl", id);
  1840. }
  1841. }
  1842. }
  1843. }
  1844. return msg;
  1845. }
  1846. xs_dict *msg_ping(snac *user, const char *rcpt)
  1847. /* creates a Ping message (https://humungus.tedunangst.com/r/honk/v/tip/f/docs/ping.txt) */
  1848. {
  1849. xs_dict *msg = msg_base(user, "Ping", "@dummy", user->actor, NULL, NULL);
  1850. msg = xs_dict_append(msg, "to", rcpt);
  1851. return msg;
  1852. }
  1853. xs_dict *msg_pong(snac *user, const char *rcpt, const char *object)
  1854. /* creates a Pong message (https://humungus.tedunangst.com/r/honk/v/tip/f/docs/ping.txt) */
  1855. {
  1856. xs_dict *msg = msg_base(user, "Pong", "@dummy", user->actor, NULL, object);
  1857. msg = xs_dict_append(msg, "to", rcpt);
  1858. return msg;
  1859. }
  1860. xs_dict *msg_move(snac *user, const char *new_account)
  1861. /* creates a Move message (to move the user to new_account) */
  1862. {
  1863. xs_dict *msg = msg_base(user, "Move", "@dummy", user->actor, NULL, user->actor);
  1864. msg = xs_dict_append(msg, "target", new_account);
  1865. return msg;
  1866. }
  1867. xs_dict *msg_question(snac *user, const char *content, xs_list *attach,
  1868. const xs_list *opts, int multiple, int end_secs)
  1869. /* creates a Question message */
  1870. {
  1871. xs_dict *msg = msg_note(user, content, NULL, NULL, attach, 0, NULL, NULL);
  1872. const xs_number *max_options = xs_dict_get(srv_config, "max_poll_options");
  1873. const xs_number *max_length = xs_dict_get(srv_config, "max_poll_option_length");
  1874. xs_set seen;
  1875. size_t max_line = 60;
  1876. int max = 8;
  1877. if (xs_type(max_options) == XSTYPE_NUMBER)
  1878. max = xs_number_get(max_options);
  1879. if (xs_type(max_length) == XSTYPE_NUMBER)
  1880. max_line = xs_number_get(max_length);
  1881. msg = xs_dict_set(msg, "type", "Question");
  1882. /* make it non-editable */
  1883. msg = xs_dict_del(msg, "sourceContent");
  1884. xs *o = xs_list_new();
  1885. xs_list *p = (xs_list *)opts;
  1886. const xs_str *v;
  1887. xs *replies = xs_json_loads("{\"type\":\"Collection\",\"totalItems\":0}");
  1888. xs_set_init(&seen);
  1889. while (max && xs_list_iter(&p, &v)) {
  1890. if (*v) {
  1891. xs *v2 = xs_dup(v);
  1892. xs *d = xs_dict_new();
  1893. if (strlen(v2) > max_line) {
  1894. v2[max_line] = '\0';
  1895. v2 = xs_str_cat(v2, "...");
  1896. }
  1897. if (xs_set_add(&seen, v2) == 1) {
  1898. d = xs_dict_append(d, "type", "Note");
  1899. d = xs_dict_append(d, "name", v2);
  1900. d = xs_dict_append(d, "replies", replies);
  1901. o = xs_list_append(o, d);
  1902. max--;
  1903. }
  1904. }
  1905. }
  1906. xs_set_free(&seen);
  1907. msg = xs_dict_append(msg, multiple ? "anyOf" : "oneOf", o);
  1908. /* set the end time */
  1909. time_t t = time(NULL) + end_secs;
  1910. xs *et = xs_str_utctime(t, ISO_DATE_SPEC);
  1911. msg = xs_dict_append(msg, "endTime", et);
  1912. return msg;
  1913. }
  1914. int get_msg_visibility(const xs_dict *msg)
  1915. /* determine visibility from message based on CC, TO and /followers mark */
  1916. {
  1917. const xs_val *to = xs_dict_get(msg, "to");
  1918. const xs_val *cc = xs_dict_get(msg, "cc");
  1919. /* check if it's unlisted (public in cc but not in to) */
  1920. int pub_in_to = 0;
  1921. int pub_in_cc = 0;
  1922. if ((xs_type(to) == XSTYPE_STRING && strcmp(to, public_address) == 0) ||
  1923. (xs_type(to) == XSTYPE_LIST && xs_list_in(to, public_address) != -1))
  1924. pub_in_to = 1;
  1925. if ((xs_type(cc) == XSTYPE_STRING && strcmp(cc, public_address) == 0) ||
  1926. (xs_type(cc) == XSTYPE_LIST && xs_list_in(cc, public_address) != -1))
  1927. pub_in_cc = 1;
  1928. if (!pub_in_to && pub_in_cc) {
  1929. return SCOPE_UNLISTED;
  1930. }
  1931. if (pub_in_to && !pub_in_cc) {
  1932. return SCOPE_PUBLIC;
  1933. }
  1934. xs *followers_url = xs_fmt("%s/followers", xs_dict_get(msg, "attributedTo"));
  1935. if ((xs_type(to) == XSTYPE_STRING && strcmp(to, followers_url) == 0) ||
  1936. (xs_type(to) == XSTYPE_LIST && xs_list_in(to, followers_url) != -1))
  1937. return SCOPE_FOLLOWERS;
  1938. else
  1939. return SCOPE_MENTIONED;
  1940. /* should be unreachable, someone violated the protocol. */
  1941. /* better treat it as followers-only to make sure we don't leak information.*/
  1942. return SCOPE_FOLLOWERS;
  1943. }
  1944. int update_question(snac *user, const char *id)
  1945. /* updates the poll counts */
  1946. {
  1947. xs *msg = NULL;
  1948. xs *rcnt = xs_dict_new();
  1949. xs *lopts = xs_list_new();
  1950. const xs_list *opts;
  1951. xs_list *p;
  1952. const xs_val *v;
  1953. /* get the object */
  1954. if (!valid_status(object_get(id, &msg)))
  1955. return -1;
  1956. /* closed? do nothing more */
  1957. if (xs_dict_get(msg, "closed"))
  1958. return -2;
  1959. /* get the options */
  1960. if ((opts = xs_dict_get(msg, "oneOf")) == NULL &&
  1961. (opts = xs_dict_get(msg, "anyOf")) == NULL)
  1962. return -3;
  1963. /* fill the initial count */
  1964. int c = 0;
  1965. while (xs_list_next(opts, &v, &c)) {
  1966. const char *name = xs_dict_get(v, "name");
  1967. if (name) {
  1968. lopts = xs_list_append(lopts, name);
  1969. rcnt = xs_dict_set(rcnt, name, xs_stock(0));
  1970. }
  1971. }
  1972. xs_set s;
  1973. xs_set_init(&s);
  1974. /* iterate now the children (the votes) */
  1975. xs *chld = object_children(id);
  1976. p = chld;
  1977. while (xs_list_iter(&p, &v)) {
  1978. xs *obj = NULL;
  1979. if (!valid_status(object_get_by_md5(v, &obj)))
  1980. continue;
  1981. const char *name = xs_dict_get(obj, "name");
  1982. const char *atto = get_atto(obj);
  1983. if (name && atto) {
  1984. /* get the current count */
  1985. const xs_number *cnt = xs_dict_get(rcnt, name);
  1986. if (xs_type(cnt) == XSTYPE_NUMBER) {
  1987. /* if it exists, increment */
  1988. xs *ucnt = xs_number_new(xs_number_get(cnt) + 1);
  1989. rcnt = xs_dict_set(rcnt, name, ucnt);
  1990. xs_set_add(&s, atto);
  1991. }
  1992. }
  1993. }
  1994. xs *rcpts = xs_set_result(&s);
  1995. /* create a new list of options with their new counts */
  1996. xs *nopts = xs_list_new();
  1997. p = lopts;
  1998. while (xs_list_iter(&p, &v)) {
  1999. const xs_number *cnt = xs_dict_get(rcnt, v);
  2000. if (xs_type(cnt) == XSTYPE_NUMBER) {
  2001. xs *d1 = xs_dict_new();
  2002. xs *d2 = xs_dict_new();
  2003. d2 = xs_dict_append(d2, "type", "Collection");
  2004. d2 = xs_dict_append(d2, "totalItems", cnt);
  2005. d1 = xs_dict_append(d1, "type", "Note");
  2006. d1 = xs_dict_append(d1, "name", v);
  2007. d1 = xs_dict_append(d1, "replies", d2);
  2008. nopts = xs_list_append(nopts, d1);
  2009. }
  2010. }
  2011. /* update the list */
  2012. msg = xs_dict_set(msg, xs_dict_get(msg, "oneOf") != NULL ? "oneOf" : "anyOf", nopts);
  2013. /* due date? */
  2014. int closed = 0;
  2015. const char *end_time = xs_dict_get(msg, "endTime");
  2016. if (!xs_is_null(end_time)) {
  2017. xs *now = xs_str_utctime(0, ISO_DATE_SPEC);
  2018. /* is now greater than the endTime? */
  2019. if (strcmp(now, end_time) >= 0) {
  2020. xs *et = xs_dup(end_time);
  2021. msg = xs_dict_set(msg, "closed", et);
  2022. closed = 1;
  2023. }
  2024. }
  2025. /* update the count of voters */
  2026. xs *vcnt = xs_number_new(xs_list_len(rcpts));
  2027. msg = xs_dict_set(msg, "votersCount", vcnt);
  2028. msg = xs_dict_set(msg, "cc", rcpts);
  2029. /* store */
  2030. object_add_ow(id, msg);
  2031. snac_debug(user, 1, xs_fmt("recounted poll %s", id));
  2032. timeline_touch(user);
  2033. /* send an update message to all voters */
  2034. xs *u_msg = msg_update(user, msg);
  2035. u_msg = xs_dict_set(u_msg, "cc", rcpts);
  2036. enqueue_message(user, u_msg);
  2037. if (closed) {
  2038. xs *c_msg = msg_update(user, msg);
  2039. notify(user, "Update", "Question", user->actor, c_msg);
  2040. }
  2041. return 0;
  2042. }
  2043. /** queues **/
  2044. int process_input_message(snac *snac, const xs_dict *msg, const xs_dict *req)
  2045. /* processes an ActivityPub message from the input queue */
  2046. /* return values: -1, fatal error; 0, transient error, retry;
  2047. 1, processed and done; 2, propagate to users (only when no user is set) */
  2048. {
  2049. const char *actor = xs_dict_get(msg, "actor");
  2050. const char *type = xs_dict_get(msg, "type");
  2051. xs *actor_o = NULL;
  2052. int a_status;
  2053. int do_notify = 0;
  2054. if (xs_is_null(actor) || *actor == '\0') {
  2055. srv_debug(0, xs_fmt("malformed message (bad actor)"));
  2056. return -1;
  2057. }
  2058. /* this instance is alive */
  2059. instance_failure(actor, OP_DEL);
  2060. /* question votes may not have a type */
  2061. if (xs_is_null(type))
  2062. type = "Note";
  2063. /* reject uninteresting messages right now */
  2064. if (xs_match(type, "Add|View|Reject|Read|Remove")) {
  2065. srv_debug(0, xs_fmt("Ignored message of type '%s'", type));
  2066. /* archive the ignored activity */
  2067. xs *ntid = tid(0);
  2068. xs *fn = xs_fmt("%s/ignored/%s.json", srv_basedir, ntid);
  2069. FILE *f;
  2070. if ((f = fopen(fn, "w")) != NULL) {
  2071. xs_json_dump(msg, 4, f);
  2072. fclose(f);
  2073. }
  2074. return -1;
  2075. }
  2076. if (strcmp(type, "EmojiReact") == 0 && xs_is_true(xs_dict_get(srv_config, "disable_emojireact"))) {
  2077. srv_log(xs_fmt("Dropping EmojiReact from %s due to admin configuration", actor));
  2078. return -1;
  2079. }
  2080. const char *object, *utype;
  2081. object = xs_dict_get(msg, "object");
  2082. if (object != NULL && xs_type(object) == XSTYPE_DICT)
  2083. utype = xs_dict_get(object, "type");
  2084. else
  2085. utype = "(null)";
  2086. /* special case for Delete messages */
  2087. if (strcmp(type, "Delete") == 0) {
  2088. /* if the actor is not here, do not even try */
  2089. if (!object_here(actor)) {
  2090. srv_debug(1, xs_fmt("dropped 'Delete' message from unknown actor '%s'", actor));
  2091. return -1;
  2092. }
  2093. /* discard crap */
  2094. if (xs_is_null(object)) {
  2095. srv_log(xs_fmt("dropped 'Delete' message with invalid object from actor '%s'", actor));
  2096. return -1;
  2097. }
  2098. /* also discard if the object to be deleted is not here */
  2099. const char *obj_id = object;
  2100. if (xs_type(obj_id) == XSTYPE_DICT)
  2101. obj_id = xs_dict_get(obj_id, "id");
  2102. if (xs_is_null(obj_id) || !object_here(obj_id)) {
  2103. srv_debug(1, xs_fmt("dropped 'Delete' message from unknown object '%s'", obj_id));
  2104. return -1;
  2105. }
  2106. }
  2107. /* bring the actor */
  2108. a_status = actor_request(snac, actor, &actor_o);
  2109. /* do not retry permanent failures */
  2110. if (a_status == HTTP_STATUS_NOT_FOUND
  2111. || a_status == HTTP_STATUS_GONE
  2112. || a_status < 0) {
  2113. srv_debug(1, xs_fmt("dropping message due to actor error %s %d", actor, a_status));
  2114. return -1;
  2115. }
  2116. if (!valid_status(a_status)) {
  2117. /* do not retry 'Delete' messages */
  2118. if (strcmp(type, "Delete") == 0) {
  2119. srv_debug(1, xs_fmt("dropping 'Delete' message due to actor error %s %d", actor, a_status));
  2120. return -1;
  2121. }
  2122. /* other actor download errors */
  2123. /* the actor may require a signed request; propagate if no user is set */
  2124. if (snac == NULL)
  2125. return 2;
  2126. /* may need a retry */
  2127. srv_debug(0, xs_fmt("error requesting actor %s %d -- retry later", actor, a_status));
  2128. return 0;
  2129. }
  2130. /* check the signature */
  2131. xs *sig_err = NULL;
  2132. xs *key_id = NULL;
  2133. if (!check_signature(req, &sig_err, &key_id)) {
  2134. srv_log(xs_fmt("bad signature %s (%s)", actor, sig_err));
  2135. srv_archive_error("check_signature", sig_err, req, msg);
  2136. return -1;
  2137. }
  2138. /* if no user is set, no further checks can be done; propagate */
  2139. if (snac == NULL)
  2140. return 2;
  2141. /* reject messages that are not for this user */
  2142. if (!is_msg_for_me(snac, msg)) {
  2143. snac_debug(snac, 1, xs_fmt("message from %s of type '%s' not for us", actor, type));
  2144. return 1;
  2145. }
  2146. /* if it's a DM from someone we don't follow, reject the message */
  2147. if (xs_type(xs_dict_get(snac->config, "drop_dm_from_unknown")) == XSTYPE_TRUE) {
  2148. if (strcmp(utype, "Note") == 0 && !is_msg_public(msg) &&
  2149. !following_check(snac, actor)) {
  2150. snac_log(snac, xs_fmt("DM rejected from unknown actor %s", actor));
  2151. return 1;
  2152. }
  2153. }
  2154. /* check the minimum acceptable account age */
  2155. int min_account_age = xs_number_get(xs_dict_get(srv_config, "min_account_age"));
  2156. if (min_account_age > 0) {
  2157. const char *actor_date = xs_dict_get(actor_o, "published");
  2158. if (!xs_is_null(actor_date)) {
  2159. time_t actor_t = xs_parse_iso_date(actor_date, 0);
  2160. if (actor_t < 950000000) {
  2161. snac_log(snac, xs_fmt("rejected activity from %s (suspicious date, %s)",
  2162. actor, actor_date));
  2163. return 1;
  2164. }
  2165. if (actor_t > 0) {
  2166. int td = (int)(time(NULL) - actor_t);
  2167. snac_debug(snac, 2, xs_fmt("actor %s age: %d seconds", actor, td));
  2168. if (td < min_account_age) {
  2169. snac_log(snac, xs_fmt("rejected activity from %s (too new, %d seconds)",
  2170. actor, td));
  2171. return 1;
  2172. }
  2173. }
  2174. }
  2175. else
  2176. snac_debug(snac, 1, xs_fmt("warning: empty or null creation date for %s", actor));
  2177. }
  2178. if (strcmp(type, "Follow") == 0) { /** **/
  2179. const char *id = xs_dict_get(msg, "id");
  2180. if (xs_is_null(id)) {
  2181. snac_log(snac, xs_fmt("malformed message: no 'id' field"));
  2182. }
  2183. else
  2184. if (!follower_check(snac, actor)) {
  2185. /* ensure the actor object is here */
  2186. if (!object_here(actor)) {
  2187. xs *actor_obj = NULL;
  2188. actor_request(snac, actor, &actor_obj);
  2189. object_add(actor, actor_obj);
  2190. }
  2191. if (xs_is_true(xs_dict_get(snac->config, "approve_followers"))) {
  2192. pending_add(snac, actor, msg);
  2193. snac_log(snac, xs_fmt("new pending follower approval %s", actor));
  2194. }
  2195. else {
  2196. /* automatic following */
  2197. xs *f_msg = xs_dup(msg);
  2198. xs *reply = msg_accept(snac, f_msg, actor);
  2199. post_message(snac, actor, reply);
  2200. if (xs_is_null(xs_dict_get(f_msg, "published"))) {
  2201. /* add a date if it doesn't include one (Mastodon) */
  2202. xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
  2203. f_msg = xs_dict_set(f_msg, "published", date);
  2204. }
  2205. timeline_add(snac, id, f_msg);
  2206. follower_add(snac, actor);
  2207. snac_log(snac, xs_fmt("new follower %s", actor));
  2208. }
  2209. do_notify = 1;
  2210. }
  2211. else
  2212. snac_log(snac, xs_fmt("repeated 'Follow' from %s", actor));
  2213. }
  2214. else
  2215. if (strcmp(type, "Undo") == 0) { /** **/
  2216. const char *id = xs_dict_get(object, "object");
  2217. const char *content = xs_dict_get(object, "content");
  2218. /* misskey sends emojis as like + tag */
  2219. xs *cd = xs_dup(content);
  2220. const char *sna = cd;
  2221. const xs_dict *tag = xs_dict_get(object, "tag");
  2222. unsigned int utf = xs_utf8_dec((const char **)&sna);
  2223. int isEmoji = 0;
  2224. if (xs_is_emoji(utf) || (tag && xs_list_len(tag) > 0))
  2225. isEmoji = 1;
  2226. if (xs_type(object) != XSTYPE_DICT) {
  2227. snac_debug(snac, 1, xs_fmt("undo: overriding utype %s | %s | %s",
  2228. utype, id, actor));
  2229. utype = "Follow";
  2230. }
  2231. if (strcmp(actor, key_id)) {
  2232. snac_log(snac, xs_fmt("Undo: mismatched actor '%s' and key '%s'", actor, key_id));
  2233. }
  2234. else
  2235. if (strcmp(utype, "Follow") == 0) { /** **/
  2236. if (!id) {
  2237. snac_log(snac, xs_fmt("no id (msg.object.object) when "
  2238. "handling follow: %s", actor));
  2239. return 1;
  2240. }
  2241. if (strcmp(id, snac->actor) != 0 && strcmp(id, snac->actor_alt) != 0)
  2242. snac_debug(snac, 1, xs_fmt("Undo + Follow from %s not for us (%s)", actor, id));
  2243. else
  2244. if (valid_status(follower_del(snac, actor))) {
  2245. snac_log(snac, xs_fmt("no longer following us %s", actor));
  2246. do_notify = 1;
  2247. }
  2248. else
  2249. if (pending_check(snac, actor)) {
  2250. pending_del(snac, actor);
  2251. snac_log(snac, xs_fmt("cancelled pending follow from %s", actor));
  2252. }
  2253. else
  2254. snac_log(snac, xs_fmt("error deleting follower %s", actor));
  2255. }
  2256. /* *key emojis are like w/ Emoji tag */
  2257. else
  2258. if (isEmoji || strcmp(utype, "EmojiReact") == 0) {
  2259. const xs_val *mid = xs_dict_get(object, "id");
  2260. int status = object_rm_emoji_react(id, mid);
  2261. /* ensure *key notifications type */
  2262. utype = "EmojiReact";
  2263. snac_log(snac, xs_fmt("Undo 'EmojiReact' for %s %d", id, status));
  2264. }
  2265. else
  2266. if (strcmp(utype, "Like") == 0) { /** **/
  2267. int status = object_unadmire(id, actor, 1);
  2268. snac_log(snac, xs_fmt("Undo '%s' for %s %d", utype, id, status));
  2269. }
  2270. else
  2271. if (strcmp(utype, "Announce") == 0) { /** **/
  2272. int status = HTTP_STATUS_OK;
  2273. /* commented out: if a followed user boosts something that
  2274. is requested and then unboosts, the post remains here,
  2275. but with no apparent reason, and that is confusing */
  2276. //status = object_unadmire(id, actor, 0);
  2277. snac_log(snac, xs_fmt("Unboost for %s %d", id, status));
  2278. }
  2279. else
  2280. snac_debug(snac, 1, xs_fmt("ignored 'Undo' for object type '%s'", utype));
  2281. }
  2282. else
  2283. if (strcmp(type, "Create") == 0) { /** **/
  2284. if (is_muted(snac, actor)) {
  2285. snac_log(snac, xs_fmt("ignored 'Create' + '%s' from muted actor %s", utype, actor));
  2286. return 1;
  2287. }
  2288. if (xs_match(utype, "Note|Article")) { /** **/
  2289. const char *id = xs_dict_get(object, "id");
  2290. const char *in_reply_to = get_in_reply_to(object);
  2291. const char *atto = get_atto(object);
  2292. xs *wrk = NULL;
  2293. if (xs_is_null(id))
  2294. snac_log(snac, xs_fmt("malformed message: no 'id' field"));
  2295. else
  2296. if (xs_is_null(atto))
  2297. snac_log(snac, xs_fmt("malformed message: no 'attributedTo' field"));
  2298. else
  2299. if (!xs_is_null(in_reply_to) && is_hidden(snac, in_reply_to)) {
  2300. snac_debug(snac, 0, xs_fmt("dropped reply %s to hidden post %s", id, in_reply_to));
  2301. }
  2302. else {
  2303. if (content_match("filter_reject.txt", object)) {
  2304. snac_log(snac, xs_fmt("rejected by content %s", id));
  2305. return 1;
  2306. }
  2307. if (strcmp(key_id, atto) != 0) {
  2308. if (following_check(snac, key_id)) {
  2309. snac_debug(snac, 1, xs_fmt("Warning: trusting key_id %s for post %s from %s atto", key_id, id, atto));
  2310. }
  2311. else {
  2312. snac_debug(snac, 1, xs_fmt("Warning: %s key_id != atto (%s != %s) -- deferring request", id, key_id, atto));
  2313. enqueue_object_request(snac, id, 0);
  2314. return 1;
  2315. }
  2316. }
  2317. if (strcmp(actor, atto) != 0)
  2318. snac_log(snac, xs_fmt("SUSPICIOUS: actor != atto (%s != %s)", actor, atto));
  2319. timeline_request(snac, &in_reply_to, &wrk, 0);
  2320. const char *quoted_id = xs_or(xs_dict_get(object, "quoteUri"), xs_dict_get(object, "quoteUrl"));
  2321. if (xs_is_string(quoted_id) && xs_match(quoted_id, "https://*|http://*")) { /** **/
  2322. xs *quoted_post = NULL;
  2323. int status;
  2324. if (valid_status(status = activitypub_request(snac, quoted_id, &quoted_post))) {
  2325. /* got quoted post */
  2326. object_add(quoted_id, quoted_post);
  2327. }
  2328. snac_debug(snac, 1, xs_fmt("retrieving quoted post %s %d", quoted_id, status));
  2329. }
  2330. if (timeline_add(snac, id, object)) {
  2331. snac_log(snac, xs_fmt("new '%s' %s %s", utype, actor, id));
  2332. do_notify = 1;
  2333. }
  2334. /* if it has a "name" field, it may be a vote for a question */
  2335. const char *name = xs_dict_get(object, "name");
  2336. if (!xs_is_null(name) && *name && !xs_is_null(in_reply_to) && *in_reply_to)
  2337. update_question(snac, in_reply_to);
  2338. }
  2339. }
  2340. else
  2341. if (strcmp(utype, "Question") == 0) { /** **/
  2342. const char *id = xs_dict_get(object, "id");
  2343. if (xs_is_null(id))
  2344. snac_log(snac, xs_fmt("malformed message: no 'id' field"));
  2345. else
  2346. if (timeline_add(snac, id, object))
  2347. snac_log(snac, xs_fmt("new 'Question' %s %s", actor, id));
  2348. }
  2349. else
  2350. if (xs_match(utype, "Audio|Video|Event")) { /** **/
  2351. const char *id = xs_dict_get(object, "id");
  2352. if (xs_is_null(id))
  2353. snac_log(snac, xs_fmt("malformed message: no 'id' field"));
  2354. else
  2355. if (timeline_add(snac, id, object))
  2356. snac_log(snac, xs_fmt("new '%s' %s %s", utype, actor, id));
  2357. }
  2358. else
  2359. snac_debug(snac, 1, xs_fmt("ignored 'Create' for object type '%s'", utype));
  2360. }
  2361. else
  2362. if (strcmp(type, "Accept") == 0) { /** **/
  2363. if (strcmp(utype, "(null)") == 0) {
  2364. const char *obj_id = xs_dict_get(msg, "object");
  2365. /* if the accepted object id is a string that may
  2366. be created by us, it's a follow */
  2367. if (xs_type(obj_id) == XSTYPE_STRING &&
  2368. xs_startswith(obj_id, srv_baseurl) &&
  2369. xs_endswith(obj_id, "/Follow"))
  2370. utype = "Follow";
  2371. }
  2372. if (strcmp(utype, "Follow") == 0) { /** **/
  2373. if (following_check(snac, actor)) {
  2374. following_add(snac, actor, msg);
  2375. snac_log(snac, xs_fmt("confirmed follow from %s", actor));
  2376. /* request a bit of this fellow's outbox */
  2377. enqueue_collect_outbox(snac, actor);
  2378. }
  2379. else
  2380. snac_log(snac, xs_fmt("spurious follow accept from %s", actor));
  2381. }
  2382. else
  2383. if (strcmp(utype, "Create") == 0) {
  2384. /* some implementations send Create confirmations, go figure */
  2385. snac_debug(snac, 1, xs_dup("ignored 'Accept' + 'Create'"));
  2386. }
  2387. else {
  2388. xs_str *e = xs_fmt("ignored 'Accept' for object type '%s'", utype);
  2389. srv_archive_error("accept", e, req, msg);
  2390. snac_log(snac, e);
  2391. }
  2392. }
  2393. else
  2394. if (strcmp(type, "Like") == 0 || strcmp(type, "EmojiReact") == 0) { /** **/
  2395. /* misskey sends emojis as Like + tag.
  2396. * It is easier to handle them both at the same time. */
  2397. const char *sna = xs_dict_get(msg, "content");
  2398. const xs_dict *tag = xs_dict_get(msg, "tag");
  2399. unsigned int utf = xs_utf8_dec((const char **)&sna);
  2400. if (xs_is_emoji(utf) || (tag && xs_list_len(tag) > 0))
  2401. type = "EmojiReact";
  2402. if (xs_type(object) == XSTYPE_DICT)
  2403. object = xs_dict_get(object, "id");
  2404. if (xs_is_null(object))
  2405. snac_log(snac, xs_fmt("malformed message: no 'id' field"));
  2406. else
  2407. if (timeline_admire(snac, object, actor, 1, msg) == HTTP_STATUS_CREATED)
  2408. snac_log(snac, xs_fmt("new '%s' %s %s", type, actor, object));
  2409. else
  2410. snac_log(snac, xs_fmt("repeated '%s' from %s to %s", type, actor, object));
  2411. do_notify = 1;
  2412. }
  2413. else
  2414. if (strcmp(type, "Announce") == 0) { /** **/
  2415. if (xs_type(object) == XSTYPE_DICT)
  2416. object = xs_dict_get(object, "id");
  2417. if (xs_is_null(object))
  2418. snac_log(snac, xs_fmt("malformed message: no 'id' field"));
  2419. else
  2420. if (is_muted(snac, actor) && !is_msg_mine(snac, object))
  2421. snac_log(snac, xs_fmt("dropped 'Announce' from muted actor %s", actor));
  2422. else
  2423. if (is_limited(snac, actor) && !is_msg_mine(snac, object))
  2424. snac_log(snac, xs_fmt("dropped 'Announce' from limited actor %s", actor));
  2425. else {
  2426. xs *a_msg = NULL;
  2427. xs *wrk = NULL;
  2428. timeline_request(snac, &object, &wrk, 0);
  2429. if (valid_status(object_get(object, &a_msg))) {
  2430. const char *who = get_atto(a_msg);
  2431. /* got the admired object: instance is [back] online */
  2432. instance_failure(object, OP_DEL);
  2433. if (who && !is_muted(snac, who)) {
  2434. /* bring the actor */
  2435. xs *who_o = NULL;
  2436. if (valid_status(actor_request(snac, who, &who_o))) {
  2437. /* don't account as such announces by our own relay */
  2438. xs *this_relay = xs_fmt("%s/relay", srv_baseurl);
  2439. if (strcmp(actor, this_relay) != 0) {
  2440. if (valid_status(timeline_admire(snac, object, actor, 0, a_msg)))
  2441. snac_log(snac, xs_fmt("new 'Announce' %s %s", actor, object));
  2442. else
  2443. snac_log(snac, xs_fmt("repeated 'Announce' from %s to %s",
  2444. actor, object));
  2445. }
  2446. /* distribute the post with the actor as 'proxy' */
  2447. list_distribute(snac, actor, a_msg);
  2448. /* distribute the post to users following these hashtags */
  2449. followed_hashtag_distribute(a_msg);
  2450. /* actor is [back] alive */
  2451. actor_failure(who, OP_DEL);
  2452. do_notify = 1;
  2453. }
  2454. else
  2455. snac_debug(snac, 1, xs_fmt("dropped 'Announce' on actor request error %s", who));
  2456. }
  2457. else
  2458. snac_log(snac, xs_fmt("ignored 'Announce' about muted actor %s", who));
  2459. }
  2460. else
  2461. snac_debug(snac, 2, xs_fmt("error requesting 'Announce' object %s", object));
  2462. }
  2463. }
  2464. else
  2465. if (strcmp(type, "Update") == 0) { /** **/
  2466. if (xs_match(utype, "Person|Service|Application")) { /** **/
  2467. if (strcmp(actor, key_id) == 0) {
  2468. actor_add(actor, xs_dict_get(msg, "object"));
  2469. timeline_touch(snac);
  2470. snac_log(snac, xs_fmt("updated actor %s", actor));
  2471. }
  2472. else {
  2473. /* actor / key mismatch: don't accept blindly, but request an actor update
  2474. from the original source, as the Update may come from a relay and be legit */
  2475. enqueue_actor_refresh(snac, actor, -10);
  2476. snac_log(snac, xs_fmt("Update: mismatched actor '%s' and key '%s'", actor, key_id));
  2477. }
  2478. }
  2479. else
  2480. if (xs_match(utype, "Note|Page|Article|Video|Audio|Event")) { /** **/
  2481. const char *id = xs_dict_get(object, "id");
  2482. if (xs_is_null(id))
  2483. snac_log(snac, xs_fmt("malformed message: no 'id' field"));
  2484. else
  2485. if (object_here(id)) {
  2486. const char *atto = get_atto(object);
  2487. if (atto == NULL)
  2488. snac_log(snac, xs_fmt("ignored post 'Update' with no attributedTo %s", id));
  2489. else
  2490. if (strcmp(atto, key_id) != 0) {
  2491. /* actor / key mismatch: request the object from the original source */
  2492. enqueue_object_request(snac, id, -10);
  2493. snac_log(snac, xs_fmt("Update: mismatched attributedTo '%s' and key '%s'", atto, key_id));
  2494. }
  2495. else
  2496. if (xs_startswith(id, srv_baseurl) && !xs_startswith(id, actor))
  2497. snac_log(snac, xs_fmt("ignored incorrect 'Update' %s %s", actor, id));
  2498. else {
  2499. object_add_ow(id, object);
  2500. timeline_touch(snac);
  2501. snac_log(snac, xs_fmt("updated '%s' %s", utype, id));
  2502. }
  2503. }
  2504. else
  2505. snac_log(snac, xs_fmt("dropped update for unknown '%s' %s", utype, id));
  2506. }
  2507. else
  2508. if (strcmp(utype, "Question") == 0) { /** **/
  2509. const char *id = xs_dict_get(object, "id");
  2510. const char *closed = xs_dict_get(object, "closed");
  2511. if (xs_is_null(id))
  2512. snac_log(snac, xs_fmt("malformed message: no 'id' field"));
  2513. else {
  2514. object_add_ow(id, object);
  2515. timeline_touch(snac);
  2516. snac_log(snac, xs_fmt("%s poll %s", closed == NULL ? "updated" : "closed", id));
  2517. if (closed != NULL)
  2518. do_notify = 1;
  2519. }
  2520. }
  2521. else {
  2522. srv_archive_error("unsupported_update", "unsupported_update", req, msg);
  2523. snac_log(snac, xs_fmt("ignored 'Update' for object type '%s'", utype));
  2524. }
  2525. }
  2526. else
  2527. if (strcmp(type, "Delete") == 0) { /** **/
  2528. if (xs_type(object) == XSTYPE_DICT)
  2529. object = xs_dict_get(object, "id");
  2530. xs *obj_data = NULL;
  2531. if (xs_is_null(object))
  2532. snac_log(snac, xs_fmt("malformed message: no 'id' field"));
  2533. else
  2534. if (valid_status(object_get(object, &obj_data))) {
  2535. const char *atto = get_atto(obj_data);
  2536. if (atto == NULL)
  2537. snac_log(snac, xs_fmt("ignored 'Delete' for object without attributedTo %s", object));
  2538. else
  2539. if (strcmp(atto, key_id) != 0) {
  2540. /* don't call srv_archive_error() on this, because it can be a delete from a relay */
  2541. snac_log(snac, xs_fmt("Delete: mismatched attributedTo '%s' and key '%s'", atto, key_id));
  2542. }
  2543. else
  2544. if (xs_startswith(object, srv_baseurl) && !is_msg_mine(snac, object))
  2545. snac_log(snac, xs_fmt("ignored incorrect 'Delete' %s %s", actor, object));
  2546. else {
  2547. timeline_del(snac, object);
  2548. snac_debug(snac, 1, xs_fmt("new 'Delete' %s %s", actor, object));
  2549. }
  2550. }
  2551. else
  2552. snac_debug(snac, 1, xs_fmt("ignored 'Delete' for unknown object %s", object));
  2553. }
  2554. else
  2555. if (strcmp(type, "Pong") == 0) { /** **/
  2556. snac_log(snac, xs_fmt("'Pong' received from %s", actor));
  2557. }
  2558. else
  2559. if (strcmp(type, "Ping") == 0) { /** **/
  2560. const char *id = xs_dict_get(msg, "id");
  2561. snac_log(snac, xs_fmt("'Ping' requested from %s", actor));
  2562. if (!xs_is_null(id)) {
  2563. xs *rsp = msg_pong(snac, actor, id);
  2564. enqueue_output_by_actor(snac, rsp, actor, 0);
  2565. }
  2566. }
  2567. else
  2568. if (strcmp(type, "Block") == 0) { /** **/
  2569. snac_debug(snac, 1, xs_fmt("'Block' received from %s", actor));
  2570. /* should we MUTE the actor back? */
  2571. /* mute(snac, actor); */
  2572. if (!xs_is_true(xs_dict_get(srv_config, "disable_block_notifications")))
  2573. do_notify = 1;
  2574. }
  2575. else
  2576. if (strcmp(type, "Move") == 0) { /** **/
  2577. do_notify = 1;
  2578. const char *old_account = xs_dict_get(msg, "object");
  2579. const char *new_account = xs_dict_get(msg, "target");
  2580. if (xs_is_string(old_account) && xs_is_string(new_account)) {
  2581. if (strcmp(old_account, key_id) != 0) {
  2582. xs_str *e = xs_fmt("'Move': mismatched old_account %s and key %s", old_account, key_id);
  2583. srv_archive_error("move_old_account_key_mismatch", e, req, msg);
  2584. snac_log(snac, e);
  2585. }
  2586. else
  2587. if (following_check(snac, old_account)) {
  2588. xs *n_actor = NULL;
  2589. if (valid_status(object_get(new_account, &n_actor))) {
  2590. const xs_list *aka = xs_dict_get(n_actor, "alsoKnownAs");
  2591. if (xs_type(aka) == XSTYPE_LIST) {
  2592. if (xs_list_in(aka, old_account) != -1) {
  2593. /* all conditions met! */
  2594. /* follow new account */
  2595. xs *f_msg = msg_follow(snac, new_account);
  2596. if (f_msg != NULL) {
  2597. const char *new_actor = xs_dict_get(f_msg, "object");
  2598. following_add(snac, new_actor, f_msg);
  2599. enqueue_output_by_actor(snac, f_msg, new_actor, 0);
  2600. snac_log(snac, xs_fmt("'Move': following %s", new_account));
  2601. }
  2602. /* unfollow old account */
  2603. xs *of_msg = NULL;
  2604. if (valid_status(following_get(snac, old_account, &of_msg))) {
  2605. xs *uf_msg = msg_undo(snac, xs_dict_get(of_msg, "object"));
  2606. following_del(snac, old_account);
  2607. enqueue_output_by_actor(snac, uf_msg, old_account, 0);
  2608. snac_log(snac, xs_fmt("'Move': unfollowing %s", old_account));
  2609. }
  2610. }
  2611. else
  2612. snac_log(snac, xs_fmt("'Move' error: old actor %s not found in %s 'alsoKnownAs'",
  2613. old_account, new_account));
  2614. }
  2615. else
  2616. snac_log(snac, xs_fmt("'Move' error: cannot get %s 'alsoKnownAs'", new_account));
  2617. }
  2618. else {
  2619. snac_log(snac, xs_fmt("'Move' error: cannot get new actor %s", new_account));
  2620. /* may be a server hiccup, retry later */
  2621. return 0;
  2622. }
  2623. }
  2624. else
  2625. snac_log(snac, xs_fmt("'Move' error: actor %s is not being followed", old_account));
  2626. }
  2627. else {
  2628. snac_log(snac, xs_fmt("'Move' error: malformed message from %s", actor));
  2629. srv_archive_error("move", "move", req, msg);
  2630. }
  2631. }
  2632. else {
  2633. srv_archive_error("unsupported_type", "unsupported_type", req, msg);
  2634. snac_debug(snac, 1, xs_fmt("process_input_message type '%s' ignored", type));
  2635. }
  2636. if (do_notify) {
  2637. notify(snac, type, utype, actor, msg);
  2638. timeline_touch(snac);
  2639. }
  2640. return 1;
  2641. }
  2642. int send_email(const xs_dict *mailinfo)
  2643. /* invoke curl */
  2644. {
  2645. const char *url = xs_dict_get(srv_config, "smtp_url");
  2646. if (!xs_is_string(url) || *url == '\0') {
  2647. /* revert back to old sendmail pipe behaviour */
  2648. const char *msg = xs_dict_get(mailinfo, "body");
  2649. FILE *f;
  2650. int status;
  2651. int fds[2];
  2652. pid_t pid;
  2653. if (pipe(fds) == -1) return -1;
  2654. pid = vfork();
  2655. if (pid == -1) return -1;
  2656. else if (pid == 0) {
  2657. dup2(fds[0], 0);
  2658. close(fds[0]);
  2659. close(fds[1]);
  2660. execl("/usr/sbin/sendmail", "sendmail", "-t", (char *) NULL);
  2661. _exit(1);
  2662. }
  2663. close(fds[0]);
  2664. if ((f = fdopen(fds[1], "w")) == NULL) {
  2665. close(fds[1]);
  2666. return -1;
  2667. }
  2668. fprintf(f, "%s\n", msg);
  2669. fclose(f);
  2670. if (waitpid(pid, &status, 0) == -1) return -1;
  2671. return status;
  2672. }
  2673. const char
  2674. *user = xs_dict_get(srv_config, "smtp_username"),
  2675. *pass = xs_dict_get(srv_config, "smtp_password"),
  2676. *from = xs_dict_get(mailinfo, "from"),
  2677. *to = xs_dict_get(mailinfo, "to"),
  2678. *body = xs_dict_get(mailinfo, "body");
  2679. if (url == NULL || *url == '\0')
  2680. url = "smtp://localhost";
  2681. int smtp_port = parse_port(url, NULL);
  2682. return xs_smtp_request(url, user, pass, from, to, body, smtp_port == 465 || smtp_port == 587);
  2683. }
  2684. void process_user_queue_item(snac *user, xs_dict *q_item)
  2685. /* processes an item from the user queue */
  2686. {
  2687. const char *type;
  2688. int queue_retry_max = xs_number_get(xs_dict_get(srv_config, "queue_retry_max"));
  2689. if ((type = xs_dict_get(q_item, "type")) == NULL)
  2690. type = "output";
  2691. if (strcmp(type, "message") == 0) {
  2692. const xs_dict *msg = xs_dict_get(q_item, "message");
  2693. xs *rcpts = recipient_list(user, msg, 1);
  2694. xs_set inboxes;
  2695. const xs_str *actor;
  2696. xs_set_init(&inboxes);
  2697. /* add this shared inbox first */
  2698. xs *this_shared_inbox = xs_fmt("%s/shared-inbox", srv_baseurl);
  2699. xs_set_add(&inboxes, this_shared_inbox);
  2700. enqueue_output(user, msg, this_shared_inbox, 0, 0);
  2701. /* iterate the recipients */
  2702. xs_list_foreach(rcpts, actor) {
  2703. /* local users were served by this_shared_inbox */
  2704. if (!xs_startswith(actor, srv_baseurl)) {
  2705. xs *inbox = get_actor_inbox(actor, 1);
  2706. if (inbox != NULL) {
  2707. /* add to the set and, if it's not there, send message */
  2708. if (xs_set_add(&inboxes, inbox) == 1)
  2709. enqueue_output(user, msg, inbox, 0, 0);
  2710. }
  2711. else
  2712. snac_log(user, xs_fmt("cannot find inbox for %s", actor));
  2713. }
  2714. }
  2715. /* if it's a public note or question, send to the collected inboxes */
  2716. if (xs_match(xs_dict_get_def(msg, "type", ""), "Create|Update") && is_msg_public(msg)) {
  2717. if (xs_type(xs_dict_get(srv_config, "disable_inbox_collection")) != XSTYPE_TRUE) {
  2718. xs *shibx = inbox_list();
  2719. const xs_str *inbox;
  2720. xs_list_foreach(shibx, inbox) {
  2721. if (xs_set_add(&inboxes, inbox) == 1)
  2722. enqueue_output(user, msg, inbox, 0, 0);
  2723. }
  2724. }
  2725. }
  2726. xs_set_free(&inboxes);
  2727. /* relay this note */
  2728. if (is_msg_public(msg) && strcmp(user->uid, "relay") != 0) { /* avoid loops */
  2729. snac relay;
  2730. if (user_open(&relay, "relay")) {
  2731. /* a 'relay' user exists */
  2732. const char *type = xs_dict_get(msg, "type");
  2733. if (xs_is_string(type) && strcmp(type, "Create") == 0) {
  2734. const xs_val *object = xs_dict_get(msg, "object");
  2735. if (xs_is_dict(object)) {
  2736. object = xs_dict_get(object, "id");
  2737. snac_debug(&relay, 1, xs_fmt("relaying message %s", object));
  2738. xs *boost = msg_admiration(&relay, object, "Announce");
  2739. enqueue_message(&relay, boost);
  2740. }
  2741. }
  2742. user_free(&relay);
  2743. }
  2744. }
  2745. }
  2746. else
  2747. if (strcmp(type, "input") == 0) {
  2748. /* process the message */
  2749. const xs_dict *msg = xs_dict_get(q_item, "message");
  2750. const xs_dict *req = xs_dict_get(q_item, "req");
  2751. int retries = xs_number_get(xs_dict_get(q_item, "retries"));
  2752. if (xs_is_null(msg))
  2753. return;
  2754. if (!process_input_message(user, msg, req)) {
  2755. if (retries > queue_retry_max)
  2756. snac_log(user, xs_fmt("input giving up"));
  2757. else {
  2758. /* reenqueue */
  2759. enqueue_input(user, msg, req, retries + 1);
  2760. snac_log(user, xs_fmt("input requeue #%d", retries + 1));
  2761. }
  2762. }
  2763. }
  2764. else
  2765. if (strcmp(type, "close_question") == 0) {
  2766. /* the time for this question has ended */
  2767. const char *id = xs_dict_get(q_item, "message");
  2768. if (!xs_is_null(id))
  2769. update_question(user, id);
  2770. }
  2771. else
  2772. if (strcmp(type, "object_request") == 0) {
  2773. const char *id = xs_dict_get(q_item, "message");
  2774. if (!xs_is_null(id)) {
  2775. int status;
  2776. xs *data = NULL;
  2777. status = activitypub_request(user, id, &data);
  2778. if (valid_status(status))
  2779. object_add_ow(id, data);
  2780. snac_debug(user, 1, xs_fmt("object_request %s %d", id, status));
  2781. }
  2782. }
  2783. else
  2784. if (strcmp(type, "verify_links") == 0) {
  2785. verify_links(user);
  2786. }
  2787. else
  2788. if (strcmp(type, "actor_refresh") == 0) {
  2789. const char *actor = xs_dict_get(q_item, "actor");
  2790. double mtime = object_mtime(actor);
  2791. if (actor_failure(actor, OP_CHECK) == -1) {
  2792. /* actor is broken beyond repair */
  2793. snac_debug(user, 1, xs_fmt("actor_refresh skipped broken actor %s", actor));
  2794. }
  2795. else
  2796. /* only refresh if it was refreshed more than an hour ago */
  2797. if (mtime + 3600.0 < (double) time(NULL)) {
  2798. xs *actor_o = NULL;
  2799. int status;
  2800. if (valid_status((status = activitypub_request(user, actor, &actor_o)))) {
  2801. /* refresh collection counts with throttling to prevent resource exhaustion */
  2802. actor_o = actor_get_collections(user, actor_o, 1);
  2803. actor_add(actor, actor_o);
  2804. /* mark actor and instance as working */
  2805. actor_failure(actor, OP_DEL);
  2806. instance_failure(actor, OP_DEL);
  2807. }
  2808. else {
  2809. if (status == HTTP_STATUS_GONE || status == HTTP_STATUS_NOT_FOUND) {
  2810. actor_failure(actor, OP_ADD);
  2811. snac_log(user, xs_fmt("actor_refresh marking actor %s as broken %d", actor, status));
  2812. }
  2813. else {
  2814. actor_failure(actor, OP_DEL);
  2815. object_touch(actor);
  2816. }
  2817. }
  2818. snac_log(user, xs_fmt("actor_refresh %s %d", actor, status));
  2819. }
  2820. }
  2821. else
  2822. if (strcmp(type, "notify_webhook") == 0) {
  2823. const char *webhook = xs_dict_get(user->config, "notify_webhook");
  2824. if (xs_is_string(webhook) && xs_match(webhook, "https://*|http://*")) { /** **/
  2825. const xs_dict *msg = xs_dict_get(q_item, "message");
  2826. int retries = xs_number_get(xs_dict_get(q_item, "retries"));
  2827. xs *hdrs = xs_dict_new();
  2828. hdrs = xs_dict_set(hdrs, "content-type", "application/json");
  2829. hdrs = xs_dict_set(hdrs, "user-agent", USER_AGENT);
  2830. xs *body = xs_json_dumps(msg, 4);
  2831. int status;
  2832. xs *rsp = xs_http_request("POST", webhook, hdrs, body, strlen(body), &status, NULL, NULL, 0);
  2833. snac_debug(user, 0, xs_fmt("webhook post %s %d", webhook, status));
  2834. if (!valid_status(status)) {
  2835. retries++;
  2836. if (retries > queue_retry_max)
  2837. snac_debug(user, 0, xs_fmt("webhook post giving up %s", webhook));
  2838. else {
  2839. snac_debug(user, 0, xs_fmt("webhook post requeue %s %d", webhook, retries));
  2840. enqueue_notify_webhook(user, msg, retries);
  2841. }
  2842. }
  2843. }
  2844. }
  2845. else
  2846. if (strcmp(type, "collect_replies") == 0) {
  2847. const char *post = xs_dict_get(q_item, "message");
  2848. collect_replies(user, post);
  2849. }
  2850. else
  2851. if (strcmp(type, "collect_outbox") == 0) {
  2852. const char *actor_id = xs_dict_get(q_item, "message");
  2853. collect_outbox(user, actor_id);
  2854. }
  2855. else
  2856. snac_log(user, xs_fmt("unexpected user q_item type '%s'", type));
  2857. }
  2858. int process_user_queue(snac *snac)
  2859. /* processes a user's queue */
  2860. {
  2861. int cnt = 0;
  2862. xs *list = user_queue(snac);
  2863. xs_list *p = list;
  2864. const xs_str *fn;
  2865. while (xs_list_iter(&p, &fn)) {
  2866. xs *q_item = dequeue(fn);
  2867. if (q_item == NULL)
  2868. continue;
  2869. process_user_queue_item(snac, q_item);
  2870. cnt++;
  2871. }
  2872. scheduled_process(snac);
  2873. return cnt;
  2874. }
  2875. xs_str *str_status(int status)
  2876. {
  2877. return xs_fmt("%d %s", status, status < 0 ? xs_curl_strerr(status) : xs_http_status_text(status));
  2878. }
  2879. void process_queue_item(xs_dict *q_item)
  2880. /* processes an item from the global queue */
  2881. {
  2882. const char *type = xs_dict_get(q_item, "type");
  2883. int queue_retry_max = xs_number_get(xs_dict_get(srv_config, "queue_retry_max"));
  2884. if (strcmp(type, "output") == 0) {
  2885. int status;
  2886. const xs_str *inbox = xs_dict_get(q_item, "inbox");
  2887. const xs_str *keyid = xs_dict_get(q_item, "keyid");
  2888. const xs_str *seckey = xs_dict_get(q_item, "seckey");
  2889. const xs_dict *msg = xs_dict_get(q_item, "message");
  2890. int retries = xs_number_get(xs_dict_get(q_item, "retries"));
  2891. int p_status = xs_number_get(xs_dict_get(q_item, "p_status"));
  2892. xs *payload = NULL;
  2893. int p_size = 0;
  2894. int timeout = 0;
  2895. if (xs_is_null(inbox) || xs_is_null(msg) || xs_is_null(keyid) || xs_is_null(seckey)) {
  2896. srv_log(xs_fmt("output message error: missing fields"));
  2897. return;
  2898. }
  2899. if (is_instance_blocked(inbox)) {
  2900. srv_debug(0, xs_fmt("discarded output message to blocked instance %s", inbox));
  2901. return;
  2902. }
  2903. if (instance_failure(inbox, OP_CHECK)) {
  2904. srv_debug(1, xs_fmt("output message error: too many failures for instance %s", inbox));
  2905. return;
  2906. }
  2907. /* deliver (if previous error status was a timeout, try now longer) */
  2908. if (p_status == 599)
  2909. timeout = xs_number_get(xs_dict_get_def(srv_config, "queue_timeout_2", "8"));
  2910. else
  2911. timeout = xs_number_get(xs_dict_get_def(srv_config, "queue_timeout", "6"));
  2912. if (timeout == 0)
  2913. timeout = 6;
  2914. status = send_to_inbox_raw(keyid, seckey, inbox, msg, &payload, &p_size, timeout);
  2915. /* register or clear a value for this instance */
  2916. instance_failure(inbox, valid_status(status) ? OP_DEL : OP_ADD);
  2917. if (payload) {
  2918. if (p_size > 1024) {
  2919. /* trim the message */
  2920. payload = xs_utf8_crop_i(payload, 0, 1024);
  2921. payload = xs_str_cat(payload, "...");
  2922. }
  2923. /* strip ugly control characters */
  2924. payload = xs_replace_i(payload, "\n", "");
  2925. payload = xs_replace_i(payload, "\r", "");
  2926. if (*payload)
  2927. payload = xs_str_wrap_i(" [", payload, "]");
  2928. }
  2929. else
  2930. payload = xs_str_new(NULL);
  2931. xs *s_status = str_status(status);
  2932. srv_log(xs_fmt("output message: sent to inbox %s (%s)%s", inbox, s_status, payload));
  2933. if (!valid_status(status)) {
  2934. retries++;
  2935. /* if it's not the first time it fails with a timeout,
  2936. penalize the server by skipping one retry */
  2937. if (p_status == status && status == HTTP_STATUS_CLIENT_CLOSED_REQUEST)
  2938. retries++;
  2939. /* error sending; requeue? */
  2940. if (status == HTTP_STATUS_BAD_REQUEST
  2941. || status == HTTP_STATUS_NOT_FOUND
  2942. || status == HTTP_STATUS_METHOD_NOT_ALLOWED
  2943. || status == HTTP_STATUS_GONE
  2944. || status == HTTP_STATUS_UNPROCESSABLE_CONTENT
  2945. || status < 0)
  2946. /* explicit error: discard */
  2947. srv_log(xs_fmt("output message: error %s (%s)", inbox, s_status));
  2948. else
  2949. if (retries > queue_retry_max)
  2950. srv_log(xs_fmt("output message: giving up %s (%s)", inbox, s_status));
  2951. else {
  2952. /* requeue */
  2953. enqueue_output_raw(keyid, seckey, msg, inbox, retries, status);
  2954. srv_log(xs_fmt("output message: requeue %s #%d", inbox, retries));
  2955. }
  2956. }
  2957. }
  2958. else
  2959. if (strcmp(type, "email") == 0) {
  2960. /* send this email */
  2961. const xs_dict *msg = xs_dict_get(q_item, "message");
  2962. int retries = xs_number_get(xs_dict_get(q_item, "retries"));
  2963. if (!send_email(msg))
  2964. srv_debug(1, xs_fmt("email message sent"));
  2965. else {
  2966. retries++;
  2967. if (retries > queue_retry_max)
  2968. srv_log(xs_fmt("email giving up (errno: %d)", errno));
  2969. else {
  2970. /* requeue */
  2971. srv_log(xs_fmt(
  2972. "email requeue #%d (errno: %d)", retries, errno));
  2973. enqueue_email(msg, retries);
  2974. }
  2975. }
  2976. }
  2977. else
  2978. if (strcmp(type, "telegram") == 0) {
  2979. /* send this via telegram */
  2980. const char *bot = xs_dict_get(q_item, "bot");
  2981. const char *msg = xs_dict_get(q_item, "message");
  2982. xs *chat_id = xs_dup(xs_dict_get(q_item, "chat_id"));
  2983. int status = 0;
  2984. /* chat_id must start with a - */
  2985. if (!xs_startswith(chat_id, "-"))
  2986. chat_id = xs_str_wrap_i("-", chat_id, NULL);
  2987. xs *url = xs_fmt("https:/" "/api.telegram.org/bot%s/sendMessage", bot);
  2988. xs *body = xs_fmt("{\"chat_id\":%s,\"text\":\"%s\"}", chat_id, msg);
  2989. xs *headers = xs_dict_new();
  2990. headers = xs_dict_append(headers, "content-type", "application/json");
  2991. xs *rsp = xs_http_request("POST", url, headers,
  2992. body, strlen(body), &status, NULL, NULL, 0);
  2993. rsp = xs_free(rsp);
  2994. srv_debug(0, xs_fmt("telegram post %d", status));
  2995. }
  2996. else
  2997. if (strcmp(type, "ntfy") == 0) {
  2998. /* send this via ntfy */
  2999. const char *ntfy_server = xs_dict_get(q_item, "ntfy_server");
  3000. const char *msg = xs_dict_get(q_item, "message");
  3001. const char *ntfy_token = xs_dict_get(q_item, "ntfy_token");
  3002. int status = 0;
  3003. xs *url = xs_fmt("%s", ntfy_server);
  3004. xs *body = xs_fmt("%s", msg);
  3005. xs *headers = xs_dict_new();
  3006. headers = xs_dict_append(headers, "content-type", "text/plain");
  3007. // Append the Authorization header only if ntfy_token is not NULL
  3008. if (ntfy_token != NULL) {
  3009. headers = xs_dict_append(headers, "Authorization", xs_fmt("Bearer %s", ntfy_token));
  3010. }
  3011. xs *rsp = xs_http_request("POST", url, headers,
  3012. body, strlen(body), &status, NULL, NULL, 0);
  3013. rsp = xs_free(rsp);
  3014. srv_debug(0, xs_fmt("ntfy post %d", status));
  3015. }
  3016. else
  3017. if (strcmp(type, "purge") == 0) {
  3018. srv_log(xs_dup("purge start"));
  3019. purge_all();
  3020. srv_log(xs_dup("purge end"));
  3021. }
  3022. else
  3023. if (strcmp(type, "input") == 0) {
  3024. const xs_dict *msg = xs_dict_get(q_item, "message");
  3025. const xs_dict *req = xs_dict_get(q_item, "req");
  3026. int retries = xs_number_get(xs_dict_get(q_item, "retries"));
  3027. /* do some instance-level checks */
  3028. int r = process_input_message(NULL, msg, req);
  3029. if (r == 0) {
  3030. /* transient error? retry */
  3031. if (retries > queue_retry_max)
  3032. srv_log(xs_fmt("shared input giving up"));
  3033. else {
  3034. /* reenqueue */
  3035. enqueue_shared_input(msg, req, retries + 1);
  3036. srv_log(xs_fmt("shared input requeue #%d", retries + 1));
  3037. }
  3038. }
  3039. else
  3040. if (r == 2) {
  3041. /* redistribute the input message to all users */
  3042. const char *ntid = xs_dict_get(q_item, "ntid");
  3043. xs *tmpfn = xs_fmt("%s/tmp/%s.json", srv_basedir, ntid);
  3044. FILE *f;
  3045. if ((f = fopen(tmpfn, "w")) != NULL) {
  3046. xs_json_dump(q_item, 4, f);
  3047. fclose(f);
  3048. }
  3049. xs *users = user_list();
  3050. xs_list *p = users;
  3051. const char *v;
  3052. int cnt = 0;
  3053. while (xs_list_iter(&p, &v)) {
  3054. snac user;
  3055. if (user_open(&user, v)) {
  3056. int rsn = is_msg_for_me(&user, msg);
  3057. if (rsn) {
  3058. xs *fn = xs_fmt("%s/queue/%s.json", user.basedir, ntid);
  3059. snac_debug(&user, 1,
  3060. xs_fmt("enqueue_input (from shared inbox) %s [%d]", xs_dict_get(msg, "id"), rsn));
  3061. if (link(tmpfn, fn) < 0)
  3062. srv_log(xs_fmt("link(%s, %s) error", tmpfn, fn));
  3063. cnt++;
  3064. }
  3065. user_free(&user);
  3066. }
  3067. }
  3068. unlink(tmpfn);
  3069. if (cnt == 0) {
  3070. srv_debug(1, xs_fmt("no valid recipients for %s", xs_dict_get(msg, "id")));
  3071. }
  3072. }
  3073. }
  3074. else
  3075. if (strcmp(type, "webmention") == 0) {
  3076. const xs_dict *msg = xs_dict_get(q_item, "message");
  3077. const char *source = xs_dict_get(msg, "id");
  3078. const char *content = xs_dict_get(msg, "content");
  3079. if (xs_is_string(source) && xs_is_string(content)) {
  3080. xs *links = xs_regex_select(content, "\"https?:/" "/[^\"]+");
  3081. const char *link;
  3082. xs_list_foreach(links, link) {
  3083. xs *target = xs_strip_chars_i(xs_dup(link), "\"");
  3084. int r = xs_webmention_send(source, target, USER_AGENT);
  3085. srv_debug(1, xs_fmt("webmention source=%s target=%s %d", source, target, r));
  3086. }
  3087. }
  3088. }
  3089. else
  3090. if (strcmp(type, "rss_hashtag_poll") == 0) {
  3091. rss_poll_hashtags();
  3092. }
  3093. else
  3094. if (strcmp(type, "fsck") == 0) {
  3095. srv_log(xs_fmt("started deferred data integrity check"));
  3096. data_fsck();
  3097. srv_log(xs_fmt("finished deferred data integrity check"));
  3098. }
  3099. else
  3100. srv_log(xs_fmt("unexpected q_item type '%s'", type));
  3101. }
  3102. int process_queue(void)
  3103. /* processes the global queue */
  3104. {
  3105. int cnt = 0;
  3106. xs *list = queue();
  3107. xs_list *p = list;
  3108. const xs_str *fn;
  3109. while (xs_list_iter(&p, &fn)) {
  3110. xs *q_item = dequeue(fn);
  3111. if (q_item != NULL) {
  3112. job_post(q_item, 0);
  3113. cnt++;
  3114. }
  3115. }
  3116. return cnt;
  3117. }
  3118. /** account migration **/
  3119. int migrate_account(snac *user)
  3120. /* migrates this account to a new one (stored in the 'alias' user field) */
  3121. {
  3122. const char *new_account = xs_dict_get(user->config, "alias");
  3123. if (xs_type(new_account) != XSTYPE_STRING) {
  3124. snac_log(user, xs_fmt("Cannot migrate: alias (destination account) not set"));
  3125. return 1;
  3126. }
  3127. xs *new_actor = NULL;
  3128. int status;
  3129. if (!valid_status(status = activitypub_request(user, new_account, &new_actor))) {
  3130. snac_log(user, xs_fmt("Cannot migrate: error requesting actor %s %d", new_account, status));
  3131. return 1;
  3132. }
  3133. actor_add(new_account, new_actor);
  3134. const char *loaka = xs_dict_get(new_actor, "alsoKnownAs");
  3135. if (xs_type(loaka) != XSTYPE_LIST) {
  3136. snac_log(user, xs_fmt("Cannot migrate: destination account doesn't have any aliases"));
  3137. return 1;
  3138. }
  3139. if (xs_list_in(loaka, user->actor) == -1) {
  3140. snac_log(user, xs_fmt("Cannot migrate: destination account doesn't have this one as an alias"));
  3141. return 1;
  3142. }
  3143. xs *move = msg_move(user, new_account);
  3144. xs *fwers = follower_list(user);
  3145. const char *actor;
  3146. xs_list_foreach(fwers, actor) {
  3147. /* get the actor inbox, excluding the shared one */
  3148. xs *inbox = get_actor_inbox(actor, 0);
  3149. if (xs_is_null(inbox))
  3150. snac_log(user, xs_fmt("migrate_account: cannot get inbox for actor %s", actor));
  3151. else
  3152. enqueue_output(user, move, inbox, 0, 0);
  3153. }
  3154. return 0;
  3155. }
  3156. /** HTTP handlers */
  3157. int activitypub_get_handler(const xs_dict *req, const char *q_path,
  3158. char **body, int *b_size, char **ctype)
  3159. {
  3160. int status = HTTP_STATUS_OK;
  3161. const char *accept = xs_dict_get(req, "accept");
  3162. snac snac;
  3163. xs *msg = NULL;
  3164. if (accept == NULL)
  3165. return 0;
  3166. if (xs_str_in(accept, "application/activity+json") == -1 &&
  3167. xs_str_in(accept, "application/ld+json") == -1)
  3168. return 0;
  3169. xs *l = xs_split_n(q_path, "/", 2);
  3170. if (xs_list_len(l) <= 1) {
  3171. srv_debug(1, xs_fmt("activitypub_get_handler bad path %s", q_path));
  3172. return HTTP_STATUS_BAD_REQUEST;
  3173. }
  3174. const char *uid;
  3175. const char *p_path;
  3176. uid = xs_list_get(l, 1);
  3177. if (!user_open(&snac, uid)) {
  3178. /* invalid user */
  3179. status = grave(uid, OP_CHECK) ? HTTP_STATUS_GONE : HTTP_STATUS_NOT_FOUND;
  3180. srv_debug(1, xs_fmt("activitypub_get_handler bad user %s %d", uid, status));
  3181. return status;
  3182. }
  3183. p_path = xs_list_get(l, 2);
  3184. const xs_dict *q_vars = xs_dict_get(req, "q_vars");
  3185. *ctype = "application/activity+json";
  3186. int show_contact_metrics = xs_is_true(xs_dict_get(snac.config, "show_contact_metrics"));
  3187. if (p_path == NULL) {
  3188. /* if there was no component after the user, it's an actor request */
  3189. msg = msg_actor(&snac);
  3190. *ctype = "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"";
  3191. const char *ua = xs_dict_get(req, "user-agent");
  3192. snac_debug(&snac, 0, xs_fmt("serving actor [%s]", ua ? ua : "No UA"));
  3193. }
  3194. else
  3195. if (strcmp(p_path, "outbox") == 0 || strcmp(p_path, "featured") == 0) {
  3196. xs *id = xs_fmt("%s/%s", snac.actor, p_path);
  3197. xs *list = xs_list_new();
  3198. const char *v;
  3199. int cnt = xs_number_get(xs_dict_get_def(srv_config, "max_public_entries", "20"));
  3200. /* get the public outbox or the pinned list */
  3201. xs *elems = *p_path == 'o' ? timeline_simple_list(&snac, "public", 0, cnt, NULL) : pinned_list(&snac);
  3202. xs_list_foreach(elems, v) {
  3203. xs *i = NULL;
  3204. if (valid_status(object_get_by_md5(v, &i))) {
  3205. const char *type = xs_dict_get(i, "type");
  3206. const char *id = xs_dict_get(i, "id");
  3207. if (type && id && strcmp(type, "Note") == 0 && is_msg_mine(&snac, id)) {
  3208. if (is_msg_public(i)) {
  3209. xs *c_msg = msg_create(&snac, i);
  3210. list = xs_list_append(list, c_msg);
  3211. }
  3212. }
  3213. }
  3214. }
  3215. /* replace the 'orderedItems' with the latest posts */
  3216. msg = msg_collection(&snac, id, xs_list_len(list));
  3217. msg = xs_dict_set(msg, "orderedItems", list);
  3218. }
  3219. else
  3220. if (strcmp(p_path, "followers") == 0) {
  3221. int total = 0;
  3222. if (show_contact_metrics) {
  3223. total = follower_list_len(&snac);
  3224. }
  3225. xs *id = xs_fmt("%s/%s", snac.actor, p_path);
  3226. msg = msg_collection(&snac, id, total);
  3227. }
  3228. else
  3229. if (strcmp(p_path, "following") == 0) {
  3230. int total = 0;
  3231. if (show_contact_metrics) {
  3232. total = following_list_len(&snac);
  3233. }
  3234. xs *id = xs_fmt("%s/%s", snac.actor, p_path);
  3235. msg = msg_collection(&snac, id, total);
  3236. }
  3237. else
  3238. if (xs_startswith(p_path, "p/")) {
  3239. xs *id = xs_fmt("%s/%s", snac.actor, p_path);
  3240. status = object_get(id, &msg);
  3241. /* don't return non-public objects */
  3242. if (valid_status(status) && !is_msg_public(msg))
  3243. status = HTTP_STATUS_NOT_FOUND;
  3244. }
  3245. else
  3246. if (xs_startswith(p_path, "r/")) {
  3247. /* replies to a post */
  3248. xs *s = xs_dup(p_path);
  3249. s[0] = 'p';
  3250. xs *id = xs_fmt("%s/%s", snac.actor, s);
  3251. xs *obj = NULL;
  3252. status = object_get(id, &obj);
  3253. /* don't return non-public objects */
  3254. if (!valid_status(status))
  3255. status = HTTP_STATUS_NOT_FOUND;
  3256. else
  3257. if (!is_msg_public(obj))
  3258. status = HTTP_STATUS_NOT_FOUND;
  3259. else
  3260. if (xs_dict_get(q_vars, "page"))
  3261. msg = msg_replies(&snac, id, 1);
  3262. else {
  3263. const xs_dict *replies = xs_dict_get(obj, "replies");
  3264. if (xs_is_dict(replies)) {
  3265. msg = xs_dup(replies);
  3266. msg = xs_dict_set(msg, "@context", "https:/""/www.w3.org/ns/activitystreams");
  3267. }
  3268. }
  3269. }
  3270. else
  3271. status = HTTP_STATUS_NOT_FOUND;
  3272. if (status == HTTP_STATUS_OK && msg != NULL) {
  3273. *body = xs_json_dumps(msg, 4);
  3274. *b_size = strlen(*body);
  3275. }
  3276. snac_debug(&snac, 1, xs_fmt("activitypub_get_handler serving %s %d", q_path, status));
  3277. user_free(&snac);
  3278. return status;
  3279. }
  3280. int activitypub_post_handler(const xs_dict *req, const char *q_path,
  3281. char *payload, int p_size,
  3282. char **body, int *b_size, char **ctype)
  3283. /* processes an input message */
  3284. {
  3285. (void)b_size;
  3286. int status = HTTP_STATUS_ACCEPTED;
  3287. const char *i_ctype = xs_dict_get(req, "content-type");
  3288. snac snac;
  3289. const char *v;
  3290. if (i_ctype == NULL) {
  3291. *body = xs_str_new("no content-type");
  3292. *ctype = "text/plain";
  3293. return HTTP_STATUS_BAD_REQUEST;
  3294. }
  3295. if (xs_is_null(payload)) {
  3296. *body = xs_str_new("no payload");
  3297. *ctype = "text/plain";
  3298. return HTTP_STATUS_BAD_REQUEST;
  3299. }
  3300. if (xs_str_in(i_ctype, "application/activity+json") == -1 &&
  3301. xs_str_in(i_ctype, "application/ld+json") == -1)
  3302. return 0;
  3303. if (p_size >= 100000) {
  3304. *body = xs_str_new("too big");
  3305. *ctype = "text/plain";
  3306. return HTTP_STATUS_BAD_REQUEST;
  3307. }
  3308. /* decode the message */
  3309. xs *msg = xs_json_loads(payload);
  3310. const char *id = xs_dict_get(msg, "id");
  3311. if (msg == NULL) {
  3312. srv_log(xs_fmt("activitypub_post_handler JSON error %s", q_path));
  3313. srv_archive_error("activitypub_post_handler", "JSON error", req, payload);
  3314. *body = xs_str_new("JSON error");
  3315. *ctype = "text/plain";
  3316. return HTTP_STATUS_BAD_REQUEST;
  3317. }
  3318. if (id && is_instance_blocked(id)) {
  3319. srv_debug(1, xs_fmt("full instance block for %s", id));
  3320. *body = xs_str_new("blocked");
  3321. *ctype = "text/plain";
  3322. return HTTP_STATUS_FORBIDDEN;
  3323. }
  3324. /* get the user and path */
  3325. xs *l = xs_split_n(q_path, "/", 2);
  3326. if (xs_list_len(l) <= 1) {
  3327. srv_debug(1, xs_fmt("activitypub_post_handler bad path %s", q_path));
  3328. return HTTP_STATUS_BAD_REQUEST;
  3329. }
  3330. if (xs_list_len(l) == 2 && strcmp(xs_list_get(l, 1), "shared-inbox") == 0) {
  3331. enqueue_shared_input(msg, req, 0);
  3332. return HTTP_STATUS_ACCEPTED;
  3333. }
  3334. if (xs_list_len(l) != 3 || strcmp(xs_list_get(l, 2), "inbox") != 0) {
  3335. /* strange q_path */
  3336. srv_debug(1, xs_fmt("activitypub_post_handler unsupported path %s", q_path));
  3337. return HTTP_STATUS_NOT_FOUND;
  3338. }
  3339. const char *uid = xs_list_get(l, 1);
  3340. if (!user_open(&snac, uid)) {
  3341. /* invalid user */
  3342. status = grave(uid, OP_CHECK) ? HTTP_STATUS_GONE : HTTP_STATUS_NOT_FOUND;
  3343. srv_debug(1, xs_fmt("activitypub_post_handler bad user %s %d", uid, status));
  3344. return status;
  3345. }
  3346. /* if it has a digest, check it now, because
  3347. later the payload won't be exactly the same */
  3348. if ((v = xs_dict_get(req, "digest")) != NULL) {
  3349. xs *s1 = xs_sha256_base64(payload, p_size);
  3350. xs *s2 = xs_fmt("SHA-256=%s", s1);
  3351. if (strcmp(s2, v) != 0) {
  3352. srv_log(xs_fmt("digest check FAILED"));
  3353. *body = xs_str_new("bad digest");
  3354. *ctype = "text/plain";
  3355. status = HTTP_STATUS_BAD_REQUEST;
  3356. }
  3357. }
  3358. /* if the message is from a muted actor, reject it right now */
  3359. if (!xs_is_null(v = xs_dict_get(msg, "actor")) && *v) {
  3360. if (is_muted(&snac, v)) {
  3361. snac_log(&snac, xs_fmt("rejected message from MUTEd actor %s", v));
  3362. *body = xs_str_new("rejected");
  3363. *ctype = "text/plain";
  3364. status = HTTP_STATUS_FORBIDDEN;
  3365. }
  3366. }
  3367. if (valid_status(status)) {
  3368. enqueue_input(&snac, msg, req, 0);
  3369. *ctype = "application/activity+json";
  3370. }
  3371. user_free(&snac);
  3372. return status;
  3373. }