activitypub.c 128 KB

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