circuitbuild.c 40 KB

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