control.c 134 KB

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