control.c 75 KB

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