control.c 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946
  1. /* Copyright 2004-2006 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. **/
  10. #include "or.h"
  11. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V0 || \
  12. (s) == CONTROL_CONN_STATE_OPEN_V1)
  13. #define STATE_IS_V0(s) ((s) == CONTROL_CONN_STATE_NEEDAUTH_V0 || \
  14. (s) == CONTROL_CONN_STATE_OPEN_V0)
  15. /*
  16. * See control-spec.txt and control-spec-v0.txt for full details on
  17. * protocol(s).
  18. *
  19. */
  20. /* Recognized message type codes. */
  21. #define CONTROL0_CMD_ERROR 0x0000
  22. #define CONTROL0_CMD_DONE 0x0001
  23. #define CONTROL0_CMD_SETCONF 0x0002
  24. #define CONTROL0_CMD_GETCONF 0x0003
  25. #define CONTROL0_CMD_CONFVALUE 0x0004
  26. #define CONTROL0_CMD_SETEVENTS 0x0005
  27. #define CONTROL0_CMD_EVENT 0x0006
  28. #define CONTROL0_CMD_AUTHENTICATE 0x0007
  29. #define CONTROL0_CMD_SAVECONF 0x0008
  30. #define CONTROL0_CMD_SIGNAL 0x0009
  31. #define CONTROL0_CMD_MAPADDRESS 0x000A
  32. #define CONTROL0_CMD_GETINFO 0x000B
  33. #define CONTROL0_CMD_INFOVALUE 0x000C
  34. #define CONTROL0_CMD_EXTENDCIRCUIT 0x000D
  35. #define CONTROL0_CMD_ATTACHSTREAM 0x000E
  36. #define CONTROL0_CMD_POSTDESCRIPTOR 0x000F
  37. #define CONTROL0_CMD_FRAGMENTHEADER 0x0010
  38. #define CONTROL0_CMD_FRAGMENT 0x0011
  39. #define CONTROL0_CMD_REDIRECTSTREAM 0x0012
  40. #define CONTROL0_CMD_CLOSESTREAM 0x0013
  41. #define CONTROL0_CMD_CLOSECIRCUIT 0x0014
  42. #define _CONTROL0_CMD_MAX_RECOGNIZED 0x0014
  43. /* Recognized error codes. */
  44. #define ERR_UNSPECIFIED 0x0000
  45. #define ERR_INTERNAL 0x0001
  46. #define ERR_UNRECOGNIZED_TYPE 0x0002
  47. #define ERR_SYNTAX 0x0003
  48. #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
  49. #define ERR_INVALID_CONFIG_VALUE 0x0005
  50. #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
  51. #define ERR_UNAUTHORIZED 0x0007
  52. #define ERR_REJECTED_AUTHENTICATION 0x0008
  53. #define ERR_RESOURCE_EXHAUSETED 0x0009
  54. #define ERR_NO_STREAM 0x000A
  55. #define ERR_NO_CIRC 0x000B
  56. #define ERR_NO_ROUTER 0x000C
  57. /* Recognized asynchronous event types. */
  58. #define _EVENT_MIN 0x0001
  59. #define EVENT_CIRCUIT_STATUS 0x0001
  60. #define EVENT_STREAM_STATUS 0x0002
  61. #define EVENT_OR_CONN_STATUS 0x0003
  62. #define EVENT_BANDWIDTH_USED 0x0004
  63. #define EVENT_LOG_OBSOLETE 0x0005
  64. #define EVENT_NEW_DESC 0x0006
  65. #define EVENT_DEBUG_MSG 0x0007
  66. #define EVENT_INFO_MSG 0x0008
  67. #define EVENT_NOTICE_MSG 0x0009
  68. #define EVENT_WARN_MSG 0x000A
  69. #define EVENT_ERR_MSG 0x000B
  70. #define LAST_V0_EVENT 0x000B
  71. #define EVENT_ADDRMAP 0x000C
  72. #define EVENT_AUTHDIR_NEWDESCS 0x000D
  73. #define _EVENT_MAX 0x000D
  74. /** Array mapping from message type codes to human-readable message
  75. * type names. Used for compatibility with version 0 of the control
  76. * protocol. */
  77. static const char * CONTROL0_COMMANDS[_CONTROL0_CMD_MAX_RECOGNIZED+1] = {
  78. "error",
  79. "done",
  80. "setconf",
  81. "getconf",
  82. "confvalue",
  83. "setevents",
  84. "events",
  85. "authenticate",
  86. "saveconf",
  87. "signal",
  88. "mapaddress",
  89. "getinfo",
  90. "infovalue",
  91. "extendcircuit",
  92. "attachstream",
  93. "postdescriptor",
  94. "fragmentheader",
  95. "fragment",
  96. };
  97. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  98. * connection is interested in events of type <b>e</b>. We use this
  99. * so that we can decide to skip generating event messages that nobody
  100. * has interest in without having to walk over the global connection
  101. * list to find out.
  102. **/
  103. static uint32_t global_event_mask0 = 0;
  104. static uint32_t global_event_mask1 = 0;
  105. /** True iff we have disabled log messages from being sent to the controller */
  106. static int disable_log_messages = 0;
  107. /** Macro: true if any control connection is interested in events of type
  108. * <b>e</b>. */
  109. #define EVENT_IS_INTERESTING0(e) (global_event_mask0 & (1<<(e)))
  110. #define EVENT_IS_INTERESTING1(e) (global_event_mask1 & (1<<(e)))
  111. #define EVENT_IS_INTERESTING(e) \
  112. ((global_event_mask0|global_event_mask1) & (1<<(e)))
  113. /** If we're using cookie-type authentication, how long should our cookies be?
  114. */
  115. #define AUTHENTICATION_COOKIE_LEN 32
  116. /** If true, we've set authentication_cookie to a secret code and
  117. * stored it to disk. */
  118. static int authentication_cookie_is_set = 0;
  119. static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
  120. static void connection_printf_to_buf(connection_t *conn,
  121. const char *format, ...)
  122. CHECK_PRINTF(2,3);
  123. /*static*/ size_t write_escaped_data(const char *data, size_t len,
  124. int translate_newlines, char **out);
  125. /*static*/ size_t read_escaped_data(const char *data, size_t len,
  126. int translate_newlines, char **out);
  127. static void send_control0_message(connection_t *conn, uint16_t type,
  128. uint32_t len, const char *body);
  129. static void send_control_done(connection_t *conn);
  130. static void send_control_done2(connection_t *conn, const char *msg,
  131. size_t len);
  132. static void send_control0_error(connection_t *conn, uint16_t error,
  133. const char *message);
  134. static void send_control0_event(uint16_t event, uint32_t len,
  135. const char *body);
  136. static void send_control1_event(uint16_t event, const char *format, ...)
  137. CHECK_PRINTF(2,3);
  138. static int handle_control_setconf(connection_t *conn, uint32_t len,
  139. char *body);
  140. static int handle_control_resetconf(connection_t *conn, uint32_t len,
  141. char *body);
  142. static int handle_control_getconf(connection_t *conn, uint32_t len,
  143. const char *body);
  144. static int handle_control_setevents(connection_t *conn, uint32_t len,
  145. const char *body);
  146. static int handle_control_authenticate(connection_t *conn, uint32_t len,
  147. const char *body);
  148. static int handle_control_saveconf(connection_t *conn, uint32_t len,
  149. const char *body);
  150. static int handle_control_signal(connection_t *conn, uint32_t len,
  151. const char *body);
  152. static int handle_control_mapaddress(connection_t *conn, uint32_t len,
  153. const char *body);
  154. static int handle_control_getinfo(connection_t *conn, uint32_t len,
  155. const char *body);
  156. static int handle_control_extendcircuit(connection_t *conn, uint32_t len,
  157. const char *body);
  158. static int handle_control_setpurpose(connection_t *conn, int for_circuits,
  159. uint32_t len, const char *body);
  160. static int handle_control_attachstream(connection_t *conn, uint32_t len,
  161. const char *body);
  162. static int handle_control_postdescriptor(connection_t *conn, uint32_t len,
  163. const char *body);
  164. static int handle_control_redirectstream(connection_t *conn, uint32_t len,
  165. const char *body);
  166. static int handle_control_closestream(connection_t *conn, uint32_t len,
  167. const char *body);
  168. static int handle_control_closecircuit(connection_t *conn, uint32_t len,
  169. const char *body);
  170. static int write_stream_target_to_buf(connection_t *conn, char *buf,
  171. size_t len);
  172. /** Given a possibly invalid message type code <b>cmd</b>, return a
  173. * human-readable string equivalent. */
  174. static INLINE const char *
  175. control_cmd_to_string(uint16_t cmd)
  176. {
  177. return (cmd<=_CONTROL0_CMD_MAX_RECOGNIZED) ?
  178. CONTROL0_COMMANDS[cmd] : "Unknown";
  179. }
  180. /** Given a control event code for a message event, return the corresponding
  181. * log severity. */
  182. static INLINE int
  183. event_to_log_severity(int event)
  184. {
  185. switch (event) {
  186. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  187. case EVENT_INFO_MSG: return LOG_INFO;
  188. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  189. case EVENT_WARN_MSG: return LOG_WARN;
  190. case EVENT_ERR_MSG: return LOG_ERR;
  191. default: return -1;
  192. }
  193. }
  194. /** Given a log severity, return the corresponding control event code. */
  195. static INLINE int
  196. log_severity_to_event(int severity)
  197. {
  198. switch (severity) {
  199. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  200. case LOG_INFO: return EVENT_INFO_MSG;
  201. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  202. case LOG_WARN: return EVENT_WARN_MSG;
  203. case LOG_ERR: return EVENT_ERR_MSG;
  204. default: return -1;
  205. }
  206. }
  207. /** Set <b>global_event_maskX</b> (where X is 0 or 1) to the bitwise OR
  208. * of each live control connection's event_mask field. */
  209. void
  210. control_update_global_event_mask(void)
  211. {
  212. connection_t **conns;
  213. int n_conns, i;
  214. global_event_mask0 = 0;
  215. global_event_mask1 = 0;
  216. get_connection_array(&conns, &n_conns);
  217. for (i = 0; i < n_conns; ++i) {
  218. if (conns[i]->type == CONN_TYPE_CONTROL &&
  219. STATE_IS_OPEN(conns[i]->state)) {
  220. if (STATE_IS_V0(conns[i]->state))
  221. global_event_mask0 |= conns[i]->event_mask;
  222. else
  223. global_event_mask1 |= conns[i]->event_mask;
  224. }
  225. }
  226. control_adjust_event_log_severity();
  227. }
  228. /** Adjust the log severities that result in control_event_logmsg being called
  229. * to match the severity of log messages that any controllers are interested
  230. * in. */
  231. void
  232. control_adjust_event_log_severity(void)
  233. {
  234. int i;
  235. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  236. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  237. if (EVENT_IS_INTERESTING(i)) {
  238. min_log_event = i;
  239. break;
  240. }
  241. }
  242. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  243. if (EVENT_IS_INTERESTING(i)) {
  244. max_log_event = i;
  245. break;
  246. }
  247. }
  248. if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE)) {
  249. if (min_log_event > EVENT_NOTICE_MSG)
  250. min_log_event = EVENT_NOTICE_MSG;
  251. if (max_log_event < EVENT_ERR_MSG)
  252. max_log_event = EVENT_ERR_MSG;
  253. }
  254. change_callback_log_severity(event_to_log_severity(min_log_event),
  255. event_to_log_severity(max_log_event),
  256. control_event_logmsg);
  257. }
  258. /** Append a NUL-terminated string <b>s</b> to the end of
  259. * <b>conn</b>-\>outbuf
  260. */
  261. static INLINE void
  262. connection_write_str_to_buf(const char *s, connection_t *conn)
  263. {
  264. size_t len = strlen(s);
  265. connection_write_to_buf(s, len, conn);
  266. }
  267. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  268. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  269. * the contents of <b>data</b> into *<b>out</b>, adding a period
  270. * before any period that that appears at the start of a line, and
  271. * adding a period-CRLF line at the end. If <b>translate_newlines</b>
  272. * is true, replace all LF characters sequences with CRLF. Return the
  273. * number of bytes in *<b>out</b>.
  274. */
  275. /* static */ size_t
  276. write_escaped_data(const char *data, size_t len, int translate_newlines,
  277. char **out)
  278. {
  279. size_t sz_out = len+8;
  280. char *outp;
  281. const char *end;
  282. int i;
  283. int start_of_line;
  284. for (i=0; i<(int)len; ++i) {
  285. if (data[i]== '\n')
  286. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  287. }
  288. *out = outp = tor_malloc(sz_out+1);
  289. end = data+len;
  290. start_of_line = 1;
  291. while (data < end) {
  292. if (*data == '\n') {
  293. if (translate_newlines)
  294. *outp++ = '\r';
  295. start_of_line = 1;
  296. } else if (*data == '.') {
  297. if (start_of_line) {
  298. start_of_line = 0;
  299. *outp++ = '.';
  300. }
  301. } else {
  302. start_of_line = 0;
  303. }
  304. *outp++ = *data++;
  305. }
  306. if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
  307. *outp++ = '\r';
  308. *outp++ = '\n';
  309. }
  310. *outp++ = '.';
  311. *outp++ = '\r';
  312. *outp++ = '\n';
  313. *outp = '\0'; /* NUL-terminate just in case. */
  314. tor_assert((outp - *out) <= (int)sz_out);
  315. return outp - *out;
  316. }
  317. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  318. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  319. * the contents of <b>data</b> into *<b>out</b>, removing any period
  320. * that appears at the start of a line. If <b>translate_newlines</b>
  321. * is true, replace all CRLF sequences with LF. Return the number of
  322. * bytes in *<b>out</b>. */
  323. /*static*/ size_t
  324. read_escaped_data(const char *data, size_t len, int translate_newlines,
  325. char **out)
  326. {
  327. char *outp;
  328. const char *next;
  329. const char *end;
  330. *out = outp = tor_malloc(len+1);
  331. end = data+len;
  332. while (data < end) {
  333. if (*data == '.')
  334. ++data;
  335. if (translate_newlines)
  336. next = tor_memmem(data, end-data, "\r\n", 2);
  337. else
  338. next = tor_memmem(data, end-data, "\r\n.", 3);
  339. if (next) {
  340. memcpy(outp, data, next-data);
  341. outp += (next-data);
  342. data = next+2;
  343. } else {
  344. memcpy(outp, data, end-data);
  345. outp += (end-data);
  346. *outp = '\0';
  347. return outp - *out;
  348. }
  349. if (translate_newlines) {
  350. *outp++ = '\n';
  351. } else {
  352. *outp++ = '\r';
  353. *outp++ = '\n';
  354. }
  355. }
  356. *outp = '\0';
  357. return outp - *out;
  358. }
  359. /** Given a pointer to a string starting at <b>start</b> containing
  360. * <b>in_len_max</b> characters, decode a string beginning with a single
  361. * quote, containing any number of non-quote characters or characters escaped
  362. * with a backslash, and ending with a final quote. Place the resulting
  363. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  364. * store its length in <b>out_len</b>. On success, return a pointer to the
  365. * character immediately following the escaped string. On failure, return
  366. * NULL. */
  367. static const char *
  368. get_escaped_string(const char *start, size_t in_len_max,
  369. char **out, size_t *out_len)
  370. {
  371. const char *cp, *end;
  372. char *outp;
  373. size_t len=0;
  374. if (*start != '\"')
  375. return NULL;
  376. cp = start+1;
  377. end = start+in_len_max;
  378. /* Calculate length. */
  379. while (1) {
  380. if (cp >= end)
  381. return NULL;
  382. else if (*cp == '\\') {
  383. if (++cp == end)
  384. return NULL; /* Can't escape EOS. */
  385. ++cp;
  386. ++len;
  387. } else if (*cp == '\"') {
  388. break;
  389. } else {
  390. ++cp;
  391. ++len;
  392. }
  393. }
  394. end = cp;
  395. outp = *out = tor_malloc(len+1);
  396. *out_len = len;
  397. cp = start+1;
  398. while (cp < end) {
  399. if (*cp == '\\')
  400. ++cp;
  401. *outp++ = *cp++;
  402. }
  403. *outp = '\0';
  404. tor_assert((outp - *out) == (int)*out_len);
  405. return end+1;
  406. }
  407. /** Acts like sprintf, but writes its formatted string to the end of
  408. * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
  409. * but it will always end with a CRLF sequence.
  410. *
  411. * Currently the length of the message is limited to 1024 (including the
  412. * ending \n\r\0. */
  413. static void
  414. connection_printf_to_buf(connection_t *conn, const char *format, ...)
  415. {
  416. #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
  417. va_list ap;
  418. char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
  419. int r;
  420. size_t len;
  421. va_start(ap,format);
  422. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  423. va_end(ap);
  424. len = strlen(buf);
  425. if (memcmp("\r\n\0", buf+len-2, 3)) {
  426. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
  427. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
  428. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
  429. }
  430. connection_write_to_buf(buf, len, conn);
  431. }
  432. /** Send a message of type <b>type</b> containing <b>len</b> bytes
  433. * from <b>body</b> along the control connection <b>conn</b> */
  434. static void
  435. send_control0_message(connection_t *conn, uint16_t type, uint32_t len,
  436. const char *body)
  437. {
  438. char buf[10];
  439. tor_assert(conn);
  440. tor_assert(STATE_IS_V0(conn->state));
  441. tor_assert(len || !body);
  442. tor_assert(type <= _CONTROL0_CMD_MAX_RECOGNIZED);
  443. if (len < 65536) {
  444. set_uint16(buf, htons(len));
  445. set_uint16(buf+2, htons(type));
  446. connection_write_to_buf(buf, 4, conn);
  447. if (len)
  448. connection_write_to_buf(body, len, conn);
  449. } else {
  450. set_uint16(buf, htons(65535));
  451. set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENTHEADER));
  452. set_uint16(buf+4, htons(type));
  453. set_uint32(buf+6, htonl(len));
  454. connection_write_to_buf(buf, 10, conn);
  455. connection_write_to_buf(body, 65535-6, conn);
  456. len -= (65535-6);
  457. body += (65535-6);
  458. while (len) {
  459. size_t chunklen = (len<65535)?len:65535;
  460. set_uint16(buf, htons((uint16_t)chunklen));
  461. set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENT));
  462. connection_write_to_buf(buf, 4, conn);
  463. connection_write_to_buf(body, chunklen, conn);
  464. len -= chunklen;
  465. body += chunklen;
  466. }
  467. }
  468. }
  469. /** Send a "DONE" message down the control connection <b>conn</b> */
  470. static void
  471. send_control_done(connection_t *conn)
  472. {
  473. if (STATE_IS_V0(conn->state)) {
  474. send_control0_message(conn, CONTROL0_CMD_DONE, 0, NULL);
  475. } else {
  476. connection_write_str_to_buf("250 OK\r\n", conn);
  477. }
  478. }
  479. /** Send a "DONE" message down the v0 control message <b>conn</b>, with body
  480. * as provided in the <b>len</b> bytes at <b>msg</b>.
  481. */
  482. static void
  483. send_control_done2(connection_t *conn, const char *msg, size_t len)
  484. {
  485. if (len==0)
  486. len = strlen(msg);
  487. send_control0_message(conn, CONTROL0_CMD_DONE, len, msg);
  488. }
  489. /** Send an error message with error code <b>error</b> and body
  490. * <b>message</b> down the connection <b>conn</b> */
  491. static void
  492. send_control0_error(connection_t *conn, uint16_t error, const char *message)
  493. {
  494. char buf[256];
  495. size_t len;
  496. set_uint16(buf, htons(error));
  497. len = strlen(message);
  498. tor_assert(len < (256-2));
  499. memcpy(buf+2, message, len);
  500. send_control0_message(conn, CONTROL0_CMD_ERROR, (uint16_t)(len+2), buf);
  501. }
  502. /** Send an 'event' message of event type <b>event</b>, containing
  503. * <b>len</b> bytes in <b>body</b> to every control connection that
  504. * is interested in it. */
  505. static void
  506. send_control0_event(uint16_t event, uint32_t len, const char *body)
  507. {
  508. connection_t **conns;
  509. int n_conns, i;
  510. size_t buflen;
  511. char *buf;
  512. tor_assert(event >= _EVENT_MIN && event <= LAST_V0_EVENT);
  513. buflen = len + 2;
  514. buf = tor_malloc_zero(buflen);
  515. set_uint16(buf, htons(event));
  516. memcpy(buf+2, body, len);
  517. get_connection_array(&conns, &n_conns);
  518. for (i = 0; i < n_conns; ++i) {
  519. if (conns[i]->type == CONN_TYPE_CONTROL &&
  520. !conns[i]->marked_for_close &&
  521. conns[i]->state == CONTROL_CONN_STATE_OPEN_V0 &&
  522. conns[i]->event_mask & (1<<event)) {
  523. send_control0_message(conns[i], CONTROL0_CMD_EVENT, buflen, buf);
  524. if (event == EVENT_ERR_MSG)
  525. _connection_controller_force_write(conns[i]);
  526. }
  527. }
  528. tor_free(buf);
  529. }
  530. /* Send an event to all v1 controllers that are listening for code
  531. * <b>event</b>. The event's body is given by <b>msg</b>. */
  532. static void
  533. send_control1_event_string(uint16_t event, const char *msg)
  534. {
  535. connection_t **conns;
  536. int n_conns, i;
  537. tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
  538. get_connection_array(&conns, &n_conns);
  539. for (i = 0; i < n_conns; ++i) {
  540. if (conns[i]->type == CONN_TYPE_CONTROL &&
  541. !conns[i]->marked_for_close &&
  542. conns[i]->state == CONTROL_CONN_STATE_OPEN_V1 &&
  543. conns[i]->event_mask & (1<<event)) {
  544. connection_write_to_buf(msg, strlen(msg), conns[i]);
  545. if (event == EVENT_ERR_MSG)
  546. _connection_controller_force_write(conns[i]);
  547. }
  548. }
  549. }
  550. /* Send an event to all v1 controllers that are listening for code
  551. * <b>event</b>. The event's body is created by the printf-style format in
  552. * <b>format</b>, and other arguments as provided.
  553. *
  554. * Currently the length of the message is limited to 1024 (including the
  555. * ending \n\r\0. */
  556. static void
  557. send_control1_event(uint16_t event, const char *format, ...)
  558. {
  559. #define SEND_CONTROL1_EVENT_BUFFERSIZE 1024
  560. int r;
  561. char buf[SEND_CONTROL1_EVENT_BUFFERSIZE]; /* XXXX Length */
  562. va_list ap;
  563. size_t len;
  564. va_start(ap, format);
  565. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  566. va_end(ap);
  567. len = strlen(buf);
  568. if (memcmp("\r\n\0", buf+len-2, 3)) {
  569. /* if it is not properly terminated, do it now */
  570. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
  571. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
  572. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
  573. }
  574. send_control1_event_string(event, buf);
  575. }
  576. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  577. static circuit_t *
  578. get_circ(const char *id)
  579. {
  580. unsigned long n_id;
  581. int ok;
  582. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  583. if (!ok)
  584. return NULL;
  585. return circuit_get_by_global_id(n_id);
  586. }
  587. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  588. static connection_t *
  589. get_stream(const char *id)
  590. {
  591. unsigned long n_id;
  592. int ok;
  593. connection_t *conn;
  594. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  595. if (!ok)
  596. return NULL;
  597. conn = connection_get_by_global_id(n_id);
  598. if (!conn || conn->type != CONN_TYPE_AP)
  599. return NULL;
  600. return conn;
  601. }
  602. /** Helper for setconf and resetconf. Acts like setconf, except
  603. * it passes <b>use_defaults</b> on to options_trial_assign().
  604. */
  605. static int
  606. control_setconf_helper(connection_t *conn, uint32_t len, char *body,
  607. int use_defaults, int clear_first)
  608. {
  609. int r;
  610. config_line_t *lines=NULL;
  611. char *start = body;
  612. char *errstring = NULL;
  613. int v0 = STATE_IS_V0(conn->state);
  614. if (!v0) {
  615. char *config = tor_malloc(len+1);
  616. char *outp = config;
  617. while (*body) {
  618. char *eq = body;
  619. while (!TOR_ISSPACE(*eq) && *eq != '=')
  620. ++eq;
  621. memcpy(outp, body, eq-body);
  622. outp += (eq-body);
  623. *outp++ = ' ';
  624. body = eq+1;
  625. if (*eq == '=') {
  626. if (*body != '\"') {
  627. while (!TOR_ISSPACE(*body))
  628. *outp++ = *body++;
  629. } else {
  630. char *val;
  631. size_t val_len;
  632. body = (char*)get_escaped_string(body, (len - (body-start)),
  633. &val, &val_len);
  634. if (!body) {
  635. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  636. tor_free(config);
  637. return 0;
  638. }
  639. memcpy(outp, val, val_len);
  640. outp += val_len;
  641. tor_free(val);
  642. }
  643. }
  644. while (TOR_ISSPACE(*body))
  645. ++body;
  646. *outp++ = '\n';
  647. }
  648. *outp = '\0';
  649. if (config_get_lines(config, &lines) < 0) {
  650. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  651. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  652. conn);
  653. tor_free(config);
  654. return 0;
  655. }
  656. tor_free(config);
  657. } else {
  658. if (config_get_lines(body, &lines) < 0) {
  659. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  660. send_control0_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
  661. return 0;
  662. }
  663. }
  664. if ((r=options_trial_assign(lines, use_defaults,
  665. clear_first, &errstring)) < 0) {
  666. int v0_err;
  667. const char *msg;
  668. log_warn(LD_CONTROL,
  669. "Controller gave us config lines that didn't validate: %s.",
  670. errstring);
  671. switch (r) {
  672. case -1:
  673. v0_err = ERR_UNRECOGNIZED_CONFIG_KEY;
  674. msg = "552 Unrecognized option";
  675. break;
  676. case -2:
  677. v0_err = ERR_INVALID_CONFIG_VALUE;
  678. msg = "513 Unacceptable option value";
  679. break;
  680. case -3:
  681. v0_err = ERR_INVALID_CONFIG_VALUE;
  682. msg = "553 Transition not allowed";
  683. break;
  684. case -4:
  685. default:
  686. v0_err = ERR_INVALID_CONFIG_VALUE;
  687. msg = "553 Unable to set option";
  688. break;
  689. }
  690. if (v0) {
  691. send_control0_error(conn, v0_err, msg);
  692. } else {
  693. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  694. }
  695. config_free_lines(lines);
  696. tor_free(errstring);
  697. return 0;
  698. }
  699. config_free_lines(lines);
  700. send_control_done(conn);
  701. return 0;
  702. }
  703. /** Called when we receive a SETCONF message: parse the body and try
  704. * to update our configuration. Reply with a DONE or ERROR message. */
  705. static int
  706. handle_control_setconf(connection_t *conn, uint32_t len, char *body)
  707. {
  708. return control_setconf_helper(conn, len, body, 0, 1);
  709. }
  710. /** Called when we receive a RESETCONF message: parse the body and try
  711. * to update our configuration. Reply with a DONE or ERROR message. */
  712. static int
  713. handle_control_resetconf(connection_t *conn, uint32_t len, char *body)
  714. {
  715. int v0 = STATE_IS_V0(conn->state);
  716. tor_assert(!v0);
  717. return control_setconf_helper(conn, len, body, 1, 1);
  718. }
  719. /** Called when we receive a GETCONF message. Parse the request, and
  720. * reply with a CONFVALUE or an ERROR message */
  721. static int
  722. handle_control_getconf(connection_t *conn, uint32_t body_len, const char *body)
  723. {
  724. smartlist_t *questions = NULL;
  725. smartlist_t *answers = NULL;
  726. smartlist_t *unrecognized = NULL;
  727. char *msg = NULL;
  728. size_t msg_len;
  729. or_options_t *options = get_options();
  730. int v0 = STATE_IS_V0(conn->state);
  731. questions = smartlist_create();
  732. if (v0) {
  733. smartlist_split_string(questions, body, "\n",
  734. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  735. } else {
  736. smartlist_split_string(questions, body, " ",
  737. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  738. }
  739. answers = smartlist_create();
  740. unrecognized = smartlist_create();
  741. SMARTLIST_FOREACH(questions, char *, q,
  742. {
  743. if (!option_is_recognized(q)) {
  744. if (v0) {
  745. send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, q);
  746. goto done;
  747. } else {
  748. smartlist_add(unrecognized, q);
  749. }
  750. } else {
  751. config_line_t *answer = option_get_assignment(options,q);
  752. if (!v0 && !answer) {
  753. const char *name = option_get_canonical_name(q);
  754. size_t alen = strlen(name)+8;
  755. char *astr = tor_malloc(alen);
  756. tor_snprintf(astr, alen, "250-%s\r\n", name);
  757. smartlist_add(answers, astr);
  758. }
  759. while (answer) {
  760. config_line_t *next;
  761. size_t alen = strlen(answer->key)+strlen(answer->value)+8;
  762. char *astr = tor_malloc(alen);
  763. if (v0)
  764. tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
  765. else
  766. tor_snprintf(astr, alen, "250-%s=%s\r\n",
  767. answer->key, answer->value);
  768. smartlist_add(answers, astr);
  769. next = answer->next;
  770. tor_free(answer->key);
  771. tor_free(answer->value);
  772. tor_free(answer);
  773. answer = next;
  774. }
  775. }
  776. });
  777. if (v0) {
  778. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  779. send_control0_message(conn, CONTROL0_CMD_CONFVALUE,
  780. (uint16_t)msg_len, msg_len?msg:NULL);
  781. } else {
  782. int i,len;
  783. if ((len = smartlist_len(unrecognized))) {
  784. for (i=0; i < len-1; ++i)
  785. connection_printf_to_buf(conn,
  786. "552-Unrecognized configuration key \"%s\"\r\n",
  787. (char*)smartlist_get(unrecognized, i));
  788. connection_printf_to_buf(conn,
  789. "552 Unrecognized configuration key \"%s\"\r\n",
  790. (char*)smartlist_get(unrecognized, len-1));
  791. } else if ((len = smartlist_len(answers))) {
  792. char *tmp = smartlist_get(answers, len-1);
  793. tor_assert(strlen(tmp)>4);
  794. tmp[3] = ' ';
  795. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  796. connection_write_to_buf(msg, msg_len, conn);
  797. } else {
  798. connection_write_str_to_buf("250 OK\r\n", conn);
  799. }
  800. }
  801. done:
  802. if (answers) {
  803. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  804. smartlist_free(answers);
  805. }
  806. if (questions) {
  807. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  808. smartlist_free(questions);
  809. }
  810. smartlist_free(unrecognized);
  811. tor_free(msg);
  812. return 0;
  813. }
  814. /** Called when we get a SETEVENTS message: update conn->event_mask,
  815. * and reply with DONE or ERROR. */
  816. static int
  817. handle_control_setevents(connection_t *conn, uint32_t len, const char *body)
  818. {
  819. uint16_t event_code;
  820. uint32_t event_mask = 0;
  821. unsigned int extended = 0;
  822. if (STATE_IS_V0(conn->state)) {
  823. if (len % 2) {
  824. send_control0_error(conn, ERR_SYNTAX,
  825. "Odd number of bytes in setevents message");
  826. return 0;
  827. }
  828. for (; len; len -= 2, body += 2) {
  829. event_code = ntohs(get_uint16(body));
  830. if (event_code < _EVENT_MIN || event_code > LAST_V0_EVENT) {
  831. send_control0_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
  832. "Unrecognized event code");
  833. return 0;
  834. }
  835. event_mask |= (1 << event_code);
  836. }
  837. } else {
  838. smartlist_t *events = smartlist_create();
  839. smartlist_split_string(events, body, " ",
  840. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  841. SMARTLIST_FOREACH(events, const char *, ev,
  842. {
  843. if (!strcasecmp(ev, "EXTENDED")) {
  844. extended = 1;
  845. continue;
  846. } else if (!strcasecmp(ev, "CIRC"))
  847. event_code = EVENT_CIRCUIT_STATUS;
  848. else if (!strcasecmp(ev, "STREAM"))
  849. event_code = EVENT_STREAM_STATUS;
  850. else if (!strcasecmp(ev, "ORCONN"))
  851. event_code = EVENT_OR_CONN_STATUS;
  852. else if (!strcasecmp(ev, "BW"))
  853. event_code = EVENT_BANDWIDTH_USED;
  854. else if (!strcasecmp(ev, "DEBUG"))
  855. event_code = EVENT_DEBUG_MSG;
  856. else if (!strcasecmp(ev, "INFO"))
  857. event_code = EVENT_INFO_MSG;
  858. else if (!strcasecmp(ev, "NOTICE"))
  859. event_code = EVENT_NOTICE_MSG;
  860. else if (!strcasecmp(ev, "WARN"))
  861. event_code = EVENT_WARN_MSG;
  862. else if (!strcasecmp(ev, "ERR"))
  863. event_code = EVENT_ERR_MSG;
  864. else if (!strcasecmp(ev, "NEWDESC"))
  865. event_code = EVENT_NEW_DESC;
  866. else if (!strcasecmp(ev, "ADDRMAP"))
  867. event_code = EVENT_ADDRMAP;
  868. else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
  869. event_code = EVENT_AUTHDIR_NEWDESCS;
  870. else {
  871. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  872. ev);
  873. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  874. smartlist_free(events);
  875. return 0;
  876. }
  877. event_mask |= (1 << event_code);
  878. });
  879. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  880. smartlist_free(events);
  881. }
  882. conn->event_mask = event_mask;
  883. conn->control_events_are_extended = extended;
  884. control_update_global_event_mask();
  885. send_control_done(conn);
  886. return 0;
  887. }
  888. /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
  889. * <b>buf</b> is provided, store the hashed password in the first
  890. * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
  891. * success, -1 on failure.
  892. */
  893. int
  894. decode_hashed_password(char *buf, const char *hashed)
  895. {
  896. char decoded[64];
  897. if (!strcmpstart(hashed, "16:")) {
  898. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  899. || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
  900. return -1;
  901. }
  902. } else {
  903. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  904. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  905. return -1;
  906. }
  907. }
  908. if (buf)
  909. memcpy(buf, decoded, S2K_SPECIFIER_LEN+DIGEST_LEN);
  910. return 0;
  911. }
  912. /** Called when we get an AUTHENTICATE message. Check whether the
  913. * authentication is valid, and if so, update the connection's state to
  914. * OPEN. Reply with DONE or ERROR.
  915. */
  916. static int
  917. handle_control_authenticate(connection_t *conn, uint32_t len, const char *body)
  918. {
  919. int used_quoted_string = 0;
  920. or_options_t *options = get_options();
  921. char *password;
  922. size_t password_len;
  923. if (STATE_IS_V0(conn->state)) {
  924. password = (char*)body;
  925. password_len = len;
  926. } else {
  927. if (TOR_ISXDIGIT(body[0])) {
  928. int i = 0;
  929. while (TOR_ISXDIGIT(body[i]))
  930. ++i;
  931. password = tor_malloc(i/2 + 1);
  932. if (base16_decode(password, i/2+1, body, i)<0) {
  933. connection_write_str_to_buf(
  934. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  935. "password? If so, the standard requires you put it in double "
  936. "quotes.\r\n", conn);
  937. tor_free(password);
  938. return 0;
  939. }
  940. password_len = i/2;
  941. } else if (TOR_ISSPACE(body[0])) {
  942. password = tor_strdup("");
  943. password_len = 0;
  944. } else {
  945. if (!get_escaped_string(body, len, &password, &password_len)) {
  946. connection_write_str_to_buf("551 Invalid quoted string. You need "
  947. "to put the password in double quotes.\r\n", conn);
  948. return 0;
  949. }
  950. used_quoted_string = 1;
  951. }
  952. }
  953. if (options->CookieAuthentication) {
  954. if (len == AUTHENTICATION_COOKIE_LEN &&
  955. !memcmp(authentication_cookie, password, password_len)) {
  956. goto ok;
  957. }
  958. } else if (options->HashedControlPassword) {
  959. char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
  960. char received[DIGEST_LEN];
  961. if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
  962. log_warn(LD_CONTROL,
  963. "Couldn't decode HashedControlPassword: invalid base16");
  964. goto err;
  965. }
  966. secret_to_key(received,DIGEST_LEN,password,password_len,expected);
  967. if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  968. goto ok;
  969. goto err;
  970. } else {
  971. /* if Tor doesn't demand any stronger authentication, then
  972. * the controller can get in with anything. */
  973. goto ok;
  974. }
  975. err:
  976. if (STATE_IS_V0(conn->state))
  977. send_control0_error(conn,ERR_REJECTED_AUTHENTICATION,
  978. "Authentication failed");
  979. else {
  980. tor_free(password);
  981. if (used_quoted_string)
  982. connection_write_str_to_buf("515 Authentication failed\r\n", conn);
  983. else
  984. connection_write_str_to_buf(
  985. "515 Authentication failed. Maybe you tried a plain text password? "
  986. "If so, the standard requires you put it in double quotes.\r\n",conn);
  987. }
  988. return 0;
  989. ok:
  990. log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->s);
  991. send_control_done(conn);
  992. if (STATE_IS_V0(conn->state))
  993. conn->state = CONTROL_CONN_STATE_OPEN_V0;
  994. else {
  995. conn->state = CONTROL_CONN_STATE_OPEN_V1;
  996. tor_free(password);
  997. }
  998. return 0;
  999. }
  1000. /** Called when we get a SAVECONF command. Try to flush the current options to
  1001. * disk, and report success or failure. */
  1002. static int
  1003. handle_control_saveconf(connection_t *conn, uint32_t len,
  1004. const char *body)
  1005. {
  1006. if (options_save_current()<0) {
  1007. if (STATE_IS_V0(conn->state))
  1008. send_control0_error(conn, ERR_INTERNAL,
  1009. "Unable to write configuration to disk.");
  1010. else
  1011. connection_write_str_to_buf(
  1012. "551 Unable to write configuration to disk.\r\n", conn);
  1013. } else {
  1014. send_control_done(conn);
  1015. }
  1016. return 0;
  1017. }
  1018. /** Called when we get a SIGNAL command. React to the provided signal, and
  1019. * report success or failure. (If the signal results in a shutdown, success
  1020. * may not be reported.) */
  1021. static int
  1022. handle_control_signal(connection_t *conn, uint32_t len,
  1023. const char *body)
  1024. {
  1025. int sig;
  1026. if (STATE_IS_V0(conn->state)) {
  1027. if (len != 1) {
  1028. send_control0_error(conn, ERR_SYNTAX,
  1029. "Body of SIGNAL command too long or too short.");
  1030. return 0;
  1031. } else {
  1032. sig = (uint8_t)body[0];
  1033. }
  1034. } else {
  1035. int n = 0;
  1036. char *s;
  1037. while (body[n] && ! TOR_ISSPACE(body[n]))
  1038. ++n;
  1039. s = tor_strndup(body, n);
  1040. if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
  1041. sig = SIGHUP;
  1042. else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
  1043. sig = SIGINT;
  1044. else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
  1045. sig = SIGUSR1;
  1046. else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
  1047. sig = SIGUSR2;
  1048. else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
  1049. sig = SIGTERM;
  1050. else if (!strcasecmp(s, "NEWNYM"))
  1051. sig = SIGNEWNYM;
  1052. else {
  1053. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1054. s);
  1055. sig = -1;
  1056. }
  1057. tor_free(s);
  1058. if (sig<0)
  1059. return 0;
  1060. }
  1061. if (control_signal_act(sig) < 0) {
  1062. if (STATE_IS_V0(conn->state))
  1063. send_control0_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
  1064. else
  1065. connection_write_str_to_buf("551 Internal error acting on signal\r\n",
  1066. conn);
  1067. } else {
  1068. send_control_done(conn);
  1069. }
  1070. return 0;
  1071. }
  1072. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1073. * and report success or failrue. */
  1074. static int
  1075. handle_control_mapaddress(connection_t *conn, uint32_t len, const char *body)
  1076. {
  1077. smartlist_t *elts;
  1078. smartlist_t *lines;
  1079. smartlist_t *reply;
  1080. char *r;
  1081. size_t sz;
  1082. int v0 = STATE_IS_V0(conn->state);
  1083. lines = smartlist_create();
  1084. elts = smartlist_create();
  1085. reply = smartlist_create();
  1086. if (v0)
  1087. smartlist_split_string(lines, body, "\n",
  1088. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1089. else
  1090. smartlist_split_string(lines, body, " ",
  1091. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1092. SMARTLIST_FOREACH(lines, char *, line,
  1093. {
  1094. tor_strlower(line);
  1095. if (v0)
  1096. smartlist_split_string(elts, line, " ", 0, 2);
  1097. else
  1098. smartlist_split_string(elts, line, "=", 0, 2);
  1099. if (smartlist_len(elts) == 2) {
  1100. const char *from = smartlist_get(elts,0);
  1101. const char *to = smartlist_get(elts,1);
  1102. size_t anslen = strlen(line)+512;
  1103. char *ans = tor_malloc(anslen);
  1104. if (!is_plausible_address(from)) {
  1105. if (!v0) {
  1106. tor_snprintf(ans, anslen,
  1107. "512-syntax error: invalid address '%s'", from);
  1108. smartlist_add(reply, ans);
  1109. } else
  1110. tor_free(ans); /* don't respond if v0 */
  1111. log_warn(LD_CONTROL,
  1112. "Skipping invalid argument '%s' in MapAddress msg",
  1113. from);
  1114. } else if (!is_plausible_address(to)) {
  1115. if (!v0) {
  1116. tor_snprintf(ans, anslen,
  1117. "512-syntax error: invalid address '%s'", to);
  1118. smartlist_add(reply, ans);
  1119. } else
  1120. tor_free(ans); /* don't respond if v0 */
  1121. log_warn(LD_CONTROL,
  1122. "Skipping invalid argument '%s' in MapAddress msg", to);
  1123. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  1124. const char *address = addressmap_register_virtual_address(
  1125. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  1126. tor_strdup(to));
  1127. if (!address) {
  1128. if (!v0) {
  1129. tor_snprintf(ans, anslen,
  1130. "451-resource exhausted: skipping '%s'", line);
  1131. smartlist_add(reply, ans);
  1132. } else
  1133. tor_free(ans); /* don't respond if v0 */
  1134. log_warn(LD_CONTROL,
  1135. "Unable to allocate address for '%s' in MapAddress msg",
  1136. safe_str(line));
  1137. } else {
  1138. if (v0)
  1139. tor_snprintf(ans, anslen, "%s %s", address, to);
  1140. else
  1141. tor_snprintf(ans, anslen, "250-%s=%s", address, to);
  1142. smartlist_add(reply, ans);
  1143. }
  1144. } else {
  1145. addressmap_register(from, tor_strdup(to), 1);
  1146. if (v0)
  1147. tor_snprintf(ans, anslen, "%s", line);
  1148. else
  1149. tor_snprintf(ans, anslen, "250-%s", line);
  1150. smartlist_add(reply, ans);
  1151. }
  1152. } else {
  1153. if (!v0) {
  1154. size_t anslen = strlen(line)+256;
  1155. char *ans = tor_malloc(anslen);
  1156. tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
  1157. "not of expected form 'foo=bar'.", line);
  1158. smartlist_add(reply, ans);
  1159. }
  1160. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1161. "number of items.", safe_str(line));
  1162. }
  1163. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1164. smartlist_clear(elts);
  1165. });
  1166. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1167. smartlist_free(lines);
  1168. smartlist_free(elts);
  1169. if (v0) {
  1170. r = smartlist_join_strings(reply, "\n", 1, &sz);
  1171. send_control_done2(conn,r,sz);
  1172. } else {
  1173. if (smartlist_len(reply))
  1174. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1175. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1176. connection_write_to_buf(r, sz, conn);
  1177. }
  1178. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1179. smartlist_free(reply);
  1180. tor_free(r);
  1181. return 0;
  1182. }
  1183. /** Return a newly allocated string listing all valid GETINFO fields as
  1184. * required by GETINFO info/names. */
  1185. static char *
  1186. list_getinfo_options(void)
  1187. {
  1188. return tor_strdup(
  1189. "accounting/bytes Number of bytes read/written so far in interval.\n"
  1190. "accounting/bytes-left Number of bytes left to read/write in interval.\n"
  1191. "accounting/enabled Is accounting currently enabled?\n"
  1192. "accounting/hibernating Are we hibernating or awake?\n"
  1193. "accounting/interval-end Time when interval ends.\n"
  1194. "accounting/interval-start Time when interval starts.\n"
  1195. "accounting/interval-wake Time to wake up in this interval.\n"
  1196. "addr-mappings/all All current remapped addresses.\n"
  1197. "addr-mappings/cache Addresses remapped by DNS cache.\n"
  1198. "addr-mappings/configl Addresses remapped from configuration options.\n"
  1199. "addr-mappings/control Addresses remapped by a controller.\n"
  1200. "circuit-status Status of each current circuit.\n"
  1201. "config/names List of configuration options, types, and documentation.\n"
  1202. "desc/id/* Server descriptor by hex ID\n"
  1203. "desc/name/* Server descriptor by nickname.\n"
  1204. "desc/all-recent Latest server descriptor for every router\n"
  1205. "dir/server/* Fetch server descriptors -- see dir-spec.txt\n"
  1206. "entry-guards Which nodes will we use as entry guards?\n"
  1207. "info/names List of GETINFO options, types, and documentation.\n"
  1208. "network-status List of hex IDs, nicknames, server statuses.\n"
  1209. "orconn-status Status of each current OR connection.\n"
  1210. "stream-status Status of each current application stream.\n"
  1211. "version The current version of Tor.\n");
  1212. }
  1213. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1214. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1215. * Return 0 if success, or -1 if internal error. */
  1216. static int
  1217. handle_getinfo_helper(const char *question, char **answer)
  1218. {
  1219. *answer = NULL; /* unrecognized key by default */
  1220. if (!strcmp(question, "version")) {
  1221. *answer = tor_strdup(VERSION);
  1222. } else if (!strcmp(question, "config-file")) {
  1223. *answer = tor_strdup(get_torrc_fname());
  1224. } else if (!strcmpstart(question, "accounting/")) {
  1225. return accounting_getinfo_helper(question, answer);
  1226. } else if (!strcmpstart(question, "helper-nodes")) { /* deprecated */
  1227. return entry_guards_getinfo(question, answer);
  1228. } else if (!strcmpstart(question, "entry-guards")) {
  1229. return entry_guards_getinfo(question, answer);
  1230. } else if (!strcmpstart(question, "config/")) {
  1231. return config_getinfo_helper(question, answer);
  1232. } else if (!strcmp(question, "info/names")) {
  1233. *answer = list_getinfo_options();
  1234. } else if (!strcmpstart(question, "desc/id/")) {
  1235. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1236. if (ri) {
  1237. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1238. if (body)
  1239. *answer = tor_strdup(body);
  1240. }
  1241. } else if (!strcmpstart(question, "desc/name/")) {
  1242. routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1243. if (ri) {
  1244. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1245. if (body)
  1246. *answer = tor_strdup(body);
  1247. }
  1248. } else if (!strcmp(question, "desc/all-recent")) {
  1249. routerlist_t *routerlist = router_get_routerlist();
  1250. smartlist_t *sl = smartlist_create();
  1251. if (routerlist && routerlist->routers) {
  1252. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1253. {
  1254. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1255. if (body)
  1256. smartlist_add(sl, tor_strdup(body));
  1257. });
  1258. }
  1259. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1260. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1261. smartlist_free(sl);
  1262. } else if (!strcmpstart(question, "unregistered-servers-")) {
  1263. *answer = dirserver_getinfo_unregistered(question +
  1264. strlen("unregistered-servers-"));
  1265. } else if (!strcmp(question, "network-status")) {
  1266. routerlist_t *routerlist = router_get_routerlist();
  1267. if (!routerlist || !routerlist->routers ||
  1268. list_server_status(routerlist->routers, answer) < 0) {
  1269. return -1;
  1270. }
  1271. } else if (!strcmp(question, "circuit-status")) {
  1272. circuit_t *circ;
  1273. smartlist_t *status = smartlist_create();
  1274. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1275. char *s, *path;
  1276. size_t slen;
  1277. const char *state;
  1278. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1279. continue;
  1280. path = circuit_list_path(circ,0);
  1281. if (circ->state == CIRCUIT_STATE_OPEN)
  1282. state = "BUILT";
  1283. else if (strlen(path))
  1284. state = "EXTENDED";
  1285. else
  1286. state = "LAUNCHED";
  1287. slen = strlen(path)+strlen(state)+20;
  1288. s = tor_malloc(slen+1);
  1289. tor_snprintf(s, slen, "%lu %s %s",
  1290. (unsigned long)circ->global_identifier,
  1291. state, path);
  1292. smartlist_add(status, s);
  1293. tor_free(path);
  1294. }
  1295. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1296. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1297. smartlist_free(status);
  1298. } else if (!strcmp(question, "stream-status")) {
  1299. connection_t **conns;
  1300. int n_conns, i;
  1301. char buf[256];
  1302. smartlist_t *status = smartlist_create();
  1303. get_connection_array(&conns, &n_conns);
  1304. for (i=0; i < n_conns; ++i) {
  1305. const char *state;
  1306. char *s;
  1307. size_t slen;
  1308. circuit_t *circ;
  1309. if (conns[i]->type != CONN_TYPE_AP ||
  1310. conns[i]->marked_for_close ||
  1311. conns[i]->state == AP_CONN_STATE_SOCKS_WAIT)
  1312. continue;
  1313. switch (conns[i]->state)
  1314. {
  1315. case AP_CONN_STATE_CONTROLLER_WAIT:
  1316. case AP_CONN_STATE_CIRCUIT_WAIT:
  1317. if (conns[i]->socks_request &&
  1318. conns[i]->socks_request->command == SOCKS_COMMAND_RESOLVE)
  1319. state = "NEWRESOLVE";
  1320. else
  1321. state = "NEW";
  1322. break;
  1323. case AP_CONN_STATE_RENDDESC_WAIT:
  1324. case AP_CONN_STATE_CONNECT_WAIT:
  1325. state = "SENTCONNECT"; break;
  1326. case AP_CONN_STATE_RESOLVE_WAIT:
  1327. state = "SENTRESOLVE"; break;
  1328. case AP_CONN_STATE_OPEN:
  1329. state = "SUCCEEDED"; break;
  1330. default:
  1331. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1332. conns[i]->state);
  1333. continue;
  1334. }
  1335. circ = circuit_get_by_edge_conn(conns[i]);
  1336. write_stream_target_to_buf(conns[i], buf, sizeof(buf));
  1337. slen = strlen(buf)+strlen(state)+32;
  1338. s = tor_malloc(slen+1);
  1339. tor_snprintf(s, slen, "%lu %s %lu %s",
  1340. (unsigned long) conns[i]->global_identifier,state,
  1341. circ?(unsigned long)circ->global_identifier : 0ul,
  1342. buf);
  1343. smartlist_add(status, s);
  1344. }
  1345. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1346. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1347. smartlist_free(status);
  1348. } else if (!strcmp(question, "orconn-status")) {
  1349. connection_t **conns;
  1350. int n_conns, i;
  1351. smartlist_t *status = smartlist_create();
  1352. get_connection_array(&conns, &n_conns);
  1353. for (i=0; i < n_conns; ++i) {
  1354. const char *state;
  1355. char *s;
  1356. char name[128];
  1357. size_t slen;
  1358. connection_t *conn = conns[i];
  1359. if (conn->type != CONN_TYPE_OR || conn->marked_for_close)
  1360. continue;
  1361. if (conn->state == OR_CONN_STATE_OPEN)
  1362. state = "CONNECTED";
  1363. else if (conn->nickname)
  1364. state = "LAUNCHED";
  1365. else
  1366. state = "NEW";
  1367. if (conn->nickname)
  1368. strlcpy(name, conn->nickname, sizeof(name));
  1369. else
  1370. tor_snprintf(name, sizeof(name), "%s:%d",
  1371. conn->address, conn->port);
  1372. slen = strlen(name)+strlen(state)+2;
  1373. s = tor_malloc(slen+1);
  1374. tor_snprintf(s, slen, "%s %s", name, state);
  1375. smartlist_add(status, s);
  1376. }
  1377. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1378. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1379. smartlist_free(status);
  1380. } else if (!strcmpstart(question, "addr-mappings/")) {
  1381. time_t min_e, max_e;
  1382. smartlist_t *mappings;
  1383. if (!strcmp(question, "addr-mappings/all")) {
  1384. min_e = 0; max_e = TIME_MAX;
  1385. } else if (!strcmp(question, "addr-mappings/cache")) {
  1386. min_e = 2; max_e = TIME_MAX;
  1387. } else if (!strcmp(question, "addr-mappings/config")) {
  1388. min_e = 0; max_e = 0;
  1389. } else if (!strcmp(question, "addr-mappings/control")) {
  1390. min_e = 1; max_e = 1;
  1391. } else {
  1392. return 0;
  1393. }
  1394. mappings = smartlist_create();
  1395. addressmap_get_mappings(mappings, min_e, max_e);
  1396. *answer = smartlist_join_strings(mappings, "\n", 0, NULL);
  1397. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1398. smartlist_free(mappings);
  1399. } else if (!strcmp(question, "dir-usage")) {
  1400. *answer = directory_dump_request_log();
  1401. } else if (!strcmpstart(question, "dir/server/")) {
  1402. size_t answer_len = 0, url_len = strlen(question)+2;
  1403. char *url = tor_malloc(url_len);
  1404. int res;
  1405. smartlist_t *descs = smartlist_create();
  1406. const char *msg;
  1407. char *cp;
  1408. tor_snprintf(url, url_len, "/tor/%s", question+4);
  1409. res = dirserv_get_routerdescs(descs, url, &msg);
  1410. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1411. answer_len += sd->signed_descriptor_len);
  1412. cp = *answer = tor_malloc(answer_len+1);
  1413. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1414. {
  1415. memcpy(cp, signed_descriptor_get_body(sd),
  1416. sd->signed_descriptor_len);
  1417. cp += sd->signed_descriptor_len;
  1418. });
  1419. *cp = '\0';
  1420. tor_free(url);
  1421. smartlist_free(descs);
  1422. } else if (!strcmpstart(question, "dir/status/")) {
  1423. smartlist_t *status_list;
  1424. size_t len;
  1425. char *cp;
  1426. if (!get_options()->DirPort)
  1427. return 0;
  1428. status_list = smartlist_create();
  1429. if (!dirserv_get_networkstatus_v2(status_list,
  1430. question+strlen("dir/status/"))) {
  1431. smartlist_free(status_list);
  1432. return 0;
  1433. }
  1434. len = 0;
  1435. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1436. cp = *answer = tor_malloc(len+1);
  1437. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1438. memcpy(cp, d->dir, d->dir_len);
  1439. cp += d->dir_len;
  1440. });
  1441. *cp = '\0';
  1442. }
  1443. return 0;
  1444. }
  1445. /** Called when we receive a GETINFO command. Try to fetch all requested
  1446. * information, and reply with information or error message. */
  1447. static int
  1448. handle_control_getinfo(connection_t *conn, uint32_t len, const char *body)
  1449. {
  1450. smartlist_t *questions = NULL;
  1451. smartlist_t *answers = NULL;
  1452. smartlist_t *unrecognized = NULL;
  1453. char *msg = NULL, *ans = NULL;
  1454. size_t msg_len;
  1455. int v0 = STATE_IS_V0(conn->state);
  1456. questions = smartlist_create();
  1457. if (v0)
  1458. smartlist_split_string(questions, body, "\n",
  1459. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1460. else
  1461. smartlist_split_string(questions, body, " ",
  1462. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1463. answers = smartlist_create();
  1464. unrecognized = smartlist_create();
  1465. SMARTLIST_FOREACH(questions, const char *, q,
  1466. {
  1467. if (handle_getinfo_helper(q, &ans) < 0) {
  1468. if (v0)
  1469. send_control0_error(conn, ERR_INTERNAL, body);
  1470. else
  1471. connection_write_str_to_buf("551 Internal error\r\n", conn);
  1472. goto done;
  1473. }
  1474. if (!ans) {
  1475. if (v0) {
  1476. send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
  1477. goto done;
  1478. } else
  1479. smartlist_add(unrecognized, (char*)q);
  1480. } else {
  1481. smartlist_add(answers, tor_strdup(q));
  1482. smartlist_add(answers, ans);
  1483. }
  1484. });
  1485. if (smartlist_len(unrecognized)) {
  1486. int i;
  1487. tor_assert(!v0);
  1488. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1489. connection_printf_to_buf(conn,
  1490. "552-Unrecognized key \"%s\"\r\n",
  1491. (char*)smartlist_get(unrecognized, i));
  1492. connection_printf_to_buf(conn,
  1493. "552 Unrecognized key \"%s\"\r\n",
  1494. (char*)smartlist_get(unrecognized, i));
  1495. goto done;
  1496. }
  1497. if (v0) {
  1498. msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
  1499. tor_assert(msg_len > 0); /* it will at least be terminated */
  1500. send_control0_message(conn, CONTROL0_CMD_INFOVALUE,
  1501. msg_len, msg);
  1502. } else {
  1503. int i;
  1504. for (i = 0; i < smartlist_len(answers); i += 2) {
  1505. char *k = smartlist_get(answers, i);
  1506. char *v = smartlist_get(answers, i+1);
  1507. /*XXXX Not an adequate test! XXXX011 */
  1508. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1509. connection_printf_to_buf(conn, "250-%s=", k);
  1510. connection_write_str_to_buf(v, conn);
  1511. connection_write_str_to_buf("\r\n", conn);
  1512. } else {
  1513. char *esc = NULL;
  1514. size_t len;
  1515. len = write_escaped_data(v, strlen(v), 1, &esc);
  1516. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1517. connection_write_to_buf(esc, len, conn);
  1518. tor_free(esc);
  1519. }
  1520. }
  1521. connection_write_str_to_buf("250 OK\r\n", conn);
  1522. }
  1523. done:
  1524. if (answers) {
  1525. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1526. smartlist_free(answers);
  1527. }
  1528. if (questions) {
  1529. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1530. smartlist_free(questions);
  1531. }
  1532. smartlist_free(unrecognized);
  1533. tor_free(msg);
  1534. return 0;
  1535. }
  1536. /** If <b>string</b> contains a recognized purpose (for
  1537. * circuits if <b>for_circuits</b> is 1, else for routers),
  1538. * possibly prefaced with the string "purpose=", then assign it
  1539. * and return 0. Otherwise return -1. */
  1540. static int
  1541. get_purpose(char *string, int for_circuits, uint8_t *purpose)
  1542. {
  1543. if (!strcmpstart(string, "purpose="))
  1544. string += strlen("purpose=");
  1545. if (!strcmp(string, "general"))
  1546. *purpose = for_circuits ? CIRCUIT_PURPOSE_C_GENERAL :
  1547. ROUTER_PURPOSE_GENERAL;
  1548. else if (!strcmp(string, "controller"))
  1549. *purpose = for_circuits ? CIRCUIT_PURPOSE_CONTROLLER :
  1550. ROUTER_PURPOSE_GENERAL;
  1551. else { /* not a recognized purpose */
  1552. return -1;
  1553. }
  1554. return 0;
  1555. }
  1556. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  1557. * circuit, and report success or failure. */
  1558. static int
  1559. handle_control_extendcircuit(connection_t *conn, uint32_t len,
  1560. const char *body)
  1561. {
  1562. smartlist_t *router_nicknames=NULL, *routers=NULL;
  1563. uint32_t circ_id;
  1564. circuit_t *circ = NULL;
  1565. int zero_circ, v0;
  1566. char reply[4];
  1567. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1568. v0 = STATE_IS_V0(conn->state);
  1569. router_nicknames = smartlist_create();
  1570. if (v0) {
  1571. if (len<5) {
  1572. send_control0_error(conn, ERR_SYNTAX, "extendcircuit message too short");
  1573. goto done;
  1574. }
  1575. smartlist_split_string(router_nicknames, body+4, ",", 0, 0);
  1576. circ_id = ntohl(get_uint32(body));
  1577. if (!circ_id) {
  1578. /* start a new circuit */
  1579. zero_circ = 1;
  1580. } else {
  1581. circ = circuit_get_by_global_id(circ_id);
  1582. zero_circ = 0;
  1583. if (!circ) {
  1584. send_control0_error(conn, ERR_NO_CIRC,
  1585. "No circuit found with given ID");
  1586. goto done;
  1587. }
  1588. }
  1589. } else { /* v1 */
  1590. smartlist_t *args;
  1591. args = smartlist_create();
  1592. smartlist_split_string(args, body, " ",
  1593. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1594. if (smartlist_len(args)<2) {
  1595. connection_printf_to_buf(conn,
  1596. "512 Missing argument to EXTENDCIRCUIT\r\n");
  1597. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1598. smartlist_free(args);
  1599. goto done;
  1600. }
  1601. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  1602. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  1603. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1604. (char*)smartlist_get(args, 0));
  1605. }
  1606. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  1607. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1608. smartlist_free(args);
  1609. if (!zero_circ && !circ) {
  1610. goto done;
  1611. }
  1612. if (zero_circ && smartlist_len(args)>2) {
  1613. if (get_purpose(smartlist_get(args,2), 1, &intended_purpose) < 0) {
  1614. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  1615. (char *)smartlist_get(args,2));
  1616. goto done;
  1617. }
  1618. }
  1619. }
  1620. routers = smartlist_create();
  1621. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  1622. {
  1623. routerinfo_t *r = router_get_by_nickname(n, 1);
  1624. if (!r) {
  1625. if (v0)
  1626. send_control0_error(conn, ERR_NO_ROUTER, n);
  1627. else
  1628. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  1629. goto done;
  1630. }
  1631. smartlist_add(routers, r);
  1632. });
  1633. if (!smartlist_len(routers)) {
  1634. if (v0)
  1635. send_control0_error(conn, ERR_SYNTAX, "No router names provided");
  1636. else
  1637. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  1638. goto done;
  1639. }
  1640. if (zero_circ) {
  1641. /* start a new circuit */
  1642. circ = circuit_init(intended_purpose, 0, 0, 0);
  1643. }
  1644. /* now circ refers to something that is ready to be extended */
  1645. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1646. {
  1647. extend_info_t *info = extend_info_from_router(r);
  1648. circuit_append_new_exit(circ, info);
  1649. extend_info_free(info);
  1650. });
  1651. /* now that we've populated the cpath, start extending */
  1652. if (zero_circ) {
  1653. if (circuit_handle_first_hop(circ) < 0) {
  1654. circuit_mark_for_close(circ, END_CIRC_AT_ORIGIN);
  1655. if (v0)
  1656. send_control0_error(conn, ERR_INTERNAL, "couldn't start circuit");
  1657. else
  1658. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  1659. goto done;
  1660. }
  1661. } else {
  1662. if (circ->state == CIRCUIT_STATE_OPEN) {
  1663. circuit_set_state(circ, CIRCUIT_STATE_BUILDING);
  1664. if (circuit_send_next_onion_skin(circ) < 0) {
  1665. log_info(LD_CONTROL,
  1666. "send_next_onion_skin failed; circuit marked for closing.");
  1667. circuit_mark_for_close(circ, END_CIRC_AT_ORIGIN);
  1668. if (v0)
  1669. send_control0_error(conn, ERR_INTERNAL, "couldn't send onion skin");
  1670. else
  1671. connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
  1672. goto done;
  1673. }
  1674. }
  1675. }
  1676. if (v0) {
  1677. set_uint32(reply, htonl(circ->global_identifier));
  1678. send_control_done2(conn, reply, sizeof(reply));
  1679. } else {
  1680. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  1681. (unsigned long)circ->global_identifier);
  1682. }
  1683. done:
  1684. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  1685. smartlist_free(router_nicknames);
  1686. if (routers)
  1687. smartlist_free(routers);
  1688. return 0;
  1689. }
  1690. /** Called when we get a SETCIRCUITPURPOSE (if <b>for_circuits</b>
  1691. * is 1) or SETROUTERPURPOSE message. If we can find
  1692. * the circuit/router and it's a valid purpose, change it. */
  1693. static int
  1694. handle_control_setpurpose(connection_t *conn, int for_circuits,
  1695. uint32_t len, const char *body)
  1696. {
  1697. circuit_t *circ = NULL;
  1698. routerinfo_t *ri = NULL;
  1699. uint8_t new_purpose;
  1700. smartlist_t *args = smartlist_create();
  1701. smartlist_split_string(args, body, " ",
  1702. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1703. if (smartlist_len(args)<2) {
  1704. connection_printf_to_buf(conn,
  1705. "512 Missing argument to SET%sPURPOSE\r\n",
  1706. for_circuits ? "CIRCUIT" : "ROUTER");
  1707. goto done;
  1708. }
  1709. if (for_circuits) {
  1710. if (!(circ = get_circ(smartlist_get(args,0)))) {
  1711. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1712. (char*)smartlist_get(args, 0));
  1713. goto done;
  1714. }
  1715. } else {
  1716. if (!(ri = router_get_by_nickname(smartlist_get(args,0), 0))) {
  1717. connection_printf_to_buf(conn, "552 Unknown router \"%s\"\r\n",
  1718. (char*)smartlist_get(args, 0));
  1719. goto done;
  1720. }
  1721. }
  1722. if (get_purpose(smartlist_get(args,1), for_circuits, &new_purpose) < 0) {
  1723. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  1724. (char *)smartlist_get(args,1));
  1725. goto done;
  1726. }
  1727. if (for_circuits)
  1728. circ->purpose = new_purpose;
  1729. else
  1730. ri->purpose = new_purpose;
  1731. connection_write_str_to_buf("250 OK\r\n", conn);
  1732. done:
  1733. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1734. smartlist_free(args);
  1735. return 0;
  1736. }
  1737. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  1738. * stream, and report success or failure. */
  1739. static int
  1740. handle_control_attachstream(connection_t *conn, uint32_t len,
  1741. const char *body)
  1742. {
  1743. connection_t *ap_conn = NULL;
  1744. circuit_t *circ = NULL;
  1745. int zero_circ;
  1746. if (STATE_IS_V0(conn->state)) {
  1747. uint32_t conn_id;
  1748. uint32_t circ_id;
  1749. if (len < 8) {
  1750. send_control0_error(conn, ERR_SYNTAX, "attachstream message too short");
  1751. return 0;
  1752. }
  1753. conn_id = ntohl(get_uint32(body));
  1754. circ_id = ntohl(get_uint32(body+4));
  1755. zero_circ = circ_id == 0;
  1756. if (!(ap_conn = connection_get_by_global_id(conn_id))) {
  1757. send_control0_error(conn, ERR_NO_STREAM,
  1758. "No connection found with given ID");
  1759. return 0;
  1760. }
  1761. if (circ_id && !(circ = circuit_get_by_global_id(circ_id))) {
  1762. send_control0_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
  1763. return 0;
  1764. }
  1765. } else {
  1766. smartlist_t *args;
  1767. args = smartlist_create();
  1768. smartlist_split_string(args, body, " ",
  1769. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1770. if (smartlist_len(args)<2) {
  1771. connection_printf_to_buf(conn,
  1772. "512 Missing argument to ATTACHSTREAM\r\n");
  1773. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1774. smartlist_free(args);
  1775. return 0;
  1776. }
  1777. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  1778. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  1779. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1780. (char*)smartlist_get(args, 0));
  1781. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  1782. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1783. (char*)smartlist_get(args, 1));
  1784. }
  1785. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1786. smartlist_free(args);
  1787. if (!ap_conn || (!zero_circ && !circ))
  1788. return 0;
  1789. }
  1790. if (ap_conn->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  1791. ap_conn->state != AP_CONN_STATE_CONNECT_WAIT &&
  1792. ap_conn->state != AP_CONN_STATE_RESOLVE_WAIT) {
  1793. if (STATE_IS_V0(conn->state)) {
  1794. send_control0_error(conn, ERR_NO_STREAM,
  1795. "Connection is not managed by controller.");
  1796. } else {
  1797. connection_write_str_to_buf(
  1798. "555 Connection is not managed by controller.\r\n",
  1799. conn);
  1800. }
  1801. return 0;
  1802. }
  1803. /* Do we need to detach it first? */
  1804. if (ap_conn->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  1805. circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
  1806. connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  1807. /* Un-mark it as ending, since we're going to reuse it. */
  1808. ap_conn->has_sent_end = 0;
  1809. if (tmpcirc)
  1810. circuit_detach_stream(tmpcirc,ap_conn);
  1811. ap_conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
  1812. }
  1813. if (circ && circ->state != CIRCUIT_STATE_OPEN) {
  1814. if (STATE_IS_V0(conn->state))
  1815. send_control0_error(conn, ERR_INTERNAL,
  1816. "Refuse to attach stream to non-open circ.");
  1817. else
  1818. connection_write_str_to_buf(
  1819. "551 Can't attach stream to non-open circuit\r\n",
  1820. conn);
  1821. return 0;
  1822. }
  1823. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ) < 0) {
  1824. if (STATE_IS_V0(conn->state))
  1825. send_control0_error(conn, ERR_INTERNAL, "Unable to attach stream.");
  1826. else
  1827. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  1828. return 0;
  1829. }
  1830. send_control_done(conn);
  1831. return 0;
  1832. }
  1833. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  1834. * descriptor, and report success or failure. */
  1835. static int
  1836. handle_control_postdescriptor(connection_t *conn, uint32_t len,
  1837. const char *body)
  1838. {
  1839. char *desc;
  1840. int v0 = STATE_IS_V0(conn->state);
  1841. const char *msg=NULL;
  1842. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  1843. if (v0)
  1844. desc = (char*)body;
  1845. else {
  1846. char *cp = memchr(body, '\n', len);
  1847. smartlist_t *args = smartlist_create();
  1848. tor_assert(cp);
  1849. *cp++ = '\0';
  1850. smartlist_split_string(args, body, " ",
  1851. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1852. if (smartlist_len(args)) {
  1853. if (get_purpose(smartlist_get(args,0), 0, &purpose) < 0) {
  1854. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  1855. (char *)smartlist_get(args,0));
  1856. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1857. smartlist_free(args);
  1858. return 0;
  1859. }
  1860. }
  1861. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1862. smartlist_free(args);
  1863. read_escaped_data(cp, len-(cp-body), 1, &desc);
  1864. }
  1865. switch (router_load_single_router(desc, purpose, &msg)) {
  1866. case -1:
  1867. if (!msg) msg = "Could not parse descriptor";
  1868. if (v0)
  1869. send_control0_error(conn,ERR_SYNTAX,msg);
  1870. else
  1871. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  1872. break;
  1873. case 0:
  1874. if (!msg) msg = "Descriptor not added";
  1875. if (v0)
  1876. send_control_done2(conn,msg,0);
  1877. else
  1878. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  1879. break;
  1880. case 1:
  1881. send_control_done(conn);
  1882. break;
  1883. }
  1884. if (!v0)
  1885. tor_free(desc);
  1886. return 0;
  1887. }
  1888. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  1889. * address of the named AP stream, and report success or failure. */
  1890. static int
  1891. handle_control_redirectstream(connection_t *conn, uint32_t len,
  1892. const char *body)
  1893. {
  1894. connection_t *ap_conn = NULL;
  1895. uint32_t conn_id;
  1896. char *new_addr = NULL;
  1897. uint16_t new_port = 0;
  1898. if (STATE_IS_V0(conn->state)) {
  1899. if (len < 6) {
  1900. send_control0_error(conn, ERR_SYNTAX,
  1901. "redirectstream message too short");
  1902. return 0;
  1903. }
  1904. conn_id = ntohl(get_uint32(body));
  1905. if (!(ap_conn = connection_get_by_global_id(conn_id))
  1906. || ap_conn->state != CONN_TYPE_AP
  1907. || !ap_conn->socks_request) {
  1908. send_control0_error(conn, ERR_NO_STREAM,
  1909. "No AP connection found with given ID");
  1910. return 0;
  1911. }
  1912. new_addr = tor_strdup(body+4);
  1913. } else {
  1914. smartlist_t *args;
  1915. args = smartlist_create();
  1916. smartlist_split_string(args, body, " ",
  1917. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1918. if (smartlist_len(args) < 2)
  1919. connection_printf_to_buf(conn,
  1920. "512 Missing argument to REDIRECTSTREAM\r\n");
  1921. else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  1922. || !ap_conn->socks_request) {
  1923. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1924. (char*)smartlist_get(args, 0));
  1925. } else {
  1926. int ok;
  1927. if (smartlist_len(args) > 2) { /* they included a port too */
  1928. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  1929. 10, 1, 65535, &ok, NULL);
  1930. }
  1931. if (!ok) {
  1932. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  1933. (char*)smartlist_get(args, 2));
  1934. } else {
  1935. new_addr = tor_strdup(smartlist_get(args, 1));
  1936. }
  1937. }
  1938. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1939. smartlist_free(args);
  1940. if (!new_addr)
  1941. return 0;
  1942. }
  1943. strlcpy(ap_conn->socks_request->address, new_addr,
  1944. sizeof(ap_conn->socks_request->address));
  1945. if (new_port)
  1946. ap_conn->socks_request->port = new_port;
  1947. tor_free(new_addr);
  1948. send_control_done(conn);
  1949. return 0;
  1950. }
  1951. /** Called when we get a CLOSESTREAM command; try to close the named stream
  1952. * and report success or failure. */
  1953. static int
  1954. handle_control_closestream(connection_t *conn, uint32_t len,
  1955. const char *body)
  1956. {
  1957. connection_t *ap_conn=NULL;
  1958. uint8_t reason=0;
  1959. if (STATE_IS_V0(conn->state)) {
  1960. uint32_t conn_id;
  1961. if (len < 6) {
  1962. send_control0_error(conn, ERR_SYNTAX, "closestream message too short");
  1963. return 0;
  1964. }
  1965. conn_id = ntohl(get_uint32(body));
  1966. reason = *(uint8_t*)(body+4);
  1967. if (!(ap_conn = connection_get_by_global_id(conn_id))
  1968. || ap_conn->state != CONN_TYPE_AP
  1969. || !ap_conn->socks_request) {
  1970. send_control0_error(conn, ERR_NO_STREAM,
  1971. "No AP connection found with given ID");
  1972. return 0;
  1973. }
  1974. } else {
  1975. smartlist_t *args;
  1976. int ok;
  1977. args = smartlist_create();
  1978. smartlist_split_string(args, body, " ",
  1979. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1980. if (smartlist_len(args)<2)
  1981. connection_printf_to_buf(conn,
  1982. "512 Missing argument to CLOSESTREAM\r\n");
  1983. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  1984. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1985. (char*)smartlist_get(args, 0));
  1986. else {
  1987. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  1988. &ok, NULL);
  1989. if (!ok) {
  1990. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  1991. (char*)smartlist_get(args, 1));
  1992. ap_conn = NULL;
  1993. }
  1994. }
  1995. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1996. smartlist_free(args);
  1997. if (!ap_conn)
  1998. return 0;
  1999. }
  2000. connection_mark_unattached_ap(ap_conn, reason);
  2001. send_control_done(conn);
  2002. return 0;
  2003. }
  2004. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2005. * and report success or failure. */
  2006. static int
  2007. handle_control_closecircuit(connection_t *conn, uint32_t len,
  2008. const char *body)
  2009. {
  2010. circuit_t *circ = NULL;
  2011. int safe = 0;
  2012. if (STATE_IS_V0(conn->state)) {
  2013. uint32_t circ_id;
  2014. if (len < 5) {
  2015. send_control0_error(conn, ERR_SYNTAX, "closecircuit message too short");
  2016. return 0;
  2017. }
  2018. circ_id = ntohl(get_uint32(body));
  2019. safe = (*(uint8_t*)(body+4)) & 1;
  2020. if (!(circ = circuit_get_by_global_id(circ_id))) {
  2021. send_control0_error(conn, ERR_NO_CIRC,
  2022. "No circuit found with given ID");
  2023. return 0;
  2024. }
  2025. } else {
  2026. smartlist_t *args;
  2027. args = smartlist_create();
  2028. smartlist_split_string(args, body, " ",
  2029. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2030. if (smartlist_len(args)<1)
  2031. connection_printf_to_buf(conn,
  2032. "512 Missing argument to CLOSECIRCUIT\r\n");
  2033. else if (!(circ=get_circ(smartlist_get(args, 0))))
  2034. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2035. (char*)smartlist_get(args, 0));
  2036. else {
  2037. int i;
  2038. for (i=1; i < smartlist_len(args); ++i) {
  2039. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2040. safe = 1;
  2041. else
  2042. log_info(LD_CONTROL, "Skipping unknown option %s",
  2043. (char*)smartlist_get(args,i));
  2044. }
  2045. }
  2046. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2047. smartlist_free(args);
  2048. if (!circ)
  2049. return 0;
  2050. }
  2051. if (!safe || !circ->p_streams) {
  2052. circuit_mark_for_close(circ, END_CIRC_REASON_NONE);
  2053. }
  2054. send_control_done(conn);
  2055. return 0;
  2056. }
  2057. /** Called when we get a v0 FRAGMENTHEADER or FRAGMENT command; try to append
  2058. * the data to conn->incoming_cmd, setting conn->incoming_(type|len|cur_len)
  2059. * as appropriate. If the command is malformed, drop it and all pending
  2060. * fragments and report failure.
  2061. */
  2062. static int
  2063. handle_control_fragments(connection_t *conn, uint16_t command_type,
  2064. uint32_t body_len, char *body)
  2065. {
  2066. if (command_type == CONTROL0_CMD_FRAGMENTHEADER) {
  2067. if (conn->incoming_cmd) {
  2068. log_warn(LD_CONTROL, "Dropping incomplete fragmented command");
  2069. tor_free(conn->incoming_cmd);
  2070. }
  2071. if (body_len < 6) {
  2072. send_control0_error(conn, ERR_SYNTAX, "FRAGMENTHEADER too short.");
  2073. return 0;
  2074. }
  2075. conn->incoming_cmd_type = ntohs(get_uint16(body));
  2076. conn->incoming_cmd_len = ntohl(get_uint32(body+2));
  2077. conn->incoming_cmd_cur_len = 0;
  2078. conn->incoming_cmd = tor_malloc(conn->incoming_cmd_len);
  2079. body += 6;
  2080. body_len -= 6;
  2081. } else if (command_type == CONTROL0_CMD_FRAGMENT) {
  2082. if (!conn->incoming_cmd) {
  2083. send_control0_error(conn, ERR_SYNTAX, "Out-of-place FRAGMENT");
  2084. return 0;
  2085. }
  2086. } else {
  2087. tor_assert(0);
  2088. }
  2089. if (conn->incoming_cmd_cur_len + body_len > conn->incoming_cmd_len) {
  2090. tor_free(conn->incoming_cmd);
  2091. send_control0_error(conn, ERR_SYNTAX,
  2092. "Fragmented data exceeds declared length");
  2093. return 0;
  2094. }
  2095. memcpy(conn->incoming_cmd + conn->incoming_cmd_cur_len,
  2096. body, body_len);
  2097. conn->incoming_cmd_cur_len += body_len;
  2098. return 0;
  2099. }
  2100. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2101. int
  2102. connection_control_finished_flushing(connection_t *conn)
  2103. {
  2104. tor_assert(conn);
  2105. tor_assert(conn->type == CONN_TYPE_CONTROL);
  2106. connection_stop_writing(conn);
  2107. return 0;
  2108. }
  2109. /** Called when <b>conn</b> has gotten its socket closed. */
  2110. int
  2111. connection_control_reached_eof(connection_t *conn)
  2112. {
  2113. tor_assert(conn);
  2114. tor_assert(conn->type == CONN_TYPE_CONTROL);
  2115. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2116. connection_mark_for_close(conn);
  2117. return 0;
  2118. }
  2119. /** Called when data has arrived on a v1 control connection: Try to fetch
  2120. * commands from conn->inbuf, and execute them.
  2121. */
  2122. static int
  2123. connection_control_process_inbuf_v1(connection_t *conn)
  2124. {
  2125. size_t data_len;
  2126. int cmd_len;
  2127. char *args;
  2128. tor_assert(conn);
  2129. tor_assert(conn->type == CONN_TYPE_CONTROL);
  2130. tor_assert(conn->state == CONTROL_CONN_STATE_OPEN_V1 ||
  2131. conn->state == CONTROL_CONN_STATE_NEEDAUTH_V1);
  2132. if (!conn->incoming_cmd) {
  2133. conn->incoming_cmd = tor_malloc(1024);
  2134. conn->incoming_cmd_len = 1024;
  2135. conn->incoming_cmd_cur_len = 0;
  2136. }
  2137. again:
  2138. while (1) {
  2139. size_t last_idx;
  2140. int r;
  2141. /* First, fetch a line. */
  2142. do {
  2143. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2144. r = fetch_from_buf_line(conn->inbuf,
  2145. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2146. &data_len);
  2147. if (r == 0)
  2148. /* Line not all here yet. Wait. */
  2149. return 0;
  2150. else if (r == -1) {
  2151. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  2152. conn->incoming_cmd_len *= 2;
  2153. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  2154. conn->incoming_cmd_len);
  2155. }
  2156. } while (r != 1);
  2157. tor_assert(data_len);
  2158. last_idx = conn->incoming_cmd_cur_len;
  2159. conn->incoming_cmd_cur_len += data_len;
  2160. /* We have appended a line to incoming_cmd. Is the command done? */
  2161. if (last_idx == 0 && *conn->incoming_cmd != '+')
  2162. /* One line command, didn't start with '+'. */
  2163. break;
  2164. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  2165. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  2166. /* Just appended ".\r\n"; we're done. Remove it. */
  2167. conn->incoming_cmd_cur_len -= 3;
  2168. break;
  2169. }
  2170. /* Otherwise, read another line. */
  2171. }
  2172. data_len = conn->incoming_cmd_cur_len;
  2173. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  2174. * recognize it.
  2175. */
  2176. cmd_len = 0;
  2177. while ((size_t)cmd_len < data_len
  2178. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  2179. ++cmd_len;
  2180. data_len -= cmd_len;
  2181. conn->incoming_cmd[cmd_len]='\0';
  2182. args = conn->incoming_cmd+cmd_len+1;
  2183. while (*args == ' ' || *args == '\t') {
  2184. ++args;
  2185. --data_len;
  2186. }
  2187. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  2188. connection_write_str_to_buf("250 closing connection\r\n", conn);
  2189. connection_mark_for_close(conn);
  2190. return 0;
  2191. }
  2192. if (conn->state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
  2193. strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2194. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  2195. conn->incoming_cmd_cur_len = 0;
  2196. goto again;
  2197. }
  2198. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  2199. if (handle_control_setconf(conn, data_len, args))
  2200. return -1;
  2201. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  2202. if (handle_control_resetconf(conn, data_len, args))
  2203. return -1;
  2204. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  2205. if (handle_control_getconf(conn, data_len, args))
  2206. return -1;
  2207. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  2208. if (handle_control_setevents(conn, data_len, args))
  2209. return -1;
  2210. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2211. if (handle_control_authenticate(conn, data_len, args))
  2212. return -1;
  2213. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  2214. if (handle_control_saveconf(conn, data_len, args))
  2215. return -1;
  2216. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  2217. if (handle_control_signal(conn, data_len, args))
  2218. return -1;
  2219. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  2220. if (handle_control_mapaddress(conn, data_len, args))
  2221. return -1;
  2222. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  2223. if (handle_control_getinfo(conn, data_len, args))
  2224. return -1;
  2225. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  2226. if (handle_control_extendcircuit(conn, data_len, args))
  2227. return -1;
  2228. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  2229. if (handle_control_setpurpose(conn, 1, data_len, args))
  2230. return -1;
  2231. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  2232. if (handle_control_setpurpose(conn, 0, data_len, args))
  2233. return -1;
  2234. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  2235. if (handle_control_attachstream(conn, data_len, args))
  2236. return -1;
  2237. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  2238. if (handle_control_postdescriptor(conn, data_len, args))
  2239. return -1;
  2240. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  2241. if (handle_control_redirectstream(conn, data_len, args))
  2242. return -1;
  2243. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  2244. if (handle_control_closestream(conn, data_len, args))
  2245. return -1;
  2246. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  2247. if (handle_control_closecircuit(conn, data_len, args))
  2248. return -1;
  2249. } else {
  2250. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  2251. conn->incoming_cmd);
  2252. }
  2253. conn->incoming_cmd_cur_len = 0;
  2254. goto again;
  2255. }
  2256. /** Called when data has arrived on a v0 control connection: Try to fetch
  2257. * commands from conn->inbuf, and execute them.
  2258. */
  2259. static int
  2260. connection_control_process_inbuf_v0(connection_t *conn)
  2261. {
  2262. uint32_t body_len;
  2263. uint16_t command_type;
  2264. char *body=NULL;
  2265. again:
  2266. /* Try to suck a control message from the buffer. */
  2267. switch (fetch_from_buf_control0(conn->inbuf, &body_len, &command_type, &body,
  2268. conn->state == CONTROL_CONN_STATE_NEEDAUTH_V0))
  2269. {
  2270. case -2:
  2271. tor_free(body);
  2272. log_info(LD_CONTROL,
  2273. "Detected v1 control protocol on connection (fd %d)",
  2274. conn->s);
  2275. conn->state = CONTROL_CONN_STATE_NEEDAUTH_V1;
  2276. return connection_control_process_inbuf_v1(conn);
  2277. case -1:
  2278. tor_free(body);
  2279. log_warn(LD_CONTROL, "Error in control command. Failing.");
  2280. return -1;
  2281. case 0:
  2282. /* Control command not all here yet. Wait. */
  2283. return 0;
  2284. case 1:
  2285. /* We got a command. Process it. */
  2286. break;
  2287. default:
  2288. tor_assert(0);
  2289. }
  2290. /* We got a command. If we need authentication, only authentication
  2291. * commands will be considered. */
  2292. if (conn->state == CONTROL_CONN_STATE_NEEDAUTH_V0 &&
  2293. command_type != CONTROL0_CMD_AUTHENTICATE) {
  2294. log_info(LD_CONTROL, "Rejecting '%s' command; authentication needed.",
  2295. control_cmd_to_string(command_type));
  2296. send_control0_error(conn, ERR_UNAUTHORIZED, "Authentication required");
  2297. tor_free(body);
  2298. goto again;
  2299. }
  2300. if (command_type == CONTROL0_CMD_FRAGMENTHEADER ||
  2301. command_type == CONTROL0_CMD_FRAGMENT) {
  2302. if (handle_control_fragments(conn, command_type, body_len, body))
  2303. return -1;
  2304. tor_free(body);
  2305. if (conn->incoming_cmd_cur_len != conn->incoming_cmd_len)
  2306. goto again;
  2307. command_type = conn->incoming_cmd_type;
  2308. body_len = conn->incoming_cmd_len;
  2309. body = conn->incoming_cmd;
  2310. conn->incoming_cmd = NULL;
  2311. } else if (conn->incoming_cmd) {
  2312. log_warn(LD_CONTROL, "Dropping incomplete fragmented command");
  2313. tor_free(conn->incoming_cmd);
  2314. }
  2315. /* Okay, we're willing to process the command. */
  2316. switch (command_type)
  2317. {
  2318. case CONTROL0_CMD_SETCONF:
  2319. if (handle_control_setconf(conn, body_len, body))
  2320. return -1;
  2321. break;
  2322. case CONTROL0_CMD_GETCONF:
  2323. if (handle_control_getconf(conn, body_len, body))
  2324. return -1;
  2325. break;
  2326. case CONTROL0_CMD_SETEVENTS:
  2327. if (handle_control_setevents(conn, body_len, body))
  2328. return -1;
  2329. break;
  2330. case CONTROL0_CMD_AUTHENTICATE:
  2331. if (handle_control_authenticate(conn, body_len, body))
  2332. return -1;
  2333. break;
  2334. case CONTROL0_CMD_SAVECONF:
  2335. if (handle_control_saveconf(conn, body_len, body))
  2336. return -1;
  2337. break;
  2338. case CONTROL0_CMD_SIGNAL:
  2339. if (handle_control_signal(conn, body_len, body))
  2340. return -1;
  2341. break;
  2342. case CONTROL0_CMD_MAPADDRESS:
  2343. if (handle_control_mapaddress(conn, body_len, body))
  2344. return -1;
  2345. break;
  2346. case CONTROL0_CMD_GETINFO:
  2347. if (handle_control_getinfo(conn, body_len, body))
  2348. return -1;
  2349. break;
  2350. case CONTROL0_CMD_EXTENDCIRCUIT:
  2351. if (handle_control_extendcircuit(conn, body_len, body))
  2352. return -1;
  2353. break;
  2354. case CONTROL0_CMD_ATTACHSTREAM:
  2355. if (handle_control_attachstream(conn, body_len, body))
  2356. return -1;
  2357. break;
  2358. case CONTROL0_CMD_POSTDESCRIPTOR:
  2359. if (handle_control_postdescriptor(conn, body_len, body))
  2360. return -1;
  2361. break;
  2362. case CONTROL0_CMD_REDIRECTSTREAM:
  2363. if (handle_control_redirectstream(conn, body_len, body))
  2364. return -1;
  2365. break;
  2366. case CONTROL0_CMD_CLOSESTREAM:
  2367. if (handle_control_closestream(conn, body_len, body))
  2368. return -1;
  2369. break;
  2370. case CONTROL0_CMD_CLOSECIRCUIT:
  2371. if (handle_control_closecircuit(conn, body_len, body))
  2372. return -1;
  2373. break;
  2374. case CONTROL0_CMD_ERROR:
  2375. case CONTROL0_CMD_DONE:
  2376. case CONTROL0_CMD_CONFVALUE:
  2377. case CONTROL0_CMD_EVENT:
  2378. case CONTROL0_CMD_INFOVALUE:
  2379. log_warn(LD_CONTROL, "Received client-only '%s' command; ignoring.",
  2380. control_cmd_to_string(command_type));
  2381. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2382. "Command type only valid from server to tor client");
  2383. break;
  2384. case CONTROL0_CMD_FRAGMENTHEADER:
  2385. case CONTROL0_CMD_FRAGMENT:
  2386. log_warn(LD_CONTROL,
  2387. "Recieved command fragment out of order; ignoring.");
  2388. send_control0_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
  2389. default:
  2390. log_warn(LD_CONTROL, "Received unrecognized command type %d; ignoring.",
  2391. (int)command_type);
  2392. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2393. "Unrecognized command type");
  2394. break;
  2395. }
  2396. tor_free(body);
  2397. goto again; /* There might be more data. */
  2398. }
  2399. /** Called when <b>conn</b> has received more bytes on its inbuf.
  2400. */
  2401. int
  2402. connection_control_process_inbuf(connection_t *conn)
  2403. {
  2404. tor_assert(conn);
  2405. tor_assert(conn->type == CONN_TYPE_CONTROL);
  2406. if (STATE_IS_V0(conn->state))
  2407. return connection_control_process_inbuf_v0(conn);
  2408. else
  2409. return connection_control_process_inbuf_v1(conn);
  2410. }
  2411. /** Something has happened to circuit <b>circ</b>: tell any interested
  2412. * control connections. */
  2413. int
  2414. control_event_circuit_status(circuit_t *circ, circuit_status_event_t tp)
  2415. {
  2416. char *path, *msg;
  2417. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2418. return 0;
  2419. tor_assert(circ);
  2420. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  2421. path = circuit_list_path(circ,0);
  2422. if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS)) {
  2423. size_t path_len = strlen(path);
  2424. msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
  2425. msg[0] = (uint8_t) tp;
  2426. set_uint32(msg+1, htonl(circ->global_identifier));
  2427. strlcpy(msg+5,path,path_len+1);
  2428. send_control0_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
  2429. tor_free(msg);
  2430. }
  2431. if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS)) {
  2432. const char *status;
  2433. switch (tp)
  2434. {
  2435. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2436. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2437. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2438. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2439. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2440. default:
  2441. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2442. return 0;
  2443. }
  2444. send_control1_event(EVENT_CIRCUIT_STATUS,
  2445. "650 CIRC %lu %s %s\r\n",
  2446. (unsigned long)circ->global_identifier,
  2447. status, path);
  2448. }
  2449. tor_free(path);
  2450. return 0;
  2451. }
  2452. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2453. * <b>buf</b>, determine the address:port combination requested on
  2454. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2455. * failure. */
  2456. static int
  2457. write_stream_target_to_buf(connection_t *conn, char *buf, size_t len)
  2458. {
  2459. char buf2[256];
  2460. if (conn->chosen_exit_name)
  2461. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2462. return -1;
  2463. if (tor_snprintf(buf, len, "%s%s%s:%d",
  2464. conn->socks_request->address,
  2465. conn->chosen_exit_name ? buf2 : "",
  2466. !conn->chosen_exit_name &&
  2467. connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
  2468. conn->socks_request->port)<0)
  2469. return -1;
  2470. return 0;
  2471. }
  2472. /** Something has happened to the stream associated with AP connection
  2473. * <b>conn</b>: tell any interested control connections. */
  2474. int
  2475. control_event_stream_status(connection_t *conn, stream_status_event_t tp)
  2476. {
  2477. char *msg;
  2478. size_t len;
  2479. char buf[256];
  2480. tor_assert(conn->type == CONN_TYPE_AP);
  2481. tor_assert(conn->socks_request);
  2482. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2483. return 0;
  2484. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2485. if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS)) {
  2486. len = strlen(buf);
  2487. msg = tor_malloc(5+len+1);
  2488. msg[0] = (uint8_t) tp;
  2489. set_uint32(msg+1, htonl(conn->global_identifier));
  2490. strlcpy(msg+5, buf, len+1);
  2491. send_control0_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
  2492. tor_free(msg);
  2493. }
  2494. if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS)) {
  2495. const char *status;
  2496. circuit_t *circ;
  2497. switch (tp)
  2498. {
  2499. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2500. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2501. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2502. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2503. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2504. case STREAM_EVENT_NEW: status = "NEW"; break;
  2505. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2506. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2507. default:
  2508. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2509. return 0;
  2510. }
  2511. circ = circuit_get_by_edge_conn(conn);
  2512. send_control1_event(EVENT_STREAM_STATUS,
  2513. "650 STREAM %lu %s %lu %s\r\n",
  2514. (unsigned long)conn->global_identifier, status,
  2515. circ?(unsigned long)circ->global_identifier : 0ul,
  2516. buf);
  2517. /* XXX need to specify its intended exit, etc? */
  2518. }
  2519. return 0;
  2520. }
  2521. /** Something has happened to the OR connection <b>conn</b>: tell any
  2522. * interested control connections. */
  2523. int
  2524. control_event_or_conn_status(connection_t *conn,or_conn_status_event_t tp)
  2525. {
  2526. char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
  2527. size_t len;
  2528. tor_assert(conn->type == CONN_TYPE_OR);
  2529. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  2530. return 0;
  2531. if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS)) {
  2532. buf[0] = (uint8_t)tp;
  2533. strlcpy(buf+1,conn->nickname ? conn->nickname : "",sizeof(buf)-1);
  2534. len = strlen(buf+1);
  2535. send_control0_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
  2536. }
  2537. if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS)) {
  2538. const char *status;
  2539. char name[128];
  2540. if (conn->nickname)
  2541. strlcpy(name, conn->nickname, sizeof(name));
  2542. else
  2543. tor_snprintf(name, sizeof(name), "%s:%d",
  2544. conn->address, conn->port);
  2545. switch (tp)
  2546. {
  2547. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2548. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  2549. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  2550. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  2551. default:
  2552. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2553. return 0;
  2554. }
  2555. send_control1_event(EVENT_OR_CONN_STATUS,
  2556. "650 ORCONN %s %s\r\n",
  2557. name, status);
  2558. }
  2559. return 0;
  2560. }
  2561. /** A second or more has elapsed: tell any interested control
  2562. * connections how much bandwidth we used. */
  2563. int
  2564. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  2565. {
  2566. char buf[8];
  2567. if (EVENT_IS_INTERESTING0(EVENT_BANDWIDTH_USED)) {
  2568. set_uint32(buf, htonl(n_read));
  2569. set_uint32(buf+4, htonl(n_written));
  2570. send_control0_event(EVENT_BANDWIDTH_USED, 8, buf);
  2571. }
  2572. if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED)) {
  2573. send_control1_event(EVENT_BANDWIDTH_USED,
  2574. "650 BW %lu %lu\r\n",
  2575. (unsigned long)n_read,
  2576. (unsigned long)n_written);
  2577. }
  2578. return 0;
  2579. }
  2580. /** Called when we are sending a log message to the controllers: suspend
  2581. * sending further log messages to the controllers until we're done. Used by
  2582. * CONN_LOG_PROTECT. */
  2583. void
  2584. disable_control_logging(void)
  2585. {
  2586. ++disable_log_messages;
  2587. }
  2588. /** We're done sending a log message to the controllers: re-enable controller
  2589. * logging. Used by CONN_LOG_PROTECT. */
  2590. void
  2591. enable_control_logging(void)
  2592. {
  2593. if (--disable_log_messages < 0)
  2594. tor_assert(0);
  2595. }
  2596. /** We got a log message: tell any interested control connections. */
  2597. void
  2598. control_event_logmsg(int severity, unsigned int domain, const char *msg)
  2599. {
  2600. int oldlog, event;
  2601. if (disable_log_messages)
  2602. return;
  2603. oldlog = EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE) &&
  2604. (severity == LOG_NOTICE || severity == LOG_WARN || severity == LOG_ERR);
  2605. event = log_severity_to_event(severity);
  2606. if (event<0 || !EVENT_IS_INTERESTING0(event))
  2607. event = 0;
  2608. if (oldlog || event) {
  2609. size_t len = strlen(msg);
  2610. ++disable_log_messages;
  2611. if (event)
  2612. send_control0_event(event, (uint32_t)(len+1), msg);
  2613. if (oldlog)
  2614. send_control0_event(EVENT_LOG_OBSOLETE, (uint32_t)(len+1), msg);
  2615. --disable_log_messages;
  2616. }
  2617. event = log_severity_to_event(severity);
  2618. if (event >= 0 && EVENT_IS_INTERESTING1(event)) {
  2619. char *b = NULL;
  2620. const char *s;
  2621. if (strchr(msg, '\n')) {
  2622. char *cp;
  2623. b = tor_strdup(msg);
  2624. for (cp = b; *cp; ++cp)
  2625. if (*cp == '\r' || *cp == '\n')
  2626. *cp = ' ';
  2627. }
  2628. switch (severity) {
  2629. case LOG_DEBUG: s = "DEBUG"; break;
  2630. case LOG_INFO: s = "INFO"; break;
  2631. case LOG_NOTICE: s = "NOTICE"; break;
  2632. case LOG_WARN: s = "WARN"; break;
  2633. case LOG_ERR: s = "ERR"; break;
  2634. default: s = "UnknownLogSeverity"; break;
  2635. }
  2636. ++disable_log_messages;
  2637. send_control1_event(event, "650 %s %s\r\n", s, b?b:msg);
  2638. --disable_log_messages;
  2639. tor_free(b);
  2640. }
  2641. }
  2642. /** Called whenever we receive new router descriptors: tell any
  2643. * interested control connections. <b>routers</b> is a list of
  2644. * DIGEST_LEN-byte identity digests.
  2645. */
  2646. int
  2647. control_event_descriptors_changed(smartlist_t *routers)
  2648. {
  2649. size_t len;
  2650. char *msg;
  2651. smartlist_t *identities;
  2652. char buf[HEX_DIGEST_LEN+1];
  2653. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  2654. return 0;
  2655. identities = smartlist_create();
  2656. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  2657. {
  2658. base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
  2659. smartlist_add(identities, tor_strdup(buf));
  2660. });
  2661. if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC)) {
  2662. msg = smartlist_join_strings(identities, ",", 0, &len);
  2663. send_control0_event(EVENT_NEW_DESC, len+1, msg);
  2664. tor_free(msg);
  2665. }
  2666. if (EVENT_IS_INTERESTING1(EVENT_NEW_DESC)) {
  2667. msg = smartlist_join_strings(identities, " ", 0, &len);
  2668. send_control1_event(EVENT_NEW_DESC, "650 NEWDESC %s\r\n", msg);
  2669. tor_free(msg);
  2670. }
  2671. SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  2672. smartlist_free(identities);
  2673. return 0;
  2674. }
  2675. /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
  2676. * <b>expires</b> values less than 3 are special; see connection_edge.c. */
  2677. int
  2678. control_event_address_mapped(const char *from, const char *to, time_t expires)
  2679. {
  2680. if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP))
  2681. return 0;
  2682. if (expires < 3)
  2683. send_control1_event(EVENT_ADDRMAP,
  2684. "650 ADDRMAP %s %s NEVER\r\n", from, to);
  2685. else {
  2686. char buf[ISO_TIME_LEN+1];
  2687. format_local_iso_time(buf,expires);
  2688. send_control1_event(EVENT_ADDRMAP, "650 ADDRMAP %s %s \"%s\"\r\n",
  2689. from, to, buf);
  2690. }
  2691. return 0;
  2692. }
  2693. /** The authoritative dirserver has received a new descriptor that
  2694. * has passed basic syntax checks and is properly self-signed.
  2695. *
  2696. * Notify any interested party of the new descriptor and what has
  2697. * been done with it, and also optionally give an explanation/reason. */
  2698. int
  2699. control_event_or_authdir_new_descriptor(const char *action,
  2700. const char *descriptor,
  2701. const char *msg)
  2702. {
  2703. char firstline[1024];
  2704. char *buf;
  2705. int totallen;
  2706. char *esc = NULL;
  2707. size_t esclen;
  2708. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  2709. return 0;
  2710. tor_snprintf(firstline, sizeof(firstline),
  2711. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  2712. action,
  2713. msg ? msg : "");
  2714. /* Escape the server descriptor properly */
  2715. esclen = write_escaped_data(descriptor, strlen(descriptor), 1, &esc);
  2716. totallen = strlen(firstline) + esclen + 1;
  2717. buf = tor_malloc(totallen);
  2718. strlcpy(buf, firstline, totallen);
  2719. strlcpy(buf+strlen(firstline), esc, totallen);
  2720. send_control1_event_string(EVENT_AUTHDIR_NEWDESCS, buf);
  2721. tor_free(esc);
  2722. tor_free(buf);
  2723. return 0;
  2724. }
  2725. /** Choose a random authentication cookie and write it to disk.
  2726. * Anybody who can read the cookie from disk will be considered
  2727. * authorized to use the control connection. */
  2728. int
  2729. init_cookie_authentication(int enabled)
  2730. {
  2731. char fname[512];
  2732. if (!enabled) {
  2733. authentication_cookie_is_set = 0;
  2734. return 0;
  2735. }
  2736. tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
  2737. get_options()->DataDirectory);
  2738. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2739. authentication_cookie_is_set = 1;
  2740. if (write_bytes_to_file(fname, authentication_cookie,
  2741. AUTHENTICATION_COOKIE_LEN, 1)) {
  2742. log_warn(LD_FS,"Error writing authentication cookie.");
  2743. return -1;
  2744. }
  2745. return 0;
  2746. }