circuitbuild.c 50 KB

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