circuitbuild.c 108 KB

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