circuitbuild.c 131 KB

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