circuitbuild.c 65 KB

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