control.c 125 KB

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