control.c 155 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697
  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. addressmap_register(from, tor_strdup(to), 1,
  1241. ADDRMAPSRC_CONTROLLER, 0, 0);
  1242. smartlist_add_asprintf(reply, "250-%s", line);
  1243. }
  1244. } else {
  1245. smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
  1246. "not of expected form 'foo=bar'.", line);
  1247. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1248. "number of items.",
  1249. safe_str_client(line));
  1250. }
  1251. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1252. smartlist_clear(elts);
  1253. } SMARTLIST_FOREACH_END(line);
  1254. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1255. smartlist_free(lines);
  1256. smartlist_free(elts);
  1257. if (smartlist_len(reply)) {
  1258. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1259. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1260. connection_write_to_buf(r, sz, TO_CONN(conn));
  1261. tor_free(r);
  1262. } else {
  1263. const char *response =
  1264. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1265. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1266. }
  1267. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1268. smartlist_free(reply);
  1269. return 0;
  1270. }
  1271. /** Implementation helper for GETINFO: knows the answers for various
  1272. * trivial-to-implement questions. */
  1273. static int
  1274. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1275. char **answer, const char **errmsg)
  1276. {
  1277. (void) conn;
  1278. if (!strcmp(question, "version")) {
  1279. *answer = tor_strdup(get_version());
  1280. } else if (!strcmp(question, "config-file")) {
  1281. *answer = tor_strdup(get_torrc_fname(0));
  1282. } else if (!strcmp(question, "config-defaults-file")) {
  1283. *answer = tor_strdup(get_torrc_fname(1));
  1284. } else if (!strcmp(question, "config-text")) {
  1285. *answer = options_dump(get_options(), 1);
  1286. } else if (!strcmp(question, "info/names")) {
  1287. *answer = list_getinfo_options();
  1288. } else if (!strcmp(question, "dormant")) {
  1289. int dormant = rep_hist_circbuilding_dormant(time(NULL));
  1290. *answer = tor_strdup(dormant ? "1" : "0");
  1291. } else if (!strcmp(question, "events/names")) {
  1292. int i;
  1293. smartlist_t *event_names = smartlist_new();
  1294. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  1295. smartlist_add(event_names, (char *)control_event_table[i].event_name);
  1296. }
  1297. *answer = smartlist_join_strings(event_names, " ", 0, NULL);
  1298. smartlist_free(event_names);
  1299. } else if (!strcmp(question, "features/names")) {
  1300. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1301. } else if (!strcmp(question, "address")) {
  1302. uint32_t addr;
  1303. if (router_pick_published_address(get_options(), &addr) < 0) {
  1304. *errmsg = "Address unknown";
  1305. return -1;
  1306. }
  1307. *answer = tor_dup_ip(addr);
  1308. } else if (!strcmp(question, "traffic/read")) {
  1309. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
  1310. } else if (!strcmp(question, "traffic/written")) {
  1311. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
  1312. } else if (!strcmp(question, "process/pid")) {
  1313. int myPid = -1;
  1314. #ifdef _WIN32
  1315. myPid = _getpid();
  1316. #else
  1317. myPid = getpid();
  1318. #endif
  1319. tor_asprintf(answer, "%d", myPid);
  1320. } else if (!strcmp(question, "process/uid")) {
  1321. #ifdef _WIN32
  1322. *answer = tor_strdup("-1");
  1323. #else
  1324. int myUid = geteuid();
  1325. tor_asprintf(answer, "%d", myUid);
  1326. #endif
  1327. } else if (!strcmp(question, "process/user")) {
  1328. #ifdef _WIN32
  1329. *answer = tor_strdup("");
  1330. #else
  1331. int myUid = geteuid();
  1332. struct passwd *myPwEntry = getpwuid(myUid);
  1333. if (myPwEntry) {
  1334. *answer = tor_strdup(myPwEntry->pw_name);
  1335. } else {
  1336. *answer = tor_strdup("");
  1337. }
  1338. #endif
  1339. } else if (!strcmp(question, "process/descriptor-limit")) {
  1340. int max_fds=-1;
  1341. set_max_file_descriptors(0, &max_fds);
  1342. tor_asprintf(answer, "%d", max_fds);
  1343. } else if (!strcmp(question, "dir-usage")) {
  1344. *answer = directory_dump_request_log();
  1345. } else if (!strcmp(question, "fingerprint")) {
  1346. crypto_pk_t *server_key;
  1347. if (!server_mode(get_options())) {
  1348. *errmsg = "Not running in server mode";
  1349. return -1;
  1350. }
  1351. server_key = get_server_identity_key();
  1352. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1353. crypto_pk_get_fingerprint(server_key, *answer, 0);
  1354. }
  1355. return 0;
  1356. }
  1357. /** Awful hack: return a newly allocated string based on a routerinfo and
  1358. * (possibly) an extrainfo, sticking the read-history and write-history from
  1359. * <b>ei</b> into the resulting string. The thing you get back won't
  1360. * necessarily have a valid signature.
  1361. *
  1362. * New code should never use this; it's for backward compatibility.
  1363. *
  1364. * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
  1365. * not be NUL-terminated. */
  1366. static char *
  1367. munge_extrainfo_into_routerinfo(const char *ri_body,
  1368. const signed_descriptor_t *ri,
  1369. const signed_descriptor_t *ei)
  1370. {
  1371. char *out = NULL, *outp;
  1372. int i;
  1373. const char *router_sig;
  1374. const char *ei_body = signed_descriptor_get_body(ei);
  1375. size_t ri_len = ri->signed_descriptor_len;
  1376. size_t ei_len = ei->signed_descriptor_len;
  1377. if (!ei_body)
  1378. goto bail;
  1379. outp = out = tor_malloc(ri_len+ei_len+1);
  1380. if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
  1381. goto bail;
  1382. ++router_sig;
  1383. memcpy(out, ri_body, router_sig-ri_body);
  1384. outp += router_sig-ri_body;
  1385. for (i=0; i < 2; ++i) {
  1386. const char *kwd = i?"\nwrite-history ":"\nread-history ";
  1387. const char *cp, *eol;
  1388. if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
  1389. continue;
  1390. ++cp;
  1391. eol = memchr(cp, '\n', ei_len - (cp-ei_body));
  1392. memcpy(outp, cp, eol-cp+1);
  1393. outp += eol-cp+1;
  1394. }
  1395. memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
  1396. *outp++ = '\0';
  1397. tor_assert(outp-out < (int)(ri_len+ei_len+1));
  1398. return out;
  1399. bail:
  1400. tor_free(out);
  1401. return tor_strndup(ri_body, ri->signed_descriptor_len);
  1402. }
  1403. /** Implementation helper for GETINFO: answers requests for information about
  1404. * which ports are bound. */
  1405. static int
  1406. getinfo_helper_listeners(control_connection_t *control_conn,
  1407. const char *question,
  1408. char **answer, const char **errmsg)
  1409. {
  1410. int type;
  1411. smartlist_t *res;
  1412. (void)control_conn;
  1413. (void)errmsg;
  1414. if (!strcmp(question, "net/listeners/or"))
  1415. type = CONN_TYPE_OR_LISTENER;
  1416. else if (!strcmp(question, "net/listeners/dir"))
  1417. type = CONN_TYPE_DIR_LISTENER;
  1418. else if (!strcmp(question, "net/listeners/socks"))
  1419. type = CONN_TYPE_AP_LISTENER;
  1420. else if (!strcmp(question, "net/listeners/trans"))
  1421. type = CONN_TYPE_AP_TRANS_LISTENER;
  1422. else if (!strcmp(question, "net/listeners/natd"))
  1423. type = CONN_TYPE_AP_NATD_LISTENER;
  1424. else if (!strcmp(question, "net/listeners/dns"))
  1425. type = CONN_TYPE_AP_DNS_LISTENER;
  1426. else if (!strcmp(question, "net/listeners/control"))
  1427. type = CONN_TYPE_CONTROL_LISTENER;
  1428. else
  1429. return 0; /* unknown key */
  1430. res = smartlist_new();
  1431. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  1432. struct sockaddr_storage ss;
  1433. socklen_t ss_len = sizeof(ss);
  1434. if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
  1435. continue;
  1436. if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
  1437. smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
  1438. } else {
  1439. char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
  1440. smartlist_add(res, esc_for_log(tmp));
  1441. tor_free(tmp);
  1442. }
  1443. } SMARTLIST_FOREACH_END(conn);
  1444. *answer = smartlist_join_strings(res, " ", 0, NULL);
  1445. SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
  1446. smartlist_free(res);
  1447. return 0;
  1448. }
  1449. /** Implementation helper for GETINFO: knows the answers for questions about
  1450. * directory information. */
  1451. static int
  1452. getinfo_helper_dir(control_connection_t *control_conn,
  1453. const char *question, char **answer,
  1454. const char **errmsg)
  1455. {
  1456. const routerinfo_t *ri;
  1457. (void) control_conn;
  1458. if (!strcmpstart(question, "desc/id/")) {
  1459. ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1460. if (ri) {
  1461. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1462. if (body)
  1463. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1464. }
  1465. } else if (!strcmpstart(question, "desc/name/")) {
  1466. /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
  1467. * warning goes to the user, not to the controller. */
  1468. ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  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 (!strcmp(question, "desc/all-recent")) {
  1475. routerlist_t *routerlist = router_get_routerlist();
  1476. smartlist_t *sl = smartlist_new();
  1477. if (routerlist && routerlist->routers) {
  1478. SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
  1479. {
  1480. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1481. if (body)
  1482. smartlist_add(sl,
  1483. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1484. });
  1485. }
  1486. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1487. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1488. smartlist_free(sl);
  1489. } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
  1490. /* XXXX Remove this once Torstat asks for extrainfos. */
  1491. routerlist_t *routerlist = router_get_routerlist();
  1492. smartlist_t *sl = smartlist_new();
  1493. if (routerlist && routerlist->routers) {
  1494. SMARTLIST_FOREACH_BEGIN(routerlist->routers, const routerinfo_t *, ri) {
  1495. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1496. signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
  1497. ri->cache_info.extra_info_digest);
  1498. if (ei && body) {
  1499. smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
  1500. &ri->cache_info, ei));
  1501. } else if (body) {
  1502. smartlist_add(sl,
  1503. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1504. }
  1505. } SMARTLIST_FOREACH_END(ri);
  1506. }
  1507. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1508. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1509. smartlist_free(sl);
  1510. } else if (!strcmpstart(question, "md/id/")) {
  1511. const node_t *node = node_get_by_hex_id(question+strlen("md/id/"));
  1512. const microdesc_t *md = NULL;
  1513. if (node) md = node->md;
  1514. if (md) {
  1515. tor_assert(md->body);
  1516. *answer = tor_strndup(md->body, md->bodylen);
  1517. }
  1518. } else if (!strcmpstart(question, "md/name/")) {
  1519. /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
  1520. * warning goes to the user, not to the controller. */
  1521. const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 1);
  1522. /* XXXX duplicated code */
  1523. const microdesc_t *md = NULL;
  1524. if (node) md = node->md;
  1525. if (md) {
  1526. tor_assert(md->body);
  1527. *answer = tor_strndup(md->body, md->bodylen);
  1528. }
  1529. } else if (!strcmpstart(question, "desc-annotations/id/")) {
  1530. ri = router_get_by_hexdigest(question+
  1531. strlen("desc-annotations/id/"));
  1532. if (ri) {
  1533. const char *annotations =
  1534. signed_descriptor_get_annotations(&ri->cache_info);
  1535. if (annotations)
  1536. *answer = tor_strndup(annotations,
  1537. ri->cache_info.annotations_len);
  1538. }
  1539. } else if (!strcmpstart(question, "dir/server/")) {
  1540. size_t answer_len = 0;
  1541. char *url = NULL;
  1542. smartlist_t *descs = smartlist_new();
  1543. const char *msg;
  1544. int res;
  1545. char *cp;
  1546. tor_asprintf(&url, "/tor/%s", question+4);
  1547. res = dirserv_get_routerdescs(descs, url, &msg);
  1548. if (res) {
  1549. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1550. smartlist_free(descs);
  1551. tor_free(url);
  1552. *errmsg = msg;
  1553. return -1;
  1554. }
  1555. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1556. answer_len += sd->signed_descriptor_len);
  1557. cp = *answer = tor_malloc(answer_len+1);
  1558. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1559. {
  1560. memcpy(cp, signed_descriptor_get_body(sd),
  1561. sd->signed_descriptor_len);
  1562. cp += sd->signed_descriptor_len;
  1563. });
  1564. *cp = '\0';
  1565. tor_free(url);
  1566. smartlist_free(descs);
  1567. } else if (!strcmpstart(question, "dir/status/")) {
  1568. if (directory_permits_controller_requests(get_options())) {
  1569. size_t len=0;
  1570. char *cp;
  1571. smartlist_t *status_list = smartlist_new();
  1572. dirserv_get_networkstatus_v2(status_list,
  1573. question+strlen("dir/status/"));
  1574. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1575. cp = *answer = tor_malloc(len+1);
  1576. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1577. memcpy(cp, d->dir, d->dir_len);
  1578. cp += d->dir_len;
  1579. });
  1580. *cp = '\0';
  1581. smartlist_free(status_list);
  1582. } else {
  1583. smartlist_t *fp_list = smartlist_new();
  1584. smartlist_t *status_list = smartlist_new();
  1585. dirserv_get_networkstatus_v2_fingerprints(
  1586. fp_list, question+strlen("dir/status/"));
  1587. SMARTLIST_FOREACH(fp_list, const char *, fp, {
  1588. char *s;
  1589. char *fname = networkstatus_get_cache_filename(fp);
  1590. s = read_file_to_str(fname, 0, NULL);
  1591. if (s)
  1592. smartlist_add(status_list, s);
  1593. tor_free(fname);
  1594. });
  1595. SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
  1596. smartlist_free(fp_list);
  1597. *answer = smartlist_join_strings(status_list, "", 0, NULL);
  1598. SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
  1599. smartlist_free(status_list);
  1600. }
  1601. } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
  1602. if (directory_caches_dir_info(get_options())) {
  1603. const cached_dir_t *consensus = dirserv_get_consensus("ns");
  1604. if (consensus)
  1605. *answer = tor_strdup(consensus->dir);
  1606. }
  1607. if (!*answer) { /* try loading it from disk */
  1608. char *filename = get_datadir_fname("cached-consensus");
  1609. *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  1610. tor_free(filename);
  1611. }
  1612. } else if (!strcmp(question, "network-status")) { /* v1 */
  1613. routerlist_t *routerlist = router_get_routerlist();
  1614. if (!routerlist || !routerlist->routers ||
  1615. list_server_status_v1(routerlist->routers, answer, 1) < 0) {
  1616. return -1;
  1617. }
  1618. } else if (!strcmpstart(question, "extra-info/digest/")) {
  1619. question += strlen("extra-info/digest/");
  1620. if (strlen(question) == HEX_DIGEST_LEN) {
  1621. char d[DIGEST_LEN];
  1622. signed_descriptor_t *sd = NULL;
  1623. if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
  1624. /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
  1625. * but I don't want to risk affecting other parts of the code,
  1626. * especially since the rules for using our own extrainfo (including
  1627. * when it might be freed) are different from those for using one
  1628. * we have downloaded. */
  1629. if (router_extrainfo_digest_is_me(d))
  1630. sd = &(router_get_my_extrainfo()->cache_info);
  1631. else
  1632. sd = extrainfo_get_by_descriptor_digest(d);
  1633. }
  1634. if (sd) {
  1635. const char *body = signed_descriptor_get_body(sd);
  1636. if (body)
  1637. *answer = tor_strndup(body, sd->signed_descriptor_len);
  1638. }
  1639. }
  1640. }
  1641. return 0;
  1642. }
  1643. /** Allocate and return a description of <b>circ</b>'s current status,
  1644. * including its path (if any). */
  1645. static char *
  1646. circuit_describe_status_for_controller(origin_circuit_t *circ)
  1647. {
  1648. char *rv;
  1649. smartlist_t *descparts = smartlist_new();
  1650. {
  1651. char *vpath = circuit_list_path_for_controller(circ);
  1652. if (*vpath) {
  1653. smartlist_add(descparts, vpath);
  1654. } else {
  1655. tor_free(vpath); /* empty path; don't put an extra space in the result */
  1656. }
  1657. }
  1658. {
  1659. cpath_build_state_t *build_state = circ->build_state;
  1660. smartlist_t *flaglist = smartlist_new();
  1661. char *flaglist_joined;
  1662. if (build_state->onehop_tunnel)
  1663. smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
  1664. if (build_state->is_internal)
  1665. smartlist_add(flaglist, (void *)"IS_INTERNAL");
  1666. if (build_state->need_capacity)
  1667. smartlist_add(flaglist, (void *)"NEED_CAPACITY");
  1668. if (build_state->need_uptime)
  1669. smartlist_add(flaglist, (void *)"NEED_UPTIME");
  1670. /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
  1671. if (smartlist_len(flaglist)) {
  1672. flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
  1673. smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
  1674. tor_free(flaglist_joined);
  1675. }
  1676. smartlist_free(flaglist);
  1677. }
  1678. smartlist_add_asprintf(descparts, "PURPOSE=%s",
  1679. circuit_purpose_to_controller_string(circ->_base.purpose));
  1680. {
  1681. const char *hs_state =
  1682. circuit_purpose_to_controller_hs_state_string(circ->_base.purpose);
  1683. if (hs_state != NULL) {
  1684. smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
  1685. }
  1686. }
  1687. if (circ->rend_data != NULL) {
  1688. smartlist_add_asprintf(descparts, "REND_QUERY=%s",
  1689. circ->rend_data->onion_address);
  1690. }
  1691. {
  1692. char tbuf[ISO_TIME_USEC_LEN+1];
  1693. format_iso_time_nospace_usec(tbuf, &circ->_base.timestamp_created);
  1694. smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
  1695. }
  1696. rv = smartlist_join_strings(descparts, " ", 0, NULL);
  1697. SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
  1698. smartlist_free(descparts);
  1699. return rv;
  1700. }
  1701. /** Implementation helper for GETINFO: knows how to generate summaries of the
  1702. * current states of things we send events about. */
  1703. static int
  1704. getinfo_helper_events(control_connection_t *control_conn,
  1705. const char *question, char **answer,
  1706. const char **errmsg)
  1707. {
  1708. (void) control_conn;
  1709. if (!strcmp(question, "circuit-status")) {
  1710. circuit_t *circ_;
  1711. smartlist_t *status = smartlist_new();
  1712. for (circ_ = _circuit_get_global_list(); circ_; circ_ = circ_->next) {
  1713. origin_circuit_t *circ;
  1714. char *circdesc;
  1715. const char *state;
  1716. if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
  1717. continue;
  1718. circ = TO_ORIGIN_CIRCUIT(circ_);
  1719. if (circ->_base.state == CIRCUIT_STATE_OPEN)
  1720. state = "BUILT";
  1721. else if (circ->cpath)
  1722. state = "EXTENDED";
  1723. else
  1724. state = "LAUNCHED";
  1725. circdesc = circuit_describe_status_for_controller(circ);
  1726. smartlist_add_asprintf(status, "%lu %s%s%s",
  1727. (unsigned long)circ->global_identifier,
  1728. state, *circdesc ? " " : "", circdesc);
  1729. tor_free(circdesc);
  1730. }
  1731. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1732. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1733. smartlist_free(status);
  1734. } else if (!strcmp(question, "stream-status")) {
  1735. smartlist_t *conns = get_connection_array();
  1736. smartlist_t *status = smartlist_new();
  1737. char buf[256];
  1738. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1739. const char *state;
  1740. entry_connection_t *conn;
  1741. circuit_t *circ;
  1742. origin_circuit_t *origin_circ = NULL;
  1743. if (base_conn->type != CONN_TYPE_AP ||
  1744. base_conn->marked_for_close ||
  1745. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  1746. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  1747. continue;
  1748. conn = TO_ENTRY_CONN(base_conn);
  1749. switch (base_conn->state)
  1750. {
  1751. case AP_CONN_STATE_CONTROLLER_WAIT:
  1752. case AP_CONN_STATE_CIRCUIT_WAIT:
  1753. if (conn->socks_request &&
  1754. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1755. state = "NEWRESOLVE";
  1756. else
  1757. state = "NEW";
  1758. break;
  1759. case AP_CONN_STATE_RENDDESC_WAIT:
  1760. case AP_CONN_STATE_CONNECT_WAIT:
  1761. state = "SENTCONNECT"; break;
  1762. case AP_CONN_STATE_RESOLVE_WAIT:
  1763. state = "SENTRESOLVE"; break;
  1764. case AP_CONN_STATE_OPEN:
  1765. state = "SUCCEEDED"; break;
  1766. default:
  1767. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1768. base_conn->state);
  1769. continue;
  1770. }
  1771. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  1772. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1773. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1774. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1775. smartlist_add_asprintf(status, "%lu %s %lu %s",
  1776. (unsigned long) base_conn->global_identifier,state,
  1777. origin_circ?
  1778. (unsigned long)origin_circ->global_identifier : 0ul,
  1779. buf);
  1780. } SMARTLIST_FOREACH_END(base_conn);
  1781. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1782. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1783. smartlist_free(status);
  1784. } else if (!strcmp(question, "orconn-status")) {
  1785. smartlist_t *conns = get_connection_array();
  1786. smartlist_t *status = smartlist_new();
  1787. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1788. const char *state;
  1789. char name[128];
  1790. or_connection_t *conn;
  1791. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  1792. continue;
  1793. conn = TO_OR_CONN(base_conn);
  1794. if (conn->_base.state == OR_CONN_STATE_OPEN)
  1795. state = "CONNECTED";
  1796. else if (conn->nickname)
  1797. state = "LAUNCHED";
  1798. else
  1799. state = "NEW";
  1800. orconn_target_get_name(name, sizeof(name), conn);
  1801. smartlist_add_asprintf(status, "%s %s", name, state);
  1802. } SMARTLIST_FOREACH_END(base_conn);
  1803. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1804. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1805. smartlist_free(status);
  1806. } else if (!strcmpstart(question, "address-mappings/")) {
  1807. time_t min_e, max_e;
  1808. smartlist_t *mappings;
  1809. question += strlen("address-mappings/");
  1810. if (!strcmp(question, "all")) {
  1811. min_e = 0; max_e = TIME_MAX;
  1812. } else if (!strcmp(question, "cache")) {
  1813. min_e = 2; max_e = TIME_MAX;
  1814. } else if (!strcmp(question, "config")) {
  1815. min_e = 0; max_e = 0;
  1816. } else if (!strcmp(question, "control")) {
  1817. min_e = 1; max_e = 1;
  1818. } else {
  1819. return 0;
  1820. }
  1821. mappings = smartlist_new();
  1822. addressmap_get_mappings(mappings, min_e, max_e, 1);
  1823. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1824. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1825. smartlist_free(mappings);
  1826. } else if (!strcmpstart(question, "status/")) {
  1827. /* Note that status/ is not a catch-all for events; there's only supposed
  1828. * to be a status GETINFO if there's a corresponding STATUS event. */
  1829. if (!strcmp(question, "status/circuit-established")) {
  1830. *answer = tor_strdup(can_complete_circuit ? "1" : "0");
  1831. } else if (!strcmp(question, "status/enough-dir-info")) {
  1832. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  1833. } else if (!strcmp(question, "status/good-server-descriptor") ||
  1834. !strcmp(question, "status/accepted-server-descriptor")) {
  1835. /* They're equivalent for now, until we can figure out how to make
  1836. * good-server-descriptor be what we want. See comment in
  1837. * control-spec.txt. */
  1838. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  1839. ? "1" : "0");
  1840. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  1841. *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
  1842. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  1843. *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
  1844. } else if (!strcmp(question, "status/reachability-succeeded")) {
  1845. tor_asprintf(answer, "OR=%d DIR=%d",
  1846. check_whether_orport_reachable() ? 1 : 0,
  1847. check_whether_dirport_reachable() ? 1 : 0);
  1848. } else if (!strcmp(question, "status/bootstrap-phase")) {
  1849. *answer = tor_strdup(last_sent_bootstrap_message);
  1850. } else if (!strcmpstart(question, "status/version/")) {
  1851. int is_server = server_mode(get_options());
  1852. networkstatus_t *c = networkstatus_get_latest_consensus();
  1853. version_status_t status;
  1854. const char *recommended;
  1855. if (c) {
  1856. recommended = is_server ? c->server_versions : c->client_versions;
  1857. status = tor_version_is_obsolete(VERSION, recommended);
  1858. } else {
  1859. recommended = "?";
  1860. status = VS_UNKNOWN;
  1861. }
  1862. if (!strcmp(question, "status/version/recommended")) {
  1863. *answer = tor_strdup(recommended);
  1864. return 0;
  1865. }
  1866. if (!strcmp(question, "status/version/current")) {
  1867. switch (status)
  1868. {
  1869. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  1870. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  1871. case VS_NEW: *answer = tor_strdup("new"); break;
  1872. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  1873. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  1874. case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
  1875. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  1876. default: tor_fragile_assert();
  1877. }
  1878. } else if (!strcmp(question, "status/version/num-versioning") ||
  1879. !strcmp(question, "status/version/num-concurring")) {
  1880. tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
  1881. log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
  1882. "information", question);
  1883. }
  1884. } else if (!strcmp(question, "status/clients-seen")) {
  1885. char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
  1886. if (!bridge_stats) {
  1887. *errmsg = "No bridge-client stats available";
  1888. return -1;
  1889. }
  1890. *answer = bridge_stats;
  1891. } else {
  1892. return 0;
  1893. }
  1894. }
  1895. return 0;
  1896. }
  1897. /** Callback function for GETINFO: on a given control connection, try to
  1898. * answer the question <b>q</b> and store the newly-allocated answer in
  1899. * *<b>a</b>. If an internal error occurs, return -1 and optionally set
  1900. * *<b>error_out</b> to point to an error message to be delivered to the
  1901. * controller. On success, _or if the key is not recognized_, return 0. Do not
  1902. * set <b>a</b> if the key is not recognized.
  1903. */
  1904. typedef int (*getinfo_helper_t)(control_connection_t *,
  1905. const char *q, char **a,
  1906. const char **error_out);
  1907. /** A single item for the GETINFO question-to-answer-function table. */
  1908. typedef struct getinfo_item_t {
  1909. const char *varname; /**< The value (or prefix) of the question. */
  1910. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  1911. * this entry is documentation-only. */
  1912. const char *desc; /**< Description of the variable. */
  1913. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  1914. } getinfo_item_t;
  1915. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  1916. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  1917. #define DOC(name, desc) { name, NULL, desc, 0 }
  1918. /** Table mapping questions accepted by GETINFO to the functions that know how
  1919. * to answer them. */
  1920. static const getinfo_item_t getinfo_items[] = {
  1921. ITEM("version", misc, "The current version of Tor."),
  1922. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  1923. ITEM("config-defaults-file", misc, "Current location of the defaults file."),
  1924. ITEM("config-text", misc,
  1925. "Return the string that would be written by a saveconf command."),
  1926. ITEM("accounting/bytes", accounting,
  1927. "Number of bytes read/written so far in the accounting interval."),
  1928. ITEM("accounting/bytes-left", accounting,
  1929. "Number of bytes left to write/read so far in the accounting interval."),
  1930. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  1931. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  1932. ITEM("accounting/interval-start", accounting,
  1933. "Time when the accounting period starts."),
  1934. ITEM("accounting/interval-end", accounting,
  1935. "Time when the accounting period ends."),
  1936. ITEM("accounting/interval-wake", accounting,
  1937. "Time to wake up in this accounting period."),
  1938. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  1939. ITEM("entry-guards", entry_guards,
  1940. "Which nodes are we using as entry guards?"),
  1941. ITEM("fingerprint", misc, NULL),
  1942. PREFIX("config/", config, "Current configuration values."),
  1943. DOC("config/names",
  1944. "List of configuration options, types, and documentation."),
  1945. ITEM("info/names", misc,
  1946. "List of GETINFO options, types, and documentation."),
  1947. ITEM("events/names", misc,
  1948. "Events that the controller can ask for with SETEVENTS."),
  1949. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  1950. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  1951. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  1952. ITEM("desc/all-recent", dir,
  1953. "All non-expired, non-superseded router descriptors."),
  1954. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  1955. PREFIX("md/id/", dir, "Microdescriptors by ID"),
  1956. PREFIX("md/name/", dir, "Microdescriptors by name"),
  1957. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  1958. PREFIX("net/listeners/", listeners, "Bound addresses by type"),
  1959. ITEM("ns/all", networkstatus,
  1960. "Brief summary of router status (v2 directory format)"),
  1961. PREFIX("ns/id/", networkstatus,
  1962. "Brief summary of router status by ID (v2 directory format)."),
  1963. PREFIX("ns/name/", networkstatus,
  1964. "Brief summary of router status by nickname (v2 directory format)."),
  1965. PREFIX("ns/purpose/", networkstatus,
  1966. "Brief summary of router status by purpose (v2 directory format)."),
  1967. ITEM("network-status", dir,
  1968. "Brief summary of router status (v1 directory format)"),
  1969. ITEM("circuit-status", events, "List of current circuits originating here."),
  1970. ITEM("stream-status", events,"List of current streams."),
  1971. ITEM("orconn-status", events, "A list of current OR connections."),
  1972. ITEM("dormant", misc,
  1973. "Is Tor dormant (not building circuits because it's idle)?"),
  1974. PREFIX("address-mappings/", events, NULL),
  1975. DOC("address-mappings/all", "Current address mappings."),
  1976. DOC("address-mappings/cache", "Current cached DNS replies."),
  1977. DOC("address-mappings/config",
  1978. "Current address mappings from configuration."),
  1979. DOC("address-mappings/control", "Current address mappings from controller."),
  1980. PREFIX("status/", events, NULL),
  1981. DOC("status/circuit-established",
  1982. "Whether we think client functionality is working."),
  1983. DOC("status/enough-dir-info",
  1984. "Whether we have enough up-to-date directory information to build "
  1985. "circuits."),
  1986. DOC("status/bootstrap-phase",
  1987. "The last bootstrap phase status event that Tor sent."),
  1988. DOC("status/clients-seen",
  1989. "Breakdown of client countries seen by a bridge."),
  1990. DOC("status/version/recommended", "List of currently recommended versions."),
  1991. DOC("status/version/current", "Status of the current version."),
  1992. DOC("status/version/num-versioning", "Number of versioning authorities."),
  1993. DOC("status/version/num-concurring",
  1994. "Number of versioning authorities agreeing on the status of the "
  1995. "current version"),
  1996. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  1997. ITEM("traffic/read", misc,"Bytes read since the process was started."),
  1998. ITEM("traffic/written", misc,
  1999. "Bytes written since the process was started."),
  2000. ITEM("process/pid", misc, "Process id belonging to the main tor process."),
  2001. ITEM("process/uid", misc, "User id running the tor process."),
  2002. ITEM("process/user", misc,
  2003. "Username under which the tor process is running."),
  2004. ITEM("process/descriptor-limit", misc, "File descriptor limit."),
  2005. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  2006. PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
  2007. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  2008. PREFIX("dir/status/", dir,
  2009. "v2 networkstatus docs as retrieved from a DirPort."),
  2010. ITEM("dir/status-vote/current/consensus", dir,
  2011. "v3 Networkstatus consensus as retrieved from a DirPort."),
  2012. ITEM("exit-policy/default", policies,
  2013. "The default value appended to the configured exit policy."),
  2014. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  2015. { NULL, NULL, NULL, 0 }
  2016. };
  2017. /** Allocate and return a list of recognized GETINFO options. */
  2018. static char *
  2019. list_getinfo_options(void)
  2020. {
  2021. int i;
  2022. smartlist_t *lines = smartlist_new();
  2023. char *ans;
  2024. for (i = 0; getinfo_items[i].varname; ++i) {
  2025. if (!getinfo_items[i].desc)
  2026. continue;
  2027. smartlist_add_asprintf(lines, "%s%s -- %s\n",
  2028. getinfo_items[i].varname,
  2029. getinfo_items[i].is_prefix ? "*" : "",
  2030. getinfo_items[i].desc);
  2031. }
  2032. smartlist_sort_strings(lines);
  2033. ans = smartlist_join_strings(lines, "", 0, NULL);
  2034. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  2035. smartlist_free(lines);
  2036. return ans;
  2037. }
  2038. /** Lookup the 'getinfo' entry <b>question</b>, and return
  2039. * the answer in <b>*answer</b> (or NULL if key not recognized).
  2040. * Return 0 if success or unrecognized, or -1 if recognized but
  2041. * internal error. */
  2042. static int
  2043. handle_getinfo_helper(control_connection_t *control_conn,
  2044. const char *question, char **answer,
  2045. const char **err_out)
  2046. {
  2047. int i;
  2048. *answer = NULL; /* unrecognized key by default */
  2049. for (i = 0; getinfo_items[i].varname; ++i) {
  2050. int match;
  2051. if (getinfo_items[i].is_prefix)
  2052. match = !strcmpstart(question, getinfo_items[i].varname);
  2053. else
  2054. match = !strcmp(question, getinfo_items[i].varname);
  2055. if (match) {
  2056. tor_assert(getinfo_items[i].fn);
  2057. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  2058. }
  2059. }
  2060. return 0; /* unrecognized */
  2061. }
  2062. /** Called when we receive a GETINFO command. Try to fetch all requested
  2063. * information, and reply with information or error message. */
  2064. static int
  2065. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  2066. const char *body)
  2067. {
  2068. smartlist_t *questions = smartlist_new();
  2069. smartlist_t *answers = smartlist_new();
  2070. smartlist_t *unrecognized = smartlist_new();
  2071. char *msg = NULL, *ans = NULL;
  2072. int i;
  2073. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2074. smartlist_split_string(questions, body, " ",
  2075. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2076. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  2077. const char *errmsg = NULL;
  2078. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  2079. if (!errmsg)
  2080. errmsg = "Internal error";
  2081. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  2082. goto done;
  2083. }
  2084. if (!ans) {
  2085. smartlist_add(unrecognized, (char*)q);
  2086. } else {
  2087. smartlist_add(answers, tor_strdup(q));
  2088. smartlist_add(answers, ans);
  2089. }
  2090. } SMARTLIST_FOREACH_END(q);
  2091. if (smartlist_len(unrecognized)) {
  2092. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  2093. connection_printf_to_buf(conn,
  2094. "552-Unrecognized key \"%s\"\r\n",
  2095. (char*)smartlist_get(unrecognized, i));
  2096. connection_printf_to_buf(conn,
  2097. "552 Unrecognized key \"%s\"\r\n",
  2098. (char*)smartlist_get(unrecognized, i));
  2099. goto done;
  2100. }
  2101. for (i = 0; i < smartlist_len(answers); i += 2) {
  2102. char *k = smartlist_get(answers, i);
  2103. char *v = smartlist_get(answers, i+1);
  2104. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  2105. connection_printf_to_buf(conn, "250-%s=", k);
  2106. connection_write_str_to_buf(v, conn);
  2107. connection_write_str_to_buf("\r\n", conn);
  2108. } else {
  2109. char *esc = NULL;
  2110. size_t esc_len;
  2111. esc_len = write_escaped_data(v, strlen(v), &esc);
  2112. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  2113. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  2114. tor_free(esc);
  2115. }
  2116. }
  2117. connection_write_str_to_buf("250 OK\r\n", conn);
  2118. done:
  2119. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  2120. smartlist_free(answers);
  2121. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  2122. smartlist_free(questions);
  2123. smartlist_free(unrecognized);
  2124. tor_free(msg);
  2125. return 0;
  2126. }
  2127. /** Given a string, convert it to a circuit purpose. */
  2128. static uint8_t
  2129. circuit_purpose_from_string(const char *string)
  2130. {
  2131. if (!strcasecmpstart(string, "purpose="))
  2132. string += strlen("purpose=");
  2133. if (!strcasecmp(string, "general"))
  2134. return CIRCUIT_PURPOSE_C_GENERAL;
  2135. else if (!strcasecmp(string, "controller"))
  2136. return CIRCUIT_PURPOSE_CONTROLLER;
  2137. else
  2138. return CIRCUIT_PURPOSE_UNKNOWN;
  2139. }
  2140. /** Return a newly allocated smartlist containing the arguments to the command
  2141. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  2142. * or if <b>max_args</b> is nonnegative and there are more than
  2143. * <b>max_args</b> arguments, send a 512 error to the controller, using
  2144. * <b>command</b> as the command name in the error message. */
  2145. static smartlist_t *
  2146. getargs_helper(const char *command, control_connection_t *conn,
  2147. const char *body, int min_args, int max_args)
  2148. {
  2149. smartlist_t *args = smartlist_new();
  2150. smartlist_split_string(args, body, " ",
  2151. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2152. if (smartlist_len(args) < min_args) {
  2153. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  2154. goto err;
  2155. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  2156. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  2157. goto err;
  2158. }
  2159. return args;
  2160. err:
  2161. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  2162. smartlist_free(args);
  2163. return NULL;
  2164. }
  2165. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  2166. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  2167. * such element exists. */
  2168. static const char *
  2169. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  2170. {
  2171. int i;
  2172. for (i = start_at; i < smartlist_len(sl); ++i) {
  2173. const char *elt = smartlist_get(sl, i);
  2174. if (!strcasecmpstart(elt, prefix))
  2175. return elt;
  2176. }
  2177. return NULL;
  2178. }
  2179. /** Helper. Return true iff s is an argument that we should treat as a
  2180. * key-value pair. */
  2181. static int
  2182. is_keyval_pair(const char *s)
  2183. {
  2184. /* An argument is a key-value pair if it has an =, and it isn't of the form
  2185. * $fingeprint=name */
  2186. return strchr(s, '=') && s[0] != '$';
  2187. }
  2188. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  2189. * circuit, and report success or failure. */
  2190. static int
  2191. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  2192. const char *body)
  2193. {
  2194. smartlist_t *router_nicknames=NULL, *nodes=NULL;
  2195. origin_circuit_t *circ = NULL;
  2196. int zero_circ;
  2197. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  2198. smartlist_t *args;
  2199. (void) len;
  2200. router_nicknames = smartlist_new();
  2201. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  2202. if (!args)
  2203. goto done;
  2204. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  2205. if (zero_circ) {
  2206. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  2207. if (purp) {
  2208. intended_purpose = circuit_purpose_from_string(purp);
  2209. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2210. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2211. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2212. smartlist_free(args);
  2213. goto done;
  2214. }
  2215. }
  2216. if ((smartlist_len(args) == 1) ||
  2217. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  2218. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  2219. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  2220. if (!circ) {
  2221. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2222. } else {
  2223. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2224. (unsigned long)circ->global_identifier);
  2225. }
  2226. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2227. smartlist_free(args);
  2228. goto done;
  2229. }
  2230. // "EXTENDCIRCUIT 0 router1,router2" ||
  2231. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  2232. }
  2233. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  2234. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2235. (char*)smartlist_get(args, 0));
  2236. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2237. smartlist_free(args);
  2238. goto done;
  2239. }
  2240. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  2241. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2242. smartlist_free(args);
  2243. nodes = smartlist_new();
  2244. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  2245. const node_t *node = node_get_by_nickname(n, 1);
  2246. if (!node) {
  2247. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  2248. goto done;
  2249. }
  2250. if (!node_has_descriptor(node)) {
  2251. connection_printf_to_buf(conn, "552 descriptor for \"%s\"\r\n", n);
  2252. goto done;
  2253. }
  2254. smartlist_add(nodes, (void*)node);
  2255. } SMARTLIST_FOREACH_END(n);
  2256. if (!smartlist_len(nodes)) {
  2257. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  2258. goto done;
  2259. }
  2260. if (zero_circ) {
  2261. /* start a new circuit */
  2262. circ = origin_circuit_init(intended_purpose, 0);
  2263. }
  2264. /* now circ refers to something that is ready to be extended */
  2265. SMARTLIST_FOREACH(nodes, const node_t *, node,
  2266. {
  2267. extend_info_t *info = extend_info_from_node(node, 0);
  2268. tor_assert(info); /* True, since node_has_descriptor(node) == true */
  2269. circuit_append_new_exit(circ, info);
  2270. extend_info_free(info);
  2271. });
  2272. /* now that we've populated the cpath, start extending */
  2273. if (zero_circ) {
  2274. int err_reason = 0;
  2275. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  2276. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2277. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2278. goto done;
  2279. }
  2280. } else {
  2281. if (circ->_base.state == CIRCUIT_STATE_OPEN) {
  2282. int err_reason = 0;
  2283. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2284. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  2285. log_info(LD_CONTROL,
  2286. "send_next_onion_skin failed; circuit marked for closing.");
  2287. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2288. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  2289. goto done;
  2290. }
  2291. }
  2292. }
  2293. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2294. (unsigned long)circ->global_identifier);
  2295. if (zero_circ) /* send a 'launched' event, for completeness */
  2296. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  2297. done:
  2298. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  2299. smartlist_free(router_nicknames);
  2300. smartlist_free(nodes);
  2301. return 0;
  2302. }
  2303. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  2304. * circuit and it's a valid purpose, change it. */
  2305. static int
  2306. handle_control_setcircuitpurpose(control_connection_t *conn,
  2307. uint32_t len, const char *body)
  2308. {
  2309. origin_circuit_t *circ = NULL;
  2310. uint8_t new_purpose;
  2311. smartlist_t *args;
  2312. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2313. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  2314. if (!args)
  2315. goto done;
  2316. if (!(circ = get_circ(smartlist_get(args,0)))) {
  2317. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2318. (char*)smartlist_get(args, 0));
  2319. goto done;
  2320. }
  2321. {
  2322. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  2323. if (!purp) {
  2324. connection_write_str_to_buf("552 No purpose given\r\n", conn);
  2325. goto done;
  2326. }
  2327. new_purpose = circuit_purpose_from_string(purp);
  2328. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2329. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2330. goto done;
  2331. }
  2332. }
  2333. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  2334. connection_write_str_to_buf("250 OK\r\n", conn);
  2335. done:
  2336. if (args) {
  2337. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2338. smartlist_free(args);
  2339. }
  2340. return 0;
  2341. }
  2342. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  2343. * stream, and report success or failure. */
  2344. static int
  2345. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  2346. const char *body)
  2347. {
  2348. entry_connection_t *ap_conn = NULL;
  2349. origin_circuit_t *circ = NULL;
  2350. int zero_circ;
  2351. smartlist_t *args;
  2352. crypt_path_t *cpath=NULL;
  2353. int hop=0, hop_line_ok=1;
  2354. (void) len;
  2355. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  2356. if (!args)
  2357. return 0;
  2358. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  2359. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  2360. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2361. (char*)smartlist_get(args, 0));
  2362. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  2363. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2364. (char*)smartlist_get(args, 1));
  2365. } else if (circ) {
  2366. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  2367. if (hopstring) {
  2368. hopstring += strlen("HOP=");
  2369. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  2370. &hop_line_ok, NULL);
  2371. if (!hop_line_ok) { /* broken hop line */
  2372. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  2373. }
  2374. }
  2375. }
  2376. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2377. smartlist_free(args);
  2378. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  2379. return 0;
  2380. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  2381. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  2382. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  2383. connection_write_str_to_buf(
  2384. "555 Connection is not managed by controller.\r\n",
  2385. conn);
  2386. return 0;
  2387. }
  2388. /* Do we need to detach it first? */
  2389. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  2390. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2391. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  2392. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  2393. /* Un-mark it as ending, since we're going to reuse it. */
  2394. edge_conn->edge_has_sent_end = 0;
  2395. edge_conn->end_reason = 0;
  2396. if (tmpcirc)
  2397. circuit_detach_stream(tmpcirc, edge_conn);
  2398. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  2399. }
  2400. if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
  2401. connection_write_str_to_buf(
  2402. "551 Can't attach stream to non-open origin circuit\r\n",
  2403. conn);
  2404. return 0;
  2405. }
  2406. /* Is this a single hop circuit? */
  2407. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  2408. const node_t *node = NULL;
  2409. char *exit_digest;
  2410. if (circ->build_state &&
  2411. circ->build_state->chosen_exit &&
  2412. !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
  2413. exit_digest = circ->build_state->chosen_exit->identity_digest;
  2414. node = node_get_by_id(exit_digest);
  2415. }
  2416. /* Do both the client and relay allow one-hop exit circuits? */
  2417. if (!node ||
  2418. !node_allows_single_hop_exits(node) ||
  2419. !get_options()->AllowSingleHopCircuits) {
  2420. connection_write_str_to_buf(
  2421. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  2422. return 0;
  2423. }
  2424. ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
  2425. }
  2426. if (circ && hop>0) {
  2427. /* find this hop in the circuit, and set cpath */
  2428. cpath = circuit_get_cpath_hop(circ, hop);
  2429. if (!cpath) {
  2430. connection_printf_to_buf(conn,
  2431. "551 Circuit doesn't have %d hops.\r\n", hop);
  2432. return 0;
  2433. }
  2434. }
  2435. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  2436. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  2437. return 0;
  2438. }
  2439. send_control_done(conn);
  2440. return 0;
  2441. }
  2442. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  2443. * descriptor, and report success or failure. */
  2444. static int
  2445. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  2446. const char *body)
  2447. {
  2448. char *desc;
  2449. const char *msg=NULL;
  2450. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  2451. int cache = 0; /* eventually, we may switch this to 1 */
  2452. char *cp = memchr(body, '\n', len);
  2453. smartlist_t *args = smartlist_new();
  2454. tor_assert(cp);
  2455. *cp++ = '\0';
  2456. smartlist_split_string(args, body, " ",
  2457. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2458. SMARTLIST_FOREACH_BEGIN(args, char *, option) {
  2459. if (!strcasecmpstart(option, "purpose=")) {
  2460. option += strlen("purpose=");
  2461. purpose = router_purpose_from_string(option);
  2462. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  2463. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  2464. option);
  2465. goto done;
  2466. }
  2467. } else if (!strcasecmpstart(option, "cache=")) {
  2468. option += strlen("cache=");
  2469. if (!strcasecmp(option, "no"))
  2470. cache = 0;
  2471. else if (!strcasecmp(option, "yes"))
  2472. cache = 1;
  2473. else {
  2474. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  2475. option);
  2476. goto done;
  2477. }
  2478. } else { /* unrecognized argument? */
  2479. connection_printf_to_buf(conn,
  2480. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  2481. goto done;
  2482. }
  2483. } SMARTLIST_FOREACH_END(option);
  2484. read_escaped_data(cp, len-(cp-body), &desc);
  2485. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  2486. case -1:
  2487. if (!msg) msg = "Could not parse descriptor";
  2488. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  2489. break;
  2490. case 0:
  2491. if (!msg) msg = "Descriptor not added";
  2492. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2493. break;
  2494. case 1:
  2495. send_control_done(conn);
  2496. break;
  2497. }
  2498. tor_free(desc);
  2499. done:
  2500. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  2501. smartlist_free(args);
  2502. return 0;
  2503. }
  2504. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2505. * address of the named AP stream, and report success or failure. */
  2506. static int
  2507. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2508. const char *body)
  2509. {
  2510. entry_connection_t *ap_conn = NULL;
  2511. char *new_addr = NULL;
  2512. uint16_t new_port = 0;
  2513. smartlist_t *args;
  2514. (void) len;
  2515. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  2516. if (!args)
  2517. return 0;
  2518. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2519. || !ap_conn->socks_request) {
  2520. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2521. (char*)smartlist_get(args, 0));
  2522. } else {
  2523. int ok = 1;
  2524. if (smartlist_len(args) > 2) { /* they included a port too */
  2525. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2526. 10, 1, 65535, &ok, NULL);
  2527. }
  2528. if (!ok) {
  2529. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2530. (char*)smartlist_get(args, 2));
  2531. } else {
  2532. new_addr = tor_strdup(smartlist_get(args, 1));
  2533. }
  2534. }
  2535. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2536. smartlist_free(args);
  2537. if (!new_addr)
  2538. return 0;
  2539. strlcpy(ap_conn->socks_request->address, new_addr,
  2540. sizeof(ap_conn->socks_request->address));
  2541. if (new_port)
  2542. ap_conn->socks_request->port = new_port;
  2543. tor_free(new_addr);
  2544. send_control_done(conn);
  2545. return 0;
  2546. }
  2547. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2548. * and report success or failure. */
  2549. static int
  2550. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2551. const char *body)
  2552. {
  2553. entry_connection_t *ap_conn=NULL;
  2554. uint8_t reason=0;
  2555. smartlist_t *args;
  2556. int ok;
  2557. (void) len;
  2558. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2559. if (!args)
  2560. return 0;
  2561. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2562. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2563. (char*)smartlist_get(args, 0));
  2564. else {
  2565. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2566. &ok, NULL);
  2567. if (!ok) {
  2568. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2569. (char*)smartlist_get(args, 1));
  2570. ap_conn = NULL;
  2571. }
  2572. }
  2573. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2574. smartlist_free(args);
  2575. if (!ap_conn)
  2576. return 0;
  2577. connection_mark_unattached_ap(ap_conn, reason);
  2578. send_control_done(conn);
  2579. return 0;
  2580. }
  2581. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2582. * and report success or failure. */
  2583. static int
  2584. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2585. const char *body)
  2586. {
  2587. origin_circuit_t *circ = NULL;
  2588. int safe = 0;
  2589. smartlist_t *args;
  2590. (void) len;
  2591. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2592. if (!args)
  2593. return 0;
  2594. if (!(circ=get_circ(smartlist_get(args, 0))))
  2595. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2596. (char*)smartlist_get(args, 0));
  2597. else {
  2598. int i;
  2599. for (i=1; i < smartlist_len(args); ++i) {
  2600. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2601. safe = 1;
  2602. else
  2603. log_info(LD_CONTROL, "Skipping unknown option %s",
  2604. (char*)smartlist_get(args,i));
  2605. }
  2606. }
  2607. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2608. smartlist_free(args);
  2609. if (!circ)
  2610. return 0;
  2611. if (!safe || !circ->p_streams) {
  2612. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2613. }
  2614. send_control_done(conn);
  2615. return 0;
  2616. }
  2617. /** Called when we get a RESOLVE command: start trying to resolve
  2618. * the listed addresses. */
  2619. static int
  2620. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2621. const char *body)
  2622. {
  2623. smartlist_t *args, *failed;
  2624. int is_reverse = 0;
  2625. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2626. if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
  2627. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2628. "isn't listening for ADDRMAP events. It probably won't see "
  2629. "the answer.");
  2630. }
  2631. args = smartlist_new();
  2632. smartlist_split_string(args, body, " ",
  2633. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2634. {
  2635. const char *modearg = find_element_starting_with(args, 0, "mode=");
  2636. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  2637. is_reverse = 1;
  2638. }
  2639. failed = smartlist_new();
  2640. SMARTLIST_FOREACH(args, const char *, arg, {
  2641. if (!is_keyval_pair(arg)) {
  2642. if (dnsserv_launch_request(arg, is_reverse)<0)
  2643. smartlist_add(failed, (char*)arg);
  2644. }
  2645. });
  2646. send_control_done(conn);
  2647. SMARTLIST_FOREACH(failed, const char *, arg, {
  2648. control_event_address_mapped(arg, arg, time(NULL),
  2649. "Unable to launch resolve request");
  2650. });
  2651. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2652. smartlist_free(args);
  2653. smartlist_free(failed);
  2654. return 0;
  2655. }
  2656. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  2657. static int
  2658. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  2659. const char *body)
  2660. {
  2661. const char *bad_arg = NULL;
  2662. smartlist_t *args;
  2663. (void)len;
  2664. conn->have_sent_protocolinfo = 1;
  2665. args = smartlist_new();
  2666. smartlist_split_string(args, body, " ",
  2667. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2668. SMARTLIST_FOREACH(args, const char *, arg, {
  2669. int ok;
  2670. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  2671. if (!ok) {
  2672. bad_arg = arg;
  2673. break;
  2674. }
  2675. });
  2676. if (bad_arg) {
  2677. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  2678. escaped(bad_arg));
  2679. /* Don't tolerate bad arguments when not authenticated. */
  2680. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  2681. connection_mark_for_close(TO_CONN(conn));
  2682. goto done;
  2683. } else {
  2684. const or_options_t *options = get_options();
  2685. int cookies = options->CookieAuthentication;
  2686. char *cfile = get_cookie_file();
  2687. char *abs_cfile;
  2688. char *esc_cfile;
  2689. char *methods;
  2690. abs_cfile = make_path_absolute(cfile);
  2691. esc_cfile = esc_for_log(abs_cfile);
  2692. {
  2693. int passwd = (options->HashedControlPassword != NULL ||
  2694. options->HashedControlSessionPassword != NULL);
  2695. smartlist_t *mlist = smartlist_new();
  2696. if (cookies) {
  2697. smartlist_add(mlist, (char*)"COOKIE");
  2698. smartlist_add(mlist, (char*)"SAFECOOKIE");
  2699. }
  2700. if (passwd)
  2701. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  2702. if (!cookies && !passwd)
  2703. smartlist_add(mlist, (char*)"NULL");
  2704. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  2705. smartlist_free(mlist);
  2706. }
  2707. connection_printf_to_buf(conn,
  2708. "250-PROTOCOLINFO 1\r\n"
  2709. "250-AUTH METHODS=%s%s%s\r\n"
  2710. "250-VERSION Tor=%s\r\n"
  2711. "250 OK\r\n",
  2712. methods,
  2713. cookies?" COOKIEFILE=":"",
  2714. cookies?esc_cfile:"",
  2715. escaped(VERSION));
  2716. tor_free(methods);
  2717. tor_free(cfile);
  2718. tor_free(abs_cfile);
  2719. tor_free(esc_cfile);
  2720. }
  2721. done:
  2722. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2723. smartlist_free(args);
  2724. return 0;
  2725. }
  2726. /** Called when we get an AUTHCHALLENGE command. */
  2727. static int
  2728. handle_control_authchallenge(control_connection_t *conn, uint32_t len,
  2729. const char *body)
  2730. {
  2731. const char *cp = body;
  2732. char *client_nonce;
  2733. size_t client_nonce_len;
  2734. char server_hash[DIGEST256_LEN];
  2735. char server_hash_encoded[HEX_DIGEST256_LEN+1];
  2736. char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
  2737. char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
  2738. cp += strspn(cp, " \t\n\r");
  2739. if (!strcasecmpstart(cp, "SAFECOOKIE")) {
  2740. cp += strlen("SAFECOOKIE");
  2741. } else {
  2742. connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
  2743. "authentication\r\n", conn);
  2744. connection_mark_for_close(TO_CONN(conn));
  2745. return -1;
  2746. }
  2747. if (!authentication_cookie_is_set) {
  2748. connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
  2749. conn);
  2750. connection_mark_for_close(TO_CONN(conn));
  2751. return -1;
  2752. }
  2753. cp += strspn(cp, " \t\n\r");
  2754. if (*cp == '"') {
  2755. const char *newcp =
  2756. decode_escaped_string(cp, len - (cp - body),
  2757. &client_nonce, &client_nonce_len);
  2758. if (newcp == NULL) {
  2759. connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
  2760. conn);
  2761. connection_mark_for_close(TO_CONN(conn));
  2762. return -1;
  2763. }
  2764. cp = newcp;
  2765. } else {
  2766. size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
  2767. client_nonce_len = client_nonce_encoded_len / 2;
  2768. client_nonce = tor_malloc_zero(client_nonce_len);
  2769. if (base16_decode(client_nonce, client_nonce_len,
  2770. cp, client_nonce_encoded_len) < 0) {
  2771. connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
  2772. conn);
  2773. connection_mark_for_close(TO_CONN(conn));
  2774. tor_free(client_nonce);
  2775. return -1;
  2776. }
  2777. cp += client_nonce_encoded_len;
  2778. }
  2779. cp += strspn(cp, " \t\n\r");
  2780. if (*cp != '\0' ||
  2781. cp != body + len) {
  2782. connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
  2783. conn);
  2784. connection_mark_for_close(TO_CONN(conn));
  2785. tor_free(client_nonce);
  2786. return -1;
  2787. }
  2788. tor_assert(!crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN));
  2789. /* Now compute and send the server-to-controller response, and the
  2790. * server's nonce. */
  2791. tor_assert(authentication_cookie != NULL);
  2792. {
  2793. size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
  2794. client_nonce_len +
  2795. SAFECOOKIE_SERVER_NONCE_LEN);
  2796. char *tmp = tor_malloc_zero(tmp_len);
  2797. char *client_hash = tor_malloc_zero(DIGEST256_LEN);
  2798. memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2799. memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
  2800. memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
  2801. server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  2802. crypto_hmac_sha256(server_hash,
  2803. SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
  2804. strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
  2805. tmp,
  2806. tmp_len);
  2807. crypto_hmac_sha256(client_hash,
  2808. SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
  2809. strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
  2810. tmp,
  2811. tmp_len);
  2812. conn->safecookie_client_hash = client_hash;
  2813. tor_free(tmp);
  2814. }
  2815. base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
  2816. server_hash, sizeof(server_hash));
  2817. base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
  2818. server_nonce, sizeof(server_nonce));
  2819. connection_printf_to_buf(conn,
  2820. "250 AUTHCHALLENGE SERVERHASH=%s "
  2821. "SERVERNONCE=%s\r\n",
  2822. server_hash_encoded,
  2823. server_nonce_encoded);
  2824. return 0;
  2825. }
  2826. /** Called when we get a USEFEATURE command: parse the feature list, and
  2827. * set up the control_connection's options properly. */
  2828. static int
  2829. handle_control_usefeature(control_connection_t *conn,
  2830. uint32_t len,
  2831. const char *body)
  2832. {
  2833. smartlist_t *args;
  2834. int bad = 0;
  2835. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2836. args = smartlist_new();
  2837. smartlist_split_string(args, body, " ",
  2838. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2839. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  2840. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2841. ;
  2842. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  2843. ;
  2844. else {
  2845. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2846. arg);
  2847. bad = 1;
  2848. break;
  2849. }
  2850. } SMARTLIST_FOREACH_END(arg);
  2851. if (!bad) {
  2852. send_control_done(conn);
  2853. }
  2854. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2855. smartlist_free(args);
  2856. return 0;
  2857. }
  2858. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2859. int
  2860. connection_control_finished_flushing(control_connection_t *conn)
  2861. {
  2862. tor_assert(conn);
  2863. return 0;
  2864. }
  2865. /** Called when <b>conn</b> has gotten its socket closed. */
  2866. int
  2867. connection_control_reached_eof(control_connection_t *conn)
  2868. {
  2869. tor_assert(conn);
  2870. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2871. connection_mark_for_close(TO_CONN(conn));
  2872. return 0;
  2873. }
  2874. /** Shut down this Tor instance in the same way that SIGINT would, but
  2875. * with a log message appropriate for the loss of an owning controller. */
  2876. static void
  2877. lost_owning_controller(const char *owner_type, const char *loss_manner)
  2878. {
  2879. int shutdown_slowly = server_mode(get_options());
  2880. log_notice(LD_CONTROL, "Owning controller %s has %s -- %s.",
  2881. owner_type, loss_manner,
  2882. shutdown_slowly ? "shutting down" : "exiting now");
  2883. /* XXXX Perhaps this chunk of code should be a separate function,
  2884. * called here and by process_signal(SIGINT). */
  2885. if (!shutdown_slowly) {
  2886. tor_cleanup();
  2887. exit(0);
  2888. }
  2889. /* XXXX This will close all listening sockets except control-port
  2890. * listeners. Perhaps we should close those too. */
  2891. hibernate_begin_shutdown();
  2892. }
  2893. /** Called when <b>conn</b> is being freed. */
  2894. void
  2895. connection_control_closed(control_connection_t *conn)
  2896. {
  2897. tor_assert(conn);
  2898. conn->event_mask = 0;
  2899. control_update_global_event_mask();
  2900. if (conn->is_owning_control_connection) {
  2901. lost_owning_controller("connection", "closed");
  2902. }
  2903. }
  2904. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  2905. * stage of the protocol. */
  2906. static int
  2907. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  2908. {
  2909. if (conn->_base.state == CONTROL_CONN_STATE_OPEN)
  2910. return 1;
  2911. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  2912. return (!conn->have_sent_protocolinfo &&
  2913. conn->safecookie_client_hash == NULL);
  2914. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  2915. return (conn->safecookie_client_hash == NULL);
  2916. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  2917. !strcasecmp(cmd, "QUIT"))
  2918. return 1;
  2919. return 0;
  2920. }
  2921. /** Do not accept any control command of more than 1MB in length. Anything
  2922. * that needs to be anywhere near this long probably means that one of our
  2923. * interfaces is broken. */
  2924. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  2925. /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
  2926. * interface as those underlying functions, but takes a connection_t intead of
  2927. * an evbuffer or a buf_t.
  2928. */
  2929. static int
  2930. peek_connection_has_control0_command(connection_t *conn)
  2931. {
  2932. IF_HAS_BUFFEREVENT(conn, {
  2933. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  2934. return peek_evbuffer_has_control0_command(input);
  2935. }) ELSE_IF_NO_BUFFEREVENT {
  2936. return peek_buf_has_control0_command(conn->inbuf);
  2937. }
  2938. }
  2939. /** Called when data has arrived on a v1 control connection: Try to fetch
  2940. * commands from conn->inbuf, and execute them.
  2941. */
  2942. int
  2943. connection_control_process_inbuf(control_connection_t *conn)
  2944. {
  2945. size_t data_len;
  2946. uint32_t cmd_data_len;
  2947. int cmd_len;
  2948. char *args;
  2949. tor_assert(conn);
  2950. tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
  2951. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
  2952. if (!conn->incoming_cmd) {
  2953. conn->incoming_cmd = tor_malloc(1024);
  2954. conn->incoming_cmd_len = 1024;
  2955. conn->incoming_cmd_cur_len = 0;
  2956. }
  2957. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2958. peek_connection_has_control0_command(TO_CONN(conn))) {
  2959. /* Detect v0 commands and send a "no more v0" message. */
  2960. size_t body_len;
  2961. char buf[128];
  2962. set_uint16(buf+2, htons(0x0000)); /* type == error */
  2963. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  2964. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  2965. "and later; upgrade your controller.",
  2966. sizeof(buf)-6);
  2967. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  2968. set_uint16(buf+0, htons(body_len));
  2969. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  2970. connection_mark_and_flush(TO_CONN(conn));
  2971. return 0;
  2972. }
  2973. again:
  2974. while (1) {
  2975. size_t last_idx;
  2976. int r;
  2977. /* First, fetch a line. */
  2978. do {
  2979. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2980. r = connection_fetch_from_buf_line(TO_CONN(conn),
  2981. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2982. &data_len);
  2983. if (r == 0)
  2984. /* Line not all here yet. Wait. */
  2985. return 0;
  2986. else if (r == -1) {
  2987. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  2988. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  2989. connection_stop_reading(TO_CONN(conn));
  2990. connection_mark_and_flush(TO_CONN(conn));
  2991. }
  2992. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  2993. conn->incoming_cmd_len *= 2;
  2994. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  2995. conn->incoming_cmd_len);
  2996. }
  2997. } while (r != 1);
  2998. tor_assert(data_len);
  2999. last_idx = conn->incoming_cmd_cur_len;
  3000. conn->incoming_cmd_cur_len += (int)data_len;
  3001. /* We have appended a line to incoming_cmd. Is the command done? */
  3002. if (last_idx == 0 && *conn->incoming_cmd != '+')
  3003. /* One line command, didn't start with '+'. */
  3004. break;
  3005. /* XXXX this code duplication is kind of dumb. */
  3006. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  3007. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  3008. /* Just appended ".\r\n"; we're done. Remove it. */
  3009. conn->incoming_cmd[last_idx] = '\0';
  3010. conn->incoming_cmd_cur_len -= 3;
  3011. break;
  3012. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  3013. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  3014. /* Just appended ".\n"; we're done. Remove it. */
  3015. conn->incoming_cmd[last_idx] = '\0';
  3016. conn->incoming_cmd_cur_len -= 2;
  3017. break;
  3018. }
  3019. /* Otherwise, read another line. */
  3020. }
  3021. data_len = conn->incoming_cmd_cur_len;
  3022. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  3023. * recognize it.
  3024. */
  3025. cmd_len = 0;
  3026. while ((size_t)cmd_len < data_len
  3027. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  3028. ++cmd_len;
  3029. conn->incoming_cmd[cmd_len]='\0';
  3030. args = conn->incoming_cmd+cmd_len+1;
  3031. tor_assert(data_len>(size_t)cmd_len);
  3032. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  3033. while (TOR_ISSPACE(*args)) {
  3034. ++args;
  3035. --data_len;
  3036. }
  3037. /* If the connection is already closing, ignore further commands */
  3038. if (TO_CONN(conn)->marked_for_close) {
  3039. return 0;
  3040. }
  3041. /* Otherwise, Quit is always valid. */
  3042. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  3043. connection_write_str_to_buf("250 closing connection\r\n", conn);
  3044. connection_mark_and_flush(TO_CONN(conn));
  3045. return 0;
  3046. }
  3047. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3048. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  3049. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  3050. connection_mark_for_close(TO_CONN(conn));
  3051. return 0;
  3052. }
  3053. if (data_len >= UINT32_MAX) {
  3054. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  3055. connection_mark_for_close(TO_CONN(conn));
  3056. return 0;
  3057. }
  3058. /* XXXX Why is this not implemented as a table like the GETINFO
  3059. * items are? Even handling the plus signs at the beginnings of
  3060. * commands wouldn't be very hard with proper macros. */
  3061. cmd_data_len = (uint32_t)data_len;
  3062. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  3063. if (handle_control_setconf(conn, cmd_data_len, args))
  3064. return -1;
  3065. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  3066. if (handle_control_resetconf(conn, cmd_data_len, args))
  3067. return -1;
  3068. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  3069. if (handle_control_getconf(conn, cmd_data_len, args))
  3070. return -1;
  3071. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  3072. if (handle_control_loadconf(conn, cmd_data_len, args))
  3073. return -1;
  3074. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  3075. if (handle_control_setevents(conn, cmd_data_len, args))
  3076. return -1;
  3077. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  3078. if (handle_control_authenticate(conn, cmd_data_len, args))
  3079. return -1;
  3080. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  3081. if (handle_control_saveconf(conn, cmd_data_len, args))
  3082. return -1;
  3083. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  3084. if (handle_control_signal(conn, cmd_data_len, args))
  3085. return -1;
  3086. } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
  3087. if (handle_control_takeownership(conn, cmd_data_len, args))
  3088. return -1;
  3089. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  3090. if (handle_control_mapaddress(conn, cmd_data_len, args))
  3091. return -1;
  3092. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  3093. if (handle_control_getinfo(conn, cmd_data_len, args))
  3094. return -1;
  3095. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  3096. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  3097. return -1;
  3098. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  3099. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  3100. return -1;
  3101. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  3102. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  3103. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  3104. if (handle_control_attachstream(conn, cmd_data_len, args))
  3105. return -1;
  3106. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  3107. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  3108. return -1;
  3109. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  3110. if (handle_control_redirectstream(conn, cmd_data_len, args))
  3111. return -1;
  3112. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  3113. if (handle_control_closestream(conn, cmd_data_len, args))
  3114. return -1;
  3115. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  3116. if (handle_control_closecircuit(conn, cmd_data_len, args))
  3117. return -1;
  3118. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  3119. if (handle_control_usefeature(conn, cmd_data_len, args))
  3120. return -1;
  3121. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  3122. if (handle_control_resolve(conn, cmd_data_len, args))
  3123. return -1;
  3124. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  3125. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  3126. return -1;
  3127. } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
  3128. if (handle_control_authchallenge(conn, cmd_data_len, args))
  3129. return -1;
  3130. } else {
  3131. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  3132. conn->incoming_cmd);
  3133. }
  3134. conn->incoming_cmd_cur_len = 0;
  3135. goto again;
  3136. }
  3137. /** Something major has happened to circuit <b>circ</b>: tell any
  3138. * interested control connections. */
  3139. int
  3140. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  3141. int reason_code)
  3142. {
  3143. const char *status;
  3144. char reasons[64] = "";
  3145. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  3146. return 0;
  3147. tor_assert(circ);
  3148. switch (tp)
  3149. {
  3150. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3151. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  3152. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  3153. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  3154. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  3155. default:
  3156. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3157. tor_fragile_assert();
  3158. return 0;
  3159. }
  3160. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  3161. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  3162. char unk_reason_buf[16];
  3163. if (!reason_str) {
  3164. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  3165. reason_str = unk_reason_buf;
  3166. }
  3167. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  3168. tor_snprintf(reasons, sizeof(reasons),
  3169. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  3170. } else {
  3171. tor_snprintf(reasons, sizeof(reasons),
  3172. " REASON=%s", reason_str);
  3173. }
  3174. }
  3175. {
  3176. char *circdesc = circuit_describe_status_for_controller(circ);
  3177. const char *sp = strlen(circdesc) ? " " : "";
  3178. send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
  3179. "650 CIRC %lu %s%s%s%s\r\n",
  3180. (unsigned long)circ->global_identifier,
  3181. status, sp,
  3182. circdesc,
  3183. reasons);
  3184. tor_free(circdesc);
  3185. }
  3186. return 0;
  3187. }
  3188. /** Something minor has happened to circuit <b>circ</b>: tell any
  3189. * interested control connections. */
  3190. static int
  3191. control_event_circuit_status_minor(origin_circuit_t *circ,
  3192. circuit_status_minor_event_t e,
  3193. int purpose, const struct timeval *tv)
  3194. {
  3195. const char *event_desc;
  3196. char event_tail[160] = "";
  3197. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  3198. return 0;
  3199. tor_assert(circ);
  3200. switch (e)
  3201. {
  3202. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  3203. event_desc = "PURPOSE_CHANGED";
  3204. {
  3205. /* event_tail can currently be up to 68 chars long */
  3206. const char *hs_state_str =
  3207. circuit_purpose_to_controller_hs_state_string(purpose);
  3208. tor_snprintf(event_tail, sizeof(event_tail),
  3209. " OLD_PURPOSE=%s%s%s",
  3210. circuit_purpose_to_controller_string(purpose),
  3211. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3212. (hs_state_str != NULL) ? hs_state_str : "");
  3213. }
  3214. break;
  3215. case CIRC_MINOR_EVENT_CANNIBALIZED:
  3216. event_desc = "CANNIBALIZED";
  3217. {
  3218. /* event_tail can currently be up to 130 chars long */
  3219. const char *hs_state_str =
  3220. circuit_purpose_to_controller_hs_state_string(purpose);
  3221. const struct timeval *old_timestamp_created = tv;
  3222. char tbuf[ISO_TIME_USEC_LEN+1];
  3223. format_iso_time_nospace_usec(tbuf, old_timestamp_created);
  3224. tor_snprintf(event_tail, sizeof(event_tail),
  3225. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  3226. circuit_purpose_to_controller_string(purpose),
  3227. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3228. (hs_state_str != NULL) ? hs_state_str : "",
  3229. tbuf);
  3230. }
  3231. break;
  3232. default:
  3233. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  3234. tor_fragile_assert();
  3235. return 0;
  3236. }
  3237. {
  3238. char *circdesc = circuit_describe_status_for_controller(circ);
  3239. const char *sp = strlen(circdesc) ? " " : "";
  3240. send_control_event(EVENT_CIRCUIT_STATUS_MINOR, ALL_FORMATS,
  3241. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  3242. (unsigned long)circ->global_identifier,
  3243. event_desc, sp,
  3244. circdesc,
  3245. event_tail);
  3246. tor_free(circdesc);
  3247. }
  3248. return 0;
  3249. }
  3250. /**
  3251. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  3252. * interested controllers.
  3253. */
  3254. int
  3255. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  3256. int old_purpose)
  3257. {
  3258. return control_event_circuit_status_minor(circ,
  3259. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  3260. old_purpose,
  3261. NULL);
  3262. }
  3263. /**
  3264. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  3265. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  3266. */
  3267. int
  3268. control_event_circuit_cannibalized(origin_circuit_t *circ,
  3269. int old_purpose,
  3270. const struct timeval *old_tv_created)
  3271. {
  3272. return control_event_circuit_status_minor(circ,
  3273. CIRC_MINOR_EVENT_CANNIBALIZED,
  3274. old_purpose,
  3275. old_tv_created);
  3276. }
  3277. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  3278. * <b>buf</b>, determine the address:port combination requested on
  3279. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  3280. * failure. */
  3281. static int
  3282. write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
  3283. {
  3284. char buf2[256];
  3285. if (conn->chosen_exit_name)
  3286. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  3287. return -1;
  3288. if (!conn->socks_request)
  3289. return -1;
  3290. if (tor_snprintf(buf, len, "%s%s%s:%d",
  3291. conn->socks_request->address,
  3292. conn->chosen_exit_name ? buf2 : "",
  3293. !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
  3294. ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
  3295. conn->socks_request->port)<0)
  3296. return -1;
  3297. return 0;
  3298. }
  3299. /** Something has happened to the stream associated with AP connection
  3300. * <b>conn</b>: tell any interested control connections. */
  3301. int
  3302. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  3303. int reason_code)
  3304. {
  3305. char reason_buf[64];
  3306. char addrport_buf[64];
  3307. const char *status;
  3308. circuit_t *circ;
  3309. origin_circuit_t *origin_circ = NULL;
  3310. char buf[256];
  3311. const char *purpose = "";
  3312. tor_assert(conn->socks_request);
  3313. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  3314. return 0;
  3315. if (tp == STREAM_EVENT_CLOSED &&
  3316. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  3317. return 0;
  3318. write_stream_target_to_buf(conn, buf, sizeof(buf));
  3319. reason_buf[0] = '\0';
  3320. switch (tp)
  3321. {
  3322. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  3323. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  3324. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  3325. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  3326. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  3327. case STREAM_EVENT_NEW: status = "NEW"; break;
  3328. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  3329. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  3330. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  3331. default:
  3332. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3333. return 0;
  3334. }
  3335. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  3336. tp == STREAM_EVENT_CLOSED ||
  3337. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  3338. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  3339. char *r = NULL;
  3340. if (!reason_str) {
  3341. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  3342. reason_str = r;
  3343. }
  3344. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  3345. tor_snprintf(reason_buf, sizeof(reason_buf),
  3346. " REASON=END REMOTE_REASON=%s", reason_str);
  3347. else
  3348. tor_snprintf(reason_buf, sizeof(reason_buf),
  3349. " REASON=%s", reason_str);
  3350. tor_free(r);
  3351. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  3352. switch (reason_code) {
  3353. case REMAP_STREAM_SOURCE_CACHE:
  3354. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  3355. break;
  3356. case REMAP_STREAM_SOURCE_EXIT:
  3357. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  3358. break;
  3359. default:
  3360. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  3361. reason_code);
  3362. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  3363. break;
  3364. }
  3365. }
  3366. if (tp == STREAM_EVENT_NEW) {
  3367. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  3368. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  3369. } else {
  3370. addrport_buf[0] = '\0';
  3371. }
  3372. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  3373. purpose = " PURPOSE=DNS_REQUEST";
  3374. } else if (tp == STREAM_EVENT_NEW) {
  3375. if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request ||
  3376. (conn->socks_request &&
  3377. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)))
  3378. purpose = " PURPOSE=DNS_REQUEST";
  3379. else if (conn->use_begindir) {
  3380. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  3381. int linked_dir_purpose = -1;
  3382. if (linked && linked->type == CONN_TYPE_DIR)
  3383. linked_dir_purpose = linked->purpose;
  3384. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  3385. purpose = " PURPOSE=DIR_UPLOAD";
  3386. else
  3387. purpose = " PURPOSE=DIR_FETCH";
  3388. } else
  3389. purpose = " PURPOSE=USER";
  3390. }
  3391. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  3392. if (circ && CIRCUIT_IS_ORIGIN(circ))
  3393. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3394. send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
  3395. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  3396. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  3397. status,
  3398. origin_circ?
  3399. (unsigned long)origin_circ->global_identifier : 0ul,
  3400. buf, reason_buf, addrport_buf, purpose);
  3401. /* XXX need to specify its intended exit, etc? */
  3402. return 0;
  3403. }
  3404. /** Figure out the best name for the target router of an OR connection
  3405. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  3406. * <b>name</b>. */
  3407. static void
  3408. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  3409. {
  3410. const node_t *node = node_get_by_id(conn->identity_digest);
  3411. if (node) {
  3412. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  3413. node_get_verbose_nickname(node, name);
  3414. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  3415. name[0] = '$';
  3416. base16_encode(name+1, len-1, conn->identity_digest,
  3417. DIGEST_LEN);
  3418. } else {
  3419. tor_snprintf(name, len, "%s:%d",
  3420. conn->_base.address, conn->_base.port);
  3421. }
  3422. }
  3423. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  3424. * interested control connections. <b>tp</b> is the new status for the
  3425. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  3426. * may be the reason why.
  3427. */
  3428. int
  3429. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  3430. int reason)
  3431. {
  3432. int ncircs = 0;
  3433. const char *status;
  3434. char name[128];
  3435. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  3436. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  3437. return 0;
  3438. switch (tp)
  3439. {
  3440. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3441. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  3442. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  3443. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  3444. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  3445. default:
  3446. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3447. return 0;
  3448. }
  3449. ncircs = circuit_count_pending_on_or_conn(conn);
  3450. ncircs += conn->n_circuits;
  3451. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  3452. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
  3453. reason ? " " : "", ncircs);
  3454. }
  3455. orconn_target_get_name(name, sizeof(name), conn);
  3456. send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
  3457. "650 ORCONN %s %s %s%s%s\r\n",
  3458. name, status,
  3459. reason ? "REASON=" : "",
  3460. orconn_end_reason_to_control_string(reason),
  3461. ncircs_buf);
  3462. return 0;
  3463. }
  3464. /**
  3465. * Print out STREAM_BW event for a single conn
  3466. */
  3467. int
  3468. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  3469. {
  3470. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3471. if (!edge_conn->n_read && !edge_conn->n_written)
  3472. return 0;
  3473. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3474. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3475. U64_PRINTF_ARG(edge_conn->_base.global_identifier),
  3476. (unsigned long)edge_conn->n_read,
  3477. (unsigned long)edge_conn->n_written);
  3478. edge_conn->n_written = edge_conn->n_read = 0;
  3479. }
  3480. return 0;
  3481. }
  3482. /** A second or more has elapsed: tell any interested control
  3483. * connections how much bandwidth streams have used. */
  3484. int
  3485. control_event_stream_bandwidth_used(void)
  3486. {
  3487. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3488. smartlist_t *conns = get_connection_array();
  3489. edge_connection_t *edge_conn;
  3490. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  3491. {
  3492. if (conn->type != CONN_TYPE_AP)
  3493. continue;
  3494. edge_conn = TO_EDGE_CONN(conn);
  3495. if (!edge_conn->n_read && !edge_conn->n_written)
  3496. continue;
  3497. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3498. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3499. U64_PRINTF_ARG(edge_conn->_base.global_identifier),
  3500. (unsigned long)edge_conn->n_read,
  3501. (unsigned long)edge_conn->n_written);
  3502. edge_conn->n_written = edge_conn->n_read = 0;
  3503. }
  3504. SMARTLIST_FOREACH_END(conn);
  3505. }
  3506. return 0;
  3507. }
  3508. /** A second or more has elapsed: tell any interested control
  3509. * connections how much bandwidth we used. */
  3510. int
  3511. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  3512. {
  3513. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  3514. send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
  3515. "650 BW %lu %lu\r\n",
  3516. (unsigned long)n_read,
  3517. (unsigned long)n_written);
  3518. }
  3519. return 0;
  3520. }
  3521. /** Called when we are sending a log message to the controllers: suspend
  3522. * sending further log messages to the controllers until we're done. Used by
  3523. * CONN_LOG_PROTECT. */
  3524. void
  3525. disable_control_logging(void)
  3526. {
  3527. ++disable_log_messages;
  3528. }
  3529. /** We're done sending a log message to the controllers: re-enable controller
  3530. * logging. Used by CONN_LOG_PROTECT. */
  3531. void
  3532. enable_control_logging(void)
  3533. {
  3534. if (--disable_log_messages < 0)
  3535. tor_assert(0);
  3536. }
  3537. /** We got a log message: tell any interested control connections. */
  3538. void
  3539. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  3540. {
  3541. int event;
  3542. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  3543. * thread. */
  3544. if (! in_main_thread())
  3545. return;
  3546. if (disable_log_messages)
  3547. return;
  3548. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  3549. severity <= LOG_NOTICE) {
  3550. char *esc = esc_for_log(msg);
  3551. ++disable_log_messages;
  3552. control_event_general_status(severity, "BUG REASON=%s", esc);
  3553. --disable_log_messages;
  3554. tor_free(esc);
  3555. }
  3556. event = log_severity_to_event(severity);
  3557. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  3558. char *b = NULL;
  3559. const char *s;
  3560. if (strchr(msg, '\n')) {
  3561. char *cp;
  3562. b = tor_strdup(msg);
  3563. for (cp = b; *cp; ++cp)
  3564. if (*cp == '\r' || *cp == '\n')
  3565. *cp = ' ';
  3566. }
  3567. switch (severity) {
  3568. case LOG_DEBUG: s = "DEBUG"; break;
  3569. case LOG_INFO: s = "INFO"; break;
  3570. case LOG_NOTICE: s = "NOTICE"; break;
  3571. case LOG_WARN: s = "WARN"; break;
  3572. case LOG_ERR: s = "ERR"; break;
  3573. default: s = "UnknownLogSeverity"; break;
  3574. }
  3575. ++disable_log_messages;
  3576. send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
  3577. --disable_log_messages;
  3578. tor_free(b);
  3579. }
  3580. }
  3581. /** Called whenever we receive new router descriptors: tell any
  3582. * interested control connections. <b>routers</b> is a list of
  3583. * routerinfo_t's.
  3584. */
  3585. int
  3586. control_event_descriptors_changed(smartlist_t *routers)
  3587. {
  3588. char *msg;
  3589. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  3590. return 0;
  3591. {
  3592. smartlist_t *names = smartlist_new();
  3593. char *ids;
  3594. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  3595. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  3596. router_get_verbose_nickname(b, ri);
  3597. smartlist_add(names, b);
  3598. });
  3599. ids = smartlist_join_strings(names, " ", 0, NULL);
  3600. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  3601. send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
  3602. tor_free(ids);
  3603. tor_free(msg);
  3604. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  3605. smartlist_free(names);
  3606. }
  3607. return 0;
  3608. }
  3609. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  3610. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  3611. * <b>error</b> is non-NULL, it is an error code describing the failure
  3612. * mode of the mapping.
  3613. */
  3614. int
  3615. control_event_address_mapped(const char *from, const char *to, time_t expires,
  3616. const char *error)
  3617. {
  3618. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  3619. return 0;
  3620. if (expires < 3 || expires == TIME_MAX)
  3621. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3622. "650 ADDRMAP %s %s NEVER %s\r\n", from, to,
  3623. error?error:"");
  3624. else {
  3625. char buf[ISO_TIME_LEN+1];
  3626. char buf2[ISO_TIME_LEN+1];
  3627. format_local_iso_time(buf,expires);
  3628. format_iso_time(buf2,expires);
  3629. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3630. "650 ADDRMAP %s %s \"%s\""
  3631. " %s%sEXPIRES=\"%s\"\r\n",
  3632. from, to, buf,
  3633. error?error:"", error?" ":"",
  3634. buf2);
  3635. }
  3636. return 0;
  3637. }
  3638. /** The authoritative dirserver has received a new descriptor that
  3639. * has passed basic syntax checks and is properly self-signed.
  3640. *
  3641. * Notify any interested party of the new descriptor and what has
  3642. * been done with it, and also optionally give an explanation/reason. */
  3643. int
  3644. control_event_or_authdir_new_descriptor(const char *action,
  3645. const char *desc, size_t desclen,
  3646. const char *msg)
  3647. {
  3648. char firstline[1024];
  3649. char *buf;
  3650. size_t totallen;
  3651. char *esc = NULL;
  3652. size_t esclen;
  3653. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  3654. return 0;
  3655. tor_snprintf(firstline, sizeof(firstline),
  3656. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  3657. action,
  3658. msg ? msg : "");
  3659. /* Escape the server descriptor properly */
  3660. esclen = write_escaped_data(desc, desclen, &esc);
  3661. totallen = strlen(firstline) + esclen + 1;
  3662. buf = tor_malloc(totallen);
  3663. strlcpy(buf, firstline, totallen);
  3664. strlcpy(buf+strlen(firstline), esc, totallen);
  3665. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3666. buf);
  3667. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3668. "650 OK\r\n");
  3669. tor_free(esc);
  3670. tor_free(buf);
  3671. return 0;
  3672. }
  3673. /** Helper function for NS-style events. Constructs and sends an event
  3674. * of type <b>event</b> with string <b>event_string</b> out of the set of
  3675. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  3676. * and NEWCONSENSUS events. */
  3677. static int
  3678. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  3679. uint16_t event,
  3680. const char *event_string)
  3681. {
  3682. smartlist_t *strs;
  3683. char *s, *esc = NULL;
  3684. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  3685. return 0;
  3686. strs = smartlist_new();
  3687. smartlist_add(strs, tor_strdup("650+"));
  3688. smartlist_add(strs, tor_strdup(event_string));
  3689. smartlist_add(strs, tor_strdup("\r\n"));
  3690. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  3691. {
  3692. s = networkstatus_getinfo_helper_single(rs);
  3693. if (!s) continue;
  3694. smartlist_add(strs, s);
  3695. });
  3696. s = smartlist_join_strings(strs, "", 0, NULL);
  3697. write_escaped_data(s, strlen(s), &esc);
  3698. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  3699. smartlist_free(strs);
  3700. tor_free(s);
  3701. send_control_event_string(event, ALL_FORMATS, esc);
  3702. send_control_event_string(event, ALL_FORMATS,
  3703. "650 OK\r\n");
  3704. tor_free(esc);
  3705. return 0;
  3706. }
  3707. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  3708. * an NS event to any controller that cares. */
  3709. int
  3710. control_event_networkstatus_changed(smartlist_t *statuses)
  3711. {
  3712. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  3713. }
  3714. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  3715. * event consisting of an NS-style line for each relay in the consensus. */
  3716. int
  3717. control_event_newconsensus(const networkstatus_t *consensus)
  3718. {
  3719. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  3720. return 0;
  3721. return control_event_networkstatus_changed_helper(
  3722. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  3723. }
  3724. /** Called when we compute a new circuitbuildtimeout */
  3725. int
  3726. control_event_buildtimeout_set(const circuit_build_times_t *cbt,
  3727. buildtimeout_set_event_t type)
  3728. {
  3729. const char *type_string = NULL;
  3730. double qnt;
  3731. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  3732. return 0;
  3733. qnt = circuit_build_times_quantile_cutoff();
  3734. switch (type) {
  3735. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  3736. type_string = "COMPUTED";
  3737. break;
  3738. case BUILDTIMEOUT_SET_EVENT_RESET:
  3739. type_string = "RESET";
  3740. qnt = 1.0;
  3741. break;
  3742. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  3743. type_string = "SUSPENDED";
  3744. qnt = 1.0;
  3745. break;
  3746. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  3747. type_string = "DISCARD";
  3748. qnt = 1.0;
  3749. break;
  3750. case BUILDTIMEOUT_SET_EVENT_RESUME:
  3751. type_string = "RESUME";
  3752. break;
  3753. default:
  3754. type_string = "UNKNOWN";
  3755. break;
  3756. }
  3757. send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
  3758. "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
  3759. "TIMEOUT_MS=%lu XM=%lu ALPHA=%f CUTOFF_QUANTILE=%f "
  3760. "TIMEOUT_RATE=%f CLOSE_MS=%lu CLOSE_RATE=%f\r\n",
  3761. type_string, (unsigned long)cbt->total_build_times,
  3762. (unsigned long)cbt->timeout_ms,
  3763. (unsigned long)cbt->Xm, cbt->alpha, qnt,
  3764. circuit_build_times_timeout_rate(cbt),
  3765. (unsigned long)cbt->close_ms,
  3766. circuit_build_times_close_rate(cbt));
  3767. return 0;
  3768. }
  3769. /** Called when a signal has been processed from signal_callback */
  3770. int
  3771. control_event_signal(uintptr_t signal)
  3772. {
  3773. const char *signal_string = NULL;
  3774. if (!control_event_is_interesting(EVENT_SIGNAL))
  3775. return 0;
  3776. switch (signal) {
  3777. case SIGHUP:
  3778. signal_string = "RELOAD";
  3779. break;
  3780. case SIGUSR1:
  3781. signal_string = "DUMP";
  3782. break;
  3783. case SIGUSR2:
  3784. signal_string = "DEBUG";
  3785. break;
  3786. case SIGNEWNYM:
  3787. signal_string = "NEWNYM";
  3788. break;
  3789. case SIGCLEARDNSCACHE:
  3790. signal_string = "CLEARDNSCACHE";
  3791. break;
  3792. default:
  3793. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  3794. (unsigned long)signal);
  3795. return -1;
  3796. }
  3797. send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
  3798. signal_string);
  3799. return 0;
  3800. }
  3801. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  3802. * to any controller that cares. */
  3803. int
  3804. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  3805. {
  3806. smartlist_t *statuses;
  3807. int r;
  3808. if (!EVENT_IS_INTERESTING(EVENT_NS))
  3809. return 0;
  3810. statuses = smartlist_new();
  3811. smartlist_add(statuses, (void*)rs);
  3812. r = control_event_networkstatus_changed(statuses);
  3813. smartlist_free(statuses);
  3814. return r;
  3815. }
  3816. /** Our own router descriptor has changed; tell any controllers that care.
  3817. */
  3818. int
  3819. control_event_my_descriptor_changed(void)
  3820. {
  3821. send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
  3822. return 0;
  3823. }
  3824. /** Helper: sends a status event where <b>type</b> is one of
  3825. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  3826. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  3827. * string corresponding to <b>args</b>. */
  3828. static int
  3829. control_event_status(int type, int severity, const char *format, va_list args)
  3830. {
  3831. char *user_buf = NULL;
  3832. char format_buf[160];
  3833. const char *status, *sev;
  3834. switch (type) {
  3835. case EVENT_STATUS_GENERAL:
  3836. status = "STATUS_GENERAL";
  3837. break;
  3838. case EVENT_STATUS_CLIENT:
  3839. status = "STATUS_CLIENT";
  3840. break;
  3841. case EVENT_STATUS_SERVER:
  3842. status = "STATUS_SERVER";
  3843. break;
  3844. default:
  3845. log_warn(LD_BUG, "Unrecognized status type %d", type);
  3846. return -1;
  3847. }
  3848. switch (severity) {
  3849. case LOG_NOTICE:
  3850. sev = "NOTICE";
  3851. break;
  3852. case LOG_WARN:
  3853. sev = "WARN";
  3854. break;
  3855. case LOG_ERR:
  3856. sev = "ERR";
  3857. break;
  3858. default:
  3859. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  3860. return -1;
  3861. }
  3862. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  3863. status, sev)<0) {
  3864. log_warn(LD_BUG, "Format string too long.");
  3865. return -1;
  3866. }
  3867. tor_vasprintf(&user_buf, format, args);
  3868. send_control_event(type, ALL_FORMATS, "%s %s\r\n", format_buf, user_buf);
  3869. tor_free(user_buf);
  3870. return 0;
  3871. }
  3872. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  3873. * by formatting the arguments using the printf-style <b>format</b>. */
  3874. int
  3875. control_event_general_status(int severity, const char *format, ...)
  3876. {
  3877. va_list ap;
  3878. int r;
  3879. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  3880. return 0;
  3881. va_start(ap, format);
  3882. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  3883. va_end(ap);
  3884. return r;
  3885. }
  3886. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  3887. * by formatting the arguments using the printf-style <b>format</b>. */
  3888. int
  3889. control_event_client_status(int severity, const char *format, ...)
  3890. {
  3891. va_list ap;
  3892. int r;
  3893. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  3894. return 0;
  3895. va_start(ap, format);
  3896. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  3897. va_end(ap);
  3898. return r;
  3899. }
  3900. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  3901. * by formatting the arguments using the printf-style <b>format</b>. */
  3902. int
  3903. control_event_server_status(int severity, const char *format, ...)
  3904. {
  3905. va_list ap;
  3906. int r;
  3907. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  3908. return 0;
  3909. va_start(ap, format);
  3910. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  3911. va_end(ap);
  3912. return r;
  3913. }
  3914. /** Called when the status of an entry guard with the given <b>nickname</b>
  3915. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  3916. * controllers that care. */
  3917. int
  3918. control_event_guard(const char *nickname, const char *digest,
  3919. const char *status)
  3920. {
  3921. char hbuf[HEX_DIGEST_LEN+1];
  3922. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  3923. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  3924. return 0;
  3925. {
  3926. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  3927. const node_t *node = node_get_by_id(digest);
  3928. if (node) {
  3929. node_get_verbose_nickname(node, buf);
  3930. } else {
  3931. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  3932. }
  3933. send_control_event(EVENT_GUARD, ALL_FORMATS,
  3934. "650 GUARD ENTRY %s %s\r\n", buf, status);
  3935. }
  3936. return 0;
  3937. }
  3938. /** Called when a configuration option changes. This is generally triggered
  3939. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  3940. * a smartlist_t containing (key, value, ...) pairs in sequence.
  3941. * <b>value</b> can be NULL. */
  3942. int
  3943. control_event_conf_changed(smartlist_t *elements)
  3944. {
  3945. int i;
  3946. char *result;
  3947. smartlist_t *lines;
  3948. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  3949. smartlist_len(elements) == 0) {
  3950. return 0;
  3951. }
  3952. lines = smartlist_new();
  3953. for (i = 0; i < smartlist_len(elements); i += 2) {
  3954. char *k = smartlist_get(elements, i);
  3955. char *v = smartlist_get(elements, i+1);
  3956. if (v == NULL) {
  3957. smartlist_add_asprintf(lines, "650-%s", k);
  3958. } else {
  3959. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  3960. }
  3961. }
  3962. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  3963. send_control_event(EVENT_CONF_CHANGED, 0,
  3964. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  3965. tor_free(result);
  3966. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  3967. smartlist_free(lines);
  3968. return 0;
  3969. }
  3970. /** Helper: Return a newly allocated string containing a path to the
  3971. * file where we store our authentication cookie. */
  3972. static char *
  3973. get_cookie_file(void)
  3974. {
  3975. const or_options_t *options = get_options();
  3976. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  3977. return tor_strdup(options->CookieAuthFile);
  3978. } else {
  3979. return get_datadir_fname("control_auth_cookie");
  3980. }
  3981. }
  3982. /** Choose a random authentication cookie and write it to disk.
  3983. * Anybody who can read the cookie from disk will be considered
  3984. * authorized to use the control connection. Return -1 if we can't
  3985. * write the file, or 0 on success. */
  3986. int
  3987. init_cookie_authentication(int enabled)
  3988. {
  3989. char *fname;
  3990. if (!enabled) {
  3991. authentication_cookie_is_set = 0;
  3992. return 0;
  3993. }
  3994. /* We don't want to generate a new cookie every time we call
  3995. * options_act(). One should be enough. */
  3996. if (authentication_cookie_is_set)
  3997. return 0; /* all set */
  3998. fname = get_cookie_file();
  3999. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  4000. authentication_cookie_is_set = 1;
  4001. if (write_bytes_to_file(fname, authentication_cookie,
  4002. AUTHENTICATION_COOKIE_LEN, 1)) {
  4003. log_warn(LD_FS,"Error writing authentication cookie to %s.",
  4004. escaped(fname));
  4005. tor_free(fname);
  4006. return -1;
  4007. }
  4008. #ifndef _WIN32
  4009. if (get_options()->CookieAuthFileGroupReadable) {
  4010. if (chmod(fname, 0640)) {
  4011. log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
  4012. }
  4013. }
  4014. #endif
  4015. tor_free(fname);
  4016. return 0;
  4017. }
  4018. /** A copy of the process specifier of Tor's owning controller, or
  4019. * NULL if this Tor instance is not currently owned by a process. */
  4020. static char *owning_controller_process_spec = NULL;
  4021. /** A process-termination monitor for Tor's owning controller, or NULL
  4022. * if this Tor instance is not currently owned by a process. */
  4023. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  4024. /** Process-termination monitor callback for Tor's owning controller
  4025. * process. */
  4026. static void
  4027. owning_controller_procmon_cb(void *unused)
  4028. {
  4029. (void)unused;
  4030. lost_owning_controller("process", "vanished");
  4031. }
  4032. /** Set <b>process_spec</b> as Tor's owning controller process.
  4033. * Exit on failure. */
  4034. void
  4035. monitor_owning_controller_process(const char *process_spec)
  4036. {
  4037. const char *msg;
  4038. tor_assert((owning_controller_process_spec == NULL) ==
  4039. (owning_controller_process_monitor == NULL));
  4040. if (owning_controller_process_spec != NULL) {
  4041. if ((process_spec != NULL) && !strcmp(process_spec,
  4042. owning_controller_process_spec)) {
  4043. /* Same process -- return now, instead of disposing of and
  4044. * recreating the process-termination monitor. */
  4045. return;
  4046. }
  4047. /* We are currently owned by a process, and we should no longer be
  4048. * owned by it. Free the process-termination monitor. */
  4049. tor_process_monitor_free(owning_controller_process_monitor);
  4050. owning_controller_process_monitor = NULL;
  4051. tor_free(owning_controller_process_spec);
  4052. owning_controller_process_spec = NULL;
  4053. }
  4054. tor_assert((owning_controller_process_spec == NULL) &&
  4055. (owning_controller_process_monitor == NULL));
  4056. if (process_spec == NULL)
  4057. return;
  4058. owning_controller_process_spec = tor_strdup(process_spec);
  4059. owning_controller_process_monitor =
  4060. tor_process_monitor_new(tor_libevent_get_base(),
  4061. owning_controller_process_spec,
  4062. LD_CONTROL,
  4063. owning_controller_procmon_cb, NULL,
  4064. &msg);
  4065. if (owning_controller_process_monitor == NULL) {
  4066. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  4067. "owning controller: %s. Exiting.",
  4068. msg);
  4069. owning_controller_process_spec = NULL;
  4070. tor_cleanup();
  4071. exit(0);
  4072. }
  4073. }
  4074. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  4075. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  4076. static int
  4077. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  4078. const char **summary)
  4079. {
  4080. switch (s) {
  4081. case BOOTSTRAP_STATUS_UNDEF:
  4082. *tag = "undef";
  4083. *summary = "Undefined";
  4084. break;
  4085. case BOOTSTRAP_STATUS_STARTING:
  4086. *tag = "starting";
  4087. *summary = "Starting";
  4088. break;
  4089. case BOOTSTRAP_STATUS_CONN_DIR:
  4090. *tag = "conn_dir";
  4091. *summary = "Connecting to directory server";
  4092. break;
  4093. case BOOTSTRAP_STATUS_HANDSHAKE:
  4094. *tag = "status_handshake";
  4095. *summary = "Finishing handshake";
  4096. break;
  4097. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  4098. *tag = "handshake_dir";
  4099. *summary = "Finishing handshake with directory server";
  4100. break;
  4101. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  4102. *tag = "onehop_create";
  4103. *summary = "Establishing an encrypted directory connection";
  4104. break;
  4105. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  4106. *tag = "requesting_status";
  4107. *summary = "Asking for networkstatus consensus";
  4108. break;
  4109. case BOOTSTRAP_STATUS_LOADING_STATUS:
  4110. *tag = "loading_status";
  4111. *summary = "Loading networkstatus consensus";
  4112. break;
  4113. case BOOTSTRAP_STATUS_LOADING_KEYS:
  4114. *tag = "loading_keys";
  4115. *summary = "Loading authority key certs";
  4116. break;
  4117. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  4118. *tag = "requesting_descriptors";
  4119. *summary = "Asking for relay descriptors";
  4120. break;
  4121. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  4122. *tag = "loading_descriptors";
  4123. *summary = "Loading relay descriptors";
  4124. break;
  4125. case BOOTSTRAP_STATUS_CONN_OR:
  4126. *tag = "conn_or";
  4127. *summary = "Connecting to the Tor network";
  4128. break;
  4129. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  4130. *tag = "handshake_or";
  4131. *summary = "Finishing handshake with first hop";
  4132. break;
  4133. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  4134. *tag = "circuit_create";
  4135. *summary = "Establishing a Tor circuit";
  4136. break;
  4137. case BOOTSTRAP_STATUS_DONE:
  4138. *tag = "done";
  4139. *summary = "Done";
  4140. break;
  4141. default:
  4142. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  4143. *tag = *summary = "unknown";
  4144. return -1;
  4145. }
  4146. return 0;
  4147. }
  4148. /** What percentage through the bootstrap process are we? We remember
  4149. * this so we can avoid sending redundant bootstrap status events, and
  4150. * so we can guess context for the bootstrap messages which are
  4151. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  4152. * Tor initializes. */
  4153. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  4154. /** How many problems have we had getting to the next bootstrapping phase?
  4155. * These include failure to establish a connection to a Tor relay,
  4156. * failures to finish the TLS handshake, failures to validate the
  4157. * consensus document, etc. */
  4158. static int bootstrap_problems = 0;
  4159. /* We only tell the controller once we've hit a threshold of problems
  4160. * for the current phase. */
  4161. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  4162. /** Called when Tor has made progress at bootstrapping its directory
  4163. * information and initial circuits.
  4164. *
  4165. * <b>status</b> is the new status, that is, what task we will be doing
  4166. * next. <b>progress</b> is zero if we just started this task, else it
  4167. * represents progress on the task. */
  4168. void
  4169. control_event_bootstrap(bootstrap_status_t status, int progress)
  4170. {
  4171. const char *tag, *summary;
  4172. char buf[BOOTSTRAP_MSG_LEN];
  4173. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  4174. return; /* already bootstrapped; nothing to be done here. */
  4175. /* special case for handshaking status, since our TLS handshaking code
  4176. * can't distinguish what the connection is going to be for. */
  4177. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  4178. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  4179. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  4180. } else {
  4181. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  4182. }
  4183. }
  4184. if (status > bootstrap_percent ||
  4185. (progress && progress > bootstrap_percent)) {
  4186. bootstrap_status_to_string(status, &tag, &summary);
  4187. log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
  4188. "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
  4189. tor_snprintf(buf, sizeof(buf),
  4190. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  4191. progress ? progress : status, tag, summary);
  4192. tor_snprintf(last_sent_bootstrap_message,
  4193. sizeof(last_sent_bootstrap_message),
  4194. "NOTICE %s", buf);
  4195. control_event_client_status(LOG_NOTICE, "%s", buf);
  4196. if (status > bootstrap_percent) {
  4197. bootstrap_percent = status; /* new milestone reached */
  4198. }
  4199. if (progress > bootstrap_percent) {
  4200. /* incremental progress within a milestone */
  4201. bootstrap_percent = progress;
  4202. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  4203. }
  4204. }
  4205. }
  4206. /** Called when Tor has failed to make bootstrapping progress in a way
  4207. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  4208. * <b>reason</b> provides an "or_conn_end_reason" tag.
  4209. */
  4210. void
  4211. control_event_bootstrap_problem(const char *warn, int reason)
  4212. {
  4213. int status = bootstrap_percent;
  4214. const char *tag, *summary;
  4215. char buf[BOOTSTRAP_MSG_LEN];
  4216. const char *recommendation = "ignore";
  4217. int severity;
  4218. /* bootstrap_percent must not be in "undefined" state here. */
  4219. tor_assert(status >= 0);
  4220. if (bootstrap_percent == 100)
  4221. return; /* already bootstrapped; nothing to be done here. */
  4222. bootstrap_problems++;
  4223. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  4224. recommendation = "warn";
  4225. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  4226. recommendation = "warn";
  4227. if (get_options()->UseBridges &&
  4228. !any_bridge_descriptors_known() &&
  4229. !any_pending_bridge_descriptor_fetches())
  4230. recommendation = "warn";
  4231. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  4232. status--; /* find a recognized status string based on current progress */
  4233. status = bootstrap_percent; /* set status back to the actual number */
  4234. severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
  4235. log_fn(severity,
  4236. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  4237. "count %d; recommendation %s)",
  4238. status, summary, warn,
  4239. orconn_end_reason_to_control_string(reason),
  4240. bootstrap_problems, recommendation);
  4241. connection_or_report_broken_states(severity, LD_HANDSHAKE);
  4242. tor_snprintf(buf, sizeof(buf),
  4243. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  4244. "COUNT=%d RECOMMENDATION=%s",
  4245. bootstrap_percent, tag, summary, warn,
  4246. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  4247. recommendation);
  4248. tor_snprintf(last_sent_bootstrap_message,
  4249. sizeof(last_sent_bootstrap_message),
  4250. "WARN %s", buf);
  4251. control_event_client_status(LOG_WARN, "%s", buf);
  4252. }
  4253. /** We just generated a new summary of which countries we've seen clients
  4254. * from recently. Send a copy to the controller in case it wants to
  4255. * display it for the user. */
  4256. void
  4257. control_event_clients_seen(const char *controller_str)
  4258. {
  4259. send_control_event(EVENT_CLIENTS_SEEN, 0,
  4260. "650 CLIENTS_SEEN %s\r\n", controller_str);
  4261. }