control.c 77 KB

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