control.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. /* Copyright 2004 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. *
  8. * \brief Implementation for Tor's control-socket interface.
  9. */
  10. #include "or.h"
  11. /* Protocol outline: a bidirectional stream, over which each side
  12. * sends a series of messages. Each message has a two-byte length field,
  13. * a two-byte typecode, and a variable-length body whose length is
  14. * given in the length field.
  15. *
  16. * By default, the server only sends messages in response to client messages.
  17. * Every client message gets a message in response. The client may, however,
  18. * _request_ that other messages be delivered asynchronously.
  19. *
  20. *
  21. * Every message type is either client-only or server-only, and every
  22. * server message type is either synchronous-only (only occurs in
  23. * response to a client request) or asynchronous-only (never is an
  24. * answer to a client request.
  25. *
  26. * See control-spec.txt for full details.
  27. */
  28. /* Recognized message type codes. */
  29. #define CONTROL_CMD_ERROR 0x0000
  30. #define CONTROL_CMD_DONE 0x0001
  31. #define CONTROL_CMD_SETCONF 0x0002
  32. #define CONTROL_CMD_GETCONF 0x0003
  33. #define CONTROL_CMD_CONFVALUE 0x0004
  34. #define CONTROL_CMD_SETEVENTS 0x0005
  35. #define CONTROL_CMD_EVENT 0x0006
  36. #define CONTROL_CMD_AUTHENTICATE 0x0007
  37. #define CONTROL_CMD_SAVECONF 0x0008
  38. #define CONTROL_CMD_SIGNAL 0x0009
  39. #define CONTROL_CMD_MAPADDRESS 0x000A
  40. #define CONTROL_CMD_GETINFO 0x000B
  41. #define CONTROL_CMD_INFOVALUE 0x000C
  42. #define CONTROL_CMD_EXTENDCIRCUIT 0x000D
  43. #define CONTROL_CMD_ATTACHSTREAM 0x000E
  44. #define CONTROL_CMD_POSTDESCRIPTOR 0x000F
  45. #define CONTROL_CMD_FRAGMENTHEADER 0x0010
  46. #define CONTROL_CMD_FRAGMENT 0x0011
  47. #define CONTROL_CMD_REDIRECTSTREAM 0x0012
  48. #define _CONTROL_CMD_MAX_RECOGNIZED 0x0012
  49. /* Recognized error codes. */
  50. #define ERR_UNSPECIFIED 0x0000
  51. #define ERR_INTERNAL 0x0001
  52. #define ERR_UNRECOGNIZED_TYPE 0x0002
  53. #define ERR_SYNTAX 0x0003
  54. #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
  55. #define ERR_INVALID_CONFIG_VALUE 0x0005
  56. #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
  57. #define ERR_UNAUTHORIZED 0x0007
  58. #define ERR_REJECTED_AUTHENTICATION 0x0008
  59. #define ERR_RESOURCE_EXHAUSETED 0x0009
  60. #define ERR_NO_STREAM 0x000A
  61. #define ERR_NO_CIRC 0x000B
  62. #define ERR_NO_ROUTER 0x000C
  63. /* Recognized asynchronous event types. */
  64. #define _EVENT_MIN 0x0001
  65. #define EVENT_CIRCUIT_STATUS 0x0001
  66. #define EVENT_STREAM_STATUS 0x0002
  67. #define EVENT_OR_CONN_STATUS 0x0003
  68. #define EVENT_BANDWIDTH_USED 0x0004
  69. #define EVENT_WARNING 0x0005
  70. #define EVENT_NEW_DESC 0x0006
  71. #define _EVENT_MAX 0x0006
  72. /** Array mapping from message type codes to human-readable message
  73. * type names. */
  74. static const char * CONTROL_COMMANDS[_CONTROL_CMD_MAX_RECOGNIZED+1] = {
  75. "error",
  76. "done",
  77. "setconf",
  78. "getconf",
  79. "confvalue",
  80. "setevents",
  81. "events",
  82. "authenticate",
  83. "saveconf",
  84. "signal",
  85. "mapaddress",
  86. "getinfo",
  87. "infovalue",
  88. "extendcircuit",
  89. "attachstream",
  90. "postdescriptor",
  91. "fragmentheader",
  92. "fragment",
  93. };
  94. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  95. * connection is interested in events of type <b>e</b>. We use this
  96. * so that we can decide to skip generating event messages that nobody
  97. * has interest in without having to walk over the global connection
  98. * list to find out.
  99. **/
  100. static uint32_t global_event_mask = 0;
  101. /** Macro: true if any control connection is interested in events of type
  102. * <b>e</b>. */
  103. #define EVENT_IS_INTERESTING(e) (global_event_mask & (1<<(e)))
  104. /** If we're using cookie-type authentication, how long should our cookies be?
  105. */
  106. #define AUTHENTICATION_COOKIE_LEN 32
  107. /** If true, we've set authentication_cookie to a secret code and
  108. * stored it to disk. */
  109. static int authentication_cookie_is_set = 0;
  110. static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
  111. static void update_global_event_mask(void);
  112. static void send_control_message(connection_t *conn, uint16_t type,
  113. uint32_t len, const char *body);
  114. static void send_control_done(connection_t *conn);
  115. static void send_control_done2(connection_t *conn, const char *msg, size_t len);
  116. static void send_control_error(connection_t *conn, uint16_t error,
  117. const char *message);
  118. static void send_control_event(uint16_t event, uint32_t len, const char *body);
  119. static int handle_control_setconf(connection_t *conn, uint32_t len,
  120. char *body);
  121. static int handle_control_getconf(connection_t *conn, uint32_t len,
  122. const char *body);
  123. static int handle_control_setevents(connection_t *conn, uint32_t len,
  124. const char *body);
  125. static int handle_control_authenticate(connection_t *conn, uint32_t len,
  126. const char *body);
  127. static int handle_control_saveconf(connection_t *conn, uint32_t len,
  128. const char *body);
  129. static int handle_control_signal(connection_t *conn, uint32_t len,
  130. const char *body);
  131. static int handle_control_mapaddress(connection_t *conn, uint32_t len,
  132. const char *body);
  133. static int handle_control_getinfo(connection_t *conn, uint32_t len,
  134. const char *body);
  135. static int handle_control_extendcircuit(connection_t *conn, uint32_t len,
  136. const char *body);
  137. static int handle_control_attachstream(connection_t *conn, uint32_t len,
  138. const char *body);
  139. static int handle_control_postdescriptor(connection_t *conn, uint32_t len,
  140. const char *body);
  141. static int handle_control_redirectstream(connection_t *conn, uint32_t len,
  142. const char *body);
  143. /** Given a possibly invalid message type code <b>cmd</b>, return a
  144. * human-readable string equivalent. */
  145. static INLINE const char *
  146. control_cmd_to_string(uint16_t cmd)
  147. {
  148. return (cmd<=_CONTROL_CMD_MAX_RECOGNIZED) ? CONTROL_COMMANDS[cmd] : "Unknown";
  149. }
  150. /** Set <b>global_event_mask</b> to the bitwise OR of each live control
  151. * connection's event_mask field. */
  152. static void update_global_event_mask(void)
  153. {
  154. connection_t **conns;
  155. int n_conns, i;
  156. global_event_mask = 0;
  157. get_connection_array(&conns, &n_conns);
  158. for (i = 0; i < n_conns; ++i) {
  159. if (conns[i]->type == CONN_TYPE_CONTROL &&
  160. conns[i]->state == CONTROL_CONN_STATE_OPEN) {
  161. global_event_mask |= conns[i]->event_mask;
  162. }
  163. }
  164. }
  165. /** Send a message of type <b>type</b> containing <b>len</b> bytes
  166. * from <b>body</b> along the control connection <b>conn</b> */
  167. static void
  168. send_control_message(connection_t *conn, uint16_t type, uint32_t len,
  169. const char *body)
  170. {
  171. char buf[10];
  172. tor_assert(conn);
  173. tor_assert(len || !body);
  174. tor_assert(type <= _CONTROL_CMD_MAX_RECOGNIZED);
  175. if (len < 65536) {
  176. set_uint16(buf, htons(len));
  177. set_uint16(buf+2, htons(type));
  178. connection_write_to_buf(buf, 4, conn);
  179. if (len)
  180. connection_write_to_buf(body, len, conn);
  181. } else {
  182. set_uint16(buf, htons(65535));
  183. set_uint16(buf+2, htons(CONTROL_CMD_FRAGMENTHEADER));
  184. set_uint16(buf+4, htons(type));
  185. set_uint32(buf+6, htonl(len));
  186. connection_write_to_buf(buf, 10, conn);
  187. connection_write_to_buf(body, 65535-6, conn);
  188. len -= (65535-6);
  189. body += (65535-6);
  190. while (len) {
  191. size_t chunklen = (len<65535)?len:65535;
  192. set_uint16(buf, htons((uint16_t)chunklen));
  193. set_uint16(buf+2, htons(CONTROL_CMD_FRAGMENT));
  194. connection_write_to_buf(buf, 4, conn);
  195. connection_write_to_buf(body, chunklen, conn);
  196. len -= chunklen;
  197. body += chunklen;
  198. }
  199. }
  200. }
  201. /** Send a "DONE" message down the control connection <b>conn</b> */
  202. static void
  203. send_control_done(connection_t *conn)
  204. {
  205. send_control_message(conn, CONTROL_CMD_DONE, 0, NULL);
  206. }
  207. static void send_control_done2(connection_t *conn, const char *msg, size_t len)
  208. {
  209. send_control_message(conn, CONTROL_CMD_DONE, len, msg);
  210. }
  211. /** Send an error message with error code <b>error</b> and body
  212. * <b>message</b> down the connection <b>conn</b> */
  213. static void
  214. send_control_error(connection_t *conn, uint16_t error, const char *message)
  215. {
  216. char buf[256];
  217. size_t len;
  218. set_uint16(buf, htons(error));
  219. len = strlen(message);
  220. tor_assert(len < (256-2));
  221. memcpy(buf+2, message, len);
  222. send_control_message(conn, CONTROL_CMD_ERROR, (uint16_t)(len+2), buf);
  223. }
  224. /** Send an 'event' message of event type <b>event</b>, containing
  225. * <b>len</b> bytes in <b>body</b> to every control connection that
  226. * is interested in it. */
  227. static void
  228. send_control_event(uint16_t event, uint32_t len, const char *body)
  229. {
  230. connection_t **conns;
  231. int n_conns, i;
  232. size_t buflen;
  233. char *buf;
  234. buflen = len + 2;
  235. buf = tor_malloc_zero(buflen);
  236. set_uint16(buf, htons(event));
  237. memcpy(buf+2, body, len);
  238. get_connection_array(&conns, &n_conns);
  239. for (i = 0; i < n_conns; ++i) {
  240. if (conns[i]->type == CONN_TYPE_CONTROL &&
  241. conns[i]->state == CONTROL_CONN_STATE_OPEN &&
  242. conns[i]->event_mask & (1<<event)) {
  243. send_control_message(conns[i], CONTROL_CMD_EVENT, buflen, buf);
  244. }
  245. }
  246. tor_free(buf);
  247. }
  248. /** Called when we receive a SETCONF message: parse the body and try
  249. * to update our configuration. Reply with a DONE or ERROR message. */
  250. static int
  251. handle_control_setconf(connection_t *conn, uint32_t len, char *body)
  252. {
  253. int r;
  254. struct config_line_t *lines=NULL;
  255. if (config_get_lines(body, &lines) < 0) {
  256. log_fn(LOG_WARN,"Controller gave us config lines we can't parse.");
  257. send_control_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
  258. return 0;
  259. }
  260. if ((r=config_trial_assign(lines, 1)) < 0) {
  261. log_fn(LOG_WARN,"Controller gave us config lines that didn't validate.");
  262. if (r==-1) {
  263. send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY,
  264. "Unrecognized option");
  265. } else {
  266. send_control_error(conn, ERR_INVALID_CONFIG_VALUE,"Invalid option value");
  267. }
  268. config_free_lines(lines);
  269. return 0;
  270. }
  271. config_free_lines(lines);
  272. if (options_act() < 0) { /* acting on them failed. die. */
  273. log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
  274. exit(1);
  275. }
  276. send_control_done(conn);
  277. return 0;
  278. }
  279. /** Called when we receive a GETCONF message. Parse the request, and
  280. * reply with a CONFVALUE or an ERROR message */
  281. static int
  282. handle_control_getconf(connection_t *conn, uint32_t body_len, const char *body)
  283. {
  284. smartlist_t *questions = NULL;
  285. smartlist_t *answers = NULL;
  286. char *msg = NULL;
  287. size_t msg_len;
  288. or_options_t *options = get_options();
  289. questions = smartlist_create();
  290. smartlist_split_string(questions, body, "\n",
  291. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  292. answers = smartlist_create();
  293. SMARTLIST_FOREACH(questions, const char *, q,
  294. {
  295. int recognized = config_option_is_recognized(q);
  296. if (!recognized) {
  297. send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
  298. goto done;
  299. } else {
  300. struct config_line_t *answer = config_get_assigned_option(options,q);
  301. while (answer) {
  302. struct config_line_t *next;
  303. size_t alen = strlen(answer->key)+strlen(answer->value)+3;
  304. char *astr = tor_malloc(alen);
  305. tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
  306. smartlist_add(answers, astr);
  307. next = answer->next;
  308. tor_free(answer->key);
  309. tor_free(answer->value);
  310. tor_free(answer);
  311. answer = next;
  312. }
  313. }
  314. });
  315. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  316. send_control_message(conn, CONTROL_CMD_CONFVALUE,
  317. (uint16_t)msg_len, msg_len?msg:NULL);
  318. done:
  319. if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  320. if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  321. smartlist_free(answers);
  322. smartlist_free(questions);
  323. tor_free(msg);
  324. return 0;
  325. }
  326. /** Called when we get a SETEVENTS message: update conn->event_mask,
  327. * and reply with DONE or ERROR. */
  328. static int
  329. handle_control_setevents(connection_t *conn, uint32_t len, const char *body)
  330. {
  331. uint16_t event_code;
  332. uint32_t event_mask = 0;
  333. if (len % 2) {
  334. send_control_error(conn, ERR_SYNTAX,
  335. "Odd number of bytes in setevents message");
  336. return 0;
  337. }
  338. for (; len; len -= 2, body += 2) {
  339. event_code = ntohs(get_uint16(body));
  340. if (event_code < _EVENT_MIN || event_code > _EVENT_MAX) {
  341. send_control_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
  342. "Unrecognized event code");
  343. return 0;
  344. }
  345. event_mask |= (1 << event_code);
  346. }
  347. conn->event_mask = event_mask;
  348. update_global_event_mask();
  349. send_control_done(conn);
  350. return 0;
  351. }
  352. /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
  353. * <b>buf</b> is provided, store the hashed password in the first
  354. * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
  355. * success, -1 on failure.
  356. */
  357. int
  358. decode_hashed_password(char *buf, const char *hashed)
  359. {
  360. char decoded[64];
  361. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  362. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  363. return -1;
  364. }
  365. if (buf)
  366. memcpy(buf, decoded, sizeof(decoded));
  367. return 0;
  368. }
  369. /** Called when we get an AUTHENTICATE message. Check whether the
  370. * authentication is valid, and if so, update the connection's state to
  371. * OPEN. Reply with DONE or ERROR.
  372. */
  373. static int
  374. handle_control_authenticate(connection_t *conn, uint32_t len, const char *body)
  375. {
  376. or_options_t *options = get_options();
  377. if (options->CookieAuthentication) {
  378. if (len == AUTHENTICATION_COOKIE_LEN &&
  379. !memcmp(authentication_cookie, body, len)) {
  380. goto ok;
  381. }
  382. } else if (options->HashedControlPassword) {
  383. char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
  384. char received[DIGEST_LEN];
  385. if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
  386. log_fn(LOG_WARN,"Couldn't decode HashedControlPassword: invalid base64");
  387. goto err;
  388. }
  389. secret_to_key(received,DIGEST_LEN,body,len,expected);
  390. if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  391. goto ok;
  392. goto err;
  393. } else {
  394. if (len == 0) {
  395. /* if Tor doesn't demand any stronger authentication, then
  396. * the controller can get in with a blank auth line. */
  397. goto ok;
  398. }
  399. goto err;
  400. }
  401. err:
  402. send_control_error(conn, ERR_REJECTED_AUTHENTICATION,"Authentication failed");
  403. return 0;
  404. ok:
  405. log_fn(LOG_INFO, "Authenticated control connection (%d)", conn->s);
  406. send_control_done(conn);
  407. conn->state = CONTROL_CONN_STATE_OPEN;
  408. return 0;
  409. }
  410. static int
  411. handle_control_saveconf(connection_t *conn, uint32_t len,
  412. const char *body)
  413. {
  414. if (save_current_config()<0) {
  415. send_control_error(conn, ERR_INTERNAL,
  416. "Unable to write configuration to disk.");
  417. } else {
  418. send_control_done(conn);
  419. }
  420. return 0;
  421. }
  422. static int
  423. handle_control_signal(connection_t *conn, uint32_t len,
  424. const char *body)
  425. {
  426. if (len != 1) {
  427. send_control_error(conn, ERR_SYNTAX,
  428. "Body of SIGNAL command too long or too short.");
  429. } else if (control_signal_act((uint8_t)body[0]) < 0) {
  430. send_control_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
  431. } else {
  432. send_control_done(conn);
  433. }
  434. return 0;
  435. }
  436. static int
  437. handle_control_mapaddress(connection_t *conn, uint32_t len, const char *body)
  438. {
  439. smartlist_t *elts;
  440. smartlist_t *lines;
  441. smartlist_t *reply;
  442. char *r;
  443. size_t sz;
  444. lines = smartlist_create();
  445. elts = smartlist_create();
  446. reply = smartlist_create();
  447. smartlist_split_string(lines, body, "\n",
  448. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  449. SMARTLIST_FOREACH(lines, char *, line,
  450. {
  451. tor_strlower(line);
  452. smartlist_split_string(elts, line, " ", 0, 2);
  453. if (smartlist_len(elts) == 2) {
  454. const char *from = smartlist_get(elts,0);
  455. const char *to = smartlist_get(elts,1);
  456. if (!is_plausible_address(from)) {
  457. log_fn(LOG_WARN,"Skipping invalid argument '%s' in MapAddress msg",from);
  458. } else if (!is_plausible_address(to)) {
  459. log_fn(LOG_WARN,"Skipping invalid argument '%s' in MapAddress msg",to);
  460. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  461. char *addr = addressmap_register_virtual_address(
  462. strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  463. tor_strdup(to));
  464. if (!addr) {
  465. log_fn(LOG_WARN,
  466. "Unable to allocate address for '%s' in MapAddress msg",line);
  467. } else {
  468. size_t anslen = strlen(addr)+strlen(to)+2;
  469. char *ans = tor_malloc(anslen);
  470. tor_snprintf(ans, anslen, "%s %s", addr, to);
  471. tor_free(addr);
  472. smartlist_add(reply, ans);
  473. }
  474. } else {
  475. addressmap_register(from, tor_strdup(to), 1);
  476. smartlist_add(reply, tor_strdup(line));
  477. }
  478. } else {
  479. log_fn(LOG_WARN, "Skipping MapAddress line with wrong number of items.");
  480. }
  481. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  482. smartlist_clear(elts);
  483. });
  484. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  485. smartlist_free(lines);
  486. smartlist_free(elts);
  487. r = smartlist_join_strings(reply, "\n", 1, &sz);
  488. send_control_done2(conn,r,sz);
  489. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  490. smartlist_free(reply);
  491. tor_free(r);
  492. return 0;
  493. }
  494. /** Lookup the 'getinfo' entry <b>question</b>, and return
  495. * the answer in <b>*answer</b> (or NULL if key not recognized).
  496. * Return 0 if success, or -1 if internal error. */
  497. static int
  498. handle_getinfo_helper(const char *question, char **answer)
  499. {
  500. *answer = NULL; /* unrecognized key by default */
  501. if (!strcmp(question, "version")) {
  502. *answer = tor_strdup(VERSION);
  503. } else if (!strcmpstart(question, "desc/id/")) {
  504. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  505. if (ri && ri->signed_descriptor)
  506. *answer = tor_strdup(ri->signed_descriptor);
  507. } else if (!strcmp(question, "network-status")) {
  508. if (list_server_status(NULL, answer) < 0)
  509. return -1;
  510. } else if (!strcmpstart(question, "addr-mappings/")) {
  511. time_t min_e, max_e;
  512. smartlist_t *mappings;
  513. if (!strcmp(question, "addr-mappings/all")) {
  514. min_e = 0; max_e = TIME_MAX;
  515. } else if (!strcmp(question, "addr-mappings/cache")) {
  516. min_e = 2; max_e = TIME_MAX;
  517. } else if (!strcmp(question, "addr-mappings/config")) {
  518. min_e = 0; max_e = 0;
  519. } else if (!strcmp(question, "addr-mappings/control")) {
  520. min_e = 1; max_e = 1;
  521. } else {
  522. return 0;
  523. }
  524. mappings = smartlist_create();
  525. addressmap_get_mappings(mappings, min_e, max_e);
  526. *answer = smartlist_join_strings(mappings, "\n", 1, NULL);
  527. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  528. smartlist_free(mappings);
  529. }
  530. return 0;
  531. }
  532. static int
  533. handle_control_getinfo(connection_t *conn, uint32_t len, const char *body)
  534. {
  535. smartlist_t *questions = NULL;
  536. smartlist_t *answers = NULL;
  537. char *msg = NULL, *ans;
  538. size_t msg_len;
  539. questions = smartlist_create();
  540. smartlist_split_string(questions, body, "\n",
  541. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  542. answers = smartlist_create();
  543. SMARTLIST_FOREACH(questions, const char *, q,
  544. {
  545. if (handle_getinfo_helper(q, &ans) < 0) {
  546. send_control_error(conn, ERR_INTERNAL, body);
  547. goto done;
  548. } if (!ans) {
  549. send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
  550. goto done;
  551. }
  552. smartlist_add(answers, tor_strdup(q));
  553. smartlist_add(answers, ans);
  554. });
  555. msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
  556. tor_assert(msg_len > 0); /* it will at least be terminated */
  557. send_control_message(conn, CONTROL_CMD_INFOVALUE,
  558. msg_len, msg);
  559. done:
  560. if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  561. if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  562. smartlist_free(answers);
  563. smartlist_free(questions);
  564. tor_free(msg);
  565. return 0;
  566. }
  567. static int
  568. handle_control_extendcircuit(connection_t *conn, uint32_t len,
  569. const char *body)
  570. {
  571. smartlist_t *router_nicknames, *routers;
  572. uint32_t circ_id;
  573. circuit_t *circ;
  574. if (len<5) {
  575. send_control_error(conn, ERR_SYNTAX, "extendcircuit message too short");
  576. return 0;
  577. }
  578. router_nicknames = smartlist_create();
  579. routers = smartlist_create();
  580. smartlist_split_string(router_nicknames, body, ",", 0, 0);
  581. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  582. {
  583. routerinfo_t *r = router_get_by_nickname(n);
  584. if (!r) {
  585. send_control_error(conn, ERR_NO_ROUTER, "Unrecognized router name");
  586. goto done;
  587. }
  588. smartlist_add(routers, r);
  589. });
  590. if (!smartlist_len(routers)) {
  591. send_control_error(conn, ERR_SYNTAX, "No router names provided");
  592. goto done;
  593. }
  594. circ_id = ntohl(get_uint32(body));
  595. if (!circ_id) {
  596. /* start a new circuit */
  597. circ = circuit_init(CIRCUIT_PURPOSE_C_GENERAL, 0, 0, 0);
  598. } else {
  599. circ = circuit_get_by_global_id(circ_id);
  600. if (!circ) {
  601. send_control_error(conn, ERR_NO_CIRC,
  602. "No circuit found with given ID");
  603. goto done;
  604. }
  605. }
  606. /* now circ refers to something that is ready to be extended */
  607. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  608. {
  609. circuit_append_new_exit(circ, r);
  610. });
  611. /* now that we've populated the cpath, start extending */
  612. if (!circ_id) {
  613. if (circuit_handle_first_hop(circ) < 0) {
  614. circuit_mark_for_close(circ);
  615. }
  616. } else {
  617. if (circ->state == CIRCUIT_STATE_OPEN) {
  618. circ->state = CIRCUIT_STATE_BUILDING;
  619. if (circuit_send_next_onion_skin(circ) < 0) {
  620. log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
  621. circuit_mark_for_close(circ);
  622. }
  623. }
  624. }
  625. send_control_done(conn);
  626. done:
  627. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  628. smartlist_free(router_nicknames);
  629. smartlist_free(routers);
  630. return 0;
  631. }
  632. static int handle_control_attachstream(connection_t *conn, uint32_t len,
  633. const char *body)
  634. {
  635. uint32_t conn_id;
  636. uint32_t circ_id;
  637. connection_t *ap_conn;
  638. circuit_t *circ;
  639. if (len < 8) {
  640. send_control_error(conn, ERR_SYNTAX, "attachstream message too short");
  641. return 0;
  642. }
  643. conn_id = ntohl(get_uint32(body));
  644. circ_id = ntohl(get_uint32(body+4));
  645. if (!(ap_conn = connection_get_by_global_id(conn_id))) {
  646. send_control_error(conn, ERR_NO_STREAM,
  647. "No connection found with given ID");
  648. return 0;
  649. }
  650. if (ap_conn->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  651. send_control_error(conn, ERR_NO_STREAM,
  652. "Connection was not managed by controller.");
  653. return 0;
  654. }
  655. if (!circ_id) {
  656. ap_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  657. if (connection_ap_handshake_attach_circuit(ap_conn)<0)
  658. connection_mark_for_close(ap_conn);
  659. return 0;
  660. }
  661. if (!(circ = circuit_get_by_global_id(circ_id))) {
  662. send_control_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
  663. return 0;
  664. }
  665. if (connection_ap_handshake_attach_chosen_circuit(ap_conn, circ) != 1) {
  666. send_control_error(conn, ERR_INTERNAL, "Unable to attach stream.");
  667. return 0;
  668. }
  669. send_control_done(conn);
  670. return 0;
  671. }
  672. static int
  673. handle_control_postdescriptor(connection_t *conn, uint32_t len,
  674. const char *body)
  675. {
  676. if (router_load_single_router(body)<0) {
  677. /* XXXX a more specific error would be nice. */
  678. send_control_error(conn,ERR_UNSPECIFIED,
  679. "Could not parse descriptor or add it");
  680. return 0;
  681. }
  682. send_control_done(conn);
  683. return 0;
  684. }
  685. static int
  686. handle_control_redirectstream(connection_t *conn, uint32_t len,
  687. const char *body)
  688. {
  689. connection_t *ap_conn;
  690. uint32_t conn_id;
  691. if (len < 6) {
  692. send_control_error(conn, ERR_SYNTAX, "attachstream message too short");
  693. return 0;
  694. }
  695. conn_id = ntohl(get_uint32(body));
  696. if (!(ap_conn = connection_get_by_global_id(conn_id))
  697. || ap_conn->state != CONN_TYPE_AP
  698. || !ap_conn->socks_request) {
  699. send_control_error(conn, ERR_NO_STREAM,
  700. "No AP connection found with given ID");
  701. return 0;
  702. }
  703. strlcpy(ap_conn->socks_request->address, body+1,
  704. sizeof(ap_conn->socks_request->address));
  705. send_control_done(conn);
  706. return 0;
  707. }
  708. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  709. int
  710. connection_control_finished_flushing(connection_t *conn) {
  711. tor_assert(conn);
  712. tor_assert(conn->type == CONN_TYPE_CONTROL);
  713. connection_stop_writing(conn);
  714. return 0;
  715. }
  716. /** Called when <b>conn</b> has gotten its socket closed. */
  717. int connection_control_reached_eof(connection_t *conn) {
  718. log_fn(LOG_INFO,"Control connection reached EOF. Closing.");
  719. connection_mark_for_close(conn);
  720. return 0;
  721. }
  722. /** Called when <b>conn</b> has received more bytes on its inbuf.
  723. */
  724. int
  725. connection_control_process_inbuf(connection_t *conn) {
  726. uint32_t body_len;
  727. uint16_t command_type;
  728. char *body;
  729. tor_assert(conn);
  730. tor_assert(conn->type == CONN_TYPE_CONTROL);
  731. again:
  732. /* Try to suck a control message from the buffer. */
  733. switch (fetch_from_buf_control(conn->inbuf, &body_len, &command_type, &body))
  734. {
  735. case -1:
  736. tor_free(body);
  737. log_fn(LOG_WARN, "Error in control command. Failing.");
  738. return -1;
  739. case 0:
  740. /* Control command not all here yet. Wait. */
  741. return 0;
  742. case 1:
  743. /* We got a command. Process it. */
  744. break;
  745. default:
  746. tor_assert(0);
  747. }
  748. /* We got a command. If we need authentication, only authentication
  749. * commands will be considered. */
  750. if (conn->state == CONTROL_CONN_STATE_NEEDAUTH &&
  751. command_type != CONTROL_CMD_AUTHENTICATE) {
  752. log_fn(LOG_WARN, "Rejecting '%s' command; authentication needed.",
  753. control_cmd_to_string(command_type));
  754. send_control_error(conn, ERR_UNAUTHORIZED, "Authentication required");
  755. tor_free(body);
  756. goto again;
  757. }
  758. /* Okay, we're willing to process the command. */
  759. switch (command_type)
  760. {
  761. case CONTROL_CMD_SETCONF:
  762. if (handle_control_setconf(conn, body_len, body))
  763. return -1;
  764. break;
  765. case CONTROL_CMD_GETCONF:
  766. if (handle_control_getconf(conn, body_len, body))
  767. return -1;
  768. break;
  769. case CONTROL_CMD_SETEVENTS:
  770. if (handle_control_setevents(conn, body_len, body))
  771. return -1;
  772. break;
  773. case CONTROL_CMD_AUTHENTICATE:
  774. if (handle_control_authenticate(conn, body_len, body))
  775. return -1;
  776. break;
  777. case CONTROL_CMD_SAVECONF:
  778. if (handle_control_saveconf(conn, body_len, body))
  779. return -1;
  780. break;
  781. case CONTROL_CMD_SIGNAL:
  782. if (handle_control_signal(conn, body_len, body))
  783. return -1;
  784. break;
  785. case CONTROL_CMD_MAPADDRESS:
  786. if (handle_control_mapaddress(conn, body_len, body))
  787. return -1;
  788. break;
  789. case CONTROL_CMD_GETINFO:
  790. if (handle_control_getinfo(conn, body_len, body))
  791. return -1;
  792. break;
  793. case CONTROL_CMD_EXTENDCIRCUIT:
  794. if (handle_control_extendcircuit(conn, body_len, body))
  795. return -1;
  796. break;
  797. case CONTROL_CMD_ATTACHSTREAM:
  798. if (handle_control_attachstream(conn, body_len, body))
  799. return -1;
  800. break;
  801. case CONTROL_CMD_POSTDESCRIPTOR:
  802. if (handle_control_postdescriptor(conn, body_len, body))
  803. return -1;
  804. break;
  805. case CONTROL_CMD_REDIRECTSTREAM:
  806. if (handle_control_redirectstream(conn, body_len, body))
  807. return -1;
  808. break;
  809. case CONTROL_CMD_ERROR:
  810. case CONTROL_CMD_DONE:
  811. case CONTROL_CMD_CONFVALUE:
  812. case CONTROL_CMD_EVENT:
  813. case CONTROL_CMD_INFOVALUE:
  814. log_fn(LOG_WARN, "Received client-only '%s' command; ignoring.",
  815. control_cmd_to_string(command_type));
  816. send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
  817. "Command type only valid from server to tor client");
  818. break;
  819. case CONTROL_CMD_FRAGMENTHEADER:
  820. case CONTROL_CMD_FRAGMENT:
  821. log_fn(LOG_WARN, "Recieved command fragment out of order; ignoring.");
  822. send_control_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
  823. default:
  824. log_fn(LOG_WARN, "Received unrecognized command type %d; ignoring.",
  825. (int)command_type);
  826. send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
  827. "Unrecognized command type");
  828. break;
  829. }
  830. tor_free(body);
  831. goto again; /* There might be more data. */
  832. }
  833. /** Something has happened to circuit <b>circ</b>: tell any interested
  834. * control connections. */
  835. int
  836. control_event_circuit_status(circuit_t *circ, circuit_status_event_t tp)
  837. {
  838. char *path, *msg;
  839. size_t path_len;
  840. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  841. return 0;
  842. tor_assert(circ);
  843. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  844. path = circuit_list_path(circ,0);
  845. path_len = strlen(path);
  846. msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
  847. msg[0] = (uint8_t) tp;
  848. set_uint32(msg+1, htonl(circ->global_identifier));
  849. strlcpy(msg+5,path,path_len+1);
  850. send_control_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
  851. tor_free(path);
  852. tor_free(msg);
  853. return 0;
  854. }
  855. /** Something has happened to the stream associated with AP connection
  856. * <b>conn</b>: tell any interested control connections. */
  857. int
  858. control_event_stream_status(connection_t *conn, stream_status_event_t tp)
  859. {
  860. char *msg;
  861. size_t len;
  862. char buf[256], buf2[256];
  863. tor_assert(conn->type == CONN_TYPE_AP);
  864. tor_assert(conn->socks_request);
  865. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  866. return 0;
  867. if (conn->chosen_exit_name)
  868. tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name);
  869. tor_snprintf(buf, sizeof(buf), "%s%s:%d",
  870. conn->socks_request->address,
  871. conn->chosen_exit_name ? buf2 : "",
  872. conn->socks_request->port),
  873. len = strlen(buf);
  874. msg = tor_malloc(5+len+1);
  875. msg[0] = (uint8_t) tp;
  876. set_uint32(msg+1, htonl(conn->global_identifier));
  877. strlcpy(msg+5, buf, len+1);
  878. send_control_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
  879. tor_free(msg);
  880. return 0;
  881. }
  882. /** Something has happened to the OR connection <b>conn</b>: tell any
  883. * interested control connections. */
  884. int
  885. control_event_or_conn_status(connection_t *conn,or_conn_status_event_t tp)
  886. {
  887. char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
  888. size_t len;
  889. tor_assert(conn->type == CONN_TYPE_OR);
  890. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  891. return 0;
  892. buf[0] = (uint8_t)tp;
  893. strlcpy(buf+1,conn->nickname,sizeof(buf)-1);
  894. len = strlen(buf+1);
  895. send_control_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
  896. return 0;
  897. }
  898. /** A second or more has elapsed: tell any interested control
  899. * connections how much bandwidth we used. */
  900. int
  901. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  902. {
  903. char buf[8];
  904. if (!EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED))
  905. return 0;
  906. set_uint32(buf, htonl(n_read));
  907. set_uint32(buf+4, htonl(n_written));
  908. send_control_event(EVENT_BANDWIDTH_USED, 8, buf);
  909. return 0;
  910. }
  911. /** We got a log message: tell any interested control connections. */
  912. void
  913. control_event_logmsg(int severity, const char *msg)
  914. {
  915. size_t len;
  916. if (severity > LOG_NOTICE) /* Less important than notice? ignore for now. */
  917. return;
  918. if (!EVENT_IS_INTERESTING(EVENT_WARNING))
  919. return;
  920. len = strlen(msg);
  921. send_control_event(EVENT_WARNING, (uint32_t)(len+1), msg);
  922. }
  923. /** Called whenever we receive new router descriptors: tell any
  924. * interested control connections. <b>routers</b> is a list of
  925. * DIGEST_LEN-byte identity digests.
  926. */
  927. int control_event_descriptors_changed(smartlist_t *routers)
  928. {
  929. size_t len;
  930. char *msg;
  931. smartlist_t *identities;
  932. char buf[HEX_DIGEST_LEN+1];
  933. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  934. return 0;
  935. identities = smartlist_create();
  936. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  937. {
  938. base16_encode(buf,sizeof(buf),r->identity_digest,DIGEST_LEN);
  939. smartlist_add(identities, tor_strdup(buf));
  940. });
  941. msg = smartlist_join_strings(identities, ",", 1, &len);
  942. send_control_event(EVENT_NEW_DESC, len+1, msg);
  943. SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  944. smartlist_free(identities);
  945. tor_free(msg);
  946. return 0;
  947. }
  948. /** Choose a random authentication cookie and write it to disk.
  949. * Anybody who can read the cookie from disk will be considered
  950. * authorized to use the control connection. */
  951. int
  952. init_cookie_authentication(int enabled)
  953. {
  954. char fname[512];
  955. if (!enabled) {
  956. authentication_cookie_is_set = 0;
  957. return 0;
  958. }
  959. tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
  960. get_options()->DataDirectory);
  961. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  962. authentication_cookie_is_set = 1;
  963. if (write_bytes_to_file(fname, authentication_cookie,
  964. AUTHENTICATION_COOKIE_LEN, 1)) {
  965. log_fn(LOG_WARN,"Error writing authentication cookie.");
  966. return -1;
  967. }
  968. return 0;
  969. }