control.c 36 KB

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