circuitbuild.c 111 KB

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