control.c 122 KB

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