control.c 140 KB

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