circuitbuild.c 105 KB

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