control.c 155 KB

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