control.c 154 KB

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