circuitbuild.c 41 KB

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