circuitbuild.c 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264
  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-2010, 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(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 = cell->payload+RELAY_HEADER_SIZE+4+2;
  699. id_digest = 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 char *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, 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, keys,
  844. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  845. log_warn(LD_CIRC,"fast_client_handshake failed.");
  846. return -END_CIRC_REASON_TORPROTOCOL;
  847. }
  848. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  849. } else {
  850. log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  851. return -END_CIRC_REASON_TORPROTOCOL;
  852. }
  853. if (hop->dh_handshake_state) {
  854. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  855. hop->dh_handshake_state = NULL;
  856. }
  857. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  858. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  859. return -END_CIRC_REASON_TORPROTOCOL;
  860. }
  861. hop->state = CPATH_STATE_OPEN;
  862. log_info(LD_CIRC,"Finished building %scircuit hop:",
  863. (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  864. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  865. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  866. return 0;
  867. }
  868. /** We received a relay truncated cell on circ.
  869. *
  870. * Since we don't ask for truncates currently, getting a truncated
  871. * means that a connection broke or an extend failed. For now,
  872. * just give up: for circ to close, and return 0.
  873. */
  874. int
  875. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
  876. {
  877. // crypt_path_t *victim;
  878. // connection_t *stream;
  879. tor_assert(circ);
  880. tor_assert(layer);
  881. /* XXX Since we don't ask for truncates currently, getting a truncated
  882. * means that a connection broke or an extend failed. For now,
  883. * just give up.
  884. */
  885. circuit_mark_for_close(TO_CIRCUIT(circ),
  886. END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
  887. return 0;
  888. #if 0
  889. while (layer->next != circ->cpath) {
  890. /* we need to clear out layer->next */
  891. victim = layer->next;
  892. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  893. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  894. if (stream->cpath_layer == victim) {
  895. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  896. stream->stream_id);
  897. /* no need to send 'end' relay cells,
  898. * because the other side's already dead
  899. */
  900. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  901. }
  902. }
  903. layer->next = victim->next;
  904. circuit_free_cpath_node(victim);
  905. }
  906. log_info(LD_CIRC, "finished");
  907. return 0;
  908. #endif
  909. }
  910. /** Given a response payload and keys, initialize, then send a created
  911. * cell back.
  912. */
  913. int
  914. onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
  915. const char *keys)
  916. {
  917. cell_t cell;
  918. crypt_path_t *tmp_cpath;
  919. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  920. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  921. memset(&cell, 0, sizeof(cell_t));
  922. cell.command = cell_type;
  923. cell.circ_id = circ->p_circ_id;
  924. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  925. memcpy(cell.payload, payload,
  926. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  927. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  928. (unsigned int)*(uint32_t*)(keys),
  929. (unsigned int)*(uint32_t*)(keys+20));
  930. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  931. log_warn(LD_BUG,"Circuit initialization failed");
  932. tor_free(tmp_cpath);
  933. return -1;
  934. }
  935. circ->n_digest = tmp_cpath->f_digest;
  936. circ->n_crypto = tmp_cpath->f_crypto;
  937. circ->p_digest = tmp_cpath->b_digest;
  938. circ->p_crypto = tmp_cpath->b_crypto;
  939. tmp_cpath->magic = 0;
  940. tor_free(tmp_cpath);
  941. if (cell_type == CELL_CREATED)
  942. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  943. else
  944. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  945. circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
  946. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  947. circ->p_conn, &cell, CELL_DIRECTION_IN);
  948. log_debug(LD_CIRC,"Finished sending 'created' cell.");
  949. if (!is_local_addr(&circ->p_conn->_base.addr) &&
  950. !connection_or_nonopen_was_started_here(circ->p_conn)) {
  951. /* record that we could process create cells from a non-local conn
  952. * that we didn't initiate; presumably this means that create cells
  953. * can reach us too. */
  954. router_orport_found_reachable();
  955. }
  956. return 0;
  957. }
  958. /** Choose a length for a circuit of purpose <b>purpose</b>.
  959. * Default length is 3 + the number of endpoints that would give something
  960. * away. If the routerlist <b>routers</b> doesn't have enough routers
  961. * to handle the desired path length, return as large a path length as
  962. * is feasible, except if it's less than 2, in which case return -1.
  963. */
  964. static int
  965. new_route_len(uint8_t purpose, extend_info_t *exit,
  966. smartlist_t *routers)
  967. {
  968. int num_acceptable_routers;
  969. int routelen;
  970. tor_assert(routers);
  971. routelen = 3;
  972. if (exit &&
  973. purpose != CIRCUIT_PURPOSE_TESTING &&
  974. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  975. routelen++;
  976. num_acceptable_routers = count_acceptable_routers(routers);
  977. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  978. routelen, num_acceptable_routers, smartlist_len(routers));
  979. if (num_acceptable_routers < 2) {
  980. log_info(LD_CIRC,
  981. "Not enough acceptable routers (%d). Discarding this circuit.",
  982. num_acceptable_routers);
  983. return -1;
  984. }
  985. if (num_acceptable_routers < routelen) {
  986. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  987. routelen, num_acceptable_routers);
  988. routelen = num_acceptable_routers;
  989. }
  990. return routelen;
  991. }
  992. /** Fetch the list of predicted ports, dup it into a smartlist of
  993. * uint16_t's, remove the ones that are already handled by an
  994. * existing circuit, and return it.
  995. */
  996. static smartlist_t *
  997. circuit_get_unhandled_ports(time_t now)
  998. {
  999. smartlist_t *source = rep_hist_get_predicted_ports(now);
  1000. smartlist_t *dest = smartlist_create();
  1001. uint16_t *tmp;
  1002. int i;
  1003. for (i = 0; i < smartlist_len(source); ++i) {
  1004. tmp = tor_malloc(sizeof(uint16_t));
  1005. memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
  1006. smartlist_add(dest, tmp);
  1007. }
  1008. circuit_remove_handled_ports(dest);
  1009. return dest;
  1010. }
  1011. /** Return 1 if we already have circuits present or on the way for
  1012. * all anticipated ports. Return 0 if we should make more.
  1013. *
  1014. * If we're returning 0, set need_uptime and need_capacity to
  1015. * indicate any requirements that the unhandled ports have.
  1016. */
  1017. int
  1018. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  1019. int *need_capacity)
  1020. {
  1021. int i, enough;
  1022. uint16_t *port;
  1023. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1024. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1025. tor_assert(need_uptime);
  1026. tor_assert(need_capacity);
  1027. enough = (smartlist_len(sl) == 0);
  1028. for (i = 0; i < smartlist_len(sl); ++i) {
  1029. port = smartlist_get(sl, i);
  1030. if (smartlist_string_num_isin(LongLivedServices, *port))
  1031. *need_uptime = 1;
  1032. tor_free(port);
  1033. }
  1034. smartlist_free(sl);
  1035. return enough;
  1036. }
  1037. /** Return 1 if <b>router</b> can handle one or more of the ports in
  1038. * <b>needed_ports</b>, else return 0.
  1039. */
  1040. static int
  1041. router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
  1042. {
  1043. int i;
  1044. uint16_t port;
  1045. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1046. addr_policy_result_t r;
  1047. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1048. tor_assert(port);
  1049. r = compare_addr_to_addr_policy(0, port, router->exit_policy);
  1050. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1051. return 1;
  1052. }
  1053. return 0;
  1054. }
  1055. /** Return true iff <b>conn</b> needs another general circuit to be
  1056. * built. */
  1057. static int
  1058. ap_stream_wants_exit_attention(connection_t *conn)
  1059. {
  1060. if (conn->type == CONN_TYPE_AP &&
  1061. conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1062. !conn->marked_for_close &&
  1063. !(TO_EDGE_CONN(conn)->want_onehop) && /* ignore one-hop streams */
  1064. !(TO_EDGE_CONN(conn)->use_begindir) && /* ignore targeted dir fetches */
  1065. !(TO_EDGE_CONN(conn)->chosen_exit_name) && /* ignore defined streams */
  1066. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1067. !circuit_stream_is_being_handled(TO_EDGE_CONN(conn), 0,
  1068. MIN_CIRCUITS_HANDLING_STREAM))
  1069. return 1;
  1070. return 0;
  1071. }
  1072. /** Return a pointer to a suitable router to be the exit node for the
  1073. * general-purpose circuit we're about to build.
  1074. *
  1075. * Look through the connection array, and choose a router that maximizes
  1076. * the number of pending streams that can exit from this router.
  1077. *
  1078. * Return NULL if we can't find any suitable routers.
  1079. */
  1080. static routerinfo_t *
  1081. choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
  1082. int need_capacity)
  1083. {
  1084. int *n_supported;
  1085. int i;
  1086. int n_pending_connections = 0;
  1087. smartlist_t *connections;
  1088. int best_support = -1;
  1089. int n_best_support=0;
  1090. routerinfo_t *router;
  1091. or_options_t *options = get_options();
  1092. connections = get_connection_array();
  1093. /* Count how many connections are waiting for a circuit to be built.
  1094. * We use this for log messages now, but in the future we may depend on it.
  1095. */
  1096. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1097. {
  1098. if (ap_stream_wants_exit_attention(conn))
  1099. ++n_pending_connections;
  1100. });
  1101. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1102. // n_pending_connections);
  1103. /* Now we count, for each of the routers in the directory, how many
  1104. * of the pending connections could possibly exit from that
  1105. * router (n_supported[i]). (We can't be sure about cases where we
  1106. * don't know the IP address of the pending connection.)
  1107. *
  1108. * -1 means "Don't use this router at all."
  1109. */
  1110. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  1111. for (i = 0; i < smartlist_len(dir->routers); ++i) {/* iterate over routers */
  1112. router = smartlist_get(dir->routers, i);
  1113. if (router_is_me(router)) {
  1114. n_supported[i] = -1;
  1115. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1116. /* XXX there's probably a reverse predecessor attack here, but
  1117. * it's slow. should we take this out? -RD
  1118. */
  1119. continue;
  1120. }
  1121. if (!router->is_running || router->is_bad_exit) {
  1122. n_supported[i] = -1;
  1123. continue; /* skip routers that are known to be down or bad exits */
  1124. }
  1125. if (router_is_unreliable(router, need_uptime, need_capacity, 0)) {
  1126. n_supported[i] = -1;
  1127. continue; /* skip routers that are not suitable */
  1128. }
  1129. if (!(router->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
  1130. /* if it's invalid and we don't want it */
  1131. n_supported[i] = -1;
  1132. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1133. // router->nickname, i);
  1134. continue; /* skip invalid routers */
  1135. }
  1136. if (options->ExcludeSingleHopRelays && router->allow_single_hop_exits) {
  1137. n_supported[i] = -1;
  1138. continue;
  1139. }
  1140. if (router_exit_policy_rejects_all(router)) {
  1141. n_supported[i] = -1;
  1142. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1143. // router->nickname, i);
  1144. continue; /* skip routers that reject all */
  1145. }
  1146. n_supported[i] = 0;
  1147. /* iterate over connections */
  1148. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1149. {
  1150. if (!ap_stream_wants_exit_attention(conn))
  1151. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1152. if (connection_ap_can_use_exit(TO_EDGE_CONN(conn), router)) {
  1153. ++n_supported[i];
  1154. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1155. // router->nickname, i, n_supported[i]);
  1156. } else {
  1157. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1158. // router->nickname, i);
  1159. }
  1160. }); /* End looping over connections. */
  1161. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1162. /* Leave best_support at -1 if that's where it is, so we can
  1163. * distinguish it later. */
  1164. continue;
  1165. }
  1166. if (n_supported[i] > best_support) {
  1167. /* If this router is better than previous ones, remember its index
  1168. * and goodness, and start counting how many routers are this good. */
  1169. best_support = n_supported[i]; n_best_support=1;
  1170. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1171. // router->nickname);
  1172. } else if (n_supported[i] == best_support) {
  1173. /* If this router is _as good_ as the best one, just increment the
  1174. * count of equally good routers.*/
  1175. ++n_best_support;
  1176. }
  1177. }
  1178. log_info(LD_CIRC,
  1179. "Found %d servers that might support %d/%d pending connections.",
  1180. n_best_support, best_support >= 0 ? best_support : 0,
  1181. n_pending_connections);
  1182. /* If any routers definitely support any pending connections, choose one
  1183. * at random. */
  1184. if (best_support > 0) {
  1185. smartlist_t *supporting = smartlist_create(), *use = smartlist_create();
  1186. for (i = 0; i < smartlist_len(dir->routers); i++)
  1187. if (n_supported[i] == best_support)
  1188. smartlist_add(supporting, smartlist_get(dir->routers, i));
  1189. routersets_get_disjunction(use, supporting, options->ExitNodes,
  1190. options->_ExcludeExitNodesUnion, 1);
  1191. if (smartlist_len(use) == 0 && !options->StrictExitNodes) {
  1192. routersets_get_disjunction(use, supporting, NULL,
  1193. options->_ExcludeExitNodesUnion, 1);
  1194. }
  1195. router = routerlist_sl_choose_by_bandwidth(use, WEIGHT_FOR_EXIT);
  1196. smartlist_free(use);
  1197. smartlist_free(supporting);
  1198. } else {
  1199. /* Either there are no pending connections, or no routers even seem to
  1200. * possibly support any of them. Choose a router at random that satisfies
  1201. * at least one predicted exit port. */
  1202. int try;
  1203. smartlist_t *needed_ports, *supporting, *use;
  1204. if (best_support == -1) {
  1205. if (need_uptime || need_capacity) {
  1206. log_info(LD_CIRC,
  1207. "We couldn't find any live%s%s routers; falling back "
  1208. "to list of all routers.",
  1209. need_capacity?", fast":"",
  1210. need_uptime?", stable":"");
  1211. tor_free(n_supported);
  1212. return choose_good_exit_server_general(dir, 0, 0);
  1213. }
  1214. log_notice(LD_CIRC, "All routers are down or won't exit -- choosing a "
  1215. "doomed exit at random.");
  1216. }
  1217. supporting = smartlist_create();
  1218. use = smartlist_create();
  1219. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1220. for (try = 0; try < 2; try++) {
  1221. /* try once to pick only from routers that satisfy a needed port,
  1222. * then if there are none, pick from any that support exiting. */
  1223. for (i = 0; i < smartlist_len(dir->routers); i++) {
  1224. router = smartlist_get(dir->routers, i);
  1225. if (n_supported[i] != -1 &&
  1226. (try || router_handles_some_port(router, needed_ports))) {
  1227. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1228. // try, router->nickname);
  1229. smartlist_add(supporting, router);
  1230. }
  1231. }
  1232. routersets_get_disjunction(use, supporting, options->ExitNodes,
  1233. options->_ExcludeExitNodesUnion, 1);
  1234. if (smartlist_len(use) == 0 && !options->StrictExitNodes) {
  1235. routersets_get_disjunction(use, supporting, NULL,
  1236. options->_ExcludeExitNodesUnion, 1);
  1237. }
  1238. /* XXX sometimes the above results in null, when the requested
  1239. * exit node is down. we should pick it anyway. */
  1240. router = routerlist_sl_choose_by_bandwidth(use, WEIGHT_FOR_EXIT);
  1241. if (router)
  1242. break;
  1243. smartlist_clear(supporting);
  1244. smartlist_clear(use);
  1245. }
  1246. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1247. smartlist_free(needed_ports);
  1248. smartlist_free(use);
  1249. smartlist_free(supporting);
  1250. }
  1251. tor_free(n_supported);
  1252. if (router) {
  1253. log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
  1254. return router;
  1255. }
  1256. if (options->StrictExitNodes) {
  1257. log_warn(LD_CIRC,
  1258. "No specified exit routers seem to be running, and "
  1259. "StrictExitNodes is set: can't choose an exit.");
  1260. }
  1261. return NULL;
  1262. }
  1263. /** Return a pointer to a suitable router to be the exit node for the
  1264. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1265. * if no router is suitable).
  1266. *
  1267. * For general-purpose circuits, pass it off to
  1268. * choose_good_exit_server_general()
  1269. *
  1270. * For client-side rendezvous circuits, choose a random node, weighted
  1271. * toward the preferences in 'options'.
  1272. */
  1273. static routerinfo_t *
  1274. choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
  1275. int need_uptime, int need_capacity, int is_internal)
  1276. {
  1277. or_options_t *options = get_options();
  1278. router_crn_flags_t flags = 0;
  1279. if (need_uptime)
  1280. flags |= CRN_NEED_UPTIME;
  1281. if (need_capacity)
  1282. flags |= CRN_NEED_CAPACITY;
  1283. switch (purpose) {
  1284. case CIRCUIT_PURPOSE_C_GENERAL:
  1285. if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
  1286. flags |= CRN_ALLOW_INVALID;
  1287. if (is_internal) /* pick it like a middle hop */
  1288. return router_choose_random_node(NULL, NULL,
  1289. options->ExcludeNodes, flags);
  1290. else
  1291. return choose_good_exit_server_general(dir,need_uptime,need_capacity);
  1292. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1293. if (options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS)
  1294. flags |= CRN_ALLOW_INVALID;
  1295. return router_choose_random_node(NULL, NULL,
  1296. options->ExcludeNodes, flags);
  1297. }
  1298. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1299. tor_fragile_assert();
  1300. return NULL;
  1301. }
  1302. /** Log a warning if the user specified an exit for the circuit that
  1303. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  1304. static void
  1305. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  1306. {
  1307. or_options_t *options = get_options();
  1308. routerset_t *rs = options->ExcludeNodes;
  1309. const char *description;
  1310. int domain = LD_CIRC;
  1311. uint8_t purpose = circ->_base.purpose;
  1312. if (circ->build_state->onehop_tunnel)
  1313. return;
  1314. switch (purpose)
  1315. {
  1316. default:
  1317. case CIRCUIT_PURPOSE_OR:
  1318. case CIRCUIT_PURPOSE_INTRO_POINT:
  1319. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  1320. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  1321. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d)",
  1322. (int)purpose);
  1323. return;
  1324. case CIRCUIT_PURPOSE_C_GENERAL:
  1325. if (circ->build_state->is_internal)
  1326. return;
  1327. description = "Requested exit node";
  1328. rs = options->_ExcludeExitNodesUnion;
  1329. break;
  1330. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1331. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  1332. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  1333. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1334. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1335. case CIRCUIT_PURPOSE_S_REND_JOINED:
  1336. case CIRCUIT_PURPOSE_TESTING:
  1337. return;
  1338. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1339. case CIRCUIT_PURPOSE_C_REND_READY:
  1340. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  1341. case CIRCUIT_PURPOSE_C_REND_JOINED:
  1342. description = "Chosen rendezvous point";
  1343. domain = LD_BUG;
  1344. break;
  1345. case CIRCUIT_PURPOSE_CONTROLLER:
  1346. rs = options->_ExcludeExitNodesUnion;
  1347. description = "Controller-selected circuit target";
  1348. break;
  1349. }
  1350. if (routerset_contains_extendinfo(rs, exit)) {
  1351. log_fn(LOG_WARN, domain, "%s '%s' is in ExcludeNodes%s. Using anyway "
  1352. "(circuit purpose %d).",
  1353. description,exit->nickname,
  1354. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1355. (int)purpose);
  1356. circuit_log_path(LOG_WARN, domain, circ);
  1357. }
  1358. return;
  1359. }
  1360. /** Decide a suitable length for circ's cpath, and pick an exit
  1361. * router (or use <b>exit</b> if provided). Store these in the
  1362. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1363. static int
  1364. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1365. {
  1366. cpath_build_state_t *state = circ->build_state;
  1367. routerlist_t *rl = router_get_routerlist();
  1368. if (state->onehop_tunnel) {
  1369. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1370. state->desired_path_len = 1;
  1371. } else {
  1372. int r = new_route_len(circ->_base.purpose, exit, rl->routers);
  1373. if (r < 1) /* must be at least 1 */
  1374. return -1;
  1375. state->desired_path_len = r;
  1376. }
  1377. if (exit) { /* the circuit-builder pre-requested one */
  1378. warn_if_last_router_excluded(circ, exit);
  1379. log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
  1380. exit = extend_info_dup(exit);
  1381. } else { /* we have to decide one */
  1382. routerinfo_t *router =
  1383. choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
  1384. state->need_capacity, state->is_internal);
  1385. if (!router) {
  1386. log_warn(LD_CIRC,"failed to choose an exit server");
  1387. return -1;
  1388. }
  1389. exit = extend_info_from_router(router);
  1390. }
  1391. state->chosen_exit = exit;
  1392. return 0;
  1393. }
  1394. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1395. * hop to the cpath reflecting this. Don't send the next extend cell --
  1396. * the caller will do this if it wants to.
  1397. */
  1398. int
  1399. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1400. {
  1401. cpath_build_state_t *state;
  1402. tor_assert(exit);
  1403. tor_assert(circ);
  1404. state = circ->build_state;
  1405. tor_assert(state);
  1406. if (state->chosen_exit)
  1407. extend_info_free(state->chosen_exit);
  1408. state->chosen_exit = extend_info_dup(exit);
  1409. ++circ->build_state->desired_path_len;
  1410. onion_append_hop(&circ->cpath, exit);
  1411. return 0;
  1412. }
  1413. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1414. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1415. * send the next extend cell to begin connecting to that hop.
  1416. */
  1417. int
  1418. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1419. {
  1420. int err_reason = 0;
  1421. warn_if_last_router_excluded(circ, exit);
  1422. circuit_append_new_exit(circ, exit);
  1423. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1424. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1425. log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
  1426. exit->nickname);
  1427. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1428. return -1;
  1429. }
  1430. return 0;
  1431. }
  1432. /** Return the number of routers in <b>routers</b> that are currently up
  1433. * and available for building circuits through.
  1434. */
  1435. static int
  1436. count_acceptable_routers(smartlist_t *routers)
  1437. {
  1438. int i, n;
  1439. int num=0;
  1440. routerinfo_t *r;
  1441. n = smartlist_len(routers);
  1442. for (i=0;i<n;i++) {
  1443. r = smartlist_get(routers, i);
  1444. // log_debug(LD_CIRC,
  1445. // "Contemplating whether router %d (%s) is a new option.",
  1446. // i, r->nickname);
  1447. if (r->is_running == 0) {
  1448. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1449. goto next_i_loop;
  1450. }
  1451. if (r->is_valid == 0) {
  1452. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1453. goto next_i_loop;
  1454. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1455. * allows this node in some places, then we're getting an inaccurate
  1456. * count. For now, be conservative and don't count it. But later we
  1457. * should try to be smarter. */
  1458. }
  1459. num++;
  1460. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1461. next_i_loop:
  1462. ; /* C requires an explicit statement after the label */
  1463. }
  1464. return num;
  1465. }
  1466. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1467. * This function is used to extend cpath by another hop.
  1468. */
  1469. void
  1470. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1471. {
  1472. if (*head_ptr) {
  1473. new_hop->next = (*head_ptr);
  1474. new_hop->prev = (*head_ptr)->prev;
  1475. (*head_ptr)->prev->next = new_hop;
  1476. (*head_ptr)->prev = new_hop;
  1477. } else {
  1478. *head_ptr = new_hop;
  1479. new_hop->prev = new_hop->next = new_hop;
  1480. }
  1481. }
  1482. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1483. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1484. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1485. * circuit. In particular, make sure we don't pick the exit node or its
  1486. * family, and make sure we don't duplicate any previous nodes or their
  1487. * families. */
  1488. static routerinfo_t *
  1489. choose_good_middle_server(uint8_t purpose,
  1490. cpath_build_state_t *state,
  1491. crypt_path_t *head,
  1492. int cur_len)
  1493. {
  1494. int i;
  1495. routerinfo_t *r, *choice;
  1496. crypt_path_t *cpath;
  1497. smartlist_t *excluded;
  1498. or_options_t *options = get_options();
  1499. router_crn_flags_t flags = 0;
  1500. tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
  1501. purpose <= _CIRCUIT_PURPOSE_MAX);
  1502. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1503. excluded = smartlist_create();
  1504. if ((r = build_state_get_exit_router(state))) {
  1505. smartlist_add(excluded, r);
  1506. routerlist_add_family(excluded, r);
  1507. }
  1508. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1509. if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
  1510. smartlist_add(excluded, r);
  1511. routerlist_add_family(excluded, r);
  1512. }
  1513. }
  1514. if (state->need_uptime)
  1515. flags |= CRN_NEED_UPTIME;
  1516. if (state->need_capacity)
  1517. flags |= CRN_NEED_CAPACITY;
  1518. if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
  1519. flags |= CRN_ALLOW_INVALID;
  1520. choice = router_choose_random_node(NULL,
  1521. excluded, options->ExcludeNodes, flags);
  1522. smartlist_free(excluded);
  1523. return choice;
  1524. }
  1525. /** Pick a good entry server for the circuit to be built according to
  1526. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  1527. * router (if we're an OR), and respect firewall settings; if we're
  1528. * configured to use entry guards, return one.
  1529. *
  1530. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  1531. * guard, not for any particular circuit.
  1532. */
  1533. static routerinfo_t *
  1534. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  1535. {
  1536. routerinfo_t *r, *choice;
  1537. smartlist_t *excluded;
  1538. or_options_t *options = get_options();
  1539. router_crn_flags_t flags = CRN_NEED_GUARD;
  1540. if (state && options->UseEntryGuards &&
  1541. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  1542. return choose_random_entry(state);
  1543. }
  1544. excluded = smartlist_create();
  1545. if (state && (r = build_state_get_exit_router(state))) {
  1546. smartlist_add(excluded, r);
  1547. routerlist_add_family(excluded, r);
  1548. }
  1549. if (firewall_is_fascist_or()) {
  1550. /*XXXX This could slow things down a lot; use a smarter implementation */
  1551. /* exclude all ORs that listen on the wrong port, if anybody notices. */
  1552. routerlist_t *rl = router_get_routerlist();
  1553. int i;
  1554. for (i=0; i < smartlist_len(rl->routers); i++) {
  1555. r = smartlist_get(rl->routers, i);
  1556. if (!fascist_firewall_allows_or(r))
  1557. smartlist_add(excluded, r);
  1558. }
  1559. }
  1560. /* and exclude current entry guards, if applicable */
  1561. if (options->UseEntryGuards && entry_guards) {
  1562. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1563. {
  1564. if ((r = router_get_by_digest(entry->identity))) {
  1565. smartlist_add(excluded, r);
  1566. routerlist_add_family(excluded, r);
  1567. }
  1568. });
  1569. }
  1570. if (state) {
  1571. if (state->need_uptime)
  1572. flags |= CRN_NEED_UPTIME;
  1573. if (state->need_capacity)
  1574. flags |= CRN_NEED_CAPACITY;
  1575. }
  1576. if (options->_AllowInvalid & ALLOW_INVALID_ENTRY)
  1577. flags |= CRN_ALLOW_INVALID;
  1578. choice = router_choose_random_node(
  1579. NULL,
  1580. excluded,
  1581. options->ExcludeNodes,
  1582. flags);
  1583. smartlist_free(excluded);
  1584. return choice;
  1585. }
  1586. /** Return the first non-open hop in cpath, or return NULL if all
  1587. * hops are open. */
  1588. static crypt_path_t *
  1589. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1590. {
  1591. crypt_path_t *hop = cpath;
  1592. do {
  1593. if (hop->state != CPATH_STATE_OPEN)
  1594. return hop;
  1595. hop = hop->next;
  1596. } while (hop != cpath);
  1597. return NULL;
  1598. }
  1599. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1600. * based on <b>state</b>. Append the hop info to head_ptr.
  1601. */
  1602. static int
  1603. onion_extend_cpath(origin_circuit_t *circ)
  1604. {
  1605. uint8_t purpose = circ->_base.purpose;
  1606. cpath_build_state_t *state = circ->build_state;
  1607. int cur_len = circuit_get_cpath_len(circ);
  1608. extend_info_t *info = NULL;
  1609. if (cur_len >= state->desired_path_len) {
  1610. log_debug(LD_CIRC, "Path is complete: %d steps long",
  1611. state->desired_path_len);
  1612. return 1;
  1613. }
  1614. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  1615. state->desired_path_len);
  1616. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1617. info = extend_info_dup(state->chosen_exit);
  1618. } else if (cur_len == 0) { /* picking first node */
  1619. routerinfo_t *r = choose_good_entry_server(purpose, state);
  1620. if (r)
  1621. info = extend_info_from_router(r);
  1622. } else {
  1623. routerinfo_t *r =
  1624. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  1625. if (r)
  1626. info = extend_info_from_router(r);
  1627. }
  1628. if (!info) {
  1629. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  1630. "this circuit.", cur_len);
  1631. return -1;
  1632. }
  1633. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  1634. info->nickname, cur_len+1, build_state_get_exit_nickname(state));
  1635. onion_append_hop(&circ->cpath, info);
  1636. extend_info_free(info);
  1637. return 0;
  1638. }
  1639. /** Create a new hop, annotate it with information about its
  1640. * corresponding router <b>choice</b>, and append it to the
  1641. * end of the cpath <b>head_ptr</b>. */
  1642. static int
  1643. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1644. {
  1645. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1646. /* link hop into the cpath, at the end. */
  1647. onion_append_to_cpath(head_ptr, hop);
  1648. hop->magic = CRYPT_PATH_MAGIC;
  1649. hop->state = CPATH_STATE_CLOSED;
  1650. hop->extend_info = extend_info_dup(choice);
  1651. hop->package_window = circuit_initial_package_window();
  1652. hop->deliver_window = CIRCWINDOW_START;
  1653. return 0;
  1654. }
  1655. /** Allocate a new extend_info object based on the various arguments. */
  1656. extend_info_t *
  1657. extend_info_alloc(const char *nickname, const char *digest,
  1658. crypto_pk_env_t *onion_key,
  1659. const tor_addr_t *addr, uint16_t port)
  1660. {
  1661. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  1662. memcpy(info->identity_digest, digest, DIGEST_LEN);
  1663. if (nickname)
  1664. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  1665. if (onion_key)
  1666. info->onion_key = crypto_pk_dup_key(onion_key);
  1667. tor_addr_copy(&info->addr, addr);
  1668. info->port = port;
  1669. return info;
  1670. }
  1671. /** Allocate and return a new extend_info_t that can be used to build a
  1672. * circuit to or through the router <b>r</b>. */
  1673. extend_info_t *
  1674. extend_info_from_router(routerinfo_t *r)
  1675. {
  1676. tor_addr_t addr;
  1677. tor_assert(r);
  1678. tor_addr_from_ipv4h(&addr, r->addr);
  1679. return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
  1680. r->onion_pkey, &addr, r->or_port);
  1681. }
  1682. /** Release storage held by an extend_info_t struct. */
  1683. void
  1684. extend_info_free(extend_info_t *info)
  1685. {
  1686. tor_assert(info);
  1687. if (info->onion_key)
  1688. crypto_free_pk_env(info->onion_key);
  1689. tor_free(info);
  1690. }
  1691. /** Allocate and return a new extend_info_t with the same contents as
  1692. * <b>info</b>. */
  1693. extend_info_t *
  1694. extend_info_dup(extend_info_t *info)
  1695. {
  1696. extend_info_t *newinfo;
  1697. tor_assert(info);
  1698. newinfo = tor_malloc(sizeof(extend_info_t));
  1699. memcpy(newinfo, info, sizeof(extend_info_t));
  1700. if (info->onion_key)
  1701. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1702. else
  1703. newinfo->onion_key = NULL;
  1704. return newinfo;
  1705. }
  1706. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  1707. * If there is no chosen exit, or if we don't know the routerinfo_t for
  1708. * the chosen exit, return NULL.
  1709. */
  1710. routerinfo_t *
  1711. build_state_get_exit_router(cpath_build_state_t *state)
  1712. {
  1713. if (!state || !state->chosen_exit)
  1714. return NULL;
  1715. return router_get_by_digest(state->chosen_exit->identity_digest);
  1716. }
  1717. /** Return the nickname for the chosen exit router in <b>state</b>. If
  1718. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1719. * chosen exit, return NULL.
  1720. */
  1721. const char *
  1722. build_state_get_exit_nickname(cpath_build_state_t *state)
  1723. {
  1724. if (!state || !state->chosen_exit)
  1725. return NULL;
  1726. return state->chosen_exit->nickname;
  1727. }
  1728. /** Check whether the entry guard <b>e</b> is usable, given the directory
  1729. * authorities' opinion about the router (stored in <b>ri</b>) and the user's
  1730. * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
  1731. * accordingly. Return true iff the entry guard's status changes.
  1732. *
  1733. * If it's not usable, set *<b>reason</b> to a static string explaining why.
  1734. */
  1735. /*XXXX take a routerstatus, not a routerinfo. */
  1736. static int
  1737. entry_guard_set_status(entry_guard_t *e, routerinfo_t *ri,
  1738. time_t now, or_options_t *options, const char **reason)
  1739. {
  1740. char buf[HEX_DIGEST_LEN+1];
  1741. int changed = 0;
  1742. tor_assert(options);
  1743. *reason = NULL;
  1744. /* Do we want to mark this guard as bad? */
  1745. if (!ri)
  1746. *reason = "unlisted";
  1747. else if (!ri->is_running)
  1748. *reason = "down";
  1749. else if (options->UseBridges && ri->purpose != ROUTER_PURPOSE_BRIDGE)
  1750. *reason = "not a bridge";
  1751. else if (!options->UseBridges && !ri->is_possible_guard &&
  1752. !routerset_contains_router(options->EntryNodes,ri))
  1753. *reason = "not recommended as a guard";
  1754. else if (routerset_contains_router(options->ExcludeNodes, ri))
  1755. *reason = "excluded";
  1756. if (*reason && ! e->bad_since) {
  1757. /* Router is newly bad. */
  1758. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  1759. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  1760. e->nickname, buf, *reason);
  1761. e->bad_since = now;
  1762. control_event_guard(e->nickname, e->identity, "BAD");
  1763. changed = 1;
  1764. } else if (!*reason && e->bad_since) {
  1765. /* There's nothing wrong with the router any more. */
  1766. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  1767. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  1768. "marking as ok.", e->nickname, buf);
  1769. e->bad_since = 0;
  1770. control_event_guard(e->nickname, e->identity, "GOOD");
  1771. changed = 1;
  1772. }
  1773. return changed;
  1774. }
  1775. /** Return true iff enough time has passed since we last tried to connect
  1776. * to the unreachable guard <b>e</b> that we're willing to try again. */
  1777. static int
  1778. entry_is_time_to_retry(entry_guard_t *e, time_t now)
  1779. {
  1780. long diff;
  1781. if (e->last_attempted < e->unreachable_since)
  1782. return 1;
  1783. diff = now - e->unreachable_since;
  1784. if (diff < 6*60*60)
  1785. return now > (e->last_attempted + 60*60);
  1786. else if (diff < 3*24*60*60)
  1787. return now > (e->last_attempted + 4*60*60);
  1788. else if (diff < 7*24*60*60)
  1789. return now > (e->last_attempted + 18*60*60);
  1790. else
  1791. return now > (e->last_attempted + 36*60*60);
  1792. }
  1793. /** Return the router corresponding to <b>e</b>, if <b>e</b> is
  1794. * working well enough that we are willing to use it as an entry
  1795. * right now. (Else return NULL.) In particular, it must be
  1796. * - Listed as either up or never yet contacted;
  1797. * - Present in the routerlist;
  1798. * - Listed as 'stable' or 'fast' by the current dirserver consensus,
  1799. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
  1800. * (This check is currently redundant with the Guard flag, but in
  1801. * the future that might change. Best to leave it in for now.)
  1802. * - Allowed by our current ReachableORAddresses config option; and
  1803. * - Currently thought to be reachable by us (unless assume_reachable
  1804. * is true).
  1805. */
  1806. static INLINE routerinfo_t *
  1807. entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
  1808. int assume_reachable)
  1809. {
  1810. routerinfo_t *r;
  1811. if (e->bad_since)
  1812. return NULL;
  1813. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  1814. if (!assume_reachable && !e->can_retry &&
  1815. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL)))
  1816. return NULL;
  1817. r = router_get_by_digest(e->identity);
  1818. if (!r)
  1819. return NULL;
  1820. if (get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_BRIDGE)
  1821. return NULL;
  1822. if (!get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_GENERAL)
  1823. return NULL;
  1824. if (router_is_unreliable(r, need_uptime, need_capacity, 0))
  1825. return NULL;
  1826. if (!fascist_firewall_allows_or(r))
  1827. return NULL;
  1828. return r;
  1829. }
  1830. /** Return the number of entry guards that we think are usable. */
  1831. static int
  1832. num_live_entry_guards(void)
  1833. {
  1834. int n = 0;
  1835. if (! entry_guards)
  1836. return 0;
  1837. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1838. {
  1839. if (entry_is_live(entry, 0, 1, 0))
  1840. ++n;
  1841. });
  1842. return n;
  1843. }
  1844. /** If <b>digest</b> matches the identity of any node in the
  1845. * entry_guards list, return that node. Else return NULL. */
  1846. static INLINE entry_guard_t *
  1847. is_an_entry_guard(const char *digest)
  1848. {
  1849. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1850. if (!memcmp(digest, entry->identity, DIGEST_LEN))
  1851. return entry;
  1852. );
  1853. return NULL;
  1854. }
  1855. /** Dump a description of our list of entry guards to the log at level
  1856. * <b>severity</b>. */
  1857. static void
  1858. log_entry_guards(int severity)
  1859. {
  1860. smartlist_t *elements = smartlist_create();
  1861. char buf[1024];
  1862. char *s;
  1863. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  1864. {
  1865. tor_snprintf(buf, sizeof(buf), "%s (%s%s)",
  1866. e->nickname,
  1867. entry_is_live(e, 0, 1, 0) ? "up " : "down ",
  1868. e->made_contact ? "made-contact" : "never-contacted");
  1869. smartlist_add(elements, tor_strdup(buf));
  1870. });
  1871. s = smartlist_join_strings(elements, ",", 0, NULL);
  1872. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  1873. smartlist_free(elements);
  1874. log_fn(severity,LD_CIRC,"%s",s);
  1875. tor_free(s);
  1876. }
  1877. /** Called when one or more guards that we would previously have used for some
  1878. * purpose are no longer in use because a higher-priority guard has become
  1879. * usable again. */
  1880. static void
  1881. control_event_guard_deferred(void)
  1882. {
  1883. /* XXXX We don't actually have a good way to figure out _how many_ entries
  1884. * are live for some purpose. We need an entry_is_even_slightly_live()
  1885. * function for this to work right. NumEntryGuards isn't reliable: if we
  1886. * need guards with weird properties, we can have more than that number
  1887. * live.
  1888. **/
  1889. #if 0
  1890. int n = 0;
  1891. or_options_t *options = get_options();
  1892. if (!entry_guards)
  1893. return;
  1894. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1895. {
  1896. if (entry_is_live(entry, 0, 1, 0)) {
  1897. if (n++ == options->NumEntryGuards) {
  1898. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  1899. return;
  1900. }
  1901. }
  1902. });
  1903. #endif
  1904. }
  1905. /** Add a new (preferably stable and fast) router to our
  1906. * entry_guards list. Return a pointer to the router if we succeed,
  1907. * or NULL if we can't find any more suitable entries.
  1908. *
  1909. * If <b>chosen</b> is defined, use that one, and if it's not
  1910. * already in our entry_guards list, put it at the *beginning*.
  1911. * Else, put the one we pick at the end of the list. */
  1912. static routerinfo_t *
  1913. add_an_entry_guard(routerinfo_t *chosen, int reset_status)
  1914. {
  1915. routerinfo_t *router;
  1916. entry_guard_t *entry;
  1917. if (chosen) {
  1918. router = chosen;
  1919. entry = is_an_entry_guard(router->cache_info.identity_digest);
  1920. if (entry) {
  1921. if (reset_status) {
  1922. entry->bad_since = 0;
  1923. entry->can_retry = 1;
  1924. }
  1925. return NULL;
  1926. }
  1927. } else {
  1928. router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  1929. if (!router)
  1930. return NULL;
  1931. }
  1932. entry = tor_malloc_zero(sizeof(entry_guard_t));
  1933. log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
  1934. strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
  1935. memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
  1936. /* Choose expiry time smudged over the past month. The goal here
  1937. * is to a) spread out when Tor clients rotate their guards, so they
  1938. * don't all select them on the same day, and b) avoid leaving a
  1939. * precise timestamp in the state file about when we first picked
  1940. * this guard. For details, see the Jan 2010 or-dev thread. */
  1941. entry->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
  1942. entry->chosen_by_version = tor_strdup(VERSION);
  1943. if (chosen) /* prepend */
  1944. smartlist_insert(entry_guards, 0, entry);
  1945. else /* append */
  1946. smartlist_add(entry_guards, entry);
  1947. control_event_guard(entry->nickname, entry->identity, "NEW");
  1948. control_event_guard_deferred();
  1949. log_entry_guards(LOG_INFO);
  1950. return router;
  1951. }
  1952. /** If the use of entry guards is configured, choose more entry guards
  1953. * until we have enough in the list. */
  1954. static void
  1955. pick_entry_guards(void)
  1956. {
  1957. or_options_t *options = get_options();
  1958. int changed = 0;
  1959. tor_assert(entry_guards);
  1960. while (num_live_entry_guards() < options->NumEntryGuards) {
  1961. if (!add_an_entry_guard(NULL, 0))
  1962. break;
  1963. changed = 1;
  1964. }
  1965. if (changed)
  1966. entry_guards_changed();
  1967. }
  1968. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  1969. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  1970. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  1971. /** Release all storage held by <b>e</b>. */
  1972. static void
  1973. entry_guard_free(entry_guard_t *e)
  1974. {
  1975. tor_assert(e);
  1976. tor_free(e->chosen_by_version);
  1977. tor_free(e);
  1978. }
  1979. /** Remove any entry guard which was selected by an unknown version of Tor,
  1980. * or which was selected by a version of Tor that's known to select
  1981. * entry guards badly. */
  1982. static int
  1983. remove_obsolete_entry_guards(void)
  1984. {
  1985. int changed = 0, i;
  1986. time_t now = time(NULL);
  1987. for (i = 0; i < smartlist_len(entry_guards); ++i) {
  1988. entry_guard_t *entry = smartlist_get(entry_guards, i);
  1989. const char *ver = entry->chosen_by_version;
  1990. const char *msg = NULL;
  1991. tor_version_t v;
  1992. int version_is_bad = 0, date_is_bad = 0;
  1993. if (!ver) {
  1994. msg = "does not say what version of Tor it was selected by";
  1995. version_is_bad = 1;
  1996. } else if (tor_version_parse(ver, &v)) {
  1997. msg = "does not seem to be from any recognized version of Tor";
  1998. version_is_bad = 1;
  1999. } else {
  2000. size_t len = strlen(ver)+5;
  2001. char *tor_ver = tor_malloc(len);
  2002. tor_snprintf(tor_ver, len, "Tor %s", ver);
  2003. if ((tor_version_as_new_as(tor_ver, "0.1.0.10-alpha") &&
  2004. !tor_version_as_new_as(tor_ver, "0.1.2.16-dev")) ||
  2005. (tor_version_as_new_as(tor_ver, "0.2.0.0-alpha") &&
  2006. !tor_version_as_new_as(tor_ver, "0.2.0.6-alpha")) ||
  2007. /* above are bug 440; below are bug 1217 */
  2008. (tor_version_as_new_as(tor_ver, "0.2.1.3-alpha") &&
  2009. !tor_version_as_new_as(tor_ver, "0.2.1.23")) ||
  2010. (tor_version_as_new_as(tor_ver, "0.2.2.0-alpha") &&
  2011. !tor_version_as_new_as(tor_ver, "0.2.2.7-alpha"))) {
  2012. msg = "was selected without regard for guard bandwidth";
  2013. version_is_bad = 1;
  2014. }
  2015. tor_free(tor_ver);
  2016. }
  2017. if (!version_is_bad && entry->chosen_on_date + 3600*24*60 < now) {
  2018. /* It's been 2 months since the date listed in our state file. */
  2019. msg = "was selected several months ago";
  2020. date_is_bad = 1;
  2021. }
  2022. if (version_is_bad || date_is_bad) { /* we need to drop it */
  2023. char dbuf[HEX_DIGEST_LEN+1];
  2024. tor_assert(msg);
  2025. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2026. log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
  2027. "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
  2028. entry->nickname, dbuf, msg, ver?escaped(ver):"none");
  2029. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2030. entry_guard_free(entry);
  2031. smartlist_del_keeporder(entry_guards, i--);
  2032. log_entry_guards(LOG_INFO);
  2033. changed = 1;
  2034. }
  2035. }
  2036. return changed ? 1 : 0;
  2037. }
  2038. /** Remove all entry guards that have been down or unlisted for so
  2039. * long that we don't think they'll come up again. Return 1 if we
  2040. * removed any, or 0 if we did nothing. */
  2041. static int
  2042. remove_dead_entry_guards(void)
  2043. {
  2044. char dbuf[HEX_DIGEST_LEN+1];
  2045. char tbuf[ISO_TIME_LEN+1];
  2046. time_t now = time(NULL);
  2047. int i;
  2048. int changed = 0;
  2049. for (i = 0; i < smartlist_len(entry_guards); ) {
  2050. entry_guard_t *entry = smartlist_get(entry_guards, i);
  2051. if (entry->bad_since &&
  2052. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  2053. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2054. format_local_iso_time(tbuf, entry->bad_since);
  2055. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  2056. "since %s local time; removing.",
  2057. entry->nickname, dbuf, tbuf);
  2058. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2059. entry_guard_free(entry);
  2060. smartlist_del_keeporder(entry_guards, i);
  2061. log_entry_guards(LOG_INFO);
  2062. changed = 1;
  2063. } else
  2064. ++i;
  2065. }
  2066. return changed ? 1 : 0;
  2067. }
  2068. /** A new directory or router-status has arrived; update the down/listed
  2069. * status of the entry guards.
  2070. *
  2071. * An entry is 'down' if the directory lists it as nonrunning.
  2072. * An entry is 'unlisted' if the directory doesn't include it.
  2073. *
  2074. * Don't call this on startup; only on a fresh download. Otherwise we'll
  2075. * think that things are unlisted.
  2076. */
  2077. void
  2078. entry_guards_compute_status(void)
  2079. {
  2080. time_t now;
  2081. int changed = 0;
  2082. int severity = LOG_DEBUG;
  2083. or_options_t *options;
  2084. digestmap_t *reasons;
  2085. if (! entry_guards)
  2086. return;
  2087. options = get_options();
  2088. now = time(NULL);
  2089. reasons = digestmap_new();
  2090. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry)
  2091. {
  2092. routerinfo_t *r = router_get_by_digest(entry->identity);
  2093. const char *reason = NULL;
  2094. if (entry_guard_set_status(entry, r, now, options, &reason))
  2095. changed = 1;
  2096. if (entry->bad_since)
  2097. tor_assert(reason);
  2098. if (reason)
  2099. digestmap_set(reasons, entry->identity, (char*)reason);
  2100. }
  2101. SMARTLIST_FOREACH_END(entry);
  2102. if (remove_dead_entry_guards())
  2103. changed = 1;
  2104. severity = changed ? LOG_DEBUG : LOG_INFO;
  2105. if (changed) {
  2106. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
  2107. const char *reason = digestmap_get(reasons, entry->identity);
  2108. log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s%s%s, and %s.",
  2109. entry->nickname,
  2110. entry->unreachable_since ? "unreachable" : "reachable",
  2111. entry->bad_since ? "unusable" : "usable",
  2112. reason ? ", ": "",
  2113. reason ? reason : "",
  2114. entry_is_live(entry, 0, 1, 0) ? "live" : "not live");
  2115. } SMARTLIST_FOREACH_END(entry);
  2116. log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
  2117. num_live_entry_guards(), smartlist_len(entry_guards));
  2118. log_entry_guards(LOG_INFO);
  2119. entry_guards_changed();
  2120. }
  2121. digestmap_free(reasons, NULL);
  2122. }
  2123. /** Called when a connection to an OR with the identity digest <b>digest</b>
  2124. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  2125. * If the OR is an entry, change that entry's up/down status.
  2126. * Return 0 normally, or -1 if we want to tear down the new connection.
  2127. *
  2128. * If <b>mark_relay_status</b>, also call router_set_status() on this
  2129. * relay.
  2130. *
  2131. * XXX022 change succeeded and mark_relay_status into 'int flags'.
  2132. */
  2133. int
  2134. entry_guard_register_connect_status(const char *digest, int succeeded,
  2135. int mark_relay_status, time_t now)
  2136. {
  2137. int changed = 0;
  2138. int refuse_conn = 0;
  2139. int first_contact = 0;
  2140. entry_guard_t *entry = NULL;
  2141. int idx = -1;
  2142. char buf[HEX_DIGEST_LEN+1];
  2143. if (! entry_guards)
  2144. return 0;
  2145. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2146. {
  2147. if (!memcmp(e->identity, digest, DIGEST_LEN)) {
  2148. entry = e;
  2149. idx = e_sl_idx;
  2150. break;
  2151. }
  2152. });
  2153. if (!entry)
  2154. return 0;
  2155. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  2156. if (succeeded) {
  2157. if (entry->unreachable_since) {
  2158. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  2159. entry->nickname, buf);
  2160. entry->can_retry = 0;
  2161. entry->unreachable_since = 0;
  2162. entry->last_attempted = now;
  2163. control_event_guard(entry->nickname, entry->identity, "UP");
  2164. changed = 1;
  2165. }
  2166. if (!entry->made_contact) {
  2167. entry->made_contact = 1;
  2168. first_contact = changed = 1;
  2169. }
  2170. } else { /* ! succeeded */
  2171. if (!entry->made_contact) {
  2172. /* We've never connected to this one. */
  2173. log_info(LD_CIRC,
  2174. "Connection to never-contacted entry guard '%s' (%s) failed. "
  2175. "Removing from the list. %d/%d entry guards usable/new.",
  2176. entry->nickname, buf,
  2177. num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
  2178. entry_guard_free(entry);
  2179. smartlist_del_keeporder(entry_guards, idx);
  2180. log_entry_guards(LOG_INFO);
  2181. changed = 1;
  2182. } else if (!entry->unreachable_since) {
  2183. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  2184. "Marking as unreachable.", entry->nickname, buf);
  2185. entry->unreachable_since = entry->last_attempted = now;
  2186. control_event_guard(entry->nickname, entry->identity, "DOWN");
  2187. changed = 1;
  2188. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2189. } else {
  2190. char tbuf[ISO_TIME_LEN+1];
  2191. format_iso_time(tbuf, entry->unreachable_since);
  2192. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  2193. "'%s' (%s). It has been unreachable since %s.",
  2194. entry->nickname, buf, tbuf);
  2195. entry->last_attempted = now;
  2196. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2197. }
  2198. }
  2199. /* if the caller asked us to, also update the is_running flags for this
  2200. * relay */
  2201. if (mark_relay_status)
  2202. router_set_status(digest, succeeded);
  2203. if (first_contact) {
  2204. /* We've just added a new long-term entry guard. Perhaps the network just
  2205. * came back? We should give our earlier entries another try too,
  2206. * and close this connection so we don't use it before we've given
  2207. * the others a shot. */
  2208. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  2209. if (e == entry)
  2210. break;
  2211. if (e->made_contact) {
  2212. routerinfo_t *r = entry_is_live(e, 0, 1, 1);
  2213. if (r && e->unreachable_since) {
  2214. refuse_conn = 1;
  2215. e->can_retry = 1;
  2216. }
  2217. }
  2218. });
  2219. if (refuse_conn) {
  2220. log_info(LD_CIRC,
  2221. "Connected to new entry guard '%s' (%s). Marking earlier "
  2222. "entry guards up. %d/%d entry guards usable/new.",
  2223. entry->nickname, buf,
  2224. num_live_entry_guards(), smartlist_len(entry_guards));
  2225. log_entry_guards(LOG_INFO);
  2226. changed = 1;
  2227. }
  2228. }
  2229. if (changed)
  2230. entry_guards_changed();
  2231. return refuse_conn ? -1 : 0;
  2232. }
  2233. /** When we try to choose an entry guard, should we parse and add
  2234. * config's EntryNodes first? */
  2235. static int should_add_entry_nodes = 0;
  2236. /** Called when the value of EntryNodes changes in our configuration. */
  2237. void
  2238. entry_nodes_should_be_added(void)
  2239. {
  2240. log_info(LD_CIRC, "New EntryNodes config option detected. Will use.");
  2241. should_add_entry_nodes = 1;
  2242. }
  2243. /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
  2244. * of guard nodes, at the front. */
  2245. static void
  2246. entry_guards_prepend_from_config(void)
  2247. {
  2248. or_options_t *options = get_options();
  2249. smartlist_t *entry_routers, *entry_fps;
  2250. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  2251. tor_assert(entry_guards);
  2252. should_add_entry_nodes = 0;
  2253. if (!options->EntryNodes) {
  2254. /* It's possible that a controller set EntryNodes, thus making
  2255. * should_add_entry_nodes set, then cleared it again, all before the
  2256. * call to choose_random_entry() that triggered us. If so, just return.
  2257. */
  2258. return;
  2259. }
  2260. if (options->EntryNodes) {
  2261. char *string = routerset_to_string(options->EntryNodes);
  2262. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
  2263. tor_free(string);
  2264. }
  2265. entry_routers = smartlist_create();
  2266. entry_fps = smartlist_create();
  2267. old_entry_guards_on_list = smartlist_create();
  2268. old_entry_guards_not_on_list = smartlist_create();
  2269. /* Split entry guards into those on the list and those not. */
  2270. /* XXXX022 Now that we allow countries and IP ranges in EntryNodes, this is
  2271. * potentially an enormous list. For now, we disable such values for
  2272. * EntryNodes in options_validate(); really, this wants a better solution.
  2273. * Perhaps we should do this calculation once whenever the list of routers
  2274. * changes or the entrynodes setting changes.
  2275. */
  2276. routerset_get_all_routers(entry_routers, options->EntryNodes, 0);
  2277. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri,
  2278. smartlist_add(entry_fps,ri->cache_info.identity_digest));
  2279. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  2280. if (smartlist_digest_isin(entry_fps, e->identity))
  2281. smartlist_add(old_entry_guards_on_list, e);
  2282. else
  2283. smartlist_add(old_entry_guards_not_on_list, e);
  2284. });
  2285. /* Remove all currently configured entry guards from entry_routers. */
  2286. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  2287. if (is_an_entry_guard(ri->cache_info.identity_digest)) {
  2288. SMARTLIST_DEL_CURRENT(entry_routers, ri);
  2289. }
  2290. });
  2291. /* Now build the new entry_guards list. */
  2292. smartlist_clear(entry_guards);
  2293. /* First, the previously configured guards that are in EntryNodes. */
  2294. smartlist_add_all(entry_guards, old_entry_guards_on_list);
  2295. /* Next, the rest of EntryNodes */
  2296. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  2297. add_an_entry_guard(ri, 0);
  2298. });
  2299. /* Finally, the remaining EntryNodes, unless we're strict */
  2300. if (options->StrictEntryNodes) {
  2301. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  2302. entry_guard_free(e));
  2303. } else {
  2304. smartlist_add_all(entry_guards, old_entry_guards_not_on_list);
  2305. }
  2306. smartlist_free(entry_routers);
  2307. smartlist_free(entry_fps);
  2308. smartlist_free(old_entry_guards_on_list);
  2309. smartlist_free(old_entry_guards_not_on_list);
  2310. entry_guards_changed();
  2311. }
  2312. /** Return 1 if we're fine adding arbitrary routers out of the
  2313. * directory to our entry guard list. Else return 0. */
  2314. int
  2315. entry_list_can_grow(or_options_t *options)
  2316. {
  2317. if (options->StrictEntryNodes)
  2318. return 0;
  2319. if (options->UseBridges)
  2320. return 0;
  2321. return 1;
  2322. }
  2323. /** Pick a live (up and listed) entry guard from entry_guards. If
  2324. * <b>state</b> is non-NULL, this is for a specific circuit --
  2325. * make sure not to pick this circuit's exit or any node in the
  2326. * exit's family. If <b>state</b> is NULL, we're looking for a random
  2327. * guard (likely a bridge). */
  2328. routerinfo_t *
  2329. choose_random_entry(cpath_build_state_t *state)
  2330. {
  2331. or_options_t *options = get_options();
  2332. smartlist_t *live_entry_guards = smartlist_create();
  2333. smartlist_t *exit_family = smartlist_create();
  2334. routerinfo_t *chosen_exit = state?build_state_get_exit_router(state) : NULL;
  2335. routerinfo_t *r = NULL;
  2336. int need_uptime = state ? state->need_uptime : 0;
  2337. int need_capacity = state ? state->need_capacity : 0;
  2338. int consider_exit_family = 0;
  2339. if (chosen_exit) {
  2340. smartlist_add(exit_family, chosen_exit);
  2341. routerlist_add_family(exit_family, chosen_exit);
  2342. consider_exit_family = 1;
  2343. }
  2344. if (!entry_guards)
  2345. entry_guards = smartlist_create();
  2346. if (should_add_entry_nodes)
  2347. entry_guards_prepend_from_config();
  2348. if (entry_list_can_grow(options) &&
  2349. (! entry_guards ||
  2350. smartlist_len(entry_guards) < options->NumEntryGuards))
  2351. pick_entry_guards();
  2352. retry:
  2353. smartlist_clear(live_entry_guards);
  2354. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2355. {
  2356. r = entry_is_live(entry, need_uptime, need_capacity, 0);
  2357. if (r && (!consider_exit_family || !smartlist_isin(exit_family, r))) {
  2358. smartlist_add(live_entry_guards, r);
  2359. if (!entry->made_contact) {
  2360. /* Always start with the first not-yet-contacted entry
  2361. * guard. Otherwise we might add several new ones, pick
  2362. * the second new one, and now we've expanded our entry
  2363. * guard list without needing to. */
  2364. goto choose_and_finish;
  2365. }
  2366. if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
  2367. break; /* we have enough */
  2368. }
  2369. });
  2370. /* Try to have at least 2 choices available. This way we don't
  2371. * get stuck with a single live-but-crummy entry and just keep
  2372. * using him.
  2373. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  2374. if (smartlist_len(live_entry_guards) < 2) {
  2375. if (entry_list_can_grow(options)) {
  2376. /* still no? try adding a new entry then */
  2377. /* XXX if guard doesn't imply fast and stable, then we need
  2378. * to tell add_an_entry_guard below what we want, or it might
  2379. * be a long time til we get it. -RD */
  2380. r = add_an_entry_guard(NULL, 0);
  2381. if (r) {
  2382. entry_guards_changed();
  2383. /* XXX we start over here in case the new node we added shares
  2384. * a family with our exit node. There's a chance that we'll just
  2385. * load up on entry guards here, if the network we're using is
  2386. * one big family. Perhaps we should teach add_an_entry_guard()
  2387. * to understand nodes-to-avoid-if-possible? -RD */
  2388. goto retry;
  2389. }
  2390. }
  2391. if (!r && need_uptime) {
  2392. need_uptime = 0; /* try without that requirement */
  2393. goto retry;
  2394. }
  2395. if (!r && need_capacity) {
  2396. /* still no? last attempt, try without requiring capacity */
  2397. need_capacity = 0;
  2398. goto retry;
  2399. }
  2400. if (!r && !entry_list_can_grow(options) && consider_exit_family) {
  2401. /* still no? if we're using bridges or have strictentrynodes
  2402. * set, and our chosen exit is in the same family as all our
  2403. * bridges/entry guards, then be flexible about families. */
  2404. consider_exit_family = 0;
  2405. goto retry;
  2406. }
  2407. /* live_entry_guards may be empty below. Oh well, we tried. */
  2408. }
  2409. choose_and_finish:
  2410. if (entry_list_can_grow(options)) {
  2411. /* We choose uniformly at random here, because choose_good_entry_server()
  2412. * already weights its choices by bandwidth, so we don't want to
  2413. * *double*-weight our guard selection. */
  2414. r = smartlist_choose(live_entry_guards);
  2415. } else {
  2416. /* We need to weight by bandwidth, because our bridges or entryguards
  2417. * were not already selected proportional to their bandwidth. */
  2418. r = routerlist_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
  2419. }
  2420. smartlist_free(live_entry_guards);
  2421. smartlist_free(exit_family);
  2422. return r;
  2423. }
  2424. /** Parse <b>state</b> and learn about the entry guards it describes.
  2425. * If <b>set</b> is true, and there are no errors, replace the global
  2426. * entry_list with what we find.
  2427. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  2428. * describing the error, and return -1.
  2429. */
  2430. int
  2431. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  2432. {
  2433. entry_guard_t *node = NULL;
  2434. smartlist_t *new_entry_guards = smartlist_create();
  2435. config_line_t *line;
  2436. time_t now = time(NULL);
  2437. const char *state_version = state->TorVersion;
  2438. digestmap_t *added_by = digestmap_new();
  2439. *msg = NULL;
  2440. for (line = state->EntryGuards; line; line = line->next) {
  2441. if (!strcasecmp(line->key, "EntryGuard")) {
  2442. smartlist_t *args = smartlist_create();
  2443. node = tor_malloc_zero(sizeof(entry_guard_t));
  2444. /* all entry guards on disk have been contacted */
  2445. node->made_contact = 1;
  2446. smartlist_add(new_entry_guards, node);
  2447. smartlist_split_string(args, line->value, " ",
  2448. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2449. if (smartlist_len(args)<2) {
  2450. *msg = tor_strdup("Unable to parse entry nodes: "
  2451. "Too few arguments to EntryGuard");
  2452. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  2453. *msg = tor_strdup("Unable to parse entry nodes: "
  2454. "Bad nickname for EntryGuard");
  2455. } else {
  2456. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  2457. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  2458. strlen(smartlist_get(args,1)))<0) {
  2459. *msg = tor_strdup("Unable to parse entry nodes: "
  2460. "Bad hex digest for EntryGuard");
  2461. }
  2462. }
  2463. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  2464. smartlist_free(args);
  2465. if (*msg)
  2466. break;
  2467. } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
  2468. !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
  2469. time_t when;
  2470. time_t last_try = 0;
  2471. if (!node) {
  2472. *msg = tor_strdup("Unable to parse entry nodes: "
  2473. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  2474. break;
  2475. }
  2476. if (parse_iso_time(line->value, &when)<0) {
  2477. *msg = tor_strdup("Unable to parse entry nodes: "
  2478. "Bad time in EntryGuardDownSince/UnlistedSince");
  2479. break;
  2480. }
  2481. if (when > now) {
  2482. /* It's a bad idea to believe info in the future: you can wind
  2483. * up with timeouts that aren't allowed to happen for years. */
  2484. continue;
  2485. }
  2486. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  2487. /* ignore failure */
  2488. (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  2489. }
  2490. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  2491. node->unreachable_since = when;
  2492. node->last_attempted = last_try;
  2493. } else {
  2494. node->bad_since = when;
  2495. }
  2496. } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
  2497. char d[DIGEST_LEN];
  2498. /* format is digest version date */
  2499. if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
  2500. log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
  2501. continue;
  2502. }
  2503. if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
  2504. line->value[HEX_DIGEST_LEN] != ' ') {
  2505. log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
  2506. "hex digest", escaped(line->value));
  2507. continue;
  2508. }
  2509. digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
  2510. } else {
  2511. log_warn(LD_BUG, "Unexpected key %s", line->key);
  2512. }
  2513. }
  2514. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  2515. {
  2516. char *sp;
  2517. char *val = digestmap_get(added_by, e->identity);
  2518. if (val && (sp = strchr(val, ' '))) {
  2519. time_t when;
  2520. *sp++ = '\0';
  2521. if (parse_iso_time(sp, &when)<0) {
  2522. log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
  2523. } else {
  2524. e->chosen_by_version = tor_strdup(val);
  2525. e->chosen_on_date = when;
  2526. }
  2527. } else {
  2528. if (state_version) {
  2529. e->chosen_by_version = tor_strdup(state_version);
  2530. e->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
  2531. }
  2532. }
  2533. });
  2534. if (*msg || !set) {
  2535. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  2536. entry_guard_free(e));
  2537. smartlist_free(new_entry_guards);
  2538. } else { /* !err && set */
  2539. if (entry_guards) {
  2540. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2541. entry_guard_free(e));
  2542. smartlist_free(entry_guards);
  2543. }
  2544. entry_guards = new_entry_guards;
  2545. entry_guards_dirty = 0;
  2546. /* XXX022 hand new_entry_guards to this func, and move it up a
  2547. * few lines, so we don't have to re-dirty it */
  2548. if (remove_obsolete_entry_guards())
  2549. entry_guards_dirty = 1;
  2550. }
  2551. digestmap_free(added_by, _tor_free);
  2552. return *msg ? -1 : 0;
  2553. }
  2554. /** Our list of entry guards has changed, or some element of one
  2555. * of our entry guards has changed. Write the changes to disk within
  2556. * the next few minutes.
  2557. */
  2558. static void
  2559. entry_guards_changed(void)
  2560. {
  2561. time_t when;
  2562. entry_guards_dirty = 1;
  2563. /* or_state_save() will call entry_guards_update_state(). */
  2564. when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
  2565. or_state_mark_dirty(get_or_state(), when);
  2566. }
  2567. /** If the entry guard info has not changed, do nothing and return.
  2568. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  2569. * a new one out of the global entry_guards list, and then mark
  2570. * <b>state</b> dirty so it will get saved to disk.
  2571. */
  2572. void
  2573. entry_guards_update_state(or_state_t *state)
  2574. {
  2575. config_line_t **next, *line;
  2576. if (! entry_guards_dirty)
  2577. return;
  2578. config_free_lines(state->EntryGuards);
  2579. next = &state->EntryGuards;
  2580. *next = NULL;
  2581. if (!entry_guards)
  2582. entry_guards = smartlist_create();
  2583. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2584. {
  2585. char dbuf[HEX_DIGEST_LEN+1];
  2586. if (!e->made_contact)
  2587. continue; /* don't write this one to disk */
  2588. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2589. line->key = tor_strdup("EntryGuard");
  2590. line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
  2591. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  2592. tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
  2593. "%s %s", e->nickname, dbuf);
  2594. next = &(line->next);
  2595. if (e->unreachable_since) {
  2596. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2597. line->key = tor_strdup("EntryGuardDownSince");
  2598. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  2599. format_iso_time(line->value, e->unreachable_since);
  2600. if (e->last_attempted) {
  2601. line->value[ISO_TIME_LEN] = ' ';
  2602. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  2603. }
  2604. next = &(line->next);
  2605. }
  2606. if (e->bad_since) {
  2607. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2608. line->key = tor_strdup("EntryGuardUnlistedSince");
  2609. line->value = tor_malloc(ISO_TIME_LEN+1);
  2610. format_iso_time(line->value, e->bad_since);
  2611. next = &(line->next);
  2612. }
  2613. if (e->chosen_on_date && e->chosen_by_version &&
  2614. !strchr(e->chosen_by_version, ' ')) {
  2615. char d[HEX_DIGEST_LEN+1];
  2616. char t[ISO_TIME_LEN+1];
  2617. size_t val_len;
  2618. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2619. line->key = tor_strdup("EntryGuardAddedBy");
  2620. val_len = (HEX_DIGEST_LEN+1+strlen(e->chosen_by_version)
  2621. +1+ISO_TIME_LEN+1);
  2622. line->value = tor_malloc(val_len);
  2623. base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
  2624. format_iso_time(t, e->chosen_on_date);
  2625. tor_snprintf(line->value, val_len, "%s %s %s",
  2626. d, e->chosen_by_version, t);
  2627. next = &(line->next);
  2628. }
  2629. });
  2630. if (!get_options()->AvoidDiskWrites)
  2631. or_state_mark_dirty(get_or_state(), 0);
  2632. entry_guards_dirty = 0;
  2633. }
  2634. /** If <b>question</b> is the string "entry-guards", then dump
  2635. * to *<b>answer</b> a newly allocated string describing all of
  2636. * the nodes in the global entry_guards list. See control-spec.txt
  2637. * for details.
  2638. * For backward compatibility, we also handle the string "helper-nodes".
  2639. * */
  2640. int
  2641. getinfo_helper_entry_guards(control_connection_t *conn,
  2642. const char *question, char **answer)
  2643. {
  2644. int use_long_names = conn->use_long_names;
  2645. if (!strcmp(question,"entry-guards") ||
  2646. !strcmp(question,"helper-nodes")) {
  2647. smartlist_t *sl = smartlist_create();
  2648. char tbuf[ISO_TIME_LEN+1];
  2649. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  2650. if (!entry_guards)
  2651. entry_guards = smartlist_create();
  2652. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2653. {
  2654. size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
  2655. char *c = tor_malloc(len);
  2656. const char *status = NULL;
  2657. time_t when = 0;
  2658. if (!e->made_contact) {
  2659. status = "never-connected";
  2660. } else if (e->bad_since) {
  2661. when = e->bad_since;
  2662. status = "unusable";
  2663. } else {
  2664. status = "up";
  2665. }
  2666. if (use_long_names) {
  2667. routerinfo_t *ri = router_get_by_digest(e->identity);
  2668. if (ri) {
  2669. router_get_verbose_nickname(nbuf, ri);
  2670. } else {
  2671. nbuf[0] = '$';
  2672. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  2673. /* e->nickname field is not very reliable if we don't know about
  2674. * this router any longer; don't include it. */
  2675. }
  2676. } else {
  2677. base16_encode(nbuf, sizeof(nbuf), e->identity, DIGEST_LEN);
  2678. }
  2679. if (when) {
  2680. format_iso_time(tbuf, when);
  2681. tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
  2682. } else {
  2683. tor_snprintf(c, len, "%s %s\n", nbuf, status);
  2684. }
  2685. smartlist_add(sl, c);
  2686. });
  2687. *answer = smartlist_join_strings(sl, "", 0, NULL);
  2688. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  2689. smartlist_free(sl);
  2690. }
  2691. return 0;
  2692. }
  2693. /** Information about a configured bridge. Currently this just matches the
  2694. * ones in the torrc file, but one day we may be able to learn about new
  2695. * bridges on our own, and remember them in the state file. */
  2696. typedef struct {
  2697. /** Address of the bridge. */
  2698. tor_addr_t addr;
  2699. /** TLS port for the bridge. */
  2700. uint16_t port;
  2701. /** Expected identity digest, or all zero bytes if we don't know what the
  2702. * digest should be. */
  2703. char identity[DIGEST_LEN];
  2704. /** When should we next try to fetch a descriptor for this bridge? */
  2705. download_status_t fetch_status;
  2706. } bridge_info_t;
  2707. /** A list of configured bridges. Whenever we actually get a descriptor
  2708. * for one, we add it as an entry guard. */
  2709. static smartlist_t *bridge_list = NULL;
  2710. /** Initialize the bridge list to empty, creating it if needed. */
  2711. void
  2712. clear_bridge_list(void)
  2713. {
  2714. if (!bridge_list)
  2715. bridge_list = smartlist_create();
  2716. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, tor_free(b));
  2717. smartlist_clear(bridge_list);
  2718. }
  2719. /** Return a bridge pointer if <b>ri</b> is one of our known bridges
  2720. * (either by comparing keys if possible, else by comparing addr/port).
  2721. * Else return NULL. */
  2722. static bridge_info_t *
  2723. routerinfo_get_configured_bridge(routerinfo_t *ri)
  2724. {
  2725. if (!bridge_list)
  2726. return NULL;
  2727. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  2728. {
  2729. if (tor_digest_is_zero(bridge->identity) &&
  2730. tor_addr_eq_ipv4h(&bridge->addr, ri->addr) &&
  2731. bridge->port == ri->or_port)
  2732. return bridge;
  2733. if (!memcmp(bridge->identity, ri->cache_info.identity_digest,
  2734. DIGEST_LEN))
  2735. return bridge;
  2736. }
  2737. SMARTLIST_FOREACH_END(bridge);
  2738. return NULL;
  2739. }
  2740. /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
  2741. int
  2742. routerinfo_is_a_configured_bridge(routerinfo_t *ri)
  2743. {
  2744. return routerinfo_get_configured_bridge(ri) ? 1 : 0;
  2745. }
  2746. /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
  2747. * is set, it tells us the identity key too. */
  2748. void
  2749. bridge_add_from_config(const tor_addr_t *addr, uint16_t port, char *digest)
  2750. {
  2751. bridge_info_t *b = tor_malloc_zero(sizeof(bridge_info_t));
  2752. tor_addr_copy(&b->addr, addr);
  2753. b->port = port;
  2754. if (digest)
  2755. memcpy(b->identity, digest, DIGEST_LEN);
  2756. b->fetch_status.schedule = DL_SCHED_BRIDGE;
  2757. if (!bridge_list)
  2758. bridge_list = smartlist_create();
  2759. smartlist_add(bridge_list, b);
  2760. }
  2761. /** If <b>digest</b> is one of our known bridges, return it. */
  2762. static bridge_info_t *
  2763. find_bridge_by_digest(const char *digest)
  2764. {
  2765. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  2766. {
  2767. if (!memcmp(bridge->identity, digest, DIGEST_LEN))
  2768. return bridge;
  2769. });
  2770. return NULL;
  2771. }
  2772. /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
  2773. * is a helpful string describing this bridge. */
  2774. static void
  2775. launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
  2776. {
  2777. char *address;
  2778. if (connection_get_by_type_addr_port_purpose(
  2779. CONN_TYPE_DIR, &bridge->addr, bridge->port,
  2780. DIR_PURPOSE_FETCH_SERVERDESC))
  2781. return; /* it's already on the way */
  2782. address = tor_dup_addr(&bridge->addr);
  2783. directory_initiate_command(address, &bridge->addr,
  2784. bridge->port, 0,
  2785. 0, /* does not matter */
  2786. 1, bridge->identity,
  2787. DIR_PURPOSE_FETCH_SERVERDESC,
  2788. ROUTER_PURPOSE_BRIDGE,
  2789. 0, "authority.z", NULL, 0, 0);
  2790. tor_free(address);
  2791. }
  2792. /** Fetching the bridge descriptor from the bridge authority returned a
  2793. * "not found". Fall back to trying a direct fetch. */
  2794. void
  2795. retry_bridge_descriptor_fetch_directly(const char *digest)
  2796. {
  2797. bridge_info_t *bridge = find_bridge_by_digest(digest);
  2798. if (!bridge)
  2799. return; /* not found? oh well. */
  2800. launch_direct_bridge_descriptor_fetch(bridge);
  2801. }
  2802. /** For each bridge in our list for which we don't currently have a
  2803. * descriptor, fetch a new copy of its descriptor -- either directly
  2804. * from the bridge or via a bridge authority. */
  2805. void
  2806. fetch_bridge_descriptors(time_t now)
  2807. {
  2808. or_options_t *options = get_options();
  2809. int num_bridge_auths = get_n_authorities(BRIDGE_AUTHORITY);
  2810. int ask_bridge_directly;
  2811. int can_use_bridge_authority;
  2812. if (!bridge_list)
  2813. return;
  2814. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  2815. {
  2816. if (!download_status_is_ready(&bridge->fetch_status, now,
  2817. IMPOSSIBLE_TO_DOWNLOAD))
  2818. continue; /* don't bother, no need to retry yet */
  2819. /* schedule another fetch as if this one will fail, in case it does */
  2820. download_status_failed(&bridge->fetch_status, 0);
  2821. can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
  2822. num_bridge_auths;
  2823. ask_bridge_directly = !can_use_bridge_authority ||
  2824. !options->UpdateBridgesFromAuthority;
  2825. log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
  2826. ask_bridge_directly, tor_digest_is_zero(bridge->identity),
  2827. !options->UpdateBridgesFromAuthority, !num_bridge_auths);
  2828. if (ask_bridge_directly &&
  2829. !fascist_firewall_allows_address_or(&bridge->addr, bridge->port)) {
  2830. log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
  2831. "firewall policy. %s.", fmt_addr(&bridge->addr),
  2832. bridge->port,
  2833. can_use_bridge_authority ?
  2834. "Asking bridge authority instead" : "Skipping");
  2835. if (can_use_bridge_authority)
  2836. ask_bridge_directly = 0;
  2837. else
  2838. continue;
  2839. }
  2840. if (ask_bridge_directly) {
  2841. /* we need to ask the bridge itself for its descriptor. */
  2842. launch_direct_bridge_descriptor_fetch(bridge);
  2843. } else {
  2844. /* We have a digest and we want to ask an authority. We could
  2845. * combine all the requests into one, but that may give more
  2846. * hints to the bridge authority than we want to give. */
  2847. char resource[10 + HEX_DIGEST_LEN];
  2848. memcpy(resource, "fp/", 3);
  2849. base16_encode(resource+3, HEX_DIGEST_LEN+1,
  2850. bridge->identity, DIGEST_LEN);
  2851. memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
  2852. log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
  2853. resource);
  2854. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  2855. ROUTER_PURPOSE_BRIDGE, resource, 0);
  2856. }
  2857. }
  2858. SMARTLIST_FOREACH_END(bridge);
  2859. }
  2860. /** We just learned a descriptor for a bridge. See if that
  2861. * digest is in our entry guard list, and add it if not. */
  2862. void
  2863. learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
  2864. {
  2865. tor_assert(ri);
  2866. tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
  2867. if (get_options()->UseBridges) {
  2868. int first = !any_bridge_descriptors_known();
  2869. bridge_info_t *bridge = routerinfo_get_configured_bridge(ri);
  2870. time_t now = time(NULL);
  2871. ri->is_running = 1;
  2872. if (bridge) { /* if we actually want to use this one */
  2873. /* it's here; schedule its re-fetch for a long time from now. */
  2874. if (!from_cache)
  2875. download_status_reset(&bridge->fetch_status);
  2876. add_an_entry_guard(ri, 1);
  2877. log_notice(LD_DIR, "new bridge descriptor '%s' (%s)", ri->nickname,
  2878. from_cache ? "cached" : "fresh");
  2879. if (first)
  2880. routerlist_retry_directory_downloads(now);
  2881. }
  2882. }
  2883. }
  2884. /** Return 1 if any of our entry guards have descriptors that
  2885. * are marked with purpose 'bridge' and are running. Else return 0.
  2886. *
  2887. * We use this function to decide if we're ready to start building
  2888. * circuits through our bridges, or if we need to wait until the
  2889. * directory "server/authority" requests finish. */
  2890. int
  2891. any_bridge_descriptors_known(void)
  2892. {
  2893. tor_assert(get_options()->UseBridges);
  2894. return choose_random_entry(NULL)!=NULL ? 1 : 0;
  2895. }
  2896. /** Return 1 if there are any directory conns fetching bridge descriptors
  2897. * that aren't marked for close. We use this to guess if we should tell
  2898. * the controller that we have a problem. */
  2899. int
  2900. any_pending_bridge_descriptor_fetches(void)
  2901. {
  2902. smartlist_t *conns = get_connection_array();
  2903. SMARTLIST_FOREACH(conns, connection_t *, conn,
  2904. {
  2905. if (conn->type == CONN_TYPE_DIR &&
  2906. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  2907. TO_DIR_CONN(conn)->router_purpose == ROUTER_PURPOSE_BRIDGE &&
  2908. !conn->marked_for_close &&
  2909. conn->linked && !conn->linked_conn->marked_for_close) {
  2910. log_debug(LD_DIR, "found one: %s", conn->address);
  2911. return 1;
  2912. }
  2913. });
  2914. return 0;
  2915. }
  2916. /** Return 1 if we have at least one descriptor for a bridge and
  2917. * all descriptors we know are down. Else return 0. If <b>act</b> is
  2918. * 1, then mark the down bridges up; else just observe and report. */
  2919. static int
  2920. bridges_retry_helper(int act)
  2921. {
  2922. routerinfo_t *ri;
  2923. int any_known = 0;
  2924. int any_running = 0;
  2925. if (!entry_guards)
  2926. entry_guards = smartlist_create();
  2927. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2928. {
  2929. ri = router_get_by_digest(e->identity);
  2930. if (ri && ri->purpose == ROUTER_PURPOSE_BRIDGE) {
  2931. any_known = 1;
  2932. if (ri->is_running)
  2933. any_running = 1; /* some bridge is both known and running */
  2934. else if (act) { /* mark it for retry */
  2935. ri->is_running = 1;
  2936. e->can_retry = 1;
  2937. e->bad_since = 0;
  2938. }
  2939. }
  2940. });
  2941. log_debug(LD_DIR, "any_known %d, any_running %d", any_known, any_running);
  2942. return any_known && !any_running;
  2943. }
  2944. /** Do we know any descriptors for our bridges, and are they all
  2945. * down? */
  2946. int
  2947. bridges_known_but_down(void)
  2948. {
  2949. return bridges_retry_helper(0);
  2950. }
  2951. /** Mark all down known bridges up. */
  2952. void
  2953. bridges_retry_all(void)
  2954. {
  2955. bridges_retry_helper(1);
  2956. }
  2957. /** Release all storage held by the list of entry guards and related
  2958. * memory structs. */
  2959. void
  2960. entry_guards_free_all(void)
  2961. {
  2962. if (entry_guards) {
  2963. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2964. entry_guard_free(e));
  2965. smartlist_free(entry_guards);
  2966. entry_guards = NULL;
  2967. }
  2968. clear_bridge_list();
  2969. smartlist_free(bridge_list);
  2970. bridge_list = NULL;
  2971. }