activitypub.c 127 KB

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