control.c 79 KB

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