control.c 78 KB

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