circuitbuild.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. /**
  7. * \file circuitbuild.c
  8. * \brief The actual details of building circuits.
  9. **/
  10. #include "or.h"
  11. /********* START VARIABLES **********/
  12. /** A global list of all circuits at this hop. */
  13. extern circuit_t *global_circuitlist;
  14. /********* END VARIABLES ************/
  15. static int
  16. circuit_deliver_create_cell(circuit_t *circ, char *payload);
  17. static cpath_build_state_t *
  18. onion_new_cpath_build_state(uint8_t purpose, const char *exit_digest);
  19. static int
  20. onion_extend_cpath(crypt_path_t **head_ptr, cpath_build_state_t
  21. *state, routerinfo_t **router_out);
  22. static int decide_circ_id_type(char *local_nick, char *remote_nick);
  23. static int count_acceptable_routers(smartlist_t *routers);
  24. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  25. * and with the high bit specified by circ_id_type (see
  26. * decide_circ_id_type()), until we get a circ_id that is not in use
  27. * by any other circuit on that conn.
  28. *
  29. * Return it, or 0 if can't get a unique circ_id.
  30. */
  31. static uint16_t get_unique_circ_id_by_conn(connection_t *conn) {
  32. uint16_t test_circ_id;
  33. int attempts=0;
  34. uint16_t high_bit;
  35. tor_assert(conn);
  36. tor_assert(conn->type == CONN_TYPE_OR);
  37. high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  38. do {
  39. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  40. * circID such that (high_bit|test_circ_id) is not already used. */
  41. test_circ_id = conn->next_circ_id++;
  42. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  43. test_circ_id = 1;
  44. conn->next_circ_id = 2;
  45. }
  46. if(++attempts > 1<<15) {
  47. /* Make sure we don't loop forever if all circ_id's are used. This
  48. * matters because it's an external DoS vulnerability.
  49. */
  50. log_fn(LOG_WARN,"No unused circ IDs. Failing.");
  51. return 0;
  52. }
  53. test_circ_id |= high_bit;
  54. } while(circuit_get_by_circ_id_conn(test_circ_id, conn));
  55. return test_circ_id;
  56. }
  57. /** Allocate and return a comma-separated list of the currently built
  58. * elements of circuit_t.
  59. */
  60. char *circuit_list_path(circuit_t *circ)
  61. {
  62. struct crypt_path_t *hop;
  63. routerinfo_t *r;
  64. smartlist_t *elements;
  65. char *s;
  66. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  67. tor_assert(circ->cpath);
  68. elements = smartlist_create();
  69. for (hop = circ->cpath; hop; hop = hop->next) {
  70. if (hop->state != CPATH_STATE_OPEN)
  71. break;
  72. if ((r = router_get_by_digest(hop->identity_digest))) {
  73. smartlist_add(elements, tor_strdup(r->nickname));
  74. } else if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  75. smartlist_add(elements, tor_strdup("<rendezvous splice>"));
  76. } else {
  77. s = tor_malloc(HEX_DIGEST_LEN+2);
  78. s[0]='$';
  79. base16_encode(s+1,HEX_DIGEST_LEN+1,hop->identity_digest,DIGEST_LEN);
  80. smartlist_add(elements, s);
  81. }
  82. }
  83. s = smartlist_join_strings(elements, ",", 0, NULL);
  84. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  85. return s;
  86. }
  87. /** Log, at severity <b>severity</b>, the nicknames of each router in
  88. * circ's cpath. Also log the length of the cpath, and the intended
  89. * exit point.
  90. */
  91. void circuit_log_path(int severity, circuit_t *circ) {
  92. char buf[1024];
  93. char *s = buf;
  94. struct crypt_path_t *hop;
  95. const char *states[] = {"closed", "waiting for keys", "open"};
  96. routerinfo_t *router;
  97. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  98. tor_assert(circ->cpath);
  99. tor_snprintf(s, sizeof(buf)-1, "circ (length %d, exit %s): ",
  100. circ->build_state->desired_path_len, circ->build_state->chosen_exit_name);
  101. hop=circ->cpath;
  102. do {
  103. s = buf + strlen(buf);
  104. router = router_get_by_digest(hop->identity_digest);
  105. if(router) {
  106. tor_snprintf(s, sizeof(buf) - (s - buf), "%s(%s) ",
  107. router->nickname, states[hop->state]);
  108. } else {
  109. if(circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  110. tor_snprintf(s, sizeof(buf) - (s - buf), "(rendjoin hop)");
  111. } else {
  112. tor_snprintf(s, sizeof(buf) - (s - buf), "UNKNOWN ");
  113. }
  114. }
  115. hop=hop->next;
  116. } while(hop!=circ->cpath);
  117. log_fn(severity,"%s",buf);
  118. }
  119. /** Tell the rep(utation)hist(ory) module about the status of the links
  120. * in circ. Hops that have become OPEN are marked as successfully
  121. * extended; the _first_ hop that isn't open (if any) is marked as
  122. * unable to extend.
  123. */
  124. void circuit_rep_hist_note_result(circuit_t *circ) {
  125. struct crypt_path_t *hop;
  126. char *prev_digest = NULL;
  127. routerinfo_t *router;
  128. hop = circ->cpath;
  129. if(!hop) {
  130. /* XXX
  131. * if !hop, then we're not the beginning of this circuit.
  132. * for now, just forget about it. later, we should remember when
  133. * extends-through-us failed, too.
  134. */
  135. return;
  136. }
  137. if (server_mode(get_options())) {
  138. routerinfo_t *me = router_get_my_routerinfo();
  139. tor_assert(me);
  140. prev_digest = me->identity_digest;
  141. }
  142. do {
  143. router = router_get_by_digest(hop->identity_digest);
  144. if (router) {
  145. if (prev_digest) {
  146. if (hop->state == CPATH_STATE_OPEN)
  147. rep_hist_note_extend_succeeded(prev_digest, router->identity_digest);
  148. else {
  149. rep_hist_note_extend_failed(prev_digest, router->identity_digest);
  150. break;
  151. }
  152. }
  153. prev_digest = router->identity_digest;
  154. } else {
  155. prev_digest = NULL;
  156. }
  157. hop=hop->next;
  158. } while (hop!=circ->cpath);
  159. }
  160. /** A helper function for circuit_dump_by_conn() below. Log a bunch
  161. * of information about circuit <b>circ</b>.
  162. */
  163. static void
  164. circuit_dump_details(int severity, circuit_t *circ, int poll_index,
  165. const char *type, int this_circid, int other_circid) {
  166. struct crypt_path_t *hop;
  167. log(severity,"Conn %d has %s circuit: circID %d (other side %d), state %d (%s), born %d",
  168. poll_index, type, this_circid, other_circid, circ->state,
  169. circuit_state_to_string[circ->state], (int)circ->timestamp_created);
  170. if(CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  171. if(circ->state == CIRCUIT_STATE_BUILDING)
  172. log(severity,"Building: desired len %d, planned exit node %s.",
  173. circ->build_state->desired_path_len, circ->build_state->chosen_exit_name);
  174. for(hop=circ->cpath;hop->next != circ->cpath; hop=hop->next)
  175. log(severity,"hop: state %d, addr 0x%.8x, port %d", hop->state,
  176. (unsigned int)hop->addr,
  177. (int)hop->port);
  178. }
  179. }
  180. /** Log, at severity <b>severity</b>, information about each circuit
  181. * that is connected to <b>conn</b>.
  182. */
  183. void circuit_dump_by_conn(connection_t *conn, int severity) {
  184. circuit_t *circ;
  185. connection_t *tmpconn;
  186. for(circ=global_circuitlist;circ;circ = circ->next) {
  187. if(circ->p_conn == conn)
  188. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  189. circ->p_circ_id, circ->n_circ_id);
  190. for(tmpconn=circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  191. if(tmpconn == conn) {
  192. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  193. circ->p_circ_id, circ->n_circ_id);
  194. }
  195. }
  196. if(circ->n_conn == conn)
  197. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  198. circ->n_circ_id, circ->p_circ_id);
  199. for(tmpconn=circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  200. if(tmpconn == conn) {
  201. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  202. circ->n_circ_id, circ->p_circ_id);
  203. }
  204. }
  205. }
  206. }
  207. /** Build a new circuit for <b>purpose</b>. If <b>exit_digest</b>
  208. * is defined, then use that as your exit router, else choose a suitable
  209. * exit node.
  210. *
  211. * Also launch a connection to the first OR in the chosen path, if
  212. * it's not open already.
  213. */
  214. circuit_t *circuit_establish_circuit(uint8_t purpose,
  215. const char *exit_digest) {
  216. routerinfo_t *firsthop;
  217. connection_t *n_conn;
  218. circuit_t *circ;
  219. circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
  220. circ->state = CIRCUIT_STATE_OR_WAIT;
  221. circ->build_state = onion_new_cpath_build_state(purpose, exit_digest);
  222. circ->purpose = purpose;
  223. if (! circ->build_state) {
  224. log_fn(LOG_INFO,"Generating cpath failed.");
  225. circuit_mark_for_close(circ);
  226. return NULL;
  227. }
  228. if(onion_extend_cpath(&circ->cpath, circ->build_state, &firsthop)<0 ||
  229. !CIRCUIT_IS_ORIGIN(circ)) {
  230. log_fn(LOG_INFO,"Generating first cpath hop failed.");
  231. circuit_mark_for_close(circ);
  232. return NULL;
  233. }
  234. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED);
  235. /* now see if we're already connected to the first OR in 'route' */
  236. tor_assert(firsthop);
  237. log_fn(LOG_DEBUG,"Looking for firsthop '%s:%u'",
  238. firsthop->address,firsthop->or_port);
  239. /* imprint the circuit with its future n_conn->id */
  240. memcpy(circ->n_conn_id_digest, firsthop->identity_digest, DIGEST_LEN);
  241. n_conn = connection_get_by_identity_digest(firsthop->identity_digest,
  242. CONN_TYPE_OR);
  243. if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) { /* not currently connected */
  244. circ->n_addr = firsthop->addr;
  245. circ->n_port = firsthop->or_port;
  246. if(!n_conn) { /* launch the connection */
  247. n_conn = connection_or_connect(firsthop->addr, firsthop->or_port,
  248. firsthop->identity_digest);
  249. if(!n_conn) { /* connect failed, forget the whole thing */
  250. log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
  251. circuit_mark_for_close(circ);
  252. return NULL;
  253. }
  254. }
  255. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  256. /* return success. The onion/circuit/etc will be taken care of automatically
  257. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  258. */
  259. return circ;
  260. } else { /* it's already open. use it. */
  261. circ->n_addr = n_conn->addr;
  262. circ->n_port = n_conn->port;
  263. circ->n_conn = n_conn;
  264. log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
  265. if(circuit_send_next_onion_skin(circ) < 0) {
  266. log_fn(LOG_INFO,"circuit_send_next_onion_skin failed.");
  267. circuit_mark_for_close(circ);
  268. return NULL;
  269. }
  270. }
  271. return circ;
  272. }
  273. /** Find circuits that are waiting on <b>or_conn</b> to become open,
  274. * if any, and get them to send their create cells forward.
  275. */
  276. void circuit_n_conn_done(connection_t *or_conn, int success) {
  277. circuit_t *circ;
  278. log_fn(LOG_DEBUG,"or_conn to %s, success=%d", or_conn->nickname, success);
  279. for(circ=global_circuitlist;circ;circ = circ->next) {
  280. if (circ->marked_for_close)
  281. continue;
  282. if(!circ->n_conn &&
  283. circ->n_addr == or_conn->addr &&
  284. circ->n_port == or_conn->port &&
  285. !memcmp(or_conn->identity_digest, circ->n_conn_id_digest, DIGEST_LEN)) {
  286. tor_assert(circ->state == CIRCUIT_STATE_OR_WAIT);
  287. if(!success) { /* or_conn failed; close circ */
  288. log_fn(LOG_INFO,"or_conn failed. Closing circ.");
  289. circuit_mark_for_close(circ);
  290. continue;
  291. }
  292. log_fn(LOG_DEBUG,"Found circ %d, sending create cell.", circ->n_circ_id);
  293. circ->n_conn = or_conn;
  294. memcpy(circ->n_conn_id_digest, or_conn->identity_digest, DIGEST_LEN);
  295. if(CIRCUIT_IS_ORIGIN(circ)) {
  296. if(circuit_send_next_onion_skin(circ) < 0) {
  297. log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
  298. circuit_mark_for_close(circ);
  299. continue;
  300. /* XXX could this be bad, eg if next_onion_skin failed because conn died? */
  301. }
  302. } else {
  303. /* pull the create cell out of circ->onionskin, and send it */
  304. if(circuit_deliver_create_cell(circ, circ->onionskin) < 0) {
  305. circuit_mark_for_close(circ);
  306. continue;
  307. }
  308. }
  309. }
  310. }
  311. }
  312. static int
  313. circuit_deliver_create_cell(circuit_t *circ, char *payload) {
  314. int circ_id_type;
  315. cell_t cell;
  316. tor_assert(circ);
  317. tor_assert(circ->n_conn);
  318. tor_assert(circ->n_conn->type == CONN_TYPE_OR);
  319. tor_assert(payload);
  320. circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn);
  321. if(!circ->n_circ_id) {
  322. log_fn(LOG_WARN,"failed to get unique circID.");
  323. return -1;
  324. }
  325. log_fn(LOG_DEBUG,"Chosen circID %u.",circ->n_circ_id);
  326. memset(&cell, 0, sizeof(cell_t));
  327. cell.command = CELL_CREATE;
  328. cell.circ_id = circ->n_circ_id;
  329. memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
  330. connection_or_write_cell_to_buf(&cell, circ->n_conn);
  331. return 0;
  332. }
  333. extern int has_completed_circuit;
  334. /** This is the backbone function for building circuits.
  335. *
  336. * If circ's first hop is closed, then we need to build a create
  337. * cell and send it forward.
  338. *
  339. * Otherwise, we need to build a relay extend cell and send it
  340. * forward.
  341. *
  342. * Return -1 if we want to tear down circ, else return 0.
  343. */
  344. int circuit_send_next_onion_skin(circuit_t *circ) {
  345. crypt_path_t *hop;
  346. routerinfo_t *router;
  347. int r;
  348. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  349. char *onionskin;
  350. size_t payload_len;
  351. tor_assert(circ);
  352. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  353. if(circ->cpath->state == CPATH_STATE_CLOSED) {
  354. log_fn(LOG_DEBUG,"First skin; sending create cell.");
  355. router = router_get_by_digest(circ->n_conn->identity_digest);
  356. if (!router) {
  357. log_fn(LOG_WARN,"Couldn't find routerinfo for %s",
  358. circ->n_conn->nickname);
  359. return -1;
  360. }
  361. if(onion_skin_create(router->onion_pkey,
  362. &(circ->cpath->handshake_state),
  363. payload) < 0) {
  364. log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
  365. return -1;
  366. }
  367. if(circuit_deliver_create_cell(circ, payload) < 0)
  368. return -1;
  369. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  370. circ->state = CIRCUIT_STATE_BUILDING;
  371. log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
  372. } else {
  373. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  374. tor_assert(circ->state == CIRCUIT_STATE_BUILDING);
  375. log_fn(LOG_DEBUG,"starting to send subsequent skin.");
  376. r = onion_extend_cpath(&circ->cpath, circ->build_state, &router);
  377. if (r==1) {
  378. /* done building the circuit. whew. */
  379. circ->state = CIRCUIT_STATE_OPEN;
  380. log_fn(LOG_INFO,"circuit built!");
  381. circuit_reset_failure_count(0);
  382. if(!has_completed_circuit) {
  383. has_completed_circuit=1;
  384. log_fn(LOG_NOTICE,"Tor has successfully opened a circuit. Looks like it's working.");
  385. // XXX008 put a count of known routers here
  386. }
  387. circuit_rep_hist_note_result(circ);
  388. circuit_has_opened(circ); /* do other actions as necessary */
  389. return 0;
  390. } else if (r<0) {
  391. log_fn(LOG_INFO,"Unable to extend circuit path.");
  392. return -1;
  393. }
  394. hop = circ->cpath->prev;
  395. *(uint32_t*)payload = htonl(hop->addr);
  396. *(uint16_t*)(payload+4) = htons(hop->port);
  397. onionskin = payload+2+4;
  398. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN, hop->identity_digest, DIGEST_LEN);
  399. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  400. if(onion_skin_create(router->onion_pkey, &(hop->handshake_state), onionskin) < 0) {
  401. log_fn(LOG_WARN,"onion_skin_create failed.");
  402. return -1;
  403. }
  404. log_fn(LOG_DEBUG,"Sending extend relay cell.");
  405. /* send it to hop->prev, because it will transfer
  406. * it to a create cell and then send to hop */
  407. if(connection_edge_send_command(NULL, circ, RELAY_COMMAND_EXTEND,
  408. payload, payload_len, hop->prev) < 0)
  409. return 0; /* circuit is closed */
  410. hop->state = CPATH_STATE_AWAITING_KEYS;
  411. }
  412. return 0;
  413. }
  414. /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
  415. * sure we're connected to the next hop, and pass it the onion skin in
  416. * a create cell.
  417. */
  418. int circuit_extend(cell_t *cell, circuit_t *circ) {
  419. connection_t *n_conn;
  420. relay_header_t rh;
  421. char *onionskin;
  422. char *id_digest=NULL;
  423. routerinfo_t *router;
  424. if(circ->n_conn) {
  425. log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
  426. return -1;
  427. }
  428. relay_header_unpack(&rh, cell->payload);
  429. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  430. log_fn(LOG_WARN, "Wrong length %d on extend cell. Closing circuit.", rh.length);
  431. return -1;
  432. }
  433. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  434. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  435. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  436. id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
  437. n_conn = connection_get_by_identity_digest(id_digest, CONN_TYPE_OR);
  438. if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) {
  439. /* Note that this will close circuits where the onion has the same
  440. * router twice in a row in the path. I think that's ok.
  441. */
  442. struct in_addr in;
  443. in.s_addr = htonl(circ->n_addr);
  444. log_fn(LOG_INFO,"Next router (%s:%d) not connected. Connecting.",
  445. inet_ntoa(in), circ->n_port);
  446. router = router_get_by_digest(id_digest);
  447. memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  448. circ->state = CIRCUIT_STATE_OR_WAIT;
  449. /* imprint the circuit with its future n_conn->id */
  450. memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
  451. if(n_conn) {
  452. circ->n_addr = n_conn->addr;
  453. circ->n_port = n_conn->port;
  454. } else {
  455. /* we should try to open a connection */
  456. n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
  457. if(!n_conn) {
  458. log_fn(LOG_INFO,"Launching n_conn failed. Closing.");
  459. return -1;
  460. }
  461. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  462. }
  463. /* return success. The onion/circuit/etc will be taken care of automatically
  464. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  465. */
  466. return 0;
  467. }
  468. /* these may be different if the router connected to us from elsewhere */
  469. circ->n_addr = n_conn->addr;
  470. circ->n_port = n_conn->port;
  471. circ->n_conn = n_conn;
  472. memcpy(circ->n_conn_id_digest, n_conn->identity_digest, DIGEST_LEN);
  473. log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
  474. if(circuit_deliver_create_cell(circ, onionskin) < 0)
  475. return -1;
  476. return 0;
  477. }
  478. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  479. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  480. * used as follows:
  481. * - 20 to initialize f_digest
  482. * - 20 to initialize b_digest
  483. * - 16 to key f_crypto
  484. * - 16 to key b_crypto
  485. *
  486. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  487. */
  488. int circuit_init_cpath_crypto(crypt_path_t *cpath, char *key_data, int reverse)
  489. {
  490. crypto_digest_env_t *tmp_digest;
  491. crypto_cipher_env_t *tmp_crypto;
  492. tor_assert(cpath);
  493. tor_assert(key_data);
  494. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  495. cpath->f_digest || cpath->b_digest));
  496. log_fn(LOG_DEBUG,"hop init digest forward 0x%.8x, backward 0x%.8x.",
  497. (unsigned int)*(uint32_t*)key_data, (unsigned int)*(uint32_t*)(key_data+20));
  498. cpath->f_digest = crypto_new_digest_env();
  499. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  500. cpath->b_digest = crypto_new_digest_env();
  501. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  502. log_fn(LOG_DEBUG,"hop init cipher forward 0x%.8x, backward 0x%.8x.",
  503. (unsigned int)*(uint32_t*)(key_data+40), (unsigned int)*(uint32_t*)(key_data+40+16));
  504. if (!(cpath->f_crypto =
  505. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  506. log(LOG_WARN,"forward cipher initialization failed.");
  507. return -1;
  508. }
  509. if (!(cpath->b_crypto =
  510. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  511. log(LOG_WARN,"backward cipher initialization failed.");
  512. return -1;
  513. }
  514. if (reverse) {
  515. tmp_digest = cpath->f_digest;
  516. cpath->f_digest = cpath->b_digest;
  517. cpath->b_digest = tmp_digest;
  518. tmp_crypto = cpath->f_crypto;
  519. cpath->f_crypto = cpath->b_crypto;
  520. cpath->b_crypto = tmp_crypto;
  521. }
  522. return 0;
  523. }
  524. /** A created or extended cell came back to us on the circuit,
  525. * and it included <b>reply</b> (the second DH key, plus KH).
  526. *
  527. * Calculate the appropriate keys and digests, make sure KH is
  528. * correct, and initialize this hop of the cpath.
  529. *
  530. * Return -1 if we want to mark circ for close, else return 0.
  531. */
  532. int circuit_finish_handshake(circuit_t *circ, char *reply) {
  533. unsigned char keys[CPATH_KEY_MATERIAL_LEN];
  534. crypt_path_t *hop;
  535. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  536. if(circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  537. hop = circ->cpath;
  538. else {
  539. for(hop=circ->cpath->next;
  540. hop != circ->cpath && hop->state == CPATH_STATE_OPEN;
  541. hop=hop->next) ;
  542. if(hop == circ->cpath) { /* got an extended when we're all done? */
  543. log_fn(LOG_WARN,"got extended when circ already built? Closing.");
  544. return -1;
  545. }
  546. }
  547. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  548. if(onion_skin_client_handshake(hop->handshake_state, reply, keys,
  549. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  550. log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
  551. return -1;
  552. }
  553. crypto_dh_free(hop->handshake_state); /* don't need it anymore */
  554. hop->handshake_state = NULL;
  555. /* Remember hash of g^xy */
  556. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  557. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  558. return -1;
  559. }
  560. hop->state = CPATH_STATE_OPEN;
  561. log_fn(LOG_INFO,"finished");
  562. circuit_log_path(LOG_INFO,circ);
  563. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED);
  564. return 0;
  565. }
  566. /** We received a relay truncated cell on circ.
  567. *
  568. * Since we don't ask for truncates currently, getting a truncated
  569. * means that a connection broke or an extend failed. For now,
  570. * just give up: for circ to close, and return 0.
  571. */
  572. int circuit_truncated(circuit_t *circ, crypt_path_t *layer) {
  573. // crypt_path_t *victim;
  574. // connection_t *stream;
  575. tor_assert(circ);
  576. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  577. tor_assert(layer);
  578. /* XXX Since we don't ask for truncates currently, getting a truncated
  579. * means that a connection broke or an extend failed. For now,
  580. * just give up.
  581. */
  582. circuit_mark_for_close(circ);
  583. return 0;
  584. #if 0
  585. while(layer->next != circ->cpath) {
  586. /* we need to clear out layer->next */
  587. victim = layer->next;
  588. log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
  589. for(stream = circ->p_streams; stream; stream=stream->next_stream) {
  590. if(stream->cpath_layer == victim) {
  591. log_fn(LOG_INFO, "Marking stream %d for close.", stream->stream_id);
  592. /* no need to send 'end' relay cells,
  593. * because the other side's already dead
  594. */
  595. stream->has_sent_end = 1;
  596. connection_mark_for_close(stream);
  597. }
  598. }
  599. layer->next = victim->next;
  600. circuit_free_cpath_node(victim);
  601. }
  602. log_fn(LOG_INFO, "finished");
  603. return 0;
  604. #endif
  605. }
  606. /** Given a response payload and keys, initialize, then send a created
  607. * cell back.
  608. */
  609. int onionskin_answer(circuit_t *circ, unsigned char *payload, unsigned char *keys) {
  610. cell_t cell;
  611. crypt_path_t *tmp_cpath;
  612. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  613. memset(&cell, 0, sizeof(cell_t));
  614. cell.command = CELL_CREATED;
  615. cell.circ_id = circ->p_circ_id;
  616. circ->state = CIRCUIT_STATE_OPEN;
  617. log_fn(LOG_DEBUG,"Entering.");
  618. memcpy(cell.payload, payload, ONIONSKIN_REPLY_LEN);
  619. log_fn(LOG_INFO,"init digest forward 0x%.8x, backward 0x%.8x.",
  620. (unsigned int)*(uint32_t*)(keys), (unsigned int)*(uint32_t*)(keys+20));
  621. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  622. log_fn(LOG_WARN,"Circuit initialization failed");
  623. tor_free(tmp_cpath);
  624. return -1;
  625. }
  626. circ->n_digest = tmp_cpath->f_digest;
  627. circ->n_crypto = tmp_cpath->f_crypto;
  628. circ->p_digest = tmp_cpath->b_digest;
  629. circ->p_crypto = tmp_cpath->b_crypto;
  630. tor_free(tmp_cpath);
  631. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  632. connection_or_write_cell_to_buf(&cell, circ->p_conn);
  633. log_fn(LOG_DEBUG,"Finished sending 'created' cell.");
  634. return 0;
  635. }
  636. /** Choose a length for a circuit of purpose <b>purpose</b>.
  637. * Default length is 3 + the number of endpoints that would give something
  638. * away. If the routerlist <b>routers</b> doesn't have enough routers
  639. * to handle the desired path length, return as large a path length as
  640. * is feasible, except if it's less than 2, in which case return -1.
  641. */
  642. static int new_route_len(double cw, uint8_t purpose, smartlist_t *routers) {
  643. int num_acceptable_routers;
  644. int routelen;
  645. tor_assert(cw >= 0.);
  646. tor_assert(cw < 1.);
  647. tor_assert(routers);
  648. #ifdef TOR_PERF
  649. routelen = 2;
  650. #else
  651. if(purpose == CIRCUIT_PURPOSE_C_GENERAL)
  652. routelen = 3;
  653. else if(purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
  654. routelen = 4;
  655. else if(purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
  656. routelen = 3;
  657. else if(purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  658. routelen = 3;
  659. else if(purpose == CIRCUIT_PURPOSE_S_CONNECT_REND)
  660. routelen = 4;
  661. else {
  662. log_fn(LOG_WARN,"Unhandled purpose %d", purpose);
  663. return -1;
  664. }
  665. #endif
  666. #if 0
  667. for(routelen = 3; ; routelen++) { /* 3, increment until coinflip says we're done */
  668. if (crypto_pseudo_rand_int(255) >= cw*255) /* don't extend */
  669. break;
  670. }
  671. #endif
  672. log_fn(LOG_DEBUG,"Chosen route length %d (%d routers available).",routelen,
  673. smartlist_len(routers));
  674. num_acceptable_routers = count_acceptable_routers(routers);
  675. if(num_acceptable_routers < 2) {
  676. log_fn(LOG_INFO,"Not enough acceptable routers (%d). Discarding this circuit.",
  677. num_acceptable_routers);
  678. return -1;
  679. }
  680. if(num_acceptable_routers < routelen) {
  681. log_fn(LOG_INFO,"Not enough routers: cutting routelen from %d to %d.",
  682. routelen, num_acceptable_routers);
  683. routelen = num_acceptable_routers;
  684. }
  685. return routelen;
  686. }
  687. /** Return a pointer to a suitable router to be the exit node for the
  688. * general-purpose circuit we're about to build.
  689. *
  690. * Look through the connection array, and choose a router that maximizes
  691. * the number of pending streams that can exit from this router.
  692. *
  693. * Return NULL if we can't find any suitable routers.
  694. */
  695. static routerinfo_t *choose_good_exit_server_general(routerlist_t *dir)
  696. {
  697. int *n_supported;
  698. int i, j;
  699. int n_pending_connections = 0;
  700. connection_t **carray;
  701. int n_connections;
  702. int best_support = -1;
  703. int n_best_support=0;
  704. smartlist_t *sl, *preferredexits, *preferredentries, *excludedexits;
  705. routerinfo_t *router;
  706. or_options_t *options = get_options();
  707. preferredentries = smartlist_create();
  708. add_nickname_list_to_smartlist(preferredentries,options->EntryNodes,1);
  709. get_connection_array(&carray, &n_connections);
  710. /* Count how many connections are waiting for a circuit to be built.
  711. * We use this for log messages now, but in the future we may depend on it.
  712. */
  713. for (i = 0; i < n_connections; ++i) {
  714. if (carray[i]->type == CONN_TYPE_AP &&
  715. carray[i]->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  716. !carray[i]->marked_for_close &&
  717. !circuit_stream_is_being_handled(carray[i]))
  718. ++n_pending_connections;
  719. }
  720. log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  721. n_pending_connections);
  722. /* Now we count, for each of the routers in the directory, how many
  723. * of the pending connections could possibly exit from that
  724. * router (n_supported[i]). (We can't be sure about cases where we
  725. * don't know the IP address of the pending connection.)
  726. */
  727. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  728. for (i = 0; i < smartlist_len(dir->routers); ++i) { /* iterate over routers */
  729. router = smartlist_get(dir->routers, i);
  730. if(router_is_me(router)) {
  731. n_supported[i] = -1;
  732. log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  733. /* XXX there's probably a reverse predecessor attack here, but
  734. * it's slow. should we take this out? -RD
  735. */
  736. continue;
  737. }
  738. if(!router->is_running) {
  739. n_supported[i] = -1;
  740. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- directory says it's not running.",
  741. router->nickname, i);
  742. continue; /* skip routers that are known to be down */
  743. }
  744. if(!router->is_verified &&
  745. (!(options->_AllowUnverified & ALLOW_UNVERIFIED_EXIT) ||
  746. router_is_unreliable_router(router, 1, 1))) {
  747. /* if it's unverified, and either we don't want it or it's unsuitable */
  748. n_supported[i] = -1;
  749. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- unverified router.",
  750. router->nickname, i);
  751. continue; /* skip unverified routers */
  752. }
  753. if(router_exit_policy_rejects_all(router)) {
  754. n_supported[i] = -1;
  755. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  756. router->nickname, i);
  757. continue; /* skip routers that reject all */
  758. }
  759. if(smartlist_len(preferredentries)==1 &&
  760. router == (routerinfo_t*)smartlist_get(preferredentries, 0)) {
  761. n_supported[i] = -1;
  762. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it's our only preferred entry node.", router->nickname, i);
  763. continue;
  764. }
  765. n_supported[i] = 0;
  766. for (j = 0; j < n_connections; ++j) { /* iterate over connections */
  767. if (carray[j]->type != CONN_TYPE_AP ||
  768. carray[j]->state != AP_CONN_STATE_CIRCUIT_WAIT ||
  769. carray[j]->marked_for_close ||
  770. circuit_stream_is_being_handled(carray[j]))
  771. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  772. if(connection_ap_can_use_exit(carray[j], router)) {
  773. ++n_supported[i];
  774. log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  775. router->nickname, i, n_supported[i]);
  776. } else {
  777. log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  778. router->nickname, i);
  779. }
  780. } /* End looping over connections. */
  781. if (n_supported[i] > best_support) {
  782. /* If this router is better than previous ones, remember its index
  783. * and goodness, and start counting how many routers are this good. */
  784. best_support = n_supported[i]; n_best_support=1;
  785. log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  786. router->nickname);
  787. } else if (n_supported[i] == best_support) {
  788. /* If this router is _as good_ as the best one, just increment the
  789. * count of equally good routers.*/
  790. ++n_best_support;
  791. }
  792. }
  793. log_fn(LOG_INFO, "Found %d servers that might support %d/%d pending connections.",
  794. n_best_support, best_support, n_pending_connections);
  795. preferredexits = smartlist_create();
  796. add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1);
  797. excludedexits = smartlist_create();
  798. add_nickname_list_to_smartlist(excludedexits,options->ExcludeNodes,0);
  799. sl = smartlist_create();
  800. /* If any routers definitely support any pending connections, choose one
  801. * at random. */
  802. if (best_support > 0) {
  803. for (i = 0; i < smartlist_len(dir->routers); i++)
  804. if (n_supported[i] == best_support)
  805. smartlist_add(sl, smartlist_get(dir->routers, i));
  806. smartlist_subtract(sl,excludedexits);
  807. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  808. smartlist_intersect(sl,preferredexits);
  809. router = routerlist_sl_choose_by_bandwidth(sl);
  810. } else {
  811. /* Either there are no pending connections, or no routers even seem to
  812. * possibly support any of them. Choose a router at random. */
  813. if (best_support == -1) {
  814. log(LOG_WARN, "All routers are down or middleman -- choosing a doomed exit at random.");
  815. }
  816. for(i = 0; i < smartlist_len(dir->routers); i++)
  817. if(n_supported[i] != -1)
  818. smartlist_add(sl, smartlist_get(dir->routers, i));
  819. smartlist_subtract(sl,excludedexits);
  820. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  821. smartlist_intersect(sl,preferredexits);
  822. router = routerlist_sl_choose_by_bandwidth(sl);
  823. }
  824. smartlist_free(preferredexits);
  825. smartlist_free(preferredentries);
  826. smartlist_free(excludedexits);
  827. smartlist_free(sl);
  828. tor_free(n_supported);
  829. if(router) {
  830. log_fn(LOG_INFO, "Chose exit server '%s'", router->nickname);
  831. return router;
  832. }
  833. if (options->StrictExitNodes)
  834. log_fn(LOG_WARN, "No exit routers seem to be running; can't choose an exit.");
  835. return NULL;
  836. }
  837. /** Return a pointer to a suitable router to be the exit node for the
  838. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  839. * if no router is suitable).
  840. *
  841. * For general-purpose circuits, pass it off to
  842. * choose_good_exit_server_general()
  843. *
  844. * For client-side rendezvous circuits, choose a random node, weighted
  845. * toward the preferences in 'options'.
  846. */
  847. static routerinfo_t *choose_good_exit_server(uint8_t purpose, routerlist_t *dir)
  848. {
  849. routerinfo_t *r;
  850. or_options_t *options = get_options();
  851. switch(purpose) {
  852. case CIRCUIT_PURPOSE_C_GENERAL:
  853. return choose_good_exit_server_general(dir);
  854. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  855. r = router_choose_random_node(options->RendNodes, options->RendExcludeNodes,
  856. NULL, 0, 1, options->_AllowUnverified & ALLOW_UNVERIFIED_RENDEZVOUS, 0);
  857. return r;
  858. }
  859. log_fn(LOG_WARN,"Unhandled purpose %d", purpose);
  860. return NULL;
  861. }
  862. /** Allocate a cpath_build_state_t, populate it based on
  863. * <b>purpose</b> and <b>exit_digest</b> (if specified), and
  864. * return it.
  865. */
  866. static cpath_build_state_t *
  867. onion_new_cpath_build_state(uint8_t purpose, const char *exit_digest)
  868. {
  869. routerlist_t *rl;
  870. int r;
  871. cpath_build_state_t *info;
  872. routerinfo_t *exit;
  873. router_get_routerlist(&rl);
  874. if (!rl)
  875. return NULL;
  876. r = new_route_len(get_options()->PathlenCoinWeight, purpose, rl->routers);
  877. if (r < 1) /* must be at least 1 */
  878. return NULL;
  879. info = tor_malloc_zero(sizeof(cpath_build_state_t));
  880. info->desired_path_len = r;
  881. if(exit_digest) { /* the circuit-builder pre-requested one */
  882. memcpy(info->chosen_exit_digest, exit_digest, DIGEST_LEN);
  883. exit = router_get_by_digest(exit_digest);
  884. if (exit) {
  885. info->chosen_exit_name = tor_strdup(exit->nickname);
  886. } else {
  887. info->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+1);
  888. base16_encode(info->chosen_exit_name, HEX_DIGEST_LEN+1,
  889. exit_digest, DIGEST_LEN);
  890. }
  891. log_fn(LOG_INFO,"Using requested exit node '%s'", info->chosen_exit_name);
  892. } else { /* we have to decide one */
  893. exit = choose_good_exit_server(purpose, rl);
  894. if(!exit) {
  895. log_fn(LOG_WARN,"failed to choose an exit server");
  896. tor_free(info);
  897. return NULL;
  898. }
  899. memcpy(info->chosen_exit_digest, exit->identity_digest, DIGEST_LEN);
  900. info->chosen_exit_name = tor_strdup(exit->nickname);
  901. }
  902. return info;
  903. }
  904. /** Return the number of routers in <b>routers</b> that are currently up
  905. * and available for building circuits through.
  906. */
  907. static int count_acceptable_routers(smartlist_t *routers) {
  908. int i, n;
  909. int num=0;
  910. routerinfo_t *r;
  911. n = smartlist_len(routers);
  912. for(i=0;i<n;i++) {
  913. r = smartlist_get(routers, i);
  914. log_fn(LOG_DEBUG,"Contemplating whether router %d (%s) is a new option...",
  915. i, r->nickname);
  916. if(r->is_running == 0) {
  917. log_fn(LOG_DEBUG,"Nope, the directory says %d is not running.",i);
  918. goto next_i_loop;
  919. }
  920. if(r->is_verified == 0) {
  921. log_fn(LOG_DEBUG,"Nope, the directory says %d is not verified.",i);
  922. /* XXXX009 But unverified routers *are* sometimes acceptable. */
  923. goto next_i_loop;
  924. }
  925. num++;
  926. log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  927. next_i_loop:
  928. ; /* C requires an explicit statement after the label */
  929. }
  930. return num;
  931. }
  932. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  933. *
  934. * This function is used to extend cpath by another hop.
  935. */
  936. void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  937. {
  938. if (*head_ptr) {
  939. new_hop->next = (*head_ptr);
  940. new_hop->prev = (*head_ptr)->prev;
  941. (*head_ptr)->prev->next = new_hop;
  942. (*head_ptr)->prev = new_hop;
  943. } else {
  944. *head_ptr = new_hop;
  945. new_hop->prev = new_hop->next = new_hop;
  946. }
  947. }
  948. static routerinfo_t *choose_good_middle_server(cpath_build_state_t *state,
  949. crypt_path_t *head,
  950. int cur_len)
  951. {
  952. int i;
  953. routerinfo_t *r, *choice;
  954. crypt_path_t *cpath;
  955. smartlist_t *excluded = smartlist_create();
  956. log_fn(LOG_DEBUG, "Contemplating intermediate hop: random choice.");
  957. excluded = smartlist_create();
  958. if((r = router_get_by_digest(state->chosen_exit_digest))) {
  959. smartlist_add(excluded, r);
  960. routerlist_add_family(excluded, r);
  961. }
  962. if((r = routerlist_find_my_routerinfo())) {
  963. smartlist_add(excluded, r);
  964. routerlist_add_family(excluded, r);
  965. }
  966. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  967. if((r = router_get_by_digest(cpath->identity_digest))) {
  968. smartlist_add(excluded, r);
  969. routerlist_add_family(excluded, r);
  970. }
  971. }
  972. choice = router_choose_random_node(NULL, get_options()->ExcludeNodes, excluded,
  973. 0, 1, get_options()->_AllowUnverified & ALLOW_UNVERIFIED_MIDDLE, 0);
  974. smartlist_free(excluded);
  975. return choice;
  976. }
  977. static routerinfo_t *choose_good_entry_server(cpath_build_state_t *state)
  978. {
  979. routerinfo_t *r, *choice;
  980. smartlist_t *excluded = smartlist_create();
  981. or_options_t *options = get_options();
  982. char buf[16];
  983. if((r = router_get_by_digest(state->chosen_exit_digest))) {
  984. smartlist_add(excluded, r);
  985. routerlist_add_family(excluded, r);
  986. }
  987. if((r = routerlist_find_my_routerinfo())) {
  988. smartlist_add(excluded, r);
  989. routerlist_add_family(excluded, r);
  990. }
  991. if(options->FascistFirewall) {
  992. /* exclude all ORs that listen on the wrong port */
  993. routerlist_t *rl;
  994. int i;
  995. router_get_routerlist(&rl);
  996. if(!rl)
  997. return NULL;
  998. for(i=0; i < smartlist_len(rl->routers); i++) {
  999. r = smartlist_get(rl->routers, i);
  1000. tor_snprintf(buf, sizeof(buf), "%d", r->or_port);
  1001. if (!smartlist_string_isin(options->FirewallPorts, buf))
  1002. smartlist_add(excluded, r);
  1003. }
  1004. }
  1005. choice = router_choose_random_node(options->EntryNodes, options->ExcludeNodes,
  1006. excluded, 0, 1, options->_AllowUnverified & ALLOW_UNVERIFIED_ENTRY,
  1007. options->StrictEntryNodes);
  1008. smartlist_free(excluded);
  1009. return choice;
  1010. }
  1011. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1012. * based on <b>state</b>. Add the hop info to head_ptr, and return a
  1013. * pointer to the chosen router in <b>router_out</b>.
  1014. */
  1015. static int
  1016. onion_extend_cpath(crypt_path_t **head_ptr, cpath_build_state_t
  1017. *state, routerinfo_t **router_out)
  1018. {
  1019. int cur_len;
  1020. crypt_path_t *cpath, *hop;
  1021. routerinfo_t *choice;
  1022. smartlist_t *excludednodes;
  1023. tor_assert(head_ptr);
  1024. tor_assert(router_out);
  1025. if (!*head_ptr) {
  1026. cur_len = 0;
  1027. } else {
  1028. cur_len = 1;
  1029. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  1030. ++cur_len;
  1031. }
  1032. }
  1033. if (cur_len >= state->desired_path_len) {
  1034. log_fn(LOG_DEBUG, "Path is complete: %d steps long",
  1035. state->desired_path_len);
  1036. return 1;
  1037. }
  1038. log_fn(LOG_DEBUG, "Path is %d long; we want %d", cur_len,
  1039. state->desired_path_len);
  1040. excludednodes = smartlist_create();
  1041. add_nickname_list_to_smartlist(excludednodes,get_options()->ExcludeNodes,0);
  1042. if(cur_len == state->desired_path_len - 1) { /* Picking last node */
  1043. choice = router_get_by_digest(state->chosen_exit_digest);
  1044. } else if(cur_len == 0) { /* picking first node */
  1045. choice = choose_good_entry_server(state);
  1046. } else {
  1047. choice = choose_good_middle_server(state, *head_ptr, cur_len);
  1048. }
  1049. smartlist_free(excludednodes);
  1050. if(!choice) {
  1051. log_fn(LOG_WARN,"Failed to find node for hop %d of our path. Discarding this circuit.", cur_len);
  1052. return -1;
  1053. }
  1054. log_fn(LOG_DEBUG,"Chose router %s for hop %d (exit is %s)",
  1055. choice->nickname, cur_len+1, state->chosen_exit_name);
  1056. hop = tor_malloc_zero(sizeof(crypt_path_t));
  1057. /* link hop into the cpath, at the end. */
  1058. onion_append_to_cpath(head_ptr, hop);
  1059. hop->state = CPATH_STATE_CLOSED;
  1060. hop->port = choice->or_port;
  1061. hop->addr = choice->addr;
  1062. memcpy(hop->identity_digest, choice->identity_digest, DIGEST_LEN);
  1063. hop->package_window = CIRCWINDOW_START;
  1064. hop->deliver_window = CIRCWINDOW_START;
  1065. log_fn(LOG_DEBUG, "Extended circuit path with %s for hop %d",
  1066. choice->nickname, cur_len+1);
  1067. *router_out = choice;
  1068. return 0;
  1069. }
  1070. /*
  1071. Local Variables:
  1072. mode:c
  1073. indent-tabs-mode:nil
  1074. c-basic-offset:2
  1075. End:
  1076. */