control.c 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file control.c
  6. * \brief Implementation for Tor's control-socket interface.
  7. * See doc/spec/control-spec.txt for full details on protocol.
  8. **/
  9. #define CONTROL_PRIVATE
  10. #include "or.h"
  11. #include "addressmap.h"
  12. #include "buffers.h"
  13. #include "channel.h"
  14. #include "channeltls.h"
  15. #include "circuitbuild.h"
  16. #include "circuitlist.h"
  17. #include "circuitstats.h"
  18. #include "circuituse.h"
  19. #include "config.h"
  20. #include "confparse.h"
  21. #include "connection.h"
  22. #include "connection_edge.h"
  23. #include "connection_or.h"
  24. #include "control.h"
  25. #include "directory.h"
  26. #include "dirserv.h"
  27. #include "dnsserv.h"
  28. #include "entrynodes.h"
  29. #include "geoip.h"
  30. #include "hibernate.h"
  31. #include "main.h"
  32. #include "networkstatus.h"
  33. #include "nodelist.h"
  34. #include "policies.h"
  35. #include "reasons.h"
  36. #include "rephist.h"
  37. #include "router.h"
  38. #include "routerlist.h"
  39. #include "routerparse.h"
  40. #ifndef _WIN32
  41. #include <pwd.h>
  42. #include <sys/resource.h>
  43. #endif
  44. #include "procmon.h"
  45. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  46. * finished authentication and is accepting commands. */
  47. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  48. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  49. * connection is interested in events of type <b>e</b>. We use this
  50. * so that we can decide to skip generating event messages that nobody
  51. * has interest in without having to walk over the global connection
  52. * list to find out.
  53. **/
  54. typedef uint64_t event_mask_t;
  55. /** An event mask of all the events that any controller is interested in
  56. * receiving. */
  57. static event_mask_t global_event_mask = 0;
  58. /** True iff we have disabled log messages from being sent to the controller */
  59. static int disable_log_messages = 0;
  60. /** Macro: true if any control connection is interested in events of type
  61. * <b>e</b>. */
  62. #define EVENT_IS_INTERESTING(e) \
  63. (!! (global_event_mask & (((uint64_t)1)<<(e))))
  64. /** If we're using cookie-type authentication, how long should our cookies be?
  65. */
  66. #define AUTHENTICATION_COOKIE_LEN 32
  67. /** If true, we've set authentication_cookie to a secret code and
  68. * stored it to disk. */
  69. static int authentication_cookie_is_set = 0;
  70. /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
  71. * and which we're using to authenticate controllers. (If the controller can
  72. * read it off disk, it has permission to connect.) */
  73. static uint8_t *authentication_cookie = NULL;
  74. #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
  75. "Tor safe cookie authentication server-to-controller hash"
  76. #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
  77. "Tor safe cookie authentication controller-to-server hash"
  78. #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
  79. /** A sufficiently large size to record the last bootstrap phase string. */
  80. #define BOOTSTRAP_MSG_LEN 1024
  81. /** What was the last bootstrap phase message we sent? We keep track
  82. * of this so we can respond to getinfo status/bootstrap-phase queries. */
  83. static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
  84. static void connection_printf_to_buf(control_connection_t *conn,
  85. const char *format, ...)
  86. CHECK_PRINTF(2,3);
  87. static void send_control_event_impl(uint16_t event, event_format_t which,
  88. const char *format, va_list ap)
  89. CHECK_PRINTF(3,0);
  90. static int control_event_status(int type, int severity, const char *format,
  91. va_list args)
  92. CHECK_PRINTF(3,0);
  93. static void send_control_done(control_connection_t *conn);
  94. static void send_control_event(uint16_t event, event_format_t which,
  95. const char *format, ...)
  96. CHECK_PRINTF(3,4);
  97. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  98. char *body);
  99. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  100. char *body);
  101. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  102. const char *body);
  103. static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
  104. const char *body);
  105. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  106. const char *body);
  107. static int handle_control_authenticate(control_connection_t *conn,
  108. uint32_t len,
  109. const char *body);
  110. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  111. const char *body);
  112. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  113. const char *body);
  114. static char *list_getinfo_options(void);
  115. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  116. const char *body);
  117. static int handle_control_extendcircuit(control_connection_t *conn,
  118. uint32_t len,
  119. const char *body);
  120. static int handle_control_setcircuitpurpose(control_connection_t *conn,
  121. uint32_t len, const char *body);
  122. static int handle_control_attachstream(control_connection_t *conn,
  123. uint32_t len,
  124. const char *body);
  125. static int handle_control_postdescriptor(control_connection_t *conn,
  126. uint32_t len,
  127. const char *body);
  128. static int handle_control_redirectstream(control_connection_t *conn,
  129. uint32_t len,
  130. const char *body);
  131. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  132. const char *body);
  133. static int handle_control_closecircuit(control_connection_t *conn,
  134. uint32_t len,
  135. const char *body);
  136. static int handle_control_resolve(control_connection_t *conn, uint32_t len,
  137. const char *body);
  138. static int handle_control_usefeature(control_connection_t *conn,
  139. uint32_t len,
  140. const char *body);
  141. static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
  142. size_t len);
  143. static void orconn_target_get_name(char *buf, size_t len,
  144. or_connection_t *conn);
  145. static char *get_cookie_file(void);
  146. /** Given a control event code for a message event, return the corresponding
  147. * log severity. */
  148. static INLINE int
  149. event_to_log_severity(int event)
  150. {
  151. switch (event) {
  152. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  153. case EVENT_INFO_MSG: return LOG_INFO;
  154. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  155. case EVENT_WARN_MSG: return LOG_WARN;
  156. case EVENT_ERR_MSG: return LOG_ERR;
  157. default: return -1;
  158. }
  159. }
  160. /** Given a log severity, return the corresponding control event code. */
  161. static INLINE int
  162. log_severity_to_event(int severity)
  163. {
  164. switch (severity) {
  165. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  166. case LOG_INFO: return EVENT_INFO_MSG;
  167. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  168. case LOG_WARN: return EVENT_WARN_MSG;
  169. case LOG_ERR: return EVENT_ERR_MSG;
  170. default: return -1;
  171. }
  172. }
  173. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  174. * connection's event_mask field. */
  175. void
  176. control_update_global_event_mask(void)
  177. {
  178. smartlist_t *conns = get_connection_array();
  179. event_mask_t old_mask, new_mask;
  180. old_mask = global_event_mask;
  181. global_event_mask = 0;
  182. SMARTLIST_FOREACH(conns, connection_t *, _conn,
  183. {
  184. if (_conn->type == CONN_TYPE_CONTROL &&
  185. STATE_IS_OPEN(_conn->state)) {
  186. control_connection_t *conn = TO_CONTROL_CONN(_conn);
  187. global_event_mask |= conn->event_mask;
  188. }
  189. });
  190. new_mask = global_event_mask;
  191. /* Handle the aftermath. Set up the log callback to tell us only what
  192. * we want to hear...*/
  193. control_adjust_event_log_severity();
  194. /* ...then, if we've started logging stream bw, clear the appropriate
  195. * fields. */
  196. if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
  197. (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
  198. SMARTLIST_FOREACH(conns, connection_t *, conn,
  199. {
  200. if (conn->type == CONN_TYPE_AP) {
  201. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  202. edge_conn->n_written = edge_conn->n_read = 0;
  203. }
  204. });
  205. }
  206. }
  207. /** Adjust the log severities that result in control_event_logmsg being called
  208. * to match the severity of log messages that any controllers are interested
  209. * in. */
  210. void
  211. control_adjust_event_log_severity(void)
  212. {
  213. int i;
  214. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  215. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  216. if (EVENT_IS_INTERESTING(i)) {
  217. min_log_event = i;
  218. break;
  219. }
  220. }
  221. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  222. if (EVENT_IS_INTERESTING(i)) {
  223. max_log_event = i;
  224. break;
  225. }
  226. }
  227. if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  228. if (min_log_event > EVENT_NOTICE_MSG)
  229. min_log_event = EVENT_NOTICE_MSG;
  230. if (max_log_event < EVENT_ERR_MSG)
  231. max_log_event = EVENT_ERR_MSG;
  232. }
  233. if (min_log_event <= max_log_event)
  234. change_callback_log_severity(event_to_log_severity(min_log_event),
  235. event_to_log_severity(max_log_event),
  236. control_event_logmsg);
  237. else
  238. change_callback_log_severity(LOG_ERR, LOG_ERR,
  239. control_event_logmsg);
  240. }
  241. /** Return true iff the event with code <b>c</b> is being sent to any current
  242. * control connection. This is useful if the amount of work needed to prepare
  243. * to call the appropriate control_event_...() function is high.
  244. */
  245. int
  246. control_event_is_interesting(int event)
  247. {
  248. return EVENT_IS_INTERESTING(event);
  249. }
  250. /** Append a NUL-terminated string <b>s</b> to the end of
  251. * <b>conn</b>-\>outbuf.
  252. */
  253. static INLINE void
  254. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  255. {
  256. size_t len = strlen(s);
  257. connection_write_to_buf(s, len, TO_CONN(conn));
  258. }
  259. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  260. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
  261. * contents of <b>data</b> into *<b>out</b>, adding a period before any period
  262. * that appears at the start of a line, and adding a period-CRLF line at
  263. * the end. Replace all LF characters sequences with CRLF. Return the number
  264. * of bytes in *<b>out</b>.
  265. */
  266. STATIC size_t
  267. write_escaped_data(const char *data, size_t len, char **out)
  268. {
  269. size_t sz_out = len+8;
  270. char *outp;
  271. const char *start = data, *end;
  272. int i;
  273. int start_of_line;
  274. for (i=0; i<(int)len; ++i) {
  275. if (data[i]== '\n')
  276. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  277. }
  278. *out = outp = tor_malloc(sz_out+1);
  279. end = data+len;
  280. start_of_line = 1;
  281. while (data < end) {
  282. if (*data == '\n') {
  283. if (data > start && data[-1] != '\r')
  284. *outp++ = '\r';
  285. start_of_line = 1;
  286. } else if (*data == '.') {
  287. if (start_of_line) {
  288. start_of_line = 0;
  289. *outp++ = '.';
  290. }
  291. } else {
  292. start_of_line = 0;
  293. }
  294. *outp++ = *data++;
  295. }
  296. if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
  297. *outp++ = '\r';
  298. *outp++ = '\n';
  299. }
  300. *outp++ = '.';
  301. *outp++ = '\r';
  302. *outp++ = '\n';
  303. *outp = '\0'; /* NUL-terminate just in case. */
  304. tor_assert((outp - *out) <= (int)sz_out);
  305. return outp - *out;
  306. }
  307. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  308. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  309. * the contents of <b>data</b> into *<b>out</b>, removing any period
  310. * that appears at the start of a line, and replacing all CRLF sequences
  311. * with LF. Return the number of
  312. * bytes in *<b>out</b>. */
  313. STATIC size_t
  314. read_escaped_data(const char *data, size_t len, char **out)
  315. {
  316. char *outp;
  317. const char *next;
  318. const char *end;
  319. *out = outp = tor_malloc(len+1);
  320. end = data+len;
  321. while (data < end) {
  322. /* we're at the start of a line. */
  323. if (*data == '.')
  324. ++data;
  325. next = memchr(data, '\n', end-data);
  326. if (next) {
  327. size_t n_to_copy = next-data;
  328. /* Don't copy a CR that precedes this LF. */
  329. if (n_to_copy && *(next-1) == '\r')
  330. --n_to_copy;
  331. memcpy(outp, data, n_to_copy);
  332. outp += n_to_copy;
  333. data = next+1; /* This will point at the start of the next line,
  334. * or the end of the string, or a period. */
  335. } else {
  336. memcpy(outp, data, end-data);
  337. outp += (end-data);
  338. *outp = '\0';
  339. return outp - *out;
  340. }
  341. *outp++ = '\n';
  342. }
  343. *outp = '\0';
  344. return outp - *out;
  345. }
  346. /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
  347. * double-quoted string with escaped characters, return the length of that
  348. * string (as encoded, including quotes). Otherwise return -1. */
  349. static INLINE int
  350. get_escaped_string_length(const char *start, size_t in_len_max,
  351. int *chars_out)
  352. {
  353. const char *cp, *end;
  354. int chars = 0;
  355. if (*start != '\"')
  356. return -1;
  357. cp = start+1;
  358. end = start+in_len_max;
  359. /* Calculate length. */
  360. while (1) {
  361. if (cp >= end) {
  362. return -1; /* Too long. */
  363. } else if (*cp == '\\') {
  364. if (++cp == end)
  365. return -1; /* Can't escape EOS. */
  366. ++cp;
  367. ++chars;
  368. } else if (*cp == '\"') {
  369. break;
  370. } else {
  371. ++cp;
  372. ++chars;
  373. }
  374. }
  375. if (chars_out)
  376. *chars_out = chars;
  377. return (int)(cp - start+1);
  378. }
  379. /** As decode_escaped_string, but does not decode the string: copies the
  380. * entire thing, including quotation marks. */
  381. static const char *
  382. extract_escaped_string(const char *start, size_t in_len_max,
  383. char **out, size_t *out_len)
  384. {
  385. int length = get_escaped_string_length(start, in_len_max, NULL);
  386. if (length<0)
  387. return NULL;
  388. *out_len = length;
  389. *out = tor_strndup(start, *out_len);
  390. return start+length;
  391. }
  392. /** Given a pointer to a string starting at <b>start</b> containing
  393. * <b>in_len_max</b> characters, decode a string beginning with one double
  394. * quote, containing any number of non-quote characters or characters escaped
  395. * with a backslash, and ending with a final double quote. Place the resulting
  396. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  397. * store its length in <b>out_len</b>. On success, return a pointer to the
  398. * character immediately following the escaped string. On failure, return
  399. * NULL. */
  400. static const char *
  401. decode_escaped_string(const char *start, size_t in_len_max,
  402. char **out, size_t *out_len)
  403. {
  404. const char *cp, *end;
  405. char *outp;
  406. int len, n_chars = 0;
  407. len = get_escaped_string_length(start, in_len_max, &n_chars);
  408. if (len<0)
  409. return NULL;
  410. end = start+len-1; /* Index of last quote. */
  411. tor_assert(*end == '\"');
  412. outp = *out = tor_malloc(len+1);
  413. *out_len = n_chars;
  414. cp = start+1;
  415. while (cp < end) {
  416. if (*cp == '\\')
  417. ++cp;
  418. *outp++ = *cp++;
  419. }
  420. *outp = '\0';
  421. tor_assert((outp - *out) == (int)*out_len);
  422. return end+1;
  423. }
  424. /** Acts like sprintf, but writes its formatted string to the end of
  425. * <b>conn</b>-\>outbuf. */
  426. static void
  427. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  428. {
  429. va_list ap;
  430. char *buf = NULL;
  431. int len;
  432. va_start(ap,format);
  433. len = tor_vasprintf(&buf, format, ap);
  434. va_end(ap);
  435. if (len < 0) {
  436. log_err(LD_BUG, "Unable to format string for controller.");
  437. tor_assert(0);
  438. }
  439. connection_write_to_buf(buf, (size_t)len, TO_CONN(conn));
  440. tor_free(buf);
  441. }
  442. /** Write all of the open control ports to ControlPortWriteToFile */
  443. void
  444. control_ports_write_to_file(void)
  445. {
  446. smartlist_t *lines;
  447. char *joined = NULL;
  448. const or_options_t *options = get_options();
  449. if (!options->ControlPortWriteToFile)
  450. return;
  451. lines = smartlist_new();
  452. SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
  453. if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
  454. continue;
  455. #ifdef AF_UNIX
  456. if (conn->socket_family == AF_UNIX) {
  457. smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
  458. continue;
  459. }
  460. #endif
  461. smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
  462. } SMARTLIST_FOREACH_END(conn);
  463. joined = smartlist_join_strings(lines, "", 0, NULL);
  464. if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
  465. log_warn(LD_CONTROL, "Writing %s failed: %s",
  466. options->ControlPortWriteToFile, strerror(errno));
  467. }
  468. #ifndef _WIN32
  469. if (options->ControlPortFileGroupReadable) {
  470. if (chmod(options->ControlPortWriteToFile, 0640)) {
  471. log_warn(LD_FS,"Unable to make %s group-readable.",
  472. options->ControlPortWriteToFile);
  473. }
  474. }
  475. #endif
  476. tor_free(joined);
  477. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  478. smartlist_free(lines);
  479. }
  480. /** Send a "DONE" message down the control connection <b>conn</b>. */
  481. static void
  482. send_control_done(control_connection_t *conn)
  483. {
  484. connection_write_str_to_buf("250 OK\r\n", conn);
  485. }
  486. /** Send an event to all v1 controllers that are listening for code
  487. * <b>event</b>. The event's body is given by <b>msg</b>.
  488. *
  489. * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
  490. * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
  491. * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
  492. * to controllers that <em>have</em> enabled VERBOSE_NAMES.
  493. *
  494. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  495. * respect to the EXTENDED_EVENTS feature. */
  496. MOCK_IMPL(STATIC void,
  497. send_control_event_string,(uint16_t event, event_format_t which,
  498. const char *msg))
  499. {
  500. smartlist_t *conns = get_connection_array();
  501. (void)which;
  502. tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
  503. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  504. if (conn->type == CONN_TYPE_CONTROL &&
  505. !conn->marked_for_close &&
  506. conn->state == CONTROL_CONN_STATE_OPEN) {
  507. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  508. if (control_conn->event_mask & (1<<event)) {
  509. int is_err = 0;
  510. connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
  511. if (event == EVENT_ERR_MSG)
  512. is_err = 1;
  513. else if (event == EVENT_STATUS_GENERAL)
  514. is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
  515. else if (event == EVENT_STATUS_CLIENT)
  516. is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
  517. else if (event == EVENT_STATUS_SERVER)
  518. is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
  519. if (is_err)
  520. connection_flush(TO_CONN(control_conn));
  521. }
  522. }
  523. } SMARTLIST_FOREACH_END(conn);
  524. }
  525. /** Helper for send_control_event and control_event_status:
  526. * Send an event to all v1 controllers that are listening for code
  527. * <b>event</b>. The event's body is created by the printf-style format in
  528. * <b>format</b>, and other arguments as provided. */
  529. static void
  530. send_control_event_impl(uint16_t event, event_format_t which,
  531. const char *format, va_list ap)
  532. {
  533. char *buf = NULL;
  534. int len;
  535. len = tor_vasprintf(&buf, format, ap);
  536. if (len < 0) {
  537. log_warn(LD_BUG, "Unable to format event for controller.");
  538. return;
  539. }
  540. send_control_event_string(event, which|ALL_FORMATS, buf);
  541. tor_free(buf);
  542. }
  543. /** Send an event to all v1 controllers that are listening for code
  544. * <b>event</b>. The event's body is created by the printf-style format in
  545. * <b>format</b>, and other arguments as provided. */
  546. static void
  547. send_control_event(uint16_t event, event_format_t which,
  548. const char *format, ...)
  549. {
  550. va_list ap;
  551. va_start(ap, format);
  552. send_control_event_impl(event, which, format, ap);
  553. va_end(ap);
  554. }
  555. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  556. static origin_circuit_t *
  557. get_circ(const char *id)
  558. {
  559. uint32_t n_id;
  560. int ok;
  561. n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
  562. if (!ok)
  563. return NULL;
  564. return circuit_get_by_global_id(n_id);
  565. }
  566. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  567. static entry_connection_t *
  568. get_stream(const char *id)
  569. {
  570. uint64_t n_id;
  571. int ok;
  572. connection_t *conn;
  573. n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
  574. if (!ok)
  575. return NULL;
  576. conn = connection_get_by_global_id(n_id);
  577. if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
  578. return NULL;
  579. return TO_ENTRY_CONN(conn);
  580. }
  581. /** Helper for setconf and resetconf. Acts like setconf, except
  582. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  583. * contents of body.
  584. */
  585. static int
  586. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  587. int use_defaults)
  588. {
  589. setopt_err_t opt_err;
  590. config_line_t *lines=NULL;
  591. char *start = body;
  592. char *errstring = NULL;
  593. const int clear_first = 1;
  594. char *config;
  595. smartlist_t *entries = smartlist_new();
  596. /* We have a string, "body", of the format '(key(=val|="val")?)' entries
  597. * separated by space. break it into a list of configuration entries. */
  598. while (*body) {
  599. char *eq = body;
  600. char *key;
  601. char *entry;
  602. while (!TOR_ISSPACE(*eq) && *eq != '=')
  603. ++eq;
  604. key = tor_strndup(body, eq-body);
  605. body = eq+1;
  606. if (*eq == '=') {
  607. char *val=NULL;
  608. size_t val_len=0;
  609. if (*body != '\"') {
  610. char *val_start = body;
  611. while (!TOR_ISSPACE(*body))
  612. body++;
  613. val = tor_strndup(val_start, body-val_start);
  614. val_len = strlen(val);
  615. } else {
  616. body = (char*)extract_escaped_string(body, (len - (body-start)),
  617. &val, &val_len);
  618. if (!body) {
  619. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  620. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  621. smartlist_free(entries);
  622. tor_free(key);
  623. return 0;
  624. }
  625. }
  626. tor_asprintf(&entry, "%s %s", key, val);
  627. tor_free(key);
  628. tor_free(val);
  629. } else {
  630. entry = key;
  631. }
  632. smartlist_add(entries, entry);
  633. while (TOR_ISSPACE(*body))
  634. ++body;
  635. }
  636. smartlist_add(entries, tor_strdup(""));
  637. config = smartlist_join_strings(entries, "\n", 0, NULL);
  638. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  639. smartlist_free(entries);
  640. if (config_get_lines(config, &lines, 0) < 0) {
  641. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  642. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  643. conn);
  644. tor_free(config);
  645. return 0;
  646. }
  647. tor_free(config);
  648. opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
  649. {
  650. const char *msg;
  651. switch (opt_err) {
  652. case SETOPT_ERR_MISC:
  653. msg = "552 Unrecognized option";
  654. break;
  655. case SETOPT_ERR_PARSE:
  656. msg = "513 Unacceptable option value";
  657. break;
  658. case SETOPT_ERR_TRANSITION:
  659. msg = "553 Transition not allowed";
  660. break;
  661. case SETOPT_ERR_SETTING:
  662. default:
  663. msg = "553 Unable to set option";
  664. break;
  665. case SETOPT_OK:
  666. config_free_lines(lines);
  667. send_control_done(conn);
  668. return 0;
  669. }
  670. log_warn(LD_CONTROL,
  671. "Controller gave us config lines that didn't validate: %s",
  672. errstring);
  673. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  674. config_free_lines(lines);
  675. tor_free(errstring);
  676. return 0;
  677. }
  678. }
  679. /** Called when we receive a SETCONF message: parse the body and try
  680. * to update our configuration. Reply with a DONE or ERROR message.
  681. * Modifies the contents of body.*/
  682. static int
  683. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  684. {
  685. return control_setconf_helper(conn, len, body, 0);
  686. }
  687. /** Called when we receive a RESETCONF message: parse the body and try
  688. * to update our configuration. Reply with a DONE or ERROR message.
  689. * Modifies the contents of body. */
  690. static int
  691. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  692. {
  693. return control_setconf_helper(conn, len, body, 1);
  694. }
  695. /** Called when we receive a GETCONF message. Parse the request, and
  696. * reply with a CONFVALUE or an ERROR message */
  697. static int
  698. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  699. const char *body)
  700. {
  701. smartlist_t *questions = smartlist_new();
  702. smartlist_t *answers = smartlist_new();
  703. smartlist_t *unrecognized = smartlist_new();
  704. char *msg = NULL;
  705. size_t msg_len;
  706. const or_options_t *options = get_options();
  707. int i, len;
  708. (void) body_len; /* body is NUL-terminated; so we can ignore len. */
  709. smartlist_split_string(questions, body, " ",
  710. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  711. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  712. if (!option_is_recognized(q)) {
  713. smartlist_add(unrecognized, (char*) q);
  714. } else {
  715. config_line_t *answer = option_get_assignment(options,q);
  716. if (!answer) {
  717. const char *name = option_get_canonical_name(q);
  718. smartlist_add_asprintf(answers, "250-%s\r\n", name);
  719. }
  720. while (answer) {
  721. config_line_t *next;
  722. smartlist_add_asprintf(answers, "250-%s=%s\r\n",
  723. answer->key, answer->value);
  724. next = answer->next;
  725. tor_free(answer->key);
  726. tor_free(answer->value);
  727. tor_free(answer);
  728. answer = next;
  729. }
  730. }
  731. } SMARTLIST_FOREACH_END(q);
  732. if ((len = smartlist_len(unrecognized))) {
  733. for (i=0; i < len-1; ++i)
  734. connection_printf_to_buf(conn,
  735. "552-Unrecognized configuration key \"%s\"\r\n",
  736. (char*)smartlist_get(unrecognized, i));
  737. connection_printf_to_buf(conn,
  738. "552 Unrecognized configuration key \"%s\"\r\n",
  739. (char*)smartlist_get(unrecognized, len-1));
  740. } else if ((len = smartlist_len(answers))) {
  741. char *tmp = smartlist_get(answers, len-1);
  742. tor_assert(strlen(tmp)>4);
  743. tmp[3] = ' ';
  744. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  745. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  746. } else {
  747. connection_write_str_to_buf("250 OK\r\n", conn);
  748. }
  749. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  750. smartlist_free(answers);
  751. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  752. smartlist_free(questions);
  753. smartlist_free(unrecognized);
  754. tor_free(msg);
  755. return 0;
  756. }
  757. /** Called when we get a +LOADCONF message. */
  758. static int
  759. handle_control_loadconf(control_connection_t *conn, uint32_t len,
  760. const char *body)
  761. {
  762. setopt_err_t retval;
  763. char *errstring = NULL;
  764. const char *msg = NULL;
  765. (void) len;
  766. retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
  767. if (retval != SETOPT_OK)
  768. log_warn(LD_CONTROL,
  769. "Controller gave us config file that didn't validate: %s",
  770. errstring);
  771. switch (retval) {
  772. case SETOPT_ERR_PARSE:
  773. msg = "552 Invalid config file";
  774. break;
  775. case SETOPT_ERR_TRANSITION:
  776. msg = "553 Transition not allowed";
  777. break;
  778. case SETOPT_ERR_SETTING:
  779. msg = "553 Unable to set option";
  780. break;
  781. case SETOPT_ERR_MISC:
  782. default:
  783. msg = "550 Unable to load config";
  784. break;
  785. case SETOPT_OK:
  786. break;
  787. }
  788. if (msg) {
  789. if (errstring)
  790. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  791. else
  792. connection_printf_to_buf(conn, "%s\r\n", msg);
  793. } else {
  794. send_control_done(conn);
  795. }
  796. tor_free(errstring);
  797. return 0;
  798. }
  799. /** Helper structure: maps event values to their names. */
  800. struct control_event_t {
  801. uint16_t event_code;
  802. const char *event_name;
  803. };
  804. /** Table mapping event values to their names. Used to implement SETEVENTS
  805. * and GETINFO events/names, and to keep they in sync. */
  806. static const struct control_event_t control_event_table[] = {
  807. { EVENT_CIRCUIT_STATUS, "CIRC" },
  808. { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
  809. { EVENT_STREAM_STATUS, "STREAM" },
  810. { EVENT_OR_CONN_STATUS, "ORCONN" },
  811. { EVENT_BANDWIDTH_USED, "BW" },
  812. { EVENT_DEBUG_MSG, "DEBUG" },
  813. { EVENT_INFO_MSG, "INFO" },
  814. { EVENT_NOTICE_MSG, "NOTICE" },
  815. { EVENT_WARN_MSG, "WARN" },
  816. { EVENT_ERR_MSG, "ERR" },
  817. { EVENT_NEW_DESC, "NEWDESC" },
  818. { EVENT_ADDRMAP, "ADDRMAP" },
  819. { EVENT_AUTHDIR_NEWDESCS, "AUTHDIR_NEWDESCS" },
  820. { EVENT_DESCCHANGED, "DESCCHANGED" },
  821. { EVENT_NS, "NS" },
  822. { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
  823. { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
  824. { EVENT_STATUS_SERVER, "STATUS_SERVER" },
  825. { EVENT_GUARD, "GUARD" },
  826. { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
  827. { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
  828. { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
  829. { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
  830. { EVENT_SIGNAL, "SIGNAL" },
  831. { EVENT_CONF_CHANGED, "CONF_CHANGED"},
  832. { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
  833. { 0, NULL },
  834. };
  835. /** Called when we get a SETEVENTS message: update conn->event_mask,
  836. * and reply with DONE or ERROR. */
  837. static int
  838. handle_control_setevents(control_connection_t *conn, uint32_t len,
  839. const char *body)
  840. {
  841. int event_code = -1;
  842. uint32_t event_mask = 0;
  843. smartlist_t *events = smartlist_new();
  844. (void) len;
  845. smartlist_split_string(events, body, " ",
  846. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  847. SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
  848. {
  849. if (!strcasecmp(ev, "EXTENDED")) {
  850. continue;
  851. } else {
  852. int i;
  853. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  854. if (!strcasecmp(ev, control_event_table[i].event_name)) {
  855. event_code = control_event_table[i].event_code;
  856. break;
  857. }
  858. }
  859. if (event_code == -1) {
  860. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  861. ev);
  862. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  863. smartlist_free(events);
  864. return 0;
  865. }
  866. }
  867. event_mask |= (1 << event_code);
  868. }
  869. SMARTLIST_FOREACH_END(ev);
  870. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  871. smartlist_free(events);
  872. conn->event_mask = event_mask;
  873. control_update_global_event_mask();
  874. send_control_done(conn);
  875. return 0;
  876. }
  877. /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
  878. * Return a smartlist of acceptable passwords (unterminated strings of
  879. * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
  880. */
  881. smartlist_t *
  882. decode_hashed_passwords(config_line_t *passwords)
  883. {
  884. char decoded[64];
  885. config_line_t *cl;
  886. smartlist_t *sl = smartlist_new();
  887. tor_assert(passwords);
  888. for (cl = passwords; cl; cl = cl->next) {
  889. const char *hashed = cl->value;
  890. if (!strcmpstart(hashed, "16:")) {
  891. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  892. || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
  893. goto err;
  894. }
  895. } else {
  896. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  897. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  898. goto err;
  899. }
  900. }
  901. smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
  902. }
  903. return sl;
  904. err:
  905. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  906. smartlist_free(sl);
  907. return NULL;
  908. }
  909. /** Called when we get an AUTHENTICATE message. Check whether the
  910. * authentication is valid, and if so, update the connection's state to
  911. * OPEN. Reply with DONE or ERROR.
  912. */
  913. static int
  914. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  915. const char *body)
  916. {
  917. int used_quoted_string = 0;
  918. const or_options_t *options = get_options();
  919. const char *errstr = NULL;
  920. char *password;
  921. size_t password_len;
  922. const char *cp;
  923. int i;
  924. int bad_cookie=0, bad_password=0;
  925. smartlist_t *sl = NULL;
  926. if (!len) {
  927. password = tor_strdup("");
  928. password_len = 0;
  929. } else if (TOR_ISXDIGIT(body[0])) {
  930. cp = body;
  931. while (TOR_ISXDIGIT(*cp))
  932. ++cp;
  933. i = (int)(cp - body);
  934. tor_assert(i>0);
  935. password_len = i/2;
  936. password = tor_malloc(password_len + 1);
  937. if (base16_decode(password, password_len+1, body, i)<0) {
  938. connection_write_str_to_buf(
  939. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  940. "password? If so, the standard requires that you put it in "
  941. "double quotes.\r\n", conn);
  942. connection_mark_for_close(TO_CONN(conn));
  943. tor_free(password);
  944. return 0;
  945. }
  946. } else {
  947. if (!decode_escaped_string(body, len, &password, &password_len)) {
  948. connection_write_str_to_buf("551 Invalid quoted string. You need "
  949. "to put the password in double quotes.\r\n", conn);
  950. connection_mark_for_close(TO_CONN(conn));
  951. return 0;
  952. }
  953. used_quoted_string = 1;
  954. }
  955. if (conn->safecookie_client_hash != NULL) {
  956. /* The controller has chosen safe cookie authentication; the only
  957. * acceptable authentication value is the controller-to-server
  958. * response. */
  959. tor_assert(authentication_cookie_is_set);
  960. if (password_len != DIGEST256_LEN) {
  961. log_warn(LD_CONTROL,
  962. "Got safe cookie authentication response with wrong length "
  963. "(%d)", (int)password_len);
  964. errstr = "Wrong length for safe cookie response.";
  965. goto err;
  966. }
  967. if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
  968. log_warn(LD_CONTROL,
  969. "Got incorrect safe cookie authentication response");
  970. errstr = "Safe cookie response did not match expected value.";
  971. goto err;
  972. }
  973. tor_free(conn->safecookie_client_hash);
  974. goto ok;
  975. }
  976. if (!options->CookieAuthentication && !options->HashedControlPassword &&
  977. !options->HashedControlSessionPassword) {
  978. /* if Tor doesn't demand any stronger authentication, then
  979. * the controller can get in with anything. */
  980. goto ok;
  981. }
  982. if (options->CookieAuthentication) {
  983. int also_password = options->HashedControlPassword != NULL ||
  984. options->HashedControlSessionPassword != NULL;
  985. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  986. if (!also_password) {
  987. log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
  988. "(%d)", (int)password_len);
  989. errstr = "Wrong length on authentication cookie.";
  990. goto err;
  991. }
  992. bad_cookie = 1;
  993. } else if (tor_memneq(authentication_cookie, password, password_len)) {
  994. if (!also_password) {
  995. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  996. errstr = "Authentication cookie did not match expected value.";
  997. goto err;
  998. }
  999. bad_cookie = 1;
  1000. } else {
  1001. goto ok;
  1002. }
  1003. }
  1004. if (options->HashedControlPassword ||
  1005. options->HashedControlSessionPassword) {
  1006. int bad = 0;
  1007. smartlist_t *sl_tmp;
  1008. char received[DIGEST_LEN];
  1009. int also_cookie = options->CookieAuthentication;
  1010. sl = smartlist_new();
  1011. if (options->HashedControlPassword) {
  1012. sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
  1013. if (!sl_tmp)
  1014. bad = 1;
  1015. else {
  1016. smartlist_add_all(sl, sl_tmp);
  1017. smartlist_free(sl_tmp);
  1018. }
  1019. }
  1020. if (options->HashedControlSessionPassword) {
  1021. sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
  1022. if (!sl_tmp)
  1023. bad = 1;
  1024. else {
  1025. smartlist_add_all(sl, sl_tmp);
  1026. smartlist_free(sl_tmp);
  1027. }
  1028. }
  1029. if (bad) {
  1030. if (!also_cookie) {
  1031. log_warn(LD_CONTROL,
  1032. "Couldn't decode HashedControlPassword: invalid base16");
  1033. errstr="Couldn't decode HashedControlPassword value in configuration.";
  1034. }
  1035. bad_password = 1;
  1036. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1037. smartlist_free(sl);
  1038. } else {
  1039. SMARTLIST_FOREACH(sl, char *, expected,
  1040. {
  1041. secret_to_key(received,DIGEST_LEN,password,password_len,expected);
  1042. if (tor_memeq(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  1043. goto ok;
  1044. });
  1045. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1046. smartlist_free(sl);
  1047. if (used_quoted_string)
  1048. errstr = "Password did not match HashedControlPassword value from "
  1049. "configuration";
  1050. else
  1051. errstr = "Password did not match HashedControlPassword value from "
  1052. "configuration. Maybe you tried a plain text password? "
  1053. "If so, the standard requires that you put it in double quotes.";
  1054. bad_password = 1;
  1055. if (!also_cookie)
  1056. goto err;
  1057. }
  1058. }
  1059. /** We only get here if both kinds of authentication failed. */
  1060. tor_assert(bad_password && bad_cookie);
  1061. log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
  1062. errstr = "Password did not match HashedControlPassword *or* authentication "
  1063. "cookie.";
  1064. err:
  1065. tor_free(password);
  1066. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
  1067. errstr ? errstr : "Unknown reason.");
  1068. connection_mark_for_close(TO_CONN(conn));
  1069. return 0;
  1070. ok:
  1071. log_info(LD_CONTROL, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
  1072. ")", conn->base_.s);
  1073. send_control_done(conn);
  1074. conn->base_.state = CONTROL_CONN_STATE_OPEN;
  1075. tor_free(password);
  1076. if (sl) { /* clean up */
  1077. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1078. smartlist_free(sl);
  1079. }
  1080. return 0;
  1081. }
  1082. /** Called when we get a SAVECONF command. Try to flush the current options to
  1083. * disk, and report success or failure. */
  1084. static int
  1085. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  1086. const char *body)
  1087. {
  1088. (void) len;
  1089. (void) body;
  1090. if (options_save_current()<0) {
  1091. connection_write_str_to_buf(
  1092. "551 Unable to write configuration to disk.\r\n", conn);
  1093. } else {
  1094. send_control_done(conn);
  1095. }
  1096. return 0;
  1097. }
  1098. struct signal_t {
  1099. int sig;
  1100. const char *signal_name;
  1101. };
  1102. static const struct signal_t signal_table[] = {
  1103. { SIGHUP, "RELOAD" },
  1104. { SIGHUP, "HUP" },
  1105. { SIGINT, "SHUTDOWN" },
  1106. { SIGUSR1, "DUMP" },
  1107. { SIGUSR1, "USR1" },
  1108. { SIGUSR2, "DEBUG" },
  1109. { SIGUSR2, "USR2" },
  1110. { SIGTERM, "HALT" },
  1111. { SIGTERM, "TERM" },
  1112. { SIGTERM, "INT" },
  1113. { SIGNEWNYM, "NEWNYM" },
  1114. { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
  1115. { 0, NULL },
  1116. };
  1117. /** Called when we get a SIGNAL command. React to the provided signal, and
  1118. * report success or failure. (If the signal results in a shutdown, success
  1119. * may not be reported.) */
  1120. static int
  1121. handle_control_signal(control_connection_t *conn, uint32_t len,
  1122. const char *body)
  1123. {
  1124. int sig = -1;
  1125. int i;
  1126. int n = 0;
  1127. char *s;
  1128. (void) len;
  1129. while (body[n] && ! TOR_ISSPACE(body[n]))
  1130. ++n;
  1131. s = tor_strndup(body, n);
  1132. for (i = 0; signal_table[i].signal_name != NULL; ++i) {
  1133. if (!strcasecmp(s, signal_table[i].signal_name)) {
  1134. sig = signal_table[i].sig;
  1135. break;
  1136. }
  1137. }
  1138. if (sig < 0)
  1139. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1140. s);
  1141. tor_free(s);
  1142. if (sig < 0)
  1143. return 0;
  1144. send_control_done(conn);
  1145. /* Flush the "done" first if the signal might make us shut down. */
  1146. if (sig == SIGTERM || sig == SIGINT)
  1147. connection_flush(TO_CONN(conn));
  1148. process_signal(sig);
  1149. return 0;
  1150. }
  1151. /** Called when we get a TAKEOWNERSHIP command. Mark this connection
  1152. * as an owning connection, so that we will exit if the connection
  1153. * closes. */
  1154. static int
  1155. handle_control_takeownership(control_connection_t *conn, uint32_t len,
  1156. const char *body)
  1157. {
  1158. (void)len;
  1159. (void)body;
  1160. conn->is_owning_control_connection = 1;
  1161. log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
  1162. "Tor instance.",
  1163. (int)(conn->base_.s));
  1164. send_control_done(conn);
  1165. return 0;
  1166. }
  1167. /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
  1168. * containing funny characters. */
  1169. static int
  1170. address_is_invalid_mapaddress_target(const char *addr)
  1171. {
  1172. if (!strcmpstart(addr, "*."))
  1173. return address_is_invalid_destination(addr+2, 1);
  1174. else
  1175. return address_is_invalid_destination(addr, 1);
  1176. }
  1177. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1178. * and report success or failure. */
  1179. static int
  1180. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1181. const char *body)
  1182. {
  1183. smartlist_t *elts;
  1184. smartlist_t *lines;
  1185. smartlist_t *reply;
  1186. char *r;
  1187. size_t sz;
  1188. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  1189. lines = smartlist_new();
  1190. elts = smartlist_new();
  1191. reply = smartlist_new();
  1192. smartlist_split_string(lines, body, " ",
  1193. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1194. SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
  1195. tor_strlower(line);
  1196. smartlist_split_string(elts, line, "=", 0, 2);
  1197. if (smartlist_len(elts) == 2) {
  1198. const char *from = smartlist_get(elts,0);
  1199. const char *to = smartlist_get(elts,1);
  1200. if (address_is_invalid_mapaddress_target(to)) {
  1201. smartlist_add_asprintf(reply,
  1202. "512-syntax error: invalid address '%s'", to);
  1203. log_warn(LD_CONTROL,
  1204. "Skipping invalid argument '%s' in MapAddress msg", to);
  1205. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
  1206. !strcmp(from, "::")) {
  1207. const char type =
  1208. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
  1209. (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
  1210. const char *address = addressmap_register_virtual_address(
  1211. type, tor_strdup(to));
  1212. if (!address) {
  1213. smartlist_add_asprintf(reply,
  1214. "451-resource exhausted: skipping '%s'", line);
  1215. log_warn(LD_CONTROL,
  1216. "Unable to allocate address for '%s' in MapAddress msg",
  1217. safe_str_client(line));
  1218. } else {
  1219. smartlist_add_asprintf(reply, "250-%s=%s", address, to);
  1220. }
  1221. } else {
  1222. const char *msg;
  1223. if (addressmap_register_auto(from, to, 1,
  1224. ADDRMAPSRC_CONTROLLER, &msg) < 0) {
  1225. smartlist_add_asprintf(reply,
  1226. "512-syntax error: invalid address mapping "
  1227. " '%s': %s", line, msg);
  1228. log_warn(LD_CONTROL,
  1229. "Skipping invalid argument '%s' in MapAddress msg: %s",
  1230. line, msg);
  1231. } else {
  1232. smartlist_add_asprintf(reply, "250-%s", line);
  1233. }
  1234. }
  1235. } else {
  1236. smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
  1237. "not of expected form 'foo=bar'.", line);
  1238. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1239. "number of items.",
  1240. safe_str_client(line));
  1241. }
  1242. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1243. smartlist_clear(elts);
  1244. } SMARTLIST_FOREACH_END(line);
  1245. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1246. smartlist_free(lines);
  1247. smartlist_free(elts);
  1248. if (smartlist_len(reply)) {
  1249. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1250. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1251. connection_write_to_buf(r, sz, TO_CONN(conn));
  1252. tor_free(r);
  1253. } else {
  1254. const char *response =
  1255. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1256. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1257. }
  1258. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1259. smartlist_free(reply);
  1260. return 0;
  1261. }
  1262. /** Implementation helper for GETINFO: knows the answers for various
  1263. * trivial-to-implement questions. */
  1264. static int
  1265. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1266. char **answer, const char **errmsg)
  1267. {
  1268. (void) conn;
  1269. if (!strcmp(question, "version")) {
  1270. *answer = tor_strdup(get_version());
  1271. } else if (!strcmp(question, "config-file")) {
  1272. *answer = tor_strdup(get_torrc_fname(0));
  1273. } else if (!strcmp(question, "config-defaults-file")) {
  1274. *answer = tor_strdup(get_torrc_fname(1));
  1275. } else if (!strcmp(question, "config-text")) {
  1276. *answer = options_dump(get_options(), 1);
  1277. } else if (!strcmp(question, "info/names")) {
  1278. *answer = list_getinfo_options();
  1279. } else if (!strcmp(question, "dormant")) {
  1280. int dormant = rep_hist_circbuilding_dormant(time(NULL));
  1281. *answer = tor_strdup(dormant ? "1" : "0");
  1282. } else if (!strcmp(question, "events/names")) {
  1283. int i;
  1284. smartlist_t *event_names = smartlist_new();
  1285. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  1286. smartlist_add(event_names, (char *)control_event_table[i].event_name);
  1287. }
  1288. *answer = smartlist_join_strings(event_names, " ", 0, NULL);
  1289. smartlist_free(event_names);
  1290. } else if (!strcmp(question, "signal/names")) {
  1291. smartlist_t *signal_names = smartlist_new();
  1292. int j;
  1293. for (j = 0; signal_table[j].signal_name != NULL; ++j) {
  1294. smartlist_add(signal_names, (char*)signal_table[j].signal_name);
  1295. }
  1296. *answer = smartlist_join_strings(signal_names, " ", 0, NULL);
  1297. smartlist_free(signal_names);
  1298. } else if (!strcmp(question, "features/names")) {
  1299. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1300. } else if (!strcmp(question, "address")) {
  1301. uint32_t addr;
  1302. if (router_pick_published_address(get_options(), &addr) < 0) {
  1303. *errmsg = "Address unknown";
  1304. return -1;
  1305. }
  1306. *answer = tor_dup_ip(addr);
  1307. } else if (!strcmp(question, "traffic/read")) {
  1308. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
  1309. } else if (!strcmp(question, "traffic/written")) {
  1310. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
  1311. } else if (!strcmp(question, "process/pid")) {
  1312. int myPid = -1;
  1313. #ifdef _WIN32
  1314. myPid = _getpid();
  1315. #else
  1316. myPid = getpid();
  1317. #endif
  1318. tor_asprintf(answer, "%d", myPid);
  1319. } else if (!strcmp(question, "process/uid")) {
  1320. #ifdef _WIN32
  1321. *answer = tor_strdup("-1");
  1322. #else
  1323. int myUid = geteuid();
  1324. tor_asprintf(answer, "%d", myUid);
  1325. #endif
  1326. } else if (!strcmp(question, "process/user")) {
  1327. #ifdef _WIN32
  1328. *answer = tor_strdup("");
  1329. #else
  1330. int myUid = geteuid();
  1331. struct passwd *myPwEntry = getpwuid(myUid);
  1332. if (myPwEntry) {
  1333. *answer = tor_strdup(myPwEntry->pw_name);
  1334. } else {
  1335. *answer = tor_strdup("");
  1336. }
  1337. #endif
  1338. } else if (!strcmp(question, "process/descriptor-limit")) {
  1339. int max_fds=-1;
  1340. set_max_file_descriptors(0, &max_fds);
  1341. tor_asprintf(answer, "%d", max_fds);
  1342. } else if (!strcmp(question, "dir-usage")) {
  1343. *answer = directory_dump_request_log();
  1344. } else if (!strcmp(question, "fingerprint")) {
  1345. crypto_pk_t *server_key;
  1346. if (!server_mode(get_options())) {
  1347. *errmsg = "Not running in server mode";
  1348. return -1;
  1349. }
  1350. server_key = get_server_identity_key();
  1351. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1352. crypto_pk_get_fingerprint(server_key, *answer, 0);
  1353. }
  1354. return 0;
  1355. }
  1356. /** Awful hack: return a newly allocated string based on a routerinfo and
  1357. * (possibly) an extrainfo, sticking the read-history and write-history from
  1358. * <b>ei</b> into the resulting string. The thing you get back won't
  1359. * necessarily have a valid signature.
  1360. *
  1361. * New code should never use this; it's for backward compatibility.
  1362. *
  1363. * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
  1364. * not be NUL-terminated. */
  1365. static char *
  1366. munge_extrainfo_into_routerinfo(const char *ri_body,
  1367. const signed_descriptor_t *ri,
  1368. const signed_descriptor_t *ei)
  1369. {
  1370. char *out = NULL, *outp;
  1371. int i;
  1372. const char *router_sig;
  1373. const char *ei_body = signed_descriptor_get_body(ei);
  1374. size_t ri_len = ri->signed_descriptor_len;
  1375. size_t ei_len = ei->signed_descriptor_len;
  1376. if (!ei_body)
  1377. goto bail;
  1378. outp = out = tor_malloc(ri_len+ei_len+1);
  1379. if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
  1380. goto bail;
  1381. ++router_sig;
  1382. memcpy(out, ri_body, router_sig-ri_body);
  1383. outp += router_sig-ri_body;
  1384. for (i=0; i < 2; ++i) {
  1385. const char *kwd = i?"\nwrite-history ":"\nread-history ";
  1386. const char *cp, *eol;
  1387. if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
  1388. continue;
  1389. ++cp;
  1390. if (!(eol = memchr(cp, '\n', ei_len - (cp-ei_body))))
  1391. continue;
  1392. memcpy(outp, cp, eol-cp+1);
  1393. outp += eol-cp+1;
  1394. }
  1395. memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
  1396. *outp++ = '\0';
  1397. tor_assert(outp-out < (int)(ri_len+ei_len+1));
  1398. return out;
  1399. bail:
  1400. tor_free(out);
  1401. return tor_strndup(ri_body, ri->signed_descriptor_len);
  1402. }
  1403. /** Implementation helper for GETINFO: answers requests for information about
  1404. * which ports are bound. */
  1405. static int
  1406. getinfo_helper_listeners(control_connection_t *control_conn,
  1407. const char *question,
  1408. char **answer, const char **errmsg)
  1409. {
  1410. int type;
  1411. smartlist_t *res;
  1412. (void)control_conn;
  1413. (void)errmsg;
  1414. if (!strcmp(question, "net/listeners/or"))
  1415. type = CONN_TYPE_OR_LISTENER;
  1416. else if (!strcmp(question, "net/listeners/dir"))
  1417. type = CONN_TYPE_DIR_LISTENER;
  1418. else if (!strcmp(question, "net/listeners/socks"))
  1419. type = CONN_TYPE_AP_LISTENER;
  1420. else if (!strcmp(question, "net/listeners/trans"))
  1421. type = CONN_TYPE_AP_TRANS_LISTENER;
  1422. else if (!strcmp(question, "net/listeners/natd"))
  1423. type = CONN_TYPE_AP_NATD_LISTENER;
  1424. else if (!strcmp(question, "net/listeners/dns"))
  1425. type = CONN_TYPE_AP_DNS_LISTENER;
  1426. else if (!strcmp(question, "net/listeners/control"))
  1427. type = CONN_TYPE_CONTROL_LISTENER;
  1428. else
  1429. return 0; /* unknown key */
  1430. res = smartlist_new();
  1431. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  1432. struct sockaddr_storage ss;
  1433. socklen_t ss_len = sizeof(ss);
  1434. if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
  1435. continue;
  1436. if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
  1437. smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
  1438. } else {
  1439. char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
  1440. smartlist_add(res, esc_for_log(tmp));
  1441. tor_free(tmp);
  1442. }
  1443. } SMARTLIST_FOREACH_END(conn);
  1444. *answer = smartlist_join_strings(res, " ", 0, NULL);
  1445. SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
  1446. smartlist_free(res);
  1447. return 0;
  1448. }
  1449. /** Implementation helper for GETINFO: knows the answers for questions about
  1450. * directory information. */
  1451. static int
  1452. getinfo_helper_dir(control_connection_t *control_conn,
  1453. const char *question, char **answer,
  1454. const char **errmsg)
  1455. {
  1456. const node_t *node;
  1457. const routerinfo_t *ri = NULL;
  1458. (void) control_conn;
  1459. if (!strcmpstart(question, "desc/id/")) {
  1460. node = node_get_by_hex_id(question+strlen("desc/id/"));
  1461. if (node)
  1462. ri = node->ri;
  1463. if (ri) {
  1464. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1465. if (body)
  1466. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1467. }
  1468. } else if (!strcmpstart(question, "desc/name/")) {
  1469. /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
  1470. * warning goes to the user, not to the controller. */
  1471. node = node_get_by_nickname(question+strlen("desc/name/"), 1);
  1472. if (node)
  1473. ri = node->ri;
  1474. if (ri) {
  1475. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1476. if (body)
  1477. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1478. }
  1479. } else if (!strcmp(question, "desc/all-recent")) {
  1480. routerlist_t *routerlist = router_get_routerlist();
  1481. smartlist_t *sl = smartlist_new();
  1482. if (routerlist && routerlist->routers) {
  1483. SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
  1484. {
  1485. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1486. if (body)
  1487. smartlist_add(sl,
  1488. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1489. });
  1490. }
  1491. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1492. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1493. smartlist_free(sl);
  1494. } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
  1495. /* XXXX Remove this once Torstat asks for extrainfos. */
  1496. routerlist_t *routerlist = router_get_routerlist();
  1497. smartlist_t *sl = smartlist_new();
  1498. if (routerlist && routerlist->routers) {
  1499. SMARTLIST_FOREACH_BEGIN(routerlist->routers, const routerinfo_t *, ri) {
  1500. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1501. signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
  1502. ri->cache_info.extra_info_digest);
  1503. if (ei && body) {
  1504. smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
  1505. &ri->cache_info, ei));
  1506. } else if (body) {
  1507. smartlist_add(sl,
  1508. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1509. }
  1510. } SMARTLIST_FOREACH_END(ri);
  1511. }
  1512. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1513. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1514. smartlist_free(sl);
  1515. } else if (!strcmpstart(question, "md/id/")) {
  1516. const node_t *node = node_get_by_hex_id(question+strlen("md/id/"));
  1517. const microdesc_t *md = NULL;
  1518. if (node) md = node->md;
  1519. if (md && md->body) {
  1520. *answer = tor_strndup(md->body, md->bodylen);
  1521. }
  1522. } else if (!strcmpstart(question, "md/name/")) {
  1523. /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
  1524. * warning goes to the user, not to the controller. */
  1525. const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 1);
  1526. /* XXXX duplicated code */
  1527. const microdesc_t *md = NULL;
  1528. if (node) md = node->md;
  1529. if (md && md->body) {
  1530. *answer = tor_strndup(md->body, md->bodylen);
  1531. }
  1532. } else if (!strcmpstart(question, "desc-annotations/id/")) {
  1533. node = node_get_by_hex_id(question+strlen("desc-annotations/id/"));
  1534. if (node)
  1535. ri = node->ri;
  1536. if (ri) {
  1537. const char *annotations =
  1538. signed_descriptor_get_annotations(&ri->cache_info);
  1539. if (annotations)
  1540. *answer = tor_strndup(annotations,
  1541. ri->cache_info.annotations_len);
  1542. }
  1543. } else if (!strcmpstart(question, "dir/server/")) {
  1544. size_t answer_len = 0;
  1545. char *url = NULL;
  1546. smartlist_t *descs = smartlist_new();
  1547. const char *msg;
  1548. int res;
  1549. char *cp;
  1550. tor_asprintf(&url, "/tor/%s", question+4);
  1551. res = dirserv_get_routerdescs(descs, url, &msg);
  1552. if (res) {
  1553. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1554. smartlist_free(descs);
  1555. tor_free(url);
  1556. *errmsg = msg;
  1557. return -1;
  1558. }
  1559. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1560. answer_len += sd->signed_descriptor_len);
  1561. cp = *answer = tor_malloc(answer_len+1);
  1562. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1563. {
  1564. memcpy(cp, signed_descriptor_get_body(sd),
  1565. sd->signed_descriptor_len);
  1566. cp += sd->signed_descriptor_len;
  1567. });
  1568. *cp = '\0';
  1569. tor_free(url);
  1570. smartlist_free(descs);
  1571. } else if (!strcmpstart(question, "dir/status/")) {
  1572. if (directory_permits_controller_requests(get_options())) {
  1573. size_t len=0;
  1574. char *cp;
  1575. smartlist_t *status_list = smartlist_new();
  1576. dirserv_get_networkstatus_v2(status_list,
  1577. question+strlen("dir/status/"));
  1578. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1579. cp = *answer = tor_malloc(len+1);
  1580. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1581. memcpy(cp, d->dir, d->dir_len);
  1582. cp += d->dir_len;
  1583. });
  1584. *cp = '\0';
  1585. smartlist_free(status_list);
  1586. } else {
  1587. smartlist_t *fp_list = smartlist_new();
  1588. smartlist_t *status_list = smartlist_new();
  1589. dirserv_get_networkstatus_v2_fingerprints(
  1590. fp_list, question+strlen("dir/status/"));
  1591. SMARTLIST_FOREACH(fp_list, const char *, fp, {
  1592. char *s;
  1593. char *fname = networkstatus_get_cache_filename(fp);
  1594. s = read_file_to_str(fname, 0, NULL);
  1595. if (s)
  1596. smartlist_add(status_list, s);
  1597. tor_free(fname);
  1598. });
  1599. SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
  1600. smartlist_free(fp_list);
  1601. *answer = smartlist_join_strings(status_list, "", 0, NULL);
  1602. SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
  1603. smartlist_free(status_list);
  1604. }
  1605. } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
  1606. if (directory_caches_dir_info(get_options())) {
  1607. const cached_dir_t *consensus = dirserv_get_consensus("ns");
  1608. if (consensus)
  1609. *answer = tor_strdup(consensus->dir);
  1610. }
  1611. if (!*answer) { /* try loading it from disk */
  1612. char *filename = get_datadir_fname("cached-consensus");
  1613. *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  1614. tor_free(filename);
  1615. }
  1616. } else if (!strcmp(question, "network-status")) { /* v1 */
  1617. routerlist_t *routerlist = router_get_routerlist();
  1618. if (!routerlist || !routerlist->routers ||
  1619. list_server_status_v1(routerlist->routers, answer, 1) < 0) {
  1620. return -1;
  1621. }
  1622. } else if (!strcmpstart(question, "extra-info/digest/")) {
  1623. question += strlen("extra-info/digest/");
  1624. if (strlen(question) == HEX_DIGEST_LEN) {
  1625. char d[DIGEST_LEN];
  1626. signed_descriptor_t *sd = NULL;
  1627. if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
  1628. /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
  1629. * but I don't want to risk affecting other parts of the code,
  1630. * especially since the rules for using our own extrainfo (including
  1631. * when it might be freed) are different from those for using one
  1632. * we have downloaded. */
  1633. if (router_extrainfo_digest_is_me(d))
  1634. sd = &(router_get_my_extrainfo()->cache_info);
  1635. else
  1636. sd = extrainfo_get_by_descriptor_digest(d);
  1637. }
  1638. if (sd) {
  1639. const char *body = signed_descriptor_get_body(sd);
  1640. if (body)
  1641. *answer = tor_strndup(body, sd->signed_descriptor_len);
  1642. }
  1643. }
  1644. }
  1645. return 0;
  1646. }
  1647. /** Allocate and return a description of <b>circ</b>'s current status,
  1648. * including its path (if any). */
  1649. static char *
  1650. circuit_describe_status_for_controller(origin_circuit_t *circ)
  1651. {
  1652. char *rv;
  1653. smartlist_t *descparts = smartlist_new();
  1654. {
  1655. char *vpath = circuit_list_path_for_controller(circ);
  1656. if (*vpath) {
  1657. smartlist_add(descparts, vpath);
  1658. } else {
  1659. tor_free(vpath); /* empty path; don't put an extra space in the result */
  1660. }
  1661. }
  1662. {
  1663. cpath_build_state_t *build_state = circ->build_state;
  1664. smartlist_t *flaglist = smartlist_new();
  1665. char *flaglist_joined;
  1666. if (build_state->onehop_tunnel)
  1667. smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
  1668. if (build_state->is_internal)
  1669. smartlist_add(flaglist, (void *)"IS_INTERNAL");
  1670. if (build_state->need_capacity)
  1671. smartlist_add(flaglist, (void *)"NEED_CAPACITY");
  1672. if (build_state->need_uptime)
  1673. smartlist_add(flaglist, (void *)"NEED_UPTIME");
  1674. /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
  1675. if (smartlist_len(flaglist)) {
  1676. flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
  1677. smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
  1678. tor_free(flaglist_joined);
  1679. }
  1680. smartlist_free(flaglist);
  1681. }
  1682. smartlist_add_asprintf(descparts, "PURPOSE=%s",
  1683. circuit_purpose_to_controller_string(circ->base_.purpose));
  1684. {
  1685. const char *hs_state =
  1686. circuit_purpose_to_controller_hs_state_string(circ->base_.purpose);
  1687. if (hs_state != NULL) {
  1688. smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
  1689. }
  1690. }
  1691. if (circ->rend_data != NULL) {
  1692. smartlist_add_asprintf(descparts, "REND_QUERY=%s",
  1693. circ->rend_data->onion_address);
  1694. }
  1695. {
  1696. char tbuf[ISO_TIME_USEC_LEN+1];
  1697. format_iso_time_nospace_usec(tbuf, &circ->base_.timestamp_created);
  1698. smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
  1699. }
  1700. rv = smartlist_join_strings(descparts, " ", 0, NULL);
  1701. SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
  1702. smartlist_free(descparts);
  1703. return rv;
  1704. }
  1705. /** Implementation helper for GETINFO: knows how to generate summaries of the
  1706. * current states of things we send events about. */
  1707. static int
  1708. getinfo_helper_events(control_connection_t *control_conn,
  1709. const char *question, char **answer,
  1710. const char **errmsg)
  1711. {
  1712. (void) control_conn;
  1713. if (!strcmp(question, "circuit-status")) {
  1714. circuit_t *circ_;
  1715. smartlist_t *status = smartlist_new();
  1716. TOR_LIST_FOREACH(circ_, circuit_get_global_list(), head) {
  1717. origin_circuit_t *circ;
  1718. char *circdesc;
  1719. const char *state;
  1720. if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
  1721. continue;
  1722. circ = TO_ORIGIN_CIRCUIT(circ_);
  1723. if (circ->base_.state == CIRCUIT_STATE_OPEN)
  1724. state = "BUILT";
  1725. else if (circ->cpath)
  1726. state = "EXTENDED";
  1727. else
  1728. state = "LAUNCHED";
  1729. circdesc = circuit_describe_status_for_controller(circ);
  1730. smartlist_add_asprintf(status, "%lu %s%s%s",
  1731. (unsigned long)circ->global_identifier,
  1732. state, *circdesc ? " " : "", circdesc);
  1733. tor_free(circdesc);
  1734. }
  1735. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1736. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1737. smartlist_free(status);
  1738. } else if (!strcmp(question, "stream-status")) {
  1739. smartlist_t *conns = get_connection_array();
  1740. smartlist_t *status = smartlist_new();
  1741. char buf[256];
  1742. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1743. const char *state;
  1744. entry_connection_t *conn;
  1745. circuit_t *circ;
  1746. origin_circuit_t *origin_circ = NULL;
  1747. if (base_conn->type != CONN_TYPE_AP ||
  1748. base_conn->marked_for_close ||
  1749. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  1750. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  1751. continue;
  1752. conn = TO_ENTRY_CONN(base_conn);
  1753. switch (base_conn->state)
  1754. {
  1755. case AP_CONN_STATE_CONTROLLER_WAIT:
  1756. case AP_CONN_STATE_CIRCUIT_WAIT:
  1757. if (conn->socks_request &&
  1758. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1759. state = "NEWRESOLVE";
  1760. else
  1761. state = "NEW";
  1762. break;
  1763. case AP_CONN_STATE_RENDDESC_WAIT:
  1764. case AP_CONN_STATE_CONNECT_WAIT:
  1765. state = "SENTCONNECT"; break;
  1766. case AP_CONN_STATE_RESOLVE_WAIT:
  1767. state = "SENTRESOLVE"; break;
  1768. case AP_CONN_STATE_OPEN:
  1769. state = "SUCCEEDED"; break;
  1770. default:
  1771. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1772. base_conn->state);
  1773. continue;
  1774. }
  1775. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  1776. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1777. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1778. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1779. smartlist_add_asprintf(status, "%lu %s %lu %s",
  1780. (unsigned long) base_conn->global_identifier,state,
  1781. origin_circ?
  1782. (unsigned long)origin_circ->global_identifier : 0ul,
  1783. buf);
  1784. } SMARTLIST_FOREACH_END(base_conn);
  1785. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1786. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1787. smartlist_free(status);
  1788. } else if (!strcmp(question, "orconn-status")) {
  1789. smartlist_t *conns = get_connection_array();
  1790. smartlist_t *status = smartlist_new();
  1791. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1792. const char *state;
  1793. char name[128];
  1794. or_connection_t *conn;
  1795. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  1796. continue;
  1797. conn = TO_OR_CONN(base_conn);
  1798. if (conn->base_.state == OR_CONN_STATE_OPEN)
  1799. state = "CONNECTED";
  1800. else if (conn->nickname)
  1801. state = "LAUNCHED";
  1802. else
  1803. state = "NEW";
  1804. orconn_target_get_name(name, sizeof(name), conn);
  1805. smartlist_add_asprintf(status, "%s %s", name, state);
  1806. } SMARTLIST_FOREACH_END(base_conn);
  1807. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1808. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1809. smartlist_free(status);
  1810. } else if (!strcmpstart(question, "address-mappings/")) {
  1811. time_t min_e, max_e;
  1812. smartlist_t *mappings;
  1813. question += strlen("address-mappings/");
  1814. if (!strcmp(question, "all")) {
  1815. min_e = 0; max_e = TIME_MAX;
  1816. } else if (!strcmp(question, "cache")) {
  1817. min_e = 2; max_e = TIME_MAX;
  1818. } else if (!strcmp(question, "config")) {
  1819. min_e = 0; max_e = 0;
  1820. } else if (!strcmp(question, "control")) {
  1821. min_e = 1; max_e = 1;
  1822. } else {
  1823. return 0;
  1824. }
  1825. mappings = smartlist_new();
  1826. addressmap_get_mappings(mappings, min_e, max_e, 1);
  1827. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1828. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1829. smartlist_free(mappings);
  1830. } else if (!strcmpstart(question, "status/")) {
  1831. /* Note that status/ is not a catch-all for events; there's only supposed
  1832. * to be a status GETINFO if there's a corresponding STATUS event. */
  1833. if (!strcmp(question, "status/circuit-established")) {
  1834. *answer = tor_strdup(can_complete_circuit ? "1" : "0");
  1835. } else if (!strcmp(question, "status/enough-dir-info")) {
  1836. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  1837. } else if (!strcmp(question, "status/good-server-descriptor") ||
  1838. !strcmp(question, "status/accepted-server-descriptor")) {
  1839. /* They're equivalent for now, until we can figure out how to make
  1840. * good-server-descriptor be what we want. See comment in
  1841. * control-spec.txt. */
  1842. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  1843. ? "1" : "0");
  1844. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  1845. *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
  1846. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  1847. *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
  1848. } else if (!strcmp(question, "status/reachability-succeeded")) {
  1849. tor_asprintf(answer, "OR=%d DIR=%d",
  1850. check_whether_orport_reachable() ? 1 : 0,
  1851. check_whether_dirport_reachable() ? 1 : 0);
  1852. } else if (!strcmp(question, "status/bootstrap-phase")) {
  1853. *answer = tor_strdup(last_sent_bootstrap_message);
  1854. } else if (!strcmpstart(question, "status/version/")) {
  1855. int is_server = server_mode(get_options());
  1856. networkstatus_t *c = networkstatus_get_latest_consensus();
  1857. version_status_t status;
  1858. const char *recommended;
  1859. if (c) {
  1860. recommended = is_server ? c->server_versions : c->client_versions;
  1861. status = tor_version_is_obsolete(VERSION, recommended);
  1862. } else {
  1863. recommended = "?";
  1864. status = VS_UNKNOWN;
  1865. }
  1866. if (!strcmp(question, "status/version/recommended")) {
  1867. *answer = tor_strdup(recommended);
  1868. return 0;
  1869. }
  1870. if (!strcmp(question, "status/version/current")) {
  1871. switch (status)
  1872. {
  1873. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  1874. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  1875. case VS_NEW: *answer = tor_strdup("new"); break;
  1876. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  1877. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  1878. case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
  1879. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  1880. default: tor_fragile_assert();
  1881. }
  1882. } else if (!strcmp(question, "status/version/num-versioning") ||
  1883. !strcmp(question, "status/version/num-concurring")) {
  1884. tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
  1885. log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
  1886. "information", question);
  1887. }
  1888. } else if (!strcmp(question, "status/clients-seen")) {
  1889. char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
  1890. if (!bridge_stats) {
  1891. *errmsg = "No bridge-client stats available";
  1892. return -1;
  1893. }
  1894. *answer = bridge_stats;
  1895. } else {
  1896. return 0;
  1897. }
  1898. }
  1899. return 0;
  1900. }
  1901. /** Callback function for GETINFO: on a given control connection, try to
  1902. * answer the question <b>q</b> and store the newly-allocated answer in
  1903. * *<b>a</b>. If an internal error occurs, return -1 and optionally set
  1904. * *<b>error_out</b> to point to an error message to be delivered to the
  1905. * controller. On success, _or if the key is not recognized_, return 0. Do not
  1906. * set <b>a</b> if the key is not recognized.
  1907. */
  1908. typedef int (*getinfo_helper_t)(control_connection_t *,
  1909. const char *q, char **a,
  1910. const char **error_out);
  1911. /** A single item for the GETINFO question-to-answer-function table. */
  1912. typedef struct getinfo_item_t {
  1913. const char *varname; /**< The value (or prefix) of the question. */
  1914. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  1915. * this entry is documentation-only. */
  1916. const char *desc; /**< Description of the variable. */
  1917. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  1918. } getinfo_item_t;
  1919. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  1920. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  1921. #define DOC(name, desc) { name, NULL, desc, 0 }
  1922. /** Table mapping questions accepted by GETINFO to the functions that know how
  1923. * to answer them. */
  1924. static const getinfo_item_t getinfo_items[] = {
  1925. ITEM("version", misc, "The current version of Tor."),
  1926. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  1927. ITEM("config-defaults-file", misc, "Current location of the defaults file."),
  1928. ITEM("config-text", misc,
  1929. "Return the string that would be written by a saveconf command."),
  1930. ITEM("accounting/bytes", accounting,
  1931. "Number of bytes read/written so far in the accounting interval."),
  1932. ITEM("accounting/bytes-left", accounting,
  1933. "Number of bytes left to write/read so far in the accounting interval."),
  1934. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  1935. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  1936. ITEM("accounting/interval-start", accounting,
  1937. "Time when the accounting period starts."),
  1938. ITEM("accounting/interval-end", accounting,
  1939. "Time when the accounting period ends."),
  1940. ITEM("accounting/interval-wake", accounting,
  1941. "Time to wake up in this accounting period."),
  1942. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  1943. ITEM("entry-guards", entry_guards,
  1944. "Which nodes are we using as entry guards?"),
  1945. ITEM("fingerprint", misc, NULL),
  1946. PREFIX("config/", config, "Current configuration values."),
  1947. DOC("config/names",
  1948. "List of configuration options, types, and documentation."),
  1949. DOC("config/defaults",
  1950. "List of default values for configuration options. "
  1951. "See also config/names"),
  1952. ITEM("info/names", misc,
  1953. "List of GETINFO options, types, and documentation."),
  1954. ITEM("events/names", misc,
  1955. "Events that the controller can ask for with SETEVENTS."),
  1956. ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
  1957. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  1958. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  1959. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  1960. ITEM("desc/all-recent", dir,
  1961. "All non-expired, non-superseded router descriptors."),
  1962. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  1963. PREFIX("md/id/", dir, "Microdescriptors by ID"),
  1964. PREFIX("md/name/", dir, "Microdescriptors by name"),
  1965. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  1966. PREFIX("net/listeners/", listeners, "Bound addresses by type"),
  1967. ITEM("ns/all", networkstatus,
  1968. "Brief summary of router status (v2 directory format)"),
  1969. PREFIX("ns/id/", networkstatus,
  1970. "Brief summary of router status by ID (v2 directory format)."),
  1971. PREFIX("ns/name/", networkstatus,
  1972. "Brief summary of router status by nickname (v2 directory format)."),
  1973. PREFIX("ns/purpose/", networkstatus,
  1974. "Brief summary of router status by purpose (v2 directory format)."),
  1975. ITEM("network-status", dir,
  1976. "Brief summary of router status (v1 directory format)"),
  1977. ITEM("circuit-status", events, "List of current circuits originating here."),
  1978. ITEM("stream-status", events,"List of current streams."),
  1979. ITEM("orconn-status", events, "A list of current OR connections."),
  1980. ITEM("dormant", misc,
  1981. "Is Tor dormant (not building circuits because it's idle)?"),
  1982. PREFIX("address-mappings/", events, NULL),
  1983. DOC("address-mappings/all", "Current address mappings."),
  1984. DOC("address-mappings/cache", "Current cached DNS replies."),
  1985. DOC("address-mappings/config",
  1986. "Current address mappings from configuration."),
  1987. DOC("address-mappings/control", "Current address mappings from controller."),
  1988. PREFIX("status/", events, NULL),
  1989. DOC("status/circuit-established",
  1990. "Whether we think client functionality is working."),
  1991. DOC("status/enough-dir-info",
  1992. "Whether we have enough up-to-date directory information to build "
  1993. "circuits."),
  1994. DOC("status/bootstrap-phase",
  1995. "The last bootstrap phase status event that Tor sent."),
  1996. DOC("status/clients-seen",
  1997. "Breakdown of client countries seen by a bridge."),
  1998. DOC("status/version/recommended", "List of currently recommended versions."),
  1999. DOC("status/version/current", "Status of the current version."),
  2000. DOC("status/version/num-versioning", "Number of versioning authorities."),
  2001. DOC("status/version/num-concurring",
  2002. "Number of versioning authorities agreeing on the status of the "
  2003. "current version"),
  2004. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  2005. ITEM("traffic/read", misc,"Bytes read since the process was started."),
  2006. ITEM("traffic/written", misc,
  2007. "Bytes written since the process was started."),
  2008. ITEM("process/pid", misc, "Process id belonging to the main tor process."),
  2009. ITEM("process/uid", misc, "User id running the tor process."),
  2010. ITEM("process/user", misc,
  2011. "Username under which the tor process is running."),
  2012. ITEM("process/descriptor-limit", misc, "File descriptor limit."),
  2013. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  2014. PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
  2015. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  2016. PREFIX("dir/status/", dir,
  2017. "v2 networkstatus docs as retrieved from a DirPort."),
  2018. ITEM("dir/status-vote/current/consensus", dir,
  2019. "v3 Networkstatus consensus as retrieved from a DirPort."),
  2020. ITEM("exit-policy/default", policies,
  2021. "The default value appended to the configured exit policy."),
  2022. ITEM("exit-policy/full", policies, "The entire exit policy of onion router"),
  2023. ITEM("exit-policy/ipv4", policies, "IPv4 parts of exit policy"),
  2024. ITEM("exit-policy/ipv6", policies, "IPv6 parts of exit policy"),
  2025. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  2026. { NULL, NULL, NULL, 0 }
  2027. };
  2028. /** Allocate and return a list of recognized GETINFO options. */
  2029. static char *
  2030. list_getinfo_options(void)
  2031. {
  2032. int i;
  2033. smartlist_t *lines = smartlist_new();
  2034. char *ans;
  2035. for (i = 0; getinfo_items[i].varname; ++i) {
  2036. if (!getinfo_items[i].desc)
  2037. continue;
  2038. smartlist_add_asprintf(lines, "%s%s -- %s\n",
  2039. getinfo_items[i].varname,
  2040. getinfo_items[i].is_prefix ? "*" : "",
  2041. getinfo_items[i].desc);
  2042. }
  2043. smartlist_sort_strings(lines);
  2044. ans = smartlist_join_strings(lines, "", 0, NULL);
  2045. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  2046. smartlist_free(lines);
  2047. return ans;
  2048. }
  2049. /** Lookup the 'getinfo' entry <b>question</b>, and return
  2050. * the answer in <b>*answer</b> (or NULL if key not recognized).
  2051. * Return 0 if success or unrecognized, or -1 if recognized but
  2052. * internal error. */
  2053. static int
  2054. handle_getinfo_helper(control_connection_t *control_conn,
  2055. const char *question, char **answer,
  2056. const char **err_out)
  2057. {
  2058. int i;
  2059. *answer = NULL; /* unrecognized key by default */
  2060. for (i = 0; getinfo_items[i].varname; ++i) {
  2061. int match;
  2062. if (getinfo_items[i].is_prefix)
  2063. match = !strcmpstart(question, getinfo_items[i].varname);
  2064. else
  2065. match = !strcmp(question, getinfo_items[i].varname);
  2066. if (match) {
  2067. tor_assert(getinfo_items[i].fn);
  2068. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  2069. }
  2070. }
  2071. return 0; /* unrecognized */
  2072. }
  2073. /** Called when we receive a GETINFO command. Try to fetch all requested
  2074. * information, and reply with information or error message. */
  2075. static int
  2076. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  2077. const char *body)
  2078. {
  2079. smartlist_t *questions = smartlist_new();
  2080. smartlist_t *answers = smartlist_new();
  2081. smartlist_t *unrecognized = smartlist_new();
  2082. char *msg = NULL, *ans = NULL;
  2083. int i;
  2084. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2085. smartlist_split_string(questions, body, " ",
  2086. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2087. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  2088. const char *errmsg = NULL;
  2089. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  2090. if (!errmsg)
  2091. errmsg = "Internal error";
  2092. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  2093. goto done;
  2094. }
  2095. if (!ans) {
  2096. smartlist_add(unrecognized, (char*)q);
  2097. } else {
  2098. smartlist_add(answers, tor_strdup(q));
  2099. smartlist_add(answers, ans);
  2100. }
  2101. } SMARTLIST_FOREACH_END(q);
  2102. if (smartlist_len(unrecognized)) {
  2103. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  2104. connection_printf_to_buf(conn,
  2105. "552-Unrecognized key \"%s\"\r\n",
  2106. (char*)smartlist_get(unrecognized, i));
  2107. connection_printf_to_buf(conn,
  2108. "552 Unrecognized key \"%s\"\r\n",
  2109. (char*)smartlist_get(unrecognized, i));
  2110. goto done;
  2111. }
  2112. for (i = 0; i < smartlist_len(answers); i += 2) {
  2113. char *k = smartlist_get(answers, i);
  2114. char *v = smartlist_get(answers, i+1);
  2115. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  2116. connection_printf_to_buf(conn, "250-%s=", k);
  2117. connection_write_str_to_buf(v, conn);
  2118. connection_write_str_to_buf("\r\n", conn);
  2119. } else {
  2120. char *esc = NULL;
  2121. size_t esc_len;
  2122. esc_len = write_escaped_data(v, strlen(v), &esc);
  2123. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  2124. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  2125. tor_free(esc);
  2126. }
  2127. }
  2128. connection_write_str_to_buf("250 OK\r\n", conn);
  2129. done:
  2130. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  2131. smartlist_free(answers);
  2132. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  2133. smartlist_free(questions);
  2134. smartlist_free(unrecognized);
  2135. tor_free(msg);
  2136. return 0;
  2137. }
  2138. /** Given a string, convert it to a circuit purpose. */
  2139. static uint8_t
  2140. circuit_purpose_from_string(const char *string)
  2141. {
  2142. if (!strcasecmpstart(string, "purpose="))
  2143. string += strlen("purpose=");
  2144. if (!strcasecmp(string, "general"))
  2145. return CIRCUIT_PURPOSE_C_GENERAL;
  2146. else if (!strcasecmp(string, "controller"))
  2147. return CIRCUIT_PURPOSE_CONTROLLER;
  2148. else
  2149. return CIRCUIT_PURPOSE_UNKNOWN;
  2150. }
  2151. /** Return a newly allocated smartlist containing the arguments to the command
  2152. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  2153. * or if <b>max_args</b> is nonnegative and there are more than
  2154. * <b>max_args</b> arguments, send a 512 error to the controller, using
  2155. * <b>command</b> as the command name in the error message. */
  2156. static smartlist_t *
  2157. getargs_helper(const char *command, control_connection_t *conn,
  2158. const char *body, int min_args, int max_args)
  2159. {
  2160. smartlist_t *args = smartlist_new();
  2161. smartlist_split_string(args, body, " ",
  2162. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2163. if (smartlist_len(args) < min_args) {
  2164. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  2165. goto err;
  2166. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  2167. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  2168. goto err;
  2169. }
  2170. return args;
  2171. err:
  2172. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  2173. smartlist_free(args);
  2174. return NULL;
  2175. }
  2176. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  2177. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  2178. * such element exists. */
  2179. static const char *
  2180. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  2181. {
  2182. int i;
  2183. for (i = start_at; i < smartlist_len(sl); ++i) {
  2184. const char *elt = smartlist_get(sl, i);
  2185. if (!strcasecmpstart(elt, prefix))
  2186. return elt;
  2187. }
  2188. return NULL;
  2189. }
  2190. /** Helper. Return true iff s is an argument that we should treat as a
  2191. * key-value pair. */
  2192. static int
  2193. is_keyval_pair(const char *s)
  2194. {
  2195. /* An argument is a key-value pair if it has an =, and it isn't of the form
  2196. * $fingeprint=name */
  2197. return strchr(s, '=') && s[0] != '$';
  2198. }
  2199. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  2200. * circuit, and report success or failure. */
  2201. static int
  2202. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  2203. const char *body)
  2204. {
  2205. smartlist_t *router_nicknames=NULL, *nodes=NULL;
  2206. origin_circuit_t *circ = NULL;
  2207. int zero_circ;
  2208. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  2209. smartlist_t *args;
  2210. (void) len;
  2211. router_nicknames = smartlist_new();
  2212. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  2213. if (!args)
  2214. goto done;
  2215. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  2216. if (zero_circ) {
  2217. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  2218. if (purp) {
  2219. intended_purpose = circuit_purpose_from_string(purp);
  2220. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2221. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2222. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2223. smartlist_free(args);
  2224. goto done;
  2225. }
  2226. }
  2227. if ((smartlist_len(args) == 1) ||
  2228. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  2229. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  2230. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  2231. if (!circ) {
  2232. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2233. } else {
  2234. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2235. (unsigned long)circ->global_identifier);
  2236. }
  2237. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2238. smartlist_free(args);
  2239. goto done;
  2240. }
  2241. // "EXTENDCIRCUIT 0 router1,router2" ||
  2242. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  2243. }
  2244. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  2245. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2246. (char*)smartlist_get(args, 0));
  2247. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2248. smartlist_free(args);
  2249. goto done;
  2250. }
  2251. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  2252. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2253. smartlist_free(args);
  2254. nodes = smartlist_new();
  2255. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  2256. const node_t *node = node_get_by_nickname(n, 1);
  2257. if (!node) {
  2258. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  2259. goto done;
  2260. }
  2261. if (!node_has_descriptor(node)) {
  2262. connection_printf_to_buf(conn, "552 descriptor for \"%s\"\r\n", n);
  2263. goto done;
  2264. }
  2265. smartlist_add(nodes, (void*)node);
  2266. } SMARTLIST_FOREACH_END(n);
  2267. if (!smartlist_len(nodes)) {
  2268. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  2269. goto done;
  2270. }
  2271. if (zero_circ) {
  2272. /* start a new circuit */
  2273. circ = origin_circuit_init(intended_purpose, 0);
  2274. }
  2275. /* now circ refers to something that is ready to be extended */
  2276. SMARTLIST_FOREACH(nodes, const node_t *, node,
  2277. {
  2278. extend_info_t *info = extend_info_from_node(node, 0);
  2279. tor_assert(info); /* True, since node_has_descriptor(node) == true */
  2280. circuit_append_new_exit(circ, info);
  2281. extend_info_free(info);
  2282. });
  2283. /* now that we've populated the cpath, start extending */
  2284. if (zero_circ) {
  2285. int err_reason = 0;
  2286. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  2287. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2288. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2289. goto done;
  2290. }
  2291. } else {
  2292. if (circ->base_.state == CIRCUIT_STATE_OPEN) {
  2293. int err_reason = 0;
  2294. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2295. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  2296. log_info(LD_CONTROL,
  2297. "send_next_onion_skin failed; circuit marked for closing.");
  2298. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2299. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  2300. goto done;
  2301. }
  2302. }
  2303. }
  2304. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2305. (unsigned long)circ->global_identifier);
  2306. if (zero_circ) /* send a 'launched' event, for completeness */
  2307. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  2308. done:
  2309. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  2310. smartlist_free(router_nicknames);
  2311. smartlist_free(nodes);
  2312. return 0;
  2313. }
  2314. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  2315. * circuit and it's a valid purpose, change it. */
  2316. static int
  2317. handle_control_setcircuitpurpose(control_connection_t *conn,
  2318. uint32_t len, const char *body)
  2319. {
  2320. origin_circuit_t *circ = NULL;
  2321. uint8_t new_purpose;
  2322. smartlist_t *args;
  2323. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2324. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  2325. if (!args)
  2326. goto done;
  2327. if (!(circ = get_circ(smartlist_get(args,0)))) {
  2328. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2329. (char*)smartlist_get(args, 0));
  2330. goto done;
  2331. }
  2332. {
  2333. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  2334. if (!purp) {
  2335. connection_write_str_to_buf("552 No purpose given\r\n", conn);
  2336. goto done;
  2337. }
  2338. new_purpose = circuit_purpose_from_string(purp);
  2339. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2340. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2341. goto done;
  2342. }
  2343. }
  2344. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  2345. connection_write_str_to_buf("250 OK\r\n", conn);
  2346. done:
  2347. if (args) {
  2348. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2349. smartlist_free(args);
  2350. }
  2351. return 0;
  2352. }
  2353. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  2354. * stream, and report success or failure. */
  2355. static int
  2356. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  2357. const char *body)
  2358. {
  2359. entry_connection_t *ap_conn = NULL;
  2360. origin_circuit_t *circ = NULL;
  2361. int zero_circ;
  2362. smartlist_t *args;
  2363. crypt_path_t *cpath=NULL;
  2364. int hop=0, hop_line_ok=1;
  2365. (void) len;
  2366. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  2367. if (!args)
  2368. return 0;
  2369. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  2370. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  2371. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2372. (char*)smartlist_get(args, 0));
  2373. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  2374. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2375. (char*)smartlist_get(args, 1));
  2376. } else if (circ) {
  2377. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  2378. if (hopstring) {
  2379. hopstring += strlen("HOP=");
  2380. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  2381. &hop_line_ok, NULL);
  2382. if (!hop_line_ok) { /* broken hop line */
  2383. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  2384. }
  2385. }
  2386. }
  2387. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2388. smartlist_free(args);
  2389. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  2390. return 0;
  2391. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  2392. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  2393. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  2394. connection_write_str_to_buf(
  2395. "555 Connection is not managed by controller.\r\n",
  2396. conn);
  2397. return 0;
  2398. }
  2399. /* Do we need to detach it first? */
  2400. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  2401. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2402. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  2403. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  2404. /* Un-mark it as ending, since we're going to reuse it. */
  2405. edge_conn->edge_has_sent_end = 0;
  2406. edge_conn->end_reason = 0;
  2407. if (tmpcirc)
  2408. circuit_detach_stream(tmpcirc, edge_conn);
  2409. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  2410. }
  2411. if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
  2412. connection_write_str_to_buf(
  2413. "551 Can't attach stream to non-open origin circuit\r\n",
  2414. conn);
  2415. return 0;
  2416. }
  2417. /* Is this a single hop circuit? */
  2418. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  2419. const node_t *node = NULL;
  2420. char *exit_digest;
  2421. if (circ->build_state &&
  2422. circ->build_state->chosen_exit &&
  2423. !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
  2424. exit_digest = circ->build_state->chosen_exit->identity_digest;
  2425. node = node_get_by_id(exit_digest);
  2426. }
  2427. /* Do both the client and relay allow one-hop exit circuits? */
  2428. if (!node ||
  2429. !node_allows_single_hop_exits(node) ||
  2430. !get_options()->AllowSingleHopCircuits) {
  2431. connection_write_str_to_buf(
  2432. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  2433. return 0;
  2434. }
  2435. ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
  2436. }
  2437. if (circ && hop>0) {
  2438. /* find this hop in the circuit, and set cpath */
  2439. cpath = circuit_get_cpath_hop(circ, hop);
  2440. if (!cpath) {
  2441. connection_printf_to_buf(conn,
  2442. "551 Circuit doesn't have %d hops.\r\n", hop);
  2443. return 0;
  2444. }
  2445. }
  2446. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  2447. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  2448. return 0;
  2449. }
  2450. send_control_done(conn);
  2451. return 0;
  2452. }
  2453. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  2454. * descriptor, and report success or failure. */
  2455. static int
  2456. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  2457. const char *body)
  2458. {
  2459. char *desc;
  2460. const char *msg=NULL;
  2461. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  2462. int cache = 0; /* eventually, we may switch this to 1 */
  2463. char *cp = memchr(body, '\n', len);
  2464. smartlist_t *args = smartlist_new();
  2465. tor_assert(cp);
  2466. *cp++ = '\0';
  2467. smartlist_split_string(args, body, " ",
  2468. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2469. SMARTLIST_FOREACH_BEGIN(args, char *, option) {
  2470. if (!strcasecmpstart(option, "purpose=")) {
  2471. option += strlen("purpose=");
  2472. purpose = router_purpose_from_string(option);
  2473. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  2474. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  2475. option);
  2476. goto done;
  2477. }
  2478. } else if (!strcasecmpstart(option, "cache=")) {
  2479. option += strlen("cache=");
  2480. if (!strcasecmp(option, "no"))
  2481. cache = 0;
  2482. else if (!strcasecmp(option, "yes"))
  2483. cache = 1;
  2484. else {
  2485. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  2486. option);
  2487. goto done;
  2488. }
  2489. } else { /* unrecognized argument? */
  2490. connection_printf_to_buf(conn,
  2491. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  2492. goto done;
  2493. }
  2494. } SMARTLIST_FOREACH_END(option);
  2495. read_escaped_data(cp, len-(cp-body), &desc);
  2496. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  2497. case -1:
  2498. if (!msg) msg = "Could not parse descriptor";
  2499. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  2500. break;
  2501. case 0:
  2502. if (!msg) msg = "Descriptor not added";
  2503. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2504. break;
  2505. case 1:
  2506. send_control_done(conn);
  2507. break;
  2508. }
  2509. tor_free(desc);
  2510. done:
  2511. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  2512. smartlist_free(args);
  2513. return 0;
  2514. }
  2515. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2516. * address of the named AP stream, and report success or failure. */
  2517. static int
  2518. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2519. const char *body)
  2520. {
  2521. entry_connection_t *ap_conn = NULL;
  2522. char *new_addr = NULL;
  2523. uint16_t new_port = 0;
  2524. smartlist_t *args;
  2525. (void) len;
  2526. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  2527. if (!args)
  2528. return 0;
  2529. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2530. || !ap_conn->socks_request) {
  2531. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2532. (char*)smartlist_get(args, 0));
  2533. } else {
  2534. int ok = 1;
  2535. if (smartlist_len(args) > 2) { /* they included a port too */
  2536. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2537. 10, 1, 65535, &ok, NULL);
  2538. }
  2539. if (!ok) {
  2540. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2541. (char*)smartlist_get(args, 2));
  2542. } else {
  2543. new_addr = tor_strdup(smartlist_get(args, 1));
  2544. }
  2545. }
  2546. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2547. smartlist_free(args);
  2548. if (!new_addr)
  2549. return 0;
  2550. strlcpy(ap_conn->socks_request->address, new_addr,
  2551. sizeof(ap_conn->socks_request->address));
  2552. if (new_port)
  2553. ap_conn->socks_request->port = new_port;
  2554. tor_free(new_addr);
  2555. send_control_done(conn);
  2556. return 0;
  2557. }
  2558. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2559. * and report success or failure. */
  2560. static int
  2561. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2562. const char *body)
  2563. {
  2564. entry_connection_t *ap_conn=NULL;
  2565. uint8_t reason=0;
  2566. smartlist_t *args;
  2567. int ok;
  2568. (void) len;
  2569. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2570. if (!args)
  2571. return 0;
  2572. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2573. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2574. (char*)smartlist_get(args, 0));
  2575. else {
  2576. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2577. &ok, NULL);
  2578. if (!ok) {
  2579. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2580. (char*)smartlist_get(args, 1));
  2581. ap_conn = NULL;
  2582. }
  2583. }
  2584. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2585. smartlist_free(args);
  2586. if (!ap_conn)
  2587. return 0;
  2588. connection_mark_unattached_ap(ap_conn, reason);
  2589. send_control_done(conn);
  2590. return 0;
  2591. }
  2592. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2593. * and report success or failure. */
  2594. static int
  2595. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2596. const char *body)
  2597. {
  2598. origin_circuit_t *circ = NULL;
  2599. int safe = 0;
  2600. smartlist_t *args;
  2601. (void) len;
  2602. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2603. if (!args)
  2604. return 0;
  2605. if (!(circ=get_circ(smartlist_get(args, 0))))
  2606. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2607. (char*)smartlist_get(args, 0));
  2608. else {
  2609. int i;
  2610. for (i=1; i < smartlist_len(args); ++i) {
  2611. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2612. safe = 1;
  2613. else
  2614. log_info(LD_CONTROL, "Skipping unknown option %s",
  2615. (char*)smartlist_get(args,i));
  2616. }
  2617. }
  2618. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2619. smartlist_free(args);
  2620. if (!circ)
  2621. return 0;
  2622. if (!safe || !circ->p_streams) {
  2623. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2624. }
  2625. send_control_done(conn);
  2626. return 0;
  2627. }
  2628. /** Called when we get a RESOLVE command: start trying to resolve
  2629. * the listed addresses. */
  2630. static int
  2631. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2632. const char *body)
  2633. {
  2634. smartlist_t *args, *failed;
  2635. int is_reverse = 0;
  2636. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2637. if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
  2638. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2639. "isn't listening for ADDRMAP events. It probably won't see "
  2640. "the answer.");
  2641. }
  2642. args = smartlist_new();
  2643. smartlist_split_string(args, body, " ",
  2644. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2645. {
  2646. const char *modearg = find_element_starting_with(args, 0, "mode=");
  2647. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  2648. is_reverse = 1;
  2649. }
  2650. failed = smartlist_new();
  2651. SMARTLIST_FOREACH(args, const char *, arg, {
  2652. if (!is_keyval_pair(arg)) {
  2653. if (dnsserv_launch_request(arg, is_reverse, conn)<0)
  2654. smartlist_add(failed, (char*)arg);
  2655. }
  2656. });
  2657. send_control_done(conn);
  2658. SMARTLIST_FOREACH(failed, const char *, arg, {
  2659. control_event_address_mapped(arg, arg, time(NULL),
  2660. "internal", 0);
  2661. });
  2662. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2663. smartlist_free(args);
  2664. smartlist_free(failed);
  2665. return 0;
  2666. }
  2667. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  2668. static int
  2669. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  2670. const char *body)
  2671. {
  2672. const char *bad_arg = NULL;
  2673. smartlist_t *args;
  2674. (void)len;
  2675. conn->have_sent_protocolinfo = 1;
  2676. args = smartlist_new();
  2677. smartlist_split_string(args, body, " ",
  2678. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2679. SMARTLIST_FOREACH(args, const char *, arg, {
  2680. int ok;
  2681. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  2682. if (!ok) {
  2683. bad_arg = arg;
  2684. break;
  2685. }
  2686. });
  2687. if (bad_arg) {
  2688. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  2689. escaped(bad_arg));
  2690. /* Don't tolerate bad arguments when not authenticated. */
  2691. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  2692. connection_mark_for_close(TO_CONN(conn));
  2693. goto done;
  2694. } else {
  2695. const or_options_t *options = get_options();
  2696. int cookies = options->CookieAuthentication;
  2697. char *cfile = get_cookie_file();
  2698. char *abs_cfile;
  2699. char *esc_cfile;
  2700. char *methods;
  2701. abs_cfile = make_path_absolute(cfile);
  2702. esc_cfile = esc_for_log(abs_cfile);
  2703. {
  2704. int passwd = (options->HashedControlPassword != NULL ||
  2705. options->HashedControlSessionPassword != NULL);
  2706. smartlist_t *mlist = smartlist_new();
  2707. if (cookies) {
  2708. smartlist_add(mlist, (char*)"COOKIE");
  2709. smartlist_add(mlist, (char*)"SAFECOOKIE");
  2710. }
  2711. if (passwd)
  2712. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  2713. if (!cookies && !passwd)
  2714. smartlist_add(mlist, (char*)"NULL");
  2715. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  2716. smartlist_free(mlist);
  2717. }
  2718. connection_printf_to_buf(conn,
  2719. "250-PROTOCOLINFO 1\r\n"
  2720. "250-AUTH METHODS=%s%s%s\r\n"
  2721. "250-VERSION Tor=%s\r\n"
  2722. "250 OK\r\n",
  2723. methods,
  2724. cookies?" COOKIEFILE=":"",
  2725. cookies?esc_cfile:"",
  2726. escaped(VERSION));
  2727. tor_free(methods);
  2728. tor_free(cfile);
  2729. tor_free(abs_cfile);
  2730. tor_free(esc_cfile);
  2731. }
  2732. done:
  2733. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2734. smartlist_free(args);
  2735. return 0;
  2736. }
  2737. /** Called when we get an AUTHCHALLENGE command. */
  2738. static int
  2739. handle_control_authchallenge(control_connection_t *conn, uint32_t len,
  2740. const char *body)
  2741. {
  2742. const char *cp = body;
  2743. char *client_nonce;
  2744. size_t client_nonce_len;
  2745. char server_hash[DIGEST256_LEN];
  2746. char server_hash_encoded[HEX_DIGEST256_LEN+1];
  2747. char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
  2748. char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
  2749. cp += strspn(cp, " \t\n\r");
  2750. if (!strcasecmpstart(cp, "SAFECOOKIE")) {
  2751. cp += strlen("SAFECOOKIE");
  2752. } else {
  2753. connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
  2754. "authentication\r\n", conn);
  2755. connection_mark_for_close(TO_CONN(conn));
  2756. return -1;
  2757. }
  2758. if (!authentication_cookie_is_set) {
  2759. connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
  2760. conn);
  2761. connection_mark_for_close(TO_CONN(conn));
  2762. return -1;
  2763. }
  2764. cp += strspn(cp, " \t\n\r");
  2765. if (*cp == '"') {
  2766. const char *newcp =
  2767. decode_escaped_string(cp, len - (cp - body),
  2768. &client_nonce, &client_nonce_len);
  2769. if (newcp == NULL) {
  2770. connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
  2771. conn);
  2772. connection_mark_for_close(TO_CONN(conn));
  2773. return -1;
  2774. }
  2775. cp = newcp;
  2776. } else {
  2777. size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
  2778. client_nonce_len = client_nonce_encoded_len / 2;
  2779. client_nonce = tor_malloc_zero(client_nonce_len);
  2780. if (base16_decode(client_nonce, client_nonce_len,
  2781. cp, client_nonce_encoded_len) < 0) {
  2782. connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
  2783. conn);
  2784. connection_mark_for_close(TO_CONN(conn));
  2785. tor_free(client_nonce);
  2786. return -1;
  2787. }
  2788. cp += client_nonce_encoded_len;
  2789. }
  2790. cp += strspn(cp, " \t\n\r");
  2791. if (*cp != '\0' ||
  2792. cp != body + len) {
  2793. connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
  2794. conn);
  2795. connection_mark_for_close(TO_CONN(conn));
  2796. tor_free(client_nonce);
  2797. return -1;
  2798. }
  2799. tor_assert(!crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN));
  2800. /* Now compute and send the server-to-controller response, and the
  2801. * server's nonce. */
  2802. tor_assert(authentication_cookie != NULL);
  2803. {
  2804. size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
  2805. client_nonce_len +
  2806. SAFECOOKIE_SERVER_NONCE_LEN);
  2807. char *tmp = tor_malloc_zero(tmp_len);
  2808. char *client_hash = tor_malloc_zero(DIGEST256_LEN);
  2809. memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2810. memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
  2811. memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
  2812. server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  2813. crypto_hmac_sha256(server_hash,
  2814. SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
  2815. strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
  2816. tmp,
  2817. tmp_len);
  2818. crypto_hmac_sha256(client_hash,
  2819. SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
  2820. strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
  2821. tmp,
  2822. tmp_len);
  2823. conn->safecookie_client_hash = client_hash;
  2824. tor_free(tmp);
  2825. }
  2826. base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
  2827. server_hash, sizeof(server_hash));
  2828. base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
  2829. server_nonce, sizeof(server_nonce));
  2830. connection_printf_to_buf(conn,
  2831. "250 AUTHCHALLENGE SERVERHASH=%s "
  2832. "SERVERNONCE=%s\r\n",
  2833. server_hash_encoded,
  2834. server_nonce_encoded);
  2835. tor_free(client_nonce);
  2836. return 0;
  2837. }
  2838. /** Called when we get a USEFEATURE command: parse the feature list, and
  2839. * set up the control_connection's options properly. */
  2840. static int
  2841. handle_control_usefeature(control_connection_t *conn,
  2842. uint32_t len,
  2843. const char *body)
  2844. {
  2845. smartlist_t *args;
  2846. int bad = 0;
  2847. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2848. args = smartlist_new();
  2849. smartlist_split_string(args, body, " ",
  2850. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2851. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  2852. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2853. ;
  2854. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  2855. ;
  2856. else {
  2857. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2858. arg);
  2859. bad = 1;
  2860. break;
  2861. }
  2862. } SMARTLIST_FOREACH_END(arg);
  2863. if (!bad) {
  2864. send_control_done(conn);
  2865. }
  2866. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2867. smartlist_free(args);
  2868. return 0;
  2869. }
  2870. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2871. int
  2872. connection_control_finished_flushing(control_connection_t *conn)
  2873. {
  2874. tor_assert(conn);
  2875. return 0;
  2876. }
  2877. /** Called when <b>conn</b> has gotten its socket closed. */
  2878. int
  2879. connection_control_reached_eof(control_connection_t *conn)
  2880. {
  2881. tor_assert(conn);
  2882. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2883. connection_mark_for_close(TO_CONN(conn));
  2884. return 0;
  2885. }
  2886. /** Shut down this Tor instance in the same way that SIGINT would, but
  2887. * with a log message appropriate for the loss of an owning controller. */
  2888. static void
  2889. lost_owning_controller(const char *owner_type, const char *loss_manner)
  2890. {
  2891. int shutdown_slowly = server_mode(get_options());
  2892. log_notice(LD_CONTROL, "Owning controller %s has %s -- %s.",
  2893. owner_type, loss_manner,
  2894. shutdown_slowly ? "shutting down" : "exiting now");
  2895. /* XXXX Perhaps this chunk of code should be a separate function,
  2896. * called here and by process_signal(SIGINT). */
  2897. if (!shutdown_slowly) {
  2898. tor_cleanup();
  2899. exit(0);
  2900. }
  2901. /* XXXX This will close all listening sockets except control-port
  2902. * listeners. Perhaps we should close those too. */
  2903. hibernate_begin_shutdown();
  2904. }
  2905. /** Called when <b>conn</b> is being freed. */
  2906. void
  2907. connection_control_closed(control_connection_t *conn)
  2908. {
  2909. tor_assert(conn);
  2910. conn->event_mask = 0;
  2911. control_update_global_event_mask();
  2912. if (conn->is_owning_control_connection) {
  2913. lost_owning_controller("connection", "closed");
  2914. }
  2915. }
  2916. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  2917. * stage of the protocol. */
  2918. static int
  2919. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  2920. {
  2921. if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
  2922. return 1;
  2923. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  2924. return (!conn->have_sent_protocolinfo &&
  2925. conn->safecookie_client_hash == NULL);
  2926. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  2927. return (conn->safecookie_client_hash == NULL);
  2928. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  2929. !strcasecmp(cmd, "QUIT"))
  2930. return 1;
  2931. return 0;
  2932. }
  2933. /** Do not accept any control command of more than 1MB in length. Anything
  2934. * that needs to be anywhere near this long probably means that one of our
  2935. * interfaces is broken. */
  2936. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  2937. /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
  2938. * interface as those underlying functions, but takes a connection_t intead of
  2939. * an evbuffer or a buf_t.
  2940. */
  2941. static int
  2942. peek_connection_has_control0_command(connection_t *conn)
  2943. {
  2944. IF_HAS_BUFFEREVENT(conn, {
  2945. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  2946. return peek_evbuffer_has_control0_command(input);
  2947. }) ELSE_IF_NO_BUFFEREVENT {
  2948. return peek_buf_has_control0_command(conn->inbuf);
  2949. }
  2950. }
  2951. /** Called when data has arrived on a v1 control connection: Try to fetch
  2952. * commands from conn->inbuf, and execute them.
  2953. */
  2954. int
  2955. connection_control_process_inbuf(control_connection_t *conn)
  2956. {
  2957. size_t data_len;
  2958. uint32_t cmd_data_len;
  2959. int cmd_len;
  2960. char *args;
  2961. tor_assert(conn);
  2962. tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
  2963. conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
  2964. if (!conn->incoming_cmd) {
  2965. conn->incoming_cmd = tor_malloc(1024);
  2966. conn->incoming_cmd_len = 1024;
  2967. conn->incoming_cmd_cur_len = 0;
  2968. }
  2969. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2970. peek_connection_has_control0_command(TO_CONN(conn))) {
  2971. /* Detect v0 commands and send a "no more v0" message. */
  2972. size_t body_len;
  2973. char buf[128];
  2974. set_uint16(buf+2, htons(0x0000)); /* type == error */
  2975. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  2976. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  2977. "and later; upgrade your controller.",
  2978. sizeof(buf)-6);
  2979. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  2980. set_uint16(buf+0, htons(body_len));
  2981. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  2982. connection_mark_and_flush(TO_CONN(conn));
  2983. return 0;
  2984. }
  2985. again:
  2986. while (1) {
  2987. size_t last_idx;
  2988. int r;
  2989. /* First, fetch a line. */
  2990. do {
  2991. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2992. r = connection_fetch_from_buf_line(TO_CONN(conn),
  2993. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2994. &data_len);
  2995. if (r == 0)
  2996. /* Line not all here yet. Wait. */
  2997. return 0;
  2998. else if (r == -1) {
  2999. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  3000. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  3001. connection_stop_reading(TO_CONN(conn));
  3002. connection_mark_and_flush(TO_CONN(conn));
  3003. }
  3004. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  3005. conn->incoming_cmd_len *= 2;
  3006. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  3007. conn->incoming_cmd_len);
  3008. }
  3009. } while (r != 1);
  3010. tor_assert(data_len);
  3011. last_idx = conn->incoming_cmd_cur_len;
  3012. conn->incoming_cmd_cur_len += (int)data_len;
  3013. /* We have appended a line to incoming_cmd. Is the command done? */
  3014. if (last_idx == 0 && *conn->incoming_cmd != '+')
  3015. /* One line command, didn't start with '+'. */
  3016. break;
  3017. /* XXXX this code duplication is kind of dumb. */
  3018. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  3019. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  3020. /* Just appended ".\r\n"; we're done. Remove it. */
  3021. conn->incoming_cmd[last_idx] = '\0';
  3022. conn->incoming_cmd_cur_len -= 3;
  3023. break;
  3024. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  3025. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  3026. /* Just appended ".\n"; we're done. Remove it. */
  3027. conn->incoming_cmd[last_idx] = '\0';
  3028. conn->incoming_cmd_cur_len -= 2;
  3029. break;
  3030. }
  3031. /* Otherwise, read another line. */
  3032. }
  3033. data_len = conn->incoming_cmd_cur_len;
  3034. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  3035. * recognize it.
  3036. */
  3037. cmd_len = 0;
  3038. while ((size_t)cmd_len < data_len
  3039. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  3040. ++cmd_len;
  3041. conn->incoming_cmd[cmd_len]='\0';
  3042. args = conn->incoming_cmd+cmd_len+1;
  3043. tor_assert(data_len>(size_t)cmd_len);
  3044. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  3045. while (TOR_ISSPACE(*args)) {
  3046. ++args;
  3047. --data_len;
  3048. }
  3049. /* If the connection is already closing, ignore further commands */
  3050. if (TO_CONN(conn)->marked_for_close) {
  3051. return 0;
  3052. }
  3053. /* Otherwise, Quit is always valid. */
  3054. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  3055. connection_write_str_to_buf("250 closing connection\r\n", conn);
  3056. connection_mark_and_flush(TO_CONN(conn));
  3057. return 0;
  3058. }
  3059. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3060. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  3061. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  3062. connection_mark_for_close(TO_CONN(conn));
  3063. return 0;
  3064. }
  3065. if (data_len >= UINT32_MAX) {
  3066. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  3067. connection_mark_for_close(TO_CONN(conn));
  3068. return 0;
  3069. }
  3070. /* XXXX Why is this not implemented as a table like the GETINFO
  3071. * items are? Even handling the plus signs at the beginnings of
  3072. * commands wouldn't be very hard with proper macros. */
  3073. cmd_data_len = (uint32_t)data_len;
  3074. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  3075. if (handle_control_setconf(conn, cmd_data_len, args))
  3076. return -1;
  3077. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  3078. if (handle_control_resetconf(conn, cmd_data_len, args))
  3079. return -1;
  3080. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  3081. if (handle_control_getconf(conn, cmd_data_len, args))
  3082. return -1;
  3083. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  3084. if (handle_control_loadconf(conn, cmd_data_len, args))
  3085. return -1;
  3086. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  3087. if (handle_control_setevents(conn, cmd_data_len, args))
  3088. return -1;
  3089. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  3090. if (handle_control_authenticate(conn, cmd_data_len, args))
  3091. return -1;
  3092. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  3093. if (handle_control_saveconf(conn, cmd_data_len, args))
  3094. return -1;
  3095. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  3096. if (handle_control_signal(conn, cmd_data_len, args))
  3097. return -1;
  3098. } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
  3099. if (handle_control_takeownership(conn, cmd_data_len, args))
  3100. return -1;
  3101. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  3102. if (handle_control_mapaddress(conn, cmd_data_len, args))
  3103. return -1;
  3104. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  3105. if (handle_control_getinfo(conn, cmd_data_len, args))
  3106. return -1;
  3107. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  3108. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  3109. return -1;
  3110. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  3111. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  3112. return -1;
  3113. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  3114. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  3115. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  3116. if (handle_control_attachstream(conn, cmd_data_len, args))
  3117. return -1;
  3118. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  3119. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  3120. return -1;
  3121. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  3122. if (handle_control_redirectstream(conn, cmd_data_len, args))
  3123. return -1;
  3124. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  3125. if (handle_control_closestream(conn, cmd_data_len, args))
  3126. return -1;
  3127. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  3128. if (handle_control_closecircuit(conn, cmd_data_len, args))
  3129. return -1;
  3130. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  3131. if (handle_control_usefeature(conn, cmd_data_len, args))
  3132. return -1;
  3133. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  3134. if (handle_control_resolve(conn, cmd_data_len, args))
  3135. return -1;
  3136. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  3137. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  3138. return -1;
  3139. } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
  3140. if (handle_control_authchallenge(conn, cmd_data_len, args))
  3141. return -1;
  3142. } else {
  3143. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  3144. conn->incoming_cmd);
  3145. }
  3146. conn->incoming_cmd_cur_len = 0;
  3147. goto again;
  3148. }
  3149. /** Something major has happened to circuit <b>circ</b>: tell any
  3150. * interested control connections. */
  3151. int
  3152. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  3153. int reason_code)
  3154. {
  3155. const char *status;
  3156. char reasons[64] = "";
  3157. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  3158. return 0;
  3159. tor_assert(circ);
  3160. switch (tp)
  3161. {
  3162. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3163. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  3164. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  3165. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  3166. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  3167. default:
  3168. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3169. tor_fragile_assert();
  3170. return 0;
  3171. }
  3172. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  3173. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  3174. char unk_reason_buf[16];
  3175. if (!reason_str) {
  3176. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  3177. reason_str = unk_reason_buf;
  3178. }
  3179. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  3180. tor_snprintf(reasons, sizeof(reasons),
  3181. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  3182. } else {
  3183. tor_snprintf(reasons, sizeof(reasons),
  3184. " REASON=%s", reason_str);
  3185. }
  3186. }
  3187. {
  3188. char *circdesc = circuit_describe_status_for_controller(circ);
  3189. const char *sp = strlen(circdesc) ? " " : "";
  3190. send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
  3191. "650 CIRC %lu %s%s%s%s\r\n",
  3192. (unsigned long)circ->global_identifier,
  3193. status, sp,
  3194. circdesc,
  3195. reasons);
  3196. tor_free(circdesc);
  3197. }
  3198. return 0;
  3199. }
  3200. /** Something minor has happened to circuit <b>circ</b>: tell any
  3201. * interested control connections. */
  3202. static int
  3203. control_event_circuit_status_minor(origin_circuit_t *circ,
  3204. circuit_status_minor_event_t e,
  3205. int purpose, const struct timeval *tv)
  3206. {
  3207. const char *event_desc;
  3208. char event_tail[160] = "";
  3209. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  3210. return 0;
  3211. tor_assert(circ);
  3212. switch (e)
  3213. {
  3214. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  3215. event_desc = "PURPOSE_CHANGED";
  3216. {
  3217. /* event_tail can currently be up to 68 chars long */
  3218. const char *hs_state_str =
  3219. circuit_purpose_to_controller_hs_state_string(purpose);
  3220. tor_snprintf(event_tail, sizeof(event_tail),
  3221. " OLD_PURPOSE=%s%s%s",
  3222. circuit_purpose_to_controller_string(purpose),
  3223. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3224. (hs_state_str != NULL) ? hs_state_str : "");
  3225. }
  3226. break;
  3227. case CIRC_MINOR_EVENT_CANNIBALIZED:
  3228. event_desc = "CANNIBALIZED";
  3229. {
  3230. /* event_tail can currently be up to 130 chars long */
  3231. const char *hs_state_str =
  3232. circuit_purpose_to_controller_hs_state_string(purpose);
  3233. const struct timeval *old_timestamp_began = tv;
  3234. char tbuf[ISO_TIME_USEC_LEN+1];
  3235. format_iso_time_nospace_usec(tbuf, old_timestamp_began);
  3236. tor_snprintf(event_tail, sizeof(event_tail),
  3237. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  3238. circuit_purpose_to_controller_string(purpose),
  3239. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3240. (hs_state_str != NULL) ? hs_state_str : "",
  3241. tbuf);
  3242. }
  3243. break;
  3244. default:
  3245. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  3246. tor_fragile_assert();
  3247. return 0;
  3248. }
  3249. {
  3250. char *circdesc = circuit_describe_status_for_controller(circ);
  3251. const char *sp = strlen(circdesc) ? " " : "";
  3252. send_control_event(EVENT_CIRCUIT_STATUS_MINOR, ALL_FORMATS,
  3253. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  3254. (unsigned long)circ->global_identifier,
  3255. event_desc, sp,
  3256. circdesc,
  3257. event_tail);
  3258. tor_free(circdesc);
  3259. }
  3260. return 0;
  3261. }
  3262. /**
  3263. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  3264. * interested controllers.
  3265. */
  3266. int
  3267. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  3268. int old_purpose)
  3269. {
  3270. return control_event_circuit_status_minor(circ,
  3271. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  3272. old_purpose,
  3273. NULL);
  3274. }
  3275. /**
  3276. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  3277. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  3278. */
  3279. int
  3280. control_event_circuit_cannibalized(origin_circuit_t *circ,
  3281. int old_purpose,
  3282. const struct timeval *old_tv_created)
  3283. {
  3284. return control_event_circuit_status_minor(circ,
  3285. CIRC_MINOR_EVENT_CANNIBALIZED,
  3286. old_purpose,
  3287. old_tv_created);
  3288. }
  3289. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  3290. * <b>buf</b>, determine the address:port combination requested on
  3291. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  3292. * failure. */
  3293. static int
  3294. write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
  3295. {
  3296. char buf2[256];
  3297. if (conn->chosen_exit_name)
  3298. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  3299. return -1;
  3300. if (!conn->socks_request)
  3301. return -1;
  3302. if (tor_snprintf(buf, len, "%s%s%s:%d",
  3303. conn->socks_request->address,
  3304. conn->chosen_exit_name ? buf2 : "",
  3305. !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
  3306. ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
  3307. conn->socks_request->port)<0)
  3308. return -1;
  3309. return 0;
  3310. }
  3311. /** Something has happened to the stream associated with AP connection
  3312. * <b>conn</b>: tell any interested control connections. */
  3313. int
  3314. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  3315. int reason_code)
  3316. {
  3317. char reason_buf[64];
  3318. char addrport_buf[64];
  3319. const char *status;
  3320. circuit_t *circ;
  3321. origin_circuit_t *origin_circ = NULL;
  3322. char buf[256];
  3323. const char *purpose = "";
  3324. tor_assert(conn->socks_request);
  3325. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  3326. return 0;
  3327. if (tp == STREAM_EVENT_CLOSED &&
  3328. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  3329. return 0;
  3330. write_stream_target_to_buf(conn, buf, sizeof(buf));
  3331. reason_buf[0] = '\0';
  3332. switch (tp)
  3333. {
  3334. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  3335. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  3336. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  3337. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  3338. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  3339. case STREAM_EVENT_NEW: status = "NEW"; break;
  3340. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  3341. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  3342. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  3343. default:
  3344. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3345. return 0;
  3346. }
  3347. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  3348. tp == STREAM_EVENT_CLOSED ||
  3349. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  3350. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  3351. char *r = NULL;
  3352. if (!reason_str) {
  3353. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  3354. reason_str = r;
  3355. }
  3356. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  3357. tor_snprintf(reason_buf, sizeof(reason_buf),
  3358. " REASON=END REMOTE_REASON=%s", reason_str);
  3359. else
  3360. tor_snprintf(reason_buf, sizeof(reason_buf),
  3361. " REASON=%s", reason_str);
  3362. tor_free(r);
  3363. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  3364. switch (reason_code) {
  3365. case REMAP_STREAM_SOURCE_CACHE:
  3366. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  3367. break;
  3368. case REMAP_STREAM_SOURCE_EXIT:
  3369. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  3370. break;
  3371. default:
  3372. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  3373. reason_code);
  3374. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  3375. break;
  3376. }
  3377. }
  3378. if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
  3379. /*
  3380. * When the control conn is an AF_UNIX socket and we have no address,
  3381. * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
  3382. * dnsserv.c.
  3383. */
  3384. if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
  3385. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  3386. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  3387. } else {
  3388. /*
  3389. * else leave it blank so control on AF_UNIX doesn't need to make
  3390. * something up.
  3391. */
  3392. addrport_buf[0] = '\0';
  3393. }
  3394. } else {
  3395. addrport_buf[0] = '\0';
  3396. }
  3397. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  3398. purpose = " PURPOSE=DNS_REQUEST";
  3399. } else if (tp == STREAM_EVENT_NEW) {
  3400. if (conn->use_begindir) {
  3401. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  3402. int linked_dir_purpose = -1;
  3403. if (linked && linked->type == CONN_TYPE_DIR)
  3404. linked_dir_purpose = linked->purpose;
  3405. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  3406. purpose = " PURPOSE=DIR_UPLOAD";
  3407. else
  3408. purpose = " PURPOSE=DIR_FETCH";
  3409. } else
  3410. purpose = " PURPOSE=USER";
  3411. }
  3412. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  3413. if (circ && CIRCUIT_IS_ORIGIN(circ))
  3414. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3415. send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
  3416. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  3417. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  3418. status,
  3419. origin_circ?
  3420. (unsigned long)origin_circ->global_identifier : 0ul,
  3421. buf, reason_buf, addrport_buf, purpose);
  3422. /* XXX need to specify its intended exit, etc? */
  3423. return 0;
  3424. }
  3425. /** Figure out the best name for the target router of an OR connection
  3426. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  3427. * <b>name</b>. */
  3428. static void
  3429. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  3430. {
  3431. const node_t *node = node_get_by_id(conn->identity_digest);
  3432. if (node) {
  3433. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  3434. node_get_verbose_nickname(node, name);
  3435. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  3436. name[0] = '$';
  3437. base16_encode(name+1, len-1, conn->identity_digest,
  3438. DIGEST_LEN);
  3439. } else {
  3440. tor_snprintf(name, len, "%s:%d",
  3441. conn->base_.address, conn->base_.port);
  3442. }
  3443. }
  3444. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  3445. * interested control connections. <b>tp</b> is the new status for the
  3446. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  3447. * may be the reason why.
  3448. */
  3449. int
  3450. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  3451. int reason)
  3452. {
  3453. int ncircs = 0;
  3454. const char *status;
  3455. char name[128];
  3456. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  3457. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  3458. return 0;
  3459. switch (tp)
  3460. {
  3461. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3462. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  3463. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  3464. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  3465. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  3466. default:
  3467. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3468. return 0;
  3469. }
  3470. if (conn->chan) {
  3471. ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
  3472. } else {
  3473. ncircs = 0;
  3474. }
  3475. ncircs += connection_or_get_num_circuits(conn);
  3476. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  3477. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
  3478. reason ? " " : "", ncircs);
  3479. }
  3480. orconn_target_get_name(name, sizeof(name), conn);
  3481. send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
  3482. "650 ORCONN %s %s %s%s%s\r\n",
  3483. name, status,
  3484. reason ? "REASON=" : "",
  3485. orconn_end_reason_to_control_string(reason),
  3486. ncircs_buf);
  3487. return 0;
  3488. }
  3489. /**
  3490. * Print out STREAM_BW event for a single conn
  3491. */
  3492. int
  3493. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  3494. {
  3495. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3496. if (!edge_conn->n_read && !edge_conn->n_written)
  3497. return 0;
  3498. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3499. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3500. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  3501. (unsigned long)edge_conn->n_read,
  3502. (unsigned long)edge_conn->n_written);
  3503. edge_conn->n_written = edge_conn->n_read = 0;
  3504. }
  3505. return 0;
  3506. }
  3507. /** A second or more has elapsed: tell any interested control
  3508. * connections how much bandwidth streams have used. */
  3509. int
  3510. control_event_stream_bandwidth_used(void)
  3511. {
  3512. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3513. smartlist_t *conns = get_connection_array();
  3514. edge_connection_t *edge_conn;
  3515. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  3516. {
  3517. if (conn->type != CONN_TYPE_AP)
  3518. continue;
  3519. edge_conn = TO_EDGE_CONN(conn);
  3520. if (!edge_conn->n_read && !edge_conn->n_written)
  3521. continue;
  3522. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3523. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3524. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  3525. (unsigned long)edge_conn->n_read,
  3526. (unsigned long)edge_conn->n_written);
  3527. edge_conn->n_written = edge_conn->n_read = 0;
  3528. }
  3529. SMARTLIST_FOREACH_END(conn);
  3530. }
  3531. return 0;
  3532. }
  3533. /** A second or more has elapsed: tell any interested control
  3534. * connections how much bandwidth we used. */
  3535. int
  3536. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  3537. {
  3538. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  3539. send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
  3540. "650 BW %lu %lu\r\n",
  3541. (unsigned long)n_read,
  3542. (unsigned long)n_written);
  3543. }
  3544. return 0;
  3545. }
  3546. /** Called when we are sending a log message to the controllers: suspend
  3547. * sending further log messages to the controllers until we're done. Used by
  3548. * CONN_LOG_PROTECT. */
  3549. void
  3550. disable_control_logging(void)
  3551. {
  3552. ++disable_log_messages;
  3553. }
  3554. /** We're done sending a log message to the controllers: re-enable controller
  3555. * logging. Used by CONN_LOG_PROTECT. */
  3556. void
  3557. enable_control_logging(void)
  3558. {
  3559. if (--disable_log_messages < 0)
  3560. tor_assert(0);
  3561. }
  3562. /** We got a log message: tell any interested control connections. */
  3563. void
  3564. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  3565. {
  3566. int event;
  3567. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  3568. * thread. */
  3569. if (! in_main_thread())
  3570. return;
  3571. if (disable_log_messages)
  3572. return;
  3573. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  3574. severity <= LOG_NOTICE) {
  3575. char *esc = esc_for_log(msg);
  3576. ++disable_log_messages;
  3577. control_event_general_status(severity, "BUG REASON=%s", esc);
  3578. --disable_log_messages;
  3579. tor_free(esc);
  3580. }
  3581. event = log_severity_to_event(severity);
  3582. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  3583. char *b = NULL;
  3584. const char *s;
  3585. if (strchr(msg, '\n')) {
  3586. char *cp;
  3587. b = tor_strdup(msg);
  3588. for (cp = b; *cp; ++cp)
  3589. if (*cp == '\r' || *cp == '\n')
  3590. *cp = ' ';
  3591. }
  3592. switch (severity) {
  3593. case LOG_DEBUG: s = "DEBUG"; break;
  3594. case LOG_INFO: s = "INFO"; break;
  3595. case LOG_NOTICE: s = "NOTICE"; break;
  3596. case LOG_WARN: s = "WARN"; break;
  3597. case LOG_ERR: s = "ERR"; break;
  3598. default: s = "UnknownLogSeverity"; break;
  3599. }
  3600. ++disable_log_messages;
  3601. send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
  3602. --disable_log_messages;
  3603. tor_free(b);
  3604. }
  3605. }
  3606. /** Called whenever we receive new router descriptors: tell any
  3607. * interested control connections. <b>routers</b> is a list of
  3608. * routerinfo_t's.
  3609. */
  3610. int
  3611. control_event_descriptors_changed(smartlist_t *routers)
  3612. {
  3613. char *msg;
  3614. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  3615. return 0;
  3616. {
  3617. smartlist_t *names = smartlist_new();
  3618. char *ids;
  3619. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  3620. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  3621. router_get_verbose_nickname(b, ri);
  3622. smartlist_add(names, b);
  3623. });
  3624. ids = smartlist_join_strings(names, " ", 0, NULL);
  3625. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  3626. send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
  3627. tor_free(ids);
  3628. tor_free(msg);
  3629. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  3630. smartlist_free(names);
  3631. }
  3632. return 0;
  3633. }
  3634. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  3635. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  3636. * <b>error</b> is non-NULL, it is an error code describing the failure
  3637. * mode of the mapping.
  3638. */
  3639. int
  3640. control_event_address_mapped(const char *from, const char *to, time_t expires,
  3641. const char *error, const int cached)
  3642. {
  3643. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  3644. return 0;
  3645. if (expires < 3 || expires == TIME_MAX)
  3646. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3647. "650 ADDRMAP %s %s NEVER %s%s"
  3648. "CACHED=\"%s\"\r\n",
  3649. from, to, error?error:"", error?" ":"",
  3650. cached?"YES":"NO");
  3651. else {
  3652. char buf[ISO_TIME_LEN+1];
  3653. char buf2[ISO_TIME_LEN+1];
  3654. format_local_iso_time(buf,expires);
  3655. format_iso_time(buf2,expires);
  3656. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3657. "650 ADDRMAP %s %s \"%s\""
  3658. " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
  3659. from, to, buf,
  3660. error?error:"", error?" ":"",
  3661. buf2, cached?"YES":"NO");
  3662. }
  3663. return 0;
  3664. }
  3665. /** The authoritative dirserver has received a new descriptor that
  3666. * has passed basic syntax checks and is properly self-signed.
  3667. *
  3668. * Notify any interested party of the new descriptor and what has
  3669. * been done with it, and also optionally give an explanation/reason. */
  3670. int
  3671. control_event_or_authdir_new_descriptor(const char *action,
  3672. const char *desc, size_t desclen,
  3673. const char *msg)
  3674. {
  3675. char firstline[1024];
  3676. char *buf;
  3677. size_t totallen;
  3678. char *esc = NULL;
  3679. size_t esclen;
  3680. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  3681. return 0;
  3682. tor_snprintf(firstline, sizeof(firstline),
  3683. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  3684. action,
  3685. msg ? msg : "");
  3686. /* Escape the server descriptor properly */
  3687. esclen = write_escaped_data(desc, desclen, &esc);
  3688. totallen = strlen(firstline) + esclen + 1;
  3689. buf = tor_malloc(totallen);
  3690. strlcpy(buf, firstline, totallen);
  3691. strlcpy(buf+strlen(firstline), esc, totallen);
  3692. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3693. buf);
  3694. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3695. "650 OK\r\n");
  3696. tor_free(esc);
  3697. tor_free(buf);
  3698. return 0;
  3699. }
  3700. /** Helper function for NS-style events. Constructs and sends an event
  3701. * of type <b>event</b> with string <b>event_string</b> out of the set of
  3702. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  3703. * and NEWCONSENSUS events. */
  3704. static int
  3705. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  3706. uint16_t event,
  3707. const char *event_string)
  3708. {
  3709. smartlist_t *strs;
  3710. char *s, *esc = NULL;
  3711. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  3712. return 0;
  3713. strs = smartlist_new();
  3714. smartlist_add(strs, tor_strdup("650+"));
  3715. smartlist_add(strs, tor_strdup(event_string));
  3716. smartlist_add(strs, tor_strdup("\r\n"));
  3717. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  3718. {
  3719. s = networkstatus_getinfo_helper_single(rs);
  3720. if (!s) continue;
  3721. smartlist_add(strs, s);
  3722. });
  3723. s = smartlist_join_strings(strs, "", 0, NULL);
  3724. write_escaped_data(s, strlen(s), &esc);
  3725. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  3726. smartlist_free(strs);
  3727. tor_free(s);
  3728. send_control_event_string(event, ALL_FORMATS, esc);
  3729. send_control_event_string(event, ALL_FORMATS,
  3730. "650 OK\r\n");
  3731. tor_free(esc);
  3732. return 0;
  3733. }
  3734. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  3735. * an NS event to any controller that cares. */
  3736. int
  3737. control_event_networkstatus_changed(smartlist_t *statuses)
  3738. {
  3739. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  3740. }
  3741. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  3742. * event consisting of an NS-style line for each relay in the consensus. */
  3743. int
  3744. control_event_newconsensus(const networkstatus_t *consensus)
  3745. {
  3746. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  3747. return 0;
  3748. return control_event_networkstatus_changed_helper(
  3749. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  3750. }
  3751. /** Called when we compute a new circuitbuildtimeout */
  3752. int
  3753. control_event_buildtimeout_set(buildtimeout_set_event_t type,
  3754. const char *args)
  3755. {
  3756. const char *type_string = NULL;
  3757. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  3758. return 0;
  3759. switch (type) {
  3760. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  3761. type_string = "COMPUTED";
  3762. break;
  3763. case BUILDTIMEOUT_SET_EVENT_RESET:
  3764. type_string = "RESET";
  3765. break;
  3766. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  3767. type_string = "SUSPENDED";
  3768. break;
  3769. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  3770. type_string = "DISCARD";
  3771. break;
  3772. case BUILDTIMEOUT_SET_EVENT_RESUME:
  3773. type_string = "RESUME";
  3774. break;
  3775. default:
  3776. type_string = "UNKNOWN";
  3777. break;
  3778. }
  3779. send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
  3780. "650 BUILDTIMEOUT_SET %s %s\r\n",
  3781. type_string, args);
  3782. return 0;
  3783. }
  3784. /** Called when a signal has been processed from signal_callback */
  3785. int
  3786. control_event_signal(uintptr_t signal)
  3787. {
  3788. const char *signal_string = NULL;
  3789. if (!control_event_is_interesting(EVENT_SIGNAL))
  3790. return 0;
  3791. switch (signal) {
  3792. case SIGHUP:
  3793. signal_string = "RELOAD";
  3794. break;
  3795. case SIGUSR1:
  3796. signal_string = "DUMP";
  3797. break;
  3798. case SIGUSR2:
  3799. signal_string = "DEBUG";
  3800. break;
  3801. case SIGNEWNYM:
  3802. signal_string = "NEWNYM";
  3803. break;
  3804. case SIGCLEARDNSCACHE:
  3805. signal_string = "CLEARDNSCACHE";
  3806. break;
  3807. default:
  3808. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  3809. (unsigned long)signal);
  3810. return -1;
  3811. }
  3812. send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
  3813. signal_string);
  3814. return 0;
  3815. }
  3816. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  3817. * to any controller that cares. */
  3818. int
  3819. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  3820. {
  3821. smartlist_t *statuses;
  3822. int r;
  3823. if (!EVENT_IS_INTERESTING(EVENT_NS))
  3824. return 0;
  3825. statuses = smartlist_new();
  3826. smartlist_add(statuses, (void*)rs);
  3827. r = control_event_networkstatus_changed(statuses);
  3828. smartlist_free(statuses);
  3829. return r;
  3830. }
  3831. /** Our own router descriptor has changed; tell any controllers that care.
  3832. */
  3833. int
  3834. control_event_my_descriptor_changed(void)
  3835. {
  3836. send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
  3837. return 0;
  3838. }
  3839. /** Helper: sends a status event where <b>type</b> is one of
  3840. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  3841. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  3842. * string corresponding to <b>args</b>. */
  3843. static int
  3844. control_event_status(int type, int severity, const char *format, va_list args)
  3845. {
  3846. char *user_buf = NULL;
  3847. char format_buf[160];
  3848. const char *status, *sev;
  3849. switch (type) {
  3850. case EVENT_STATUS_GENERAL:
  3851. status = "STATUS_GENERAL";
  3852. break;
  3853. case EVENT_STATUS_CLIENT:
  3854. status = "STATUS_CLIENT";
  3855. break;
  3856. case EVENT_STATUS_SERVER:
  3857. status = "STATUS_SERVER";
  3858. break;
  3859. default:
  3860. log_warn(LD_BUG, "Unrecognized status type %d", type);
  3861. return -1;
  3862. }
  3863. switch (severity) {
  3864. case LOG_NOTICE:
  3865. sev = "NOTICE";
  3866. break;
  3867. case LOG_WARN:
  3868. sev = "WARN";
  3869. break;
  3870. case LOG_ERR:
  3871. sev = "ERR";
  3872. break;
  3873. default:
  3874. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  3875. return -1;
  3876. }
  3877. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  3878. status, sev)<0) {
  3879. log_warn(LD_BUG, "Format string too long.");
  3880. return -1;
  3881. }
  3882. tor_vasprintf(&user_buf, format, args);
  3883. send_control_event(type, ALL_FORMATS, "%s %s\r\n", format_buf, user_buf);
  3884. tor_free(user_buf);
  3885. return 0;
  3886. }
  3887. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  3888. * by formatting the arguments using the printf-style <b>format</b>. */
  3889. int
  3890. control_event_general_status(int severity, const char *format, ...)
  3891. {
  3892. va_list ap;
  3893. int r;
  3894. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  3895. return 0;
  3896. va_start(ap, format);
  3897. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  3898. va_end(ap);
  3899. return r;
  3900. }
  3901. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  3902. * by formatting the arguments using the printf-style <b>format</b>. */
  3903. int
  3904. control_event_client_status(int severity, const char *format, ...)
  3905. {
  3906. va_list ap;
  3907. int r;
  3908. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  3909. return 0;
  3910. va_start(ap, format);
  3911. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  3912. va_end(ap);
  3913. return r;
  3914. }
  3915. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  3916. * by formatting the arguments using the printf-style <b>format</b>. */
  3917. int
  3918. control_event_server_status(int severity, const char *format, ...)
  3919. {
  3920. va_list ap;
  3921. int r;
  3922. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  3923. return 0;
  3924. va_start(ap, format);
  3925. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  3926. va_end(ap);
  3927. return r;
  3928. }
  3929. /** Called when the status of an entry guard with the given <b>nickname</b>
  3930. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  3931. * controllers that care. */
  3932. int
  3933. control_event_guard(const char *nickname, const char *digest,
  3934. const char *status)
  3935. {
  3936. char hbuf[HEX_DIGEST_LEN+1];
  3937. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  3938. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  3939. return 0;
  3940. {
  3941. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  3942. const node_t *node = node_get_by_id(digest);
  3943. if (node) {
  3944. node_get_verbose_nickname(node, buf);
  3945. } else {
  3946. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  3947. }
  3948. send_control_event(EVENT_GUARD, ALL_FORMATS,
  3949. "650 GUARD ENTRY %s %s\r\n", buf, status);
  3950. }
  3951. return 0;
  3952. }
  3953. /** Called when a configuration option changes. This is generally triggered
  3954. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  3955. * a smartlist_t containing (key, value, ...) pairs in sequence.
  3956. * <b>value</b> can be NULL. */
  3957. int
  3958. control_event_conf_changed(const smartlist_t *elements)
  3959. {
  3960. int i;
  3961. char *result;
  3962. smartlist_t *lines;
  3963. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  3964. smartlist_len(elements) == 0) {
  3965. return 0;
  3966. }
  3967. lines = smartlist_new();
  3968. for (i = 0; i < smartlist_len(elements); i += 2) {
  3969. char *k = smartlist_get(elements, i);
  3970. char *v = smartlist_get(elements, i+1);
  3971. if (v == NULL) {
  3972. smartlist_add_asprintf(lines, "650-%s", k);
  3973. } else {
  3974. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  3975. }
  3976. }
  3977. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  3978. send_control_event(EVENT_CONF_CHANGED, 0,
  3979. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  3980. tor_free(result);
  3981. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  3982. smartlist_free(lines);
  3983. return 0;
  3984. }
  3985. /** Helper: Return a newly allocated string containing a path to the
  3986. * file where we store our authentication cookie. */
  3987. static char *
  3988. get_cookie_file(void)
  3989. {
  3990. const or_options_t *options = get_options();
  3991. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  3992. return tor_strdup(options->CookieAuthFile);
  3993. } else {
  3994. return get_datadir_fname("control_auth_cookie");
  3995. }
  3996. }
  3997. /* Initialize the cookie-based authentication system of the
  3998. * ControlPort. If <b>enabled</b> is 0, then disable the cookie
  3999. * authentication system. */
  4000. int
  4001. init_control_cookie_authentication(int enabled)
  4002. {
  4003. char *fname = NULL;
  4004. int retval;
  4005. if (!enabled) {
  4006. authentication_cookie_is_set = 0;
  4007. return 0;
  4008. }
  4009. fname = get_cookie_file();
  4010. retval = init_cookie_authentication(fname, "", /* no header */
  4011. AUTHENTICATION_COOKIE_LEN,
  4012. &authentication_cookie,
  4013. &authentication_cookie_is_set);
  4014. tor_free(fname);
  4015. return retval;
  4016. }
  4017. /** A copy of the process specifier of Tor's owning controller, or
  4018. * NULL if this Tor instance is not currently owned by a process. */
  4019. static char *owning_controller_process_spec = NULL;
  4020. /** A process-termination monitor for Tor's owning controller, or NULL
  4021. * if this Tor instance is not currently owned by a process. */
  4022. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  4023. /** Process-termination monitor callback for Tor's owning controller
  4024. * process. */
  4025. static void
  4026. owning_controller_procmon_cb(void *unused)
  4027. {
  4028. (void)unused;
  4029. lost_owning_controller("process", "vanished");
  4030. }
  4031. /** Set <b>process_spec</b> as Tor's owning controller process.
  4032. * Exit on failure. */
  4033. void
  4034. monitor_owning_controller_process(const char *process_spec)
  4035. {
  4036. const char *msg;
  4037. tor_assert((owning_controller_process_spec == NULL) ==
  4038. (owning_controller_process_monitor == NULL));
  4039. if (owning_controller_process_spec != NULL) {
  4040. if ((process_spec != NULL) && !strcmp(process_spec,
  4041. owning_controller_process_spec)) {
  4042. /* Same process -- return now, instead of disposing of and
  4043. * recreating the process-termination monitor. */
  4044. return;
  4045. }
  4046. /* We are currently owned by a process, and we should no longer be
  4047. * owned by it. Free the process-termination monitor. */
  4048. tor_process_monitor_free(owning_controller_process_monitor);
  4049. owning_controller_process_monitor = NULL;
  4050. tor_free(owning_controller_process_spec);
  4051. owning_controller_process_spec = NULL;
  4052. }
  4053. tor_assert((owning_controller_process_spec == NULL) &&
  4054. (owning_controller_process_monitor == NULL));
  4055. if (process_spec == NULL)
  4056. return;
  4057. owning_controller_process_spec = tor_strdup(process_spec);
  4058. owning_controller_process_monitor =
  4059. tor_process_monitor_new(tor_libevent_get_base(),
  4060. owning_controller_process_spec,
  4061. LD_CONTROL,
  4062. owning_controller_procmon_cb, NULL,
  4063. &msg);
  4064. if (owning_controller_process_monitor == NULL) {
  4065. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  4066. "owning controller: %s. Exiting.",
  4067. msg);
  4068. owning_controller_process_spec = NULL;
  4069. tor_cleanup();
  4070. exit(0);
  4071. }
  4072. }
  4073. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  4074. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  4075. static int
  4076. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  4077. const char **summary)
  4078. {
  4079. switch (s) {
  4080. case BOOTSTRAP_STATUS_UNDEF:
  4081. *tag = "undef";
  4082. *summary = "Undefined";
  4083. break;
  4084. case BOOTSTRAP_STATUS_STARTING:
  4085. *tag = "starting";
  4086. *summary = "Starting";
  4087. break;
  4088. case BOOTSTRAP_STATUS_CONN_DIR:
  4089. *tag = "conn_dir";
  4090. *summary = "Connecting to directory server";
  4091. break;
  4092. case BOOTSTRAP_STATUS_HANDSHAKE:
  4093. *tag = "status_handshake";
  4094. *summary = "Finishing handshake";
  4095. break;
  4096. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  4097. *tag = "handshake_dir";
  4098. *summary = "Finishing handshake with directory server";
  4099. break;
  4100. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  4101. *tag = "onehop_create";
  4102. *summary = "Establishing an encrypted directory connection";
  4103. break;
  4104. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  4105. *tag = "requesting_status";
  4106. *summary = "Asking for networkstatus consensus";
  4107. break;
  4108. case BOOTSTRAP_STATUS_LOADING_STATUS:
  4109. *tag = "loading_status";
  4110. *summary = "Loading networkstatus consensus";
  4111. break;
  4112. case BOOTSTRAP_STATUS_LOADING_KEYS:
  4113. *tag = "loading_keys";
  4114. *summary = "Loading authority key certs";
  4115. break;
  4116. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  4117. *tag = "requesting_descriptors";
  4118. *summary = "Asking for relay descriptors";
  4119. break;
  4120. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  4121. *tag = "loading_descriptors";
  4122. *summary = "Loading relay descriptors";
  4123. break;
  4124. case BOOTSTRAP_STATUS_CONN_OR:
  4125. *tag = "conn_or";
  4126. *summary = "Connecting to the Tor network";
  4127. break;
  4128. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  4129. *tag = "handshake_or";
  4130. *summary = "Finishing handshake with first hop";
  4131. break;
  4132. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  4133. *tag = "circuit_create";
  4134. *summary = "Establishing a Tor circuit";
  4135. break;
  4136. case BOOTSTRAP_STATUS_DONE:
  4137. *tag = "done";
  4138. *summary = "Done";
  4139. break;
  4140. default:
  4141. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  4142. *tag = *summary = "unknown";
  4143. return -1;
  4144. }
  4145. return 0;
  4146. }
  4147. /** What percentage through the bootstrap process are we? We remember
  4148. * this so we can avoid sending redundant bootstrap status events, and
  4149. * so we can guess context for the bootstrap messages which are
  4150. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  4151. * Tor initializes. */
  4152. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  4153. /** How many problems have we had getting to the next bootstrapping phase?
  4154. * These include failure to establish a connection to a Tor relay,
  4155. * failures to finish the TLS handshake, failures to validate the
  4156. * consensus document, etc. */
  4157. static int bootstrap_problems = 0;
  4158. /* We only tell the controller once we've hit a threshold of problems
  4159. * for the current phase. */
  4160. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  4161. /** Called when Tor has made progress at bootstrapping its directory
  4162. * information and initial circuits.
  4163. *
  4164. * <b>status</b> is the new status, that is, what task we will be doing
  4165. * next. <b>progress</b> is zero if we just started this task, else it
  4166. * represents progress on the task. */
  4167. void
  4168. control_event_bootstrap(bootstrap_status_t status, int progress)
  4169. {
  4170. const char *tag, *summary;
  4171. char buf[BOOTSTRAP_MSG_LEN];
  4172. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  4173. return; /* already bootstrapped; nothing to be done here. */
  4174. /* special case for handshaking status, since our TLS handshaking code
  4175. * can't distinguish what the connection is going to be for. */
  4176. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  4177. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  4178. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  4179. } else {
  4180. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  4181. }
  4182. }
  4183. if (status > bootstrap_percent ||
  4184. (progress && progress > bootstrap_percent)) {
  4185. bootstrap_status_to_string(status, &tag, &summary);
  4186. tor_log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
  4187. "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
  4188. tor_snprintf(buf, sizeof(buf),
  4189. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  4190. progress ? progress : status, tag, summary);
  4191. tor_snprintf(last_sent_bootstrap_message,
  4192. sizeof(last_sent_bootstrap_message),
  4193. "NOTICE %s", buf);
  4194. control_event_client_status(LOG_NOTICE, "%s", buf);
  4195. if (status > bootstrap_percent) {
  4196. bootstrap_percent = status; /* new milestone reached */
  4197. }
  4198. if (progress > bootstrap_percent) {
  4199. /* incremental progress within a milestone */
  4200. bootstrap_percent = progress;
  4201. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  4202. }
  4203. }
  4204. }
  4205. /** Called when Tor has failed to make bootstrapping progress in a way
  4206. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  4207. * <b>reason</b> provides an "or_conn_end_reason" tag.
  4208. */
  4209. MOCK_IMPL(void,
  4210. control_event_bootstrap_problem, (const char *warn, int reason))
  4211. {
  4212. int status = bootstrap_percent;
  4213. const char *tag, *summary;
  4214. char buf[BOOTSTRAP_MSG_LEN];
  4215. const char *recommendation = "ignore";
  4216. int severity;
  4217. /* bootstrap_percent must not be in "undefined" state here. */
  4218. tor_assert(status >= 0);
  4219. if (bootstrap_percent == 100)
  4220. return; /* already bootstrapped; nothing to be done here. */
  4221. bootstrap_problems++;
  4222. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  4223. recommendation = "warn";
  4224. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  4225. recommendation = "warn";
  4226. if (get_options()->UseBridges &&
  4227. !any_bridge_descriptors_known() &&
  4228. !any_pending_bridge_descriptor_fetches())
  4229. recommendation = "warn";
  4230. if (we_are_hibernating())
  4231. recommendation = "ignore";
  4232. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  4233. status--; /* find a recognized status string based on current progress */
  4234. status = bootstrap_percent; /* set status back to the actual number */
  4235. severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
  4236. log_fn(severity,
  4237. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  4238. "count %d; recommendation %s)",
  4239. status, summary, warn,
  4240. orconn_end_reason_to_control_string(reason),
  4241. bootstrap_problems, recommendation);
  4242. connection_or_report_broken_states(severity, LD_HANDSHAKE);
  4243. tor_snprintf(buf, sizeof(buf),
  4244. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  4245. "COUNT=%d RECOMMENDATION=%s",
  4246. bootstrap_percent, tag, summary, warn,
  4247. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  4248. recommendation);
  4249. tor_snprintf(last_sent_bootstrap_message,
  4250. sizeof(last_sent_bootstrap_message),
  4251. "WARN %s", buf);
  4252. control_event_client_status(LOG_WARN, "%s", buf);
  4253. }
  4254. /** We just generated a new summary of which countries we've seen clients
  4255. * from recently. Send a copy to the controller in case it wants to
  4256. * display it for the user. */
  4257. void
  4258. control_event_clients_seen(const char *controller_str)
  4259. {
  4260. send_control_event(EVENT_CLIENTS_SEEN, 0,
  4261. "650 CLIENTS_SEEN %s\r\n", controller_str);
  4262. }
  4263. /** A new pluggable transport called <b>transport_name</b> was
  4264. * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
  4265. * "server" or "client" depending on the mode of the pluggable
  4266. * transport.
  4267. * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
  4268. */
  4269. void
  4270. control_event_transport_launched(const char *mode, const char *transport_name,
  4271. tor_addr_t *addr, uint16_t port)
  4272. {
  4273. send_control_event(EVENT_TRANSPORT_LAUNCHED, ALL_FORMATS,
  4274. "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
  4275. mode, transport_name, fmt_addr(addr), port);
  4276. }
  4277. /** Free any leftover allocated memory of the control.c subsystem. */
  4278. void
  4279. control_free_all(void)
  4280. {
  4281. if (authentication_cookie) /* Free the auth cookie */
  4282. tor_free(authentication_cookie);
  4283. }
  4284. #ifdef TOR_UNIT_TESTS
  4285. /* For testing: change the value of global_event_mask */
  4286. void
  4287. control_testing_set_global_event_mask(uint64_t mask)
  4288. {
  4289. global_event_mask = mask;
  4290. }
  4291. #endif