circuitbuild.c 41 KB

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