circuitbuild.c 43 KB

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