control.c 121 KB

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