circuitbuild.c 109 KB

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