control.c 77 KB

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