control.c 157 KB

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