circuitbuild.c 50 KB

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