circuitbuild.c 138 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193
  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. (!options->ExitNodes ||
  1884. !routerset_contains_router(options->ExitNodes, router))) {
  1885. /* FFFF Someday, differentiate between a routerset that names
  1886. * routers, and a routerset that names countries, and only do this
  1887. * check if they've asked for specific exit relays. Or if the country
  1888. * they ask for is rare. Or something. */
  1889. n_supported[i] = -1;
  1890. continue; /* skip routers that are not suitable, unless we have
  1891. * ExitNodes set, in which case we asked for it */
  1892. }
  1893. if (!(router->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
  1894. /* if it's invalid and we don't want it */
  1895. n_supported[i] = -1;
  1896. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1897. // router->nickname, i);
  1898. continue; /* skip invalid routers */
  1899. }
  1900. if (options->ExcludeSingleHopRelays && router->allow_single_hop_exits) {
  1901. n_supported[i] = -1;
  1902. continue;
  1903. }
  1904. if (router_exit_policy_rejects_all(router)) {
  1905. n_supported[i] = -1;
  1906. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1907. // router->nickname, i);
  1908. continue; /* skip routers that reject all */
  1909. }
  1910. n_supported[i] = 0;
  1911. /* iterate over connections */
  1912. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1913. {
  1914. if (!ap_stream_wants_exit_attention(conn))
  1915. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1916. if (connection_ap_can_use_exit(TO_EDGE_CONN(conn), router, 1)) {
  1917. ++n_supported[i];
  1918. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1919. // router->nickname, i, n_supported[i]);
  1920. } else {
  1921. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1922. // router->nickname, i);
  1923. }
  1924. }); /* End looping over connections. */
  1925. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1926. /* Leave best_support at -1 if that's where it is, so we can
  1927. * distinguish it later. */
  1928. continue;
  1929. }
  1930. if (n_supported[i] > best_support) {
  1931. /* If this router is better than previous ones, remember its index
  1932. * and goodness, and start counting how many routers are this good. */
  1933. best_support = n_supported[i]; n_best_support=1;
  1934. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1935. // router->nickname);
  1936. } else if (n_supported[i] == best_support) {
  1937. /* If this router is _as good_ as the best one, just increment the
  1938. * count of equally good routers.*/
  1939. ++n_best_support;
  1940. }
  1941. }
  1942. log_info(LD_CIRC,
  1943. "Found %d servers that might support %d/%d pending connections.",
  1944. n_best_support, best_support >= 0 ? best_support : 0,
  1945. n_pending_connections);
  1946. /* If any routers definitely support any pending connections, choose one
  1947. * at random. */
  1948. if (best_support > 0) {
  1949. smartlist_t *supporting = smartlist_create(), *use = smartlist_create();
  1950. for (i = 0; i < smartlist_len(dir->routers); i++)
  1951. if (n_supported[i] == best_support)
  1952. smartlist_add(supporting, smartlist_get(dir->routers, i));
  1953. routersets_get_disjunction(use, supporting, options->ExitNodes,
  1954. options->_ExcludeExitNodesUnion, 1);
  1955. if (smartlist_len(use) == 0 && options->ExitNodes &&
  1956. !options->StrictNodes) { /* give up on exitnodes and try again */
  1957. routersets_get_disjunction(use, supporting, NULL,
  1958. options->_ExcludeExitNodesUnion, 1);
  1959. }
  1960. router = routerlist_sl_choose_by_bandwidth(use, WEIGHT_FOR_EXIT);
  1961. smartlist_free(use);
  1962. smartlist_free(supporting);
  1963. } else {
  1964. /* Either there are no pending connections, or no routers even seem to
  1965. * possibly support any of them. Choose a router at random that satisfies
  1966. * at least one predicted exit port. */
  1967. int try;
  1968. smartlist_t *needed_ports, *supporting, *use;
  1969. if (best_support == -1) {
  1970. if (need_uptime || need_capacity) {
  1971. log_info(LD_CIRC,
  1972. "We couldn't find any live%s%s routers; falling back "
  1973. "to list of all routers.",
  1974. need_capacity?", fast":"",
  1975. need_uptime?", stable":"");
  1976. tor_free(n_supported);
  1977. return choose_good_exit_server_general(dir, 0, 0);
  1978. }
  1979. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  1980. "choosing a doomed exit at random.",
  1981. options->_ExcludeExitNodesUnion ? " or are Excluded" : "");
  1982. }
  1983. supporting = smartlist_create();
  1984. use = smartlist_create();
  1985. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1986. for (try = 0; try < 2; try++) {
  1987. /* try once to pick only from routers that satisfy a needed port,
  1988. * then if there are none, pick from any that support exiting. */
  1989. for (i = 0; i < smartlist_len(dir->routers); i++) {
  1990. router = smartlist_get(dir->routers, i);
  1991. if (n_supported[i] != -1 &&
  1992. (try || router_handles_some_port(router, needed_ports))) {
  1993. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1994. // try, router->nickname);
  1995. smartlist_add(supporting, router);
  1996. }
  1997. }
  1998. routersets_get_disjunction(use, supporting, options->ExitNodes,
  1999. options->_ExcludeExitNodesUnion, 1);
  2000. if (smartlist_len(use) == 0 && options->ExitNodes &&
  2001. !options->StrictNodes) { /* give up on exitnodes and try again */
  2002. routersets_get_disjunction(use, supporting, NULL,
  2003. options->_ExcludeExitNodesUnion, 1);
  2004. }
  2005. /* FFF sometimes the above results in null, when the requested
  2006. * exit node is considered down by the consensus. we should pick
  2007. * it anyway, since the user asked for it. */
  2008. router = routerlist_sl_choose_by_bandwidth(use, WEIGHT_FOR_EXIT);
  2009. if (router)
  2010. break;
  2011. smartlist_clear(supporting);
  2012. smartlist_clear(use);
  2013. }
  2014. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  2015. smartlist_free(needed_ports);
  2016. smartlist_free(use);
  2017. smartlist_free(supporting);
  2018. }
  2019. tor_free(n_supported);
  2020. if (router) {
  2021. log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
  2022. return router;
  2023. }
  2024. if (options->ExitNodes && options->StrictNodes) {
  2025. log_warn(LD_CIRC,
  2026. "No specified exit routers seem to be running, and "
  2027. "StrictNodes is set: can't choose an exit.");
  2028. }
  2029. return NULL;
  2030. }
  2031. /** Return a pointer to a suitable router to be the exit node for the
  2032. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  2033. * if no router is suitable).
  2034. *
  2035. * For general-purpose circuits, pass it off to
  2036. * choose_good_exit_server_general()
  2037. *
  2038. * For client-side rendezvous circuits, choose a random node, weighted
  2039. * toward the preferences in 'options'.
  2040. */
  2041. static routerinfo_t *
  2042. choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
  2043. int need_uptime, int need_capacity, int is_internal)
  2044. {
  2045. or_options_t *options = get_options();
  2046. router_crn_flags_t flags = 0;
  2047. if (need_uptime)
  2048. flags |= CRN_NEED_UPTIME;
  2049. if (need_capacity)
  2050. flags |= CRN_NEED_CAPACITY;
  2051. switch (purpose) {
  2052. case CIRCUIT_PURPOSE_C_GENERAL:
  2053. if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
  2054. flags |= CRN_ALLOW_INVALID;
  2055. if (is_internal) /* pick it like a middle hop */
  2056. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2057. else
  2058. return choose_good_exit_server_general(dir,need_uptime,need_capacity);
  2059. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2060. if (options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS)
  2061. flags |= CRN_ALLOW_INVALID;
  2062. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2063. }
  2064. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  2065. tor_fragile_assert();
  2066. return NULL;
  2067. }
  2068. /** Log a warning if the user specified an exit for the circuit that
  2069. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  2070. static void
  2071. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  2072. {
  2073. or_options_t *options = get_options();
  2074. routerset_t *rs = options->ExcludeNodes;
  2075. const char *description;
  2076. int domain = LD_CIRC;
  2077. uint8_t purpose = circ->_base.purpose;
  2078. if (circ->build_state->onehop_tunnel)
  2079. return;
  2080. switch (purpose)
  2081. {
  2082. default:
  2083. case CIRCUIT_PURPOSE_OR:
  2084. case CIRCUIT_PURPOSE_INTRO_POINT:
  2085. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  2086. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  2087. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d)",
  2088. (int)purpose);
  2089. return;
  2090. case CIRCUIT_PURPOSE_C_GENERAL:
  2091. if (circ->build_state->is_internal)
  2092. return;
  2093. description = "Requested exit node";
  2094. rs = options->_ExcludeExitNodesUnion;
  2095. break;
  2096. case CIRCUIT_PURPOSE_C_INTRODUCING:
  2097. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  2098. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  2099. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  2100. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  2101. case CIRCUIT_PURPOSE_S_REND_JOINED:
  2102. case CIRCUIT_PURPOSE_TESTING:
  2103. return;
  2104. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2105. case CIRCUIT_PURPOSE_C_REND_READY:
  2106. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  2107. case CIRCUIT_PURPOSE_C_REND_JOINED:
  2108. description = "Chosen rendezvous point";
  2109. domain = LD_BUG;
  2110. break;
  2111. case CIRCUIT_PURPOSE_CONTROLLER:
  2112. rs = options->_ExcludeExitNodesUnion;
  2113. description = "Controller-selected circuit target";
  2114. break;
  2115. }
  2116. if (routerset_contains_extendinfo(rs, exit)) {
  2117. log_fn(LOG_WARN, domain, "%s '%s' is in ExcludeNodes%s. Using anyway "
  2118. "(circuit purpose %d).",
  2119. description,exit->nickname,
  2120. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2121. (int)purpose);
  2122. circuit_log_path(LOG_WARN, domain, circ);
  2123. }
  2124. return;
  2125. }
  2126. /** Decide a suitable length for circ's cpath, and pick an exit
  2127. * router (or use <b>exit</b> if provided). Store these in the
  2128. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  2129. static int
  2130. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  2131. {
  2132. cpath_build_state_t *state = circ->build_state;
  2133. routerlist_t *rl = router_get_routerlist();
  2134. if (state->onehop_tunnel) {
  2135. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  2136. state->desired_path_len = 1;
  2137. } else {
  2138. int r = new_route_len(circ->_base.purpose, exit, rl->routers);
  2139. if (r < 1) /* must be at least 1 */
  2140. return -1;
  2141. state->desired_path_len = r;
  2142. }
  2143. if (exit) { /* the circuit-builder pre-requested one */
  2144. warn_if_last_router_excluded(circ, exit);
  2145. log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
  2146. exit = extend_info_dup(exit);
  2147. } else { /* we have to decide one */
  2148. routerinfo_t *router =
  2149. choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
  2150. state->need_capacity, state->is_internal);
  2151. if (!router) {
  2152. log_warn(LD_CIRC,"failed to choose an exit server");
  2153. return -1;
  2154. }
  2155. exit = extend_info_from_router(router);
  2156. }
  2157. state->chosen_exit = exit;
  2158. return 0;
  2159. }
  2160. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  2161. * hop to the cpath reflecting this. Don't send the next extend cell --
  2162. * the caller will do this if it wants to.
  2163. */
  2164. int
  2165. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2166. {
  2167. cpath_build_state_t *state;
  2168. tor_assert(exit);
  2169. tor_assert(circ);
  2170. state = circ->build_state;
  2171. tor_assert(state);
  2172. extend_info_free(state->chosen_exit);
  2173. state->chosen_exit = extend_info_dup(exit);
  2174. ++circ->build_state->desired_path_len;
  2175. onion_append_hop(&circ->cpath, exit);
  2176. return 0;
  2177. }
  2178. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  2179. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  2180. * send the next extend cell to begin connecting to that hop.
  2181. */
  2182. int
  2183. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2184. {
  2185. int err_reason = 0;
  2186. warn_if_last_router_excluded(circ, exit);
  2187. circuit_append_new_exit(circ, exit);
  2188. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2189. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  2190. log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
  2191. exit->nickname);
  2192. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2193. return -1;
  2194. }
  2195. return 0;
  2196. }
  2197. /** Return the number of routers in <b>routers</b> that are currently up
  2198. * and available for building circuits through.
  2199. */
  2200. static int
  2201. count_acceptable_routers(smartlist_t *routers)
  2202. {
  2203. int i, n;
  2204. int num=0;
  2205. routerinfo_t *r;
  2206. n = smartlist_len(routers);
  2207. for (i=0;i<n;i++) {
  2208. r = smartlist_get(routers, i);
  2209. // log_debug(LD_CIRC,
  2210. // "Contemplating whether router %d (%s) is a new option.",
  2211. // i, r->nickname);
  2212. if (r->is_running == 0) {
  2213. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  2214. goto next_i_loop;
  2215. }
  2216. if (r->is_valid == 0) {
  2217. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  2218. goto next_i_loop;
  2219. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  2220. * allows this node in some places, then we're getting an inaccurate
  2221. * count. For now, be conservative and don't count it. But later we
  2222. * should try to be smarter. */
  2223. }
  2224. num++;
  2225. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  2226. next_i_loop:
  2227. ; /* C requires an explicit statement after the label */
  2228. }
  2229. return num;
  2230. }
  2231. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  2232. * This function is used to extend cpath by another hop.
  2233. */
  2234. void
  2235. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  2236. {
  2237. if (*head_ptr) {
  2238. new_hop->next = (*head_ptr);
  2239. new_hop->prev = (*head_ptr)->prev;
  2240. (*head_ptr)->prev->next = new_hop;
  2241. (*head_ptr)->prev = new_hop;
  2242. } else {
  2243. *head_ptr = new_hop;
  2244. new_hop->prev = new_hop->next = new_hop;
  2245. }
  2246. }
  2247. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  2248. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  2249. * to length <b>cur_len</b> to decide a suitable middle hop for a
  2250. * circuit. In particular, make sure we don't pick the exit node or its
  2251. * family, and make sure we don't duplicate any previous nodes or their
  2252. * families. */
  2253. static routerinfo_t *
  2254. choose_good_middle_server(uint8_t purpose,
  2255. cpath_build_state_t *state,
  2256. crypt_path_t *head,
  2257. int cur_len)
  2258. {
  2259. int i;
  2260. routerinfo_t *r, *choice;
  2261. crypt_path_t *cpath;
  2262. smartlist_t *excluded;
  2263. or_options_t *options = get_options();
  2264. router_crn_flags_t flags = 0;
  2265. tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
  2266. purpose <= _CIRCUIT_PURPOSE_MAX);
  2267. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  2268. excluded = smartlist_create();
  2269. if ((r = build_state_get_exit_router(state))) {
  2270. smartlist_add(excluded, r);
  2271. routerlist_add_family(excluded, r);
  2272. }
  2273. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  2274. if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
  2275. smartlist_add(excluded, r);
  2276. routerlist_add_family(excluded, r);
  2277. }
  2278. }
  2279. if (state->need_uptime)
  2280. flags |= CRN_NEED_UPTIME;
  2281. if (state->need_capacity)
  2282. flags |= CRN_NEED_CAPACITY;
  2283. if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
  2284. flags |= CRN_ALLOW_INVALID;
  2285. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2286. smartlist_free(excluded);
  2287. return choice;
  2288. }
  2289. /** Pick a good entry server for the circuit to be built according to
  2290. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  2291. * router (if we're an OR), and respect firewall settings; if we're
  2292. * configured to use entry guards, return one.
  2293. *
  2294. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  2295. * guard, not for any particular circuit.
  2296. */
  2297. static routerinfo_t *
  2298. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  2299. {
  2300. routerinfo_t *r, *choice;
  2301. smartlist_t *excluded;
  2302. or_options_t *options = get_options();
  2303. router_crn_flags_t flags = 0;
  2304. if (state && options->UseEntryGuards &&
  2305. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  2306. return choose_random_entry(state);
  2307. }
  2308. excluded = smartlist_create();
  2309. if (state && (r = build_state_get_exit_router(state))) {
  2310. smartlist_add(excluded, r);
  2311. routerlist_add_family(excluded, r);
  2312. }
  2313. if (firewall_is_fascist_or()) {
  2314. /*XXXX This could slow things down a lot; use a smarter implementation */
  2315. /* exclude all ORs that listen on the wrong port, if anybody notices. */
  2316. routerlist_t *rl = router_get_routerlist();
  2317. int i;
  2318. for (i=0; i < smartlist_len(rl->routers); i++) {
  2319. r = smartlist_get(rl->routers, i);
  2320. if (!fascist_firewall_allows_or(r))
  2321. smartlist_add(excluded, r);
  2322. }
  2323. }
  2324. /* and exclude current entry guards, if applicable */
  2325. if (options->UseEntryGuards && entry_guards) {
  2326. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2327. {
  2328. if ((r = router_get_by_digest(entry->identity))) {
  2329. smartlist_add(excluded, r);
  2330. routerlist_add_family(excluded, r);
  2331. }
  2332. });
  2333. }
  2334. if (state) {
  2335. flags |= CRN_NEED_GUARD;
  2336. if (state->need_uptime)
  2337. flags |= CRN_NEED_UPTIME;
  2338. if (state->need_capacity)
  2339. flags |= CRN_NEED_CAPACITY;
  2340. }
  2341. if (options->_AllowInvalid & ALLOW_INVALID_ENTRY)
  2342. flags |= CRN_ALLOW_INVALID;
  2343. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2344. smartlist_free(excluded);
  2345. return choice;
  2346. }
  2347. /** Return the first non-open hop in cpath, or return NULL if all
  2348. * hops are open. */
  2349. static crypt_path_t *
  2350. onion_next_hop_in_cpath(crypt_path_t *cpath)
  2351. {
  2352. crypt_path_t *hop = cpath;
  2353. do {
  2354. if (hop->state != CPATH_STATE_OPEN)
  2355. return hop;
  2356. hop = hop->next;
  2357. } while (hop != cpath);
  2358. return NULL;
  2359. }
  2360. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  2361. * based on <b>state</b>. Append the hop info to head_ptr.
  2362. */
  2363. static int
  2364. onion_extend_cpath(origin_circuit_t *circ)
  2365. {
  2366. uint8_t purpose = circ->_base.purpose;
  2367. cpath_build_state_t *state = circ->build_state;
  2368. int cur_len = circuit_get_cpath_len(circ);
  2369. extend_info_t *info = NULL;
  2370. if (cur_len >= state->desired_path_len) {
  2371. log_debug(LD_CIRC, "Path is complete: %d steps long",
  2372. state->desired_path_len);
  2373. return 1;
  2374. }
  2375. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  2376. state->desired_path_len);
  2377. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  2378. info = extend_info_dup(state->chosen_exit);
  2379. } else if (cur_len == 0) { /* picking first node */
  2380. routerinfo_t *r = choose_good_entry_server(purpose, state);
  2381. if (r)
  2382. info = extend_info_from_router(r);
  2383. } else {
  2384. routerinfo_t *r =
  2385. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  2386. if (r)
  2387. info = extend_info_from_router(r);
  2388. }
  2389. if (!info) {
  2390. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  2391. "this circuit.", cur_len);
  2392. return -1;
  2393. }
  2394. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  2395. info->nickname, cur_len+1, build_state_get_exit_nickname(state));
  2396. onion_append_hop(&circ->cpath, info);
  2397. extend_info_free(info);
  2398. return 0;
  2399. }
  2400. /** Create a new hop, annotate it with information about its
  2401. * corresponding router <b>choice</b>, and append it to the
  2402. * end of the cpath <b>head_ptr</b>. */
  2403. static int
  2404. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  2405. {
  2406. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  2407. /* link hop into the cpath, at the end. */
  2408. onion_append_to_cpath(head_ptr, hop);
  2409. hop->magic = CRYPT_PATH_MAGIC;
  2410. hop->state = CPATH_STATE_CLOSED;
  2411. hop->extend_info = extend_info_dup(choice);
  2412. hop->package_window = circuit_initial_package_window();
  2413. hop->deliver_window = CIRCWINDOW_START;
  2414. return 0;
  2415. }
  2416. /** Allocate a new extend_info object based on the various arguments. */
  2417. extend_info_t *
  2418. extend_info_alloc(const char *nickname, const char *digest,
  2419. crypto_pk_env_t *onion_key,
  2420. const tor_addr_t *addr, uint16_t port)
  2421. {
  2422. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  2423. memcpy(info->identity_digest, digest, DIGEST_LEN);
  2424. if (nickname)
  2425. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  2426. if (onion_key)
  2427. info->onion_key = crypto_pk_dup_key(onion_key);
  2428. tor_addr_copy(&info->addr, addr);
  2429. info->port = port;
  2430. return info;
  2431. }
  2432. /** Allocate and return a new extend_info_t that can be used to build a
  2433. * circuit to or through the router <b>r</b>. */
  2434. extend_info_t *
  2435. extend_info_from_router(routerinfo_t *r)
  2436. {
  2437. tor_addr_t addr;
  2438. tor_assert(r);
  2439. tor_addr_from_ipv4h(&addr, r->addr);
  2440. return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
  2441. r->onion_pkey, &addr, r->or_port);
  2442. }
  2443. /** Release storage held by an extend_info_t struct. */
  2444. void
  2445. extend_info_free(extend_info_t *info)
  2446. {
  2447. if (!info)
  2448. return;
  2449. crypto_free_pk_env(info->onion_key);
  2450. tor_free(info);
  2451. }
  2452. /** Allocate and return a new extend_info_t with the same contents as
  2453. * <b>info</b>. */
  2454. extend_info_t *
  2455. extend_info_dup(extend_info_t *info)
  2456. {
  2457. extend_info_t *newinfo;
  2458. tor_assert(info);
  2459. newinfo = tor_malloc(sizeof(extend_info_t));
  2460. memcpy(newinfo, info, sizeof(extend_info_t));
  2461. if (info->onion_key)
  2462. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  2463. else
  2464. newinfo->onion_key = NULL;
  2465. return newinfo;
  2466. }
  2467. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  2468. * If there is no chosen exit, or if we don't know the routerinfo_t for
  2469. * the chosen exit, return NULL.
  2470. */
  2471. routerinfo_t *
  2472. build_state_get_exit_router(cpath_build_state_t *state)
  2473. {
  2474. if (!state || !state->chosen_exit)
  2475. return NULL;
  2476. return router_get_by_digest(state->chosen_exit->identity_digest);
  2477. }
  2478. /** Return the nickname for the chosen exit router in <b>state</b>. If
  2479. * there is no chosen exit, or if we don't know the routerinfo_t for the
  2480. * chosen exit, return NULL.
  2481. */
  2482. const char *
  2483. build_state_get_exit_nickname(cpath_build_state_t *state)
  2484. {
  2485. if (!state || !state->chosen_exit)
  2486. return NULL;
  2487. return state->chosen_exit->nickname;
  2488. }
  2489. /** Check whether the entry guard <b>e</b> is usable, given the directory
  2490. * authorities' opinion about the router (stored in <b>ri</b>) and the user's
  2491. * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
  2492. * accordingly. Return true iff the entry guard's status changes.
  2493. *
  2494. * If it's not usable, set *<b>reason</b> to a static string explaining why.
  2495. */
  2496. /*XXXX take a routerstatus, not a routerinfo. */
  2497. static int
  2498. entry_guard_set_status(entry_guard_t *e, routerinfo_t *ri,
  2499. time_t now, or_options_t *options, const char **reason)
  2500. {
  2501. char buf[HEX_DIGEST_LEN+1];
  2502. int changed = 0;
  2503. tor_assert(options);
  2504. *reason = NULL;
  2505. /* Do we want to mark this guard as bad? */
  2506. if (!ri)
  2507. *reason = "unlisted";
  2508. else if (!ri->is_running)
  2509. *reason = "down";
  2510. else if (options->UseBridges && ri->purpose != ROUTER_PURPOSE_BRIDGE)
  2511. *reason = "not a bridge";
  2512. else if (!options->UseBridges && !ri->is_possible_guard &&
  2513. !routerset_contains_router(options->EntryNodes,ri))
  2514. *reason = "not recommended as a guard";
  2515. else if (routerset_contains_router(options->ExcludeNodes, ri))
  2516. *reason = "excluded";
  2517. if (*reason && ! e->bad_since) {
  2518. /* Router is newly bad. */
  2519. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  2520. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  2521. e->nickname, buf, *reason);
  2522. e->bad_since = now;
  2523. control_event_guard(e->nickname, e->identity, "BAD");
  2524. changed = 1;
  2525. } else if (!*reason && e->bad_since) {
  2526. /* There's nothing wrong with the router any more. */
  2527. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  2528. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  2529. "marking as ok.", e->nickname, buf);
  2530. e->bad_since = 0;
  2531. control_event_guard(e->nickname, e->identity, "GOOD");
  2532. changed = 1;
  2533. }
  2534. return changed;
  2535. }
  2536. /** Return true iff enough time has passed since we last tried to connect
  2537. * to the unreachable guard <b>e</b> that we're willing to try again. */
  2538. static int
  2539. entry_is_time_to_retry(entry_guard_t *e, time_t now)
  2540. {
  2541. long diff;
  2542. if (e->last_attempted < e->unreachable_since)
  2543. return 1;
  2544. diff = now - e->unreachable_since;
  2545. if (diff < 6*60*60)
  2546. return now > (e->last_attempted + 60*60);
  2547. else if (diff < 3*24*60*60)
  2548. return now > (e->last_attempted + 4*60*60);
  2549. else if (diff < 7*24*60*60)
  2550. return now > (e->last_attempted + 18*60*60);
  2551. else
  2552. return now > (e->last_attempted + 36*60*60);
  2553. }
  2554. /** Return the router corresponding to <b>e</b>, if <b>e</b> is
  2555. * working well enough that we are willing to use it as an entry
  2556. * right now. (Else return NULL.) In particular, it must be
  2557. * - Listed as either up or never yet contacted;
  2558. * - Present in the routerlist;
  2559. * - Listed as 'stable' or 'fast' by the current dirserver consensus,
  2560. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
  2561. * (unless it's a configured EntryNode);
  2562. * - Allowed by our current ReachableORAddresses config option; and
  2563. * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
  2564. * is true).
  2565. *
  2566. * If the answer is no, set *<b>msg</b> to an explanation of why.
  2567. */
  2568. static INLINE routerinfo_t *
  2569. entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
  2570. int assume_reachable, const char **msg)
  2571. {
  2572. routerinfo_t *r;
  2573. or_options_t *options = get_options();
  2574. tor_assert(msg);
  2575. if (e->bad_since) {
  2576. *msg = "bad";
  2577. return NULL;
  2578. }
  2579. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  2580. if (!assume_reachable && !e->can_retry &&
  2581. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
  2582. *msg = "unreachable";
  2583. return NULL;
  2584. }
  2585. r = router_get_by_digest(e->identity);
  2586. if (!r) {
  2587. *msg = "no descriptor";
  2588. return NULL;
  2589. }
  2590. if (get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_BRIDGE) {
  2591. *msg = "not a bridge";
  2592. return NULL;
  2593. }
  2594. if (!get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_GENERAL) {
  2595. *msg = "not general-purpose";
  2596. return NULL;
  2597. }
  2598. if (options->EntryNodes &&
  2599. routerset_contains_router(options->EntryNodes, r)) {
  2600. /* they asked for it, they get it */
  2601. need_uptime = need_capacity = 0;
  2602. }
  2603. if (router_is_unreliable(r, need_uptime, need_capacity, 0)) {
  2604. *msg = "not fast/stable";
  2605. return NULL;
  2606. }
  2607. if (!fascist_firewall_allows_or(r)) {
  2608. *msg = "unreachable by config";
  2609. return NULL;
  2610. }
  2611. return r;
  2612. }
  2613. /** Return the number of entry guards that we think are usable. */
  2614. static int
  2615. num_live_entry_guards(void)
  2616. {
  2617. int n = 0;
  2618. const char *msg;
  2619. if (! entry_guards)
  2620. return 0;
  2621. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2622. {
  2623. if (entry_is_live(entry, 0, 1, 0, &msg))
  2624. ++n;
  2625. });
  2626. return n;
  2627. }
  2628. /** If <b>digest</b> matches the identity of any node in the
  2629. * entry_guards list, return that node. Else return NULL. */
  2630. static INLINE entry_guard_t *
  2631. is_an_entry_guard(const char *digest)
  2632. {
  2633. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2634. if (!memcmp(digest, entry->identity, DIGEST_LEN))
  2635. return entry;
  2636. );
  2637. return NULL;
  2638. }
  2639. /** Dump a description of our list of entry guards to the log at level
  2640. * <b>severity</b>. */
  2641. static void
  2642. log_entry_guards(int severity)
  2643. {
  2644. smartlist_t *elements = smartlist_create();
  2645. char buf[1024];
  2646. char *s;
  2647. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2648. {
  2649. const char *msg = NULL;
  2650. if (entry_is_live(e, 0, 1, 0, &msg))
  2651. tor_snprintf(buf, sizeof(buf), "%s (up %s)",
  2652. e->nickname,
  2653. e->made_contact ? "made-contact" : "never-contacted");
  2654. else
  2655. tor_snprintf(buf, sizeof(buf), "%s (%s, %s)",
  2656. e->nickname, msg,
  2657. e->made_contact ? "made-contact" : "never-contacted");
  2658. smartlist_add(elements, tor_strdup(buf));
  2659. });
  2660. s = smartlist_join_strings(elements, ",", 0, NULL);
  2661. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  2662. smartlist_free(elements);
  2663. log_fn(severity,LD_CIRC,"%s",s);
  2664. tor_free(s);
  2665. }
  2666. /** Called when one or more guards that we would previously have used for some
  2667. * purpose are no longer in use because a higher-priority guard has become
  2668. * usable again. */
  2669. static void
  2670. control_event_guard_deferred(void)
  2671. {
  2672. /* XXXX We don't actually have a good way to figure out _how many_ entries
  2673. * are live for some purpose. We need an entry_is_even_slightly_live()
  2674. * function for this to work right. NumEntryGuards isn't reliable: if we
  2675. * need guards with weird properties, we can have more than that number
  2676. * live.
  2677. **/
  2678. #if 0
  2679. int n = 0;
  2680. const char *msg;
  2681. or_options_t *options = get_options();
  2682. if (!entry_guards)
  2683. return;
  2684. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2685. {
  2686. if (entry_is_live(entry, 0, 1, 0, &msg)) {
  2687. if (n++ == options->NumEntryGuards) {
  2688. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  2689. return;
  2690. }
  2691. }
  2692. });
  2693. #endif
  2694. }
  2695. /** Add a new (preferably stable and fast) router to our
  2696. * entry_guards list. Return a pointer to the router if we succeed,
  2697. * or NULL if we can't find any more suitable entries.
  2698. *
  2699. * If <b>chosen</b> is defined, use that one, and if it's not
  2700. * already in our entry_guards list, put it at the *beginning*.
  2701. * Else, put the one we pick at the end of the list. */
  2702. static routerinfo_t *
  2703. add_an_entry_guard(routerinfo_t *chosen, int reset_status)
  2704. {
  2705. routerinfo_t *router;
  2706. entry_guard_t *entry;
  2707. if (chosen) {
  2708. router = chosen;
  2709. entry = is_an_entry_guard(router->cache_info.identity_digest);
  2710. if (entry) {
  2711. if (reset_status) {
  2712. entry->bad_since = 0;
  2713. entry->can_retry = 1;
  2714. }
  2715. return NULL;
  2716. }
  2717. } else {
  2718. router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  2719. if (!router)
  2720. return NULL;
  2721. }
  2722. entry = tor_malloc_zero(sizeof(entry_guard_t));
  2723. log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
  2724. strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
  2725. memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
  2726. entry->chosen_on_date = start_of_month(time(NULL));
  2727. entry->chosen_by_version = tor_strdup(VERSION);
  2728. if (chosen) /* prepend */
  2729. smartlist_insert(entry_guards, 0, entry);
  2730. else /* append */
  2731. smartlist_add(entry_guards, entry);
  2732. control_event_guard(entry->nickname, entry->identity, "NEW");
  2733. control_event_guard_deferred();
  2734. log_entry_guards(LOG_INFO);
  2735. return router;
  2736. }
  2737. /** If the use of entry guards is configured, choose more entry guards
  2738. * until we have enough in the list. */
  2739. static void
  2740. pick_entry_guards(void)
  2741. {
  2742. or_options_t *options = get_options();
  2743. int changed = 0;
  2744. tor_assert(entry_guards);
  2745. while (num_live_entry_guards() < options->NumEntryGuards) {
  2746. if (!add_an_entry_guard(NULL, 0))
  2747. break;
  2748. changed = 1;
  2749. }
  2750. if (changed)
  2751. entry_guards_changed();
  2752. }
  2753. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  2754. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  2755. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  2756. /** Release all storage held by <b>e</b>. */
  2757. static void
  2758. entry_guard_free(entry_guard_t *e)
  2759. {
  2760. if (!e)
  2761. return;
  2762. tor_free(e->chosen_by_version);
  2763. tor_free(e);
  2764. }
  2765. /** Remove any entry guard which was selected by an unknown version of Tor,
  2766. * or which was selected by a version of Tor that's known to select
  2767. * entry guards badly. */
  2768. static int
  2769. remove_obsolete_entry_guards(void)
  2770. {
  2771. int changed = 0, i;
  2772. time_t this_month = start_of_month(time(NULL));
  2773. for (i = 0; i < smartlist_len(entry_guards); ++i) {
  2774. entry_guard_t *entry = smartlist_get(entry_guards, i);
  2775. const char *ver = entry->chosen_by_version;
  2776. const char *msg = NULL;
  2777. tor_version_t v;
  2778. int version_is_bad = 0, date_is_bad = 0;
  2779. if (!ver) {
  2780. msg = "does not say what version of Tor it was selected by";
  2781. version_is_bad = 1;
  2782. } else if (tor_version_parse(ver, &v)) {
  2783. msg = "does not seem to be from any recognized version of Tor";
  2784. version_is_bad = 1;
  2785. } else if ((tor_version_as_new_as(ver, "0.1.0.10-alpha") &&
  2786. !tor_version_as_new_as(ver, "0.1.2.16-dev")) ||
  2787. (tor_version_as_new_as(ver, "0.2.0.0-alpha") &&
  2788. !tor_version_as_new_as(ver, "0.2.0.6-alpha"))) {
  2789. msg = "was selected without regard for guard bandwidth";
  2790. version_is_bad = 1;
  2791. } else if (entry->chosen_on_date + 3600*24*35 < this_month) {
  2792. /* It's been more than a month, and probably more like two since
  2793. * chosen_on_date is clipped to the beginning of its month. */
  2794. msg = "was selected several months ago";
  2795. date_is_bad = 1;
  2796. }
  2797. if (version_is_bad || date_is_bad) { /* we need to drop it */
  2798. char dbuf[HEX_DIGEST_LEN+1];
  2799. tor_assert(msg);
  2800. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2801. log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
  2802. "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
  2803. entry->nickname, dbuf, msg, ver?escaped(ver):"none");
  2804. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2805. entry_guard_free(entry);
  2806. smartlist_del_keeporder(entry_guards, i--);
  2807. log_entry_guards(LOG_INFO);
  2808. changed = 1;
  2809. }
  2810. }
  2811. return changed ? 1 : 0;
  2812. }
  2813. /** Remove all entry guards that have been down or unlisted for so
  2814. * long that we don't think they'll come up again. Return 1 if we
  2815. * removed any, or 0 if we did nothing. */
  2816. static int
  2817. remove_dead_entry_guards(void)
  2818. {
  2819. char dbuf[HEX_DIGEST_LEN+1];
  2820. char tbuf[ISO_TIME_LEN+1];
  2821. time_t now = time(NULL);
  2822. int i;
  2823. int changed = 0;
  2824. for (i = 0; i < smartlist_len(entry_guards); ) {
  2825. entry_guard_t *entry = smartlist_get(entry_guards, i);
  2826. if (entry->bad_since &&
  2827. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  2828. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2829. format_local_iso_time(tbuf, entry->bad_since);
  2830. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  2831. "since %s local time; removing.",
  2832. entry->nickname, dbuf, tbuf);
  2833. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2834. entry_guard_free(entry);
  2835. smartlist_del_keeporder(entry_guards, i);
  2836. log_entry_guards(LOG_INFO);
  2837. changed = 1;
  2838. } else
  2839. ++i;
  2840. }
  2841. return changed ? 1 : 0;
  2842. }
  2843. /** A new directory or router-status has arrived; update the down/listed
  2844. * status of the entry guards.
  2845. *
  2846. * An entry is 'down' if the directory lists it as nonrunning.
  2847. * An entry is 'unlisted' if the directory doesn't include it.
  2848. *
  2849. * Don't call this on startup; only on a fresh download. Otherwise we'll
  2850. * think that things are unlisted.
  2851. */
  2852. void
  2853. entry_guards_compute_status(void)
  2854. {
  2855. time_t now;
  2856. int changed = 0;
  2857. int severity = LOG_DEBUG;
  2858. or_options_t *options;
  2859. digestmap_t *reasons;
  2860. if (! entry_guards)
  2861. return;
  2862. options = get_options();
  2863. if (options->EntryNodes) /* reshuffle the entry guard list if needed */
  2864. entry_nodes_should_be_added();
  2865. now = time(NULL);
  2866. reasons = digestmap_new();
  2867. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry)
  2868. {
  2869. routerinfo_t *r = router_get_by_digest(entry->identity);
  2870. const char *reason = NULL;
  2871. if (entry_guard_set_status(entry, r, now, options, &reason))
  2872. changed = 1;
  2873. if (entry->bad_since)
  2874. tor_assert(reason);
  2875. if (reason)
  2876. digestmap_set(reasons, entry->identity, (char*)reason);
  2877. }
  2878. SMARTLIST_FOREACH_END(entry);
  2879. if (remove_dead_entry_guards())
  2880. changed = 1;
  2881. severity = changed ? LOG_DEBUG : LOG_INFO;
  2882. if (changed) {
  2883. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
  2884. const char *reason = digestmap_get(reasons, entry->identity);
  2885. const char *live_msg;
  2886. routerinfo_t *r = entry_is_live(entry, 0, 1, 0, &live_msg);
  2887. log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s%s%s, and %s%s.",
  2888. entry->nickname,
  2889. entry->unreachable_since ? "unreachable" : "reachable",
  2890. entry->bad_since ? "unusable" : "usable",
  2891. reason ? ", ": "",
  2892. reason ? reason : "",
  2893. r ? "live" : "not live / ",
  2894. r ? "" : live_msg);
  2895. } SMARTLIST_FOREACH_END(entry);
  2896. log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
  2897. num_live_entry_guards(), smartlist_len(entry_guards));
  2898. log_entry_guards(LOG_INFO);
  2899. entry_guards_changed();
  2900. }
  2901. digestmap_free(reasons, NULL);
  2902. }
  2903. /** Called when a connection to an OR with the identity digest <b>digest</b>
  2904. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  2905. * If the OR is an entry, change that entry's up/down status.
  2906. * Return 0 normally, or -1 if we want to tear down the new connection.
  2907. *
  2908. * If <b>mark_relay_status</b>, also call router_set_status() on this
  2909. * relay.
  2910. *
  2911. * XXX022 change succeeded and mark_relay_status into 'int flags'.
  2912. */
  2913. int
  2914. entry_guard_register_connect_status(const char *digest, int succeeded,
  2915. int mark_relay_status, time_t now)
  2916. {
  2917. int changed = 0;
  2918. int refuse_conn = 0;
  2919. int first_contact = 0;
  2920. entry_guard_t *entry = NULL;
  2921. int idx = -1;
  2922. char buf[HEX_DIGEST_LEN+1];
  2923. if (! entry_guards)
  2924. return 0;
  2925. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2926. {
  2927. if (!memcmp(e->identity, digest, DIGEST_LEN)) {
  2928. entry = e;
  2929. idx = e_sl_idx;
  2930. break;
  2931. }
  2932. });
  2933. if (!entry)
  2934. return 0;
  2935. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  2936. if (succeeded) {
  2937. if (entry->unreachable_since) {
  2938. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  2939. entry->nickname, buf);
  2940. entry->can_retry = 0;
  2941. entry->unreachable_since = 0;
  2942. entry->last_attempted = now;
  2943. control_event_guard(entry->nickname, entry->identity, "UP");
  2944. changed = 1;
  2945. }
  2946. if (!entry->made_contact) {
  2947. entry->made_contact = 1;
  2948. first_contact = changed = 1;
  2949. }
  2950. } else { /* ! succeeded */
  2951. if (!entry->made_contact) {
  2952. /* We've never connected to this one. */
  2953. log_info(LD_CIRC,
  2954. "Connection to never-contacted entry guard '%s' (%s) failed. "
  2955. "Removing from the list. %d/%d entry guards usable/new.",
  2956. entry->nickname, buf,
  2957. num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
  2958. entry_guard_free(entry);
  2959. smartlist_del_keeporder(entry_guards, idx);
  2960. log_entry_guards(LOG_INFO);
  2961. changed = 1;
  2962. } else if (!entry->unreachable_since) {
  2963. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  2964. "Marking as unreachable.", entry->nickname, buf);
  2965. entry->unreachable_since = entry->last_attempted = now;
  2966. control_event_guard(entry->nickname, entry->identity, "DOWN");
  2967. changed = 1;
  2968. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2969. } else {
  2970. char tbuf[ISO_TIME_LEN+1];
  2971. format_iso_time(tbuf, entry->unreachable_since);
  2972. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  2973. "'%s' (%s). It has been unreachable since %s.",
  2974. entry->nickname, buf, tbuf);
  2975. entry->last_attempted = now;
  2976. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2977. }
  2978. }
  2979. /* if the caller asked us to, also update the is_running flags for this
  2980. * relay */
  2981. if (mark_relay_status)
  2982. router_set_status(digest, succeeded);
  2983. if (first_contact) {
  2984. /* We've just added a new long-term entry guard. Perhaps the network just
  2985. * came back? We should give our earlier entries another try too,
  2986. * and close this connection so we don't use it before we've given
  2987. * the others a shot. */
  2988. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  2989. if (e == entry)
  2990. break;
  2991. if (e->made_contact) {
  2992. const char *msg;
  2993. routerinfo_t *r = entry_is_live(e, 0, 1, 1, &msg);
  2994. if (r && e->unreachable_since) {
  2995. refuse_conn = 1;
  2996. e->can_retry = 1;
  2997. }
  2998. }
  2999. });
  3000. if (refuse_conn) {
  3001. log_info(LD_CIRC,
  3002. "Connected to new entry guard '%s' (%s). Marking earlier "
  3003. "entry guards up. %d/%d entry guards usable/new.",
  3004. entry->nickname, buf,
  3005. num_live_entry_guards(), smartlist_len(entry_guards));
  3006. log_entry_guards(LOG_INFO);
  3007. changed = 1;
  3008. }
  3009. }
  3010. if (changed)
  3011. entry_guards_changed();
  3012. return refuse_conn ? -1 : 0;
  3013. }
  3014. /** When we try to choose an entry guard, should we parse and add
  3015. * config's EntryNodes first? */
  3016. static int should_add_entry_nodes = 0;
  3017. /** Called when the value of EntryNodes changes in our configuration. */
  3018. void
  3019. entry_nodes_should_be_added(void)
  3020. {
  3021. log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
  3022. "relays at the front of the entry guard list.");
  3023. should_add_entry_nodes = 1;
  3024. }
  3025. /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
  3026. * of guard nodes, at the front. */
  3027. static void
  3028. entry_guards_prepend_from_config(void)
  3029. {
  3030. or_options_t *options = get_options();
  3031. smartlist_t *entry_routers, *entry_fps;
  3032. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  3033. tor_assert(entry_guards);
  3034. should_add_entry_nodes = 0;
  3035. if (!options->EntryNodes) {
  3036. /* It's possible that a controller set EntryNodes, thus making
  3037. * should_add_entry_nodes set, then cleared it again, all before the
  3038. * call to choose_random_entry() that triggered us. If so, just return.
  3039. */
  3040. return;
  3041. }
  3042. {
  3043. char *string = routerset_to_string(options->EntryNodes);
  3044. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
  3045. tor_free(string);
  3046. }
  3047. entry_routers = smartlist_create();
  3048. entry_fps = smartlist_create();
  3049. old_entry_guards_on_list = smartlist_create();
  3050. old_entry_guards_not_on_list = smartlist_create();
  3051. /* Split entry guards into those on the list and those not. */
  3052. /* XXXX022 Now that we allow countries and IP ranges in EntryNodes, this is
  3053. * potentially an enormous list. For now, we disable such values for
  3054. * EntryNodes in options_validate(); really, this wants a better solution.
  3055. * Perhaps we should do this calculation once whenever the list of routers
  3056. * changes or the entrynodes setting changes.
  3057. */
  3058. routerset_get_all_routers(entry_routers, options->EntryNodes, 0);
  3059. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri,
  3060. smartlist_add(entry_fps,ri->cache_info.identity_digest));
  3061. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  3062. if (smartlist_digest_isin(entry_fps, e->identity))
  3063. smartlist_add(old_entry_guards_on_list, e);
  3064. else
  3065. smartlist_add(old_entry_guards_not_on_list, e);
  3066. });
  3067. /* Remove all currently configured entry guards from entry_routers. */
  3068. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  3069. if (is_an_entry_guard(ri->cache_info.identity_digest)) {
  3070. SMARTLIST_DEL_CURRENT(entry_routers, ri);
  3071. }
  3072. });
  3073. /* Now build the new entry_guards list. */
  3074. smartlist_clear(entry_guards);
  3075. /* First, the previously configured guards that are in EntryNodes. */
  3076. smartlist_add_all(entry_guards, old_entry_guards_on_list);
  3077. /* Next, the rest of EntryNodes */
  3078. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  3079. add_an_entry_guard(ri, 0);
  3080. });
  3081. /* Finally, the remaining previously configured guards that are not in
  3082. * EntryNodes, unless we're strict in which case we drop them */
  3083. if (options->StrictNodes) {
  3084. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  3085. entry_guard_free(e));
  3086. } else {
  3087. smartlist_add_all(entry_guards, old_entry_guards_not_on_list);
  3088. }
  3089. smartlist_free(entry_routers);
  3090. smartlist_free(entry_fps);
  3091. smartlist_free(old_entry_guards_on_list);
  3092. smartlist_free(old_entry_guards_not_on_list);
  3093. entry_guards_changed();
  3094. }
  3095. /** Return 0 if we're fine adding arbitrary routers out of the
  3096. * directory to our entry guard list, or return 1 if we have a
  3097. * list already and we'd prefer to stick to it.
  3098. */
  3099. int
  3100. entry_list_is_constrained(or_options_t *options)
  3101. {
  3102. if (options->EntryNodes)
  3103. return 1;
  3104. if (options->UseBridges)
  3105. return 1;
  3106. return 0;
  3107. }
  3108. /* Are we dead set against changing our entry guard list, or would we
  3109. * change it if it means keeping Tor usable? */
  3110. static int
  3111. entry_list_is_totally_static(or_options_t *options)
  3112. {
  3113. if (options->EntryNodes && options->StrictNodes)
  3114. return 1;
  3115. if (options->UseBridges)
  3116. return 1;
  3117. return 0;
  3118. }
  3119. /** Pick a live (up and listed) entry guard from entry_guards. If
  3120. * <b>state</b> is non-NULL, this is for a specific circuit --
  3121. * make sure not to pick this circuit's exit or any node in the
  3122. * exit's family. If <b>state</b> is NULL, we're looking for a random
  3123. * guard (likely a bridge). */
  3124. routerinfo_t *
  3125. choose_random_entry(cpath_build_state_t *state)
  3126. {
  3127. or_options_t *options = get_options();
  3128. smartlist_t *live_entry_guards = smartlist_create();
  3129. smartlist_t *exit_family = smartlist_create();
  3130. routerinfo_t *chosen_exit = state?build_state_get_exit_router(state) : NULL;
  3131. routerinfo_t *r = NULL;
  3132. int need_uptime = state ? state->need_uptime : 0;
  3133. int need_capacity = state ? state->need_capacity : 0;
  3134. int preferred_min, consider_exit_family = 0;
  3135. if (chosen_exit) {
  3136. smartlist_add(exit_family, chosen_exit);
  3137. routerlist_add_family(exit_family, chosen_exit);
  3138. consider_exit_family = 1;
  3139. }
  3140. if (!entry_guards)
  3141. entry_guards = smartlist_create();
  3142. if (should_add_entry_nodes)
  3143. entry_guards_prepend_from_config();
  3144. if (!entry_list_is_constrained(options) &&
  3145. smartlist_len(entry_guards) < options->NumEntryGuards)
  3146. pick_entry_guards();
  3147. retry:
  3148. smartlist_clear(live_entry_guards);
  3149. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3150. {
  3151. const char *msg;
  3152. r = entry_is_live(entry, need_uptime, need_capacity, 0, &msg);
  3153. if (!r)
  3154. continue; /* down, no point */
  3155. if (consider_exit_family && smartlist_isin(exit_family, r))
  3156. continue; /* avoid relays that are family members of our exit */
  3157. if (options->EntryNodes &&
  3158. !routerset_contains_router(options->EntryNodes, r)) {
  3159. /* We've come to the end of our preferred entry nodes. */
  3160. if (smartlist_len(live_entry_guards))
  3161. goto choose_and_finish; /* only choose from the ones we like */
  3162. if (options->StrictNodes) {
  3163. /* in theory this case should never happen, since
  3164. * entry_guards_prepend_from_config() drops unwanted relays */
  3165. tor_fragile_assert();
  3166. } else {
  3167. log_info(LD_CIRC,
  3168. "No relays from EntryNodes available. Using others.");
  3169. }
  3170. }
  3171. smartlist_add(live_entry_guards, r);
  3172. if (!entry->made_contact) {
  3173. /* Always start with the first not-yet-contacted entry
  3174. * guard. Otherwise we might add several new ones, pick
  3175. * the second new one, and now we've expanded our entry
  3176. * guard list without needing to. */
  3177. goto choose_and_finish;
  3178. }
  3179. if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
  3180. break; /* we have enough */
  3181. });
  3182. if (entry_list_is_constrained(options)) {
  3183. /* If we prefer the entry nodes we've got, and we have at least
  3184. * one choice, that's great. Use it. */
  3185. preferred_min = 1;
  3186. } else {
  3187. /* Try to have at least 2 choices available. This way we don't
  3188. * get stuck with a single live-but-crummy entry and just keep
  3189. * using him.
  3190. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  3191. preferred_min = 2;
  3192. }
  3193. if (smartlist_len(live_entry_guards) < preferred_min) {
  3194. if (!entry_list_is_totally_static(options)) {
  3195. /* still no? try adding a new entry then */
  3196. /* XXX if guard doesn't imply fast and stable, then we need
  3197. * to tell add_an_entry_guard below what we want, or it might
  3198. * be a long time til we get it. -RD */
  3199. r = add_an_entry_guard(NULL, 0);
  3200. if (r) {
  3201. entry_guards_changed();
  3202. /* XXX we start over here in case the new node we added shares
  3203. * a family with our exit node. There's a chance that we'll just
  3204. * load up on entry guards here, if the network we're using is
  3205. * one big family. Perhaps we should teach add_an_entry_guard()
  3206. * to understand nodes-to-avoid-if-possible? -RD */
  3207. goto retry;
  3208. }
  3209. }
  3210. if (!r && need_uptime) {
  3211. need_uptime = 0; /* try without that requirement */
  3212. goto retry;
  3213. }
  3214. if (!r && need_capacity) {
  3215. /* still no? last attempt, try without requiring capacity */
  3216. need_capacity = 0;
  3217. goto retry;
  3218. }
  3219. if (!r && entry_list_is_constrained(options) && consider_exit_family) {
  3220. /* still no? if we're using bridges or have strictentrynodes
  3221. * set, and our chosen exit is in the same family as all our
  3222. * bridges/entry guards, then be flexible about families. */
  3223. consider_exit_family = 0;
  3224. goto retry;
  3225. }
  3226. /* live_entry_guards may be empty below. Oh well, we tried. */
  3227. }
  3228. choose_and_finish:
  3229. if (entry_list_is_constrained(options)) {
  3230. /* We need to weight by bandwidth, because our bridges or entryguards
  3231. * were not already selected proportional to their bandwidth. */
  3232. r = routerlist_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
  3233. } else {
  3234. /* We choose uniformly at random here, because choose_good_entry_server()
  3235. * already weights its choices by bandwidth, so we don't want to
  3236. * *double*-weight our guard selection. */
  3237. r = smartlist_choose(live_entry_guards);
  3238. }
  3239. smartlist_free(live_entry_guards);
  3240. smartlist_free(exit_family);
  3241. return r;
  3242. }
  3243. /** Helper: Return the start of the month containing <b>time</b>. */
  3244. static time_t
  3245. start_of_month(time_t now)
  3246. {
  3247. struct tm tm;
  3248. tor_gmtime_r(&now, &tm);
  3249. tm.tm_sec = 0;
  3250. tm.tm_min = 0;
  3251. tm.tm_hour = 0;
  3252. tm.tm_mday = 1;
  3253. return tor_timegm(&tm);
  3254. }
  3255. /** Parse <b>state</b> and learn about the entry guards it describes.
  3256. * If <b>set</b> is true, and there are no errors, replace the global
  3257. * entry_list with what we find.
  3258. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  3259. * describing the error, and return -1.
  3260. */
  3261. int
  3262. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  3263. {
  3264. entry_guard_t *node = NULL;
  3265. smartlist_t *new_entry_guards = smartlist_create();
  3266. config_line_t *line;
  3267. time_t now = time(NULL);
  3268. const char *state_version = state->TorVersion;
  3269. digestmap_t *added_by = digestmap_new();
  3270. *msg = NULL;
  3271. for (line = state->EntryGuards; line; line = line->next) {
  3272. if (!strcasecmp(line->key, "EntryGuard")) {
  3273. smartlist_t *args = smartlist_create();
  3274. node = tor_malloc_zero(sizeof(entry_guard_t));
  3275. /* all entry guards on disk have been contacted */
  3276. node->made_contact = 1;
  3277. smartlist_add(new_entry_guards, node);
  3278. smartlist_split_string(args, line->value, " ",
  3279. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3280. if (smartlist_len(args)<2) {
  3281. *msg = tor_strdup("Unable to parse entry nodes: "
  3282. "Too few arguments to EntryGuard");
  3283. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  3284. *msg = tor_strdup("Unable to parse entry nodes: "
  3285. "Bad nickname for EntryGuard");
  3286. } else {
  3287. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  3288. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  3289. strlen(smartlist_get(args,1)))<0) {
  3290. *msg = tor_strdup("Unable to parse entry nodes: "
  3291. "Bad hex digest for EntryGuard");
  3292. }
  3293. }
  3294. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  3295. smartlist_free(args);
  3296. if (*msg)
  3297. break;
  3298. } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
  3299. !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
  3300. time_t when;
  3301. time_t last_try = 0;
  3302. if (!node) {
  3303. *msg = tor_strdup("Unable to parse entry nodes: "
  3304. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  3305. break;
  3306. }
  3307. if (parse_iso_time(line->value, &when)<0) {
  3308. *msg = tor_strdup("Unable to parse entry nodes: "
  3309. "Bad time in EntryGuardDownSince/UnlistedSince");
  3310. break;
  3311. }
  3312. if (when > now) {
  3313. /* It's a bad idea to believe info in the future: you can wind
  3314. * up with timeouts that aren't allowed to happen for years. */
  3315. continue;
  3316. }
  3317. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  3318. /* ignore failure */
  3319. (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  3320. }
  3321. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  3322. node->unreachable_since = when;
  3323. node->last_attempted = last_try;
  3324. } else {
  3325. node->bad_since = when;
  3326. }
  3327. } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
  3328. char d[DIGEST_LEN];
  3329. /* format is digest version date */
  3330. if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
  3331. log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
  3332. continue;
  3333. }
  3334. if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
  3335. line->value[HEX_DIGEST_LEN] != ' ') {
  3336. log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
  3337. "hex digest", escaped(line->value));
  3338. continue;
  3339. }
  3340. digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
  3341. } else {
  3342. log_warn(LD_BUG, "Unexpected key %s", line->key);
  3343. }
  3344. }
  3345. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  3346. {
  3347. char *sp;
  3348. char *val = digestmap_get(added_by, e->identity);
  3349. if (val && (sp = strchr(val, ' '))) {
  3350. time_t when;
  3351. *sp++ = '\0';
  3352. if (parse_iso_time(sp, &when)<0) {
  3353. log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
  3354. } else {
  3355. e->chosen_by_version = tor_strdup(val);
  3356. e->chosen_on_date = when;
  3357. }
  3358. } else {
  3359. if (state_version) {
  3360. e->chosen_by_version = tor_strdup(state_version);
  3361. e->chosen_on_date = start_of_month(time(NULL));
  3362. }
  3363. }
  3364. });
  3365. if (*msg || !set) {
  3366. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  3367. entry_guard_free(e));
  3368. smartlist_free(new_entry_guards);
  3369. } else { /* !err && set */
  3370. if (entry_guards) {
  3371. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  3372. entry_guard_free(e));
  3373. smartlist_free(entry_guards);
  3374. }
  3375. entry_guards = new_entry_guards;
  3376. entry_guards_dirty = 0;
  3377. /* XXX022 hand new_entry_guards to this func, and move it up a
  3378. * few lines, so we don't have to re-dirty it */
  3379. if (remove_obsolete_entry_guards())
  3380. entry_guards_dirty = 1;
  3381. }
  3382. digestmap_free(added_by, _tor_free);
  3383. return *msg ? -1 : 0;
  3384. }
  3385. /** Our list of entry guards has changed, or some element of one
  3386. * of our entry guards has changed. Write the changes to disk within
  3387. * the next few minutes.
  3388. */
  3389. static void
  3390. entry_guards_changed(void)
  3391. {
  3392. time_t when;
  3393. entry_guards_dirty = 1;
  3394. /* or_state_save() will call entry_guards_update_state(). */
  3395. when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
  3396. or_state_mark_dirty(get_or_state(), when);
  3397. }
  3398. /** If the entry guard info has not changed, do nothing and return.
  3399. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  3400. * a new one out of the global entry_guards list, and then mark
  3401. * <b>state</b> dirty so it will get saved to disk.
  3402. */
  3403. void
  3404. entry_guards_update_state(or_state_t *state)
  3405. {
  3406. config_line_t **next, *line;
  3407. if (! entry_guards_dirty)
  3408. return;
  3409. config_free_lines(state->EntryGuards);
  3410. next = &state->EntryGuards;
  3411. *next = NULL;
  3412. if (!entry_guards)
  3413. entry_guards = smartlist_create();
  3414. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  3415. {
  3416. char dbuf[HEX_DIGEST_LEN+1];
  3417. if (!e->made_contact)
  3418. continue; /* don't write this one to disk */
  3419. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3420. line->key = tor_strdup("EntryGuard");
  3421. line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
  3422. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  3423. tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
  3424. "%s %s", e->nickname, dbuf);
  3425. next = &(line->next);
  3426. if (e->unreachable_since) {
  3427. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3428. line->key = tor_strdup("EntryGuardDownSince");
  3429. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  3430. format_iso_time(line->value, e->unreachable_since);
  3431. if (e->last_attempted) {
  3432. line->value[ISO_TIME_LEN] = ' ';
  3433. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  3434. }
  3435. next = &(line->next);
  3436. }
  3437. if (e->bad_since) {
  3438. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3439. line->key = tor_strdup("EntryGuardUnlistedSince");
  3440. line->value = tor_malloc(ISO_TIME_LEN+1);
  3441. format_iso_time(line->value, e->bad_since);
  3442. next = &(line->next);
  3443. }
  3444. if (e->chosen_on_date && e->chosen_by_version &&
  3445. !strchr(e->chosen_by_version, ' ')) {
  3446. char d[HEX_DIGEST_LEN+1];
  3447. char t[ISO_TIME_LEN+1];
  3448. size_t val_len;
  3449. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3450. line->key = tor_strdup("EntryGuardAddedBy");
  3451. val_len = (HEX_DIGEST_LEN+1+strlen(e->chosen_by_version)
  3452. +1+ISO_TIME_LEN+1);
  3453. line->value = tor_malloc(val_len);
  3454. base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
  3455. format_iso_time(t, e->chosen_on_date);
  3456. tor_snprintf(line->value, val_len, "%s %s %s",
  3457. d, e->chosen_by_version, t);
  3458. next = &(line->next);
  3459. }
  3460. });
  3461. if (!get_options()->AvoidDiskWrites)
  3462. or_state_mark_dirty(get_or_state(), 0);
  3463. entry_guards_dirty = 0;
  3464. }
  3465. /** If <b>question</b> is the string "entry-guards", then dump
  3466. * to *<b>answer</b> a newly allocated string describing all of
  3467. * the nodes in the global entry_guards list. See control-spec.txt
  3468. * for details.
  3469. * For backward compatibility, we also handle the string "helper-nodes".
  3470. * */
  3471. int
  3472. getinfo_helper_entry_guards(control_connection_t *conn,
  3473. const char *question, char **answer)
  3474. {
  3475. (void) conn;
  3476. if (!strcmp(question,"entry-guards") ||
  3477. !strcmp(question,"helper-nodes")) {
  3478. smartlist_t *sl = smartlist_create();
  3479. char tbuf[ISO_TIME_LEN+1];
  3480. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  3481. if (!entry_guards)
  3482. entry_guards = smartlist_create();
  3483. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
  3484. size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
  3485. char *c = tor_malloc(len);
  3486. const char *status = NULL;
  3487. time_t when = 0;
  3488. routerinfo_t *ri;
  3489. if (!e->made_contact) {
  3490. status = "never-connected";
  3491. } else if (e->bad_since) {
  3492. when = e->bad_since;
  3493. status = "unusable";
  3494. } else {
  3495. status = "up";
  3496. }
  3497. ri = router_get_by_digest(e->identity);
  3498. if (ri) {
  3499. router_get_verbose_nickname(nbuf, ri);
  3500. } else {
  3501. nbuf[0] = '$';
  3502. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  3503. /* e->nickname field is not very reliable if we don't know about
  3504. * this router any longer; don't include it. */
  3505. }
  3506. if (when) {
  3507. format_iso_time(tbuf, when);
  3508. tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
  3509. } else {
  3510. tor_snprintf(c, len, "%s %s\n", nbuf, status);
  3511. }
  3512. smartlist_add(sl, c);
  3513. } SMARTLIST_FOREACH_END(e);
  3514. *answer = smartlist_join_strings(sl, "", 0, NULL);
  3515. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  3516. smartlist_free(sl);
  3517. }
  3518. return 0;
  3519. }
  3520. /** Information about a configured bridge. Currently this just matches the
  3521. * ones in the torrc file, but one day we may be able to learn about new
  3522. * bridges on our own, and remember them in the state file. */
  3523. typedef struct {
  3524. /** Address of the bridge. */
  3525. tor_addr_t addr;
  3526. /** TLS port for the bridge. */
  3527. uint16_t port;
  3528. /** Expected identity digest, or all zero bytes if we don't know what the
  3529. * digest should be. */
  3530. char identity[DIGEST_LEN];
  3531. /** When should we next try to fetch a descriptor for this bridge? */
  3532. download_status_t fetch_status;
  3533. } bridge_info_t;
  3534. /** A list of configured bridges. Whenever we actually get a descriptor
  3535. * for one, we add it as an entry guard. */
  3536. static smartlist_t *bridge_list = NULL;
  3537. /** Initialize the bridge list to empty, creating it if needed. */
  3538. void
  3539. clear_bridge_list(void)
  3540. {
  3541. if (!bridge_list)
  3542. bridge_list = smartlist_create();
  3543. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, tor_free(b));
  3544. smartlist_clear(bridge_list);
  3545. }
  3546. /** Return a bridge pointer if <b>ri</b> is one of our known bridges
  3547. * (either by comparing keys if possible, else by comparing addr/port).
  3548. * Else return NULL. */
  3549. static bridge_info_t *
  3550. routerinfo_get_configured_bridge(routerinfo_t *ri)
  3551. {
  3552. if (!bridge_list)
  3553. return NULL;
  3554. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  3555. {
  3556. if (tor_digest_is_zero(bridge->identity) &&
  3557. tor_addr_eq_ipv4h(&bridge->addr, ri->addr) &&
  3558. bridge->port == ri->or_port)
  3559. return bridge;
  3560. if (!memcmp(bridge->identity, ri->cache_info.identity_digest,
  3561. DIGEST_LEN))
  3562. return bridge;
  3563. }
  3564. SMARTLIST_FOREACH_END(bridge);
  3565. return NULL;
  3566. }
  3567. /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
  3568. int
  3569. routerinfo_is_a_configured_bridge(routerinfo_t *ri)
  3570. {
  3571. return routerinfo_get_configured_bridge(ri) ? 1 : 0;
  3572. }
  3573. /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
  3574. * is set, it tells us the identity key too. */
  3575. void
  3576. bridge_add_from_config(const tor_addr_t *addr, uint16_t port, char *digest)
  3577. {
  3578. bridge_info_t *b = tor_malloc_zero(sizeof(bridge_info_t));
  3579. tor_addr_copy(&b->addr, addr);
  3580. b->port = port;
  3581. if (digest)
  3582. memcpy(b->identity, digest, DIGEST_LEN);
  3583. b->fetch_status.schedule = DL_SCHED_BRIDGE;
  3584. if (!bridge_list)
  3585. bridge_list = smartlist_create();
  3586. smartlist_add(bridge_list, b);
  3587. }
  3588. /** If <b>digest</b> is one of our known bridges, return it. */
  3589. static bridge_info_t *
  3590. find_bridge_by_digest(const char *digest)
  3591. {
  3592. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  3593. {
  3594. if (!memcmp(bridge->identity, digest, DIGEST_LEN))
  3595. return bridge;
  3596. });
  3597. return NULL;
  3598. }
  3599. /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
  3600. * is a helpful string describing this bridge. */
  3601. static void
  3602. launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
  3603. {
  3604. char *address;
  3605. if (connection_get_by_type_addr_port_purpose(
  3606. CONN_TYPE_DIR, &bridge->addr, bridge->port,
  3607. DIR_PURPOSE_FETCH_SERVERDESC))
  3608. return; /* it's already on the way */
  3609. address = tor_dup_addr(&bridge->addr);
  3610. directory_initiate_command(address, &bridge->addr,
  3611. bridge->port, 0,
  3612. 0, /* does not matter */
  3613. 1, bridge->identity,
  3614. DIR_PURPOSE_FETCH_SERVERDESC,
  3615. ROUTER_PURPOSE_BRIDGE,
  3616. 0, "authority.z", NULL, 0, 0);
  3617. tor_free(address);
  3618. }
  3619. /** Fetching the bridge descriptor from the bridge authority returned a
  3620. * "not found". Fall back to trying a direct fetch. */
  3621. void
  3622. retry_bridge_descriptor_fetch_directly(const char *digest)
  3623. {
  3624. bridge_info_t *bridge = find_bridge_by_digest(digest);
  3625. if (!bridge)
  3626. return; /* not found? oh well. */
  3627. launch_direct_bridge_descriptor_fetch(bridge);
  3628. }
  3629. /** For each bridge in our list for which we don't currently have a
  3630. * descriptor, fetch a new copy of its descriptor -- either directly
  3631. * from the bridge or via a bridge authority. */
  3632. void
  3633. fetch_bridge_descriptors(time_t now)
  3634. {
  3635. or_options_t *options = get_options();
  3636. int num_bridge_auths = get_n_authorities(BRIDGE_AUTHORITY);
  3637. int ask_bridge_directly;
  3638. int can_use_bridge_authority;
  3639. if (!bridge_list)
  3640. return;
  3641. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  3642. {
  3643. if (!download_status_is_ready(&bridge->fetch_status, now,
  3644. IMPOSSIBLE_TO_DOWNLOAD))
  3645. continue; /* don't bother, no need to retry yet */
  3646. /* schedule another fetch as if this one will fail, in case it does */
  3647. download_status_failed(&bridge->fetch_status, 0);
  3648. can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
  3649. num_bridge_auths;
  3650. ask_bridge_directly = !can_use_bridge_authority ||
  3651. !options->UpdateBridgesFromAuthority;
  3652. log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
  3653. ask_bridge_directly, tor_digest_is_zero(bridge->identity),
  3654. !options->UpdateBridgesFromAuthority, !num_bridge_auths);
  3655. if (ask_bridge_directly &&
  3656. !fascist_firewall_allows_address_or(&bridge->addr, bridge->port)) {
  3657. log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
  3658. "firewall policy. %s.", fmt_addr(&bridge->addr),
  3659. bridge->port,
  3660. can_use_bridge_authority ?
  3661. "Asking bridge authority instead" : "Skipping");
  3662. if (can_use_bridge_authority)
  3663. ask_bridge_directly = 0;
  3664. else
  3665. continue;
  3666. }
  3667. if (ask_bridge_directly) {
  3668. /* we need to ask the bridge itself for its descriptor. */
  3669. launch_direct_bridge_descriptor_fetch(bridge);
  3670. } else {
  3671. /* We have a digest and we want to ask an authority. We could
  3672. * combine all the requests into one, but that may give more
  3673. * hints to the bridge authority than we want to give. */
  3674. char resource[10 + HEX_DIGEST_LEN];
  3675. memcpy(resource, "fp/", 3);
  3676. base16_encode(resource+3, HEX_DIGEST_LEN+1,
  3677. bridge->identity, DIGEST_LEN);
  3678. memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
  3679. log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
  3680. resource);
  3681. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  3682. ROUTER_PURPOSE_BRIDGE, resource, 0);
  3683. }
  3684. }
  3685. SMARTLIST_FOREACH_END(bridge);
  3686. }
  3687. /** We just learned a descriptor for a bridge. See if that
  3688. * digest is in our entry guard list, and add it if not. */
  3689. void
  3690. learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
  3691. {
  3692. tor_assert(ri);
  3693. tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
  3694. if (get_options()->UseBridges) {
  3695. int first = !any_bridge_descriptors_known();
  3696. bridge_info_t *bridge = routerinfo_get_configured_bridge(ri);
  3697. time_t now = time(NULL);
  3698. ri->is_running = 1;
  3699. if (bridge) { /* if we actually want to use this one */
  3700. /* it's here; schedule its re-fetch for a long time from now. */
  3701. if (!from_cache)
  3702. download_status_reset(&bridge->fetch_status);
  3703. add_an_entry_guard(ri, 1);
  3704. log_notice(LD_DIR, "new bridge descriptor '%s' (%s)", ri->nickname,
  3705. from_cache ? "cached" : "fresh");
  3706. if (first)
  3707. routerlist_retry_directory_downloads(now);
  3708. }
  3709. }
  3710. }
  3711. /** Return 1 if any of our entry guards have descriptors that
  3712. * are marked with purpose 'bridge' and are running. Else return 0.
  3713. *
  3714. * We use this function to decide if we're ready to start building
  3715. * circuits through our bridges, or if we need to wait until the
  3716. * directory "server/authority" requests finish. */
  3717. int
  3718. any_bridge_descriptors_known(void)
  3719. {
  3720. tor_assert(get_options()->UseBridges);
  3721. return choose_random_entry(NULL)!=NULL ? 1 : 0;
  3722. }
  3723. /** Return 1 if there are any directory conns fetching bridge descriptors
  3724. * that aren't marked for close. We use this to guess if we should tell
  3725. * the controller that we have a problem. */
  3726. int
  3727. any_pending_bridge_descriptor_fetches(void)
  3728. {
  3729. smartlist_t *conns = get_connection_array();
  3730. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3731. {
  3732. if (conn->type == CONN_TYPE_DIR &&
  3733. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  3734. TO_DIR_CONN(conn)->router_purpose == ROUTER_PURPOSE_BRIDGE &&
  3735. !conn->marked_for_close &&
  3736. conn->linked && !conn->linked_conn->marked_for_close) {
  3737. log_debug(LD_DIR, "found one: %s", conn->address);
  3738. return 1;
  3739. }
  3740. });
  3741. return 0;
  3742. }
  3743. /** Return 1 if we have at least one descriptor for a bridge and
  3744. * all descriptors we know are down. Else return 0. If <b>act</b> is
  3745. * 1, then mark the down bridges up; else just observe and report. */
  3746. static int
  3747. bridges_retry_helper(int act)
  3748. {
  3749. routerinfo_t *ri;
  3750. int any_known = 0;
  3751. int any_running = 0;
  3752. if (!entry_guards)
  3753. entry_guards = smartlist_create();
  3754. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  3755. {
  3756. ri = router_get_by_digest(e->identity);
  3757. if (ri && ri->purpose == ROUTER_PURPOSE_BRIDGE) {
  3758. any_known = 1;
  3759. if (ri->is_running)
  3760. any_running = 1; /* some bridge is both known and running */
  3761. else if (act) { /* mark it for retry */
  3762. ri->is_running = 1;
  3763. e->can_retry = 1;
  3764. e->bad_since = 0;
  3765. }
  3766. }
  3767. });
  3768. log_debug(LD_DIR, "any_known %d, any_running %d", any_known, any_running);
  3769. return any_known && !any_running;
  3770. }
  3771. /** Do we know any descriptors for our bridges, and are they all
  3772. * down? */
  3773. int
  3774. bridges_known_but_down(void)
  3775. {
  3776. return bridges_retry_helper(0);
  3777. }
  3778. /** Mark all down known bridges up. */
  3779. void
  3780. bridges_retry_all(void)
  3781. {
  3782. bridges_retry_helper(1);
  3783. }
  3784. /** Release all storage held by the list of entry guards and related
  3785. * memory structs. */
  3786. void
  3787. entry_guards_free_all(void)
  3788. {
  3789. if (entry_guards) {
  3790. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  3791. entry_guard_free(e));
  3792. smartlist_free(entry_guards);
  3793. entry_guards = NULL;
  3794. }
  3795. clear_bridge_list();
  3796. smartlist_free(bridge_list);
  3797. bridge_list = NULL;
  3798. }