control.c 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609
  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_control_done(conn);
  1042. /* Flush the "done" first if the signal might make us shut down. */
  1043. if (sig == SIGTERM || sig == SIGINT)
  1044. connection_handle_write(TO_CONN(conn), 1);
  1045. control_signal_act(sig);
  1046. return 0;
  1047. }
  1048. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1049. * and report success or failrue. */
  1050. static int
  1051. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1052. const char *body)
  1053. {
  1054. smartlist_t *elts;
  1055. smartlist_t *lines;
  1056. smartlist_t *reply;
  1057. char *r;
  1058. size_t sz;
  1059. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1060. lines = smartlist_create();
  1061. elts = smartlist_create();
  1062. reply = smartlist_create();
  1063. smartlist_split_string(lines, body, " ",
  1064. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1065. SMARTLIST_FOREACH(lines, char *, line,
  1066. {
  1067. tor_strlower(line);
  1068. smartlist_split_string(elts, line, "=", 0, 2);
  1069. if (smartlist_len(elts) == 2) {
  1070. const char *from = smartlist_get(elts,0);
  1071. const char *to = smartlist_get(elts,1);
  1072. size_t anslen = strlen(line)+512;
  1073. char *ans = tor_malloc(anslen);
  1074. if (address_is_invalid_destination(to, 1)) {
  1075. tor_snprintf(ans, anslen,
  1076. "512-syntax error: invalid address '%s'", to);
  1077. smartlist_add(reply, ans);
  1078. log_warn(LD_CONTROL,
  1079. "Skipping invalid argument '%s' in MapAddress msg", to);
  1080. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  1081. const char *address = addressmap_register_virtual_address(
  1082. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  1083. tor_strdup(to));
  1084. if (!address) {
  1085. tor_snprintf(ans, anslen,
  1086. "451-resource exhausted: skipping '%s'", line);
  1087. smartlist_add(reply, ans);
  1088. log_warn(LD_CONTROL,
  1089. "Unable to allocate address for '%s' in MapAddress msg",
  1090. safe_str(line));
  1091. } else {
  1092. tor_snprintf(ans, anslen, "250-%s=%s", address, to);
  1093. smartlist_add(reply, ans);
  1094. }
  1095. } else {
  1096. addressmap_register(from, tor_strdup(to), 1);
  1097. tor_snprintf(ans, anslen, "250-%s", line);
  1098. smartlist_add(reply, ans);
  1099. }
  1100. } else {
  1101. size_t anslen = strlen(line)+256;
  1102. char *ans = tor_malloc(anslen);
  1103. tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
  1104. "not of expected form 'foo=bar'.", line);
  1105. smartlist_add(reply, ans);
  1106. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1107. "number of items.", safe_str(line));
  1108. }
  1109. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1110. smartlist_clear(elts);
  1111. });
  1112. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1113. smartlist_free(lines);
  1114. smartlist_free(elts);
  1115. if (smartlist_len(reply)) {
  1116. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1117. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1118. connection_write_to_buf(r, sz, TO_CONN(conn));
  1119. tor_free(r);
  1120. } else {
  1121. const char *response =
  1122. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1123. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1124. }
  1125. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1126. smartlist_free(reply);
  1127. return 0;
  1128. }
  1129. /** Implementation helper for GETINFO: knows the answers for various
  1130. * trivial-to-implement questions. */
  1131. static int
  1132. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1133. char **answer)
  1134. {
  1135. (void) conn;
  1136. if (!strcmp(question, "version")) {
  1137. *answer = tor_strdup(get_version());
  1138. } else if (!strcmp(question, "config-file")) {
  1139. *answer = tor_strdup(get_torrc_fname());
  1140. } else if (!strcmp(question, "info/names")) {
  1141. *answer = list_getinfo_options();
  1142. } else if (!strcmp(question, "events/names")) {
  1143. *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
  1144. "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
  1145. "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
  1146. "GUARD STREAM_BW");
  1147. } else if (!strcmp(question, "features/names")) {
  1148. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1149. } else if (!strcmp(question, "address")) {
  1150. uint32_t addr;
  1151. if (router_pick_published_address(get_options(), &addr) < 0)
  1152. return -1;
  1153. *answer = tor_dup_addr(addr);
  1154. } else if (!strcmp(question, "dir-usage")) {
  1155. *answer = directory_dump_request_log();
  1156. } else if (!strcmp(question, "fingerprint")) {
  1157. routerinfo_t *me = router_get_my_routerinfo();
  1158. if (!me)
  1159. return -1;
  1160. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1161. base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
  1162. DIGEST_LEN);
  1163. }
  1164. return 0;
  1165. }
  1166. /** Awful hack: return a newly allocated string based on a routerinfo and
  1167. * (possibly) an extrainfo, sticking the read-history and write-history from
  1168. * <b>ei</b> into the resulting string. The thing you get back won't
  1169. * necessarily have a valid signature.
  1170. *
  1171. * New code should never use this; it's for backward compatibiliy.
  1172. *
  1173. * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
  1174. * not be NUL-terminated. */
  1175. static char *
  1176. munge_extrainfo_into_routerinfo(const char *ri_body, signed_descriptor_t *ri,
  1177. signed_descriptor_t *ei)
  1178. {
  1179. char *out = NULL, *outp;
  1180. int i;
  1181. const char *router_sig;
  1182. const char *ei_body = signed_descriptor_get_body(ei);
  1183. size_t ri_len = ri->signed_descriptor_len;
  1184. size_t ei_len = ei->signed_descriptor_len;
  1185. if (!ei_body)
  1186. goto bail;
  1187. outp = out = tor_malloc(ri_len+ei_len+1);
  1188. if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
  1189. goto bail;
  1190. ++router_sig;
  1191. memcpy(out, ri_body, router_sig-ri_body);
  1192. outp += router_sig-ri_body;
  1193. for (i=0; i < 2; ++i) {
  1194. const char *kwd = i?"\nwrite-history ":"\nread-history ";
  1195. const char *cp, *eol;
  1196. if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
  1197. continue;
  1198. ++cp;
  1199. eol = memchr(cp, '\n', ei_len - (cp-ei_body));
  1200. memcpy(outp, cp, eol-cp+1);
  1201. outp += eol-cp+1;
  1202. }
  1203. memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
  1204. *outp++ = '\0';
  1205. tor_assert(outp-out < (int)(ri_len+ei_len+1));
  1206. return out;
  1207. bail:
  1208. tor_free(out);
  1209. return tor_strndup(ri_body, ri->signed_descriptor_len);
  1210. }
  1211. /** Implementation helper for GETINFO: knows the answers for questions about
  1212. * directory information. */
  1213. static int
  1214. getinfo_helper_dir(control_connection_t *control_conn,
  1215. const char *question, char **answer)
  1216. {
  1217. if (!strcmpstart(question, "desc/id/")) {
  1218. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1219. if (ri) {
  1220. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1221. if (body)
  1222. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1223. }
  1224. } else if (!strcmpstart(question, "desc/name/")) {
  1225. routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1226. if (ri) {
  1227. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1228. if (body)
  1229. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1230. }
  1231. } else if (!strcmp(question, "desc/all-recent")) {
  1232. routerlist_t *routerlist = router_get_routerlist();
  1233. smartlist_t *sl = smartlist_create();
  1234. if (routerlist && routerlist->routers) {
  1235. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1236. {
  1237. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1238. if (body)
  1239. smartlist_add(sl,
  1240. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1241. });
  1242. }
  1243. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1244. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1245. smartlist_free(sl);
  1246. } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
  1247. /* XXXX Remove this once Torstat asks for extrainfos. */
  1248. routerlist_t *routerlist = router_get_routerlist();
  1249. smartlist_t *sl = smartlist_create();
  1250. if (routerlist && routerlist->routers) {
  1251. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1252. {
  1253. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1254. signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
  1255. ri->cache_info.extra_info_digest);
  1256. if (ei && body) {
  1257. smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
  1258. &ri->cache_info, ei));
  1259. } else if (body) {
  1260. smartlist_add(sl,
  1261. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1262. }
  1263. });
  1264. }
  1265. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1266. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1267. smartlist_free(sl);
  1268. } else if (!strcmpstart(question, "dir/server/")) {
  1269. size_t answer_len = 0, url_len = strlen(question)+2;
  1270. char *url = tor_malloc(url_len);
  1271. smartlist_t *descs = smartlist_create();
  1272. const char *msg;
  1273. int res;
  1274. char *cp;
  1275. tor_snprintf(url, url_len, "/tor/%s", question+4);
  1276. res = dirserv_get_routerdescs(descs, url, &msg);
  1277. if (res) {
  1278. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1279. return -1;
  1280. }
  1281. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1282. answer_len += sd->signed_descriptor_len);
  1283. cp = *answer = tor_malloc(answer_len+1);
  1284. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1285. {
  1286. memcpy(cp, signed_descriptor_get_body(sd),
  1287. sd->signed_descriptor_len);
  1288. cp += sd->signed_descriptor_len;
  1289. });
  1290. *cp = '\0';
  1291. tor_free(url);
  1292. smartlist_free(descs);
  1293. } else if (!strcmpstart(question, "dir/status/")) {
  1294. if (dirserver_mode(get_options())) {
  1295. size_t len=0;
  1296. char *cp;
  1297. smartlist_t *status_list = smartlist_create();
  1298. dirserv_get_networkstatus_v2(status_list,
  1299. question+strlen("dir/status/"));
  1300. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1301. cp = *answer = tor_malloc(len+1);
  1302. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1303. memcpy(cp, d->dir, d->dir_len);
  1304. cp += d->dir_len;
  1305. });
  1306. *cp = '\0';
  1307. smartlist_free(status_list);
  1308. } else {
  1309. smartlist_t *fp_list = smartlist_create();
  1310. smartlist_t *status_list = smartlist_create();
  1311. dirserv_get_networkstatus_v2_fingerprints(
  1312. fp_list, question+strlen("dir/status/"));
  1313. SMARTLIST_FOREACH(fp_list, const char *, fp, {
  1314. char *s;
  1315. char *fname = networkstatus_get_cache_filename(fp);
  1316. s = read_file_to_str(fname, 0, NULL);
  1317. if (s)
  1318. smartlist_add(status_list, s);
  1319. tor_free(fname);
  1320. });
  1321. SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
  1322. smartlist_free(fp_list);
  1323. *answer = smartlist_join_strings(status_list, "", 0, NULL);
  1324. SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
  1325. smartlist_free(status_list);
  1326. }
  1327. } else if (!strcmp(question, "network-status")) {
  1328. routerlist_t *routerlist = router_get_routerlist();
  1329. int verbose = control_conn->use_long_names;
  1330. if (!routerlist || !routerlist->routers ||
  1331. list_server_status(routerlist->routers, answer, verbose ? 2 : 1) < 0) {
  1332. return -1;
  1333. }
  1334. } else if (!strcmpstart(question, "extra-info/digest/")) {
  1335. question += strlen("extra-info/digest/");
  1336. if (strlen(question) == HEX_DIGEST_LEN) {
  1337. char d[DIGEST_LEN];
  1338. signed_descriptor_t *sd;
  1339. base16_decode(d, sizeof(d), question, strlen(question));
  1340. sd = extrainfo_get_by_descriptor_digest(d);
  1341. if (sd) {
  1342. const char *body = signed_descriptor_get_body(sd);
  1343. if (body)
  1344. *answer = tor_strndup(body, sd->signed_descriptor_len);
  1345. }
  1346. }
  1347. }
  1348. return 0;
  1349. }
  1350. /** Implementation helper for GETINFO: knows how to generate summaries of the
  1351. * current states of things we send events about. */
  1352. static int
  1353. getinfo_helper_events(control_connection_t *control_conn,
  1354. const char *question, char **answer)
  1355. {
  1356. if (!strcmp(question, "circuit-status")) {
  1357. circuit_t *circ;
  1358. smartlist_t *status = smartlist_create();
  1359. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1360. char *s, *path;
  1361. size_t slen;
  1362. const char *state;
  1363. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1364. continue;
  1365. if (control_conn->use_long_names)
  1366. path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
  1367. else
  1368. path = circuit_list_path(TO_ORIGIN_CIRCUIT(circ),0);
  1369. if (circ->state == CIRCUIT_STATE_OPEN)
  1370. state = "BUILT";
  1371. else if (strlen(path))
  1372. state = "EXTENDED";
  1373. else
  1374. state = "LAUNCHED";
  1375. slen = strlen(path)+strlen(state)+20;
  1376. s = tor_malloc(slen+1);
  1377. tor_snprintf(s, slen, "%lu %s%s%s",
  1378. (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1379. state, *path ? " " : "", path);
  1380. smartlist_add(status, s);
  1381. tor_free(path);
  1382. }
  1383. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1384. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1385. smartlist_free(status);
  1386. } else if (!strcmp(question, "stream-status")) {
  1387. smartlist_t *conns = get_connection_array();
  1388. smartlist_t *status = smartlist_create();
  1389. char buf[256];
  1390. SMARTLIST_FOREACH(conns, connection_t *, base_conn,
  1391. {
  1392. const char *state;
  1393. edge_connection_t *conn;
  1394. char *s;
  1395. size_t slen;
  1396. circuit_t *circ;
  1397. origin_circuit_t *origin_circ = NULL;
  1398. if (base_conn->type != CONN_TYPE_AP ||
  1399. base_conn->marked_for_close ||
  1400. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  1401. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  1402. continue;
  1403. conn = TO_EDGE_CONN(base_conn);
  1404. switch (conn->_base.state)
  1405. {
  1406. case AP_CONN_STATE_CONTROLLER_WAIT:
  1407. case AP_CONN_STATE_CIRCUIT_WAIT:
  1408. if (conn->socks_request &&
  1409. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1410. state = "NEWRESOLVE";
  1411. else
  1412. state = "NEW";
  1413. break;
  1414. case AP_CONN_STATE_RENDDESC_WAIT:
  1415. case AP_CONN_STATE_CONNECT_WAIT:
  1416. state = "SENTCONNECT"; break;
  1417. case AP_CONN_STATE_RESOLVE_WAIT:
  1418. state = "SENTRESOLVE"; break;
  1419. case AP_CONN_STATE_OPEN:
  1420. state = "SUCCEEDED"; break;
  1421. default:
  1422. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1423. conn->_base.state);
  1424. continue;
  1425. }
  1426. circ = circuit_get_by_edge_conn(conn);
  1427. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1428. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1429. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1430. slen = strlen(buf)+strlen(state)+32;
  1431. s = tor_malloc(slen+1);
  1432. tor_snprintf(s, slen, "%lu %s %lu %s",
  1433. (unsigned long) conn->global_identifier,state,
  1434. origin_circ?
  1435. (unsigned long)origin_circ->global_identifier : 0ul,
  1436. buf);
  1437. smartlist_add(status, s);
  1438. });
  1439. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1440. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1441. smartlist_free(status);
  1442. } else if (!strcmp(question, "orconn-status")) {
  1443. smartlist_t *conns = get_connection_array();
  1444. smartlist_t *status = smartlist_create();
  1445. SMARTLIST_FOREACH(conns, connection_t *, base_conn,
  1446. {
  1447. const char *state;
  1448. char *s;
  1449. char name[128];
  1450. size_t slen;
  1451. or_connection_t *conn;
  1452. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  1453. continue;
  1454. conn = TO_OR_CONN(base_conn);
  1455. if (conn->_base.state == OR_CONN_STATE_OPEN)
  1456. state = "CONNECTED";
  1457. else if (conn->nickname)
  1458. state = "LAUNCHED";
  1459. else
  1460. state = "NEW";
  1461. orconn_target_get_name(control_conn->use_long_names, name, sizeof(name),
  1462. conn);
  1463. slen = strlen(name)+strlen(state)+2;
  1464. s = tor_malloc(slen+1);
  1465. tor_snprintf(s, slen, "%s %s", name, state);
  1466. smartlist_add(status, s);
  1467. });
  1468. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1469. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1470. smartlist_free(status);
  1471. } else if (!strcmpstart(question, "addr-mappings/") ||
  1472. !strcmpstart(question, "address-mappings/")) {
  1473. /* XXXX020 Warn about deprecated addr-mappings variant? Or wait for
  1474. * 0.2.1.x? */
  1475. time_t min_e, max_e;
  1476. smartlist_t *mappings;
  1477. int want_expiry = !strcmpstart(question, "address-mappings/");
  1478. question += strlen(want_expiry ? "address-mappings/"
  1479. : "addr-mappings/");
  1480. if (!strcmp(question, "all")) {
  1481. min_e = 0; max_e = TIME_MAX;
  1482. } else if (!strcmp(question, "cache")) {
  1483. min_e = 2; max_e = TIME_MAX;
  1484. } else if (!strcmp(question, "config")) {
  1485. min_e = 0; max_e = 0;
  1486. } else if (!strcmp(question, "control")) {
  1487. min_e = 1; max_e = 1;
  1488. } else {
  1489. return 0;
  1490. }
  1491. mappings = smartlist_create();
  1492. addressmap_get_mappings(mappings, min_e, max_e, want_expiry);
  1493. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1494. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1495. smartlist_free(mappings);
  1496. } else if (!strcmpstart(question, "status/")) {
  1497. /* Note that status/ is not a catch-all for events; there's only supposed
  1498. * to be a status GETINFO if there's a corresponding STATUS event. */
  1499. if (!strcmp(question, "status/circuit-established")) {
  1500. *answer = tor_strdup(has_completed_circuit ? "1" : "0");
  1501. } else if (!strcmp(question, "status/enough-dir-info")) {
  1502. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  1503. } else if (!strcmp(question, "status/good-server-descriptor")) {
  1504. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  1505. ? "1" : "0");
  1506. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  1507. *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
  1508. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  1509. *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
  1510. } else if (!strcmp(question, "status/reachability-succeeded")) {
  1511. *answer = tor_malloc(16);
  1512. tor_snprintf(*answer, 16, "OR=%d DIR=%d",
  1513. check_whether_orport_reachable() ? 1 : 0,
  1514. check_whether_dirport_reachable() ? 1 : 0);
  1515. } else if (!strcmpstart(question, "status/version/")) {
  1516. int is_server = server_mode(get_options());
  1517. networkstatus_vote_t *c = networkstatus_get_latest_consensus();
  1518. version_status_t status;
  1519. const char *recommended;
  1520. if (c) {
  1521. recommended = is_server ? c->server_versions : c->client_versions;
  1522. status = tor_version_is_obsolete(VERSION, recommended);
  1523. } else {
  1524. recommended = "?";
  1525. status = VS_UNKNOWN;
  1526. }
  1527. if (!strcmp(question, "status/version/recommended")) {
  1528. *answer = tor_strdup(recommended);
  1529. return 0;
  1530. }
  1531. if (!strcmp(question, "status/version/current")) {
  1532. switch (status)
  1533. {
  1534. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  1535. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  1536. case VS_NEW: *answer = tor_strdup("new"); break;
  1537. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  1538. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  1539. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  1540. default: tor_fragile_assert();
  1541. }
  1542. } else if (!strcmp(question, "status/version/num-versioning") ||
  1543. !strcmp(question, "status/version/num-concurring")) {
  1544. /*XXXX020 deprecate.*/
  1545. char s[33];
  1546. tor_snprintf(s, sizeof(s), "%d", get_n_authorities(V3_AUTHORITY));
  1547. *answer = tor_strdup(s);
  1548. }
  1549. } else {
  1550. return 0;
  1551. }
  1552. }
  1553. return 0;
  1554. }
  1555. /** Callback function for GETINFO: on a given control connection, try to
  1556. * answer the question <b>q</b> and store the newly-allocated answer in
  1557. * *<b>a</b>. If there's no answer, or an error occurs, just don't set
  1558. * <b>a</b>. Return 0.
  1559. */
  1560. typedef int (*getinfo_helper_t)(control_connection_t *,
  1561. const char *q, char **a);
  1562. /** A single item for the GETINFO question-to-answer-function table. */
  1563. typedef struct getinfo_item_t {
  1564. const char *varname; /**< The value (or prefix) of the question. */
  1565. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  1566. * this entry is documentation-only. */
  1567. const char *desc; /**< Description of the variable. */
  1568. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  1569. } getinfo_item_t;
  1570. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  1571. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  1572. #define DOC(name, desc) { name, NULL, desc, 0 }
  1573. /** Table mapping questions accepted by GETINFO to the functions that know how
  1574. * to answer them. */
  1575. static const getinfo_item_t getinfo_items[] = {
  1576. ITEM("version", misc, "The current version of Tor."),
  1577. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  1578. ITEM("accounting/bytes", accounting,
  1579. "Number of bytes read/written so far in the accounting interval."),
  1580. ITEM("accounting/bytes-left", accounting,
  1581. "Number of bytes left to write/read so far in the accounting interval."),
  1582. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  1583. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  1584. ITEM("accounting/interval-start", accounting,
  1585. "Time when the accounting period starts."),
  1586. ITEM("accounting/interval-end", accounting,
  1587. "Time when the accounting period ends."),
  1588. ITEM("accounting/interval-wake", accounting,
  1589. "Time to wake up in this accounting period."),
  1590. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  1591. ITEM("entry-guards", entry_guards,
  1592. "Which nodes are we using as entry guards?"),
  1593. ITEM("fingerprint", misc, NULL),
  1594. PREFIX("config/", config, "Current configuration values."),
  1595. DOC("config/names",
  1596. "List of configuration options, types, and documentation."),
  1597. ITEM("info/names", misc,
  1598. "List of GETINFO options, types, and documentation."),
  1599. ITEM("events/names", misc,
  1600. "Events that the controller can ask for with SETEVENTS."),
  1601. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  1602. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  1603. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  1604. ITEM("desc/all-recent", dir,
  1605. "All non-expired, non-superseded router descriptors."),
  1606. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  1607. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  1608. ITEM("ns/all", networkstatus,
  1609. "Brief summary of router status (v2 directory format)"),
  1610. PREFIX("ns/id/", networkstatus,
  1611. "Brief summary of router status by ID (v2 directory format)."),
  1612. PREFIX("ns/name/", networkstatus,
  1613. "Brief summary of router status by nickname (v2 directory format)."),
  1614. PREFIX("unregistered-servers-", dirserv_unregistered, NULL),
  1615. ITEM("network-status", dir,
  1616. "Brief summary of router status (v1 directory format)"),
  1617. ITEM("circuit-status", events, "List of current circuits originating here."),
  1618. ITEM("stream-status", events,"List of current streams."),
  1619. ITEM("orconn-status", events, "A list of current OR connections."),
  1620. PREFIX("address-mappings/", events, NULL),
  1621. DOC("address-mappings/all", "Current address mappings."),
  1622. DOC("address-mappings/cache", "Current cached DNS replies."),
  1623. DOC("address-mappings/config",
  1624. "Current address mappings from configuration."),
  1625. DOC("address-mappings/control", "Current address mappings from controller."),
  1626. PREFIX("addr-mappings/", events, NULL),
  1627. DOC("addr-mappings/all", "Current address mappings without expiry times."),
  1628. DOC("addr-mappings/cache",
  1629. "Current cached DNS replies without expiry times."),
  1630. DOC("addr-mappings/config",
  1631. "Current address mappings from configuration without expiry times."),
  1632. DOC("addr-mappings/control",
  1633. "Current address mappings from controller without expiry times."),
  1634. PREFIX("status/", events, NULL),
  1635. DOC("status/circuit-established",
  1636. "Whether we think client functionality is working."),
  1637. DOC("status/enough-dir-info",
  1638. "Whether we have enough up-to-date directory information to build "
  1639. "circuits."),
  1640. DOC("status/version/recommended", "List of currently recommended versions."),
  1641. DOC("status/version/current", "Status of the current version."),
  1642. DOC("status/version/num-versioning", "Number of versioning authorities."),
  1643. DOC("status/version/num-concurring",
  1644. "Number of versioning authorities agreeing on the status of the "
  1645. "current version"),
  1646. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  1647. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  1648. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  1649. PREFIX("dir/status/", dir,"Networkstatus docs as retrieved from a DirPort."),
  1650. PREFIX("exit-policy/default", policies,
  1651. "The default value appended to the configured exit policy."),
  1652. { NULL, NULL, NULL, 0 }
  1653. };
  1654. /** Allocate and return a list of recognized GETINFO options. */
  1655. static char *
  1656. list_getinfo_options(void)
  1657. {
  1658. int i;
  1659. char buf[300];
  1660. smartlist_t *lines = smartlist_create();
  1661. char *ans;
  1662. for (i = 0; getinfo_items[i].varname; ++i) {
  1663. if (!getinfo_items[i].desc)
  1664. continue;
  1665. tor_snprintf(buf, sizeof(buf), "%s%s -- %s\n",
  1666. getinfo_items[i].varname,
  1667. getinfo_items[i].is_prefix ? "*" : "",
  1668. getinfo_items[i].desc);
  1669. smartlist_add(lines, tor_strdup(buf));
  1670. }
  1671. smartlist_sort_strings(lines);
  1672. ans = smartlist_join_strings(lines, "", 0, NULL);
  1673. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1674. smartlist_free(lines);
  1675. return ans;
  1676. }
  1677. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1678. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1679. * Return 0 if success or unrecognized, or -1 if recognized but
  1680. * internal error. */
  1681. static int
  1682. handle_getinfo_helper(control_connection_t *control_conn,
  1683. const char *question, char **answer)
  1684. {
  1685. int i;
  1686. *answer = NULL; /* unrecognized key by default */
  1687. for (i = 0; getinfo_items[i].varname; ++i) {
  1688. int match;
  1689. if (getinfo_items[i].is_prefix)
  1690. match = !strcmpstart(question, getinfo_items[i].varname);
  1691. else
  1692. match = !strcmp(question, getinfo_items[i].varname);
  1693. if (match) {
  1694. tor_assert(getinfo_items[i].fn);
  1695. return getinfo_items[i].fn(control_conn, question, answer);
  1696. }
  1697. }
  1698. return 0; /* unrecognized */
  1699. }
  1700. /** Called when we receive a GETINFO command. Try to fetch all requested
  1701. * information, and reply with information or error message. */
  1702. static int
  1703. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  1704. const char *body)
  1705. {
  1706. smartlist_t *questions = NULL;
  1707. smartlist_t *answers = NULL;
  1708. smartlist_t *unrecognized = NULL;
  1709. char *msg = NULL, *ans = NULL;
  1710. int i;
  1711. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1712. questions = smartlist_create();
  1713. smartlist_split_string(questions, body, " ",
  1714. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1715. answers = smartlist_create();
  1716. unrecognized = smartlist_create();
  1717. SMARTLIST_FOREACH(questions, const char *, q,
  1718. {
  1719. if (handle_getinfo_helper(conn, q, &ans) < 0) {
  1720. connection_write_str_to_buf("551 Internal error\r\n", conn);
  1721. goto done;
  1722. }
  1723. if (!ans) {
  1724. smartlist_add(unrecognized, (char*)q);
  1725. } else {
  1726. smartlist_add(answers, tor_strdup(q));
  1727. smartlist_add(answers, ans);
  1728. }
  1729. });
  1730. if (smartlist_len(unrecognized)) {
  1731. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1732. connection_printf_to_buf(conn,
  1733. "552-Unrecognized key \"%s\"\r\n",
  1734. (char*)smartlist_get(unrecognized, i));
  1735. connection_printf_to_buf(conn,
  1736. "552 Unrecognized key \"%s\"\r\n",
  1737. (char*)smartlist_get(unrecognized, i));
  1738. goto done;
  1739. }
  1740. for (i = 0; i < smartlist_len(answers); i += 2) {
  1741. char *k = smartlist_get(answers, i);
  1742. char *v = smartlist_get(answers, i+1);
  1743. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1744. connection_printf_to_buf(conn, "250-%s=", k);
  1745. connection_write_str_to_buf(v, conn);
  1746. connection_write_str_to_buf("\r\n", conn);
  1747. } else {
  1748. char *esc = NULL;
  1749. size_t esc_len;
  1750. esc_len = write_escaped_data(v, strlen(v), &esc);
  1751. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1752. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  1753. tor_free(esc);
  1754. }
  1755. }
  1756. connection_write_str_to_buf("250 OK\r\n", conn);
  1757. done:
  1758. if (answers) {
  1759. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1760. smartlist_free(answers);
  1761. }
  1762. if (questions) {
  1763. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1764. smartlist_free(questions);
  1765. }
  1766. smartlist_free(unrecognized);
  1767. tor_free(msg);
  1768. return 0;
  1769. }
  1770. /** Given a string, convert it to a circuit purpose. */
  1771. static uint8_t
  1772. circuit_purpose_from_string(const char *string)
  1773. {
  1774. if (!strcmpstart(string, "purpose="))
  1775. string += strlen("purpose=");
  1776. if (!strcmp(string, "general"))
  1777. return CIRCUIT_PURPOSE_C_GENERAL;
  1778. else if (!strcmp(string, "controller"))
  1779. return CIRCUIT_PURPOSE_CONTROLLER;
  1780. else
  1781. return CIRCUIT_PURPOSE_UNKNOWN;
  1782. }
  1783. /** Return a newly allocated smartlist containing the arguments to the command
  1784. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  1785. * or if <b>max_args</b> is nonnegative and there are more than
  1786. * <b>max_args</b> arguments, send a 512 error to the controller, using
  1787. * <b>command</b> as the command name in the error message. */
  1788. static smartlist_t *
  1789. getargs_helper(const char *command, control_connection_t *conn,
  1790. const char *body, int min_args, int max_args)
  1791. {
  1792. smartlist_t *args = smartlist_create();
  1793. smartlist_split_string(args, body, " ",
  1794. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1795. if (smartlist_len(args) < min_args) {
  1796. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  1797. goto err;
  1798. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  1799. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  1800. goto err;
  1801. }
  1802. return args;
  1803. err:
  1804. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  1805. smartlist_free(args);
  1806. return NULL;
  1807. }
  1808. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  1809. * circuit, and report success or failure. */
  1810. static int
  1811. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  1812. const char *body)
  1813. {
  1814. smartlist_t *router_nicknames=NULL, *routers=NULL;
  1815. origin_circuit_t *circ = NULL;
  1816. int zero_circ;
  1817. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1818. smartlist_t *args;
  1819. (void) len;
  1820. router_nicknames = smartlist_create();
  1821. args = getargs_helper("EXTENDCIRCUIT", conn, body, 2, -1);
  1822. if (!args)
  1823. goto done;
  1824. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  1825. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  1826. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1827. (char*)smartlist_get(args, 0));
  1828. }
  1829. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  1830. if (zero_circ && smartlist_len(args)>2) {
  1831. char *purp = smartlist_get(args,2);
  1832. intended_purpose = circuit_purpose_from_string(purp);
  1833. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  1834. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1835. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1836. smartlist_free(args);
  1837. goto done;
  1838. }
  1839. }
  1840. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1841. smartlist_free(args);
  1842. if (!zero_circ && !circ) {
  1843. goto done;
  1844. }
  1845. routers = smartlist_create();
  1846. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  1847. {
  1848. routerinfo_t *r = router_get_by_nickname(n, 1);
  1849. if (!r) {
  1850. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  1851. goto done;
  1852. }
  1853. smartlist_add(routers, r);
  1854. });
  1855. if (!smartlist_len(routers)) {
  1856. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  1857. goto done;
  1858. }
  1859. if (zero_circ) {
  1860. /* start a new circuit */
  1861. circ = origin_circuit_init(intended_purpose, 0, 0, 0, 0);
  1862. }
  1863. /* now circ refers to something that is ready to be extended */
  1864. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1865. {
  1866. extend_info_t *info = extend_info_from_router(r);
  1867. circuit_append_new_exit(circ, info);
  1868. extend_info_free(info);
  1869. });
  1870. /* now that we've populated the cpath, start extending */
  1871. if (zero_circ) {
  1872. int err_reason = 0;
  1873. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  1874. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1875. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  1876. goto done;
  1877. }
  1878. } else {
  1879. if (circ->_base.state == CIRCUIT_STATE_OPEN) {
  1880. int err_reason = 0;
  1881. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1882. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  1883. log_info(LD_CONTROL,
  1884. "send_next_onion_skin failed; circuit marked for closing.");
  1885. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1886. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  1887. goto done;
  1888. }
  1889. }
  1890. }
  1891. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  1892. (unsigned long)circ->global_identifier);
  1893. if (zero_circ) /* send a 'launched' event, for completeness */
  1894. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  1895. done:
  1896. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  1897. smartlist_free(router_nicknames);
  1898. if (routers)
  1899. smartlist_free(routers);
  1900. return 0;
  1901. }
  1902. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  1903. * circuit and it's a valid purpose, change it. */
  1904. static int
  1905. handle_control_setcircuitpurpose(control_connection_t *conn,
  1906. uint32_t len, const char *body)
  1907. {
  1908. origin_circuit_t *circ = NULL;
  1909. uint8_t new_purpose;
  1910. smartlist_t *args;
  1911. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1912. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  1913. if (!args)
  1914. goto done;
  1915. if (!(circ = get_circ(smartlist_get(args,0)))) {
  1916. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1917. (char*)smartlist_get(args, 0));
  1918. goto done;
  1919. }
  1920. {
  1921. char *purp = smartlist_get(args,1);
  1922. new_purpose = circuit_purpose_from_string(purp);
  1923. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  1924. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1925. goto done;
  1926. }
  1927. }
  1928. circ->_base.purpose = new_purpose;
  1929. connection_write_str_to_buf("250 OK\r\n", conn);
  1930. done:
  1931. if (args) {
  1932. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1933. smartlist_free(args);
  1934. }
  1935. return 0;
  1936. }
  1937. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  1938. * stream, and report success or failure. */
  1939. static int
  1940. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  1941. const char *body)
  1942. {
  1943. edge_connection_t *ap_conn = NULL;
  1944. origin_circuit_t *circ = NULL;
  1945. int zero_circ;
  1946. smartlist_t *args;
  1947. crypt_path_t *cpath=NULL;
  1948. int hop=0, hop_line_ok=1;
  1949. (void) len;
  1950. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  1951. if (!args)
  1952. return 0;
  1953. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  1954. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  1955. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1956. (char*)smartlist_get(args, 0));
  1957. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  1958. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1959. (char*)smartlist_get(args, 1));
  1960. } else if (circ && smartlist_len(args) > 2) {
  1961. char *hopstring = smartlist_get(args, 2);
  1962. if (!strcasecmpstart(hopstring, "HOP=")) {
  1963. hopstring += strlen("HOP=");
  1964. hop = tor_parse_ulong(hopstring, 10, 0, ULONG_MAX,
  1965. &hop_line_ok, NULL);
  1966. if (!hop_line_ok) { /* broken hop line */
  1967. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  1968. }
  1969. }
  1970. }
  1971. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1972. smartlist_free(args);
  1973. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  1974. return 0;
  1975. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
  1976. ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
  1977. ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  1978. connection_write_str_to_buf(
  1979. "555 Connection is not managed by controller.\r\n",
  1980. conn);
  1981. return 0;
  1982. }
  1983. /* Do we need to detach it first? */
  1984. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
  1985. circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
  1986. connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT);
  1987. /* Un-mark it as ending, since we're going to reuse it. */
  1988. ap_conn->_base.edge_has_sent_end = 0;
  1989. ap_conn->end_reason = 0;
  1990. if (tmpcirc)
  1991. circuit_detach_stream(tmpcirc,ap_conn);
  1992. ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1993. }
  1994. if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
  1995. connection_write_str_to_buf(
  1996. "551 Can't attach stream to non-open origin circuit\r\n",
  1997. conn);
  1998. return 0;
  1999. }
  2000. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  2001. connection_write_str_to_buf(
  2002. "551 Can't attach stream to one-hop circuit.\r\n", conn);
  2003. return 0;
  2004. }
  2005. if (circ && hop>0) {
  2006. /* find this hop in the circuit, and set cpath */
  2007. cpath = circuit_get_cpath_hop(circ, hop);
  2008. if (!cpath) {
  2009. connection_printf_to_buf(conn,
  2010. "551 Circuit doesn't have %d hops.\r\n", hop);
  2011. return 0;
  2012. }
  2013. }
  2014. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  2015. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  2016. return 0;
  2017. }
  2018. send_control_done(conn);
  2019. return 0;
  2020. }
  2021. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  2022. * descriptor, and report success or failure. */
  2023. static int
  2024. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  2025. const char *body)
  2026. {
  2027. char *desc;
  2028. const char *msg=NULL;
  2029. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  2030. int cache = 0; /* eventually, we may switch this to 1 */
  2031. char *cp = memchr(body, '\n', len);
  2032. smartlist_t *args = smartlist_create();
  2033. tor_assert(cp);
  2034. *cp++ = '\0';
  2035. smartlist_split_string(args, body, " ",
  2036. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2037. SMARTLIST_FOREACH(args, char *, option,
  2038. {
  2039. if (!strcasecmpstart(option, "purpose=")) {
  2040. option += strlen("purpose=");
  2041. purpose = router_purpose_from_string(option);
  2042. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  2043. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  2044. option);
  2045. goto done;
  2046. }
  2047. } else if (!strcasecmpstart(option, "cache=")) {
  2048. option += strlen("cache=");
  2049. if (!strcmp(option, "no"))
  2050. cache = 0;
  2051. else if (!strcmp(option, "yes"))
  2052. cache = 1;
  2053. else {
  2054. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  2055. option);
  2056. goto done;
  2057. }
  2058. } else { /* unrecognized argument? */
  2059. connection_printf_to_buf(conn,
  2060. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  2061. goto done;
  2062. }
  2063. });
  2064. read_escaped_data(cp, len-(cp-body), &desc);
  2065. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  2066. case -1:
  2067. if (!msg) msg = "Could not parse descriptor";
  2068. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  2069. break;
  2070. case 0:
  2071. if (!msg) msg = "Descriptor not added";
  2072. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2073. break;
  2074. case 1:
  2075. send_control_done(conn);
  2076. break;
  2077. }
  2078. tor_free(desc);
  2079. done:
  2080. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  2081. smartlist_free(args);
  2082. return 0;
  2083. }
  2084. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2085. * address of the named AP stream, and report success or failure. */
  2086. static int
  2087. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2088. const char *body)
  2089. {
  2090. edge_connection_t *ap_conn = NULL;
  2091. char *new_addr = NULL;
  2092. uint16_t new_port = 0;
  2093. smartlist_t *args;
  2094. (void) len;
  2095. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  2096. if (!args)
  2097. return 0;
  2098. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2099. || !ap_conn->socks_request) {
  2100. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2101. (char*)smartlist_get(args, 0));
  2102. } else {
  2103. int ok;
  2104. if (smartlist_len(args) > 2) { /* they included a port too */
  2105. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2106. 10, 1, 65535, &ok, NULL);
  2107. }
  2108. if (!ok) {
  2109. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2110. (char*)smartlist_get(args, 2));
  2111. } else {
  2112. new_addr = tor_strdup(smartlist_get(args, 1));
  2113. }
  2114. }
  2115. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2116. smartlist_free(args);
  2117. if (!new_addr)
  2118. return 0;
  2119. strlcpy(ap_conn->socks_request->address, new_addr,
  2120. sizeof(ap_conn->socks_request->address));
  2121. if (new_port)
  2122. ap_conn->socks_request->port = new_port;
  2123. tor_free(new_addr);
  2124. send_control_done(conn);
  2125. return 0;
  2126. }
  2127. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2128. * and report success or failure. */
  2129. static int
  2130. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2131. const char *body)
  2132. {
  2133. edge_connection_t *ap_conn=NULL;
  2134. uint8_t reason=0;
  2135. smartlist_t *args;
  2136. int ok;
  2137. (void) len;
  2138. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2139. if (!args)
  2140. return 0;
  2141. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2142. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2143. (char*)smartlist_get(args, 0));
  2144. else {
  2145. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2146. &ok, NULL);
  2147. if (!ok) {
  2148. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2149. (char*)smartlist_get(args, 1));
  2150. ap_conn = NULL;
  2151. }
  2152. }
  2153. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2154. smartlist_free(args);
  2155. if (!ap_conn)
  2156. return 0;
  2157. connection_mark_unattached_ap(ap_conn, reason);
  2158. send_control_done(conn);
  2159. return 0;
  2160. }
  2161. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2162. * and report success or failure. */
  2163. static int
  2164. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2165. const char *body)
  2166. {
  2167. origin_circuit_t *circ = NULL;
  2168. int safe = 0;
  2169. smartlist_t *args;
  2170. (void) len;
  2171. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2172. if (!args)
  2173. return 0;
  2174. if (!(circ=get_circ(smartlist_get(args, 0))))
  2175. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2176. (char*)smartlist_get(args, 0));
  2177. else {
  2178. int i;
  2179. for (i=1; i < smartlist_len(args); ++i) {
  2180. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2181. safe = 1;
  2182. else
  2183. log_info(LD_CONTROL, "Skipping unknown option %s",
  2184. (char*)smartlist_get(args,i));
  2185. }
  2186. }
  2187. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2188. smartlist_free(args);
  2189. if (!circ)
  2190. return 0;
  2191. if (!safe || !circ->p_streams) {
  2192. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2193. }
  2194. send_control_done(conn);
  2195. return 0;
  2196. }
  2197. /** Called when we get a RESOLVE command: start trying to resolve
  2198. * the listed addresses. */
  2199. static int
  2200. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2201. const char *body)
  2202. {
  2203. smartlist_t *args;
  2204. int is_reverse = 0;
  2205. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2206. if (!(conn->event_mask & (1L<<EVENT_ADDRMAP))) {
  2207. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2208. "isn't listening for ADDRMAP events. It probably won't see "
  2209. "the answer.");
  2210. }
  2211. args = smartlist_create();
  2212. smartlist_split_string(args, body, " ",
  2213. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2214. if (smartlist_len(args) &&
  2215. !strcasecmp(smartlist_get(args, 0), "mode=reverse")) {
  2216. char *cp = smartlist_get(args, 0);
  2217. smartlist_del_keeporder(args, 0);
  2218. tor_free(cp);
  2219. is_reverse = 1;
  2220. }
  2221. SMARTLIST_FOREACH(args, const char *, arg, {
  2222. dnsserv_launch_request(arg, is_reverse);
  2223. });
  2224. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2225. smartlist_free(args);
  2226. send_control_done(conn);
  2227. return 0;
  2228. }
  2229. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  2230. static int
  2231. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  2232. const char *body)
  2233. {
  2234. const char *bad_arg = NULL;
  2235. smartlist_t *args;
  2236. (void)len;
  2237. conn->have_sent_protocolinfo = 1;
  2238. args = smartlist_create();
  2239. smartlist_split_string(args, body, " ",
  2240. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2241. SMARTLIST_FOREACH(args, const char *, arg, {
  2242. int ok;
  2243. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  2244. if (!ok) {
  2245. bad_arg = arg;
  2246. break;
  2247. }
  2248. });
  2249. if (bad_arg) {
  2250. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  2251. escaped(bad_arg));
  2252. /* Don't tolerate bad arguments when not authenticated. */
  2253. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  2254. connection_mark_for_close(TO_CONN(conn));
  2255. goto done;
  2256. } else {
  2257. or_options_t *options = get_options();
  2258. int cookies = options->CookieAuthentication;
  2259. char *cfile = get_cookie_file();
  2260. char *esc_cfile = esc_for_log(cfile);
  2261. char *methods;
  2262. {
  2263. int passwd = (options->HashedControlPassword != NULL) &&
  2264. strlen(options->HashedControlPassword);
  2265. smartlist_t *mlist = smartlist_create();
  2266. if (cookies)
  2267. smartlist_add(mlist, (char*)"COOKIE");
  2268. if (passwd)
  2269. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  2270. if (!cookies && !passwd)
  2271. smartlist_add(mlist, (char*)"NULL");
  2272. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  2273. smartlist_free(mlist);
  2274. }
  2275. connection_printf_to_buf(conn,
  2276. "250-PROTOCOLINFO 1\r\n"
  2277. "250-AUTH METHODS=%s%s%s\r\n"
  2278. "250-VERSION Tor=%s\r\n"
  2279. "250 OK\r\n",
  2280. methods,
  2281. cookies?" COOKIEFILE=":"",
  2282. cookies?esc_cfile:"",
  2283. escaped(VERSION));
  2284. tor_free(methods);
  2285. tor_free(cfile);
  2286. tor_free(esc_cfile);
  2287. }
  2288. done:
  2289. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2290. smartlist_free(args);
  2291. return 0;
  2292. }
  2293. /** Called when we get a USEFEATURE command: parse the feature list, and
  2294. * set up the control_connection's options properly. */
  2295. static int
  2296. handle_control_usefeature(control_connection_t *conn,
  2297. uint32_t len,
  2298. const char *body)
  2299. {
  2300. smartlist_t *args;
  2301. int verbose_names = 0, extended_events = 0;
  2302. int bad = 0;
  2303. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2304. args = smartlist_create();
  2305. smartlist_split_string(args, body, " ",
  2306. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2307. SMARTLIST_FOREACH(args, const char *, arg, {
  2308. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2309. verbose_names = 1;
  2310. else if (!strcasecmp(arg, "EXTENDED_EVENTS")) /* <- documented */
  2311. extended_events = 1;
  2312. else if (!strcasecmp(arg, "EXTENDED_FORMAT")) {
  2313. /* remove this in 0.1.2.4; EXTENDED_FORMAT only ever worked for a
  2314. * little while during 0.1.2.2-alpha-dev. */
  2315. log_warn(LD_GENERAL,
  2316. "EXTENDED_FORMAT is deprecated; use EXTENDED_EVENTS "
  2317. "instead.");
  2318. extended_events = 1;
  2319. } else {
  2320. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2321. arg);
  2322. bad = 1;
  2323. break;
  2324. }
  2325. });
  2326. if (!bad) {
  2327. if (verbose_names) {
  2328. conn->use_long_names = 1;
  2329. control_update_global_event_mask();
  2330. }
  2331. if (extended_events)
  2332. conn->use_extended_events = 1;
  2333. send_control_done(conn);
  2334. }
  2335. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2336. smartlist_free(args);
  2337. return 0;
  2338. }
  2339. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2340. int
  2341. connection_control_finished_flushing(control_connection_t *conn)
  2342. {
  2343. tor_assert(conn);
  2344. connection_stop_writing(TO_CONN(conn));
  2345. return 0;
  2346. }
  2347. /** Called when <b>conn</b> has gotten its socket closed. */
  2348. int
  2349. connection_control_reached_eof(control_connection_t *conn)
  2350. {
  2351. tor_assert(conn);
  2352. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2353. connection_mark_for_close(TO_CONN(conn));
  2354. return 0;
  2355. }
  2356. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  2357. * stage of the protocol. */
  2358. static int
  2359. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  2360. {
  2361. if (conn->_base.state == CONTROL_CONN_STATE_OPEN)
  2362. return 1;
  2363. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  2364. return !conn->have_sent_protocolinfo;
  2365. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  2366. !strcasecmp(cmd, "QUIT"))
  2367. return 1;
  2368. return 0;
  2369. }
  2370. /** Called when data has arrived on a v1 control connection: Try to fetch
  2371. * commands from conn->inbuf, and execute them.
  2372. */
  2373. int
  2374. connection_control_process_inbuf(control_connection_t *conn)
  2375. {
  2376. size_t data_len;
  2377. int cmd_len;
  2378. char *args;
  2379. tor_assert(conn);
  2380. tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
  2381. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
  2382. if (!conn->incoming_cmd) {
  2383. conn->incoming_cmd = tor_malloc(1024);
  2384. conn->incoming_cmd_len = 1024;
  2385. conn->incoming_cmd_cur_len = 0;
  2386. }
  2387. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2388. peek_buf_has_control0_command(conn->_base.inbuf)) {
  2389. /* Detect v0 commands and send a "no more v0" message. */
  2390. size_t body_len;
  2391. char buf[128];
  2392. set_uint16(buf+2, htons(0x0000)); /* type == error */
  2393. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  2394. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  2395. "and later; upgrade your controller.",
  2396. sizeof(buf)-6);
  2397. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  2398. set_uint16(buf+0, htons(body_len));
  2399. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  2400. connection_mark_for_close(TO_CONN(conn));
  2401. conn->_base.hold_open_until_flushed = 1;
  2402. return 0;
  2403. }
  2404. again:
  2405. while (1) {
  2406. size_t last_idx;
  2407. int r;
  2408. /* First, fetch a line. */
  2409. do {
  2410. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2411. r = fetch_from_buf_line(conn->_base.inbuf,
  2412. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2413. &data_len);
  2414. if (r == 0)
  2415. /* Line not all here yet. Wait. */
  2416. return 0;
  2417. else if (r == -1) {
  2418. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  2419. conn->incoming_cmd_len *= 2;
  2420. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  2421. conn->incoming_cmd_len);
  2422. }
  2423. } while (r != 1);
  2424. tor_assert(data_len);
  2425. last_idx = conn->incoming_cmd_cur_len;
  2426. conn->incoming_cmd_cur_len += data_len;
  2427. /* We have appended a line to incoming_cmd. Is the command done? */
  2428. if (last_idx == 0 && *conn->incoming_cmd != '+')
  2429. /* One line command, didn't start with '+'. */
  2430. break;
  2431. /* XXXX this code duplication is kind of dumb. */
  2432. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  2433. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  2434. /* Just appended ".\r\n"; we're done. Remove it. */
  2435. conn->incoming_cmd_cur_len -= 3;
  2436. break;
  2437. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  2438. !memcmp(conn->incoming_cmd + last_idx, ".\n", 2)) {
  2439. /* Just appended ".\n"; we're done. Remove it. */
  2440. conn->incoming_cmd_cur_len -= 2;
  2441. break;
  2442. }
  2443. /* Otherwise, read another line. */
  2444. }
  2445. data_len = conn->incoming_cmd_cur_len;
  2446. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  2447. * recognize it.
  2448. */
  2449. cmd_len = 0;
  2450. while ((size_t)cmd_len < data_len
  2451. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  2452. ++cmd_len;
  2453. data_len -= cmd_len;
  2454. conn->incoming_cmd[cmd_len]='\0';
  2455. args = conn->incoming_cmd+cmd_len+1;
  2456. while (*args == ' ' || *args == '\t') {
  2457. ++args;
  2458. --data_len;
  2459. }
  2460. /* Quit is always valid. */
  2461. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  2462. connection_write_str_to_buf("250 closing connection\r\n", conn);
  2463. connection_mark_for_close(TO_CONN(conn));
  2464. return 0;
  2465. }
  2466. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2467. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  2468. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  2469. connection_mark_for_close(TO_CONN(conn));
  2470. return 0;
  2471. }
  2472. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  2473. if (handle_control_setconf(conn, data_len, args))
  2474. return -1;
  2475. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  2476. if (handle_control_resetconf(conn, data_len, args))
  2477. return -1;
  2478. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  2479. if (handle_control_getconf(conn, data_len, args))
  2480. return -1;
  2481. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  2482. if (handle_control_setevents(conn, data_len, args))
  2483. return -1;
  2484. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2485. if (handle_control_authenticate(conn, data_len, args))
  2486. return -1;
  2487. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  2488. if (handle_control_saveconf(conn, data_len, args))
  2489. return -1;
  2490. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  2491. if (handle_control_signal(conn, data_len, args))
  2492. return -1;
  2493. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  2494. if (handle_control_mapaddress(conn, data_len, args))
  2495. return -1;
  2496. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  2497. if (handle_control_getinfo(conn, data_len, args))
  2498. return -1;
  2499. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  2500. if (handle_control_extendcircuit(conn, data_len, args))
  2501. return -1;
  2502. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  2503. if (handle_control_setcircuitpurpose(conn, data_len, args))
  2504. return -1;
  2505. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  2506. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  2507. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  2508. if (handle_control_attachstream(conn, data_len, args))
  2509. return -1;
  2510. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  2511. if (handle_control_postdescriptor(conn, data_len, args))
  2512. return -1;
  2513. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  2514. if (handle_control_redirectstream(conn, data_len, args))
  2515. return -1;
  2516. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  2517. if (handle_control_closestream(conn, data_len, args))
  2518. return -1;
  2519. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  2520. if (handle_control_closecircuit(conn, data_len, args))
  2521. return -1;
  2522. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  2523. if (handle_control_usefeature(conn, data_len, args))
  2524. return -1;
  2525. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  2526. if (handle_control_resolve(conn, data_len, args))
  2527. return -1;
  2528. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  2529. if (handle_control_protocolinfo(conn, data_len, args))
  2530. return -1;
  2531. } else {
  2532. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  2533. conn->incoming_cmd);
  2534. }
  2535. conn->incoming_cmd_cur_len = 0;
  2536. goto again;
  2537. }
  2538. /** Convert a numeric reason for destroying a circuit into a string for a
  2539. * CIRCUIT event. */
  2540. static const char *
  2541. circuit_end_reason_to_string(int reason)
  2542. {
  2543. if (reason >= 0 && reason & END_CIRC_REASON_FLAG_REMOTE)
  2544. reason &= ~END_CIRC_REASON_FLAG_REMOTE;
  2545. switch (reason) {
  2546. case END_CIRC_AT_ORIGIN:
  2547. /* This shouldn't get passed here; it's a catch-all reason. */
  2548. return "ORIGIN";
  2549. case END_CIRC_REASON_NONE:
  2550. /* This shouldn't get passed here; it's a catch-all reason. */
  2551. return "NONE";
  2552. case END_CIRC_REASON_TORPROTOCOL:
  2553. return "TORPROTOCOL";
  2554. case END_CIRC_REASON_INTERNAL:
  2555. return "INTERNAL";
  2556. case END_CIRC_REASON_REQUESTED:
  2557. return "REQUESTED";
  2558. case END_CIRC_REASON_HIBERNATING:
  2559. return "HIBERNATING";
  2560. case END_CIRC_REASON_RESOURCELIMIT:
  2561. return "RESOURCELIMIT";
  2562. case END_CIRC_REASON_CONNECTFAILED:
  2563. return "CONNECTFAILED";
  2564. case END_CIRC_REASON_OR_IDENTITY:
  2565. return "OR_IDENTITY";
  2566. case END_CIRC_REASON_OR_CONN_CLOSED:
  2567. return "OR_CONN_CLOSED";
  2568. case END_CIRC_REASON_FINISHED:
  2569. return "FINISHED";
  2570. case END_CIRC_REASON_TIMEOUT:
  2571. return "TIMEOUT";
  2572. case END_CIRC_REASON_DESTROYED:
  2573. return "DESTROYED";
  2574. case END_CIRC_REASON_NOPATH:
  2575. return "NOPATH";
  2576. case END_CIRC_REASON_NOSUCHSERVICE:
  2577. return "NOSUCHSERVICE";
  2578. default:
  2579. log_warn(LD_BUG, "Unrecognized reason code %d", (int)reason);
  2580. return NULL;
  2581. }
  2582. }
  2583. /** Something has happened to circuit <b>circ</b>: tell any interested
  2584. * control connections. */
  2585. int
  2586. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  2587. int reason_code)
  2588. {
  2589. const char *status;
  2590. char reason_buf[64];
  2591. int providing_reason=0;
  2592. char *path=NULL;
  2593. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2594. return 0;
  2595. tor_assert(circ);
  2596. if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS))
  2597. path = circuit_list_path(circ,0);
  2598. switch (tp)
  2599. {
  2600. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2601. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2602. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2603. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2604. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2605. default:
  2606. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2607. return 0;
  2608. }
  2609. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  2610. const char *reason_str = circuit_end_reason_to_string(reason_code);
  2611. char *reason = NULL;
  2612. providing_reason=1;
  2613. if (!reason_str) {
  2614. reason = tor_malloc(16);
  2615. tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
  2616. reason_str = reason;
  2617. }
  2618. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  2619. tor_snprintf(reason_buf, sizeof(reason_buf),
  2620. "REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  2621. } else {
  2622. tor_snprintf(reason_buf, sizeof(reason_buf),
  2623. "REASON=%s", reason_str);
  2624. }
  2625. tor_free(reason);
  2626. }
  2627. if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS)) {
  2628. const char *sp = strlen(path) ? " " : "";
  2629. if (providing_reason)
  2630. send_control_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
  2631. "650 CIRC %lu %s%s%s@%s\r\n",
  2632. (unsigned long)circ->global_identifier,
  2633. status, sp, path, reason_buf);
  2634. else
  2635. send_control_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
  2636. "650 CIRC %lu %s%s%s\r\n",
  2637. (unsigned long)circ->global_identifier,
  2638. status, sp, path);
  2639. }
  2640. if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS)) {
  2641. char *vpath = circuit_list_path_for_controller(circ);
  2642. const char *sp = strlen(vpath) ? " " : "";
  2643. if (providing_reason)
  2644. send_control_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
  2645. "650 CIRC %lu %s%s%s@%s\r\n",
  2646. (unsigned long)circ->global_identifier,
  2647. status, sp, vpath, reason_buf);
  2648. else
  2649. send_control_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
  2650. "650 CIRC %lu %s%s%s\r\n",
  2651. (unsigned long)circ->global_identifier,
  2652. status, sp, vpath);
  2653. tor_free(vpath);
  2654. }
  2655. tor_free(path);
  2656. return 0;
  2657. }
  2658. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2659. * <b>buf</b>, determine the address:port combination requested on
  2660. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2661. * failure. */
  2662. static int
  2663. write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
  2664. {
  2665. char buf2[256];
  2666. if (conn->chosen_exit_name)
  2667. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2668. return -1;
  2669. if (tor_snprintf(buf, len, "%s%s%s:%d",
  2670. conn->socks_request->address,
  2671. conn->chosen_exit_name ? buf2 : "",
  2672. !conn->chosen_exit_name &&
  2673. connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
  2674. conn->socks_request->port)<0)
  2675. return -1;
  2676. return 0;
  2677. }
  2678. /** Convert the reason for ending a stream <b>reason</b> into the format used
  2679. * in STREAM events. Return NULL if the reason is unrecognized. */
  2680. static const char *
  2681. stream_end_reason_to_string(int reason)
  2682. {
  2683. reason &= END_STREAM_REASON_MASK;
  2684. switch (reason) {
  2685. case END_STREAM_REASON_MISC: return "MISC";
  2686. case END_STREAM_REASON_RESOLVEFAILED: return "RESOLVEFAILED";
  2687. case END_STREAM_REASON_CONNECTREFUSED: return "CONNECTREFUSED";
  2688. case END_STREAM_REASON_EXITPOLICY: return "EXITPOLICY";
  2689. case END_STREAM_REASON_DESTROY: return "DESTROY";
  2690. case END_STREAM_REASON_DONE: return "DONE";
  2691. case END_STREAM_REASON_TIMEOUT: return "TIMEOUT";
  2692. case END_STREAM_REASON_HIBERNATING: return "HIBERNATING";
  2693. case END_STREAM_REASON_INTERNAL: return "INTERNAL";
  2694. case END_STREAM_REASON_RESOURCELIMIT: return "RESOURCELIMIT";
  2695. case END_STREAM_REASON_CONNRESET: return "CONNRESET";
  2696. case END_STREAM_REASON_TORPROTOCOL: return "TORPROTOCOL";
  2697. case END_STREAM_REASON_NOTDIRECTORY: return "NOTDIRECTORY";
  2698. case END_STREAM_REASON_CANT_ATTACH: return "CANT_ATTACH";
  2699. case END_STREAM_REASON_NET_UNREACHABLE: return "NET_UNREACHABLE";
  2700. case END_STREAM_REASON_SOCKSPROTOCOL: return "SOCKS_PROTOCOL";
  2701. default: return NULL;
  2702. }
  2703. }
  2704. /** Something has happened to the stream associated with AP connection
  2705. * <b>conn</b>: tell any interested control connections. */
  2706. int
  2707. control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
  2708. int reason_code)
  2709. {
  2710. char reason_buf[64];
  2711. char addrport_buf[64];
  2712. const char *status;
  2713. circuit_t *circ;
  2714. origin_circuit_t *origin_circ = NULL;
  2715. char buf[256];
  2716. tor_assert(conn->socks_request);
  2717. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2718. return 0;
  2719. if (tp == STREAM_EVENT_CLOSED &&
  2720. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  2721. return 0;
  2722. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2723. reason_buf[0] = '\0';
  2724. switch (tp)
  2725. {
  2726. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2727. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2728. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2729. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2730. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2731. case STREAM_EVENT_NEW: status = "NEW"; break;
  2732. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2733. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2734. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  2735. default:
  2736. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2737. return 0;
  2738. }
  2739. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  2740. tp == STREAM_EVENT_CLOSED ||
  2741. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  2742. const char *reason_str = stream_end_reason_to_string(reason_code);
  2743. char *r = NULL;
  2744. if (!reason_str) {
  2745. r = tor_malloc(16);
  2746. tor_snprintf(r, 16, "UNKNOWN_%d", reason_code);
  2747. reason_str = r;
  2748. }
  2749. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  2750. tor_snprintf(reason_buf, sizeof(reason_buf),
  2751. "REASON=END REMOTE_REASON=%s", reason_str);
  2752. else
  2753. tor_snprintf(reason_buf, sizeof(reason_buf),
  2754. "REASON=%s", reason_str);
  2755. tor_free(r);
  2756. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  2757. switch (reason_code) {
  2758. case REMAP_STREAM_SOURCE_CACHE:
  2759. strlcpy(reason_buf, "SOURCE=CACHE", sizeof(reason_buf));
  2760. break;
  2761. case REMAP_STREAM_SOURCE_EXIT:
  2762. strlcpy(reason_buf, "SOURCE=EXIT", sizeof(reason_buf));
  2763. break;
  2764. default:
  2765. tor_snprintf(reason_buf, sizeof(reason_buf), "REASON=UNKNOWN_%d",
  2766. reason_code);
  2767. break;
  2768. }
  2769. }
  2770. if (tp == STREAM_EVENT_NEW) {
  2771. tor_snprintf(addrport_buf,sizeof(addrport_buf), "%sSOURCE_ADDR=%s:%d",
  2772. strlen(reason_buf) ? " " : "",
  2773. TO_CONN(conn)->address, TO_CONN(conn)->port );
  2774. } else {
  2775. addrport_buf[0] = '\0';
  2776. }
  2777. circ = circuit_get_by_edge_conn(conn);
  2778. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2779. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2780. send_control_event_extended(EVENT_STREAM_STATUS, ALL_NAMES,
  2781. "650 STREAM %lu %s %lu %s@%s%s\r\n",
  2782. (unsigned long)conn->global_identifier, status,
  2783. origin_circ?
  2784. (unsigned long)origin_circ->global_identifier : 0ul,
  2785. buf, reason_buf, addrport_buf);
  2786. /* XXX need to specify its intended exit, etc? */
  2787. return 0;
  2788. }
  2789. /** Figure out the best name for the target router of an OR connection
  2790. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  2791. * <b>name</b>. Use verbose names if <b>long_names</b> is set. */
  2792. static void
  2793. orconn_target_get_name(int long_names,
  2794. char *name, size_t len, or_connection_t *conn)
  2795. {
  2796. if (! long_names) {
  2797. if (conn->nickname)
  2798. strlcpy(name, conn->nickname, len);
  2799. else
  2800. tor_snprintf(name, len, "%s:%d",
  2801. conn->_base.address, conn->_base.port);
  2802. } else {
  2803. routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
  2804. if (ri) {
  2805. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  2806. router_get_verbose_nickname(name, ri);
  2807. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  2808. name[0] = '$';
  2809. base16_encode(name+1, len-1, conn->identity_digest,
  2810. DIGEST_LEN);
  2811. } else {
  2812. tor_snprintf(name, len, "%s:%d",
  2813. conn->_base.address, conn->_base.port);
  2814. }
  2815. }
  2816. }
  2817. /** Convert a TOR_TLS_* error code into an END_OR_CONN_* reason. */
  2818. int
  2819. control_tls_error_to_reason(int e)
  2820. {
  2821. switch (e) {
  2822. case TOR_TLS_ERROR_IO:
  2823. return END_OR_CONN_REASON_TLS_IO_ERROR;
  2824. case TOR_TLS_ERROR_CONNREFUSED:
  2825. return END_OR_CONN_REASON_TCP_REFUSED;
  2826. case TOR_TLS_ERROR_CONNRESET:
  2827. return END_OR_CONN_REASON_TLS_CONNRESET;
  2828. case TOR_TLS_ERROR_NO_ROUTE:
  2829. return END_OR_CONN_REASON_TLS_NO_ROUTE;
  2830. case TOR_TLS_ERROR_TIMEOUT:
  2831. return END_OR_CONN_REASON_TLS_TIMEOUT;
  2832. case TOR_TLS_WANTREAD:
  2833. case TOR_TLS_WANTWRITE:
  2834. case TOR_TLS_CLOSE:
  2835. case TOR_TLS_DONE:
  2836. return END_OR_CONN_REASON_DONE;
  2837. default:
  2838. return END_OR_CONN_REASON_TLS_MISC;
  2839. }
  2840. }
  2841. /** Convert the reason for ending an OR connection <b>r</b> into the format
  2842. * used in ORCONN events. Return NULL if the reason is unrecognized. */
  2843. static const char *
  2844. or_conn_end_reason_to_string(int r)
  2845. {
  2846. switch (r) {
  2847. case END_OR_CONN_REASON_DONE:
  2848. return "REASON=DONE";
  2849. case END_OR_CONN_REASON_TCP_REFUSED:
  2850. return "REASON=CONNECTREFUSED";
  2851. case END_OR_CONN_REASON_OR_IDENTITY:
  2852. return "REASON=IDENTITY";
  2853. case END_OR_CONN_REASON_TLS_CONNRESET:
  2854. return "REASON=CONNECTRESET";
  2855. case END_OR_CONN_REASON_TLS_TIMEOUT:
  2856. return "REASON=TIMEOUT";
  2857. case END_OR_CONN_REASON_TLS_NO_ROUTE:
  2858. return "REASON=NOROUTE";
  2859. case END_OR_CONN_REASON_TLS_IO_ERROR:
  2860. return "REASON=IOERROR";
  2861. case END_OR_CONN_REASON_TLS_MISC:
  2862. return "REASON=MISC";
  2863. case 0:
  2864. return "";
  2865. default:
  2866. log_warn(LD_BUG, "Unrecognized or_conn reason code %d", r);
  2867. return "REASON=BOGUS";
  2868. }
  2869. }
  2870. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  2871. * interested control connections. <b>tp</b> is the new status for the
  2872. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  2873. * may be the reason why.
  2874. */
  2875. int
  2876. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  2877. int reason)
  2878. {
  2879. int ncircs = 0;
  2880. const char *status;
  2881. char name[128];
  2882. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  2883. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  2884. return 0;
  2885. switch (tp)
  2886. {
  2887. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2888. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  2889. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  2890. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  2891. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  2892. default:
  2893. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2894. return 0;
  2895. }
  2896. ncircs = circuit_count_pending_on_or_conn(conn);
  2897. ncircs += conn->n_circuits;
  2898. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  2899. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
  2900. reason ? " " : "", ncircs);
  2901. }
  2902. if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS)) {
  2903. orconn_target_get_name(0, name, sizeof(name), conn);
  2904. send_control_event_extended(EVENT_OR_CONN_STATUS, SHORT_NAMES,
  2905. "650 ORCONN %s %s@%s%s\r\n",
  2906. name, status,
  2907. or_conn_end_reason_to_string(reason), ncircs_buf);
  2908. }
  2909. if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS)) {
  2910. orconn_target_get_name(1, name, sizeof(name), conn);
  2911. send_control_event_extended(EVENT_OR_CONN_STATUS, LONG_NAMES,
  2912. "650 ORCONN %s %s@%s%s\r\n",
  2913. name, status,
  2914. or_conn_end_reason_to_string(reason), ncircs_buf);
  2915. }
  2916. return 0;
  2917. }
  2918. /** A second or more has elapsed: tell any interested control
  2919. * connections how much bandwidth streams have used. */
  2920. int
  2921. control_event_stream_bandwidth_used(void)
  2922. {
  2923. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  2924. smartlist_t *conns = get_connection_array();
  2925. edge_connection_t *edge_conn;
  2926. SMARTLIST_FOREACH(conns, connection_t *, conn,
  2927. {
  2928. if (conn->type != CONN_TYPE_AP)
  2929. continue;
  2930. edge_conn = TO_EDGE_CONN(conn);
  2931. if (!edge_conn->n_read && !edge_conn->n_written)
  2932. continue;
  2933. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_NAMES,
  2934. "650 STREAM_BW %lu %lu %lu\r\n",
  2935. (unsigned long)edge_conn->global_identifier,
  2936. (unsigned long)edge_conn->n_read,
  2937. (unsigned long)edge_conn->n_written);
  2938. edge_conn->n_written = edge_conn->n_read = 0;
  2939. });
  2940. }
  2941. return 0;
  2942. }
  2943. /** A second or more has elapsed: tell any interested control
  2944. * connections how much bandwidth we used. */
  2945. int
  2946. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  2947. {
  2948. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  2949. send_control_event(EVENT_BANDWIDTH_USED, ALL_NAMES,
  2950. "650 BW %lu %lu\r\n",
  2951. (unsigned long)n_read,
  2952. (unsigned long)n_written);
  2953. }
  2954. return 0;
  2955. }
  2956. /** Called when we are sending a log message to the controllers: suspend
  2957. * sending further log messages to the controllers until we're done. Used by
  2958. * CONN_LOG_PROTECT. */
  2959. void
  2960. disable_control_logging(void)
  2961. {
  2962. ++disable_log_messages;
  2963. }
  2964. /** We're done sending a log message to the controllers: re-enable controller
  2965. * logging. Used by CONN_LOG_PROTECT. */
  2966. void
  2967. enable_control_logging(void)
  2968. {
  2969. if (--disable_log_messages < 0)
  2970. tor_assert(0);
  2971. }
  2972. /** We got a log message: tell any interested control connections. */
  2973. void
  2974. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  2975. {
  2976. int event;
  2977. if (disable_log_messages)
  2978. return;
  2979. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  2980. severity <= LOG_NOTICE) {
  2981. char *esc = esc_for_log(msg);
  2982. ++disable_log_messages;
  2983. control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
  2984. --disable_log_messages;
  2985. tor_free(esc);
  2986. }
  2987. event = log_severity_to_event(severity);
  2988. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  2989. char *b = NULL;
  2990. const char *s;
  2991. if (strchr(msg, '\n')) {
  2992. char *cp;
  2993. b = tor_strdup(msg);
  2994. for (cp = b; *cp; ++cp)
  2995. if (*cp == '\r' || *cp == '\n')
  2996. *cp = ' ';
  2997. }
  2998. switch (severity) {
  2999. case LOG_DEBUG: s = "DEBUG"; break;
  3000. case LOG_INFO: s = "INFO"; break;
  3001. case LOG_NOTICE: s = "NOTICE"; break;
  3002. case LOG_WARN: s = "WARN"; break;
  3003. case LOG_ERR: s = "ERR"; break;
  3004. default: s = "UnknownLogSeverity"; break;
  3005. }
  3006. ++disable_log_messages;
  3007. send_control_event(event, ALL_NAMES, "650 %s %s\r\n", s, b?b:msg);
  3008. --disable_log_messages;
  3009. tor_free(b);
  3010. }
  3011. }
  3012. /** Called whenever we receive new router descriptors: tell any
  3013. * interested control connections. <b>routers</b> is a list of
  3014. * routerinfo_t's.
  3015. */
  3016. int
  3017. control_event_descriptors_changed(smartlist_t *routers)
  3018. {
  3019. size_t len;
  3020. char *msg;
  3021. smartlist_t *identities = NULL;
  3022. char buf[HEX_DIGEST_LEN+1];
  3023. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  3024. return 0;
  3025. if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
  3026. identities = smartlist_create();
  3027. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  3028. {
  3029. base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
  3030. smartlist_add(identities, tor_strdup(buf));
  3031. });
  3032. }
  3033. if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
  3034. char *ids = smartlist_join_strings(identities, " ", 0, &len);
  3035. size_t ids_len = strlen(ids)+32;
  3036. msg = tor_malloc(ids_len);
  3037. tor_snprintf(msg, ids_len, "650 NEWDESC %s\r\n", ids);
  3038. send_control_event_string(EVENT_NEW_DESC, SHORT_NAMES|ALL_FORMATS, msg);
  3039. tor_free(ids);
  3040. tor_free(msg);
  3041. }
  3042. if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC)) {
  3043. smartlist_t *names = smartlist_create();
  3044. char *ids;
  3045. size_t names_len;
  3046. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  3047. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  3048. router_get_verbose_nickname(b, ri);
  3049. smartlist_add(names, b);
  3050. });
  3051. ids = smartlist_join_strings(names, " ", 0, &names_len);
  3052. names_len = strlen(ids)+32;
  3053. msg = tor_malloc(names_len);
  3054. tor_snprintf(msg, names_len, "650 NEWDESC %s\r\n", ids);
  3055. send_control_event_string(EVENT_NEW_DESC, LONG_NAMES|ALL_FORMATS, msg);
  3056. tor_free(ids);
  3057. tor_free(msg);
  3058. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  3059. smartlist_free(names);
  3060. }
  3061. if (identities) {
  3062. SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  3063. smartlist_free(identities);
  3064. }
  3065. return 0;
  3066. }
  3067. /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
  3068. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  3069. * <b>error</b> is non-NULL, it is an error code describing the failure
  3070. * mode of the mapping.
  3071. */
  3072. int
  3073. control_event_address_mapped(const char *from, const char *to, time_t expires,
  3074. const char *error)
  3075. {
  3076. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  3077. return 0;
  3078. if (expires < 3 || expires == TIME_MAX)
  3079. send_control_event_extended(EVENT_ADDRMAP, ALL_NAMES,
  3080. "650 ADDRMAP %s %s NEVER@%s\r\n", from, to,
  3081. error?error:"");
  3082. else {
  3083. char buf[ISO_TIME_LEN+1];
  3084. char buf2[ISO_TIME_LEN+1];
  3085. format_local_iso_time(buf,expires);
  3086. format_iso_time(buf2,expires);
  3087. send_control_event_extended(EVENT_ADDRMAP, ALL_NAMES,
  3088. "650 ADDRMAP %s %s \"%s\""
  3089. "@%s%sEXPIRES=\"%s\"\r\n",
  3090. from, to, buf,
  3091. error?error:"", error?" ":"",
  3092. buf2);
  3093. }
  3094. return 0;
  3095. }
  3096. /** The authoritative dirserver has received a new descriptor that
  3097. * has passed basic syntax checks and is properly self-signed.
  3098. *
  3099. * Notify any interested party of the new descriptor and what has
  3100. * been done with it, and also optionally give an explanation/reason. */
  3101. int
  3102. control_event_or_authdir_new_descriptor(const char *action,
  3103. const char *desc, size_t desclen,
  3104. const char *msg)
  3105. {
  3106. char firstline[1024];
  3107. char *buf;
  3108. int totallen;
  3109. char *esc = NULL;
  3110. size_t esclen;
  3111. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  3112. return 0;
  3113. tor_snprintf(firstline, sizeof(firstline),
  3114. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  3115. action,
  3116. msg ? msg : "");
  3117. /* Escape the server descriptor properly */
  3118. esclen = write_escaped_data(desc, desclen, &esc);
  3119. totallen = strlen(firstline) + esclen + 1;
  3120. buf = tor_malloc(totallen);
  3121. strlcpy(buf, firstline, totallen);
  3122. strlcpy(buf+strlen(firstline), esc, totallen);
  3123. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES|ALL_FORMATS,
  3124. buf);
  3125. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES|ALL_FORMATS,
  3126. "650 OK\r\n");
  3127. tor_free(esc);
  3128. tor_free(buf);
  3129. return 0;
  3130. }
  3131. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  3132. * an NS event to any controller that cares. */
  3133. int
  3134. control_event_networkstatus_changed(smartlist_t *statuses)
  3135. {
  3136. smartlist_t *strs;
  3137. char *s, *esc = NULL;
  3138. if (!EVENT_IS_INTERESTING(EVENT_NS) || !smartlist_len(statuses))
  3139. return 0;
  3140. strs = smartlist_create();
  3141. smartlist_add(strs, tor_strdup("650+NS\r\n"));
  3142. SMARTLIST_FOREACH(statuses, routerstatus_t *, rs,
  3143. {
  3144. s = networkstatus_getinfo_helper_single(rs);
  3145. if (!s) continue;
  3146. smartlist_add(strs, s);
  3147. });
  3148. s = smartlist_join_strings(strs, "", 0, NULL);
  3149. write_escaped_data(s, strlen(s), &esc);
  3150. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  3151. smartlist_free(strs);
  3152. tor_free(s);
  3153. send_control_event_string(EVENT_NS, ALL_NAMES|ALL_FORMATS, esc);
  3154. send_control_event_string(EVENT_NS, ALL_NAMES|ALL_FORMATS,
  3155. "650 OK\r\n");
  3156. tor_free(esc);
  3157. return 0;
  3158. }
  3159. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  3160. * to any countroller that cares. */
  3161. int
  3162. control_event_networkstatus_changed_single(routerstatus_t *rs)
  3163. {
  3164. smartlist_t *statuses;
  3165. int r;
  3166. if (!EVENT_IS_INTERESTING(EVENT_NS))
  3167. return 0;
  3168. statuses = smartlist_create();
  3169. smartlist_add(statuses, rs);
  3170. r = control_event_networkstatus_changed(statuses);
  3171. smartlist_free(statuses);
  3172. return r;
  3173. }
  3174. /** Our own router descriptor has changed; tell any controllers that care.
  3175. */
  3176. int
  3177. control_event_my_descriptor_changed(void)
  3178. {
  3179. send_control_event(EVENT_DESCCHANGED, ALL_NAMES, "650 DESCCHANGED\r\n");
  3180. return 0;
  3181. }
  3182. /** Helper: sends a status event where <b>type</b> is one of
  3183. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  3184. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  3185. * string corresponding to <b>args</b>. */
  3186. static int
  3187. control_event_status(int type, int severity, const char *format, va_list args)
  3188. {
  3189. char format_buf[160];
  3190. const char *status, *sev;
  3191. switch (type) {
  3192. case EVENT_STATUS_GENERAL:
  3193. status = "STATUS_GENERAL";
  3194. break;
  3195. case EVENT_STATUS_CLIENT:
  3196. status = "STATUS_CLIENT";
  3197. break;
  3198. case EVENT_STATUS_SERVER:
  3199. status = "STATUS_SEVER";
  3200. break;
  3201. default:
  3202. log_warn(LD_BUG, "Unrecognized status type %d", type);
  3203. return -1;
  3204. }
  3205. switch (severity) {
  3206. case LOG_NOTICE:
  3207. sev = "NOTICE";
  3208. break;
  3209. case LOG_WARN:
  3210. sev = "WARN";
  3211. break;
  3212. case LOG_ERR:
  3213. sev = "ERR";
  3214. break;
  3215. default:
  3216. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  3217. return -1;
  3218. }
  3219. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
  3220. status, sev, format)<0) {
  3221. log_warn(LD_BUG, "Format string too long.");
  3222. return -1;
  3223. }
  3224. send_control_event_impl(type, ALL_NAMES|ALL_FORMATS, 0, format_buf, args);
  3225. return 0;
  3226. }
  3227. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  3228. * by formatting the arguments using the printf-style <b>format</b>. */
  3229. int
  3230. control_event_general_status(int severity, const char *format, ...)
  3231. {
  3232. va_list ap;
  3233. int r;
  3234. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  3235. return 0;
  3236. va_start(ap, format);
  3237. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  3238. va_end(ap);
  3239. return r;
  3240. }
  3241. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  3242. * by formatting the arguments using the printf-style <b>format</b>. */
  3243. int
  3244. control_event_client_status(int severity, const char *format, ...)
  3245. {
  3246. va_list ap;
  3247. int r;
  3248. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  3249. return 0;
  3250. va_start(ap, format);
  3251. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  3252. va_end(ap);
  3253. return r;
  3254. }
  3255. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  3256. * by formatting the arguments using the printf-style <b>format</b>. */
  3257. int
  3258. control_event_server_status(int severity, const char *format, ...)
  3259. {
  3260. va_list ap;
  3261. int r;
  3262. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  3263. return 0;
  3264. va_start(ap, format);
  3265. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  3266. va_end(ap);
  3267. return r;
  3268. }
  3269. /** Called when the status of an entry guard with the given <b>nickname</b>
  3270. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  3271. * controllers that care. */
  3272. int
  3273. control_event_guard(const char *nickname, const char *digest,
  3274. const char *status)
  3275. {
  3276. char hbuf[HEX_DIGEST_LEN+1];
  3277. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  3278. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  3279. return 0;
  3280. if (EVENT_IS_INTERESTING1L(EVENT_GUARD)) {
  3281. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  3282. routerinfo_t *ri = router_get_by_digest(digest);
  3283. if (ri) {
  3284. router_get_verbose_nickname(buf, ri);
  3285. } else {
  3286. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  3287. }
  3288. send_control_event(EVENT_GUARD, LONG_NAMES,
  3289. "650 GUARD ENTRY %s %s\r\n", buf, status);
  3290. }
  3291. if (EVENT_IS_INTERESTING1S(EVENT_GUARD)) {
  3292. send_control_event(EVENT_GUARD, SHORT_NAMES,
  3293. "650 GUARD ENTRY $%s %s\r\n", hbuf, status);
  3294. }
  3295. return 0;
  3296. }
  3297. /** Helper: Return a newly allocated string containing a path to the
  3298. * file where we store our authentication cookie. */
  3299. static char *
  3300. get_cookie_file(void)
  3301. {
  3302. or_options_t *options = get_options();
  3303. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  3304. return tor_strdup(options->CookieAuthFile);
  3305. } else {
  3306. return get_datadir_fname("control_auth_cookie");
  3307. }
  3308. }
  3309. /** Choose a random authentication cookie and write it to disk.
  3310. * Anybody who can read the cookie from disk will be considered
  3311. * authorized to use the control connection. Return -1 if we can't
  3312. * write the file, or 0 on success. */
  3313. int
  3314. init_cookie_authentication(int enabled)
  3315. {
  3316. char *fname;
  3317. if (!enabled) {
  3318. authentication_cookie_is_set = 0;
  3319. return 0;
  3320. }
  3321. /* We don't want to generate a new cookie every time we call
  3322. * options_act(). One should be enough. */
  3323. if (authentication_cookie_is_set)
  3324. return 0; /* all set */
  3325. fname = get_cookie_file();
  3326. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  3327. authentication_cookie_is_set = 1;
  3328. if (write_bytes_to_file(fname, authentication_cookie,
  3329. AUTHENTICATION_COOKIE_LEN, 1)) {
  3330. log_warn(LD_FS,"Error writing authentication cookie to %s.",
  3331. escaped(fname));
  3332. tor_free(fname);
  3333. return -1;
  3334. }
  3335. #ifndef MS_WINDOWS
  3336. if (get_options()->CookieAuthFileGroupReadable) {
  3337. if (chmod(fname, 0640)) {
  3338. log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
  3339. }
  3340. }
  3341. #endif
  3342. tor_free(fname);
  3343. return 0;
  3344. }