circuitbuild.c 48 KB

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