control.c 171 KB

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