control.c 171 KB

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