control.c 84 KB

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