activitypub.c 132 KB

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