circuitbuild.c 137 KB

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