circuitbuild.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  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. // XXX008 put a count of known routers here
  354. }
  355. circuit_rep_hist_note_result(circ);
  356. circuit_has_opened(circ); /* do other actions as necessary */
  357. return 0;
  358. } else if (r<0) {
  359. log_fn(LOG_INFO,"Unable to extend circuit path.");
  360. return -1;
  361. }
  362. hop = circ->cpath->prev;
  363. *(uint32_t*)payload = htonl(hop->addr);
  364. *(uint16_t*)(payload+4) = htons(hop->port);
  365. onionskin = payload+2+4;
  366. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN, hop->identity_digest, DIGEST_LEN);
  367. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  368. if(onion_skin_create(router->onion_pkey, &(hop->handshake_state), onionskin) < 0) {
  369. log_fn(LOG_WARN,"onion_skin_create failed.");
  370. return -1;
  371. }
  372. log_fn(LOG_DEBUG,"Sending extend relay cell.");
  373. /* send it to hop->prev, because it will transfer
  374. * it to a create cell and then send to hop */
  375. if(connection_edge_send_command(NULL, circ, RELAY_COMMAND_EXTEND,
  376. payload, payload_len, hop->prev) < 0)
  377. return 0; /* circuit is closed */
  378. hop->state = CPATH_STATE_AWAITING_KEYS;
  379. }
  380. return 0;
  381. }
  382. /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
  383. * sure we're connected to the next hop, and pass it the onion skin in
  384. * a create cell.
  385. */
  386. int circuit_extend(cell_t *cell, circuit_t *circ) {
  387. connection_t *n_conn;
  388. relay_header_t rh;
  389. int old_format;
  390. char *onionskin;
  391. char *id_digest=NULL;
  392. if(circ->n_conn) {
  393. log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
  394. return -1;
  395. }
  396. relay_header_unpack(&rh, cell->payload);
  397. if (rh.length == 4+2+ONIONSKIN_CHALLENGE_LEN) {
  398. old_format = 1;
  399. } else if (rh.length == 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  400. old_format = 0;
  401. } else {
  402. log_fn(LOG_WARN, "Wrong length %d on extend cell. Closing circuit.", rh.length);
  403. return -1;
  404. }
  405. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  406. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  407. if (old_format) {
  408. n_conn = connection_exact_get_by_addr_port(circ->n_addr,circ->n_port);
  409. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  410. } else {
  411. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  412. id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
  413. n_conn = connection_get_by_identity_digest(id_digest, CONN_TYPE_OR);
  414. }
  415. if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) {
  416. /* Note that this will close circuits where the onion has the same
  417. * router twice in a row in the path. I think that's ok.
  418. */
  419. routerinfo_t *router;
  420. struct in_addr in;
  421. in.s_addr = htonl(circ->n_addr);
  422. log_fn(LOG_INFO,"Next router (%s:%d) not connected. Connecting.",
  423. inet_ntoa(in), circ->n_port);
  424. if (old_format) {
  425. router = router_get_by_addr_port(circ->n_addr, circ->n_port);
  426. if(!router) {
  427. log_fn(LOG_WARN,"Next hop is an unknown router. Closing.");
  428. return -1;
  429. }
  430. id_digest = router->identity_digest;
  431. } else { /* new format */
  432. router = router_get_by_digest(id_digest);
  433. }
  434. tor_assert(id_digest);
  435. memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  436. circ->state = CIRCUIT_STATE_OR_WAIT;
  437. /* imprint the circuit with its future n_conn->id */
  438. memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
  439. if(n_conn) {
  440. circ->n_addr = n_conn->addr;
  441. circ->n_port = n_conn->port;
  442. } else {
  443. /* we should try to open a connection */
  444. n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
  445. if(!n_conn) {
  446. log_fn(LOG_INFO,"Launching n_conn failed. Closing.");
  447. return -1;
  448. }
  449. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  450. }
  451. /* return success. The onion/circuit/etc will be taken care of automatically
  452. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  453. */
  454. return 0;
  455. }
  456. /* these may be different if the router connected to us from elsewhere */
  457. circ->n_addr = n_conn->addr;
  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. !(options._AllowUnverified & ALLOW_UNVERIFIED_EXIT)) {
  743. n_supported[i] = -1;
  744. log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- unverified router.",
  745. router->nickname, i);
  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 (options.StrictExitNodes || 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 (options.StrictExitNodes || 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. if (options.StrictExitNodes)
  822. log_fn(LOG_WARN, "No exit routers seem to be running; can't choose an exit.");
  823. return NULL;
  824. }
  825. /** Return a pointer to a suitable router to be the exit node for the
  826. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  827. * if no router is suitable).
  828. *
  829. * For general-purpose circuits, pass it off to
  830. * choose_good_exit_server_general()
  831. *
  832. * For client-side rendezvous circuits, choose a random node, weighted
  833. * toward the preferences in 'options'.
  834. */
  835. static routerinfo_t *choose_good_exit_server(uint8_t purpose, routerlist_t *dir)
  836. {
  837. routerinfo_t *r;
  838. /* XXX one day, consider picking chosen_exit knowing what's in EntryNodes */
  839. switch(purpose) {
  840. case CIRCUIT_PURPOSE_C_GENERAL:
  841. return choose_good_exit_server_general(dir);
  842. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  843. r = router_choose_random_node(options.RendNodes, options.RendExcludeNodes,
  844. NULL, 0, 1, options._AllowUnverified & ALLOW_UNVERIFIED_RENDEZVOUS, 0);
  845. return r;
  846. default:
  847. log_fn(LOG_WARN,"unhandled purpose %d", purpose);
  848. tor_assert(0);
  849. }
  850. return NULL; /* never reached */
  851. }
  852. /** Allocate a cpath_build_state_t, populate it based on
  853. * <b>purpose</b> and <b>exit_digest</b> (if specified), and
  854. * return it.
  855. */
  856. static cpath_build_state_t *
  857. onion_new_cpath_build_state(uint8_t purpose, const char *exit_digest)
  858. {
  859. routerlist_t *rl;
  860. int r;
  861. cpath_build_state_t *info;
  862. routerinfo_t *exit;
  863. router_get_routerlist(&rl);
  864. r = new_route_len(options.PathlenCoinWeight, purpose, rl->routers);
  865. if (r < 0)
  866. return NULL;
  867. info = tor_malloc_zero(sizeof(cpath_build_state_t));
  868. info->desired_path_len = r;
  869. if(exit_digest) { /* the circuit-builder pre-requested one */
  870. memcpy(info->chosen_exit_digest, exit_digest, DIGEST_LEN);
  871. exit = router_get_by_digest(exit_digest);
  872. if (exit) {
  873. info->chosen_exit_name = tor_strdup(exit->nickname);
  874. } else {
  875. info->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+1);
  876. base16_encode(info->chosen_exit_name, HEX_DIGEST_LEN+1,
  877. exit_digest, DIGEST_LEN);
  878. }
  879. log_fn(LOG_INFO,"Using requested exit node '%s'", info->chosen_exit_name);
  880. } else { /* we have to decide one */
  881. exit = choose_good_exit_server(purpose, rl);
  882. if(!exit) {
  883. log_fn(LOG_WARN,"failed to choose an exit server");
  884. tor_free(info);
  885. return NULL;
  886. }
  887. memcpy(info->chosen_exit_digest, exit->identity_digest, DIGEST_LEN);
  888. info->chosen_exit_name = tor_strdup(exit->nickname);
  889. }
  890. return info;
  891. }
  892. /** Return the number of routers in <b>routers</b> that are currently up
  893. * and available for building circuits through. Count sets of twins only
  894. * once.
  895. */
  896. static int count_acceptable_routers(smartlist_t *routers) {
  897. int i, j, n;
  898. int num=0;
  899. connection_t *conn;
  900. routerinfo_t *r, *r2;
  901. n = smartlist_len(routers);
  902. for(i=0;i<n;i++) {
  903. r = smartlist_get(routers, i);
  904. log_fn(LOG_DEBUG,"Contemplating whether router %d (%s) is a new option...",
  905. i, r->nickname);
  906. if(r->is_running == 0) {
  907. log_fn(LOG_DEBUG,"Nope, the directory says %d is not running.",i);
  908. goto next_i_loop;
  909. }
  910. if(r->is_verified == 0) {
  911. log_fn(LOG_DEBUG,"Nope, the directory says %d is not verified.",i);
  912. goto next_i_loop; /* XXX008 */
  913. }
  914. if(clique_mode()) {
  915. conn = connection_get_by_identity_digest(r->identity_digest,
  916. CONN_TYPE_OR);
  917. if(!conn || conn->state != OR_CONN_STATE_OPEN) {
  918. log_fn(LOG_DEBUG,"Nope, %d is not connected.",i);
  919. goto next_i_loop;
  920. }
  921. }
  922. for(j=0;j<i;j++) {
  923. r2 = smartlist_get(routers, j);
  924. if(!crypto_pk_cmp_keys(r->onion_pkey, r2->onion_pkey)) {
  925. /* these guys are twins. so we've already counted him. */
  926. log_fn(LOG_DEBUG,"Nope, %d is a twin of %d.",i,j);
  927. goto next_i_loop;
  928. }
  929. }
  930. num++;
  931. log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  932. next_i_loop:
  933. ; /* C requires an explicit statement after the label */
  934. }
  935. return num;
  936. }
  937. #if 0
  938. /** Go through smartlist <b>sl</b> of routers, and remove all elements that
  939. * have the same onion key as twin.
  940. */
  941. static void remove_twins_from_smartlist(smartlist_t *sl, routerinfo_t *twin) {
  942. int i;
  943. routerinfo_t *r;
  944. if(twin == NULL)
  945. return;
  946. for(i=0; i < smartlist_len(sl); i++) {
  947. r = smartlist_get(sl,i);
  948. if (!crypto_pk_cmp_keys(r->onion_pkey, twin->onion_pkey)) {
  949. smartlist_del(sl,i--);
  950. }
  951. }
  952. }
  953. #endif
  954. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  955. *
  956. * This function is used to extend cpath by another hop.
  957. */
  958. void onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  959. {
  960. if (*head_ptr) {
  961. new_hop->next = (*head_ptr);
  962. new_hop->prev = (*head_ptr)->prev;
  963. (*head_ptr)->prev->next = new_hop;
  964. (*head_ptr)->prev = new_hop;
  965. } else {
  966. *head_ptr = new_hop;
  967. new_hop->prev = new_hop->next = new_hop;
  968. }
  969. }
  970. static routerinfo_t *choose_good_middle_server(cpath_build_state_t *state,
  971. crypt_path_t *head,
  972. int cur_len)
  973. {
  974. int i;
  975. routerinfo_t *r, *choice;
  976. crypt_path_t *cpath;
  977. smartlist_t *excluded = smartlist_create();
  978. log_fn(LOG_DEBUG, "Contemplating intermediate hop: random choice.");
  979. excluded = smartlist_create();
  980. if((r = router_get_by_digest(state->chosen_exit_digest)))
  981. smartlist_add(excluded, r);
  982. if((r = router_get_my_routerinfo()))
  983. smartlist_add(excluded, r);
  984. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  985. r = router_get_by_digest(cpath->identity_digest);
  986. tor_assert(r);
  987. smartlist_add(excluded, r);
  988. }
  989. choice = router_choose_random_node("", options.ExcludeNodes, excluded,
  990. 0, 1, options._AllowUnverified & ALLOW_UNVERIFIED_MIDDLE, 0);
  991. smartlist_free(excluded);
  992. return choice;
  993. }
  994. static routerinfo_t *choose_good_entry_server(cpath_build_state_t *state)
  995. {
  996. routerinfo_t *r, *choice;
  997. smartlist_t *excluded = smartlist_create();
  998. char buf[16];
  999. if((r = router_get_by_digest(state->chosen_exit_digest)))
  1000. smartlist_add(excluded, r);
  1001. if((r = router_get_my_routerinfo()))
  1002. smartlist_add(excluded, r);
  1003. if(options.FascistFirewall) {
  1004. /* exclude all ORs that listen on the wrong port */
  1005. routerlist_t *rl;
  1006. int i;
  1007. router_get_routerlist(&rl);
  1008. if(!rl)
  1009. return NULL;
  1010. for(i=0; i < smartlist_len(rl->routers); i++) {
  1011. r = smartlist_get(rl->routers, i);
  1012. sprintf(buf, "%d", r->or_port);
  1013. if(!smartlist_string_isin(options.FirewallPorts, buf))
  1014. smartlist_add(excluded, r);
  1015. }
  1016. }
  1017. choice = router_choose_random_node(options.EntryNodes, options.ExcludeNodes,
  1018. excluded, 0, 1, options._AllowUnverified & ALLOW_UNVERIFIED_ENTRY,
  1019. options.StrictEntryNodes);
  1020. smartlist_free(excluded);
  1021. return choice;
  1022. }
  1023. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1024. * based on <b>state</b>. Add the hop info to head_ptr, and return a
  1025. * pointer to the chosen router in <b>router_out</b>.
  1026. */
  1027. static int
  1028. onion_extend_cpath(crypt_path_t **head_ptr, cpath_build_state_t
  1029. *state, routerinfo_t **router_out)
  1030. {
  1031. int cur_len;
  1032. crypt_path_t *cpath, *hop;
  1033. routerinfo_t *choice;
  1034. smartlist_t *excludednodes;
  1035. tor_assert(head_ptr);
  1036. tor_assert(router_out);
  1037. if (!*head_ptr) {
  1038. cur_len = 0;
  1039. } else {
  1040. cur_len = 1;
  1041. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  1042. ++cur_len;
  1043. }
  1044. }
  1045. if (cur_len >= state->desired_path_len) {
  1046. log_fn(LOG_DEBUG, "Path is complete: %d steps long",
  1047. state->desired_path_len);
  1048. return 1;
  1049. }
  1050. log_fn(LOG_DEBUG, "Path is %d long; we want %d", cur_len,
  1051. state->desired_path_len);
  1052. excludednodes = smartlist_create();
  1053. add_nickname_list_to_smartlist(excludednodes,options.ExcludeNodes);
  1054. if(cur_len == state->desired_path_len - 1) { /* Picking last node */
  1055. choice = router_get_by_digest(state->chosen_exit_digest);
  1056. } else if(cur_len == 0) { /* picking first node */
  1057. choice = choose_good_entry_server(state);
  1058. } else {
  1059. choice = choose_good_middle_server(state, *head_ptr, cur_len);
  1060. }
  1061. smartlist_free(excludednodes);
  1062. if(!choice) {
  1063. log_fn(LOG_WARN,"Failed to find node for hop %d of our path. Discarding this circuit.", cur_len);
  1064. return -1;
  1065. }
  1066. log_fn(LOG_DEBUG,"Chose router %s for hop %d (exit is %s)",
  1067. choice->nickname, cur_len, state->chosen_exit_name);
  1068. hop = tor_malloc_zero(sizeof(crypt_path_t));
  1069. /* link hop into the cpath, at the end. */
  1070. onion_append_to_cpath(head_ptr, hop);
  1071. hop->state = CPATH_STATE_CLOSED;
  1072. hop->port = choice->or_port;
  1073. hop->addr = choice->addr;
  1074. memcpy(hop->identity_digest, choice->identity_digest, DIGEST_LEN);
  1075. hop->package_window = CIRCWINDOW_START;
  1076. hop->deliver_window = CIRCWINDOW_START;
  1077. log_fn(LOG_DEBUG, "Extended circuit path with %s for hop %d",
  1078. choice->nickname, cur_len);
  1079. *router_out = choice;
  1080. return 0;
  1081. }
  1082. /*
  1083. Local Variables:
  1084. mode:c
  1085. indent-tabs-mode:nil
  1086. c-basic-offset:2
  1087. End:
  1088. */