circuitbuild.c 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924
  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>exit</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 = time(NULL);
  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. /*XXXX020 some of these are leaked somewhere.. fix that. */
  962. tmp = tor_malloc(sizeof(uint16_t));
  963. memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
  964. smartlist_add(dest, tmp);
  965. }
  966. circuit_remove_handled_ports(dest);
  967. return dest;
  968. }
  969. /** Return 1 if we already have circuits present or on the way for
  970. * all anticipated ports. Return 0 if we should make more.
  971. *
  972. * If we're returning 0, set need_uptime and need_capacity to
  973. * indicate any requirements that the unhandled ports have.
  974. */
  975. int
  976. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  977. int *need_capacity)
  978. {
  979. int i, enough;
  980. uint16_t *port;
  981. smartlist_t *sl = circuit_get_unhandled_ports(now);
  982. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  983. tor_assert(need_uptime);
  984. tor_assert(need_capacity);
  985. enough = (smartlist_len(sl) == 0);
  986. for (i = 0; i < smartlist_len(sl); ++i) {
  987. port = smartlist_get(sl, i);
  988. if (smartlist_string_num_isin(LongLivedServices, *port))
  989. *need_uptime = 1;
  990. tor_free(port);
  991. }
  992. smartlist_free(sl);
  993. return enough;
  994. }
  995. /** Return 1 if <b>router</b> can handle one or more of the ports in
  996. * <b>needed_ports</b>, else return 0.
  997. */
  998. static int
  999. router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
  1000. {
  1001. int i;
  1002. uint16_t port;
  1003. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1004. addr_policy_result_t r;
  1005. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1006. tor_assert(port);
  1007. r = compare_addr_to_addr_policy(0, port, router->exit_policy);
  1008. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1009. return 1;
  1010. }
  1011. return 0;
  1012. }
  1013. /** Return true iff <b>conn</b> needs another general circuit to be
  1014. * built. */
  1015. static int
  1016. ap_stream_wants_exit_attention(connection_t *conn)
  1017. {
  1018. if (conn->type == CONN_TYPE_AP &&
  1019. conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1020. !conn->marked_for_close &&
  1021. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1022. !circuit_stream_is_being_handled(TO_EDGE_CONN(conn), 0,
  1023. MIN_CIRCUITS_HANDLING_STREAM))
  1024. return 1;
  1025. return 0;
  1026. }
  1027. /** Return a pointer to a suitable router to be the exit node for the
  1028. * general-purpose circuit we're about to build.
  1029. *
  1030. * Look through the connection array, and choose a router that maximizes
  1031. * the number of pending streams that can exit from this router.
  1032. *
  1033. * Return NULL if we can't find any suitable routers.
  1034. */
  1035. static routerinfo_t *
  1036. choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
  1037. int need_capacity)
  1038. {
  1039. int *n_supported;
  1040. int i;
  1041. int n_pending_connections = 0;
  1042. smartlist_t *connections;
  1043. int best_support = -1;
  1044. int n_best_support=0;
  1045. smartlist_t *sl, *preferredexits, *excludedexits;
  1046. routerinfo_t *router;
  1047. or_options_t *options = get_options();
  1048. connections = get_connection_array();
  1049. /* Count how many connections are waiting for a circuit to be built.
  1050. * We use this for log messages now, but in the future we may depend on it.
  1051. */
  1052. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1053. {
  1054. if (ap_stream_wants_exit_attention(conn))
  1055. ++n_pending_connections;
  1056. });
  1057. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1058. // n_pending_connections);
  1059. /* Now we count, for each of the routers in the directory, how many
  1060. * of the pending connections could possibly exit from that
  1061. * router (n_supported[i]). (We can't be sure about cases where we
  1062. * don't know the IP address of the pending connection.)
  1063. */
  1064. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  1065. for (i = 0; i < smartlist_len(dir->routers); ++i) {/* iterate over routers */
  1066. router = smartlist_get(dir->routers, i);
  1067. if (router_is_me(router)) {
  1068. n_supported[i] = -1;
  1069. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1070. /* XXX there's probably a reverse predecessor attack here, but
  1071. * it's slow. should we take this out? -RD
  1072. */
  1073. continue;
  1074. }
  1075. if (!router->is_running || router->is_bad_exit) {
  1076. n_supported[i] = -1;
  1077. continue; /* skip routers that are known to be down or bad exits */
  1078. }
  1079. if (router_is_unreliable(router, need_uptime, need_capacity, 0)) {
  1080. n_supported[i] = -1;
  1081. continue; /* skip routers that are not suitable */
  1082. }
  1083. if (!(router->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
  1084. /* if it's invalid and we don't want it */
  1085. n_supported[i] = -1;
  1086. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1087. // router->nickname, i);
  1088. continue; /* skip invalid routers */
  1089. }
  1090. if (router_exit_policy_rejects_all(router)) {
  1091. n_supported[i] = -1;
  1092. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1093. // router->nickname, i);
  1094. continue; /* skip routers that reject all */
  1095. }
  1096. n_supported[i] = 0;
  1097. /* iterate over connections */
  1098. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1099. {
  1100. if (!ap_stream_wants_exit_attention(conn))
  1101. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1102. if (connection_ap_can_use_exit(TO_EDGE_CONN(conn), router)) {
  1103. ++n_supported[i];
  1104. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1105. // router->nickname, i, n_supported[i]);
  1106. } else {
  1107. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1108. // router->nickname, i);
  1109. }
  1110. }); /* End looping over connections. */
  1111. if (n_supported[i] > best_support) {
  1112. /* If this router is better than previous ones, remember its index
  1113. * and goodness, and start counting how many routers are this good. */
  1114. best_support = n_supported[i]; n_best_support=1;
  1115. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1116. // router->nickname);
  1117. } else if (n_supported[i] == best_support) {
  1118. /* If this router is _as good_ as the best one, just increment the
  1119. * count of equally good routers.*/
  1120. ++n_best_support;
  1121. }
  1122. }
  1123. log_info(LD_CIRC,
  1124. "Found %d servers that might support %d/%d pending connections.",
  1125. n_best_support, best_support >= 0 ? best_support : 0,
  1126. n_pending_connections);
  1127. preferredexits = smartlist_create();
  1128. add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1);
  1129. excludedexits = smartlist_create();
  1130. add_nickname_list_to_smartlist(excludedexits,options->ExcludeNodes,0);
  1131. sl = smartlist_create();
  1132. /* If any routers definitely support any pending connections, choose one
  1133. * at random. */
  1134. if (best_support > 0) {
  1135. for (i = 0; i < smartlist_len(dir->routers); i++)
  1136. if (n_supported[i] == best_support)
  1137. smartlist_add(sl, smartlist_get(dir->routers, i));
  1138. smartlist_subtract(sl,excludedexits);
  1139. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1140. smartlist_intersect(sl,preferredexits);
  1141. router = routerlist_sl_choose_by_bandwidth(sl, 1);
  1142. } else {
  1143. /* Either there are no pending connections, or no routers even seem to
  1144. * possibly support any of them. Choose a router at random that satisfies
  1145. * at least one predicted exit port. */
  1146. int try;
  1147. smartlist_t *needed_ports = circuit_get_unhandled_ports(time(NULL));
  1148. if (best_support == -1) {
  1149. if (need_uptime || need_capacity) {
  1150. log_info(LD_CIRC,
  1151. "We couldn't find any live%s%s routers; falling back "
  1152. "to list of all routers.",
  1153. need_capacity?", fast":"",
  1154. need_uptime?", stable":"");
  1155. smartlist_free(preferredexits);
  1156. smartlist_free(excludedexits);
  1157. smartlist_free(sl);
  1158. tor_free(n_supported);
  1159. return choose_good_exit_server_general(dir, 0, 0);
  1160. }
  1161. log_notice(LD_CIRC, "All routers are down or won't exit -- choosing a "
  1162. "doomed exit at random.");
  1163. }
  1164. for (try = 0; try < 2; try++) {
  1165. /* try once to pick only from routers that satisfy a needed port,
  1166. * then if there are none, pick from any that support exiting. */
  1167. for (i = 0; i < smartlist_len(dir->routers); i++) {
  1168. router = smartlist_get(dir->routers, i);
  1169. if (n_supported[i] != -1 &&
  1170. (try || router_handles_some_port(router, needed_ports))) {
  1171. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1172. // try, router->nickname);
  1173. smartlist_add(sl, router);
  1174. }
  1175. }
  1176. smartlist_subtract(sl,excludedexits);
  1177. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1178. smartlist_intersect(sl,preferredexits);
  1179. /* XXX sometimes the above results in null, when the requested
  1180. * exit node is down. we should pick it anyway. */
  1181. router = routerlist_sl_choose_by_bandwidth(sl, 1);
  1182. if (router)
  1183. break;
  1184. }
  1185. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1186. smartlist_free(needed_ports);
  1187. }
  1188. smartlist_free(preferredexits);
  1189. smartlist_free(excludedexits);
  1190. smartlist_free(sl);
  1191. tor_free(n_supported);
  1192. if (router) {
  1193. log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
  1194. return router;
  1195. }
  1196. if (options->StrictExitNodes) {
  1197. log_warn(LD_CIRC,
  1198. "No specified exit routers seem to be running, and "
  1199. "StrictExitNodes is set: can't choose an exit.");
  1200. }
  1201. return NULL;
  1202. }
  1203. /** Return a pointer to a suitable router to be the exit node for the
  1204. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1205. * if no router is suitable).
  1206. *
  1207. * For general-purpose circuits, pass it off to
  1208. * choose_good_exit_server_general()
  1209. *
  1210. * For client-side rendezvous circuits, choose a random node, weighted
  1211. * toward the preferences in 'options'.
  1212. */
  1213. static routerinfo_t *
  1214. choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
  1215. int need_uptime, int need_capacity, int is_internal)
  1216. {
  1217. or_options_t *options = get_options();
  1218. switch (purpose) {
  1219. case CIRCUIT_PURPOSE_C_GENERAL:
  1220. if (is_internal) /* pick it like a middle hop */
  1221. return router_choose_random_node(NULL, get_options()->ExcludeNodes,
  1222. NULL, need_uptime, need_capacity, 0,
  1223. get_options()->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0, 0);
  1224. else
  1225. return choose_good_exit_server_general(dir,need_uptime,need_capacity);
  1226. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1227. return router_choose_random_node(
  1228. options->RendNodes, options->RendExcludeNodes,
  1229. NULL, need_uptime, need_capacity, 0,
  1230. options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS, 0, 0);
  1231. }
  1232. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1233. tor_fragile_assert();
  1234. return NULL;
  1235. }
  1236. /** Decide a suitable length for circ's cpath, and pick an exit
  1237. * router (or use <b>exit</b> if provided). Store these in the
  1238. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1239. static int
  1240. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1241. {
  1242. cpath_build_state_t *state = circ->build_state;
  1243. routerlist_t *rl = router_get_routerlist();
  1244. if (state->onehop_tunnel) {
  1245. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1246. state->desired_path_len = 1;
  1247. } else {
  1248. int r = new_route_len(circ->_base.purpose, exit, rl->routers);
  1249. if (r < 1) /* must be at least 1 */
  1250. return -1;
  1251. state->desired_path_len = r;
  1252. }
  1253. if (exit) { /* the circuit-builder pre-requested one */
  1254. log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
  1255. exit = extend_info_dup(exit);
  1256. } else { /* we have to decide one */
  1257. routerinfo_t *router =
  1258. choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
  1259. state->need_capacity, state->is_internal);
  1260. if (!router) {
  1261. log_warn(LD_CIRC,"failed to choose an exit server");
  1262. return -1;
  1263. }
  1264. exit = extend_info_from_router(router);
  1265. }
  1266. state->chosen_exit = exit;
  1267. return 0;
  1268. }
  1269. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1270. * hop to the cpath reflecting this. Don't send the next extend cell --
  1271. * the caller will do this if it wants to.
  1272. */
  1273. int
  1274. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1275. {
  1276. cpath_build_state_t *state;
  1277. tor_assert(exit);
  1278. tor_assert(circ);
  1279. state = circ->build_state;
  1280. tor_assert(state);
  1281. if (state->chosen_exit)
  1282. extend_info_free(state->chosen_exit);
  1283. state->chosen_exit = extend_info_dup(exit);
  1284. ++circ->build_state->desired_path_len;
  1285. onion_append_hop(&circ->cpath, exit);
  1286. return 0;
  1287. }
  1288. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1289. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1290. * send the next extend cell to begin connecting to that hop.
  1291. */
  1292. int
  1293. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1294. {
  1295. int err_reason = 0;
  1296. circuit_append_new_exit(circ, exit);
  1297. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1298. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1299. log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
  1300. exit->nickname);
  1301. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1302. return -1;
  1303. }
  1304. return 0;
  1305. }
  1306. /** Return the number of routers in <b>routers</b> that are currently up
  1307. * and available for building circuits through.
  1308. */
  1309. static int
  1310. count_acceptable_routers(smartlist_t *routers)
  1311. {
  1312. int i, n;
  1313. int num=0;
  1314. routerinfo_t *r;
  1315. n = smartlist_len(routers);
  1316. for (i=0;i<n;i++) {
  1317. r = smartlist_get(routers, i);
  1318. // log_debug(LD_CIRC,
  1319. // "Contemplating whether router %d (%s) is a new option.",
  1320. // i, r->nickname);
  1321. if (r->is_running == 0) {
  1322. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1323. goto next_i_loop;
  1324. }
  1325. if (r->is_valid == 0) {
  1326. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1327. goto next_i_loop;
  1328. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1329. * allows this node in some places, then we're getting an inaccurate
  1330. * count. For now, be conservative and don't count it. But later we
  1331. * should try to be smarter. */
  1332. }
  1333. num++;
  1334. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1335. next_i_loop:
  1336. ; /* C requires an explicit statement after the label */
  1337. }
  1338. return num;
  1339. }
  1340. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1341. * This function is used to extend cpath by another hop.
  1342. */
  1343. void
  1344. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1345. {
  1346. if (*head_ptr) {
  1347. new_hop->next = (*head_ptr);
  1348. new_hop->prev = (*head_ptr)->prev;
  1349. (*head_ptr)->prev->next = new_hop;
  1350. (*head_ptr)->prev = new_hop;
  1351. } else {
  1352. *head_ptr = new_hop;
  1353. new_hop->prev = new_hop->next = new_hop;
  1354. }
  1355. }
  1356. /** Pick a random server digest that's running a Tor version that
  1357. * doesn't have the reachability bug. These are versions 0.1.1.21-cvs+
  1358. * and 0.1.2.1-alpha+. Avoid picking authorities, since we're
  1359. * probably already connected to them.
  1360. *
  1361. * We only return one, so this doesn't become stupid when the
  1362. * whole network has upgraded. */
  1363. static char *
  1364. compute_preferred_testing_list(const char *answer)
  1365. {
  1366. smartlist_t *choices;
  1367. routerlist_t *rl = router_get_routerlist();
  1368. routerinfo_t *router;
  1369. char *s;
  1370. if (answer) /* they have one in mind -- easy */
  1371. return tor_strdup(answer);
  1372. choices = smartlist_create();
  1373. /* now count up our choices */
  1374. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1375. if (r->is_running && r->is_valid &&
  1376. ((tor_version_as_new_as(r->platform,"0.1.1.21-cvs") &&
  1377. !tor_version_as_new_as(r->platform,"0.1.2.0-alpha-cvs")) ||
  1378. tor_version_as_new_as(r->platform,"0.1.2.1-alpha")) &&
  1379. !is_local_IP(r->addr) &&
  1380. !router_get_trusteddirserver_by_digest(r->cache_info.identity_digest))
  1381. smartlist_add(choices, r));
  1382. router = smartlist_choose(choices);
  1383. smartlist_free(choices);
  1384. if (!router) {
  1385. log_info(LD_CIRC, "Looking for middle server that doesn't have the "
  1386. "reachability bug, but didn't find one. Oh well.");
  1387. return NULL;
  1388. }
  1389. log_info(LD_CIRC, "Looking for middle server that doesn't have the "
  1390. "reachability bug, and chose '%s'. Great.", router->nickname);
  1391. s = tor_malloc(HEX_DIGEST_LEN+2);
  1392. s[0] = '$';
  1393. base16_encode(s+1, HEX_DIGEST_LEN+1,
  1394. router->cache_info.identity_digest, DIGEST_LEN);
  1395. return s;
  1396. }
  1397. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1398. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1399. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1400. * circuit. In particular, make sure we don't pick the exit node or its
  1401. * family, and make sure we don't duplicate any previous nodes or their
  1402. * families. */
  1403. static routerinfo_t *
  1404. choose_good_middle_server(uint8_t purpose,
  1405. cpath_build_state_t *state,
  1406. crypt_path_t *head,
  1407. int cur_len)
  1408. {
  1409. int i;
  1410. routerinfo_t *r, *choice;
  1411. crypt_path_t *cpath;
  1412. smartlist_t *excluded;
  1413. or_options_t *options = get_options();
  1414. char *preferred = NULL;
  1415. tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
  1416. purpose <= _CIRCUIT_PURPOSE_MAX);
  1417. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1418. excluded = smartlist_create();
  1419. if ((r = build_state_get_exit_router(state))) {
  1420. smartlist_add(excluded, r);
  1421. routerlist_add_family(excluded, r);
  1422. }
  1423. if ((r = routerlist_find_my_routerinfo())) {
  1424. smartlist_add(excluded, r);
  1425. routerlist_add_family(excluded, r);
  1426. }
  1427. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1428. if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
  1429. smartlist_add(excluded, r);
  1430. routerlist_add_family(excluded, r);
  1431. }
  1432. }
  1433. if (purpose == CIRCUIT_PURPOSE_TESTING)
  1434. preferred = compute_preferred_testing_list(options->TestVia);
  1435. choice = router_choose_random_node(preferred,
  1436. options->ExcludeNodes, excluded,
  1437. state->need_uptime, state->need_capacity, 0,
  1438. options->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0, 0);
  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 to connect
  1705. * to the 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 ReachableORAddresses 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 (!fascist_firewall_allows_address_or(r->addr,r->or_port))
  1756. return NULL;
  1757. return r;
  1758. }
  1759. /** Return the number of entry guards that we think are usable. */
  1760. static int
  1761. num_live_entry_guards(void)
  1762. {
  1763. int n = 0;
  1764. if (! entry_guards)
  1765. return 0;
  1766. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1767. {
  1768. if (entry_is_live(entry, 0, 1, 0))
  1769. ++n;
  1770. });
  1771. return n;
  1772. }
  1773. /** If <b>digest</b> matches the identity of any node in the
  1774. * entry_guards list, return that node. Else return NULL. */
  1775. static INLINE entry_guard_t *
  1776. is_an_entry_guard(const char *digest)
  1777. {
  1778. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1779. if (!memcmp(digest, entry->identity, DIGEST_LEN))
  1780. return entry;
  1781. );
  1782. return NULL;
  1783. }
  1784. /** Dump a description of our list of entry guards to the log at level
  1785. * <b>severity</b>. */
  1786. static void
  1787. log_entry_guards(int severity)
  1788. {
  1789. smartlist_t *elements = smartlist_create();
  1790. char buf[1024];
  1791. char *s;
  1792. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  1793. {
  1794. tor_snprintf(buf, sizeof(buf), "%s (%s%s)",
  1795. e->nickname,
  1796. e->bad_since ? "down " : "up ",
  1797. e->made_contact ? "made-contact" : "never-contacted");
  1798. smartlist_add(elements, tor_strdup(buf));
  1799. });
  1800. s = smartlist_join_strings(elements, ",", 0, NULL);
  1801. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  1802. smartlist_free(elements);
  1803. log_fn(severity,LD_CIRC,"%s",s);
  1804. tor_free(s);
  1805. }
  1806. /** Called when one or more guards that we would previously have used for some
  1807. * purpose are no longer in use because a higher-priority guard has become
  1808. * useable again. */
  1809. static void
  1810. control_event_guard_deferred(void)
  1811. {
  1812. /* XXXX We don't actually have a good way to figure out _how many_ entries
  1813. * are live for some purpose. We need an entry_is_even_slightly_live()
  1814. * function for this to work right. NumEntryGuards isn't reliable: if we
  1815. * need guards with weird properties, we can have more than that number
  1816. * live.
  1817. **/
  1818. #if 0
  1819. int n = 0;
  1820. or_options_t *options = get_options();
  1821. if (!entry_guards)
  1822. return;
  1823. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1824. {
  1825. if (entry_is_live(entry, 0, 1, 0)) {
  1826. if (n++ == options->NumEntryGuards) {
  1827. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  1828. return;
  1829. }
  1830. }
  1831. });
  1832. #endif
  1833. }
  1834. /** Add a new (preferably stable and fast) router to our
  1835. * entry_guards list. Return a pointer to the router if we succeed,
  1836. * or NULL if we can't find any more suitable entries.
  1837. *
  1838. * If <b>chosen</b> is defined, use that one, and if it's not
  1839. * already in our entry_guards list, put it at the *beginning*.
  1840. * Else, put the one we pick at the end of the list. */
  1841. static routerinfo_t *
  1842. add_an_entry_guard(routerinfo_t *chosen, int reset_status)
  1843. {
  1844. routerinfo_t *router;
  1845. entry_guard_t *entry;
  1846. if (chosen) {
  1847. router = chosen;
  1848. entry = is_an_entry_guard(router->cache_info.identity_digest);
  1849. if (entry) {
  1850. if (reset_status)
  1851. entry->bad_since = 0;
  1852. return NULL;
  1853. }
  1854. } else {
  1855. router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  1856. if (!router)
  1857. return NULL;
  1858. }
  1859. entry = tor_malloc_zero(sizeof(entry_guard_t));
  1860. log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
  1861. strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
  1862. memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
  1863. if (chosen) /* prepend */
  1864. smartlist_insert(entry_guards, 0, entry);
  1865. else /* append */
  1866. smartlist_add(entry_guards, entry);
  1867. control_event_guard(entry->nickname, entry->identity, "NEW");
  1868. control_event_guard_deferred();
  1869. log_entry_guards(LOG_INFO);
  1870. return router;
  1871. }
  1872. /** If the use of entry guards is configured, choose more entry guards
  1873. * until we have enough in the list. */
  1874. static void
  1875. pick_entry_guards(void)
  1876. {
  1877. or_options_t *options = get_options();
  1878. int changed = 0;
  1879. tor_assert(entry_guards);
  1880. while (num_live_entry_guards() < options->NumEntryGuards) {
  1881. if (!add_an_entry_guard(NULL, 0))
  1882. break;
  1883. changed = 1;
  1884. }
  1885. if (changed)
  1886. entry_guards_changed();
  1887. }
  1888. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  1889. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  1890. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  1891. /** Remove all entry guards that have been down or unlisted for so
  1892. * long that we don't think they'll come up again. Return 1 if we
  1893. * removed any, or 0 if we did nothing. */
  1894. static int
  1895. remove_dead_entries(void)
  1896. {
  1897. char dbuf[HEX_DIGEST_LEN+1];
  1898. char tbuf[ISO_TIME_LEN+1];
  1899. time_t now = time(NULL);
  1900. int i;
  1901. int changed = 0;
  1902. for (i = 0; i < smartlist_len(entry_guards); ) {
  1903. entry_guard_t *entry = smartlist_get(entry_guards, i);
  1904. if (entry->bad_since &&
  1905. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  1906. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  1907. format_local_iso_time(tbuf, entry->bad_since);
  1908. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  1909. "since %s local time; removing.",
  1910. entry->nickname, dbuf, tbuf);
  1911. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  1912. tor_free(entry);
  1913. smartlist_del_keeporder(entry_guards, i);
  1914. log_entry_guards(LOG_INFO);
  1915. changed = 1;
  1916. } else
  1917. ++i;
  1918. }
  1919. return changed ? 1 : 0;
  1920. }
  1921. /** A new directory or router-status has arrived; update the down/listed
  1922. * status of the entry guards.
  1923. *
  1924. * An entry is 'down' if the directory lists it as nonrunning.
  1925. * An entry is 'unlisted' if the directory doesn't include it.
  1926. */
  1927. void
  1928. entry_guards_compute_status(void)
  1929. {
  1930. /* Don't call this on startup; only on a fresh download. Otherwise we'll
  1931. * think that things are unlisted. */
  1932. time_t now;
  1933. int changed = 0;
  1934. int severity = LOG_INFO;
  1935. or_options_t *options;
  1936. if (! entry_guards)
  1937. return;
  1938. options = get_options();
  1939. now = time(NULL);
  1940. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1941. {
  1942. routerinfo_t *r = router_get_by_digest(entry->identity);
  1943. if (entry_guard_set_status(entry, r, now, options))
  1944. changed = 1;
  1945. log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s and %s.",
  1946. entry->nickname,
  1947. entry->unreachable_since ? "unreachable" : "reachable",
  1948. entry->bad_since ? "unusable" : "usable",
  1949. entry_is_live(entry, 0, 1, 0) ? "live" : "not live");
  1950. });
  1951. if (remove_dead_entries())
  1952. changed = 1;
  1953. if (changed) {
  1954. log_fn(severity, LD_CIRC, " (%d/%d entry guards are usable/new)",
  1955. num_live_entry_guards(), smartlist_len(entry_guards));
  1956. log_entry_guards(LOG_INFO);
  1957. entry_guards_changed();
  1958. }
  1959. }
  1960. /** Called when a connection to an OR with the identity digest <b>digest</b>
  1961. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  1962. * If the OR is an entry, change that entry's up/down status.
  1963. * Return 0 normally, or -1 if we want to tear down the new connection.
  1964. */
  1965. int
  1966. entry_guard_register_connect_status(const char *digest, int succeeded,
  1967. time_t now)
  1968. {
  1969. int changed = 0;
  1970. int refuse_conn = 0;
  1971. int first_contact = 0;
  1972. entry_guard_t *entry = NULL;
  1973. int idx = -1;
  1974. char buf[HEX_DIGEST_LEN+1];
  1975. if (! entry_guards)
  1976. return 0;
  1977. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  1978. {
  1979. if (!memcmp(e->identity, digest, DIGEST_LEN)) {
  1980. entry = e;
  1981. idx = e_sl_idx;
  1982. break;
  1983. }
  1984. });
  1985. if (!entry)
  1986. return 0;
  1987. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  1988. if (succeeded) {
  1989. if (entry->unreachable_since) {
  1990. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  1991. entry->nickname, buf);
  1992. entry->can_retry = 0;
  1993. entry->unreachable_since = 0;
  1994. entry->last_attempted = now;
  1995. control_event_guard(entry->nickname, entry->identity, "UP");
  1996. changed = 1;
  1997. }
  1998. if (!entry->made_contact) {
  1999. entry->made_contact = 1;
  2000. first_contact = changed = 1;
  2001. }
  2002. } else { /* ! succeeded */
  2003. if (!entry->made_contact) {
  2004. /* We've never connected to this one. */
  2005. log_info(LD_CIRC,
  2006. "Connection to never-contacted entry guard '%s' (%s) failed. "
  2007. "Removing from the list. %d/%d entry guards usable/new.",
  2008. entry->nickname, buf,
  2009. num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
  2010. tor_free(entry);
  2011. smartlist_del_keeporder(entry_guards, idx);
  2012. log_entry_guards(LOG_INFO);
  2013. changed = 1;
  2014. } else if (!entry->unreachable_since) {
  2015. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  2016. "Marking as unreachable.", entry->nickname, buf);
  2017. entry->unreachable_since = entry->last_attempted = now;
  2018. control_event_guard(entry->nickname, entry->identity, "DOWN");
  2019. changed = 1;
  2020. } else {
  2021. char tbuf[ISO_TIME_LEN+1];
  2022. format_iso_time(tbuf, entry->unreachable_since);
  2023. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  2024. "'%s' (%s). It has been unreachable since %s.",
  2025. entry->nickname, buf, tbuf);
  2026. entry->last_attempted = now;
  2027. }
  2028. if (entry)
  2029. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2030. }
  2031. if (first_contact) {
  2032. /* We've just added a new long-term entry guard. Perhaps the network just
  2033. * came back? We should give our earlier entries another try too,
  2034. * and close this connection so we don't use it before we've given
  2035. * the others a shot. */
  2036. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  2037. if (e == entry)
  2038. break;
  2039. if (e->made_contact) {
  2040. routerinfo_t *r = entry_is_live(e, 0, 1, 1);
  2041. if (r && e->unreachable_since) {
  2042. refuse_conn = 1;
  2043. e->can_retry = 1;
  2044. }
  2045. }
  2046. });
  2047. if (refuse_conn) {
  2048. log_info(LD_CIRC,
  2049. "Connected to new entry guard '%s' (%s). Marking earlier "
  2050. "entry guards up. %d/%d entry guards usable/new.",
  2051. entry->nickname, buf,
  2052. num_live_entry_guards(), smartlist_len(entry_guards));
  2053. log_entry_guards(LOG_INFO);
  2054. changed = 1;
  2055. }
  2056. }
  2057. if (changed)
  2058. entry_guards_changed();
  2059. return refuse_conn ? -1 : 0;
  2060. }
  2061. /** When we try to choose an entry guard, should we parse and add
  2062. * config's EntryNodes first? */
  2063. static int should_add_entry_nodes = 0;
  2064. /** Called when the value of EntryNodes changes in our configuration. */
  2065. void
  2066. entry_nodes_should_be_added(void)
  2067. {
  2068. log_info(LD_CIRC, "New EntryNodes config option detected. Will use.");
  2069. should_add_entry_nodes = 1;
  2070. }
  2071. /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
  2072. * of guard nodes, at the front. */
  2073. static void
  2074. entry_guards_prepend_from_config(void)
  2075. {
  2076. or_options_t *options = get_options();
  2077. smartlist_t *entry_routers, *entry_fps;
  2078. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  2079. tor_assert(entry_guards);
  2080. should_add_entry_nodes = 0;
  2081. if (!options->EntryNodes) {
  2082. /* It's possible that a controller set EntryNodes, thus making
  2083. * should_add_entry_nodes set, then cleared it again, all before the
  2084. * call to choose_random_entry() that triggered us. If so, just return.
  2085. */
  2086. return;
  2087. }
  2088. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.",
  2089. options->EntryNodes);
  2090. entry_routers = smartlist_create();
  2091. entry_fps = smartlist_create();
  2092. old_entry_guards_on_list = smartlist_create();
  2093. old_entry_guards_not_on_list = smartlist_create();
  2094. /* Split entry guards into those on the list and those not. */
  2095. add_nickname_list_to_smartlist(entry_routers, options->EntryNodes, 0);
  2096. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri,
  2097. smartlist_add(entry_fps,ri->cache_info.identity_digest));
  2098. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  2099. if (smartlist_digest_isin(entry_fps, e->identity))
  2100. smartlist_add(old_entry_guards_on_list, e);
  2101. else
  2102. smartlist_add(old_entry_guards_not_on_list, e);
  2103. });
  2104. /* Remove all currently configured entry guards from entry_routers. */
  2105. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  2106. if (is_an_entry_guard(ri->cache_info.identity_digest)) {
  2107. SMARTLIST_DEL_CURRENT(entry_routers, ri);
  2108. }
  2109. });
  2110. /* Now build the new entry_guards list. */
  2111. smartlist_clear(entry_guards);
  2112. /* First, the previously configured guards that are in EntryNodes. */
  2113. smartlist_add_all(entry_guards, old_entry_guards_on_list);
  2114. /* Next, the rest of EntryNodes */
  2115. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  2116. add_an_entry_guard(ri, 0);
  2117. });
  2118. /* Finally, the remaining EntryNodes, unless we're strict */
  2119. if (options->StrictEntryNodes) {
  2120. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  2121. tor_free(e));
  2122. } else {
  2123. smartlist_add_all(entry_guards, old_entry_guards_not_on_list);
  2124. }
  2125. smartlist_free(entry_routers);
  2126. smartlist_free(entry_fps);
  2127. smartlist_free(old_entry_guards_on_list);
  2128. smartlist_free(old_entry_guards_not_on_list);
  2129. entry_guards_changed();
  2130. }
  2131. /** Return 1 if we're fine adding arbitrary routers out of the
  2132. * directory to our entry guard list. Else return 0. */
  2133. static int
  2134. can_grow_entry_list(or_options_t *options)
  2135. {
  2136. if (options->StrictEntryNodes)
  2137. return 0;
  2138. if (options->UseBridges)
  2139. return 0;
  2140. return 1;
  2141. }
  2142. /** Pick a live (up and listed) entry guard from entry_guards. If
  2143. * <b>state</b> is non-NULL, this is for a specific circuit --
  2144. * make sure not to pick this circuit's exit or any node in the
  2145. * exit's family. If <b>state</b> is NULL, we're looking for a random
  2146. * guard (likely a bridge). */
  2147. routerinfo_t *
  2148. choose_random_entry(cpath_build_state_t *state)
  2149. {
  2150. or_options_t *options = get_options();
  2151. smartlist_t *live_entry_guards = smartlist_create();
  2152. smartlist_t *exit_family = smartlist_create();
  2153. routerinfo_t *chosen_exit = state?build_state_get_exit_router(state) : NULL;
  2154. routerinfo_t *r = NULL;
  2155. int need_uptime = state ? state->need_uptime : 0;
  2156. int need_capacity = state ? state->need_capacity : 0;
  2157. if (chosen_exit) {
  2158. smartlist_add(exit_family, chosen_exit);
  2159. routerlist_add_family(exit_family, chosen_exit);
  2160. }
  2161. if (!entry_guards)
  2162. entry_guards = smartlist_create();
  2163. if (should_add_entry_nodes)
  2164. entry_guards_prepend_from_config();
  2165. if (can_grow_entry_list(options) &&
  2166. (! entry_guards ||
  2167. smartlist_len(entry_guards) < options->NumEntryGuards))
  2168. pick_entry_guards();
  2169. retry:
  2170. smartlist_clear(live_entry_guards);
  2171. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2172. {
  2173. r = entry_is_live(entry, need_uptime, need_capacity, 0);
  2174. if (r && !smartlist_isin(exit_family, r)) {
  2175. smartlist_add(live_entry_guards, r);
  2176. if (!entry->made_contact) {
  2177. /* Always start with the first not-yet-contacted entry
  2178. * guard. Otherwise we might add several new ones, pick
  2179. * the second new one, and now we've expanded our entry
  2180. * guard list without needing to. */
  2181. goto choose_and_finish;
  2182. }
  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, 0);
  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. choose_and_finish:
  2215. r = smartlist_choose(live_entry_guards);
  2216. smartlist_free(live_entry_guards);
  2217. smartlist_free(exit_family);
  2218. return r;
  2219. }
  2220. /** Parse <b>state</b> and learn about the entry guards it describes.
  2221. * If <b>set</b> is true, and there are no errors, replace the global
  2222. * entry_list with what we find.
  2223. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  2224. * describing the error, and return -1.
  2225. */
  2226. int
  2227. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  2228. {
  2229. entry_guard_t *node = NULL;
  2230. smartlist_t *new_entry_guards = smartlist_create();
  2231. config_line_t *line;
  2232. *msg = NULL;
  2233. for (line = state->EntryGuards; line; line = line->next) {
  2234. if (!strcasecmp(line->key, "EntryGuard")) {
  2235. smartlist_t *args = smartlist_create();
  2236. node = tor_malloc_zero(sizeof(entry_guard_t));
  2237. /* all entry guards on disk have been contacted */
  2238. node->made_contact = 1;
  2239. smartlist_add(new_entry_guards, node);
  2240. smartlist_split_string(args, line->value, " ",
  2241. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2242. if (smartlist_len(args)<2) {
  2243. *msg = tor_strdup("Unable to parse entry nodes: "
  2244. "Too few arguments to EntryGuard");
  2245. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  2246. *msg = tor_strdup("Unable to parse entry nodes: "
  2247. "Bad nickname for EntryGuard");
  2248. } else {
  2249. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  2250. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  2251. strlen(smartlist_get(args,1)))<0) {
  2252. *msg = tor_strdup("Unable to parse entry nodes: "
  2253. "Bad hex digest for EntryGuard");
  2254. }
  2255. }
  2256. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  2257. smartlist_free(args);
  2258. if (*msg)
  2259. break;
  2260. } else {
  2261. time_t when;
  2262. time_t last_try = 0;
  2263. if (!node) {
  2264. *msg = tor_strdup("Unable to parse entry nodes: "
  2265. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  2266. break;
  2267. }
  2268. if (parse_iso_time(line->value, &when)<0) {
  2269. *msg = tor_strdup("Unable to parse entry nodes: "
  2270. "Bad time in EntryGuardDownSince/UnlistedSince");
  2271. break;
  2272. }
  2273. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  2274. /* ignore failure */
  2275. parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  2276. }
  2277. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  2278. node->unreachable_since = when;
  2279. node->last_attempted = last_try;
  2280. } else {
  2281. node->bad_since = when;
  2282. }
  2283. }
  2284. }
  2285. if (*msg || !set) {
  2286. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e, tor_free(e));
  2287. smartlist_free(new_entry_guards);
  2288. } else { /* !*err && set */
  2289. if (entry_guards) {
  2290. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, tor_free(e));
  2291. smartlist_free(entry_guards);
  2292. }
  2293. entry_guards = new_entry_guards;
  2294. entry_guards_dirty = 0;
  2295. }
  2296. return *msg ? -1 : 0;
  2297. }
  2298. /** Our list of entry guards has changed, or some element of one
  2299. * of our entry guards has changed. Write the changes to disk within
  2300. * the next few minutes.
  2301. */
  2302. static void
  2303. entry_guards_changed(void)
  2304. {
  2305. time_t when;
  2306. entry_guards_dirty = 1;
  2307. /* or_state_save() will call entry_guards_update_state(). */
  2308. when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
  2309. or_state_mark_dirty(get_or_state(), when);
  2310. }
  2311. /** If the entry guard info has not changed, do nothing and return.
  2312. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  2313. * a new one out of the global entry_guards list, and then mark
  2314. * <b>state</b> dirty so it will get saved to disk.
  2315. */
  2316. void
  2317. entry_guards_update_state(or_state_t *state)
  2318. {
  2319. config_line_t **next, *line;
  2320. if (! entry_guards_dirty)
  2321. return;
  2322. config_free_lines(state->EntryGuards);
  2323. next = &state->EntryGuards;
  2324. *next = NULL;
  2325. if (!entry_guards)
  2326. entry_guards = smartlist_create();
  2327. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2328. {
  2329. char dbuf[HEX_DIGEST_LEN+1];
  2330. if (!e->made_contact)
  2331. continue; /* don't write this one to disk */
  2332. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2333. line->key = tor_strdup("EntryGuard");
  2334. line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
  2335. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  2336. tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
  2337. "%s %s", e->nickname, dbuf);
  2338. next = &(line->next);
  2339. if (e->unreachable_since) {
  2340. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2341. line->key = tor_strdup("EntryGuardDownSince");
  2342. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  2343. format_iso_time(line->value, e->unreachable_since);
  2344. if (e->last_attempted) {
  2345. line->value[ISO_TIME_LEN] = ' ';
  2346. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  2347. }
  2348. next = &(line->next);
  2349. }
  2350. if (e->bad_since) {
  2351. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2352. line->key = tor_strdup("EntryGuardUnlistedSince");
  2353. line->value = tor_malloc(ISO_TIME_LEN+1);
  2354. format_iso_time(line->value, e->bad_since);
  2355. next = &(line->next);
  2356. }
  2357. });
  2358. if (!get_options()->AvoidDiskWrites)
  2359. or_state_mark_dirty(get_or_state(), 0);
  2360. entry_guards_dirty = 0;
  2361. }
  2362. /** If <b>question</b> is the string "entry-guards", then dump
  2363. * to *<b>answer</b> a newly allocated string describing all of
  2364. * the nodes in the global entry_guards list. See control-spec.txt
  2365. * for details.
  2366. * For backward compatibility, we also handle the string "helper-nodes".
  2367. * */
  2368. int
  2369. getinfo_helper_entry_guards(control_connection_t *conn,
  2370. const char *question, char **answer)
  2371. {
  2372. int use_long_names = conn->use_long_names;
  2373. if (!strcmp(question,"entry-guards") ||
  2374. !strcmp(question,"helper-nodes")) {
  2375. smartlist_t *sl = smartlist_create();
  2376. char tbuf[ISO_TIME_LEN+1];
  2377. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  2378. if (!entry_guards)
  2379. entry_guards = smartlist_create();
  2380. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2381. {
  2382. size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
  2383. char *c = tor_malloc(len);
  2384. const char *status = NULL;
  2385. time_t when = 0;
  2386. if (!e->made_contact) {
  2387. status = "never-connected";
  2388. } else if (e->bad_since) {
  2389. when = e->bad_since;
  2390. status = "unusable";
  2391. } else {
  2392. status = "up";
  2393. }
  2394. if (use_long_names) {
  2395. routerinfo_t *ri = router_get_by_digest(e->identity);
  2396. if (ri) {
  2397. router_get_verbose_nickname(nbuf, ri);
  2398. } else {
  2399. nbuf[0] = '$';
  2400. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  2401. /* e->nickname field is not very reliable if we don't know about
  2402. * this router any longer; don't include it. */
  2403. }
  2404. } else {
  2405. base16_encode(nbuf, sizeof(nbuf), e->identity, DIGEST_LEN);
  2406. }
  2407. if (when) {
  2408. format_iso_time(tbuf, when);
  2409. tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
  2410. } else {
  2411. tor_snprintf(c, len, "%s %s\n", nbuf, status);
  2412. }
  2413. smartlist_add(sl, c);
  2414. });
  2415. *answer = smartlist_join_strings(sl, "", 0, NULL);
  2416. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  2417. smartlist_free(sl);
  2418. }
  2419. return 0;
  2420. }
  2421. typedef struct {
  2422. uint32_t addr;
  2423. uint16_t port;
  2424. char identity[DIGEST_LEN];
  2425. download_status_t fetch_status;
  2426. } bridge_info_t;
  2427. /** A list of known bridges. */
  2428. static smartlist_t *bridge_list = NULL;
  2429. /** Initialize the bridge list to empty, creating it if needed. */
  2430. void
  2431. clear_bridge_list(void)
  2432. {
  2433. if (!bridge_list)
  2434. bridge_list = smartlist_create();
  2435. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, tor_free(b));
  2436. smartlist_clear(bridge_list);
  2437. }
  2438. #if 0
  2439. /** Return 1 if <b>digest</b> is one of our known bridges. */
  2440. int
  2441. identity_digest_is_a_bridge(const char *digest)
  2442. {
  2443. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  2444. {
  2445. if (!memcmp(bridge->identity, digest, DIGEST_LEN))
  2446. return 1;
  2447. });
  2448. return 0;
  2449. }
  2450. #endif
  2451. /** Return a bridge pointer if <b>ri</b> is one of our known bridges
  2452. * (either by comparing keys if possible, else by comparing addr/port).
  2453. * Else return NULL. */
  2454. static bridge_info_t *
  2455. routerinfo_get_configured_bridge(routerinfo_t *ri)
  2456. {
  2457. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  2458. {
  2459. if (tor_digest_is_zero(bridge->identity) &&
  2460. bridge->addr == ri->addr && bridge->port == ri->or_port)
  2461. return bridge;
  2462. if (!memcmp(bridge->identity, ri->cache_info.identity_digest,
  2463. DIGEST_LEN))
  2464. return bridge;
  2465. });
  2466. return NULL;
  2467. }
  2468. /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
  2469. int
  2470. routerinfo_is_a_configured_bridge(routerinfo_t *ri)
  2471. {
  2472. return routerinfo_get_configured_bridge(ri) ? 1 : 0;
  2473. }
  2474. /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
  2475. * is set, it tells us the identity key too. */
  2476. void
  2477. bridge_add_from_config(uint32_t addr, uint16_t port, char *digest)
  2478. {
  2479. bridge_info_t *b = tor_malloc_zero(sizeof(bridge_info_t));
  2480. b->addr = addr;
  2481. b->port = port;
  2482. if (digest)
  2483. memcpy(b->identity, digest, DIGEST_LEN);
  2484. if (!bridge_list)
  2485. bridge_list = smartlist_create();
  2486. smartlist_add(bridge_list, b);
  2487. }
  2488. /** Schedule the next fetch for <b>bridge</b>, based on
  2489. * some retry schedule. */
  2490. static void
  2491. bridge_fetch_status_increment(bridge_info_t *bridge, time_t now)
  2492. {
  2493. switch (bridge->fetch_status.n_download_failures) {
  2494. case 0: bridge->fetch_status.next_attempt_at = now+60*15; break;
  2495. case 1: bridge->fetch_status.next_attempt_at = now+60*15; break;
  2496. default: bridge->fetch_status.next_attempt_at = now+60*60; break;
  2497. }
  2498. if (bridge->fetch_status.n_download_failures < 10)
  2499. bridge->fetch_status.n_download_failures++;
  2500. }
  2501. /** We just got a new descriptor for <b>bridge</b>. Reschedule the
  2502. * next fetch for a long time from <b>now</b>. */
  2503. static void
  2504. bridge_fetch_status_arrived(bridge_info_t *bridge, time_t now)
  2505. {
  2506. bridge->fetch_status.next_attempt_at = now+60*60;
  2507. bridge->fetch_status.n_download_failures = 0;
  2508. }
  2509. /** For each bridge in our list for which we don't currently have a
  2510. * descriptor, fetch a new copy of its descriptor -- either directly
  2511. * from the bridge or via a bridge authority. */
  2512. void
  2513. fetch_bridge_descriptors(time_t now)
  2514. {
  2515. char address_buf[INET_NTOA_BUF_LEN+1];
  2516. struct in_addr in;
  2517. or_options_t *options = get_options();
  2518. int num_bridge_auths = get_n_authorities(BRIDGE_AUTHORITY);
  2519. int ask_bridge_directly;
  2520. if (!bridge_list)
  2521. return;
  2522. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  2523. {
  2524. if (bridge->fetch_status.next_attempt_at > now)
  2525. continue; /* don't bother, no need to retry yet */
  2526. /* schedule another fetch as if this one will fail, in case it does */
  2527. bridge_fetch_status_increment(bridge, now);
  2528. in.s_addr = htonl(bridge->addr);
  2529. tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
  2530. ask_bridge_directly = tor_digest_is_zero(bridge->identity) ||
  2531. !options->UpdateBridgesFromAuthority ||
  2532. !num_bridge_auths;
  2533. if (ask_bridge_directly &&
  2534. !fascist_firewall_allows_address_or(bridge->addr, bridge->port)) {
  2535. log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
  2536. "firewall policy. %s.", address_buf, bridge->port,
  2537. num_bridge_auths ? "Asking bridge authority instead" :
  2538. "Skipping");
  2539. ask_bridge_directly = 0;
  2540. }
  2541. if (ask_bridge_directly) {
  2542. if (!connection_get_by_type_addr_port_purpose(
  2543. CONN_TYPE_DIR, bridge->addr, bridge->port,
  2544. DIR_PURPOSE_FETCH_SERVERDESC)) {
  2545. /* we need to ask the bridge itself for its descriptor. */
  2546. directory_initiate_command(address_buf, bridge->addr,
  2547. bridge->port, 0,
  2548. 1, bridge->identity,
  2549. DIR_PURPOSE_FETCH_SERVERDESC,
  2550. ROUTER_PURPOSE_BRIDGE,
  2551. 0, "authority.z", NULL, 0);
  2552. }
  2553. } else {
  2554. /* We have a digest and we want to ask an authority. We could
  2555. * combine all the requests into one, but that may give more
  2556. * hints to the bridge authority than we want to give. */
  2557. char resource[10 + HEX_DIGEST_LEN];
  2558. memcpy(resource, "fp/", 3);
  2559. base16_encode(resource+3, HEX_DIGEST_LEN+1,
  2560. bridge->identity, DIGEST_LEN);
  2561. memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
  2562. log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
  2563. resource);
  2564. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  2565. ROUTER_PURPOSE_BRIDGE, resource, 1);
  2566. }
  2567. });
  2568. }
  2569. /** We just learned a descriptor for a bridge. See if that
  2570. * digest is in our entry guard list, and add it if not. */
  2571. void
  2572. learned_bridge_descriptor(routerinfo_t *ri)
  2573. {
  2574. tor_assert(ri);
  2575. tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
  2576. if (get_options()->UseBridges) {
  2577. int first = !any_bridge_descriptors_known();
  2578. bridge_info_t *bridge = routerinfo_get_configured_bridge(ri);
  2579. time_t now = time(NULL);
  2580. ri->is_running = 1;
  2581. /* it's here; schedule its re-fetch for a long time from now. */
  2582. bridge_fetch_status_arrived(bridge, now);
  2583. add_an_entry_guard(ri, 1);
  2584. log_notice(LD_DIR, "new bridge descriptor '%s'", ri->nickname);
  2585. if (first)
  2586. routerlist_retry_directory_downloads(now);
  2587. }
  2588. }
  2589. /** Return 1 if any of our entry guards have descriptors that
  2590. * are marked with purpose 'bridge' and are running. Else return 0.
  2591. *
  2592. * We use this function to decide if we're ready to start building
  2593. * circuits through our bridges, or if we need to wait until the
  2594. * directory "server/authority" requests finish. */
  2595. int
  2596. any_bridge_descriptors_known(void)
  2597. {
  2598. tor_assert(get_options()->UseBridges);
  2599. return choose_random_entry(NULL)!=NULL ? 1 : 0;
  2600. }
  2601. /** Return 1 if we have at least one descriptor for a bridge and
  2602. * all descriptors we know are down. Else return 0. If <b>act</b> is
  2603. * 1, then mark the down bridges up; else just observe and report. */
  2604. static int
  2605. bridges_retry_helper(int act)
  2606. {
  2607. routerinfo_t *ri;
  2608. int any_known = 0;
  2609. int any_running = 0;
  2610. if (!entry_guards)
  2611. entry_guards = smartlist_create();
  2612. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2613. {
  2614. ri = router_get_by_digest(e->identity);
  2615. if (ri && ri->purpose == ROUTER_PURPOSE_BRIDGE) {
  2616. any_known = 1;
  2617. if (ri->is_running)
  2618. any_running = 1; /* some bridge is both known and running */
  2619. else if (act) { /* mark it for retry */
  2620. ri->is_running = 1;
  2621. e->can_retry = 1;
  2622. e->bad_since = 0;
  2623. }
  2624. }
  2625. });
  2626. return any_known && !any_running;
  2627. }
  2628. /** Do we know any descriptors for our bridges, and are they all
  2629. * down? */
  2630. int
  2631. bridges_should_be_retried(void)
  2632. {
  2633. return bridges_retry_helper(0);
  2634. }
  2635. /** Mark all down known bridges up. */
  2636. void
  2637. bridges_retry_all(void)
  2638. {
  2639. bridges_retry_helper(1);
  2640. }
  2641. /** Release all storage held by the list of entry guards and related
  2642. * memory structs. */
  2643. void
  2644. entry_guards_free_all(void)
  2645. {
  2646. if (entry_guards) {
  2647. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, tor_free(e));
  2648. smartlist_free(entry_guards);
  2649. entry_guards = NULL;
  2650. }
  2651. clear_bridge_list();
  2652. smartlist_free(bridge_list);
  2653. bridge_list = NULL;
  2654. }