circuitbuild.c 45 KB

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