control.c 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730
  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. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  2023. { NULL, NULL, NULL, 0 }
  2024. };
  2025. /** Allocate and return a list of recognized GETINFO options. */
  2026. static char *
  2027. list_getinfo_options(void)
  2028. {
  2029. int i;
  2030. smartlist_t *lines = smartlist_new();
  2031. char *ans;
  2032. for (i = 0; getinfo_items[i].varname; ++i) {
  2033. if (!getinfo_items[i].desc)
  2034. continue;
  2035. smartlist_add_asprintf(lines, "%s%s -- %s\n",
  2036. getinfo_items[i].varname,
  2037. getinfo_items[i].is_prefix ? "*" : "",
  2038. getinfo_items[i].desc);
  2039. }
  2040. smartlist_sort_strings(lines);
  2041. ans = smartlist_join_strings(lines, "", 0, NULL);
  2042. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  2043. smartlist_free(lines);
  2044. return ans;
  2045. }
  2046. /** Lookup the 'getinfo' entry <b>question</b>, and return
  2047. * the answer in <b>*answer</b> (or NULL if key not recognized).
  2048. * Return 0 if success or unrecognized, or -1 if recognized but
  2049. * internal error. */
  2050. static int
  2051. handle_getinfo_helper(control_connection_t *control_conn,
  2052. const char *question, char **answer,
  2053. const char **err_out)
  2054. {
  2055. int i;
  2056. *answer = NULL; /* unrecognized key by default */
  2057. for (i = 0; getinfo_items[i].varname; ++i) {
  2058. int match;
  2059. if (getinfo_items[i].is_prefix)
  2060. match = !strcmpstart(question, getinfo_items[i].varname);
  2061. else
  2062. match = !strcmp(question, getinfo_items[i].varname);
  2063. if (match) {
  2064. tor_assert(getinfo_items[i].fn);
  2065. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  2066. }
  2067. }
  2068. return 0; /* unrecognized */
  2069. }
  2070. /** Called when we receive a GETINFO command. Try to fetch all requested
  2071. * information, and reply with information or error message. */
  2072. static int
  2073. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  2074. const char *body)
  2075. {
  2076. smartlist_t *questions = smartlist_new();
  2077. smartlist_t *answers = smartlist_new();
  2078. smartlist_t *unrecognized = smartlist_new();
  2079. char *msg = NULL, *ans = NULL;
  2080. int i;
  2081. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2082. smartlist_split_string(questions, body, " ",
  2083. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2084. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  2085. const char *errmsg = NULL;
  2086. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  2087. if (!errmsg)
  2088. errmsg = "Internal error";
  2089. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  2090. goto done;
  2091. }
  2092. if (!ans) {
  2093. smartlist_add(unrecognized, (char*)q);
  2094. } else {
  2095. smartlist_add(answers, tor_strdup(q));
  2096. smartlist_add(answers, ans);
  2097. }
  2098. } SMARTLIST_FOREACH_END(q);
  2099. if (smartlist_len(unrecognized)) {
  2100. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  2101. connection_printf_to_buf(conn,
  2102. "552-Unrecognized key \"%s\"\r\n",
  2103. (char*)smartlist_get(unrecognized, i));
  2104. connection_printf_to_buf(conn,
  2105. "552 Unrecognized key \"%s\"\r\n",
  2106. (char*)smartlist_get(unrecognized, i));
  2107. goto done;
  2108. }
  2109. for (i = 0; i < smartlist_len(answers); i += 2) {
  2110. char *k = smartlist_get(answers, i);
  2111. char *v = smartlist_get(answers, i+1);
  2112. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  2113. connection_printf_to_buf(conn, "250-%s=", k);
  2114. connection_write_str_to_buf(v, conn);
  2115. connection_write_str_to_buf("\r\n", conn);
  2116. } else {
  2117. char *esc = NULL;
  2118. size_t esc_len;
  2119. esc_len = write_escaped_data(v, strlen(v), &esc);
  2120. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  2121. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  2122. tor_free(esc);
  2123. }
  2124. }
  2125. connection_write_str_to_buf("250 OK\r\n", conn);
  2126. done:
  2127. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  2128. smartlist_free(answers);
  2129. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  2130. smartlist_free(questions);
  2131. smartlist_free(unrecognized);
  2132. tor_free(msg);
  2133. return 0;
  2134. }
  2135. /** Given a string, convert it to a circuit purpose. */
  2136. static uint8_t
  2137. circuit_purpose_from_string(const char *string)
  2138. {
  2139. if (!strcasecmpstart(string, "purpose="))
  2140. string += strlen("purpose=");
  2141. if (!strcasecmp(string, "general"))
  2142. return CIRCUIT_PURPOSE_C_GENERAL;
  2143. else if (!strcasecmp(string, "controller"))
  2144. return CIRCUIT_PURPOSE_CONTROLLER;
  2145. else
  2146. return CIRCUIT_PURPOSE_UNKNOWN;
  2147. }
  2148. /** Return a newly allocated smartlist containing the arguments to the command
  2149. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  2150. * or if <b>max_args</b> is nonnegative and there are more than
  2151. * <b>max_args</b> arguments, send a 512 error to the controller, using
  2152. * <b>command</b> as the command name in the error message. */
  2153. static smartlist_t *
  2154. getargs_helper(const char *command, control_connection_t *conn,
  2155. const char *body, int min_args, int max_args)
  2156. {
  2157. smartlist_t *args = smartlist_new();
  2158. smartlist_split_string(args, body, " ",
  2159. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2160. if (smartlist_len(args) < min_args) {
  2161. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  2162. goto err;
  2163. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  2164. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  2165. goto err;
  2166. }
  2167. return args;
  2168. err:
  2169. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  2170. smartlist_free(args);
  2171. return NULL;
  2172. }
  2173. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  2174. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  2175. * such element exists. */
  2176. static const char *
  2177. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  2178. {
  2179. int i;
  2180. for (i = start_at; i < smartlist_len(sl); ++i) {
  2181. const char *elt = smartlist_get(sl, i);
  2182. if (!strcasecmpstart(elt, prefix))
  2183. return elt;
  2184. }
  2185. return NULL;
  2186. }
  2187. /** Helper. Return true iff s is an argument that we should treat as a
  2188. * key-value pair. */
  2189. static int
  2190. is_keyval_pair(const char *s)
  2191. {
  2192. /* An argument is a key-value pair if it has an =, and it isn't of the form
  2193. * $fingeprint=name */
  2194. return strchr(s, '=') && s[0] != '$';
  2195. }
  2196. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  2197. * circuit, and report success or failure. */
  2198. static int
  2199. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  2200. const char *body)
  2201. {
  2202. smartlist_t *router_nicknames=NULL, *nodes=NULL;
  2203. origin_circuit_t *circ = NULL;
  2204. int zero_circ;
  2205. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  2206. smartlist_t *args;
  2207. (void) len;
  2208. router_nicknames = smartlist_new();
  2209. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  2210. if (!args)
  2211. goto done;
  2212. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  2213. if (zero_circ) {
  2214. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  2215. if (purp) {
  2216. intended_purpose = circuit_purpose_from_string(purp);
  2217. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2218. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2219. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2220. smartlist_free(args);
  2221. goto done;
  2222. }
  2223. }
  2224. if ((smartlist_len(args) == 1) ||
  2225. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  2226. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  2227. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  2228. if (!circ) {
  2229. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2230. } else {
  2231. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2232. (unsigned long)circ->global_identifier);
  2233. }
  2234. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2235. smartlist_free(args);
  2236. goto done;
  2237. }
  2238. // "EXTENDCIRCUIT 0 router1,router2" ||
  2239. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  2240. }
  2241. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  2242. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2243. (char*)smartlist_get(args, 0));
  2244. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2245. smartlist_free(args);
  2246. goto done;
  2247. }
  2248. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  2249. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2250. smartlist_free(args);
  2251. nodes = smartlist_new();
  2252. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  2253. const node_t *node = node_get_by_nickname(n, 1);
  2254. if (!node) {
  2255. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  2256. goto done;
  2257. }
  2258. if (!node_has_descriptor(node)) {
  2259. connection_printf_to_buf(conn, "552 descriptor for \"%s\"\r\n", n);
  2260. goto done;
  2261. }
  2262. smartlist_add(nodes, (void*)node);
  2263. } SMARTLIST_FOREACH_END(n);
  2264. if (!smartlist_len(nodes)) {
  2265. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  2266. goto done;
  2267. }
  2268. if (zero_circ) {
  2269. /* start a new circuit */
  2270. circ = origin_circuit_init(intended_purpose, 0);
  2271. }
  2272. /* now circ refers to something that is ready to be extended */
  2273. SMARTLIST_FOREACH(nodes, const node_t *, node,
  2274. {
  2275. extend_info_t *info = extend_info_from_node(node, 0);
  2276. tor_assert(info); /* True, since node_has_descriptor(node) == true */
  2277. circuit_append_new_exit(circ, info);
  2278. extend_info_free(info);
  2279. });
  2280. /* now that we've populated the cpath, start extending */
  2281. if (zero_circ) {
  2282. int err_reason = 0;
  2283. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  2284. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2285. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2286. goto done;
  2287. }
  2288. } else {
  2289. if (circ->base_.state == CIRCUIT_STATE_OPEN) {
  2290. int err_reason = 0;
  2291. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2292. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  2293. log_info(LD_CONTROL,
  2294. "send_next_onion_skin failed; circuit marked for closing.");
  2295. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2296. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  2297. goto done;
  2298. }
  2299. }
  2300. }
  2301. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2302. (unsigned long)circ->global_identifier);
  2303. if (zero_circ) /* send a 'launched' event, for completeness */
  2304. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  2305. done:
  2306. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  2307. smartlist_free(router_nicknames);
  2308. smartlist_free(nodes);
  2309. return 0;
  2310. }
  2311. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  2312. * circuit and it's a valid purpose, change it. */
  2313. static int
  2314. handle_control_setcircuitpurpose(control_connection_t *conn,
  2315. uint32_t len, const char *body)
  2316. {
  2317. origin_circuit_t *circ = NULL;
  2318. uint8_t new_purpose;
  2319. smartlist_t *args;
  2320. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2321. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  2322. if (!args)
  2323. goto done;
  2324. if (!(circ = get_circ(smartlist_get(args,0)))) {
  2325. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2326. (char*)smartlist_get(args, 0));
  2327. goto done;
  2328. }
  2329. {
  2330. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  2331. if (!purp) {
  2332. connection_write_str_to_buf("552 No purpose given\r\n", conn);
  2333. goto done;
  2334. }
  2335. new_purpose = circuit_purpose_from_string(purp);
  2336. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2337. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2338. goto done;
  2339. }
  2340. }
  2341. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  2342. connection_write_str_to_buf("250 OK\r\n", conn);
  2343. done:
  2344. if (args) {
  2345. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2346. smartlist_free(args);
  2347. }
  2348. return 0;
  2349. }
  2350. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  2351. * stream, and report success or failure. */
  2352. static int
  2353. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  2354. const char *body)
  2355. {
  2356. entry_connection_t *ap_conn = NULL;
  2357. origin_circuit_t *circ = NULL;
  2358. int zero_circ;
  2359. smartlist_t *args;
  2360. crypt_path_t *cpath=NULL;
  2361. int hop=0, hop_line_ok=1;
  2362. (void) len;
  2363. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  2364. if (!args)
  2365. return 0;
  2366. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  2367. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  2368. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2369. (char*)smartlist_get(args, 0));
  2370. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  2371. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2372. (char*)smartlist_get(args, 1));
  2373. } else if (circ) {
  2374. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  2375. if (hopstring) {
  2376. hopstring += strlen("HOP=");
  2377. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  2378. &hop_line_ok, NULL);
  2379. if (!hop_line_ok) { /* broken hop line */
  2380. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  2381. }
  2382. }
  2383. }
  2384. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2385. smartlist_free(args);
  2386. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  2387. return 0;
  2388. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  2389. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  2390. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  2391. connection_write_str_to_buf(
  2392. "555 Connection is not managed by controller.\r\n",
  2393. conn);
  2394. return 0;
  2395. }
  2396. /* Do we need to detach it first? */
  2397. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  2398. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2399. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  2400. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  2401. /* Un-mark it as ending, since we're going to reuse it. */
  2402. edge_conn->edge_has_sent_end = 0;
  2403. edge_conn->end_reason = 0;
  2404. if (tmpcirc)
  2405. circuit_detach_stream(tmpcirc, edge_conn);
  2406. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  2407. }
  2408. if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
  2409. connection_write_str_to_buf(
  2410. "551 Can't attach stream to non-open origin circuit\r\n",
  2411. conn);
  2412. return 0;
  2413. }
  2414. /* Is this a single hop circuit? */
  2415. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  2416. const node_t *node = NULL;
  2417. char *exit_digest;
  2418. if (circ->build_state &&
  2419. circ->build_state->chosen_exit &&
  2420. !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
  2421. exit_digest = circ->build_state->chosen_exit->identity_digest;
  2422. node = node_get_by_id(exit_digest);
  2423. }
  2424. /* Do both the client and relay allow one-hop exit circuits? */
  2425. if (!node ||
  2426. !node_allows_single_hop_exits(node) ||
  2427. !get_options()->AllowSingleHopCircuits) {
  2428. connection_write_str_to_buf(
  2429. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  2430. return 0;
  2431. }
  2432. ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
  2433. }
  2434. if (circ && hop>0) {
  2435. /* find this hop in the circuit, and set cpath */
  2436. cpath = circuit_get_cpath_hop(circ, hop);
  2437. if (!cpath) {
  2438. connection_printf_to_buf(conn,
  2439. "551 Circuit doesn't have %d hops.\r\n", hop);
  2440. return 0;
  2441. }
  2442. }
  2443. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  2444. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  2445. return 0;
  2446. }
  2447. send_control_done(conn);
  2448. return 0;
  2449. }
  2450. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  2451. * descriptor, and report success or failure. */
  2452. static int
  2453. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  2454. const char *body)
  2455. {
  2456. char *desc;
  2457. const char *msg=NULL;
  2458. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  2459. int cache = 0; /* eventually, we may switch this to 1 */
  2460. char *cp = memchr(body, '\n', len);
  2461. smartlist_t *args = smartlist_new();
  2462. tor_assert(cp);
  2463. *cp++ = '\0';
  2464. smartlist_split_string(args, body, " ",
  2465. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2466. SMARTLIST_FOREACH_BEGIN(args, char *, option) {
  2467. if (!strcasecmpstart(option, "purpose=")) {
  2468. option += strlen("purpose=");
  2469. purpose = router_purpose_from_string(option);
  2470. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  2471. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  2472. option);
  2473. goto done;
  2474. }
  2475. } else if (!strcasecmpstart(option, "cache=")) {
  2476. option += strlen("cache=");
  2477. if (!strcasecmp(option, "no"))
  2478. cache = 0;
  2479. else if (!strcasecmp(option, "yes"))
  2480. cache = 1;
  2481. else {
  2482. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  2483. option);
  2484. goto done;
  2485. }
  2486. } else { /* unrecognized argument? */
  2487. connection_printf_to_buf(conn,
  2488. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  2489. goto done;
  2490. }
  2491. } SMARTLIST_FOREACH_END(option);
  2492. read_escaped_data(cp, len-(cp-body), &desc);
  2493. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  2494. case -1:
  2495. if (!msg) msg = "Could not parse descriptor";
  2496. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  2497. break;
  2498. case 0:
  2499. if (!msg) msg = "Descriptor not added";
  2500. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2501. break;
  2502. case 1:
  2503. send_control_done(conn);
  2504. break;
  2505. }
  2506. tor_free(desc);
  2507. done:
  2508. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  2509. smartlist_free(args);
  2510. return 0;
  2511. }
  2512. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2513. * address of the named AP stream, and report success or failure. */
  2514. static int
  2515. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2516. const char *body)
  2517. {
  2518. entry_connection_t *ap_conn = NULL;
  2519. char *new_addr = NULL;
  2520. uint16_t new_port = 0;
  2521. smartlist_t *args;
  2522. (void) len;
  2523. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  2524. if (!args)
  2525. return 0;
  2526. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2527. || !ap_conn->socks_request) {
  2528. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2529. (char*)smartlist_get(args, 0));
  2530. } else {
  2531. int ok = 1;
  2532. if (smartlist_len(args) > 2) { /* they included a port too */
  2533. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2534. 10, 1, 65535, &ok, NULL);
  2535. }
  2536. if (!ok) {
  2537. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2538. (char*)smartlist_get(args, 2));
  2539. } else {
  2540. new_addr = tor_strdup(smartlist_get(args, 1));
  2541. }
  2542. }
  2543. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2544. smartlist_free(args);
  2545. if (!new_addr)
  2546. return 0;
  2547. strlcpy(ap_conn->socks_request->address, new_addr,
  2548. sizeof(ap_conn->socks_request->address));
  2549. if (new_port)
  2550. ap_conn->socks_request->port = new_port;
  2551. tor_free(new_addr);
  2552. send_control_done(conn);
  2553. return 0;
  2554. }
  2555. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2556. * and report success or failure. */
  2557. static int
  2558. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2559. const char *body)
  2560. {
  2561. entry_connection_t *ap_conn=NULL;
  2562. uint8_t reason=0;
  2563. smartlist_t *args;
  2564. int ok;
  2565. (void) len;
  2566. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2567. if (!args)
  2568. return 0;
  2569. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2570. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2571. (char*)smartlist_get(args, 0));
  2572. else {
  2573. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2574. &ok, NULL);
  2575. if (!ok) {
  2576. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2577. (char*)smartlist_get(args, 1));
  2578. ap_conn = NULL;
  2579. }
  2580. }
  2581. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2582. smartlist_free(args);
  2583. if (!ap_conn)
  2584. return 0;
  2585. connection_mark_unattached_ap(ap_conn, reason);
  2586. send_control_done(conn);
  2587. return 0;
  2588. }
  2589. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2590. * and report success or failure. */
  2591. static int
  2592. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2593. const char *body)
  2594. {
  2595. origin_circuit_t *circ = NULL;
  2596. int safe = 0;
  2597. smartlist_t *args;
  2598. (void) len;
  2599. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2600. if (!args)
  2601. return 0;
  2602. if (!(circ=get_circ(smartlist_get(args, 0))))
  2603. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2604. (char*)smartlist_get(args, 0));
  2605. else {
  2606. int i;
  2607. for (i=1; i < smartlist_len(args); ++i) {
  2608. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2609. safe = 1;
  2610. else
  2611. log_info(LD_CONTROL, "Skipping unknown option %s",
  2612. (char*)smartlist_get(args,i));
  2613. }
  2614. }
  2615. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2616. smartlist_free(args);
  2617. if (!circ)
  2618. return 0;
  2619. if (!safe || !circ->p_streams) {
  2620. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2621. }
  2622. send_control_done(conn);
  2623. return 0;
  2624. }
  2625. /** Called when we get a RESOLVE command: start trying to resolve
  2626. * the listed addresses. */
  2627. static int
  2628. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2629. const char *body)
  2630. {
  2631. smartlist_t *args, *failed;
  2632. int is_reverse = 0;
  2633. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2634. if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
  2635. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2636. "isn't listening for ADDRMAP events. It probably won't see "
  2637. "the answer.");
  2638. }
  2639. args = smartlist_new();
  2640. smartlist_split_string(args, body, " ",
  2641. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2642. {
  2643. const char *modearg = find_element_starting_with(args, 0, "mode=");
  2644. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  2645. is_reverse = 1;
  2646. }
  2647. failed = smartlist_new();
  2648. SMARTLIST_FOREACH(args, const char *, arg, {
  2649. if (!is_keyval_pair(arg)) {
  2650. if (dnsserv_launch_request(arg, is_reverse, conn)<0)
  2651. smartlist_add(failed, (char*)arg);
  2652. }
  2653. });
  2654. send_control_done(conn);
  2655. SMARTLIST_FOREACH(failed, const char *, arg, {
  2656. control_event_address_mapped(arg, arg, time(NULL),
  2657. "internal", 0);
  2658. });
  2659. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2660. smartlist_free(args);
  2661. smartlist_free(failed);
  2662. return 0;
  2663. }
  2664. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  2665. static int
  2666. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  2667. const char *body)
  2668. {
  2669. const char *bad_arg = NULL;
  2670. smartlist_t *args;
  2671. (void)len;
  2672. conn->have_sent_protocolinfo = 1;
  2673. args = smartlist_new();
  2674. smartlist_split_string(args, body, " ",
  2675. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2676. SMARTLIST_FOREACH(args, const char *, arg, {
  2677. int ok;
  2678. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  2679. if (!ok) {
  2680. bad_arg = arg;
  2681. break;
  2682. }
  2683. });
  2684. if (bad_arg) {
  2685. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  2686. escaped(bad_arg));
  2687. /* Don't tolerate bad arguments when not authenticated. */
  2688. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  2689. connection_mark_for_close(TO_CONN(conn));
  2690. goto done;
  2691. } else {
  2692. const or_options_t *options = get_options();
  2693. int cookies = options->CookieAuthentication;
  2694. char *cfile = get_cookie_file();
  2695. char *abs_cfile;
  2696. char *esc_cfile;
  2697. char *methods;
  2698. abs_cfile = make_path_absolute(cfile);
  2699. esc_cfile = esc_for_log(abs_cfile);
  2700. {
  2701. int passwd = (options->HashedControlPassword != NULL ||
  2702. options->HashedControlSessionPassword != NULL);
  2703. smartlist_t *mlist = smartlist_new();
  2704. if (cookies) {
  2705. smartlist_add(mlist, (char*)"COOKIE");
  2706. smartlist_add(mlist, (char*)"SAFECOOKIE");
  2707. }
  2708. if (passwd)
  2709. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  2710. if (!cookies && !passwd)
  2711. smartlist_add(mlist, (char*)"NULL");
  2712. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  2713. smartlist_free(mlist);
  2714. }
  2715. connection_printf_to_buf(conn,
  2716. "250-PROTOCOLINFO 1\r\n"
  2717. "250-AUTH METHODS=%s%s%s\r\n"
  2718. "250-VERSION Tor=%s\r\n"
  2719. "250 OK\r\n",
  2720. methods,
  2721. cookies?" COOKIEFILE=":"",
  2722. cookies?esc_cfile:"",
  2723. escaped(VERSION));
  2724. tor_free(methods);
  2725. tor_free(cfile);
  2726. tor_free(abs_cfile);
  2727. tor_free(esc_cfile);
  2728. }
  2729. done:
  2730. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2731. smartlist_free(args);
  2732. return 0;
  2733. }
  2734. /** Called when we get an AUTHCHALLENGE command. */
  2735. static int
  2736. handle_control_authchallenge(control_connection_t *conn, uint32_t len,
  2737. const char *body)
  2738. {
  2739. const char *cp = body;
  2740. char *client_nonce;
  2741. size_t client_nonce_len;
  2742. char server_hash[DIGEST256_LEN];
  2743. char server_hash_encoded[HEX_DIGEST256_LEN+1];
  2744. char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
  2745. char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
  2746. cp += strspn(cp, " \t\n\r");
  2747. if (!strcasecmpstart(cp, "SAFECOOKIE")) {
  2748. cp += strlen("SAFECOOKIE");
  2749. } else {
  2750. connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
  2751. "authentication\r\n", conn);
  2752. connection_mark_for_close(TO_CONN(conn));
  2753. return -1;
  2754. }
  2755. if (!authentication_cookie_is_set) {
  2756. connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
  2757. conn);
  2758. connection_mark_for_close(TO_CONN(conn));
  2759. return -1;
  2760. }
  2761. cp += strspn(cp, " \t\n\r");
  2762. if (*cp == '"') {
  2763. const char *newcp =
  2764. decode_escaped_string(cp, len - (cp - body),
  2765. &client_nonce, &client_nonce_len);
  2766. if (newcp == NULL) {
  2767. connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
  2768. conn);
  2769. connection_mark_for_close(TO_CONN(conn));
  2770. return -1;
  2771. }
  2772. cp = newcp;
  2773. } else {
  2774. size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
  2775. client_nonce_len = client_nonce_encoded_len / 2;
  2776. client_nonce = tor_malloc_zero(client_nonce_len);
  2777. if (base16_decode(client_nonce, client_nonce_len,
  2778. cp, client_nonce_encoded_len) < 0) {
  2779. connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
  2780. conn);
  2781. connection_mark_for_close(TO_CONN(conn));
  2782. tor_free(client_nonce);
  2783. return -1;
  2784. }
  2785. cp += client_nonce_encoded_len;
  2786. }
  2787. cp += strspn(cp, " \t\n\r");
  2788. if (*cp != '\0' ||
  2789. cp != body + len) {
  2790. connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
  2791. conn);
  2792. connection_mark_for_close(TO_CONN(conn));
  2793. tor_free(client_nonce);
  2794. return -1;
  2795. }
  2796. tor_assert(!crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN));
  2797. /* Now compute and send the server-to-controller response, and the
  2798. * server's nonce. */
  2799. tor_assert(authentication_cookie != NULL);
  2800. {
  2801. size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
  2802. client_nonce_len +
  2803. SAFECOOKIE_SERVER_NONCE_LEN);
  2804. char *tmp = tor_malloc_zero(tmp_len);
  2805. char *client_hash = tor_malloc_zero(DIGEST256_LEN);
  2806. memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2807. memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
  2808. memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
  2809. server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  2810. crypto_hmac_sha256(server_hash,
  2811. SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
  2812. strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
  2813. tmp,
  2814. tmp_len);
  2815. crypto_hmac_sha256(client_hash,
  2816. SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
  2817. strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
  2818. tmp,
  2819. tmp_len);
  2820. conn->safecookie_client_hash = client_hash;
  2821. tor_free(tmp);
  2822. }
  2823. base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
  2824. server_hash, sizeof(server_hash));
  2825. base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
  2826. server_nonce, sizeof(server_nonce));
  2827. connection_printf_to_buf(conn,
  2828. "250 AUTHCHALLENGE SERVERHASH=%s "
  2829. "SERVERNONCE=%s\r\n",
  2830. server_hash_encoded,
  2831. server_nonce_encoded);
  2832. tor_free(client_nonce);
  2833. return 0;
  2834. }
  2835. /** Called when we get a USEFEATURE command: parse the feature list, and
  2836. * set up the control_connection's options properly. */
  2837. static int
  2838. handle_control_usefeature(control_connection_t *conn,
  2839. uint32_t len,
  2840. const char *body)
  2841. {
  2842. smartlist_t *args;
  2843. int bad = 0;
  2844. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2845. args = smartlist_new();
  2846. smartlist_split_string(args, body, " ",
  2847. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2848. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  2849. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2850. ;
  2851. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  2852. ;
  2853. else {
  2854. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2855. arg);
  2856. bad = 1;
  2857. break;
  2858. }
  2859. } SMARTLIST_FOREACH_END(arg);
  2860. if (!bad) {
  2861. send_control_done(conn);
  2862. }
  2863. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2864. smartlist_free(args);
  2865. return 0;
  2866. }
  2867. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2868. int
  2869. connection_control_finished_flushing(control_connection_t *conn)
  2870. {
  2871. tor_assert(conn);
  2872. return 0;
  2873. }
  2874. /** Called when <b>conn</b> has gotten its socket closed. */
  2875. int
  2876. connection_control_reached_eof(control_connection_t *conn)
  2877. {
  2878. tor_assert(conn);
  2879. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2880. connection_mark_for_close(TO_CONN(conn));
  2881. return 0;
  2882. }
  2883. /** Shut down this Tor instance in the same way that SIGINT would, but
  2884. * with a log message appropriate for the loss of an owning controller. */
  2885. static void
  2886. lost_owning_controller(const char *owner_type, const char *loss_manner)
  2887. {
  2888. int shutdown_slowly = server_mode(get_options());
  2889. log_notice(LD_CONTROL, "Owning controller %s has %s -- %s.",
  2890. owner_type, loss_manner,
  2891. shutdown_slowly ? "shutting down" : "exiting now");
  2892. /* XXXX Perhaps this chunk of code should be a separate function,
  2893. * called here and by process_signal(SIGINT). */
  2894. if (!shutdown_slowly) {
  2895. tor_cleanup();
  2896. exit(0);
  2897. }
  2898. /* XXXX This will close all listening sockets except control-port
  2899. * listeners. Perhaps we should close those too. */
  2900. hibernate_begin_shutdown();
  2901. }
  2902. /** Called when <b>conn</b> is being freed. */
  2903. void
  2904. connection_control_closed(control_connection_t *conn)
  2905. {
  2906. tor_assert(conn);
  2907. conn->event_mask = 0;
  2908. control_update_global_event_mask();
  2909. if (conn->is_owning_control_connection) {
  2910. lost_owning_controller("connection", "closed");
  2911. }
  2912. }
  2913. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  2914. * stage of the protocol. */
  2915. static int
  2916. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  2917. {
  2918. if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
  2919. return 1;
  2920. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  2921. return (!conn->have_sent_protocolinfo &&
  2922. conn->safecookie_client_hash == NULL);
  2923. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  2924. return (conn->safecookie_client_hash == NULL);
  2925. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  2926. !strcasecmp(cmd, "QUIT"))
  2927. return 1;
  2928. return 0;
  2929. }
  2930. /** Do not accept any control command of more than 1MB in length. Anything
  2931. * that needs to be anywhere near this long probably means that one of our
  2932. * interfaces is broken. */
  2933. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  2934. /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
  2935. * interface as those underlying functions, but takes a connection_t intead of
  2936. * an evbuffer or a buf_t.
  2937. */
  2938. static int
  2939. peek_connection_has_control0_command(connection_t *conn)
  2940. {
  2941. IF_HAS_BUFFEREVENT(conn, {
  2942. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  2943. return peek_evbuffer_has_control0_command(input);
  2944. }) ELSE_IF_NO_BUFFEREVENT {
  2945. return peek_buf_has_control0_command(conn->inbuf);
  2946. }
  2947. }
  2948. /** Called when data has arrived on a v1 control connection: Try to fetch
  2949. * commands from conn->inbuf, and execute them.
  2950. */
  2951. int
  2952. connection_control_process_inbuf(control_connection_t *conn)
  2953. {
  2954. size_t data_len;
  2955. uint32_t cmd_data_len;
  2956. int cmd_len;
  2957. char *args;
  2958. tor_assert(conn);
  2959. tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
  2960. conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
  2961. if (!conn->incoming_cmd) {
  2962. conn->incoming_cmd = tor_malloc(1024);
  2963. conn->incoming_cmd_len = 1024;
  2964. conn->incoming_cmd_cur_len = 0;
  2965. }
  2966. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2967. peek_connection_has_control0_command(TO_CONN(conn))) {
  2968. /* Detect v0 commands and send a "no more v0" message. */
  2969. size_t body_len;
  2970. char buf[128];
  2971. set_uint16(buf+2, htons(0x0000)); /* type == error */
  2972. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  2973. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  2974. "and later; upgrade your controller.",
  2975. sizeof(buf)-6);
  2976. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  2977. set_uint16(buf+0, htons(body_len));
  2978. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  2979. connection_mark_and_flush(TO_CONN(conn));
  2980. return 0;
  2981. }
  2982. again:
  2983. while (1) {
  2984. size_t last_idx;
  2985. int r;
  2986. /* First, fetch a line. */
  2987. do {
  2988. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2989. r = connection_fetch_from_buf_line(TO_CONN(conn),
  2990. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2991. &data_len);
  2992. if (r == 0)
  2993. /* Line not all here yet. Wait. */
  2994. return 0;
  2995. else if (r == -1) {
  2996. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  2997. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  2998. connection_stop_reading(TO_CONN(conn));
  2999. connection_mark_and_flush(TO_CONN(conn));
  3000. }
  3001. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  3002. conn->incoming_cmd_len *= 2;
  3003. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  3004. conn->incoming_cmd_len);
  3005. }
  3006. } while (r != 1);
  3007. tor_assert(data_len);
  3008. last_idx = conn->incoming_cmd_cur_len;
  3009. conn->incoming_cmd_cur_len += (int)data_len;
  3010. /* We have appended a line to incoming_cmd. Is the command done? */
  3011. if (last_idx == 0 && *conn->incoming_cmd != '+')
  3012. /* One line command, didn't start with '+'. */
  3013. break;
  3014. /* XXXX this code duplication is kind of dumb. */
  3015. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  3016. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  3017. /* Just appended ".\r\n"; we're done. Remove it. */
  3018. conn->incoming_cmd[last_idx] = '\0';
  3019. conn->incoming_cmd_cur_len -= 3;
  3020. break;
  3021. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  3022. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  3023. /* Just appended ".\n"; we're done. Remove it. */
  3024. conn->incoming_cmd[last_idx] = '\0';
  3025. conn->incoming_cmd_cur_len -= 2;
  3026. break;
  3027. }
  3028. /* Otherwise, read another line. */
  3029. }
  3030. data_len = conn->incoming_cmd_cur_len;
  3031. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  3032. * recognize it.
  3033. */
  3034. cmd_len = 0;
  3035. while ((size_t)cmd_len < data_len
  3036. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  3037. ++cmd_len;
  3038. conn->incoming_cmd[cmd_len]='\0';
  3039. args = conn->incoming_cmd+cmd_len+1;
  3040. tor_assert(data_len>(size_t)cmd_len);
  3041. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  3042. while (TOR_ISSPACE(*args)) {
  3043. ++args;
  3044. --data_len;
  3045. }
  3046. /* If the connection is already closing, ignore further commands */
  3047. if (TO_CONN(conn)->marked_for_close) {
  3048. return 0;
  3049. }
  3050. /* Otherwise, Quit is always valid. */
  3051. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  3052. connection_write_str_to_buf("250 closing connection\r\n", conn);
  3053. connection_mark_and_flush(TO_CONN(conn));
  3054. return 0;
  3055. }
  3056. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3057. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  3058. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  3059. connection_mark_for_close(TO_CONN(conn));
  3060. return 0;
  3061. }
  3062. if (data_len >= UINT32_MAX) {
  3063. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  3064. connection_mark_for_close(TO_CONN(conn));
  3065. return 0;
  3066. }
  3067. /* XXXX Why is this not implemented as a table like the GETINFO
  3068. * items are? Even handling the plus signs at the beginnings of
  3069. * commands wouldn't be very hard with proper macros. */
  3070. cmd_data_len = (uint32_t)data_len;
  3071. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  3072. if (handle_control_setconf(conn, cmd_data_len, args))
  3073. return -1;
  3074. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  3075. if (handle_control_resetconf(conn, cmd_data_len, args))
  3076. return -1;
  3077. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  3078. if (handle_control_getconf(conn, cmd_data_len, args))
  3079. return -1;
  3080. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  3081. if (handle_control_loadconf(conn, cmd_data_len, args))
  3082. return -1;
  3083. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  3084. if (handle_control_setevents(conn, cmd_data_len, args))
  3085. return -1;
  3086. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  3087. if (handle_control_authenticate(conn, cmd_data_len, args))
  3088. return -1;
  3089. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  3090. if (handle_control_saveconf(conn, cmd_data_len, args))
  3091. return -1;
  3092. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  3093. if (handle_control_signal(conn, cmd_data_len, args))
  3094. return -1;
  3095. } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
  3096. if (handle_control_takeownership(conn, cmd_data_len, args))
  3097. return -1;
  3098. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  3099. if (handle_control_mapaddress(conn, cmd_data_len, args))
  3100. return -1;
  3101. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  3102. if (handle_control_getinfo(conn, cmd_data_len, args))
  3103. return -1;
  3104. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  3105. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  3106. return -1;
  3107. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  3108. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  3109. return -1;
  3110. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  3111. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  3112. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  3113. if (handle_control_attachstream(conn, cmd_data_len, args))
  3114. return -1;
  3115. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  3116. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  3117. return -1;
  3118. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  3119. if (handle_control_redirectstream(conn, cmd_data_len, args))
  3120. return -1;
  3121. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  3122. if (handle_control_closestream(conn, cmd_data_len, args))
  3123. return -1;
  3124. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  3125. if (handle_control_closecircuit(conn, cmd_data_len, args))
  3126. return -1;
  3127. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  3128. if (handle_control_usefeature(conn, cmd_data_len, args))
  3129. return -1;
  3130. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  3131. if (handle_control_resolve(conn, cmd_data_len, args))
  3132. return -1;
  3133. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  3134. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  3135. return -1;
  3136. } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
  3137. if (handle_control_authchallenge(conn, cmd_data_len, args))
  3138. return -1;
  3139. } else {
  3140. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  3141. conn->incoming_cmd);
  3142. }
  3143. conn->incoming_cmd_cur_len = 0;
  3144. goto again;
  3145. }
  3146. /** Something major has happened to circuit <b>circ</b>: tell any
  3147. * interested control connections. */
  3148. int
  3149. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  3150. int reason_code)
  3151. {
  3152. const char *status;
  3153. char reasons[64] = "";
  3154. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  3155. return 0;
  3156. tor_assert(circ);
  3157. switch (tp)
  3158. {
  3159. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3160. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  3161. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  3162. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  3163. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  3164. default:
  3165. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3166. tor_fragile_assert();
  3167. return 0;
  3168. }
  3169. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  3170. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  3171. char unk_reason_buf[16];
  3172. if (!reason_str) {
  3173. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  3174. reason_str = unk_reason_buf;
  3175. }
  3176. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  3177. tor_snprintf(reasons, sizeof(reasons),
  3178. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  3179. } else {
  3180. tor_snprintf(reasons, sizeof(reasons),
  3181. " REASON=%s", reason_str);
  3182. }
  3183. }
  3184. {
  3185. char *circdesc = circuit_describe_status_for_controller(circ);
  3186. const char *sp = strlen(circdesc) ? " " : "";
  3187. send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
  3188. "650 CIRC %lu %s%s%s%s\r\n",
  3189. (unsigned long)circ->global_identifier,
  3190. status, sp,
  3191. circdesc,
  3192. reasons);
  3193. tor_free(circdesc);
  3194. }
  3195. return 0;
  3196. }
  3197. /** Something minor has happened to circuit <b>circ</b>: tell any
  3198. * interested control connections. */
  3199. static int
  3200. control_event_circuit_status_minor(origin_circuit_t *circ,
  3201. circuit_status_minor_event_t e,
  3202. int purpose, const struct timeval *tv)
  3203. {
  3204. const char *event_desc;
  3205. char event_tail[160] = "";
  3206. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  3207. return 0;
  3208. tor_assert(circ);
  3209. switch (e)
  3210. {
  3211. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  3212. event_desc = "PURPOSE_CHANGED";
  3213. {
  3214. /* event_tail can currently be up to 68 chars long */
  3215. const char *hs_state_str =
  3216. circuit_purpose_to_controller_hs_state_string(purpose);
  3217. tor_snprintf(event_tail, sizeof(event_tail),
  3218. " OLD_PURPOSE=%s%s%s",
  3219. circuit_purpose_to_controller_string(purpose),
  3220. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3221. (hs_state_str != NULL) ? hs_state_str : "");
  3222. }
  3223. break;
  3224. case CIRC_MINOR_EVENT_CANNIBALIZED:
  3225. event_desc = "CANNIBALIZED";
  3226. {
  3227. /* event_tail can currently be up to 130 chars long */
  3228. const char *hs_state_str =
  3229. circuit_purpose_to_controller_hs_state_string(purpose);
  3230. const struct timeval *old_timestamp_began = tv;
  3231. char tbuf[ISO_TIME_USEC_LEN+1];
  3232. format_iso_time_nospace_usec(tbuf, old_timestamp_began);
  3233. tor_snprintf(event_tail, sizeof(event_tail),
  3234. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  3235. circuit_purpose_to_controller_string(purpose),
  3236. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3237. (hs_state_str != NULL) ? hs_state_str : "",
  3238. tbuf);
  3239. }
  3240. break;
  3241. default:
  3242. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  3243. tor_fragile_assert();
  3244. return 0;
  3245. }
  3246. {
  3247. char *circdesc = circuit_describe_status_for_controller(circ);
  3248. const char *sp = strlen(circdesc) ? " " : "";
  3249. send_control_event(EVENT_CIRCUIT_STATUS_MINOR, ALL_FORMATS,
  3250. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  3251. (unsigned long)circ->global_identifier,
  3252. event_desc, sp,
  3253. circdesc,
  3254. event_tail);
  3255. tor_free(circdesc);
  3256. }
  3257. return 0;
  3258. }
  3259. /**
  3260. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  3261. * interested controllers.
  3262. */
  3263. int
  3264. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  3265. int old_purpose)
  3266. {
  3267. return control_event_circuit_status_minor(circ,
  3268. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  3269. old_purpose,
  3270. NULL);
  3271. }
  3272. /**
  3273. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  3274. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  3275. */
  3276. int
  3277. control_event_circuit_cannibalized(origin_circuit_t *circ,
  3278. int old_purpose,
  3279. const struct timeval *old_tv_created)
  3280. {
  3281. return control_event_circuit_status_minor(circ,
  3282. CIRC_MINOR_EVENT_CANNIBALIZED,
  3283. old_purpose,
  3284. old_tv_created);
  3285. }
  3286. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  3287. * <b>buf</b>, determine the address:port combination requested on
  3288. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  3289. * failure. */
  3290. static int
  3291. write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
  3292. {
  3293. char buf2[256];
  3294. if (conn->chosen_exit_name)
  3295. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  3296. return -1;
  3297. if (!conn->socks_request)
  3298. return -1;
  3299. if (tor_snprintf(buf, len, "%s%s%s:%d",
  3300. conn->socks_request->address,
  3301. conn->chosen_exit_name ? buf2 : "",
  3302. !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
  3303. ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
  3304. conn->socks_request->port)<0)
  3305. return -1;
  3306. return 0;
  3307. }
  3308. /** Something has happened to the stream associated with AP connection
  3309. * <b>conn</b>: tell any interested control connections. */
  3310. int
  3311. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  3312. int reason_code)
  3313. {
  3314. char reason_buf[64];
  3315. char addrport_buf[64];
  3316. const char *status;
  3317. circuit_t *circ;
  3318. origin_circuit_t *origin_circ = NULL;
  3319. char buf[256];
  3320. const char *purpose = "";
  3321. tor_assert(conn->socks_request);
  3322. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  3323. return 0;
  3324. if (tp == STREAM_EVENT_CLOSED &&
  3325. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  3326. return 0;
  3327. write_stream_target_to_buf(conn, buf, sizeof(buf));
  3328. reason_buf[0] = '\0';
  3329. switch (tp)
  3330. {
  3331. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  3332. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  3333. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  3334. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  3335. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  3336. case STREAM_EVENT_NEW: status = "NEW"; break;
  3337. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  3338. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  3339. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  3340. default:
  3341. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3342. return 0;
  3343. }
  3344. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  3345. tp == STREAM_EVENT_CLOSED ||
  3346. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  3347. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  3348. char *r = NULL;
  3349. if (!reason_str) {
  3350. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  3351. reason_str = r;
  3352. }
  3353. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  3354. tor_snprintf(reason_buf, sizeof(reason_buf),
  3355. " REASON=END REMOTE_REASON=%s", reason_str);
  3356. else
  3357. tor_snprintf(reason_buf, sizeof(reason_buf),
  3358. " REASON=%s", reason_str);
  3359. tor_free(r);
  3360. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  3361. switch (reason_code) {
  3362. case REMAP_STREAM_SOURCE_CACHE:
  3363. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  3364. break;
  3365. case REMAP_STREAM_SOURCE_EXIT:
  3366. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  3367. break;
  3368. default:
  3369. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  3370. reason_code);
  3371. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  3372. break;
  3373. }
  3374. }
  3375. if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
  3376. /*
  3377. * When the control conn is an AF_UNIX socket and we have no address,
  3378. * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
  3379. * dnsserv.c.
  3380. */
  3381. if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
  3382. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  3383. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  3384. } else {
  3385. /*
  3386. * else leave it blank so control on AF_UNIX doesn't need to make
  3387. * something up.
  3388. */
  3389. addrport_buf[0] = '\0';
  3390. }
  3391. } else {
  3392. addrport_buf[0] = '\0';
  3393. }
  3394. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  3395. purpose = " PURPOSE=DNS_REQUEST";
  3396. } else if (tp == STREAM_EVENT_NEW) {
  3397. if (conn->use_begindir) {
  3398. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  3399. int linked_dir_purpose = -1;
  3400. if (linked && linked->type == CONN_TYPE_DIR)
  3401. linked_dir_purpose = linked->purpose;
  3402. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  3403. purpose = " PURPOSE=DIR_UPLOAD";
  3404. else
  3405. purpose = " PURPOSE=DIR_FETCH";
  3406. } else
  3407. purpose = " PURPOSE=USER";
  3408. }
  3409. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  3410. if (circ && CIRCUIT_IS_ORIGIN(circ))
  3411. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3412. send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
  3413. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  3414. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  3415. status,
  3416. origin_circ?
  3417. (unsigned long)origin_circ->global_identifier : 0ul,
  3418. buf, reason_buf, addrport_buf, purpose);
  3419. /* XXX need to specify its intended exit, etc? */
  3420. return 0;
  3421. }
  3422. /** Figure out the best name for the target router of an OR connection
  3423. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  3424. * <b>name</b>. */
  3425. static void
  3426. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  3427. {
  3428. const node_t *node = node_get_by_id(conn->identity_digest);
  3429. if (node) {
  3430. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  3431. node_get_verbose_nickname(node, name);
  3432. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  3433. name[0] = '$';
  3434. base16_encode(name+1, len-1, conn->identity_digest,
  3435. DIGEST_LEN);
  3436. } else {
  3437. tor_snprintf(name, len, "%s:%d",
  3438. conn->base_.address, conn->base_.port);
  3439. }
  3440. }
  3441. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  3442. * interested control connections. <b>tp</b> is the new status for the
  3443. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  3444. * may be the reason why.
  3445. */
  3446. int
  3447. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  3448. int reason)
  3449. {
  3450. int ncircs = 0;
  3451. const char *status;
  3452. char name[128];
  3453. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  3454. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  3455. return 0;
  3456. switch (tp)
  3457. {
  3458. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3459. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  3460. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  3461. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  3462. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  3463. default:
  3464. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3465. return 0;
  3466. }
  3467. if (conn->chan) {
  3468. ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
  3469. } else {
  3470. ncircs = 0;
  3471. }
  3472. ncircs += connection_or_get_num_circuits(conn);
  3473. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  3474. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
  3475. reason ? " " : "", ncircs);
  3476. }
  3477. orconn_target_get_name(name, sizeof(name), conn);
  3478. send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
  3479. "650 ORCONN %s %s %s%s%s\r\n",
  3480. name, status,
  3481. reason ? "REASON=" : "",
  3482. orconn_end_reason_to_control_string(reason),
  3483. ncircs_buf);
  3484. return 0;
  3485. }
  3486. /**
  3487. * Print out STREAM_BW event for a single conn
  3488. */
  3489. int
  3490. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  3491. {
  3492. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3493. if (!edge_conn->n_read && !edge_conn->n_written)
  3494. return 0;
  3495. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3496. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3497. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  3498. (unsigned long)edge_conn->n_read,
  3499. (unsigned long)edge_conn->n_written);
  3500. edge_conn->n_written = edge_conn->n_read = 0;
  3501. }
  3502. return 0;
  3503. }
  3504. /** A second or more has elapsed: tell any interested control
  3505. * connections how much bandwidth streams have used. */
  3506. int
  3507. control_event_stream_bandwidth_used(void)
  3508. {
  3509. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3510. smartlist_t *conns = get_connection_array();
  3511. edge_connection_t *edge_conn;
  3512. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  3513. {
  3514. if (conn->type != CONN_TYPE_AP)
  3515. continue;
  3516. edge_conn = TO_EDGE_CONN(conn);
  3517. if (!edge_conn->n_read && !edge_conn->n_written)
  3518. continue;
  3519. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3520. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3521. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  3522. (unsigned long)edge_conn->n_read,
  3523. (unsigned long)edge_conn->n_written);
  3524. edge_conn->n_written = edge_conn->n_read = 0;
  3525. }
  3526. SMARTLIST_FOREACH_END(conn);
  3527. }
  3528. return 0;
  3529. }
  3530. /** A second or more has elapsed: tell any interested control
  3531. * connections how much bandwidth we used. */
  3532. int
  3533. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  3534. {
  3535. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  3536. send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
  3537. "650 BW %lu %lu\r\n",
  3538. (unsigned long)n_read,
  3539. (unsigned long)n_written);
  3540. }
  3541. return 0;
  3542. }
  3543. /** Called when we are sending a log message to the controllers: suspend
  3544. * sending further log messages to the controllers until we're done. Used by
  3545. * CONN_LOG_PROTECT. */
  3546. void
  3547. disable_control_logging(void)
  3548. {
  3549. ++disable_log_messages;
  3550. }
  3551. /** We're done sending a log message to the controllers: re-enable controller
  3552. * logging. Used by CONN_LOG_PROTECT. */
  3553. void
  3554. enable_control_logging(void)
  3555. {
  3556. if (--disable_log_messages < 0)
  3557. tor_assert(0);
  3558. }
  3559. /** We got a log message: tell any interested control connections. */
  3560. void
  3561. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  3562. {
  3563. int event;
  3564. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  3565. * thread. */
  3566. if (! in_main_thread())
  3567. return;
  3568. if (disable_log_messages)
  3569. return;
  3570. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  3571. severity <= LOG_NOTICE) {
  3572. char *esc = esc_for_log(msg);
  3573. ++disable_log_messages;
  3574. control_event_general_status(severity, "BUG REASON=%s", esc);
  3575. --disable_log_messages;
  3576. tor_free(esc);
  3577. }
  3578. event = log_severity_to_event(severity);
  3579. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  3580. char *b = NULL;
  3581. const char *s;
  3582. if (strchr(msg, '\n')) {
  3583. char *cp;
  3584. b = tor_strdup(msg);
  3585. for (cp = b; *cp; ++cp)
  3586. if (*cp == '\r' || *cp == '\n')
  3587. *cp = ' ';
  3588. }
  3589. switch (severity) {
  3590. case LOG_DEBUG: s = "DEBUG"; break;
  3591. case LOG_INFO: s = "INFO"; break;
  3592. case LOG_NOTICE: s = "NOTICE"; break;
  3593. case LOG_WARN: s = "WARN"; break;
  3594. case LOG_ERR: s = "ERR"; break;
  3595. default: s = "UnknownLogSeverity"; break;
  3596. }
  3597. ++disable_log_messages;
  3598. send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
  3599. --disable_log_messages;
  3600. tor_free(b);
  3601. }
  3602. }
  3603. /** Called whenever we receive new router descriptors: tell any
  3604. * interested control connections. <b>routers</b> is a list of
  3605. * routerinfo_t's.
  3606. */
  3607. int
  3608. control_event_descriptors_changed(smartlist_t *routers)
  3609. {
  3610. char *msg;
  3611. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  3612. return 0;
  3613. {
  3614. smartlist_t *names = smartlist_new();
  3615. char *ids;
  3616. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  3617. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  3618. router_get_verbose_nickname(b, ri);
  3619. smartlist_add(names, b);
  3620. });
  3621. ids = smartlist_join_strings(names, " ", 0, NULL);
  3622. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  3623. send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
  3624. tor_free(ids);
  3625. tor_free(msg);
  3626. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  3627. smartlist_free(names);
  3628. }
  3629. return 0;
  3630. }
  3631. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  3632. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  3633. * <b>error</b> is non-NULL, it is an error code describing the failure
  3634. * mode of the mapping.
  3635. */
  3636. int
  3637. control_event_address_mapped(const char *from, const char *to, time_t expires,
  3638. const char *error, const int cached)
  3639. {
  3640. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  3641. return 0;
  3642. if (expires < 3 || expires == TIME_MAX)
  3643. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3644. "650 ADDRMAP %s %s NEVER %s%s"
  3645. "CACHED=\"%s\"\r\n",
  3646. from, to, error?error:"", error?" ":"",
  3647. cached?"YES":"NO");
  3648. else {
  3649. char buf[ISO_TIME_LEN+1];
  3650. char buf2[ISO_TIME_LEN+1];
  3651. format_local_iso_time(buf,expires);
  3652. format_iso_time(buf2,expires);
  3653. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3654. "650 ADDRMAP %s %s \"%s\""
  3655. " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
  3656. from, to, buf,
  3657. error?error:"", error?" ":"",
  3658. buf2, cached?"YES":"NO");
  3659. }
  3660. return 0;
  3661. }
  3662. /** The authoritative dirserver has received a new descriptor that
  3663. * has passed basic syntax checks and is properly self-signed.
  3664. *
  3665. * Notify any interested party of the new descriptor and what has
  3666. * been done with it, and also optionally give an explanation/reason. */
  3667. int
  3668. control_event_or_authdir_new_descriptor(const char *action,
  3669. const char *desc, size_t desclen,
  3670. const char *msg)
  3671. {
  3672. char firstline[1024];
  3673. char *buf;
  3674. size_t totallen;
  3675. char *esc = NULL;
  3676. size_t esclen;
  3677. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  3678. return 0;
  3679. tor_snprintf(firstline, sizeof(firstline),
  3680. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  3681. action,
  3682. msg ? msg : "");
  3683. /* Escape the server descriptor properly */
  3684. esclen = write_escaped_data(desc, desclen, &esc);
  3685. totallen = strlen(firstline) + esclen + 1;
  3686. buf = tor_malloc(totallen);
  3687. strlcpy(buf, firstline, totallen);
  3688. strlcpy(buf+strlen(firstline), esc, totallen);
  3689. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3690. buf);
  3691. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3692. "650 OK\r\n");
  3693. tor_free(esc);
  3694. tor_free(buf);
  3695. return 0;
  3696. }
  3697. /** Helper function for NS-style events. Constructs and sends an event
  3698. * of type <b>event</b> with string <b>event_string</b> out of the set of
  3699. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  3700. * and NEWCONSENSUS events. */
  3701. static int
  3702. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  3703. uint16_t event,
  3704. const char *event_string)
  3705. {
  3706. smartlist_t *strs;
  3707. char *s, *esc = NULL;
  3708. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  3709. return 0;
  3710. strs = smartlist_new();
  3711. smartlist_add(strs, tor_strdup("650+"));
  3712. smartlist_add(strs, tor_strdup(event_string));
  3713. smartlist_add(strs, tor_strdup("\r\n"));
  3714. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  3715. {
  3716. s = networkstatus_getinfo_helper_single(rs);
  3717. if (!s) continue;
  3718. smartlist_add(strs, s);
  3719. });
  3720. s = smartlist_join_strings(strs, "", 0, NULL);
  3721. write_escaped_data(s, strlen(s), &esc);
  3722. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  3723. smartlist_free(strs);
  3724. tor_free(s);
  3725. send_control_event_string(event, ALL_FORMATS, esc);
  3726. send_control_event_string(event, ALL_FORMATS,
  3727. "650 OK\r\n");
  3728. tor_free(esc);
  3729. return 0;
  3730. }
  3731. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  3732. * an NS event to any controller that cares. */
  3733. int
  3734. control_event_networkstatus_changed(smartlist_t *statuses)
  3735. {
  3736. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  3737. }
  3738. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  3739. * event consisting of an NS-style line for each relay in the consensus. */
  3740. int
  3741. control_event_newconsensus(const networkstatus_t *consensus)
  3742. {
  3743. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  3744. return 0;
  3745. return control_event_networkstatus_changed_helper(
  3746. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  3747. }
  3748. /** Called when we compute a new circuitbuildtimeout */
  3749. int
  3750. control_event_buildtimeout_set(buildtimeout_set_event_t type,
  3751. const char *args)
  3752. {
  3753. const char *type_string = NULL;
  3754. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  3755. return 0;
  3756. switch (type) {
  3757. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  3758. type_string = "COMPUTED";
  3759. break;
  3760. case BUILDTIMEOUT_SET_EVENT_RESET:
  3761. type_string = "RESET";
  3762. break;
  3763. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  3764. type_string = "SUSPENDED";
  3765. break;
  3766. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  3767. type_string = "DISCARD";
  3768. break;
  3769. case BUILDTIMEOUT_SET_EVENT_RESUME:
  3770. type_string = "RESUME";
  3771. break;
  3772. default:
  3773. type_string = "UNKNOWN";
  3774. break;
  3775. }
  3776. send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
  3777. "650 BUILDTIMEOUT_SET %s %s\r\n",
  3778. type_string, args);
  3779. return 0;
  3780. }
  3781. /** Called when a signal has been processed from signal_callback */
  3782. int
  3783. control_event_signal(uintptr_t signal)
  3784. {
  3785. const char *signal_string = NULL;
  3786. if (!control_event_is_interesting(EVENT_SIGNAL))
  3787. return 0;
  3788. switch (signal) {
  3789. case SIGHUP:
  3790. signal_string = "RELOAD";
  3791. break;
  3792. case SIGUSR1:
  3793. signal_string = "DUMP";
  3794. break;
  3795. case SIGUSR2:
  3796. signal_string = "DEBUG";
  3797. break;
  3798. case SIGNEWNYM:
  3799. signal_string = "NEWNYM";
  3800. break;
  3801. case SIGCLEARDNSCACHE:
  3802. signal_string = "CLEARDNSCACHE";
  3803. break;
  3804. default:
  3805. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  3806. (unsigned long)signal);
  3807. return -1;
  3808. }
  3809. send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
  3810. signal_string);
  3811. return 0;
  3812. }
  3813. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  3814. * to any controller that cares. */
  3815. int
  3816. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  3817. {
  3818. smartlist_t *statuses;
  3819. int r;
  3820. if (!EVENT_IS_INTERESTING(EVENT_NS))
  3821. return 0;
  3822. statuses = smartlist_new();
  3823. smartlist_add(statuses, (void*)rs);
  3824. r = control_event_networkstatus_changed(statuses);
  3825. smartlist_free(statuses);
  3826. return r;
  3827. }
  3828. /** Our own router descriptor has changed; tell any controllers that care.
  3829. */
  3830. int
  3831. control_event_my_descriptor_changed(void)
  3832. {
  3833. send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
  3834. return 0;
  3835. }
  3836. /** Helper: sends a status event where <b>type</b> is one of
  3837. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  3838. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  3839. * string corresponding to <b>args</b>. */
  3840. static int
  3841. control_event_status(int type, int severity, const char *format, va_list args)
  3842. {
  3843. char *user_buf = NULL;
  3844. char format_buf[160];
  3845. const char *status, *sev;
  3846. switch (type) {
  3847. case EVENT_STATUS_GENERAL:
  3848. status = "STATUS_GENERAL";
  3849. break;
  3850. case EVENT_STATUS_CLIENT:
  3851. status = "STATUS_CLIENT";
  3852. break;
  3853. case EVENT_STATUS_SERVER:
  3854. status = "STATUS_SERVER";
  3855. break;
  3856. default:
  3857. log_warn(LD_BUG, "Unrecognized status type %d", type);
  3858. return -1;
  3859. }
  3860. switch (severity) {
  3861. case LOG_NOTICE:
  3862. sev = "NOTICE";
  3863. break;
  3864. case LOG_WARN:
  3865. sev = "WARN";
  3866. break;
  3867. case LOG_ERR:
  3868. sev = "ERR";
  3869. break;
  3870. default:
  3871. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  3872. return -1;
  3873. }
  3874. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  3875. status, sev)<0) {
  3876. log_warn(LD_BUG, "Format string too long.");
  3877. return -1;
  3878. }
  3879. tor_vasprintf(&user_buf, format, args);
  3880. send_control_event(type, ALL_FORMATS, "%s %s\r\n", format_buf, user_buf);
  3881. tor_free(user_buf);
  3882. return 0;
  3883. }
  3884. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  3885. * by formatting the arguments using the printf-style <b>format</b>. */
  3886. int
  3887. control_event_general_status(int severity, const char *format, ...)
  3888. {
  3889. va_list ap;
  3890. int r;
  3891. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  3892. return 0;
  3893. va_start(ap, format);
  3894. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  3895. va_end(ap);
  3896. return r;
  3897. }
  3898. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  3899. * by formatting the arguments using the printf-style <b>format</b>. */
  3900. int
  3901. control_event_client_status(int severity, const char *format, ...)
  3902. {
  3903. va_list ap;
  3904. int r;
  3905. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  3906. return 0;
  3907. va_start(ap, format);
  3908. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  3909. va_end(ap);
  3910. return r;
  3911. }
  3912. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  3913. * by formatting the arguments using the printf-style <b>format</b>. */
  3914. int
  3915. control_event_server_status(int severity, const char *format, ...)
  3916. {
  3917. va_list ap;
  3918. int r;
  3919. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  3920. return 0;
  3921. va_start(ap, format);
  3922. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  3923. va_end(ap);
  3924. return r;
  3925. }
  3926. /** Called when the status of an entry guard with the given <b>nickname</b>
  3927. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  3928. * controllers that care. */
  3929. int
  3930. control_event_guard(const char *nickname, const char *digest,
  3931. const char *status)
  3932. {
  3933. char hbuf[HEX_DIGEST_LEN+1];
  3934. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  3935. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  3936. return 0;
  3937. {
  3938. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  3939. const node_t *node = node_get_by_id(digest);
  3940. if (node) {
  3941. node_get_verbose_nickname(node, buf);
  3942. } else {
  3943. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  3944. }
  3945. send_control_event(EVENT_GUARD, ALL_FORMATS,
  3946. "650 GUARD ENTRY %s %s\r\n", buf, status);
  3947. }
  3948. return 0;
  3949. }
  3950. /** Called when a configuration option changes. This is generally triggered
  3951. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  3952. * a smartlist_t containing (key, value, ...) pairs in sequence.
  3953. * <b>value</b> can be NULL. */
  3954. int
  3955. control_event_conf_changed(const smartlist_t *elements)
  3956. {
  3957. int i;
  3958. char *result;
  3959. smartlist_t *lines;
  3960. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  3961. smartlist_len(elements) == 0) {
  3962. return 0;
  3963. }
  3964. lines = smartlist_new();
  3965. for (i = 0; i < smartlist_len(elements); i += 2) {
  3966. char *k = smartlist_get(elements, i);
  3967. char *v = smartlist_get(elements, i+1);
  3968. if (v == NULL) {
  3969. smartlist_add_asprintf(lines, "650-%s", k);
  3970. } else {
  3971. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  3972. }
  3973. }
  3974. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  3975. send_control_event(EVENT_CONF_CHANGED, 0,
  3976. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  3977. tor_free(result);
  3978. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  3979. smartlist_free(lines);
  3980. return 0;
  3981. }
  3982. /** Helper: Return a newly allocated string containing a path to the
  3983. * file where we store our authentication cookie. */
  3984. static char *
  3985. get_cookie_file(void)
  3986. {
  3987. const or_options_t *options = get_options();
  3988. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  3989. return tor_strdup(options->CookieAuthFile);
  3990. } else {
  3991. return get_datadir_fname("control_auth_cookie");
  3992. }
  3993. }
  3994. /* Initialize the cookie-based authentication system of the
  3995. * ControlPort. If <b>enabled</b> is 0, then disable the cookie
  3996. * authentication system. */
  3997. int
  3998. init_control_cookie_authentication(int enabled)
  3999. {
  4000. char *fname = NULL;
  4001. int retval;
  4002. if (!enabled) {
  4003. authentication_cookie_is_set = 0;
  4004. return 0;
  4005. }
  4006. fname = get_cookie_file();
  4007. retval = init_cookie_authentication(fname, "", /* no header */
  4008. AUTHENTICATION_COOKIE_LEN,
  4009. &authentication_cookie,
  4010. &authentication_cookie_is_set);
  4011. tor_free(fname);
  4012. return retval;
  4013. }
  4014. /** A copy of the process specifier of Tor's owning controller, or
  4015. * NULL if this Tor instance is not currently owned by a process. */
  4016. static char *owning_controller_process_spec = NULL;
  4017. /** A process-termination monitor for Tor's owning controller, or NULL
  4018. * if this Tor instance is not currently owned by a process. */
  4019. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  4020. /** Process-termination monitor callback for Tor's owning controller
  4021. * process. */
  4022. static void
  4023. owning_controller_procmon_cb(void *unused)
  4024. {
  4025. (void)unused;
  4026. lost_owning_controller("process", "vanished");
  4027. }
  4028. /** Set <b>process_spec</b> as Tor's owning controller process.
  4029. * Exit on failure. */
  4030. void
  4031. monitor_owning_controller_process(const char *process_spec)
  4032. {
  4033. const char *msg;
  4034. tor_assert((owning_controller_process_spec == NULL) ==
  4035. (owning_controller_process_monitor == NULL));
  4036. if (owning_controller_process_spec != NULL) {
  4037. if ((process_spec != NULL) && !strcmp(process_spec,
  4038. owning_controller_process_spec)) {
  4039. /* Same process -- return now, instead of disposing of and
  4040. * recreating the process-termination monitor. */
  4041. return;
  4042. }
  4043. /* We are currently owned by a process, and we should no longer be
  4044. * owned by it. Free the process-termination monitor. */
  4045. tor_process_monitor_free(owning_controller_process_monitor);
  4046. owning_controller_process_monitor = NULL;
  4047. tor_free(owning_controller_process_spec);
  4048. owning_controller_process_spec = NULL;
  4049. }
  4050. tor_assert((owning_controller_process_spec == NULL) &&
  4051. (owning_controller_process_monitor == NULL));
  4052. if (process_spec == NULL)
  4053. return;
  4054. owning_controller_process_spec = tor_strdup(process_spec);
  4055. owning_controller_process_monitor =
  4056. tor_process_monitor_new(tor_libevent_get_base(),
  4057. owning_controller_process_spec,
  4058. LD_CONTROL,
  4059. owning_controller_procmon_cb, NULL,
  4060. &msg);
  4061. if (owning_controller_process_monitor == NULL) {
  4062. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  4063. "owning controller: %s. Exiting.",
  4064. msg);
  4065. owning_controller_process_spec = NULL;
  4066. tor_cleanup();
  4067. exit(0);
  4068. }
  4069. }
  4070. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  4071. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  4072. static int
  4073. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  4074. const char **summary)
  4075. {
  4076. switch (s) {
  4077. case BOOTSTRAP_STATUS_UNDEF:
  4078. *tag = "undef";
  4079. *summary = "Undefined";
  4080. break;
  4081. case BOOTSTRAP_STATUS_STARTING:
  4082. *tag = "starting";
  4083. *summary = "Starting";
  4084. break;
  4085. case BOOTSTRAP_STATUS_CONN_DIR:
  4086. *tag = "conn_dir";
  4087. *summary = "Connecting to directory server";
  4088. break;
  4089. case BOOTSTRAP_STATUS_HANDSHAKE:
  4090. *tag = "status_handshake";
  4091. *summary = "Finishing handshake";
  4092. break;
  4093. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  4094. *tag = "handshake_dir";
  4095. *summary = "Finishing handshake with directory server";
  4096. break;
  4097. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  4098. *tag = "onehop_create";
  4099. *summary = "Establishing an encrypted directory connection";
  4100. break;
  4101. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  4102. *tag = "requesting_status";
  4103. *summary = "Asking for networkstatus consensus";
  4104. break;
  4105. case BOOTSTRAP_STATUS_LOADING_STATUS:
  4106. *tag = "loading_status";
  4107. *summary = "Loading networkstatus consensus";
  4108. break;
  4109. case BOOTSTRAP_STATUS_LOADING_KEYS:
  4110. *tag = "loading_keys";
  4111. *summary = "Loading authority key certs";
  4112. break;
  4113. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  4114. *tag = "requesting_descriptors";
  4115. *summary = "Asking for relay descriptors";
  4116. break;
  4117. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  4118. *tag = "loading_descriptors";
  4119. *summary = "Loading relay descriptors";
  4120. break;
  4121. case BOOTSTRAP_STATUS_CONN_OR:
  4122. *tag = "conn_or";
  4123. *summary = "Connecting to the Tor network";
  4124. break;
  4125. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  4126. *tag = "handshake_or";
  4127. *summary = "Finishing handshake with first hop";
  4128. break;
  4129. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  4130. *tag = "circuit_create";
  4131. *summary = "Establishing a Tor circuit";
  4132. break;
  4133. case BOOTSTRAP_STATUS_DONE:
  4134. *tag = "done";
  4135. *summary = "Done";
  4136. break;
  4137. default:
  4138. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  4139. *tag = *summary = "unknown";
  4140. return -1;
  4141. }
  4142. return 0;
  4143. }
  4144. /** What percentage through the bootstrap process are we? We remember
  4145. * this so we can avoid sending redundant bootstrap status events, and
  4146. * so we can guess context for the bootstrap messages which are
  4147. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  4148. * Tor initializes. */
  4149. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  4150. /** How many problems have we had getting to the next bootstrapping phase?
  4151. * These include failure to establish a connection to a Tor relay,
  4152. * failures to finish the TLS handshake, failures to validate the
  4153. * consensus document, etc. */
  4154. static int bootstrap_problems = 0;
  4155. /* We only tell the controller once we've hit a threshold of problems
  4156. * for the current phase. */
  4157. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  4158. /** Called when Tor has made progress at bootstrapping its directory
  4159. * information and initial circuits.
  4160. *
  4161. * <b>status</b> is the new status, that is, what task we will be doing
  4162. * next. <b>progress</b> is zero if we just started this task, else it
  4163. * represents progress on the task. */
  4164. void
  4165. control_event_bootstrap(bootstrap_status_t status, int progress)
  4166. {
  4167. const char *tag, *summary;
  4168. char buf[BOOTSTRAP_MSG_LEN];
  4169. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  4170. return; /* already bootstrapped; nothing to be done here. */
  4171. /* special case for handshaking status, since our TLS handshaking code
  4172. * can't distinguish what the connection is going to be for. */
  4173. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  4174. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  4175. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  4176. } else {
  4177. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  4178. }
  4179. }
  4180. if (status > bootstrap_percent ||
  4181. (progress && progress > bootstrap_percent)) {
  4182. bootstrap_status_to_string(status, &tag, &summary);
  4183. tor_log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
  4184. "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
  4185. tor_snprintf(buf, sizeof(buf),
  4186. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  4187. progress ? progress : status, tag, summary);
  4188. tor_snprintf(last_sent_bootstrap_message,
  4189. sizeof(last_sent_bootstrap_message),
  4190. "NOTICE %s", buf);
  4191. control_event_client_status(LOG_NOTICE, "%s", buf);
  4192. if (status > bootstrap_percent) {
  4193. bootstrap_percent = status; /* new milestone reached */
  4194. }
  4195. if (progress > bootstrap_percent) {
  4196. /* incremental progress within a milestone */
  4197. bootstrap_percent = progress;
  4198. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  4199. }
  4200. }
  4201. }
  4202. /** Called when Tor has failed to make bootstrapping progress in a way
  4203. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  4204. * <b>reason</b> provides an "or_conn_end_reason" tag.
  4205. */
  4206. MOCK_IMPL(void,
  4207. control_event_bootstrap_problem, (const char *warn, int reason))
  4208. {
  4209. int status = bootstrap_percent;
  4210. const char *tag, *summary;
  4211. char buf[BOOTSTRAP_MSG_LEN];
  4212. const char *recommendation = "ignore";
  4213. int severity;
  4214. /* bootstrap_percent must not be in "undefined" state here. */
  4215. tor_assert(status >= 0);
  4216. if (bootstrap_percent == 100)
  4217. return; /* already bootstrapped; nothing to be done here. */
  4218. bootstrap_problems++;
  4219. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  4220. recommendation = "warn";
  4221. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  4222. recommendation = "warn";
  4223. if (get_options()->UseBridges &&
  4224. !any_bridge_descriptors_known() &&
  4225. !any_pending_bridge_descriptor_fetches())
  4226. recommendation = "warn";
  4227. if (we_are_hibernating())
  4228. recommendation = "ignore";
  4229. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  4230. status--; /* find a recognized status string based on current progress */
  4231. status = bootstrap_percent; /* set status back to the actual number */
  4232. severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
  4233. log_fn(severity,
  4234. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  4235. "count %d; recommendation %s)",
  4236. status, summary, warn,
  4237. orconn_end_reason_to_control_string(reason),
  4238. bootstrap_problems, recommendation);
  4239. connection_or_report_broken_states(severity, LD_HANDSHAKE);
  4240. tor_snprintf(buf, sizeof(buf),
  4241. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  4242. "COUNT=%d RECOMMENDATION=%s",
  4243. bootstrap_percent, tag, summary, warn,
  4244. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  4245. recommendation);
  4246. tor_snprintf(last_sent_bootstrap_message,
  4247. sizeof(last_sent_bootstrap_message),
  4248. "WARN %s", buf);
  4249. control_event_client_status(LOG_WARN, "%s", buf);
  4250. }
  4251. /** We just generated a new summary of which countries we've seen clients
  4252. * from recently. Send a copy to the controller in case it wants to
  4253. * display it for the user. */
  4254. void
  4255. control_event_clients_seen(const char *controller_str)
  4256. {
  4257. send_control_event(EVENT_CLIENTS_SEEN, 0,
  4258. "650 CLIENTS_SEEN %s\r\n", controller_str);
  4259. }
  4260. /** A new pluggable transport called <b>transport_name</b> was
  4261. * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
  4262. * "server" or "client" depending on the mode of the pluggable
  4263. * transport.
  4264. * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
  4265. */
  4266. void
  4267. control_event_transport_launched(const char *mode, const char *transport_name,
  4268. tor_addr_t *addr, uint16_t port)
  4269. {
  4270. send_control_event(EVENT_TRANSPORT_LAUNCHED, ALL_FORMATS,
  4271. "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
  4272. mode, transport_name, fmt_addr(addr), port);
  4273. }
  4274. /** Free any leftover allocated memory of the control.c subsystem. */
  4275. void
  4276. control_free_all(void)
  4277. {
  4278. if (authentication_cookie) /* Free the auth cookie */
  4279. tor_free(authentication_cookie);
  4280. }
  4281. #ifdef TOR_UNIT_TESTS
  4282. /* For testing: change the value of global_event_mask */
  4283. void
  4284. control_testing_set_global_event_mask(uint64_t mask)
  4285. {
  4286. global_event_mask = mask;
  4287. }
  4288. #endif