circuitbuild.c 93 KB

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