circuitbuild.c 40 KB

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