circuitbuild.c 40 KB

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