circuitbuild.c 80 KB

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