control.c 128 KB

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