activitypub.c 134 KB

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