circuitbuild.c 50 KB

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