circuitbuild.c 88 KB

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