control.c 157 KB

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