1
0

activitypub.c 130 KB

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