control.c 109 KB

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