circuitbuild.c 47 KB

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