control.c 107 KB

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