circuitbuild.c 127 KB

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