circuitbuild.c 120 KB

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