control.c 78 KB

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