control.c 77 KB

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