circuitbuild.c 104 KB

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