circuitbuild.c 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 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. /** A helper_node_t represents our information about a chosen fixed entry, or
  16. * "helper" node. We can't just use a routerinfo_t, since we want to remember
  17. * these even when we don't have a directory. */
  18. typedef struct {
  19. char nickname[MAX_NICKNAME_LEN+1];
  20. char identity[DIGEST_LEN];
  21. time_t down_since; /**< 0 if this router is currently up, or the time at which
  22. * it was observed to go down. */
  23. time_t unlisted_since; /**< 0 if this router is currently listed, or the time
  24. * at which it became unlisted */
  25. } helper_node_t;
  26. /** A list of our chosen helper nodes. */
  27. static smartlist_t *helper_nodes = NULL;
  28. static int helper_nodes_dirty = 0;
  29. /********* END VARIABLES ************/
  30. static int circuit_deliver_create_cell(circuit_t *circ,
  31. uint8_t cell_type, char *payload);
  32. static int onion_pick_cpath_exit(circuit_t *circ, extend_info_t *exit);
  33. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  34. static int onion_extend_cpath(uint8_t purpose, crypt_path_t **head_ptr,
  35. cpath_build_state_t *state);
  36. static int count_acceptable_routers(smartlist_t *routers);
  37. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  38. static void pick_helper_nodes(void);
  39. static routerinfo_t *choose_random_helper(void);
  40. static void clear_helper_nodes(void);
  41. static void remove_dead_helpers(void);
  42. static void helper_nodes_changed(void);
  43. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  44. * and with the high bit specified by circ_id_type (see
  45. * decide_circ_id_type()), until we get a circ_id that is not in use
  46. * by any other circuit on that conn.
  47. *
  48. * Return it, or 0 if can't get a unique circ_id.
  49. */
  50. static uint16_t
  51. get_unique_circ_id_by_conn(connection_t *conn)
  52. {
  53. uint16_t test_circ_id;
  54. int attempts=0;
  55. uint16_t high_bit;
  56. tor_assert(conn);
  57. tor_assert(conn->type == CONN_TYPE_OR);
  58. high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  59. do {
  60. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  61. * circID such that (high_bit|test_circ_id) is not already used. */
  62. test_circ_id = conn->next_circ_id++;
  63. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  64. test_circ_id = 1;
  65. conn->next_circ_id = 2;
  66. }
  67. if (++attempts > 1<<15) {
  68. /* Make sure we don't loop forever if all circ_id's are used. This
  69. * matters because it's an external DoS opportunity.
  70. */
  71. warn(LD_CIRC,"No unused circ IDs. Failing.");
  72. return 0;
  73. }
  74. test_circ_id |= high_bit;
  75. } while (circuit_id_used_on_conn(test_circ_id, conn));
  76. return test_circ_id;
  77. }
  78. /** If <b>verbose</b> is false, allocate and return a comma-separated
  79. * list of the currently built elements of circuit_t. If
  80. * <b>verbose</b> is true, also list information about link status in
  81. * a more verbose format using spaces.
  82. */
  83. char *
  84. circuit_list_path(circuit_t *circ, int verbose)
  85. {
  86. crypt_path_t *hop;
  87. smartlist_t *elements;
  88. const char *states[] = {"closed", "waiting for keys", "open"};
  89. char buf[128];
  90. char *s;
  91. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  92. elements = smartlist_create();
  93. if (verbose) {
  94. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  95. tor_snprintf(buf, sizeof(buf)-1, "%s%s circ (length %d%s%s):",
  96. circ->build_state->is_internal ? "internal" : "exit",
  97. circ->build_state->need_uptime ? " (high-uptime)" : "",
  98. circ->build_state->desired_path_len,
  99. circ->state == CIRCUIT_STATE_OPEN ? "" : ", exit ",
  100. circ->state == CIRCUIT_STATE_OPEN ? "" :
  101. (nickname?nickname:"*unnamed*"));
  102. smartlist_add(elements, tor_strdup(buf));
  103. }
  104. hop = circ->cpath;
  105. do {
  106. const char *elt;
  107. if (!hop)
  108. break;
  109. if (!verbose && hop->state != CPATH_STATE_OPEN)
  110. break;
  111. if (!hop->extend_info)
  112. break;
  113. elt = hop->extend_info->nickname;
  114. tor_assert(elt);
  115. if (verbose) {
  116. size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
  117. char *v = tor_malloc(len);
  118. tor_assert(hop->state <= 2);
  119. tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
  120. smartlist_add(elements, v);
  121. } else {
  122. smartlist_add(elements, tor_strdup(elt));
  123. }
  124. hop = hop->next;
  125. } while (hop != circ->cpath);
  126. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  127. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  128. smartlist_free(elements);
  129. return s;
  130. }
  131. /** Log, at severity <b>severity</b>, the nicknames of each router in
  132. * circ's cpath. Also log the length of the cpath, and the intended
  133. * exit point.
  134. */
  135. void
  136. circuit_log_path(int severity, unsigned int domain, circuit_t *circ)
  137. {
  138. char *s = circuit_list_path(circ,1);
  139. log(severity,domain,"%s",s);
  140. tor_free(s);
  141. }
  142. /** Tell the rep(utation)hist(ory) module about the status of the links
  143. * in circ. Hops that have become OPEN are marked as successfully
  144. * extended; the _first_ hop that isn't open (if any) is marked as
  145. * unable to extend.
  146. */
  147. void
  148. circuit_rep_hist_note_result(circuit_t *circ)
  149. {
  150. crypt_path_t *hop;
  151. char *prev_digest = NULL;
  152. routerinfo_t *router;
  153. hop = circ->cpath;
  154. if (!hop) {
  155. /* XXX
  156. * if !hop, then we're not the beginning of this circuit.
  157. * for now, just forget about it. later, we should remember when
  158. * extends-through-us failed, too.
  159. */
  160. return;
  161. }
  162. if (server_mode(get_options())) {
  163. routerinfo_t *me = router_get_my_routerinfo();
  164. tor_assert(me);
  165. prev_digest = me->cache_info.identity_digest;
  166. }
  167. do {
  168. router = router_get_by_digest(hop->extend_info->identity_digest);
  169. if (router) {
  170. if (prev_digest) {
  171. if (hop->state == CPATH_STATE_OPEN)
  172. rep_hist_note_extend_succeeded(prev_digest, router->cache_info.identity_digest);
  173. else {
  174. rep_hist_note_extend_failed(prev_digest, router->cache_info.identity_digest);
  175. break;
  176. }
  177. }
  178. prev_digest = router->cache_info.identity_digest;
  179. } else {
  180. prev_digest = NULL;
  181. }
  182. hop=hop->next;
  183. } while (hop!=circ->cpath);
  184. }
  185. /** A helper function for circuit_dump_by_conn() below. Log a bunch
  186. * of information about circuit <b>circ</b>.
  187. */
  188. static void
  189. circuit_dump_details(int severity, circuit_t *circ, int poll_index,
  190. const char *type, int this_circid, int other_circid)
  191. {
  192. log(severity, LD_CIRC, "Conn %d has %s circuit: circID %d (other side %d), state %d (%s), born %d:",
  193. poll_index, type, this_circid, other_circid, circ->state,
  194. circuit_state_to_string(circ->state), (int)circ->timestamp_created);
  195. if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  196. circuit_log_path(severity, LD_CIRC, circ);
  197. }
  198. }
  199. /** Log, at severity <b>severity</b>, information about each circuit
  200. * that is connected to <b>conn</b>.
  201. */
  202. void
  203. circuit_dump_by_conn(connection_t *conn, int severity)
  204. {
  205. circuit_t *circ;
  206. connection_t *tmpconn;
  207. for (circ=global_circuitlist;circ;circ = circ->next) {
  208. if (circ->marked_for_close)
  209. continue;
  210. if (circ->p_conn == conn)
  211. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  212. circ->p_circ_id, circ->n_circ_id);
  213. for (tmpconn=circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  214. if (tmpconn == conn) {
  215. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  216. circ->p_circ_id, circ->n_circ_id);
  217. }
  218. }
  219. if (circ->n_conn == conn)
  220. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  221. circ->n_circ_id, circ->p_circ_id);
  222. for (tmpconn=circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  223. if (tmpconn == conn) {
  224. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  225. circ->n_circ_id, circ->p_circ_id);
  226. }
  227. }
  228. if (!circ->n_conn && circ->n_addr && circ->n_port &&
  229. circ->n_addr == conn->addr &&
  230. circ->n_port == conn->port &&
  231. !memcmp(conn->identity_digest, circ->n_conn_id_digest, DIGEST_LEN)) {
  232. circuit_dump_details(severity, circ, conn->poll_index, "Pending",
  233. circ->n_circ_id, circ->p_circ_id);
  234. }
  235. }
  236. }
  237. /** Pick all the entries in our cpath. Stop and return 0 when we're
  238. * happy, or return -1 if an error occurs. */
  239. static int
  240. onion_populate_cpath(circuit_t *circ)
  241. {
  242. int r;
  243. again:
  244. r = onion_extend_cpath(circ->purpose, &circ->cpath, circ->build_state);
  245. // || !CIRCUIT_IS_ORIGIN(circ)) { // wtf? -rd
  246. if (r < 0) {
  247. info(LD_CIRC,"Generating cpath hop failed.");
  248. return -1;
  249. }
  250. if (r == 0)
  251. goto again;
  252. return 0; /* if r == 1 */
  253. }
  254. /** Create and return a new circuit. Initialize its purpose and
  255. * build-state based on our arguments. */
  256. circuit_t *
  257. circuit_init(uint8_t purpose, int need_uptime, int need_capacity, int internal)
  258. {
  259. circuit_t *circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
  260. circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
  261. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  262. circ->build_state->need_uptime = need_uptime;
  263. circ->build_state->need_capacity = need_capacity;
  264. circ->build_state->is_internal = internal;
  265. circ->purpose = purpose;
  266. return circ;
  267. }
  268. /** Build a new circuit for <b>purpose</b>. If <b>info/b>
  269. * is defined, then use that as your exit router, else choose a suitable
  270. * exit node.
  271. *
  272. * Also launch a connection to the first OR in the chosen path, if
  273. * it's not open already.
  274. */
  275. circuit_t *
  276. circuit_establish_circuit(uint8_t purpose, extend_info_t *info,
  277. int need_uptime, int need_capacity, int internal)
  278. {
  279. circuit_t *circ;
  280. circ = circuit_init(purpose, need_uptime, need_capacity, internal);
  281. if (onion_pick_cpath_exit(circ, info) < 0 ||
  282. onion_populate_cpath(circ) < 0) {
  283. circuit_mark_for_close(circ);
  284. return NULL;
  285. }
  286. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED);
  287. if (circuit_handle_first_hop(circ) < 0) {
  288. circuit_mark_for_close(circ);
  289. return NULL;
  290. }
  291. return circ;
  292. }
  293. /** Start establishing the first hop of our circuit. Figure out what
  294. * OR we should connect to, and if necessary start the connection to
  295. * it. If we're already connected, then send the 'create' cell.
  296. * Return 0 for ok, -1 if circ should be marked-for-close. */
  297. int
  298. circuit_handle_first_hop(circuit_t *circ)
  299. {
  300. crypt_path_t *firsthop;
  301. connection_t *n_conn;
  302. char tmpbuf[INET_NTOA_BUF_LEN+1];
  303. struct in_addr in;
  304. firsthop = onion_next_hop_in_cpath(circ->cpath);
  305. tor_assert(firsthop);
  306. tor_assert(firsthop->extend_info);
  307. /* now see if we're already connected to the first OR in 'route' */
  308. in.s_addr = htonl(firsthop->extend_info->addr);
  309. tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
  310. debug(LD_CIRC,"Looking for firsthop '%s:%u'",tmpbuf,
  311. firsthop->extend_info->port);
  312. /* imprint the circuit with its future n_conn->id */
  313. memcpy(circ->n_conn_id_digest, firsthop->extend_info->identity_digest,
  314. DIGEST_LEN);
  315. n_conn = connection_or_get_by_identity_digest(
  316. firsthop->extend_info->identity_digest);
  317. if (!n_conn || n_conn->state != OR_CONN_STATE_OPEN ||
  318. (n_conn->is_obsolete &&
  319. router_digest_version_as_new_as(firsthop->extend_info->identity_digest,
  320. "0.1.1.9-alpha-cvs"))) {
  321. /* not currently connected */
  322. circ->n_addr = firsthop->extend_info->addr;
  323. circ->n_port = firsthop->extend_info->port;
  324. if (!n_conn || n_conn->is_obsolete) { /* launch the connection */
  325. n_conn = connection_or_connect(firsthop->extend_info->addr,
  326. firsthop->extend_info->port,
  327. firsthop->extend_info->identity_digest);
  328. if (!n_conn) { /* connect failed, forget the whole thing */
  329. info(LD_CIRC,"connect to firsthop failed. Closing.");
  330. return -1;
  331. }
  332. }
  333. debug(LD_CIRC,"connecting in progress (or finished). Good.");
  334. /* return success. The onion/circuit/etc will be taken care of automatically
  335. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  336. */
  337. return 0;
  338. } else { /* it's already open. use it. */
  339. circ->n_addr = n_conn->addr;
  340. circ->n_port = n_conn->port;
  341. circ->n_conn = n_conn;
  342. debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  343. if (circuit_send_next_onion_skin(circ) < 0) {
  344. info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  345. return -1;
  346. }
  347. }
  348. return 0;
  349. }
  350. /** Find circuits that are waiting on <b>or_conn</b> to become open,
  351. * if any, and get them to send their create cells forward.
  352. *
  353. * Status is 1 if connect succeeded, or 0 if connect failed.
  354. */
  355. void
  356. circuit_n_conn_done(connection_t *or_conn, int status)
  357. {
  358. extern smartlist_t *circuits_pending_or_conns;
  359. debug(LD_CIRC,"or_conn to %s, status=%d",
  360. or_conn->nickname ? or_conn->nickname : "NULL", status);
  361. if (!circuits_pending_or_conns)
  362. return;
  363. SMARTLIST_FOREACH(circuits_pending_or_conns, circuit_t *, circ,
  364. {
  365. if (circ->marked_for_close)
  366. continue;
  367. tor_assert(circ->state == CIRCUIT_STATE_OR_WAIT);
  368. if (!circ->n_conn &&
  369. circ->n_addr == or_conn->addr &&
  370. circ->n_port == or_conn->port &&
  371. !memcmp(or_conn->identity_digest, circ->n_conn_id_digest, DIGEST_LEN)) {
  372. if (!status) { /* or_conn failed; close circ */
  373. info(LD_CIRC,"or_conn failed. Closing circ.");
  374. circuit_mark_for_close(circ);
  375. continue;
  376. }
  377. debug(LD_CIRC,"Found circ %d, sending create cell.", circ->n_circ_id);
  378. /* circuit_deliver_create_cell will set n_circ_id and add us to
  379. * orconn_circuid_circuit_map, so we don't need to call
  380. * set_circid_orconn here. */
  381. circ->n_conn = or_conn;
  382. memcpy(circ->n_conn_id_digest, or_conn->identity_digest, DIGEST_LEN);
  383. if (CIRCUIT_IS_ORIGIN(circ)) {
  384. if (circuit_send_next_onion_skin(circ) < 0) {
  385. info(LD_CIRC,"send_next_onion_skin failed; circuit marked for closing.");
  386. circuit_mark_for_close(circ);
  387. continue;
  388. /* XXX could this be bad, eg if next_onion_skin failed because conn died? */
  389. }
  390. } else {
  391. /* pull the create cell out of circ->onionskin, and send it */
  392. tor_assert(circ->onionskin);
  393. if (circuit_deliver_create_cell(circ,CELL_CREATE,circ->onionskin) < 0) {
  394. circuit_mark_for_close(circ);
  395. continue;
  396. }
  397. tor_free(circ->onionskin);
  398. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  399. }
  400. }
  401. });
  402. }
  403. /** Find a new circid that isn't currently in use by the outgoing
  404. * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
  405. * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
  406. * to this circuit.
  407. * Return -1 if we failed to find a suitable circid, else return 0.
  408. */
  409. static int
  410. circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type, char *payload)
  411. {
  412. cell_t cell;
  413. uint16_t id;
  414. tor_assert(circ);
  415. tor_assert(circ->n_conn);
  416. tor_assert(circ->n_conn->type == CONN_TYPE_OR);
  417. tor_assert(payload);
  418. tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
  419. id = get_unique_circ_id_by_conn(circ->n_conn);
  420. if (!id) {
  421. warn(LD_CIRC,"failed to get unique circID.");
  422. return -1;
  423. }
  424. debug(LD_CIRC,"Chosen circID %u.", id);
  425. circuit_set_circid_orconn(circ, id, circ->n_conn, N_CONN_CHANGED);
  426. memset(&cell, 0, sizeof(cell_t));
  427. cell.command = cell_type;
  428. cell.circ_id = circ->n_circ_id;
  429. memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
  430. connection_or_write_cell_to_buf(&cell, circ->n_conn);
  431. return 0;
  432. }
  433. /** We've decided to start our reachability testing. If all
  434. * is set, log this to the user. Return 1 if we did, or 0 if
  435. * we chose not to log anything. */
  436. static int
  437. inform_testing_reachability(void)
  438. {
  439. char dirbuf[128];
  440. routerinfo_t *me = router_get_my_routerinfo();
  441. if (!me)
  442. return 0;
  443. if (me->dir_port)
  444. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  445. me->address, me->dir_port);
  446. log(LOG_NOTICE, LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... (this may take several minutes)",
  447. me->address, me->or_port,
  448. me->dir_port ? dirbuf : "",
  449. me->dir_port ? "are" : "is");
  450. return 1;
  451. }
  452. extern int has_completed_circuit;
  453. /** This is the backbone function for building circuits.
  454. *
  455. * If circ's first hop is closed, then we need to build a create
  456. * cell and send it forward.
  457. *
  458. * Otherwise, we need to build a relay extend cell and send it
  459. * forward.
  460. *
  461. * Return -1 if we want to tear down circ, else return 0.
  462. */
  463. int
  464. circuit_send_next_onion_skin(circuit_t *circ)
  465. {
  466. crypt_path_t *hop;
  467. routerinfo_t *router;
  468. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  469. char *onionskin;
  470. size_t payload_len;
  471. tor_assert(circ);
  472. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  473. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  474. uint8_t cell_type;
  475. debug(LD_CIRC,"First skin; sending create cell.");
  476. router = router_get_by_digest(circ->n_conn->identity_digest);
  477. if (1 || /* Disable this '1' once we believe CREATE_FAST works. XXXX */
  478. (get_options()->ORPort || !router || !router->platform ||
  479. !tor_version_as_new_as(router->platform, "0.1.0.6-rc"))) {
  480. /* We are an OR, or we are connecting to an old Tor: we should
  481. * send an old slow create cell.
  482. */
  483. cell_type = CELL_CREATE;
  484. if (onion_skin_create(circ->cpath->extend_info->onion_key,
  485. &(circ->cpath->dh_handshake_state),
  486. payload) < 0) {
  487. warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  488. return -1;
  489. }
  490. } else {
  491. /* We are not an OR, and we're building the first hop of a circuit to
  492. * a new OR: we can be speedy. */
  493. cell_type = CELL_CREATE_FAST;
  494. memset(payload, 0, sizeof(payload));
  495. crypto_rand(circ->cpath->fast_handshake_state,
  496. sizeof(circ->cpath->fast_handshake_state));
  497. memcpy(payload, circ->cpath->fast_handshake_state,
  498. sizeof(circ->cpath->fast_handshake_state));
  499. }
  500. if (circuit_deliver_create_cell(circ, cell_type, payload) < 0)
  501. return -1;
  502. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  503. circuit_set_state(circ, CIRCUIT_STATE_BUILDING);
  504. debug(LD_CIRC,"first skin; finished sending create cell.");
  505. } else {
  506. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  507. tor_assert(circ->state == CIRCUIT_STATE_BUILDING);
  508. debug(LD_CIRC,"starting to send subsequent skin.");
  509. hop = onion_next_hop_in_cpath(circ->cpath);
  510. if (!hop) {
  511. /* done building the circuit. whew. */
  512. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  513. info(LD_CIRC,"circuit built!");
  514. circuit_reset_failure_count(0);
  515. if (!has_completed_circuit) {
  516. or_options_t *options = get_options();
  517. has_completed_circuit=1;
  518. /* FFFF Log a count of known routers here */
  519. log(LOG_NOTICE, LD_GENERAL,
  520. "Tor has successfully opened a circuit. Looks like it's working.");
  521. if (server_mode(options) && !check_whether_orport_reachable()) {
  522. inform_testing_reachability();
  523. }
  524. }
  525. circuit_rep_hist_note_result(circ);
  526. circuit_has_opened(circ); /* do other actions as necessary */
  527. return 0;
  528. }
  529. *(uint32_t*)payload = htonl(hop->extend_info->addr);
  530. *(uint16_t*)(payload+4) = htons(hop->extend_info->port);
  531. onionskin = payload+2+4;
  532. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN, hop->extend_info->identity_digest, DIGEST_LEN);
  533. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  534. if (onion_skin_create(hop->extend_info->onion_key,
  535. &(hop->dh_handshake_state), onionskin) < 0) {
  536. warn(LD_CIRC,"onion_skin_create failed.");
  537. return -1;
  538. }
  539. debug(LD_CIRC,"Sending extend relay cell.");
  540. /* send it to hop->prev, because it will transfer
  541. * it to a create cell and then send to hop */
  542. if (connection_edge_send_command(NULL, circ, RELAY_COMMAND_EXTEND,
  543. payload, payload_len, hop->prev) < 0)
  544. return 0; /* circuit is closed */
  545. hop->state = CPATH_STATE_AWAITING_KEYS;
  546. }
  547. return 0;
  548. }
  549. /** Our clock just jumped forward by <b>seconds_elapsed</b>. Assume
  550. * something has also gone wrong with our network: notify the user,
  551. * and abandon all not-yet-used circuits. */
  552. void
  553. circuit_note_clock_jumped(int seconds_elapsed)
  554. {
  555. log(LOG_NOTICE, LD_GENERAL,"Your clock just jumped %d seconds forward; assuming established circuits no longer work.", seconds_elapsed);
  556. has_completed_circuit=0; /* so it'll log when it works again */
  557. circuit_mark_all_unused_circs();
  558. }
  559. /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
  560. * sure we're connected to the next hop, and pass it the onion skin using
  561. * a create cell. Return -1 if we want to warn and tear down the circuit,
  562. * else return 0.
  563. */
  564. int
  565. circuit_extend(cell_t *cell, circuit_t *circ)
  566. {
  567. connection_t *n_conn;
  568. relay_header_t rh;
  569. char *onionskin;
  570. char *id_digest=NULL;
  571. if (circ->n_conn) {
  572. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
  573. "n_conn already set. Bug/attack. Closing.");
  574. return -1;
  575. }
  576. relay_header_unpack(&rh, cell->payload);
  577. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  578. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,"Wrong length %d on extend cell. Closing circuit.", rh.length);
  579. return -1;
  580. }
  581. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  582. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  583. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  584. id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
  585. n_conn = connection_or_get_by_identity_digest(id_digest);
  586. if (!n_conn || n_conn->state != OR_CONN_STATE_OPEN ||
  587. (n_conn->is_obsolete &&
  588. router_digest_version_as_new_as(id_digest,"0.1.1.9-alpha-cvs"))) {
  589. /* Note that this will close circuits where the onion has the same
  590. * router twice in a row in the path. I think that's ok.
  591. */
  592. struct in_addr in;
  593. char tmpbuf[INET_NTOA_BUF_LEN];
  594. in.s_addr = htonl(circ->n_addr);
  595. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  596. info(LD_CIRC|LD_OR,"Next router (%s:%d) not connected. Connecting.",
  597. tmpbuf, circ->n_port);
  598. circ->onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
  599. memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  600. circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
  601. /* imprint the circuit with its future n_conn->id */
  602. memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
  603. if (n_conn && !n_conn->is_obsolete) {
  604. circ->n_addr = n_conn->addr;
  605. circ->n_port = n_conn->port;
  606. } else {
  607. /* we should try to open a connection */
  608. n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
  609. if (!n_conn) {
  610. info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
  611. circuit_mark_for_close(circ);
  612. return 0;
  613. }
  614. debug(LD_CIRC,"connecting in progress (or finished). Good.");
  615. }
  616. /* return success. The onion/circuit/etc will be taken care of automatically
  617. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  618. */
  619. return 0;
  620. }
  621. /* these may be different if the router connected to us from elsewhere */
  622. circ->n_addr = n_conn->addr;
  623. circ->n_port = n_conn->port;
  624. circ->n_conn = n_conn;
  625. memcpy(circ->n_conn_id_digest, n_conn->identity_digest, DIGEST_LEN);
  626. debug(LD_CIRC,"n_conn is %s:%u",n_conn->address,n_conn->port);
  627. if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
  628. return -1;
  629. return 0;
  630. }
  631. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  632. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  633. * used as follows:
  634. * - 20 to initialize f_digest
  635. * - 20 to initialize b_digest
  636. * - 16 to key f_crypto
  637. * - 16 to key b_crypto
  638. *
  639. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  640. */
  641. int
  642. circuit_init_cpath_crypto(crypt_path_t *cpath, char *key_data, int reverse)
  643. {
  644. crypto_digest_env_t *tmp_digest;
  645. crypto_cipher_env_t *tmp_crypto;
  646. tor_assert(cpath);
  647. tor_assert(key_data);
  648. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  649. cpath->f_digest || cpath->b_digest));
  650. // log_fn(LOG_DEBUG,"hop init digest forward 0x%.8x, backward 0x%.8x.",
  651. // (unsigned int)*(uint32_t*)key_data, (unsigned int)*(uint32_t*)(key_data+20));
  652. cpath->f_digest = crypto_new_digest_env();
  653. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  654. cpath->b_digest = crypto_new_digest_env();
  655. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  656. // log_fn(LOG_DEBUG,"hop init cipher forward 0x%.8x, backward 0x%.8x.",
  657. // (unsigned int)*(uint32_t*)(key_data+40), (unsigned int)*(uint32_t*)(key_data+40+16));
  658. if (!(cpath->f_crypto =
  659. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  660. warn(LD_BUG,"Bug: forward cipher initialization failed.");
  661. return -1;
  662. }
  663. if (!(cpath->b_crypto =
  664. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  665. warn(LD_BUG,"Bug: backward cipher initialization failed.");
  666. return -1;
  667. }
  668. if (reverse) {
  669. tmp_digest = cpath->f_digest;
  670. cpath->f_digest = cpath->b_digest;
  671. cpath->b_digest = tmp_digest;
  672. tmp_crypto = cpath->f_crypto;
  673. cpath->f_crypto = cpath->b_crypto;
  674. cpath->b_crypto = tmp_crypto;
  675. }
  676. return 0;
  677. }
  678. /** A created or extended cell came back to us on the circuit,
  679. * and it included <b>reply</b> (the second DH key, plus KH).
  680. * DOCDOC reply_type.
  681. *
  682. * Calculate the appropriate keys and digests, make sure KH is
  683. * correct, and initialize this hop of the cpath.
  684. *
  685. * Return -1 if we want to mark circ for close, else return 0.
  686. */
  687. int
  688. circuit_finish_handshake(circuit_t *circ, uint8_t reply_type, char *reply)
  689. {
  690. char keys[CPATH_KEY_MATERIAL_LEN];
  691. crypt_path_t *hop;
  692. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  693. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  694. hop = circ->cpath;
  695. else {
  696. hop = onion_next_hop_in_cpath(circ->cpath);
  697. if (!hop) { /* got an extended when we're all done? */
  698. warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  699. return -1;
  700. }
  701. }
  702. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  703. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  704. if (onion_skin_client_handshake(hop->dh_handshake_state, reply, keys,
  705. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  706. warn(LD_CIRC,"onion_skin_client_handshake failed.");
  707. return -1;
  708. }
  709. /* Remember hash of g^xy */
  710. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  711. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  712. if (fast_client_handshake(hop->fast_handshake_state, reply, keys,
  713. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  714. warn(LD_CIRC,"fast_client_handshake failed.");
  715. return -1;
  716. }
  717. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  718. } else {
  719. warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  720. return -1;
  721. }
  722. if (hop->dh_handshake_state) {
  723. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  724. hop->dh_handshake_state = NULL;
  725. }
  726. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  727. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  728. return -1;
  729. }
  730. hop->state = CPATH_STATE_OPEN;
  731. info(LD_CIRC,"Finished building circuit hop:");
  732. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  733. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED);
  734. return 0;
  735. }
  736. /** We received a relay truncated cell on circ.
  737. *
  738. * Since we don't ask for truncates currently, getting a truncated
  739. * means that a connection broke or an extend failed. For now,
  740. * just give up: for circ to close, and return 0.
  741. */
  742. int
  743. circuit_truncated(circuit_t *circ, crypt_path_t *layer)
  744. {
  745. // crypt_path_t *victim;
  746. // connection_t *stream;
  747. tor_assert(circ);
  748. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  749. tor_assert(layer);
  750. /* XXX Since we don't ask for truncates currently, getting a truncated
  751. * means that a connection broke or an extend failed. For now,
  752. * just give up.
  753. */
  754. circuit_mark_for_close(circ);
  755. return 0;
  756. #if 0
  757. while (layer->next != circ->cpath) {
  758. /* we need to clear out layer->next */
  759. victim = layer->next;
  760. debug(LD_CIRC, "Killing a layer of the cpath.");
  761. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  762. if (stream->cpath_layer == victim) {
  763. /* XXXX NM LD_CIRC? */
  764. info(LD_APP, "Marking stream %d for close.", stream->stream_id);
  765. /* no need to send 'end' relay cells,
  766. * because the other side's already dead
  767. */
  768. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  769. }
  770. }
  771. layer->next = victim->next;
  772. circuit_free_cpath_node(victim);
  773. }
  774. info(LD_CIRC, "finished");
  775. return 0;
  776. #endif
  777. }
  778. /** Given a response payload and keys, initialize, then send a created
  779. * cell back.
  780. */
  781. int
  782. onionskin_answer(circuit_t *circ, uint8_t cell_type, char *payload, char *keys)
  783. {
  784. cell_t cell;
  785. crypt_path_t *tmp_cpath;
  786. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  787. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  788. memset(&cell, 0, sizeof(cell_t));
  789. cell.command = cell_type;
  790. cell.circ_id = circ->p_circ_id;
  791. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  792. memcpy(cell.payload, payload,
  793. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  794. debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  795. (unsigned int)*(uint32_t*)(keys), (unsigned int)*(uint32_t*)(keys+20));
  796. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  797. warn(LD_BUG,"Circuit initialization failed");
  798. tor_free(tmp_cpath);
  799. return -1;
  800. }
  801. circ->n_digest = tmp_cpath->f_digest;
  802. circ->n_crypto = tmp_cpath->f_crypto;
  803. circ->p_digest = tmp_cpath->b_digest;
  804. circ->p_crypto = tmp_cpath->b_crypto;
  805. tmp_cpath->magic = 0;
  806. tor_free(tmp_cpath);
  807. if (cell_type == CELL_CREATED)
  808. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  809. else
  810. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  811. connection_or_write_cell_to_buf(&cell, circ->p_conn);
  812. debug(LD_CIRC,"Finished sending 'created' cell.");
  813. if (!is_local_IP(circ->p_conn->addr) &&
  814. tor_tls_is_server(circ->p_conn->tls)) {
  815. /* record that we could process create cells from a non-local conn
  816. * that we didn't initiate; presumably this means that create cells
  817. * can reach us too. */
  818. router_orport_found_reachable();
  819. }
  820. return 0;
  821. }
  822. /** Choose a length for a circuit of purpose <b>purpose</b>.
  823. * Default length is 3 + the number of endpoints that would give something
  824. * away. If the routerlist <b>routers</b> doesn't have enough routers
  825. * to handle the desired path length, return as large a path length as
  826. * is feasible, except if it's less than 2, in which case return -1.
  827. */
  828. static int
  829. new_route_len(double cw, uint8_t purpose, extend_info_t *exit,
  830. smartlist_t *routers)
  831. {
  832. int num_acceptable_routers;
  833. int routelen;
  834. tor_assert(cw >= 0.);
  835. tor_assert(cw < 1.);
  836. tor_assert(routers);
  837. #ifdef TOR_PERF
  838. routelen = 2;
  839. #else
  840. routelen = 3;
  841. if (exit &&
  842. purpose != CIRCUIT_PURPOSE_TESTING &&
  843. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  844. routelen++;
  845. #endif
  846. debug(LD_CIRC,"Chosen route length %d (%d routers available).",routelen,
  847. smartlist_len(routers));
  848. num_acceptable_routers = count_acceptable_routers(routers);
  849. if (num_acceptable_routers < 2) {
  850. info(LD_CIRC,"Not enough acceptable routers (%d). Discarding this circuit.",
  851. num_acceptable_routers);
  852. return -1;
  853. }
  854. if (num_acceptable_routers < routelen) {
  855. info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  856. routelen, num_acceptable_routers);
  857. routelen = num_acceptable_routers;
  858. }
  859. return routelen;
  860. }
  861. /** Fetch the list of predicted ports, dup it into a smartlist of
  862. * uint16_t's, remove the ones that are already handled by an
  863. * existing circuit, and return it.
  864. */
  865. static smartlist_t *
  866. circuit_get_unhandled_ports(time_t now)
  867. {
  868. smartlist_t *source = rep_hist_get_predicted_ports(now);
  869. smartlist_t *dest = smartlist_create();
  870. uint16_t *tmp;
  871. int i;
  872. for (i = 0; i < smartlist_len(source); ++i) {
  873. tmp = tor_malloc(sizeof(uint16_t));
  874. memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
  875. smartlist_add(dest, tmp);
  876. }
  877. circuit_remove_handled_ports(dest);
  878. return dest;
  879. }
  880. /** Return 1 if we already have circuits present or on the way for
  881. * all anticipated ports. Return 0 if we should make more.
  882. *
  883. * If we're returning 0, set need_uptime and need_capacity to
  884. * indicate any requirements that the unhandled ports have.
  885. */
  886. int
  887. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  888. int *need_capacity)
  889. {
  890. int i, enough;
  891. uint16_t *port;
  892. smartlist_t *sl = circuit_get_unhandled_ports(now);
  893. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  894. tor_assert(need_uptime);
  895. tor_assert(need_capacity);
  896. enough = (smartlist_len(sl) == 0);
  897. for (i = 0; i < smartlist_len(sl); ++i) {
  898. port = smartlist_get(sl, i);
  899. if (smartlist_string_num_isin(LongLivedServices, *port))
  900. *need_uptime = 1;
  901. tor_free(port);
  902. }
  903. smartlist_free(sl);
  904. return enough;
  905. }
  906. /** Return 1 if <b>router</b> can handle one or more of the ports in
  907. * <b>needed_ports</b>, else return 0.
  908. */
  909. static int
  910. router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
  911. {
  912. int i;
  913. uint16_t port;
  914. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  915. addr_policy_result_t r;
  916. port = *(uint16_t *)smartlist_get(needed_ports, i);
  917. tor_assert(port);
  918. r = router_compare_addr_to_addr_policy(0, port, router->exit_policy);
  919. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  920. return 1;
  921. }
  922. return 0;
  923. }
  924. /** How many circuits do we want simultaneously in-progress to handle
  925. * a given stream?
  926. */
  927. #define MIN_CIRCUITS_HANDLING_STREAM 2
  928. static int
  929. ap_stream_wants_exit_attention(connection_t *conn)
  930. {
  931. if (conn->type == CONN_TYPE_AP &&
  932. conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  933. !conn->marked_for_close &&
  934. !connection_edge_is_rendezvous_stream(conn) &&
  935. !circuit_stream_is_being_handled(conn, 0, MIN_CIRCUITS_HANDLING_STREAM))
  936. return 1;
  937. return 0;
  938. }
  939. /** Return a pointer to a suitable router to be the exit node for the
  940. * general-purpose circuit we're about to build.
  941. *
  942. * Look through the connection array, and choose a router that maximizes
  943. * the number of pending streams that can exit from this router.
  944. *
  945. * Return NULL if we can't find any suitable routers.
  946. */
  947. static routerinfo_t *
  948. choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
  949. int need_capacity)
  950. {
  951. int *n_supported;
  952. int i, j;
  953. int n_pending_connections = 0;
  954. connection_t **carray;
  955. int n_connections;
  956. int best_support = -1;
  957. int n_best_support=0;
  958. smartlist_t *sl, *preferredexits, *preferredentries, *excludedexits;
  959. routerinfo_t *router;
  960. or_options_t *options = get_options();
  961. preferredentries = smartlist_create();
  962. add_nickname_list_to_smartlist(preferredentries,options->EntryNodes,1,1);
  963. get_connection_array(&carray, &n_connections);
  964. /* Count how many connections are waiting for a circuit to be built.
  965. * We use this for log messages now, but in the future we may depend on it.
  966. */
  967. for (i = 0; i < n_connections; ++i) {
  968. if (ap_stream_wants_exit_attention(carray[i]))
  969. ++n_pending_connections;
  970. }
  971. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  972. // n_pending_connections);
  973. /* Now we count, for each of the routers in the directory, how many
  974. * of the pending connections could possibly exit from that
  975. * router (n_supported[i]). (We can't be sure about cases where we
  976. * don't know the IP address of the pending connection.)
  977. */
  978. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  979. for (i = 0; i < smartlist_len(dir->routers); ++i) { /* iterate over routers */
  980. router = smartlist_get(dir->routers, i);
  981. if (router_is_me(router)) {
  982. n_supported[i] = -1;
  983. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  984. /* XXX there's probably a reverse predecessor attack here, but
  985. * it's slow. should we take this out? -RD
  986. */
  987. continue;
  988. }
  989. if (!router->is_running) {
  990. n_supported[i] = -1;
  991. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- directory says it's not running.",
  992. // router->nickname, i);
  993. continue; /* skip routers that are known to be down */
  994. }
  995. if (router_is_unreliable(router, need_uptime, need_capacity)) {
  996. n_supported[i] = -1;
  997. continue; /* skip routers that are not suitable */
  998. }
  999. if (!router->is_verified &&
  1000. (!(options->_AllowUnverified & ALLOW_UNVERIFIED_EXIT) ||
  1001. router_is_unreliable(router, 1, 1))) {
  1002. /* if it's unverified, and either we don't want it or it's unsuitable */
  1003. n_supported[i] = -1;
  1004. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- unverified router.",
  1005. // router->nickname, i);
  1006. continue; /* skip unverified routers */
  1007. }
  1008. if (router_exit_policy_rejects_all(router)) {
  1009. n_supported[i] = -1;
  1010. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1011. // router->nickname, i);
  1012. continue; /* skip routers that reject all */
  1013. }
  1014. if (smartlist_len(preferredentries)==1 &&
  1015. router == (routerinfo_t*)smartlist_get(preferredentries, 0)) {
  1016. n_supported[i] = -1;
  1017. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it's our only preferred entry node.", router->nickname, i);
  1018. continue;
  1019. }
  1020. n_supported[i] = 0;
  1021. for (j = 0; j < n_connections; ++j) { /* iterate over connections */
  1022. if (!ap_stream_wants_exit_attention(carray[j]))
  1023. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1024. if (connection_ap_can_use_exit(carray[j], router)) {
  1025. ++n_supported[i];
  1026. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1027. // router->nickname, i, n_supported[i]);
  1028. } else {
  1029. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1030. // router->nickname, i);
  1031. }
  1032. } /* End looping over connections. */
  1033. if (n_supported[i] > best_support) {
  1034. /* If this router is better than previous ones, remember its index
  1035. * and goodness, and start counting how many routers are this good. */
  1036. best_support = n_supported[i]; n_best_support=1;
  1037. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1038. // router->nickname);
  1039. } else if (n_supported[i] == best_support) {
  1040. /* If this router is _as good_ as the best one, just increment the
  1041. * count of equally good routers.*/
  1042. ++n_best_support;
  1043. }
  1044. }
  1045. info(LD_CIRC, "Found %d servers that might support %d/%d pending connections.",
  1046. n_best_support, best_support, n_pending_connections);
  1047. preferredexits = smartlist_create();
  1048. add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1,1);
  1049. excludedexits = smartlist_create();
  1050. add_nickname_list_to_smartlist(excludedexits,options->ExcludeNodes,0,1);
  1051. sl = smartlist_create();
  1052. /* If any routers definitely support any pending connections, choose one
  1053. * at random. */
  1054. if (best_support > 0) {
  1055. for (i = 0; i < smartlist_len(dir->routers); i++)
  1056. if (n_supported[i] == best_support)
  1057. smartlist_add(sl, smartlist_get(dir->routers, i));
  1058. smartlist_subtract(sl,excludedexits);
  1059. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1060. smartlist_intersect(sl,preferredexits);
  1061. router = routerlist_sl_choose_by_bandwidth(sl);
  1062. } else {
  1063. /* Either there are no pending connections, or no routers even seem to
  1064. * possibly support any of them. Choose a router at random that satisfies
  1065. * at least one predicted exit port. */
  1066. int try;
  1067. smartlist_t *needed_ports = circuit_get_unhandled_ports(time(NULL));
  1068. if (best_support == -1) {
  1069. if (need_uptime || need_capacity) {
  1070. info(LD_CIRC, "We couldn't find any live%s%s routers; falling back to list of all routers.",
  1071. need_capacity?", fast":"",
  1072. need_uptime?", stable":"");
  1073. return choose_good_exit_server_general(dir, 0, 0);
  1074. }
  1075. notice(LD_CIRC, "All routers are down or middleman -- choosing a doomed exit at random.");
  1076. }
  1077. for (try = 0; try < 2; try++) {
  1078. /* try once to pick only from routers that satisfy a needed port,
  1079. * then if there are none, pick from any that support exiting. */
  1080. for (i = 0; i < smartlist_len(dir->routers); i++) {
  1081. router = smartlist_get(dir->routers, i);
  1082. if (n_supported[i] != -1 &&
  1083. (try || router_handles_some_port(router, needed_ports))) {
  1084. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.", try, router->nickname);
  1085. smartlist_add(sl, router);
  1086. }
  1087. }
  1088. smartlist_subtract(sl,excludedexits);
  1089. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1090. smartlist_intersect(sl,preferredexits);
  1091. /* XXX sometimes the above results in null, when the requested
  1092. * exit node is down. we should pick it anyway. */
  1093. router = routerlist_sl_choose_by_bandwidth(sl);
  1094. if (router)
  1095. break;
  1096. }
  1097. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1098. smartlist_free(needed_ports);
  1099. }
  1100. smartlist_free(preferredexits);
  1101. smartlist_free(preferredentries);
  1102. smartlist_free(excludedexits);
  1103. smartlist_free(sl);
  1104. tor_free(n_supported);
  1105. if (router) {
  1106. info(LD_CIRC, "Chose exit server '%s'", router->nickname);
  1107. return router;
  1108. }
  1109. if (options->StrictExitNodes) {
  1110. warn(LD_CIRC, "No exit routers seem to be running; can't choose an exit.");
  1111. }
  1112. return NULL;
  1113. }
  1114. /** Return a pointer to a suitable router to be the exit node for the
  1115. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1116. * if no router is suitable).
  1117. *
  1118. * For general-purpose circuits, pass it off to
  1119. * choose_good_exit_server_general()
  1120. *
  1121. * For client-side rendezvous circuits, choose a random node, weighted
  1122. * toward the preferences in 'options'.
  1123. */
  1124. static routerinfo_t *
  1125. choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
  1126. int need_uptime, int need_capacity, int is_internal)
  1127. {
  1128. or_options_t *options = get_options();
  1129. switch (purpose) {
  1130. case CIRCUIT_PURPOSE_C_GENERAL:
  1131. if (is_internal) /* pick it like a middle hop */
  1132. return router_choose_random_node(NULL, get_options()->ExcludeNodes,
  1133. NULL, need_uptime, need_capacity,
  1134. get_options()->_AllowUnverified & ALLOW_UNVERIFIED_MIDDLE, 0);
  1135. else
  1136. return choose_good_exit_server_general(dir, need_uptime, need_capacity);
  1137. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1138. return router_choose_random_node(options->RendNodes, options->RendExcludeNodes,
  1139. NULL, need_uptime, need_capacity,
  1140. options->_AllowUnverified & ALLOW_UNVERIFIED_RENDEZVOUS, 0);
  1141. }
  1142. warn(LD_BUG,"Bug: unhandled purpose %d", purpose);
  1143. tor_fragile_assert();
  1144. return NULL;
  1145. }
  1146. /** Decide a suitable length for circ's cpath, and pick an exit
  1147. * router (or use <b>exit</b> if provided). Store these in the
  1148. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1149. static int
  1150. onion_pick_cpath_exit(circuit_t *circ, extend_info_t *exit)
  1151. {
  1152. cpath_build_state_t *state = circ->build_state;
  1153. routerlist_t *rl = router_get_routerlist();
  1154. int r;
  1155. r = new_route_len(get_options()->PathlenCoinWeight, circ->purpose,
  1156. exit, rl->routers);
  1157. if (r < 1) /* must be at least 1 */
  1158. return -1;
  1159. state->desired_path_len = r;
  1160. if (exit) { /* the circuit-builder pre-requested one */
  1161. info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
  1162. exit = extend_info_dup(exit);
  1163. } else { /* we have to decide one */
  1164. routerinfo_t *router =
  1165. choose_good_exit_server(circ->purpose, rl, state->need_uptime,
  1166. state->need_capacity, state->is_internal);
  1167. if (!router) {
  1168. warn(LD_CIRC,"failed to choose an exit server");
  1169. return -1;
  1170. }
  1171. exit = extend_info_from_router(router);
  1172. }
  1173. state->chosen_exit = exit;
  1174. return 0;
  1175. }
  1176. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1177. * hop to the cpath reflecting this. Don't send the next extend cell --
  1178. * the caller will do this if it wants to.
  1179. */
  1180. int
  1181. circuit_append_new_exit(circuit_t *circ, extend_info_t *info)
  1182. {
  1183. cpath_build_state_t *state;
  1184. tor_assert(info);
  1185. tor_assert(circ && CIRCUIT_IS_ORIGIN(circ));
  1186. state = circ->build_state;
  1187. tor_assert(state);
  1188. if (state->chosen_exit)
  1189. extend_info_free(state->chosen_exit);
  1190. state->chosen_exit = extend_info_dup(info);
  1191. ++circ->build_state->desired_path_len;
  1192. onion_append_hop(&circ->cpath, info);
  1193. return 0;
  1194. }
  1195. /** DOCDOC */
  1196. int
  1197. circuit_extend_to_new_exit(circuit_t *circ, extend_info_t *info)
  1198. {
  1199. circuit_append_new_exit(circ, info);
  1200. circuit_set_state(circ, CIRCUIT_STATE_BUILDING);
  1201. if (circuit_send_next_onion_skin(circ)<0) {
  1202. warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
  1203. info->nickname);
  1204. circuit_mark_for_close(circ);
  1205. return -1;
  1206. }
  1207. return 0;
  1208. }
  1209. /** Return the number of routers in <b>routers</b> that are currently up
  1210. * and available for building circuits through.
  1211. */
  1212. static int
  1213. count_acceptable_routers(smartlist_t *routers)
  1214. {
  1215. int i, n;
  1216. int num=0;
  1217. routerinfo_t *r;
  1218. n = smartlist_len(routers);
  1219. for (i=0;i<n;i++) {
  1220. r = smartlist_get(routers, i);
  1221. // log_fn(LOG_DEBUG,"Contemplating whether router %d (%s) is a new option...",
  1222. // i, r->nickname);
  1223. if (r->is_running == 0) {
  1224. // log_fn(LOG_DEBUG,"Nope, the directory says %d is not running.",i);
  1225. goto next_i_loop;
  1226. }
  1227. if (r->is_verified == 0) {
  1228. // log_fn(LOG_DEBUG,"Nope, the directory says %d is not verified.",i);
  1229. /* XXXX009 But unverified routers *are* sometimes acceptable. */
  1230. goto next_i_loop;
  1231. }
  1232. num++;
  1233. // log_fn(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  1234. next_i_loop:
  1235. ; /* C requires an explicit statement after the label */
  1236. }
  1237. return num;
  1238. }
  1239. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1240. *
  1241. * This function is used to extend cpath by another hop.
  1242. */
  1243. void
  1244. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1245. {
  1246. if (*head_ptr) {
  1247. new_hop->next = (*head_ptr);
  1248. new_hop->prev = (*head_ptr)->prev;
  1249. (*head_ptr)->prev->next = new_hop;
  1250. (*head_ptr)->prev = new_hop;
  1251. } else {
  1252. *head_ptr = new_hop;
  1253. new_hop->prev = new_hop->next = new_hop;
  1254. }
  1255. }
  1256. /** DOCDOC */
  1257. static routerinfo_t *
  1258. choose_good_middle_server(uint8_t purpose,
  1259. cpath_build_state_t *state,
  1260. crypt_path_t *head,
  1261. int cur_len)
  1262. {
  1263. int i;
  1264. routerinfo_t *r, *choice;
  1265. crypt_path_t *cpath;
  1266. smartlist_t *excluded;
  1267. tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
  1268. purpose <= _CIRCUIT_PURPOSE_MAX);
  1269. debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1270. excluded = smartlist_create();
  1271. if ((r = build_state_get_exit_router(state))) {
  1272. smartlist_add(excluded, r);
  1273. routerlist_add_family(excluded, r);
  1274. }
  1275. if ((r = routerlist_find_my_routerinfo())) {
  1276. smartlist_add(excluded, r);
  1277. routerlist_add_family(excluded, r);
  1278. }
  1279. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1280. if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
  1281. smartlist_add(excluded, r);
  1282. routerlist_add_family(excluded, r);
  1283. }
  1284. }
  1285. choice = router_choose_random_node(NULL, get_options()->ExcludeNodes, excluded,
  1286. state->need_uptime, state->need_capacity,
  1287. get_options()->_AllowUnverified & ALLOW_UNVERIFIED_MIDDLE, 0);
  1288. smartlist_free(excluded);
  1289. return choice;
  1290. }
  1291. /** Pick a good entry server for the circuit to be built according to
  1292. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this router
  1293. * (if we're an OR), and respect firewall settings; if we're using helper nodes,
  1294. * return one.
  1295. *
  1296. * If <b>state</b> is NULL, we're choosing entries to serve as helper nodes,
  1297. * not for any particular circuit.
  1298. */
  1299. static routerinfo_t *
  1300. choose_good_entry_server(cpath_build_state_t *state)
  1301. {
  1302. routerinfo_t *r, *choice;
  1303. smartlist_t *excluded = smartlist_create();
  1304. or_options_t *options = get_options();
  1305. if (state && options->UseHelperNodes) {
  1306. return choose_random_helper();
  1307. }
  1308. if (state && (r = build_state_get_exit_router(state))) {
  1309. smartlist_add(excluded, r);
  1310. routerlist_add_family(excluded, r);
  1311. }
  1312. if ((r = routerlist_find_my_routerinfo())) {
  1313. smartlist_add(excluded, r);
  1314. routerlist_add_family(excluded, r);
  1315. }
  1316. if (firewall_is_fascist()) {
  1317. /* exclude all ORs that listen on the wrong port */
  1318. routerlist_t *rl = router_get_routerlist();
  1319. int i;
  1320. for (i=0; i < smartlist_len(rl->routers); i++) {
  1321. r = smartlist_get(rl->routers, i);
  1322. if (!fascist_firewall_allows_address(r->addr,r->or_port))
  1323. smartlist_add(excluded, r);
  1324. }
  1325. }
  1326. choice = router_choose_random_node(options->EntryNodes, options->ExcludeNodes,
  1327. excluded, state ? state->need_uptime : 1,
  1328. state ? state->need_capacity : 0,
  1329. options->_AllowUnverified & ALLOW_UNVERIFIED_ENTRY,
  1330. options->StrictEntryNodes);
  1331. smartlist_free(excluded);
  1332. return choice;
  1333. }
  1334. /** Return the first non-open hop in cpath, or return NULL if all
  1335. * hops are open. */
  1336. static crypt_path_t *
  1337. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1338. {
  1339. crypt_path_t *hop = cpath;
  1340. do {
  1341. if (hop->state != CPATH_STATE_OPEN)
  1342. return hop;
  1343. hop = hop->next;
  1344. } while (hop != cpath);
  1345. return NULL;
  1346. }
  1347. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1348. * based on <b>state</b>. Append the hop info to head_ptr.
  1349. */
  1350. static int
  1351. onion_extend_cpath(uint8_t purpose, crypt_path_t **head_ptr,
  1352. cpath_build_state_t *state)
  1353. {
  1354. int cur_len;
  1355. crypt_path_t *cpath;
  1356. extend_info_t *info = NULL;
  1357. tor_assert(head_ptr);
  1358. if (!*head_ptr) {
  1359. cur_len = 0;
  1360. } else {
  1361. cur_len = 1;
  1362. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  1363. ++cur_len;
  1364. }
  1365. }
  1366. if (cur_len >= state->desired_path_len) {
  1367. debug(LD_CIRC, "Path is complete: %d steps long",
  1368. state->desired_path_len);
  1369. return 1;
  1370. }
  1371. debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  1372. state->desired_path_len);
  1373. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1374. info = extend_info_dup(state->chosen_exit);
  1375. } else if (cur_len == 0) { /* picking first node */
  1376. routerinfo_t *r = choose_good_entry_server(state);
  1377. if (r)
  1378. info = extend_info_from_router(r);
  1379. } else {
  1380. routerinfo_t *r =
  1381. choose_good_middle_server(purpose, state, *head_ptr, cur_len);
  1382. if (r)
  1383. info = extend_info_from_router(r);
  1384. }
  1385. if (!info) {
  1386. warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding this circuit.", cur_len);
  1387. return -1;
  1388. }
  1389. debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  1390. info->nickname, cur_len+1, build_state_get_exit_nickname(state));
  1391. onion_append_hop(head_ptr, info);
  1392. extend_info_free(info);
  1393. return 0;
  1394. }
  1395. /** Create a new hop, annotate it with information about its
  1396. * corresponding router <b>choice</b>, and append it to the
  1397. * end of the cpath <b>head_ptr</b>. */
  1398. static int
  1399. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1400. {
  1401. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1402. /* link hop into the cpath, at the end. */
  1403. onion_append_to_cpath(head_ptr, hop);
  1404. hop->magic = CRYPT_PATH_MAGIC;
  1405. hop->state = CPATH_STATE_CLOSED;
  1406. hop->extend_info = extend_info_dup(choice);
  1407. hop->package_window = CIRCWINDOW_START;
  1408. hop->deliver_window = CIRCWINDOW_START;
  1409. return 0;
  1410. }
  1411. /** Allocate and return a new extend_info_t that can be used to build a
  1412. * circuit to or through the router <b>r</b>. */
  1413. extend_info_t *
  1414. extend_info_from_router(routerinfo_t *r)
  1415. {
  1416. extend_info_t *info;
  1417. tor_assert(r);
  1418. info = tor_malloc_zero(sizeof(extend_info_t));
  1419. strlcpy(info->nickname, r->nickname, sizeof(info->nickname));
  1420. memcpy(info->identity_digest, r->cache_info.identity_digest, DIGEST_LEN);
  1421. info->onion_key = crypto_pk_dup_key(r->onion_pkey);
  1422. info->addr = r->addr;
  1423. info->port = r->or_port;
  1424. return info;
  1425. }
  1426. /** Release storage held by an extend_info_t struct. */
  1427. void
  1428. extend_info_free(extend_info_t *info)
  1429. {
  1430. tor_assert(info);
  1431. crypto_free_pk_env(info->onion_key);
  1432. tor_free(info);
  1433. }
  1434. /** Allocate and return a new extend_info_t with the same contents as
  1435. * <b>info</b>. */
  1436. extend_info_t *
  1437. extend_info_dup(extend_info_t *info)
  1438. {
  1439. extend_info_t *newinfo;
  1440. tor_assert(info);
  1441. newinfo = tor_malloc(sizeof(extend_info_t));
  1442. memcpy(newinfo, info, sizeof(extend_info_t));
  1443. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1444. return newinfo;
  1445. }
  1446. /**
  1447. * Return the routerinfo_t for the chosen exit router in <b>state</b>. If
  1448. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1449. * chosen exit, return NULL.
  1450. */
  1451. routerinfo_t *
  1452. build_state_get_exit_router(cpath_build_state_t *state)
  1453. {
  1454. if (!state || !state->chosen_exit)
  1455. return NULL;
  1456. return router_get_by_digest(state->chosen_exit->identity_digest);
  1457. }
  1458. /**
  1459. * Return the nickname for the chosen exit router in <b>state</b>. If
  1460. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1461. * chosen exit, return NULL.
  1462. */
  1463. const char *
  1464. build_state_get_exit_nickname(cpath_build_state_t *state)
  1465. {
  1466. if (!state || !state->chosen_exit)
  1467. return NULL;
  1468. return state->chosen_exit->nickname;
  1469. }
  1470. /** Return the number of helper nodes that we think are usable. */
  1471. static int
  1472. num_live_helpers(void)
  1473. {
  1474. int n = 0;
  1475. if (! helper_nodes)
  1476. return 0;
  1477. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, helper,
  1478. if (! helper->down_since && ! helper->unlisted_since)
  1479. ++n;);
  1480. return n;
  1481. }
  1482. /** If the use of helper nodes is configured, choose more helper nodes until
  1483. * we have enough in the list. */
  1484. static void
  1485. pick_helper_nodes(void)
  1486. {
  1487. or_options_t *options = get_options();
  1488. int changed = 0;
  1489. if (! options->UseHelperNodes)
  1490. return;
  1491. if (!helper_nodes)
  1492. helper_nodes = smartlist_create();
  1493. while (smartlist_len(helper_nodes) < options->NumHelperNodes) {
  1494. routerinfo_t *entry = choose_good_entry_server(NULL);
  1495. /* XXXX deal with duplicate entries. NM */
  1496. helper_node_t *helper = tor_malloc_zero(sizeof(helper_node_t));
  1497. /* XXXX Downgrade this to info before release. NM */
  1498. notice(LD_CIRC, "Chose '%s' as helper node.", entry->nickname);
  1499. strlcpy(helper->nickname, entry->nickname, sizeof(helper->nickname));
  1500. memcpy(helper->identity, entry->cache_info.identity_digest, DIGEST_LEN);
  1501. smartlist_add(helper_nodes, helper);
  1502. changed = 1;
  1503. }
  1504. if (changed)
  1505. helper_nodes_changed();
  1506. }
  1507. /** Remove all elements from the list of helper nodes. */
  1508. static void
  1509. clear_helper_nodes(void)
  1510. {
  1511. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, h, tor_free(h));
  1512. smartlist_clear(helper_nodes);
  1513. helper_nodes_changed();
  1514. }
  1515. /** Release all storage held by the list of helper nodes. */
  1516. void
  1517. helper_nodes_free_all(void)
  1518. {
  1519. /* Don't call clear_helper_nodes(); that will flush our state change to disk */
  1520. if (helper_nodes) {
  1521. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, h, tor_free(h));
  1522. smartlist_free(helper_nodes);
  1523. helper_nodes = NULL;
  1524. }
  1525. }
  1526. /** How long (in seconds) do we allow a helper node to be nonfunctional before
  1527. * we give up on it? */
  1528. #define HELPER_ALLOW_DOWNTIME 48*60*60
  1529. /** How long (in seconds) do we allow a helper node to be unlisted in the
  1530. * directory before we give up on it? */
  1531. #define HELPER_ALLOW_UNLISTED 48*60*60
  1532. /** Remove all helper nodes that have been down or unlisted for so long that
  1533. * we don't think they'll come up again. */
  1534. static void
  1535. remove_dead_helpers(void)
  1536. {
  1537. char dbuf[HEX_DIGEST_LEN+1];
  1538. char tbuf[ISO_TIME_LEN+1];
  1539. time_t now = time(NULL);
  1540. int i;
  1541. for (i = 0; i < smartlist_len(helper_nodes); ) {
  1542. helper_node_t *helper = smartlist_get(helper_nodes, i);
  1543. const char *why = NULL;
  1544. time_t since = 0;
  1545. if (helper->unlisted_since + HELPER_ALLOW_UNLISTED > now) {
  1546. why = "unlisted";
  1547. since = helper->unlisted_since;
  1548. } else if (helper->down_since + HELPER_ALLOW_DOWNTIME > now) {
  1549. why = "down";
  1550. since = helper->unlisted_since;
  1551. }
  1552. if (why) {
  1553. base16_encode(dbuf, sizeof(dbuf), helper->identity, DIGEST_LEN);
  1554. format_local_iso_time(tbuf, since);
  1555. warn(LD_CIRC, "Helper node '%s' (%s) has been %s since %s; removing.",
  1556. helper->nickname, dbuf, why, tbuf);
  1557. tor_free(helper);
  1558. smartlist_del(helper_nodes, i);
  1559. helper_nodes_changed();
  1560. } else
  1561. ++i;
  1562. }
  1563. }
  1564. /** A new directory or router-status has arrived; update the down/listed status
  1565. * of the helper nodes.
  1566. *
  1567. * A helper is 'down' if the directory lists it as nonrunning, or if we tried
  1568. * to connect to it and failed. A helper is 'unlisted' if the directory
  1569. * doesn't include it.
  1570. */
  1571. void
  1572. helper_nodes_set_status_from_directory(void)
  1573. {
  1574. /* Don't call this on startup; only on a fresh download. Otherwise we'll
  1575. * think that things are unlisted. */
  1576. routerlist_t *routers;
  1577. time_t now;
  1578. int changed = 0;
  1579. int severity = LOG_NOTICE;
  1580. if (! helper_nodes)
  1581. return;
  1582. routers = router_get_routerlist();
  1583. now = time(NULL);
  1584. /*XXXX Most of these warns should be non-warns. */
  1585. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, helper,
  1586. {
  1587. routerinfo_t *r = router_get_by_digest(helper->identity);
  1588. if (! r) {
  1589. if (! helper->unlisted_since) {
  1590. helper->unlisted_since = time(NULL);
  1591. ++changed;
  1592. warn(LD_CIRC,"Helper node '%s' is not listed by directories",
  1593. helper->nickname);
  1594. severity = LOG_WARN;
  1595. }
  1596. } else {
  1597. if (helper->unlisted_since) {
  1598. warn(LD_CIRC,"Helper node '%s' is listed again by directories",
  1599. helper->nickname);
  1600. ++changed;
  1601. severity = LOG_WARN;
  1602. }
  1603. helper->unlisted_since = 0;
  1604. if (! r->is_running) {
  1605. if (! helper->down_since) {
  1606. helper->down_since = now;
  1607. warn(LD_CIRC, "Helper node '%s' is now down.", helper->nickname);
  1608. ++changed;
  1609. severity = LOG_WARN;
  1610. }
  1611. } else {
  1612. if (helper->down_since) {
  1613. notice(LD_CIRC,"Helper node '%s' is up in latest directories",
  1614. helper->nickname);
  1615. ++changed;
  1616. }
  1617. helper->down_since = 0;
  1618. }
  1619. }
  1620. });
  1621. if (changed) {
  1622. log_fn(severity, LD_CIRC, " (%d/%d helpers are usable)",
  1623. num_live_helpers(), smartlist_len(helper_nodes));
  1624. helper_nodes_changed();
  1625. }
  1626. remove_dead_helpers();
  1627. pick_helper_nodes();
  1628. }
  1629. /** Called when a connection to an OR with the identity digest <b>digest</b>
  1630. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  1631. * If the OR is a helper, change that helper's up/down status.
  1632. */
  1633. void
  1634. helper_node_set_status(const char *digest, int succeeded)
  1635. {
  1636. if (! helper_nodes)
  1637. return;
  1638. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, helper,
  1639. {
  1640. if (!memcmp(helper->identity, digest, DIGEST_LEN)) {
  1641. if (succeeded) {
  1642. if (helper->down_since) {
  1643. /*XXXX shouldn't warn. NM */
  1644. warn(LD_CIRC,
  1645. "Connection to formerly down helper node '%s' succeeded. "
  1646. "%d/%d helpers usable.", helper->nickname,
  1647. num_live_helpers(), smartlist_len(helper_nodes));
  1648. helper_nodes_changed();
  1649. }
  1650. helper->down_since = 0;
  1651. } else if (!helper->down_since) {
  1652. helper->down_since = time(NULL);
  1653. warn(LD_CIRC,
  1654. "Connection to helper node '%s' failed. %d/%d helpers usable.",
  1655. helper->nickname, num_live_helpers(), smartlist_len(helper_nodes));
  1656. helper_nodes_changed();
  1657. }
  1658. }
  1659. });
  1660. }
  1661. /** Pick a live (up and listed) helper node from the list of helpers. If
  1662. * no helpers are available, pick a new list. */
  1663. static routerinfo_t *
  1664. choose_random_helper(void)
  1665. {
  1666. smartlist_t *live_helpers = smartlist_create();
  1667. routerinfo_t *r;
  1668. if (! helper_nodes)
  1669. pick_helper_nodes();
  1670. retry:
  1671. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, helper,
  1672. if (! helper->down_since && ! helper->unlisted_since) {
  1673. if ((r = router_get_by_digest(helper->identity))) {
  1674. smartlist_add(live_helpers, r);
  1675. }
  1676. });
  1677. if (! smartlist_len(live_helpers)) {
  1678. /* XXXX Is this right? What if network is down? */
  1679. warn(LD_CIRC, "No functional helper nodes found; picking a new set.");
  1680. clear_helper_nodes();
  1681. pick_helper_nodes();
  1682. goto retry;
  1683. }
  1684. r = smartlist_choose(live_helpers);
  1685. smartlist_free(live_helpers);
  1686. return r;
  1687. }
  1688. /** DOCDOC */
  1689. int
  1690. helper_nodes_parse_state(or_state_t *state, int set, const char **err)
  1691. {
  1692. helper_node_t *node = NULL;
  1693. smartlist_t *helpers = smartlist_create();
  1694. config_line_t *line;
  1695. *err = NULL;
  1696. for (line = state->HelperNodes; line; line = line->next) {
  1697. if (!strcasecmp(line->key, "HelperNode")) {
  1698. smartlist_t *args = smartlist_create();
  1699. node = tor_malloc_zero(sizeof(helper_node_t));
  1700. smartlist_add(helpers, node);
  1701. smartlist_split_string(args, line->value, " ",
  1702. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1703. if (smartlist_len(args)<2) {
  1704. *err = "Too few arguments to HelperNode";
  1705. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  1706. *err = "Bad nickname for HelperNode";
  1707. } else {
  1708. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  1709. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  1710. strlen(smartlist_get(args,1)))<0) {
  1711. *err = "Bad hex digest for HelperNode";
  1712. }
  1713. }
  1714. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  1715. smartlist_free(args);
  1716. if (*err)
  1717. break;
  1718. } else {
  1719. time_t when;
  1720. if (!node) {
  1721. *err = "HelperNodeDownSince/UnlistedSince without HelperNode";
  1722. break;
  1723. }
  1724. if (parse_iso_time(line->value, &when)<0) {
  1725. *err = "Bad time in HelperNodeDownSince/UnlistedSince";
  1726. break;
  1727. }
  1728. if (!strcasecmp(line->key, "HelperNodeDownSince"))
  1729. node->down_since = when;
  1730. else
  1731. node->unlisted_since = when;
  1732. }
  1733. }
  1734. if (*err || !set) {
  1735. SMARTLIST_FOREACH(helpers, helper_node_t *, h, tor_free(h));
  1736. smartlist_free(helpers);
  1737. helpers = NULL;
  1738. }
  1739. if (!*err && set) {
  1740. if (helper_nodes) {
  1741. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, h, tor_free(h));
  1742. smartlist_free(helper_nodes);
  1743. }
  1744. helper_nodes = helpers;
  1745. helper_nodes_dirty = 0;
  1746. }
  1747. return *err ? -1 : 0;
  1748. }
  1749. /** DOCDOC */
  1750. static void
  1751. helper_nodes_changed(void)
  1752. {
  1753. helper_nodes_dirty = 1;
  1754. or_state_save();
  1755. }
  1756. /** DOCDOC */
  1757. int
  1758. helper_nodes_update_state(or_state_t *state)
  1759. {
  1760. config_line_t **next, *line;
  1761. if (! helper_nodes_dirty)
  1762. return 0;
  1763. config_free_lines(state->HelperNodes);
  1764. next = &state->HelperNodes;
  1765. *next = NULL;
  1766. if (!helper_nodes)
  1767. helper_nodes = smartlist_create();
  1768. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, h,
  1769. {
  1770. char dbuf[HEX_DIGEST_LEN+1];
  1771. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1772. line->key = tor_strdup("HelperNode");
  1773. line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
  1774. base16_encode(dbuf, sizeof(dbuf), h->identity, DIGEST_LEN);
  1775. tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
  1776. "%s %s", h->nickname, dbuf);
  1777. next = &(line->next);
  1778. if (h->down_since) {
  1779. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1780. line->key = tor_strdup("HelperNodeDownSince");
  1781. line->value = tor_malloc(ISO_TIME_LEN+1);
  1782. format_iso_time(line->value, h->down_since);
  1783. next = &(line->next);
  1784. }
  1785. if (h->unlisted_since) {
  1786. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1787. line->key = tor_strdup("HelperNodeUnlistedSince");
  1788. line->value = tor_malloc(ISO_TIME_LEN+1);
  1789. format_iso_time(line->value, h->unlisted_since);
  1790. next = &(line->next);
  1791. }
  1792. });
  1793. state->dirty = 1;
  1794. helper_nodes_dirty = 0;
  1795. return 1;
  1796. }
  1797. /** DOCDOC */
  1798. int
  1799. helper_nodes_getinfo_helper(const char *question, char **answer)
  1800. {
  1801. if (!strcmp(question,"helper-nodes")) {
  1802. smartlist_t *sl = smartlist_create();
  1803. char tbuf[ISO_TIME_LEN+1];
  1804. char dbuf[HEX_DIGEST_LEN+1];
  1805. if (!helper_nodes)
  1806. helper_nodes = smartlist_create();
  1807. SMARTLIST_FOREACH(helper_nodes, helper_node_t *, h,
  1808. {
  1809. size_t len = HEX_DIGEST_LEN+ISO_TIME_LEN+16;
  1810. char *c = tor_malloc(len);
  1811. const char *status = NULL;
  1812. time_t when = 0;
  1813. if (h->unlisted_since) {
  1814. when = h->unlisted_since;
  1815. status = "unlisted";
  1816. } else if (h->down_since) {
  1817. when = h->down_since;
  1818. status = "down";
  1819. } else {
  1820. status = "up";
  1821. }
  1822. base16_encode(dbuf, sizeof(dbuf), h->identity, DIGEST_LEN);
  1823. if (when) {
  1824. format_iso_time(tbuf, when);
  1825. tor_snprintf(c, len, "$%s %s %s\n", dbuf, status, tbuf);
  1826. } else {
  1827. tor_snprintf(c, len, "$%s %s\n", dbuf, status);
  1828. }
  1829. smartlist_add(sl, c);
  1830. });
  1831. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1832. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1833. smartlist_free(sl);
  1834. }
  1835. return 0;
  1836. }