activitypub.c 129 KB

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