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