circuitbuild.c 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 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 circuit_deliver_create_cell(circuit_t *circ,
  17. uint8_t cell_type, char *payload);
  18. static int onion_pick_cpath_exit(circuit_t *circ, routerinfo_t *exit);
  19. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  20. static int onion_next_router_in_cpath(circuit_t *circ, routerinfo_t **router);
  21. static int onion_extend_cpath(uint8_t purpose, crypt_path_t **head_ptr,
  22. cpath_build_state_t *state);
  23. static int count_acceptable_routers(smartlist_t *routers);
  24. static int onion_append_hop(crypt_path_t **head_ptr, routerinfo_t *choice);
  25. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  26. * and with the high bit specified by circ_id_type (see
  27. * decide_circ_id_type()), until we get a circ_id that is not in use
  28. * by any other circuit on that conn.
  29. *
  30. * Return it, or 0 if can't get a unique circ_id.
  31. */
  32. static uint16_t
  33. get_unique_circ_id_by_conn(connection_t *conn)
  34. {
  35. uint16_t test_circ_id;
  36. int attempts=0;
  37. uint16_t high_bit;
  38. tor_assert(conn);
  39. tor_assert(conn->type == CONN_TYPE_OR);
  40. high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  41. do {
  42. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  43. * circID such that (high_bit|test_circ_id) is not already used. */
  44. test_circ_id = conn->next_circ_id++;
  45. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  46. test_circ_id = 1;
  47. conn->next_circ_id = 2;
  48. }
  49. if (++attempts > 1<<15) {
  50. /* Make sure we don't loop forever if all circ_id's are used. This
  51. * matters because it's an external DoS vulnerability.
  52. */
  53. log_fn(LOG_WARN,"No unused circ IDs. Failing.");
  54. return 0;
  55. }
  56. test_circ_id |= high_bit;
  57. } while (circuit_get_by_circid_orconn(test_circ_id, conn));
  58. return test_circ_id;
  59. }
  60. /** If <b>verbose</b> is false, allocate and return a comma-separated
  61. * list of the currently built elements of circuit_t. If
  62. * <b>verbose</b> is true, also list information about link status in
  63. * a more verbose format using spaces.
  64. */
  65. char *
  66. circuit_list_path(circuit_t *circ, int verbose)
  67. {
  68. struct crypt_path_t *hop;
  69. smartlist_t *elements;
  70. const char *states[] = {"closed", "waiting for keys", "open"};
  71. char buf[128];
  72. char *s;
  73. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  74. tor_assert(circ->cpath);
  75. elements = smartlist_create();
  76. if (verbose) {
  77. tor_snprintf(buf, sizeof(buf)-1, "%s%s circ (length %d, exit %s):",
  78. circ->build_state->is_internal ? "internal" : "exit",
  79. circ->build_state->need_uptime ? " (high-uptime)" : "",
  80. circ->build_state->desired_path_len,
  81. circ->build_state->chosen_exit_name);
  82. smartlist_add(elements, tor_strdup(buf));
  83. }
  84. hop = circ->cpath;
  85. do {
  86. const char *elt;
  87. routerinfo_t *r;
  88. if (!hop)
  89. break;
  90. if (!verbose && hop->state != CPATH_STATE_OPEN)
  91. break;
  92. if ((r = router_get_by_digest(hop->identity_digest))) {
  93. elt = r->nickname;
  94. } else if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  95. elt = "<rendezvous splice>";
  96. } else {
  97. buf[0]='$';
  98. base16_encode(buf+1,sizeof(buf)-1,hop->identity_digest,DIGEST_LEN);
  99. elt = buf;
  100. }
  101. if (verbose) {
  102. size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
  103. char *v = tor_malloc(len);
  104. tor_assert(hop->state <= 2);
  105. tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
  106. smartlist_add(elements, v);
  107. } else {
  108. smartlist_add(elements, tor_strdup(elt));
  109. }
  110. hop = hop->next;
  111. } while (hop != circ->cpath);
  112. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  113. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  114. smartlist_free(elements);
  115. return s;
  116. }
  117. /** Log, at severity <b>severity</b>, the nicknames of each router in
  118. * circ's cpath. Also log the length of the cpath, and the intended
  119. * exit point.
  120. */
  121. void
  122. circuit_log_path(int severity, circuit_t *circ)
  123. {
  124. char *s = circuit_list_path(circ,1);
  125. log_fn(severity,"%s",s);
  126. tor_free(s);
  127. }
  128. /** Tell the rep(utation)hist(ory) module about the status of the links
  129. * in circ. Hops that have become OPEN are marked as successfully
  130. * extended; the _first_ hop that isn't open (if any) is marked as
  131. * unable to extend.
  132. */
  133. void
  134. circuit_rep_hist_note_result(circuit_t *circ)
  135. {
  136. struct crypt_path_t *hop;
  137. char *prev_digest = NULL;
  138. routerinfo_t *router;
  139. hop = circ->cpath;
  140. if (!hop) {
  141. /* XXX
  142. * if !hop, then we're not the beginning of this circuit.
  143. * for now, just forget about it. later, we should remember when
  144. * extends-through-us failed, too.
  145. */
  146. return;
  147. }
  148. if (server_mode(get_options())) {
  149. routerinfo_t *me = router_get_my_routerinfo();
  150. tor_assert(me);
  151. prev_digest = me->identity_digest;
  152. }
  153. do {
  154. router = router_get_by_digest(hop->identity_digest);
  155. if (router) {
  156. if (prev_digest) {
  157. if (hop->state == CPATH_STATE_OPEN)
  158. rep_hist_note_extend_succeeded(prev_digest, router->identity_digest);
  159. else {
  160. rep_hist_note_extend_failed(prev_digest, router->identity_digest);
  161. break;
  162. }
  163. }
  164. prev_digest = router->identity_digest;
  165. } else {
  166. prev_digest = NULL;
  167. }
  168. hop=hop->next;
  169. } while (hop!=circ->cpath);
  170. }
  171. /** A helper function for circuit_dump_by_conn() below. Log a bunch
  172. * of information about circuit <b>circ</b>.
  173. */
  174. static void
  175. circuit_dump_details(int severity, circuit_t *circ, int poll_index,
  176. const char *type, int this_circid, int other_circid)
  177. {
  178. log(severity,"Conn %d has %s circuit: circID %d (other side %d), state %d (%s), born %d:",
  179. poll_index, type, this_circid, other_circid, circ->state,
  180. circuit_state_to_string(circ->state), (int)circ->timestamp_created);
  181. if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  182. circuit_log_path(severity, circ);
  183. }
  184. }
  185. /** Log, at severity <b>severity</b>, information about each circuit
  186. * that is connected to <b>conn</b>.
  187. */
  188. void
  189. circuit_dump_by_conn(connection_t *conn, int severity)
  190. {
  191. circuit_t *circ;
  192. connection_t *tmpconn;
  193. for (circ=global_circuitlist;circ;circ = circ->next) {
  194. if (circ->marked_for_close)
  195. continue;
  196. if (circ->p_conn == conn)
  197. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  198. circ->p_circ_id, circ->n_circ_id);
  199. for (tmpconn=circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  200. if (tmpconn == conn) {
  201. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  202. circ->p_circ_id, circ->n_circ_id);
  203. }
  204. }
  205. if (circ->n_conn == conn)
  206. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  207. circ->n_circ_id, circ->p_circ_id);
  208. for (tmpconn=circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  209. if (tmpconn == conn) {
  210. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  211. circ->n_circ_id, circ->p_circ_id);
  212. }
  213. }
  214. if (!circ->n_conn && circ->n_addr && circ->n_port &&
  215. circ->n_addr == conn->addr &&
  216. circ->n_port == conn->port &&
  217. !memcmp(conn->identity_digest, circ->n_conn_id_digest, DIGEST_LEN)) {
  218. circuit_dump_details(severity, circ, conn->poll_index, "Pending",
  219. circ->n_circ_id, circ->p_circ_id);
  220. }
  221. }
  222. }
  223. /** Pick all the entries in our cpath. Stop and return 0 when we're
  224. * happy, or return -1 if an error occurs. */
  225. static int
  226. onion_populate_cpath(circuit_t *circ)
  227. {
  228. int r;
  229. again:
  230. r = onion_extend_cpath(circ->purpose, &circ->cpath, circ->build_state);
  231. // || !CIRCUIT_IS_ORIGIN(circ)) { // wtf? -rd
  232. if (r < 0) {
  233. log_fn(LOG_INFO,"Generating cpath hop failed.");
  234. return -1;
  235. }
  236. if (r == 0)
  237. goto again;
  238. return 0; /* if r == 1 */
  239. }
  240. /** Create and return a new circuit. Initialize its purpose and
  241. * build-state based on our arguments. */
  242. circuit_t *
  243. circuit_init(uint8_t purpose, int need_uptime, int need_capacity, int internal)
  244. {
  245. circuit_t *circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
  246. circ->state = CIRCUIT_STATE_OR_WAIT;
  247. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  248. circ->build_state->need_uptime = need_uptime;
  249. circ->build_state->need_capacity = need_capacity;
  250. circ->build_state->is_internal = internal;
  251. circ->purpose = purpose;
  252. return circ;
  253. }
  254. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  255. * is defined, then use that as your exit router, else choose a suitable
  256. * exit node.
  257. *
  258. * Also launch a connection to the first OR in the chosen path, if
  259. * it's not open already.
  260. */
  261. circuit_t *
  262. circuit_establish_circuit(uint8_t purpose, routerinfo_t *exit,
  263. int need_uptime, int need_capacity, int internal)
  264. {
  265. circuit_t *circ;
  266. circ = circuit_init(purpose, need_uptime, need_capacity, internal);
  267. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  268. onion_populate_cpath(circ) < 0) {
  269. circuit_mark_for_close(circ);
  270. return NULL;
  271. }
  272. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED);
  273. if (circuit_handle_first_hop(circ) < 0) {
  274. circuit_mark_for_close(circ);
  275. return NULL;
  276. }
  277. return circ;
  278. }
  279. /** Start establishing the first hop of our circuit. Figure out what
  280. * OR we should connect to, and if necessary start the connection to
  281. * it. If we're already connected, then send the 'create' cell.
  282. * Return 0 for ok, -1 if circ should be marked-for-close. */
  283. int
  284. circuit_handle_first_hop(circuit_t *circ)
  285. {
  286. routerinfo_t *firsthop;
  287. connection_t *n_conn;
  288. onion_next_router_in_cpath(circ, &firsthop);
  289. tor_assert(firsthop);
  290. /* now see if we're already connected to the first OR in 'route' */
  291. log_fn(LOG_DEBUG,"Looking for firsthop '%s:%u'",
  292. firsthop->address,firsthop->or_port);
  293. /* imprint the circuit with its future n_conn->id */
  294. memcpy(circ->n_conn_id_digest, firsthop->identity_digest, DIGEST_LEN);
  295. n_conn = connection_get_by_identity_digest(firsthop->identity_digest,
  296. CONN_TYPE_OR);
  297. if (!n_conn || n_conn->state != OR_CONN_STATE_OPEN) { /* not currently connected */
  298. circ->n_addr = firsthop->addr;
  299. circ->n_port = firsthop->or_port;
  300. if (!n_conn) { /* launch the connection */
  301. n_conn = connection_or_connect(firsthop->addr, firsthop->or_port,
  302. firsthop->identity_digest);
  303. if (!n_conn) { /* connect failed, forget the whole thing */
  304. log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
  305. return -1;
  306. }
  307. }
  308. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  309. /* return success. The onion/circuit/etc will be taken care of automatically
  310. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  311. */
  312. return 0;
  313. } else { /* it's already open. use it. */
  314. circ->n_addr = n_conn->addr;
  315. circ->n_port = n_conn->port;
  316. circ->n_conn = n_conn;
  317. log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
  318. if (circuit_send_next_onion_skin(circ) < 0) {
  319. log_fn(LOG_INFO,"circuit_send_next_onion_skin failed.");
  320. return -1;
  321. }
  322. }
  323. return 0;
  324. }
  325. /** Find circuits that are waiting on <b>or_conn</b> to become open,
  326. * if any, and get them to send their create cells forward.
  327. *
  328. * Status is 1 if connect succeeded, or 0 if connect failed.
  329. */
  330. void
  331. circuit_n_conn_done(connection_t *or_conn, int status)
  332. {
  333. circuit_t *circ;
  334. log_fn(LOG_DEBUG,"or_conn to %s, status=%d",
  335. or_conn->nickname ? or_conn->nickname : "NULL", status);
  336. for (circ=global_circuitlist;circ;circ = circ->next) {
  337. if (circ->marked_for_close)
  338. continue;
  339. if (circ->state == CIRCUIT_STATE_OR_WAIT &&
  340. !circ->n_conn &&
  341. circ->n_addr == or_conn->addr &&
  342. circ->n_port == or_conn->port &&
  343. !memcmp(or_conn->identity_digest, circ->n_conn_id_digest, DIGEST_LEN)) {
  344. if (!status) { /* or_conn failed; close circ */
  345. log_fn(LOG_INFO,"or_conn failed. Closing circ.");
  346. circuit_mark_for_close(circ);
  347. continue;
  348. }
  349. log_fn(LOG_DEBUG,"Found circ %d, sending create cell.", circ->n_circ_id);
  350. circ->n_conn = or_conn;
  351. memcpy(circ->n_conn_id_digest, or_conn->identity_digest, DIGEST_LEN);
  352. if (CIRCUIT_IS_ORIGIN(circ)) {
  353. if (circuit_send_next_onion_skin(circ) < 0) {
  354. log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
  355. circuit_mark_for_close(circ);
  356. continue;
  357. /* XXX could this be bad, eg if next_onion_skin failed because conn died? */
  358. }
  359. } else {
  360. /* pull the create cell out of circ->onionskin, and send it */
  361. if (circuit_deliver_create_cell(circ,CELL_CREATE,circ->onionskin) < 0) {
  362. circuit_mark_for_close(circ);
  363. continue;
  364. }
  365. }
  366. }
  367. }
  368. }
  369. /** DOCDOC */
  370. static int
  371. circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type, char *payload)
  372. {
  373. cell_t cell;
  374. uint16_t id;
  375. tor_assert(circ);
  376. tor_assert(circ->n_conn);
  377. tor_assert(circ->n_conn->type == CONN_TYPE_OR);
  378. tor_assert(payload);
  379. tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
  380. id = get_unique_circ_id_by_conn(circ->n_conn);
  381. if (!id) {
  382. log_fn(LOG_WARN,"failed to get unique circID.");
  383. return -1;
  384. }
  385. log_fn(LOG_DEBUG,"Chosen circID %u.", id);
  386. circuit_set_circid_orconn(circ, id, circ->n_conn, N_CONN_CHANGED);
  387. memset(&cell, 0, sizeof(cell_t));
  388. cell.command = cell_type;
  389. cell.circ_id = circ->n_circ_id;
  390. memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
  391. connection_or_write_cell_to_buf(&cell, circ->n_conn);
  392. return 0;
  393. }
  394. extern int has_completed_circuit;
  395. /** This is the backbone function for building circuits.
  396. *
  397. * If circ's first hop is closed, then we need to build a create
  398. * cell and send it forward.
  399. *
  400. * Otherwise, we need to build a relay extend cell and send it
  401. * forward.
  402. *
  403. * Return -1 if we want to tear down circ, else return 0.
  404. */
  405. int
  406. circuit_send_next_onion_skin(circuit_t *circ)
  407. {
  408. crypt_path_t *hop;
  409. routerinfo_t *router;
  410. int r;
  411. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  412. char *onionskin;
  413. size_t payload_len;
  414. tor_assert(circ);
  415. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  416. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  417. uint8_t cell_type;
  418. log_fn(LOG_DEBUG,"First skin; sending create cell.");
  419. router = router_get_by_digest(circ->n_conn->identity_digest);
  420. if (!router) {
  421. log_fn(LOG_WARN,"Couldn't find routerinfo for %s",
  422. circ->n_conn->nickname);
  423. return -1;
  424. }
  425. if (1 || /* Disable this '1' once we believe CREATE_FAST works. XXXX */
  426. (get_options()->ORPort || !router->platform ||
  427. !tor_version_as_new_as(router->platform, "0.1.0.6-rc"))) {
  428. /* We are an OR, or we are connecting to an old Tor: we should
  429. * send an old slow create cell.
  430. */
  431. cell_type = CELL_CREATE;
  432. if (onion_skin_create(router->onion_pkey,
  433. &(circ->cpath->dh_handshake_state),
  434. payload) < 0) {
  435. log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
  436. return -1;
  437. }
  438. } else {
  439. /* We are not an OR, and we building the first hop of a circuit to
  440. * a new OR: we can be speedy. */
  441. cell_type = CELL_CREATE_FAST;
  442. memset(payload, 0, sizeof(payload));
  443. crypto_rand(circ->cpath->fast_handshake_state,
  444. sizeof(circ->cpath->fast_handshake_state));
  445. memcpy(payload, circ->cpath->fast_handshake_state,
  446. sizeof(circ->cpath->fast_handshake_state));
  447. }
  448. if (circuit_deliver_create_cell(circ, cell_type, payload) < 0)
  449. return -1;
  450. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  451. circ->state = CIRCUIT_STATE_BUILDING;
  452. log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
  453. } else {
  454. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  455. tor_assert(circ->state == CIRCUIT_STATE_BUILDING);
  456. log_fn(LOG_DEBUG,"starting to send subsequent skin.");
  457. r = onion_next_router_in_cpath(circ, &router);
  458. if (r > 0) {
  459. /* done building the circuit. whew. */
  460. circ->state = CIRCUIT_STATE_OPEN;
  461. log_fn(LOG_INFO,"circuit built!");
  462. circuit_reset_failure_count(0);
  463. if (!has_completed_circuit) {
  464. or_options_t *options = get_options();
  465. has_completed_circuit=1;
  466. log(LOG_NOTICE,"Tor has successfully opened a circuit. Looks like it's working.");
  467. /* XXX009 Log a count of known routers here */
  468. if (server_mode(options) && !check_whether_orport_reachable())
  469. log(LOG_NOTICE,"Now checking whether ORPort %s%s reachable... (this may take several minutes)",
  470. options->DirPort ? "and DirPort " : "",
  471. options->DirPort ? "are" : "is");
  472. }
  473. circuit_rep_hist_note_result(circ);
  474. circuit_has_opened(circ); /* do other actions as necessary */
  475. return 0;
  476. } else if (r < 0) {
  477. return -1;
  478. }
  479. hop = onion_next_hop_in_cpath(circ->cpath);
  480. *(uint32_t*)payload = htonl(hop->addr);
  481. *(uint16_t*)(payload+4) = htons(hop->port);
  482. onionskin = payload+2+4;
  483. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN, hop->identity_digest, DIGEST_LEN);
  484. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  485. if (onion_skin_create(router->onion_pkey, &(hop->dh_handshake_state), onionskin) < 0) {
  486. log_fn(LOG_WARN,"onion_skin_create failed.");
  487. return -1;
  488. }
  489. log_fn(LOG_DEBUG,"Sending extend relay cell.");
  490. /* send it to hop->prev, because it will transfer
  491. * it to a create cell and then send to hop */
  492. if (connection_edge_send_command(NULL, circ, RELAY_COMMAND_EXTEND,
  493. payload, payload_len, hop->prev) < 0)
  494. return 0; /* circuit is closed */
  495. hop->state = CPATH_STATE_AWAITING_KEYS;
  496. }
  497. return 0;
  498. }
  499. /** Our clock just jumped forward by <b>seconds_elapsed</b>. Assume
  500. * something has also gone wrong with our network: notify the user,
  501. * and abandon all not-yet-used circuits. */
  502. void
  503. circuit_note_clock_jumped(int seconds_elapsed)
  504. {
  505. log(LOG_NOTICE,"Your clock just jumped %d seconds forward; assuming established circuits no longer work.", seconds_elapsed);
  506. has_completed_circuit=0; /* so it'll log when it works again */
  507. circuit_mark_all_unused_circs();
  508. }
  509. /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
  510. * sure we're connected to the next hop, and pass it the onion skin in
  511. * a create cell.
  512. */
  513. int
  514. circuit_extend(cell_t *cell, circuit_t *circ)
  515. {
  516. connection_t *n_conn;
  517. relay_header_t rh;
  518. char *onionskin;
  519. char *id_digest=NULL;
  520. if (circ->n_conn) {
  521. log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
  522. return -1;
  523. }
  524. relay_header_unpack(&rh, cell->payload);
  525. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  526. log_fn(LOG_WARN, "Wrong length %d on extend cell. Closing circuit.", rh.length);
  527. return -1;
  528. }
  529. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  530. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  531. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  532. id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
  533. n_conn = connection_get_by_identity_digest(id_digest, CONN_TYPE_OR);
  534. if (!n_conn || n_conn->state != OR_CONN_STATE_OPEN) {
  535. /* Note that this will close circuits where the onion has the same
  536. * router twice in a row in the path. I think that's ok.
  537. */
  538. struct in_addr in;
  539. char tmpbuf[INET_NTOA_BUF_LEN];
  540. in.s_addr = htonl(circ->n_addr);
  541. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  542. log_fn(LOG_INFO,"Next router (%s:%d) not connected. Connecting.",
  543. tmpbuf, circ->n_port);
  544. memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  545. circ->state = CIRCUIT_STATE_OR_WAIT;
  546. /* imprint the circuit with its future n_conn->id */
  547. memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
  548. if (n_conn) {
  549. circ->n_addr = n_conn->addr;
  550. circ->n_port = n_conn->port;
  551. } else {
  552. /* we should try to open a connection */
  553. n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
  554. if (!n_conn) {
  555. log_fn(LOG_INFO,"Launching n_conn failed. Closing.");
  556. return -1;
  557. }
  558. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  559. }
  560. /* return success. The onion/circuit/etc will be taken care of automatically
  561. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  562. */
  563. return 0;
  564. }
  565. /* these may be different if the router connected to us from elsewhere */
  566. circ->n_addr = n_conn->addr;
  567. circ->n_port = n_conn->port;
  568. circ->n_conn = n_conn;
  569. memcpy(circ->n_conn_id_digest, n_conn->identity_digest, DIGEST_LEN);
  570. log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
  571. if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
  572. return -1;
  573. return 0;
  574. }
  575. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  576. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  577. * used as follows:
  578. * - 20 to initialize f_digest
  579. * - 20 to initialize b_digest
  580. * - 16 to key f_crypto
  581. * - 16 to key b_crypto
  582. *
  583. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  584. */
  585. int
  586. circuit_init_cpath_crypto(crypt_path_t *cpath, char *key_data, int reverse)
  587. {
  588. crypto_digest_env_t *tmp_digest;
  589. crypto_cipher_env_t *tmp_crypto;
  590. tor_assert(cpath);
  591. tor_assert(key_data);
  592. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  593. cpath->f_digest || cpath->b_digest));
  594. // log_fn(LOG_DEBUG,"hop init digest forward 0x%.8x, backward 0x%.8x.",
  595. // (unsigned int)*(uint32_t*)key_data, (unsigned int)*(uint32_t*)(key_data+20));
  596. cpath->f_digest = crypto_new_digest_env();
  597. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  598. cpath->b_digest = crypto_new_digest_env();
  599. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  600. // log_fn(LOG_DEBUG,"hop init cipher forward 0x%.8x, backward 0x%.8x.",
  601. // (unsigned int)*(uint32_t*)(key_data+40), (unsigned int)*(uint32_t*)(key_data+40+16));
  602. if (!(cpath->f_crypto =
  603. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  604. log(LOG_WARN,"Bug: forward cipher initialization failed.");
  605. return -1;
  606. }
  607. if (!(cpath->b_crypto =
  608. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  609. log(LOG_WARN,"Bug: backward cipher initialization failed.");
  610. return -1;
  611. }
  612. if (reverse) {
  613. tmp_digest = cpath->f_digest;
  614. cpath->f_digest = cpath->b_digest;
  615. cpath->b_digest = tmp_digest;
  616. tmp_crypto = cpath->f_crypto;
  617. cpath->f_crypto = cpath->b_crypto;
  618. cpath->b_crypto = tmp_crypto;
  619. }
  620. return 0;
  621. }
  622. /** A created or extended cell came back to us on the circuit,
  623. * and it included <b>reply</b> (the second DH key, plus KH).
  624. * DOCDOC reply_type.
  625. *
  626. * Calculate the appropriate keys and digests, make sure KH is
  627. * correct, and initialize this hop of the cpath.
  628. *
  629. * Return -1 if we want to mark circ for close, else return 0.
  630. */
  631. int
  632. circuit_finish_handshake(circuit_t *circ, uint8_t reply_type, char *reply)
  633. {
  634. char keys[CPATH_KEY_MATERIAL_LEN];
  635. crypt_path_t *hop;
  636. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  637. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  638. hop = circ->cpath;
  639. else {
  640. hop = onion_next_hop_in_cpath(circ->cpath);
  641. if (!hop) { /* got an extended when we're all done? */
  642. log_fn(LOG_WARN,"got extended when circ already built? Closing.");
  643. return -1;
  644. }
  645. }
  646. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  647. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  648. if (onion_skin_client_handshake(hop->dh_handshake_state, reply, keys,
  649. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  650. log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
  651. return -1;
  652. }
  653. /* Remember hash of g^xy */
  654. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  655. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  656. if (fast_client_handshake(hop->fast_handshake_state, reply, keys,
  657. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  658. log_fn(LOG_WARN,"fast_client_handshake failed.");
  659. return -1;
  660. }
  661. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  662. } else {
  663. log_fn(LOG_WARN,"CREATED cell type did not match CREATE cell type.");
  664. return -1;
  665. }
  666. if (hop->dh_handshake_state) {
  667. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  668. hop->dh_handshake_state = NULL;
  669. }
  670. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  671. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  672. return -1;
  673. }
  674. hop->state = CPATH_STATE_OPEN;
  675. log_fn(LOG_INFO,"Finished building circuit hop:");
  676. circuit_log_path(LOG_INFO,circ);
  677. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED);
  678. return 0;
  679. }
  680. /** We received a relay truncated cell on circ.
  681. *
  682. * Since we don't ask for truncates currently, getting a truncated
  683. * means that a connection broke or an extend failed. For now,
  684. * just give up: for circ to close, and return 0.
  685. */
  686. int
  687. circuit_truncated(circuit_t *circ, crypt_path_t *layer)
  688. {
  689. // crypt_path_t *victim;
  690. // connection_t *stream;
  691. tor_assert(circ);
  692. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  693. tor_assert(layer);
  694. /* XXX Since we don't ask for truncates currently, getting a truncated
  695. * means that a connection broke or an extend failed. For now,
  696. * just give up.
  697. */
  698. circuit_mark_for_close(circ);
  699. return 0;
  700. #if 0
  701. while (layer->next != circ->cpath) {
  702. /* we need to clear out layer->next */
  703. victim = layer->next;
  704. log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
  705. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  706. if (stream->cpath_layer == victim) {
  707. log_fn(LOG_INFO, "Marking stream %d for close.", stream->stream_id);
  708. /* no need to send 'end' relay cells,
  709. * because the other side's already dead
  710. */
  711. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  712. }
  713. }
  714. layer->next = victim->next;
  715. circuit_free_cpath_node(victim);
  716. }
  717. log_fn(LOG_INFO, "finished");
  718. return 0;
  719. #endif
  720. }
  721. /** Given a response payload and keys, initialize, then send a created
  722. * cell back.
  723. */
  724. int
  725. onionskin_answer(circuit_t *circ, uint8_t cell_type, char *payload, char *keys)
  726. {
  727. cell_t cell;
  728. crypt_path_t *tmp_cpath;
  729. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  730. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  731. memset(&cell, 0, sizeof(cell_t));
  732. cell.command = cell_type;
  733. cell.circ_id = circ->p_circ_id;
  734. circ->state = CIRCUIT_STATE_OPEN;
  735. memcpy(cell.payload, payload,
  736. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  737. log_fn(LOG_INFO,"init digest forward 0x%.8x, backward 0x%.8x.",
  738. (unsigned int)*(uint32_t*)(keys), (unsigned int)*(uint32_t*)(keys+20));
  739. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  740. log_fn(LOG_WARN,"Circuit initialization failed");
  741. tor_free(tmp_cpath);
  742. return -1;
  743. }
  744. circ->n_digest = tmp_cpath->f_digest;
  745. circ->n_crypto = tmp_cpath->f_crypto;
  746. circ->p_digest = tmp_cpath->b_digest;
  747. circ->p_crypto = tmp_cpath->b_crypto;
  748. tmp_cpath->magic = 0;
  749. tor_free(tmp_cpath);
  750. if (cell_type == CELL_CREATED)
  751. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  752. else
  753. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  754. connection_or_write_cell_to_buf(&cell, circ->p_conn);
  755. log_fn(LOG_DEBUG,"Finished sending 'created' cell.");
  756. if (!is_local_IP(circ->p_conn->addr) &&
  757. tor_tls_is_server(circ->p_conn->tls)) {
  758. /* record that we could process create cells from a non-local conn
  759. * that we didn't initiate; presumably this means that create cells
  760. * can reach us too. */
  761. router_orport_found_reachable();
  762. }
  763. return 0;
  764. }
  765. /** Choose a length for a circuit of purpose <b>purpose</b>.
  766. * Default length is 3 + the number of endpoints that would give something
  767. * away. If the routerlist <b>routers</b> doesn't have enough routers
  768. * to handle the desired path length, return as large a path length as
  769. * is feasible, except if it's less than 2, in which case return -1.
  770. */
  771. static int
  772. new_route_len(double cw, uint8_t purpose, smartlist_t *routers)
  773. {
  774. int num_acceptable_routers;
  775. int routelen;
  776. tor_assert(cw >= 0.);
  777. tor_assert(cw < 1.);
  778. tor_assert(routers);
  779. #ifdef TOR_PERF
  780. routelen = 2;
  781. #else
  782. if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
  783. routelen = 3;
  784. else if (purpose == CIRCUIT_PURPOSE_TESTING)
  785. routelen = 3;
  786. else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
  787. routelen = 4;
  788. else if (purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
  789. routelen = 3;
  790. else if (purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  791. routelen = 3;
  792. else if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND)
  793. routelen = 4;
  794. else {
  795. log_fn(LOG_WARN,"Bug: unhandled purpose %d", purpose);
  796. tor_fragile_assert();
  797. return -1;
  798. }
  799. #endif
  800. #if 0
  801. for (routelen = 3; ; routelen++) { /* 3, increment until coinflip says we're done */
  802. if (crypto_pseudo_rand_int(255) >= cw*255) /* don't extend */
  803. break;
  804. }
  805. #endif
  806. log_fn(LOG_DEBUG,"Chosen route length %d (%d routers available).",routelen,
  807. smartlist_len(routers));
  808. num_acceptable_routers = count_acceptable_routers(routers);
  809. if (num_acceptable_routers < 2) {
  810. log_fn(LOG_INFO,"Not enough acceptable routers (%d). Discarding this circuit.",
  811. num_acceptable_routers);
  812. return -1;
  813. }
  814. if (num_acceptable_routers < routelen) {
  815. log_fn(LOG_INFO,"Not enough routers: cutting routelen from %d to %d.",
  816. routelen, num_acceptable_routers);
  817. routelen = num_acceptable_routers;
  818. }
  819. return routelen;
  820. }
  821. /** Fetch the list of predicted ports, dup it into a smartlist of
  822. * uint16_t's, remove the ones that are already handled by an
  823. * existing circuit, and return it.
  824. */
  825. static smartlist_t *
  826. circuit_get_unhandled_ports(time_t now)
  827. {
  828. smartlist_t *source = rep_hist_get_predicted_ports(now);
  829. smartlist_t *dest = smartlist_create();
  830. uint16_t *tmp;
  831. int i;
  832. for (i = 0; i < smartlist_len(source); ++i) {
  833. tmp = tor_malloc(sizeof(uint16_t));
  834. memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
  835. smartlist_add(dest, tmp);
  836. }
  837. circuit_remove_handled_ports(dest);
  838. return dest;
  839. }
  840. /** Return 1 if we already have circuits present or on the way for
  841. * all anticipated ports. Return 0 if we should make more.
  842. *
  843. * If we're returning 0, set need_uptime and need_capacity to
  844. * indicate any requirements that the unhandled ports have.
  845. */
  846. int
  847. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  848. int *need_capacity)
  849. {
  850. int i, enough;
  851. uint16_t *port;
  852. smartlist_t *sl = circuit_get_unhandled_ports(now);
  853. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  854. enough = (smartlist_len(sl) == 0);
  855. for (i = 0; i < smartlist_len(sl); ++i) {
  856. port = smartlist_get(sl, i);
  857. if (smartlist_string_num_isin(LongLivedServices, *port))
  858. *need_uptime = 1;
  859. tor_free(port);
  860. }
  861. smartlist_free(sl);
  862. return enough;
  863. }
  864. /** Return 1 if <b>router</b> can handle one or more of the ports in
  865. * <b>needed_ports</b>, else return 0.
  866. */
  867. static int
  868. router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
  869. {
  870. int i;
  871. uint16_t port;
  872. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  873. addr_policy_result_t r;
  874. port = *(uint16_t *)smartlist_get(needed_ports, i);
  875. tor_assert(port);
  876. r = router_compare_addr_to_addr_policy(0, port, router->exit_policy);
  877. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  878. return 1;
  879. }
  880. return 0;
  881. }
  882. /** How many circuits do we want simultaneously in-progress to handle
  883. * a given stream?
  884. */
  885. #define MIN_CIRCUITS_HANDLING_STREAM 2
  886. static int
  887. ap_stream_wants_exit_attention(connection_t *conn)
  888. {
  889. if (conn->type == CONN_TYPE_AP &&
  890. conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  891. !conn->marked_for_close &&
  892. !connection_edge_is_rendezvous_stream(conn) &&
  893. !circuit_stream_is_being_handled(conn, 0, MIN_CIRCUITS_HANDLING_STREAM))
  894. return 1;
  895. return 0;
  896. }
  897. /** Return a pointer to a suitable router to be the exit node for the
  898. * general-purpose circuit we're about to build.
  899. *
  900. * Look through the connection array, and choose a router that maximizes
  901. * the number of pending streams that can exit from this router.
  902. *
  903. * Return NULL if we can't find any suitable routers.
  904. */
  905. static routerinfo_t *
  906. choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
  907. int need_capacity)
  908. {
  909. int *n_supported;
  910. int i, j;
  911. int n_pending_connections = 0;
  912. connection_t **carray;
  913. int n_connections;
  914. int best_support = -1;
  915. int n_best_support=0;
  916. smartlist_t *sl, *preferredexits, *preferredentries, *excludedexits;
  917. routerinfo_t *router;
  918. or_options_t *options = get_options();
  919. preferredentries = smartlist_create();
  920. add_nickname_list_to_smartlist(preferredentries,options->EntryNodes,1);
  921. get_connection_array(&carray, &n_connections);
  922. /* Count how many connections are waiting for a circuit to be built.
  923. * We use this for log messages now, but in the future we may depend on it.
  924. */
  925. for (i = 0; i < n_connections; ++i) {
  926. if (ap_stream_wants_exit_attention(carray[i]))
  927. ++n_pending_connections;
  928. }
  929. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  930. // n_pending_connections);
  931. /* Now we count, for each of the routers in the directory, how many
  932. * of the pending connections could possibly exit from that
  933. * router (n_supported[i]). (We can't be sure about cases where we
  934. * don't know the IP address of the pending connection.)
  935. */
  936. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  937. for (i = 0; i < smartlist_len(dir->routers); ++i) { /* iterate over routers */
  938. router = smartlist_get(dir->routers, i);
  939. if (router_is_me(router)) {
  940. n_supported[i] = -1;
  941. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  942. /* XXX there's probably a reverse predecessor attack here, but
  943. * it's slow. should we take this out? -RD
  944. */
  945. continue;
  946. }
  947. if (!router->is_running) {
  948. n_supported[i] = -1;
  949. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- directory says it's not running.",
  950. // router->nickname, i);
  951. continue; /* skip routers that are known to be down */
  952. }
  953. if (router_is_unreliable(router, need_uptime, need_capacity)) {
  954. n_supported[i] = -1;
  955. continue; /* skip routers that are not suitable */
  956. }
  957. if (!router->is_verified &&
  958. (!(options->_AllowUnverified & ALLOW_UNVERIFIED_EXIT) ||
  959. router_is_unreliable(router, 1, 1))) {
  960. /* if it's unverified, and either we don't want it or it's unsuitable */
  961. n_supported[i] = -1;
  962. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- unverified router.",
  963. // router->nickname, i);
  964. continue; /* skip unverified routers */
  965. }
  966. if (router_exit_policy_rejects_all(router)) {
  967. n_supported[i] = -1;
  968. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  969. // router->nickname, i);
  970. continue; /* skip routers that reject all */
  971. }
  972. if (smartlist_len(preferredentries)==1 &&
  973. router == (routerinfo_t*)smartlist_get(preferredentries, 0)) {
  974. n_supported[i] = -1;
  975. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it's our only preferred entry node.", router->nickname, i);
  976. continue;
  977. }
  978. n_supported[i] = 0;
  979. for (j = 0; j < n_connections; ++j) { /* iterate over connections */
  980. if (!ap_stream_wants_exit_attention(carray[j]))
  981. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  982. if (connection_ap_can_use_exit(carray[j], router)) {
  983. ++n_supported[i];
  984. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  985. // router->nickname, i, n_supported[i]);
  986. } else {
  987. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  988. // router->nickname, i);
  989. }
  990. } /* End looping over connections. */
  991. if (n_supported[i] > best_support) {
  992. /* If this router is better than previous ones, remember its index
  993. * and goodness, and start counting how many routers are this good. */
  994. best_support = n_supported[i]; n_best_support=1;
  995. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  996. // router->nickname);
  997. } else if (n_supported[i] == best_support) {
  998. /* If this router is _as good_ as the best one, just increment the
  999. * count of equally good routers.*/
  1000. ++n_best_support;
  1001. }
  1002. }
  1003. log_fn(LOG_INFO, "Found %d servers that might support %d/%d pending connections.",
  1004. n_best_support, best_support, n_pending_connections);
  1005. preferredexits = smartlist_create();
  1006. add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1);
  1007. excludedexits = smartlist_create();
  1008. add_nickname_list_to_smartlist(excludedexits,options->ExcludeNodes,0);
  1009. sl = smartlist_create();
  1010. /* If any routers definitely support any pending connections, choose one
  1011. * at random. */
  1012. if (best_support > 0) {
  1013. for (i = 0; i < smartlist_len(dir->routers); i++)
  1014. if (n_supported[i] == best_support)
  1015. smartlist_add(sl, smartlist_get(dir->routers, i));
  1016. smartlist_subtract(sl,excludedexits);
  1017. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1018. smartlist_intersect(sl,preferredexits);
  1019. router = routerlist_sl_choose_by_bandwidth(sl);
  1020. } else {
  1021. /* Either there are no pending connections, or no routers even seem to
  1022. * possibly support any of them. Choose a router at random that satisfies
  1023. * at least one predicted exit port. */
  1024. int try;
  1025. smartlist_t *needed_ports = circuit_get_unhandled_ports(time(NULL));
  1026. if (best_support == -1) {
  1027. log(LOG_NOTICE, "All routers are down or middleman -- choosing a doomed exit at random.");
  1028. }
  1029. for (try = 0; try < 2; try++) {
  1030. /* try once to pick only from routers that satisfy a needed port,
  1031. * then if there are none, pick from any that support exiting. */
  1032. for (i = 0; i < smartlist_len(dir->routers); i++) {
  1033. router = smartlist_get(dir->routers, i);
  1034. if (n_supported[i] != -1 &&
  1035. (try || router_handles_some_port(router, needed_ports))) {
  1036. log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.", try, router->nickname);
  1037. smartlist_add(sl, router);
  1038. }
  1039. }
  1040. smartlist_subtract(sl,excludedexits);
  1041. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1042. smartlist_intersect(sl,preferredexits);
  1043. router = routerlist_sl_choose_by_bandwidth(sl);
  1044. if (router)
  1045. break;
  1046. }
  1047. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1048. smartlist_free(needed_ports);
  1049. }
  1050. smartlist_free(preferredexits);
  1051. smartlist_free(preferredentries);
  1052. smartlist_free(excludedexits);
  1053. smartlist_free(sl);
  1054. tor_free(n_supported);
  1055. if (router) {
  1056. log_fn(LOG_INFO, "Chose exit server '%s'", router->nickname);
  1057. return router;
  1058. }
  1059. if (options->StrictExitNodes)
  1060. log_fn(LOG_WARN, "No exit routers seem to be running; can't choose an exit.");
  1061. return NULL;
  1062. }
  1063. /** Return a pointer to a suitable router to be the exit node for the
  1064. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1065. * if no router is suitable).
  1066. *
  1067. * For general-purpose circuits, pass it off to
  1068. * choose_good_exit_server_general()
  1069. *
  1070. * For client-side rendezvous circuits, choose a random node, weighted
  1071. * toward the preferences in 'options'.
  1072. */
  1073. static routerinfo_t *
  1074. choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
  1075. int need_uptime, int need_capacity)
  1076. {
  1077. routerinfo_t *r;
  1078. or_options_t *options = get_options();
  1079. switch (purpose) {
  1080. case CIRCUIT_PURPOSE_C_GENERAL:
  1081. return choose_good_exit_server_general(dir, need_uptime, need_capacity);
  1082. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1083. r = router_choose_random_node(options->RendNodes, options->RendExcludeNodes,
  1084. NULL, need_uptime, need_capacity,
  1085. options->_AllowUnverified & ALLOW_UNVERIFIED_RENDEZVOUS, 0);
  1086. return r;
  1087. }
  1088. log_fn(LOG_WARN,"Bug: unhandled purpose %d", purpose);
  1089. tor_fragile_assert();
  1090. return NULL;
  1091. }
  1092. /** Decide a suitable length for circ's cpath, and pick an exit
  1093. * router (or use <b>exit</b> if provided). Store these in the
  1094. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1095. static int
  1096. onion_pick_cpath_exit(circuit_t *circ, routerinfo_t *exit)
  1097. {
  1098. cpath_build_state_t *state = circ->build_state;
  1099. routerlist_t *rl;
  1100. int r;
  1101. router_get_routerlist(&rl);
  1102. if (!rl) {
  1103. log_fn(LOG_WARN,"router_get_routerlist returned empty list; closing circ.");
  1104. return -1;
  1105. }
  1106. r = new_route_len(get_options()->PathlenCoinWeight, circ->purpose, rl->routers);
  1107. if (r < 1) /* must be at least 1 */
  1108. return -1;
  1109. state->desired_path_len = r;
  1110. if (exit) { /* the circuit-builder pre-requested one */
  1111. log_fn(LOG_INFO,"Using requested exit node '%s'", exit->nickname);
  1112. } else { /* we have to decide one */
  1113. exit = choose_good_exit_server(circ->purpose, rl,
  1114. state->need_uptime, state->need_capacity);
  1115. if (!exit) {
  1116. log_fn(LOG_WARN,"failed to choose an exit server");
  1117. return -1;
  1118. }
  1119. }
  1120. memcpy(state->chosen_exit_digest, exit->identity_digest, DIGEST_LEN);
  1121. state->chosen_exit_name = tor_strdup(exit->nickname);
  1122. return 0;
  1123. }
  1124. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1125. * hop to the cpath reflecting this. Don't send the next extend cell --
  1126. * the caller will do this if it wants to.
  1127. */
  1128. int
  1129. circuit_append_new_exit(circuit_t *circ, routerinfo_t *exit)
  1130. {
  1131. tor_assert(exit);
  1132. tor_assert(circ && CIRCUIT_IS_ORIGIN(circ));
  1133. tor_free(circ->build_state->chosen_exit_name);
  1134. circ->build_state->chosen_exit_name = tor_strdup(exit->nickname);
  1135. memcpy(circ->build_state->chosen_exit_digest, exit->identity_digest, DIGEST_LEN);
  1136. ++circ->build_state->desired_path_len;
  1137. onion_append_hop(&circ->cpath, exit);
  1138. return 0;
  1139. }
  1140. /** Take the open circ originating here, give it a new exit destination
  1141. * to <b>exit</b>, and get it to send the next extend cell. If you can't
  1142. * send the extend cell, mark the circuit for close and return -1, else
  1143. * return 0. */
  1144. int
  1145. circuit_extend_to_new_exit(circuit_t *circ, routerinfo_t *exit)
  1146. {
  1147. circuit_append_new_exit(circ, exit);
  1148. circ->state = CIRCUIT_STATE_BUILDING;
  1149. if (circuit_send_next_onion_skin(circ)<0) {
  1150. log_fn(LOG_WARN, "Couldn't extend circuit to new point '%s'.",
  1151. circ->build_state->chosen_exit_name);
  1152. circuit_mark_for_close(circ);
  1153. return -1;
  1154. }
  1155. return 0;
  1156. }
  1157. /** Return the number of routers in <b>routers</b> that are currently up
  1158. * and available for building circuits through.
  1159. */
  1160. static int
  1161. count_acceptable_routers(smartlist_t *routers)
  1162. {
  1163. int i, n;
  1164. int num=0;
  1165. routerinfo_t *r;
  1166. n = smartlist_len(routers);
  1167. for (i=0;i<n;i++) {
  1168. r = smartlist_get(routers, i);
  1169. // log_fn(LOG_DEBUG,"Contemplating whether router %d (%s) is a new option...",
  1170. // i, r->nickname);
  1171. if (r->is_running == 0) {
  1172. // log_fn(LOG_DEBUG,"Nope, the directory says %d is not running.",i);
  1173. goto next_i_loop;
  1174. }
  1175. if (r->is_verified == 0) {
  1176. // log_fn(LOG_DEBUG,"Nope, the directory says %d is not verified.",i);
  1177. /* XXXX009 But unverified routers *are* sometimes acceptable. */
  1178. goto next_i_loop;
  1179. }
  1180. num++;
  1181. // log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  1182. next_i_loop:
  1183. ; /* C requires an explicit statement after the label */
  1184. }
  1185. return num;
  1186. }
  1187. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1188. *
  1189. * This function is used to extend cpath by another hop.
  1190. */
  1191. void
  1192. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1193. {
  1194. if (*head_ptr) {
  1195. new_hop->next = (*head_ptr);
  1196. new_hop->prev = (*head_ptr)->prev;
  1197. (*head_ptr)->prev->next = new_hop;
  1198. (*head_ptr)->prev = new_hop;
  1199. } else {
  1200. *head_ptr = new_hop;
  1201. new_hop->prev = new_hop->next = new_hop;
  1202. }
  1203. }
  1204. /** DOCDOC */
  1205. static routerinfo_t *
  1206. choose_good_middle_server(uint8_t purpose,
  1207. cpath_build_state_t *state,
  1208. crypt_path_t *head,
  1209. int cur_len)
  1210. {
  1211. int i;
  1212. routerinfo_t *r, *choice;
  1213. crypt_path_t *cpath;
  1214. smartlist_t *excluded;
  1215. log_fn(LOG_DEBUG, "Contemplating intermediate hop: random choice.");
  1216. excluded = smartlist_create();
  1217. if ((r = router_get_by_digest(state->chosen_exit_digest))) {
  1218. smartlist_add(excluded, r);
  1219. routerlist_add_family(excluded, r);
  1220. }
  1221. if ((r = routerlist_find_my_routerinfo())) {
  1222. smartlist_add(excluded, r);
  1223. routerlist_add_family(excluded, r);
  1224. }
  1225. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1226. if ((r = router_get_by_digest(cpath->identity_digest))) {
  1227. smartlist_add(excluded, r);
  1228. routerlist_add_family(excluded, r);
  1229. }
  1230. }
  1231. choice = router_choose_random_node(NULL, get_options()->ExcludeNodes, excluded,
  1232. state->need_uptime, state->need_capacity,
  1233. get_options()->_AllowUnverified & ALLOW_UNVERIFIED_MIDDLE, 0);
  1234. smartlist_free(excluded);
  1235. return choice;
  1236. }
  1237. /** DOCDOC */
  1238. static routerinfo_t *
  1239. choose_good_entry_server(cpath_build_state_t *state)
  1240. {
  1241. routerinfo_t *r, *choice;
  1242. smartlist_t *excluded = smartlist_create();
  1243. or_options_t *options = get_options();
  1244. if ((r = router_get_by_digest(state->chosen_exit_digest))) {
  1245. smartlist_add(excluded, r);
  1246. routerlist_add_family(excluded, r);
  1247. }
  1248. if ((r = routerlist_find_my_routerinfo())) {
  1249. smartlist_add(excluded, r);
  1250. routerlist_add_family(excluded, r);
  1251. }
  1252. if (options->FascistFirewall) {
  1253. /* exclude all ORs that listen on the wrong port */
  1254. routerlist_t *rl;
  1255. int i;
  1256. router_get_routerlist(&rl);
  1257. if (!rl)
  1258. return NULL;
  1259. for (i=0; i < smartlist_len(rl->routers); i++) {
  1260. r = smartlist_get(rl->routers, i);
  1261. if (!smartlist_string_num_isin(options->FirewallPorts, r->or_port))
  1262. smartlist_add(excluded, r);
  1263. }
  1264. }
  1265. choice = router_choose_random_node(options->EntryNodes, options->ExcludeNodes,
  1266. excluded, state->need_uptime, state->need_capacity,
  1267. options->_AllowUnverified & ALLOW_UNVERIFIED_ENTRY,
  1268. options->StrictEntryNodes);
  1269. smartlist_free(excluded);
  1270. return choice;
  1271. }
  1272. /** Return the first non-open hop in cpath, or return NULL if all
  1273. * hops are open. */
  1274. static crypt_path_t *
  1275. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1276. {
  1277. crypt_path_t *hop = cpath;
  1278. do {
  1279. if (hop->state != CPATH_STATE_OPEN)
  1280. return hop;
  1281. hop = hop->next;
  1282. } while (hop != cpath);
  1283. return NULL;
  1284. }
  1285. /** Find the router corresponding to the first non-open hop in
  1286. * circ->cpath. Make sure it's state closed. Return 1 if all
  1287. * hops are open (the circuit is complete), 0 if we find a router
  1288. * (and set it to *router), and -1 if we fail to lookup the router.
  1289. */
  1290. static int
  1291. onion_next_router_in_cpath(circuit_t *circ, routerinfo_t **router) {
  1292. routerinfo_t *r;
  1293. crypt_path_t *hop = onion_next_hop_in_cpath(circ->cpath);
  1294. if (!hop) /* all hops are open */
  1295. return 1;
  1296. tor_assert(hop->state == CPATH_STATE_CLOSED);
  1297. r = router_get_by_digest(hop->identity_digest);
  1298. if (!r) {
  1299. log_fn(LOG_WARN,"Circuit intended to extend to a hop whose routerinfo we've lost. Cancelling circuit.");
  1300. return -1;
  1301. }
  1302. *router = r;
  1303. return 0;
  1304. }
  1305. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1306. * based on <b>state</b>. Append the hop info to head_ptr.
  1307. */
  1308. static int
  1309. onion_extend_cpath(uint8_t purpose, crypt_path_t **head_ptr,
  1310. cpath_build_state_t *state)
  1311. {
  1312. int cur_len;
  1313. crypt_path_t *cpath;
  1314. routerinfo_t *choice;
  1315. smartlist_t *excludednodes;
  1316. tor_assert(head_ptr);
  1317. if (!*head_ptr) {
  1318. cur_len = 0;
  1319. } else {
  1320. cur_len = 1;
  1321. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  1322. ++cur_len;
  1323. }
  1324. }
  1325. if (cur_len >= state->desired_path_len) {
  1326. log_fn(LOG_DEBUG, "Path is complete: %d steps long",
  1327. state->desired_path_len);
  1328. return 1;
  1329. }
  1330. log_fn(LOG_DEBUG, "Path is %d long; we want %d", cur_len,
  1331. state->desired_path_len);
  1332. excludednodes = smartlist_create();
  1333. add_nickname_list_to_smartlist(excludednodes,get_options()->ExcludeNodes,0);
  1334. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1335. choice = router_get_by_digest(state->chosen_exit_digest);
  1336. } else if (cur_len == 0) { /* picking first node */
  1337. choice = choose_good_entry_server(state);
  1338. } else {
  1339. choice = choose_good_middle_server(purpose, state, *head_ptr, cur_len);
  1340. }
  1341. smartlist_free(excludednodes);
  1342. if (!choice) {
  1343. log_fn(LOG_WARN,"Failed to find node for hop %d of our path. Discarding this circuit.", cur_len);
  1344. return -1;
  1345. }
  1346. log_fn(LOG_DEBUG,"Chose router %s for hop %d (exit is %s)",
  1347. choice->nickname, cur_len+1, state->chosen_exit_name);
  1348. onion_append_hop(head_ptr, choice);
  1349. return 0;
  1350. }
  1351. /** Create a new hop, annotate it with information about its
  1352. * corresponding router <b>choice</b>, and append it to the
  1353. * end of the cpath <b>head_ptr</b>. */
  1354. static int
  1355. onion_append_hop(crypt_path_t **head_ptr, routerinfo_t *choice)
  1356. {
  1357. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1358. /* link hop into the cpath, at the end. */
  1359. onion_append_to_cpath(head_ptr, hop);
  1360. hop->magic = CRYPT_PATH_MAGIC;
  1361. hop->state = CPATH_STATE_CLOSED;
  1362. hop->port = choice->or_port;
  1363. hop->addr = choice->addr;
  1364. memcpy(hop->identity_digest, choice->identity_digest, DIGEST_LEN);
  1365. hop->package_window = CIRCWINDOW_START;
  1366. hop->deliver_window = CIRCWINDOW_START;
  1367. return 0;
  1368. }