circuitbuild.c 41 KB

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