circuitbuild.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  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. onionskin = payload+2+4;
  365. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN, hop->identity_digest, DIGEST_LEN);
  366. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  367. if(onion_skin_create(router->onion_pkey, &(hop->handshake_state), onionskin) < 0) {
  368. log_fn(LOG_WARN,"onion_skin_create failed.");
  369. return -1;
  370. }
  371. log_fn(LOG_DEBUG,"Sending extend relay cell.");
  372. /* send it to hop->prev, because it will transfer
  373. * it to a create cell and then send to hop */
  374. if(connection_edge_send_command(NULL, circ, RELAY_COMMAND_EXTEND,
  375. payload, payload_len, hop->prev) < 0)
  376. return 0; /* circuit is closed */
  377. hop->state = CPATH_STATE_AWAITING_KEYS;
  378. }
  379. return 0;
  380. }
  381. /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
  382. * sure we're connected to the next hop, and pass it the onion skin in
  383. * a create cell.
  384. */
  385. int circuit_extend(cell_t *cell, circuit_t *circ) {
  386. connection_t *n_conn;
  387. relay_header_t rh;
  388. int old_format;
  389. char *onionskin;
  390. char *id_digest=NULL;
  391. if(circ->n_conn) {
  392. log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
  393. return -1;
  394. }
  395. relay_header_unpack(&rh, cell->payload);
  396. if (rh.length == 4+2+ONIONSKIN_CHALLENGE_LEN) {
  397. /* Once this format is no longer supported, nobody will use
  398. * connection_*_get_by_addr_port. */
  399. old_format = 1;
  400. } else if (rh.length == 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  401. old_format = 0;
  402. } else {
  403. log_fn(LOG_WARN, "Wrong length on extend cell. Closing circuit.");
  404. return -1;
  405. }
  406. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  407. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  408. if (old_format) {
  409. n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
  410. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  411. } else {
  412. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  413. id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
  414. n_conn = connection_get_by_identity_digest(id_digest, CONN_TYPE_OR);
  415. }
  416. if(!n_conn) { /* we should try to open a connection */
  417. /* Note that this will close circuits where the onion has the same
  418. * router twice in a row in the path. I think that's ok.
  419. */
  420. routerinfo_t *router;
  421. struct in_addr in;
  422. in.s_addr = htonl(circ->n_addr);
  423. log_fn(LOG_INFO,"Next router (%s:%d) not connected. Connecting.",
  424. inet_ntoa(in), circ->n_port);
  425. if (old_format) {
  426. router = router_get_by_addr_port(circ->n_addr, circ->n_port);
  427. if(!router) {
  428. log_fn(LOG_INFO,"Next hop is an unknown router. Closing.");
  429. return -1;
  430. }
  431. id_digest = router->identity_digest;
  432. } else { /* new format */
  433. router = router_get_by_digest(id_digest);
  434. #if 0
  435. if(router) { /* addr/port might be different */
  436. circ->n_addr = router->addr;
  437. circ->n_port = router->or_port;
  438. }
  439. #endif
  440. }
  441. tor_assert(id_digest);
  442. memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  443. circ->state = CIRCUIT_STATE_OR_WAIT;
  444. /* imprint the circuit with its future n_conn->id */
  445. memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
  446. n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
  447. if(!n_conn) {
  448. log_fn(LOG_INFO,"Launching n_conn failed. Closing.");
  449. return -1;
  450. }
  451. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  452. /* return success. The onion/circuit/etc will be taken care of automatically
  453. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  454. */
  455. return 0;
  456. }
  457. circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
  458. circ->n_port = n_conn->port;
  459. circ->n_conn = n_conn;
  460. memcpy(circ->n_conn_id_digest, n_conn->identity_digest, DIGEST_LEN);
  461. log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
  462. if(circuit_deliver_create_cell(circ, onionskin) < 0)
  463. return -1;
  464. return 0;
  465. }
  466. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  467. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  468. * used as follows:
  469. * - 20 to initialize f_digest
  470. * - 20 to initialize b_digest
  471. * - 16 to key f_crypto
  472. * - 16 to key b_crypto
  473. *
  474. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  475. */
  476. int circuit_init_cpath_crypto(crypt_path_t *cpath, char *key_data, int reverse)
  477. {
  478. crypto_digest_env_t *tmp_digest;
  479. crypto_cipher_env_t *tmp_crypto;
  480. tor_assert(cpath && key_data);
  481. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  482. cpath->f_digest || cpath->b_digest));
  483. log_fn(LOG_DEBUG,"hop init digest forward 0x%.8x, backward 0x%.8x.",
  484. (unsigned int)*(uint32_t*)key_data, (unsigned int)*(uint32_t*)(key_data+20));
  485. cpath->f_digest = crypto_new_digest_env();
  486. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  487. cpath->b_digest = crypto_new_digest_env();
  488. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  489. log_fn(LOG_DEBUG,"hop init cipher forward 0x%.8x, backward 0x%.8x.",
  490. (unsigned int)*(uint32_t*)(key_data+40), (unsigned int)*(uint32_t*)(key_data+40+16));
  491. if (!(cpath->f_crypto =
  492. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  493. log(LOG_WARN,"forward cipher initialization failed.");
  494. return -1;
  495. }
  496. if (!(cpath->b_crypto =
  497. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  498. log(LOG_WARN,"backward cipher initialization failed.");
  499. return -1;
  500. }
  501. if (reverse) {
  502. tmp_digest = cpath->f_digest;
  503. cpath->f_digest = cpath->b_digest;
  504. cpath->b_digest = tmp_digest;
  505. tmp_crypto = cpath->f_crypto;
  506. cpath->f_crypto = cpath->b_crypto;
  507. cpath->b_crypto = tmp_crypto;
  508. }
  509. return 0;
  510. }
  511. /** A created or extended cell came back to us on the circuit,
  512. * and it included <b>reply</b> (the second DH key, plus KH).
  513. *
  514. * Calculate the appropriate keys and digests, make sure KH is
  515. * correct, and initialize this hop of the cpath.
  516. *
  517. * Return -1 if we want to mark circ for close, else return 0.
  518. */
  519. int circuit_finish_handshake(circuit_t *circ, char *reply) {
  520. unsigned char keys[CPATH_KEY_MATERIAL_LEN];
  521. crypt_path_t *hop;
  522. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  523. if(circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  524. hop = circ->cpath;
  525. else {
  526. for(hop=circ->cpath->next;
  527. hop != circ->cpath && hop->state == CPATH_STATE_OPEN;
  528. hop=hop->next) ;
  529. if(hop == circ->cpath) { /* got an extended when we're all done? */
  530. log_fn(LOG_WARN,"got extended when circ already built? Closing.");
  531. return -1;
  532. }
  533. }
  534. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  535. if(onion_skin_client_handshake(hop->handshake_state, reply, keys,
  536. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  537. log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
  538. return -1;
  539. }
  540. crypto_dh_free(hop->handshake_state); /* don't need it anymore */
  541. hop->handshake_state = NULL;
  542. /* Remember hash of g^xy */
  543. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  544. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  545. return -1;
  546. }
  547. hop->state = CPATH_STATE_OPEN;
  548. log_fn(LOG_INFO,"finished");
  549. circuit_log_path(LOG_INFO,circ);
  550. return 0;
  551. }
  552. /** We received a relay truncated cell on circ.
  553. *
  554. * Since we don't ask for truncates currently, getting a truncated
  555. * means that a connection broke or an extend failed. For now,
  556. * just give up: for circ to close, and return 0.
  557. */
  558. int circuit_truncated(circuit_t *circ, crypt_path_t *layer) {
  559. crypt_path_t *victim;
  560. connection_t *stream;
  561. tor_assert(circ && CIRCUIT_IS_ORIGIN(circ));
  562. tor_assert(layer);
  563. /* XXX Since we don't ask for truncates currently, getting a truncated
  564. * means that a connection broke or an extend failed. For now,
  565. * just give up.
  566. */
  567. circuit_mark_for_close(circ);
  568. return 0;
  569. while(layer->next != circ->cpath) {
  570. /* we need to clear out layer->next */
  571. victim = layer->next;
  572. log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
  573. for(stream = circ->p_streams; stream; stream=stream->next_stream) {
  574. if(stream->cpath_layer == victim) {
  575. log_fn(LOG_INFO, "Marking stream %d for close.", stream->stream_id);
  576. /* no need to send 'end' relay cells,
  577. * because the other side's already dead
  578. */
  579. stream->has_sent_end = 1;
  580. connection_mark_for_close(stream);
  581. }
  582. }
  583. layer->next = victim->next;
  584. circuit_free_cpath_node(victim);
  585. }
  586. log_fn(LOG_INFO, "finished");
  587. return 0;
  588. }
  589. /** Decide whether the first bit of the circuit ID will be
  590. * 0 or 1, to avoid conflicts where each side randomly chooses
  591. * the same circuit ID.
  592. *
  593. * Return CIRC_ID_TYPE_LOWER if local_nick is NULL, or if
  594. * local_nick is lexographically smaller than remote_nick.
  595. * Else return CIRC_ID_TYPE_HIGHER.
  596. */
  597. static int decide_circ_id_type(char *local_nick, char *remote_nick) {
  598. int result;
  599. tor_assert(remote_nick);
  600. if(!local_nick)
  601. return CIRC_ID_TYPE_LOWER;
  602. result = strcasecmp(local_nick, remote_nick);
  603. tor_assert(result);
  604. if(result < 0)
  605. return CIRC_ID_TYPE_LOWER;
  606. return CIRC_ID_TYPE_HIGHER;
  607. }
  608. /** Given a response payload and keys, initialize, then send a created
  609. * cell back.
  610. */
  611. int onionskin_answer(circuit_t *circ, unsigned char *payload, unsigned char *keys) {
  612. cell_t cell;
  613. crypt_path_t *tmp_cpath;
  614. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  615. memset(&cell, 0, sizeof(cell_t));
  616. cell.command = CELL_CREATED;
  617. cell.circ_id = circ->p_circ_id;
  618. circ->state = CIRCUIT_STATE_OPEN;
  619. log_fn(LOG_DEBUG,"Entering.");
  620. memcpy(cell.payload, payload, ONIONSKIN_REPLY_LEN);
  621. log_fn(LOG_INFO,"init digest forward 0x%.8x, backward 0x%.8x.",
  622. (unsigned int)*(uint32_t*)(keys), (unsigned int)*(uint32_t*)(keys+20));
  623. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  624. log_fn(LOG_WARN,"Circuit initialization failed");
  625. tor_free(tmp_cpath);
  626. return -1;
  627. }
  628. circ->n_digest = tmp_cpath->f_digest;
  629. circ->n_crypto = tmp_cpath->f_crypto;
  630. circ->p_digest = tmp_cpath->b_digest;
  631. circ->p_crypto = tmp_cpath->b_crypto;
  632. tor_free(tmp_cpath);
  633. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  634. connection_or_write_cell_to_buf(&cell, circ->p_conn);
  635. log_fn(LOG_DEBUG,"Finished sending 'created' cell.");
  636. return 0;
  637. }
  638. /** Choose a length for a circuit of purpose <b>purpose</b>.
  639. * Default length is 3 + the number of endpoints that would give something
  640. * away. If the routerlist <b>routers</b> doesn't have enough routers
  641. * to handle the desired path length, return as large a path length as
  642. * is feasible, except if it's less than 2, in which case return -1.
  643. */
  644. static int new_route_len(double cw, uint8_t purpose, smartlist_t *routers) {
  645. int num_acceptable_routers;
  646. int routelen;
  647. tor_assert((cw >= 0) && (cw < 1) && routers); /* valid parameters */
  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, *excludedexits;
  705. routerinfo_t *router;
  706. get_connection_array(&carray, &n_connections);
  707. /* Count how many connections are waiting for a circuit to be built.
  708. * We use this for log messages now, but in the future we may depend on it.
  709. */
  710. for (i = 0; i < n_connections; ++i) {
  711. if (carray[i]->type == CONN_TYPE_AP &&
  712. carray[i]->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  713. !carray[i]->marked_for_close &&
  714. !circuit_stream_is_being_handled(carray[i]))
  715. ++n_pending_connections;
  716. }
  717. log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  718. n_pending_connections);
  719. /* Now we count, for each of the routers in the directory, how many
  720. * of the pending connections could possibly exit from that
  721. * router (n_supported[i]). (We can't be sure about cases where we
  722. * don't know the IP address of the pending connection.)
  723. */
  724. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  725. for (i = 0; i < smartlist_len(dir->routers); ++i) { /* iterate over routers */
  726. router = smartlist_get(dir->routers, i);
  727. if(router_is_me(router)) {
  728. n_supported[i] = -1;
  729. log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  730. /* XXX there's probably a reverse predecessor attack here, but
  731. * it's slow. should we take this out? -RD
  732. */
  733. continue;
  734. }
  735. if(!router->is_running) {
  736. n_supported[i] = -1;
  737. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- directory says it's not running.",
  738. router->nickname, i);
  739. continue; /* skip routers that are known to be down */
  740. }
  741. if(!router->is_verified) {
  742. n_supported[i] = -1;
  743. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- unverified router.",
  744. router->nickname, i);
  745. /* XXX008 maybe one day allow unverified routers as exits */
  746. continue; /* skip unverified routers */
  747. }
  748. if(router_exit_policy_rejects_all(router)) {
  749. n_supported[i] = -1;
  750. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  751. router->nickname, i);
  752. continue; /* skip routers that reject all */
  753. }
  754. n_supported[i] = 0;
  755. for (j = 0; j < n_connections; ++j) { /* iterate over connections */
  756. if (carray[j]->type != CONN_TYPE_AP ||
  757. carray[j]->state != AP_CONN_STATE_CIRCUIT_WAIT ||
  758. carray[j]->marked_for_close ||
  759. circuit_stream_is_being_handled(carray[j]))
  760. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  761. if(connection_ap_can_use_exit(carray[j], router)) {
  762. ++n_supported[i];
  763. log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  764. router->nickname, i, n_supported[i]);
  765. } else {
  766. log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  767. router->nickname, i);
  768. }
  769. } /* End looping over connections. */
  770. if (n_supported[i] > best_support) {
  771. /* If this router is better than previous ones, remember its index
  772. * and goodness, and start counting how many routers are this good. */
  773. best_support = n_supported[i]; n_best_support=1;
  774. log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  775. router->nickname);
  776. } else if (n_supported[i] == best_support) {
  777. /* If this router is _as good_ as the best one, just increment the
  778. * count of equally good routers.*/
  779. ++n_best_support;
  780. }
  781. }
  782. log_fn(LOG_INFO, "Found %d servers that might support %d/%d pending connections.",
  783. n_best_support, best_support, n_pending_connections);
  784. preferredexits = smartlist_create();
  785. add_nickname_list_to_smartlist(preferredexits,options.ExitNodes);
  786. excludedexits = smartlist_create();
  787. add_nickname_list_to_smartlist(excludedexits,options.ExcludeNodes);
  788. sl = smartlist_create();
  789. /* If any routers definitely support any pending connections, choose one
  790. * at random. */
  791. if (best_support > 0) {
  792. for (i = 0; i < smartlist_len(dir->routers); i++)
  793. if (n_supported[i] == best_support)
  794. smartlist_add(sl, smartlist_get(dir->routers, i));
  795. smartlist_subtract(sl,excludedexits);
  796. if (smartlist_overlap(sl,preferredexits))
  797. smartlist_intersect(sl,preferredexits);
  798. router = smartlist_choose(sl);
  799. } else {
  800. /* Either there are no pending connections, or no routers even seem to
  801. * possibly support any of them. Choose a router at random. */
  802. if (best_support == -1) {
  803. log(LOG_WARN, "All routers are down or middleman -- choosing a doomed exit at random.");
  804. }
  805. for(i = 0; i < smartlist_len(dir->routers); i++)
  806. if(n_supported[i] != -1)
  807. smartlist_add(sl, smartlist_get(dir->routers, i));
  808. smartlist_subtract(sl,excludedexits);
  809. if (smartlist_overlap(sl,preferredexits))
  810. smartlist_intersect(sl,preferredexits);
  811. router = smartlist_choose(sl);
  812. }
  813. smartlist_free(preferredexits);
  814. smartlist_free(excludedexits);
  815. smartlist_free(sl);
  816. tor_free(n_supported);
  817. if(router) {
  818. log_fn(LOG_INFO, "Chose exit server '%s'", router->nickname);
  819. return router;
  820. }
  821. log_fn(LOG_WARN, "No exit routers seem to be running; can't choose an exit.");
  822. return NULL;
  823. }
  824. /** Return a pointer to a suitable router to be the exit node for the
  825. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  826. * if no router is suitable).
  827. *
  828. * For general-purpose circuits, pass it off to
  829. * choose_good_exit_server_general()
  830. *
  831. * For client-side rendezvous circuits, choose a random node, weighted
  832. * toward the preferences in 'options'.
  833. */
  834. static routerinfo_t *choose_good_exit_server(uint8_t purpose, routerlist_t *dir)
  835. {
  836. routerinfo_t *r;
  837. switch(purpose) {
  838. case CIRCUIT_PURPOSE_C_GENERAL:
  839. return choose_good_exit_server_general(dir);
  840. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  841. r = router_choose_random_node(options.RendNodes, options.RendExcludeNodes, NULL);
  842. return r;
  843. default:
  844. log_fn(LOG_WARN,"unhandled purpose %d", purpose);
  845. tor_assert(0);
  846. }
  847. return NULL; /* never reached */
  848. }
  849. /** Allocate a cpath_build_state_t, populate it based on
  850. * <b>purpose</b> and <b>exit_digest</b> (if specified), and
  851. * return it.
  852. */
  853. static cpath_build_state_t *
  854. onion_new_cpath_build_state(uint8_t purpose, const char *exit_digest)
  855. {
  856. routerlist_t *rl;
  857. int r;
  858. cpath_build_state_t *info;
  859. routerinfo_t *exit;
  860. router_get_routerlist(&rl);
  861. r = new_route_len(options.PathlenCoinWeight, purpose, rl->routers);
  862. if (r < 0)
  863. return NULL;
  864. info = tor_malloc_zero(sizeof(cpath_build_state_t));
  865. info->desired_path_len = r;
  866. if(exit_digest) { /* the circuit-builder pre-requested one */
  867. memcpy(info->chosen_exit_digest, exit_digest, DIGEST_LEN);
  868. exit = router_get_by_digest(exit_digest);
  869. if (exit) {
  870. info->chosen_exit_name = tor_strdup(exit->nickname);
  871. } else {
  872. info->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+1);
  873. base16_encode(info->chosen_exit_name, HEX_DIGEST_LEN+1,
  874. exit_digest, DIGEST_LEN);
  875. }
  876. log_fn(LOG_INFO,"Using requested exit node '%s'", info->chosen_exit_name);
  877. } else { /* we have to decide one */
  878. exit = choose_good_exit_server(purpose, rl);
  879. if(!exit) {
  880. log_fn(LOG_WARN,"failed to choose an exit server");
  881. tor_free(info);
  882. return NULL;
  883. }
  884. memcpy(info->chosen_exit_digest, exit->identity_digest, DIGEST_LEN);
  885. info->chosen_exit_name = tor_strdup(exit->nickname);
  886. }
  887. return info;
  888. }
  889. /** Return the number of routers in <b>routers</b> that are currently up
  890. * and available for building circuits through. Count sets of twins only
  891. * once.
  892. */
  893. static int count_acceptable_routers(smartlist_t *routers) {
  894. int i, j, n;
  895. int num=0;
  896. connection_t *conn;
  897. routerinfo_t *r, *r2;
  898. n = smartlist_len(routers);
  899. for(i=0;i<n;i++) {
  900. r = smartlist_get(routers, i);
  901. log_fn(LOG_DEBUG,"Contemplating whether router %d (%s) is a new option...",
  902. i, r->nickname);
  903. if(r->is_running == 0) {
  904. log_fn(LOG_DEBUG,"Nope, the directory says %d is not running.",i);
  905. goto next_i_loop;
  906. }
  907. if(r->is_verified == 0) {
  908. log_fn(LOG_DEBUG,"Nope, the directory says %d is not verified.",i);
  909. goto next_i_loop; /* XXX008 */
  910. }
  911. if(clique_mode()) {
  912. conn = connection_get_by_identity_digest(r->identity_digest,
  913. CONN_TYPE_OR);
  914. if(!conn || conn->type != CONN_TYPE_OR || conn->state != OR_CONN_STATE_OPEN) {
  915. log_fn(LOG_DEBUG,"Nope, %d is not connected.",i);
  916. goto next_i_loop;
  917. }
  918. }
  919. for(j=0;j<i;j++) {
  920. r2 = smartlist_get(routers, j);
  921. if(!crypto_pk_cmp_keys(r->onion_pkey, r2->onion_pkey)) {
  922. /* these guys are twins. so we've already counted him. */
  923. log_fn(LOG_DEBUG,"Nope, %d is a twin of %d.",i,j);
  924. goto next_i_loop;
  925. }
  926. }
  927. num++;
  928. log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  929. next_i_loop:
  930. ; /* C requires an explicit statement after the label */
  931. }
  932. return num;
  933. }
  934. /** Go through smartlist <b>sl</b> of routers, and remove all elements that
  935. * have the same onion key as twin.
  936. */
  937. static void remove_twins_from_smartlist(smartlist_t *sl, routerinfo_t *twin) {
  938. int i;
  939. routerinfo_t *r;
  940. if(twin == NULL)
  941. return;
  942. for(i=0; i < smartlist_len(sl); i++) {
  943. r = smartlist_get(sl,i);
  944. if (!crypto_pk_cmp_keys(r->onion_pkey, twin->onion_pkey)) {
  945. smartlist_del(sl,i--);
  946. }
  947. }
  948. }
  949. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  950. *
  951. * This function is used to extend cpath by another hop.
  952. */
  953. void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  954. {
  955. if (*head_ptr) {
  956. new_hop->next = (*head_ptr);
  957. new_hop->prev = (*head_ptr)->prev;
  958. (*head_ptr)->prev->next = new_hop;
  959. (*head_ptr)->prev = new_hop;
  960. } else {
  961. *head_ptr = new_hop;
  962. new_hop->prev = new_hop->next = new_hop;
  963. }
  964. }
  965. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  966. * based on <b>state</b>. Add the hop info to head_ptr, and return a
  967. * pointer to the chosen router in <b>router_out</b>.
  968. */
  969. static int
  970. onion_extend_cpath(crypt_path_t **head_ptr, cpath_build_state_t
  971. *state, routerinfo_t **router_out)
  972. {
  973. int cur_len;
  974. crypt_path_t *cpath, *hop;
  975. routerinfo_t *r;
  976. routerinfo_t *choice;
  977. int i;
  978. smartlist_t *sl, *excludednodes;
  979. tor_assert(head_ptr);
  980. tor_assert(router_out);
  981. if (!*head_ptr) {
  982. cur_len = 0;
  983. } else {
  984. cur_len = 1;
  985. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  986. ++cur_len;
  987. }
  988. }
  989. if (cur_len >= state->desired_path_len) {
  990. log_fn(LOG_DEBUG, "Path is complete: %d steps long",
  991. state->desired_path_len);
  992. return 1;
  993. }
  994. log_fn(LOG_DEBUG, "Path is %d long; we want %d", cur_len,
  995. state->desired_path_len);
  996. excludednodes = smartlist_create();
  997. add_nickname_list_to_smartlist(excludednodes,options.ExcludeNodes);
  998. if(cur_len == state->desired_path_len - 1) { /* Picking last node */
  999. log_fn(LOG_DEBUG, "Contemplating last hop: choice already made: %s",
  1000. state->chosen_exit_name);
  1001. choice = router_get_by_digest(state->chosen_exit_digest);
  1002. smartlist_free(excludednodes);
  1003. if(!choice) {
  1004. log_fn(LOG_WARN,"Our chosen exit %s is no longer in the directory? Discarding this circuit.",
  1005. state->chosen_exit_name);
  1006. return -1;
  1007. }
  1008. } else if(cur_len == 0) { /* picking first node */
  1009. /* try the nodes in EntryNodes first */
  1010. sl = smartlist_create();
  1011. add_nickname_list_to_smartlist(sl,options.EntryNodes);
  1012. /* XXX one day, consider picking chosen_exit knowing what's in EntryNodes */
  1013. remove_twins_from_smartlist(sl,router_get_by_digest(state->chosen_exit_digest));
  1014. remove_twins_from_smartlist(sl,router_get_my_routerinfo());
  1015. smartlist_subtract(sl,excludednodes);
  1016. choice = smartlist_choose(sl);
  1017. smartlist_free(sl);
  1018. if(!choice) {
  1019. sl = smartlist_create();
  1020. router_add_running_routers_to_smartlist(sl);
  1021. remove_twins_from_smartlist(sl,router_get_by_digest(state->chosen_exit_digest));
  1022. remove_twins_from_smartlist(sl,router_get_my_routerinfo());
  1023. smartlist_subtract(sl,excludednodes);
  1024. choice = smartlist_choose(sl);
  1025. smartlist_free(sl);
  1026. }
  1027. smartlist_free(excludednodes);
  1028. if(!choice) {
  1029. log_fn(LOG_WARN,"No acceptable routers while picking entry node. Discarding this circuit.");
  1030. return -1;
  1031. }
  1032. } else {
  1033. log_fn(LOG_DEBUG, "Contemplating intermediate hop: random choice.");
  1034. sl = smartlist_create();
  1035. router_add_running_routers_to_smartlist(sl);
  1036. remove_twins_from_smartlist(sl,router_get_by_digest(state->chosen_exit_digest));
  1037. remove_twins_from_smartlist(sl,router_get_my_routerinfo());
  1038. for (i = 0, cpath = *head_ptr; i < cur_len; ++i, cpath=cpath->next) {
  1039. r = router_get_by_digest(cpath->identity_digest);
  1040. tor_assert(r);
  1041. remove_twins_from_smartlist(sl,r);
  1042. }
  1043. smartlist_subtract(sl,excludednodes);
  1044. choice = smartlist_choose(sl);
  1045. smartlist_free(sl);
  1046. smartlist_free(excludednodes);
  1047. if(!choice) {
  1048. log_fn(LOG_WARN,"No acceptable routers while picking intermediate node. Discarding this circuit.");
  1049. return -1;
  1050. }
  1051. }
  1052. log_fn(LOG_DEBUG,"Chose router %s for hop %d (exit is %s)",
  1053. choice->nickname, cur_len, state->chosen_exit_name);
  1054. hop = tor_malloc_zero(sizeof(crypt_path_t));
  1055. /* link hop into the cpath, at the end. */
  1056. onion_append_to_cpath(head_ptr, hop);
  1057. hop->state = CPATH_STATE_CLOSED;
  1058. hop->port = choice->or_port;
  1059. hop->addr = choice->addr;
  1060. memcpy(hop->identity_digest, choice->identity_digest, DIGEST_LEN);
  1061. hop->package_window = CIRCWINDOW_START;
  1062. hop->deliver_window = CIRCWINDOW_START;
  1063. log_fn(LOG_DEBUG, "Extended circuit path with %s for hop %d",
  1064. choice->nickname, cur_len);
  1065. *router_out = choice;
  1066. return 0;
  1067. }
  1068. /*
  1069. Local Variables:
  1070. mode:c
  1071. indent-tabs-mode:nil
  1072. c-basic-offset:2
  1073. End:
  1074. */