control.c 167 KB

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