circuitbuild.c 42 KB

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