circuitbuild.c 134 KB

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