control.c 156 KB

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