control.c 147 KB

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