circuitbuild.c 40 KB

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