control.c 82 KB

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