circuitbuild.c 127 KB

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