circuitbuild.c 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171
  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-2011, 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 "circuitbuild.h"
  13. #include "circuitlist.h"
  14. #include "circuituse.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "connection_edge.h"
  18. #include "connection_or.h"
  19. #include "control.h"
  20. #include "directory.h"
  21. #include "main.h"
  22. #include "networkstatus.h"
  23. #include "nodelist.h"
  24. #include "onion.h"
  25. #include "policies.h"
  26. #include "relay.h"
  27. #include "rephist.h"
  28. #include "router.h"
  29. #include "routerlist.h"
  30. #include "routerparse.h"
  31. #include "crypto.h"
  32. #undef log
  33. #include <math.h>
  34. #ifndef MIN
  35. #define MIN(a,b) ((a)<(b)?(a):(b))
  36. #endif
  37. #define CBT_BIN_TO_MS(bin) ((bin)*CBT_BIN_WIDTH + (CBT_BIN_WIDTH/2))
  38. /********* START VARIABLES **********/
  39. /** Global list of circuit build times */
  40. // XXXX023: Add this as a member for entry_guard_t instead of global?
  41. // Then we could do per-guard statistics, as guards are likely to
  42. // vary in their own latency. The downside of this is that guards
  43. // can change frequently, so we'd be building a lot more circuits
  44. // most likely.
  45. /* XXXX023 Make this static; add accessor functions. */
  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 node_t, since we want to remember these even when we
  52. * don't have any directory info. */
  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. /** Information about a configured bridge. Currently this just matches the
  74. * ones in the torrc file, but one day we may be able to learn about new
  75. * bridges on our own, and remember them in the state file. */
  76. typedef struct {
  77. /** Address of the bridge. */
  78. tor_addr_t addr;
  79. /** TLS port for the bridge. */
  80. uint16_t port;
  81. /** Boolean: We are re-parsing our bridge list, and we are going to remove
  82. * this one if we don't find it in the list of configured bridges. */
  83. unsigned marked_for_removal : 1;
  84. /** Expected identity digest, or all zero bytes if we don't know what the
  85. * digest should be. */
  86. char identity[DIGEST_LEN];
  87. /** Name of pluggable transport protocol taken from its config line. */
  88. char *transport_name;
  89. /** When should we next try to fetch a descriptor for this bridge? */
  90. download_status_t fetch_status;
  91. } bridge_info_t;
  92. /** A list of our chosen entry guards. */
  93. static smartlist_t *entry_guards = NULL;
  94. /** A value of 1 means that the entry_guards list has changed
  95. * and those changes need to be flushed to disk. */
  96. static int entry_guards_dirty = 0;
  97. /** If set, we're running the unit tests: we should avoid clobbering
  98. * our state file or accessing get_options() or get_or_state() */
  99. static int unit_tests = 0;
  100. /********* END VARIABLES ************/
  101. static int circuit_deliver_create_cell(circuit_t *circ,
  102. uint8_t cell_type, const char *payload);
  103. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  104. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  105. static int onion_extend_cpath(origin_circuit_t *circ);
  106. static int count_acceptable_nodes(smartlist_t *routers);
  107. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  108. static void entry_guards_changed(void);
  109. static const transport_t *transport_get_by_name(const char *name);
  110. static void transport_free(transport_t *transport);
  111. static void bridge_free(bridge_info_t *bridge);
  112. /**
  113. * This function decides if CBT learning should be disabled. It returns
  114. * true if one or more of the following four conditions are met:
  115. *
  116. * 1. If the cbtdisabled consensus parameter is set.
  117. * 2. If the torrc option LearnCircuitBuildTimeout is false.
  118. * 3. If we are a directory authority
  119. * 4. If we fail to write circuit build time history to our state file.
  120. */
  121. static int
  122. circuit_build_times_disabled(void)
  123. {
  124. if (unit_tests) {
  125. return 0;
  126. } else {
  127. int consensus_disabled = networkstatus_get_param(NULL, "cbtdisabled",
  128. 0, 0, 1);
  129. int config_disabled = !get_options()->LearnCircuitBuildTimeout;
  130. int dirauth_disabled = get_options()->AuthoritativeDir;
  131. int state_disabled = did_last_state_file_write_fail() ? 1 : 0;
  132. if (consensus_disabled || config_disabled || dirauth_disabled ||
  133. state_disabled) {
  134. log_info(LD_CIRC,
  135. "CircuitBuildTime learning is disabled. "
  136. "Consensus=%d, Config=%d, AuthDir=%d, StateFile=%d",
  137. consensus_disabled, config_disabled, dirauth_disabled,
  138. state_disabled);
  139. return 1;
  140. } else {
  141. return 0;
  142. }
  143. }
  144. }
  145. /**
  146. * Retrieve and bounds-check the cbtmaxtimeouts consensus paramter.
  147. *
  148. * Effect: When this many timeouts happen in the last 'cbtrecentcount'
  149. * circuit attempts, the client should discard all of its history and
  150. * begin learning a fresh timeout value.
  151. */
  152. static int32_t
  153. circuit_build_times_max_timeouts(void)
  154. {
  155. return networkstatus_get_param(NULL, "cbtmaxtimeouts",
  156. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT,
  157. CBT_MIN_MAX_RECENT_TIMEOUT_COUNT,
  158. CBT_MAX_MAX_RECENT_TIMEOUT_COUNT);
  159. }
  160. /**
  161. * Retrieve and bounds-check the cbtnummodes consensus paramter.
  162. *
  163. * Effect: This value governs how many modes to use in the weighted
  164. * average calculation of Pareto parameter Xm. A value of 3 introduces
  165. * some bias (2-5% of CDF) under ideal conditions, but allows for better
  166. * performance in the event that a client chooses guard nodes of radically
  167. * different performance characteristics.
  168. */
  169. static int32_t
  170. circuit_build_times_default_num_xm_modes(void)
  171. {
  172. int32_t num = networkstatus_get_param(NULL, "cbtnummodes",
  173. CBT_DEFAULT_NUM_XM_MODES,
  174. CBT_MIN_NUM_XM_MODES,
  175. CBT_MAX_NUM_XM_MODES);
  176. return num;
  177. }
  178. /**
  179. * Retrieve and bounds-check the cbtmincircs consensus paramter.
  180. *
  181. * Effect: This is the minimum number of circuits to build before
  182. * computing a timeout.
  183. */
  184. static int32_t
  185. circuit_build_times_min_circs_to_observe(void)
  186. {
  187. int32_t num = networkstatus_get_param(NULL, "cbtmincircs",
  188. CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE,
  189. CBT_MIN_MIN_CIRCUITS_TO_OBSERVE,
  190. CBT_MAX_MIN_CIRCUITS_TO_OBSERVE);
  191. return num;
  192. }
  193. /** Return true iff <b>cbt</b> has recorded enough build times that we
  194. * want to start acting on the timeout it implies. */
  195. int
  196. circuit_build_times_enough_to_compute(circuit_build_times_t *cbt)
  197. {
  198. return cbt->total_build_times >= circuit_build_times_min_circs_to_observe();
  199. }
  200. /**
  201. * Retrieve and bounds-check the cbtquantile consensus paramter.
  202. *
  203. * Effect: This is the position on the quantile curve to use to set the
  204. * timeout value. It is a percent (10-99).
  205. */
  206. double
  207. circuit_build_times_quantile_cutoff(void)
  208. {
  209. int32_t num = networkstatus_get_param(NULL, "cbtquantile",
  210. CBT_DEFAULT_QUANTILE_CUTOFF,
  211. CBT_MIN_QUANTILE_CUTOFF,
  212. CBT_MAX_QUANTILE_CUTOFF);
  213. return num/100.0;
  214. }
  215. int
  216. circuit_build_times_get_bw_scale(networkstatus_t *ns)
  217. {
  218. return networkstatus_get_param(ns, "bwweightscale",
  219. BW_WEIGHT_SCALE,
  220. BW_MIN_WEIGHT_SCALE,
  221. BW_MAX_WEIGHT_SCALE);
  222. }
  223. /**
  224. * Retrieve and bounds-check the cbtclosequantile consensus paramter.
  225. *
  226. * Effect: This is the position on the quantile curve to use to set the
  227. * timeout value to use to actually close circuits. It is a percent
  228. * (0-99).
  229. */
  230. static double
  231. circuit_build_times_close_quantile(void)
  232. {
  233. int32_t param;
  234. /* Cast is safe - circuit_build_times_quantile_cutoff() is capped */
  235. int32_t min = (int)tor_lround(100*circuit_build_times_quantile_cutoff());
  236. param = networkstatus_get_param(NULL, "cbtclosequantile",
  237. CBT_DEFAULT_CLOSE_QUANTILE,
  238. CBT_MIN_CLOSE_QUANTILE,
  239. CBT_MAX_CLOSE_QUANTILE);
  240. if (param < min) {
  241. log_warn(LD_DIR, "Consensus parameter cbtclosequantile is "
  242. "too small, raising to %d", min);
  243. param = min;
  244. }
  245. return param / 100.0;
  246. }
  247. /**
  248. * Retrieve and bounds-check the cbttestfreq consensus paramter.
  249. *
  250. * Effect: Describes how often in seconds to build a test circuit to
  251. * gather timeout values. Only applies if less than 'cbtmincircs'
  252. * have been recorded.
  253. */
  254. static int32_t
  255. circuit_build_times_test_frequency(void)
  256. {
  257. int32_t num = networkstatus_get_param(NULL, "cbttestfreq",
  258. CBT_DEFAULT_TEST_FREQUENCY,
  259. CBT_MIN_TEST_FREQUENCY,
  260. CBT_MAX_TEST_FREQUENCY);
  261. return num;
  262. }
  263. /**
  264. * Retrieve and bounds-check the cbtmintimeout consensus parameter.
  265. *
  266. * Effect: This is the minimum allowed timeout value in milliseconds.
  267. * The minimum is to prevent rounding to 0 (we only check once
  268. * per second).
  269. */
  270. static int32_t
  271. circuit_build_times_min_timeout(void)
  272. {
  273. int32_t num = networkstatus_get_param(NULL, "cbtmintimeout",
  274. CBT_DEFAULT_TIMEOUT_MIN_VALUE,
  275. CBT_MIN_TIMEOUT_MIN_VALUE,
  276. CBT_MAX_TIMEOUT_MIN_VALUE);
  277. return num;
  278. }
  279. /**
  280. * Retrieve and bounds-check the cbtinitialtimeout consensus paramter.
  281. *
  282. * Effect: This is the timeout value to use before computing a timeout,
  283. * in milliseconds.
  284. */
  285. int32_t
  286. circuit_build_times_initial_timeout(void)
  287. {
  288. int32_t min = circuit_build_times_min_timeout();
  289. int32_t param = networkstatus_get_param(NULL, "cbtinitialtimeout",
  290. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE,
  291. CBT_MIN_TIMEOUT_INITIAL_VALUE,
  292. CBT_MAX_TIMEOUT_INITIAL_VALUE);
  293. if (param < min) {
  294. log_warn(LD_DIR, "Consensus parameter cbtinitialtimeout is too small, "
  295. "raising to %d", min);
  296. param = min;
  297. }
  298. return param;
  299. }
  300. /**
  301. * Retrieve and bounds-check the cbtrecentcount consensus paramter.
  302. *
  303. * Effect: This is the number of circuit build times to keep track of
  304. * for deciding if we hit cbtmaxtimeouts and need to reset our state
  305. * and learn a new timeout.
  306. */
  307. static int32_t
  308. circuit_build_times_recent_circuit_count(networkstatus_t *ns)
  309. {
  310. return networkstatus_get_param(ns, "cbtrecentcount",
  311. CBT_DEFAULT_RECENT_CIRCUITS,
  312. CBT_MIN_RECENT_CIRCUITS,
  313. CBT_MAX_RECENT_CIRCUITS);
  314. }
  315. /**
  316. * This function is called when we get a consensus update.
  317. *
  318. * It checks to see if we have changed any consensus parameters
  319. * that require reallocation or discard of previous stats.
  320. */
  321. void
  322. circuit_build_times_new_consensus_params(circuit_build_times_t *cbt,
  323. networkstatus_t *ns)
  324. {
  325. int32_t num = circuit_build_times_recent_circuit_count(ns);
  326. if (num > 0 && num != cbt->liveness.num_recent_circs) {
  327. int8_t *recent_circs;
  328. log_notice(LD_CIRC, "The Tor Directory Consensus has changed how many "
  329. "circuits we must track to detect network failures from %d "
  330. "to %d.", cbt->liveness.num_recent_circs, num);
  331. tor_assert(cbt->liveness.timeouts_after_firsthop);
  332. /*
  333. * Technically this is a circular array that we are reallocating
  334. * and memcopying. However, since it only consists of either 1s
  335. * or 0s, and is only used in a statistical test to determine when
  336. * we should discard our history after a sufficient number of 1's
  337. * have been reached, it is fine if order is not preserved or
  338. * elements are lost.
  339. *
  340. * cbtrecentcount should only be changing in cases of severe network
  341. * distress anyway, so memory correctness here is paramount over
  342. * doing acrobatics to preserve the array.
  343. */
  344. recent_circs = tor_malloc_zero(sizeof(int8_t)*num);
  345. memcpy(recent_circs, cbt->liveness.timeouts_after_firsthop,
  346. sizeof(int8_t)*MIN(num, cbt->liveness.num_recent_circs));
  347. // Adjust the index if it needs it.
  348. if (num < cbt->liveness.num_recent_circs) {
  349. cbt->liveness.after_firsthop_idx = MIN(num-1,
  350. cbt->liveness.after_firsthop_idx);
  351. }
  352. tor_free(cbt->liveness.timeouts_after_firsthop);
  353. cbt->liveness.timeouts_after_firsthop = recent_circs;
  354. cbt->liveness.num_recent_circs = num;
  355. }
  356. }
  357. /** Make a note that we're running unit tests (rather than running Tor
  358. * itself), so we avoid clobbering our state file. */
  359. void
  360. circuitbuild_running_unit_tests(void)
  361. {
  362. unit_tests = 1;
  363. }
  364. /**
  365. * Return the initial default or configured timeout in milliseconds
  366. */
  367. static double
  368. circuit_build_times_get_initial_timeout(void)
  369. {
  370. double timeout;
  371. if (!unit_tests && get_options()->CircuitBuildTimeout) {
  372. timeout = get_options()->CircuitBuildTimeout*1000;
  373. if (timeout < circuit_build_times_min_timeout()) {
  374. log_warn(LD_CIRC, "Config CircuitBuildTimeout too low. Setting to %ds",
  375. circuit_build_times_min_timeout()/1000);
  376. timeout = circuit_build_times_min_timeout();
  377. }
  378. } else {
  379. timeout = circuit_build_times_initial_timeout();
  380. }
  381. return timeout;
  382. }
  383. /**
  384. * Reset the build time state.
  385. *
  386. * Leave estimated parameters, timeout and network liveness intact
  387. * for future use.
  388. */
  389. void
  390. circuit_build_times_reset(circuit_build_times_t *cbt)
  391. {
  392. memset(cbt->circuit_build_times, 0, sizeof(cbt->circuit_build_times));
  393. cbt->total_build_times = 0;
  394. cbt->build_times_idx = 0;
  395. cbt->have_computed_timeout = 0;
  396. }
  397. /**
  398. * Initialize the buildtimes structure for first use.
  399. *
  400. * Sets the initial timeout values based on either the config setting,
  401. * the consensus param, or the default (CBT_DEFAULT_TIMEOUT_INITIAL_VALUE).
  402. */
  403. void
  404. circuit_build_times_init(circuit_build_times_t *cbt)
  405. {
  406. memset(cbt, 0, sizeof(*cbt));
  407. cbt->liveness.num_recent_circs =
  408. circuit_build_times_recent_circuit_count(NULL);
  409. cbt->liveness.timeouts_after_firsthop = tor_malloc_zero(sizeof(int8_t)*
  410. cbt->liveness.num_recent_circs);
  411. cbt->close_ms = cbt->timeout_ms = circuit_build_times_get_initial_timeout();
  412. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  413. }
  414. #if 0
  415. /**
  416. * Rewind our build time history by n positions.
  417. */
  418. static void
  419. circuit_build_times_rewind_history(circuit_build_times_t *cbt, int n)
  420. {
  421. int i = 0;
  422. cbt->build_times_idx -= n;
  423. cbt->build_times_idx %= CBT_NCIRCUITS_TO_OBSERVE;
  424. for (i = 0; i < n; i++) {
  425. cbt->circuit_build_times[(i+cbt->build_times_idx)
  426. %CBT_NCIRCUITS_TO_OBSERVE]=0;
  427. }
  428. if (cbt->total_build_times > n) {
  429. cbt->total_build_times -= n;
  430. } else {
  431. cbt->total_build_times = 0;
  432. }
  433. log_info(LD_CIRC,
  434. "Rewound history by %d places. Current index: %d. "
  435. "Total: %d", n, cbt->build_times_idx, cbt->total_build_times);
  436. }
  437. #endif
  438. /**
  439. * Add a new build time value <b>time</b> to the set of build times. Time
  440. * units are milliseconds.
  441. *
  442. * circuit_build_times <b>cbt</b> is a circular array, so loop around when
  443. * array is full.
  444. */
  445. int
  446. circuit_build_times_add_time(circuit_build_times_t *cbt, build_time_t time)
  447. {
  448. if (time <= 0 || time > CBT_BUILD_TIME_MAX) {
  449. log_warn(LD_BUG, "Circuit build time is too large (%u)."
  450. "This is probably a bug.", time);
  451. tor_fragile_assert();
  452. return -1;
  453. }
  454. log_debug(LD_CIRC, "Adding circuit build time %u", time);
  455. cbt->circuit_build_times[cbt->build_times_idx] = time;
  456. cbt->build_times_idx = (cbt->build_times_idx + 1) % CBT_NCIRCUITS_TO_OBSERVE;
  457. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  458. cbt->total_build_times++;
  459. if ((cbt->total_build_times % CBT_SAVE_STATE_EVERY) == 0) {
  460. /* Save state every n circuit builds */
  461. if (!unit_tests && !get_options()->AvoidDiskWrites)
  462. or_state_mark_dirty(get_or_state(), 0);
  463. }
  464. return 0;
  465. }
  466. /**
  467. * Return maximum circuit build time
  468. */
  469. static build_time_t
  470. circuit_build_times_max(circuit_build_times_t *cbt)
  471. {
  472. int i = 0;
  473. build_time_t max_build_time = 0;
  474. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  475. if (cbt->circuit_build_times[i] > max_build_time
  476. && cbt->circuit_build_times[i] != CBT_BUILD_ABANDONED)
  477. max_build_time = cbt->circuit_build_times[i];
  478. }
  479. return max_build_time;
  480. }
  481. #if 0
  482. /** Return minimum circuit build time */
  483. build_time_t
  484. circuit_build_times_min(circuit_build_times_t *cbt)
  485. {
  486. int i = 0;
  487. build_time_t min_build_time = CBT_BUILD_TIME_MAX;
  488. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  489. if (cbt->circuit_build_times[i] && /* 0 <-> uninitialized */
  490. cbt->circuit_build_times[i] < min_build_time)
  491. min_build_time = cbt->circuit_build_times[i];
  492. }
  493. if (min_build_time == CBT_BUILD_TIME_MAX) {
  494. log_warn(LD_CIRC, "No build times less than CBT_BUILD_TIME_MAX!");
  495. }
  496. return min_build_time;
  497. }
  498. #endif
  499. /**
  500. * Calculate and return a histogram for the set of build times.
  501. *
  502. * Returns an allocated array of histrogram bins representing
  503. * the frequency of index*CBT_BIN_WIDTH millisecond
  504. * build times. Also outputs the number of bins in nbins.
  505. *
  506. * The return value must be freed by the caller.
  507. */
  508. static uint32_t *
  509. circuit_build_times_create_histogram(circuit_build_times_t *cbt,
  510. build_time_t *nbins)
  511. {
  512. uint32_t *histogram;
  513. build_time_t max_build_time = circuit_build_times_max(cbt);
  514. int i, c;
  515. *nbins = 1 + (max_build_time / CBT_BIN_WIDTH);
  516. histogram = tor_malloc_zero(*nbins * sizeof(build_time_t));
  517. // calculate histogram
  518. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  519. if (cbt->circuit_build_times[i] == 0
  520. || cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  521. continue; /* 0 <-> uninitialized */
  522. c = (cbt->circuit_build_times[i] / CBT_BIN_WIDTH);
  523. histogram[c]++;
  524. }
  525. return histogram;
  526. }
  527. /**
  528. * Return the Pareto start-of-curve parameter Xm.
  529. *
  530. * Because we are not a true Pareto curve, we compute this as the
  531. * weighted average of the N most frequent build time bins. N is either
  532. * 1 if we don't have enough circuit build time data collected, or
  533. * determined by the consensus parameter cbtnummodes (default 3).
  534. */
  535. static build_time_t
  536. circuit_build_times_get_xm(circuit_build_times_t *cbt)
  537. {
  538. build_time_t i, nbins;
  539. build_time_t *nth_max_bin;
  540. int32_t bin_counts=0;
  541. build_time_t ret = 0;
  542. uint32_t *histogram = circuit_build_times_create_histogram(cbt, &nbins);
  543. int n=0;
  544. int num_modes = circuit_build_times_default_num_xm_modes();
  545. tor_assert(nbins > 0);
  546. tor_assert(num_modes > 0);
  547. // Only use one mode if < 1000 buildtimes. Not enough data
  548. // for multiple.
  549. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  550. num_modes = 1;
  551. nth_max_bin = (build_time_t*)tor_malloc_zero(num_modes*sizeof(build_time_t));
  552. /* Determine the N most common build times */
  553. for (i = 0; i < nbins; i++) {
  554. if (histogram[i] >= histogram[nth_max_bin[0]]) {
  555. nth_max_bin[0] = i;
  556. }
  557. for (n = 1; n < num_modes; n++) {
  558. if (histogram[i] >= histogram[nth_max_bin[n]] &&
  559. (!histogram[nth_max_bin[n-1]]
  560. || histogram[i] < histogram[nth_max_bin[n-1]])) {
  561. nth_max_bin[n] = i;
  562. }
  563. }
  564. }
  565. for (n = 0; n < num_modes; n++) {
  566. bin_counts += histogram[nth_max_bin[n]];
  567. ret += CBT_BIN_TO_MS(nth_max_bin[n])*histogram[nth_max_bin[n]];
  568. log_info(LD_CIRC, "Xm mode #%d: %u %u", n, CBT_BIN_TO_MS(nth_max_bin[n]),
  569. histogram[nth_max_bin[n]]);
  570. }
  571. /* The following assert is safe, because we don't get called when we
  572. * haven't observed at least CBT_MIN_MIN_CIRCUITS_TO_OBSERVE circuits. */
  573. tor_assert(bin_counts > 0);
  574. ret /= bin_counts;
  575. tor_free(histogram);
  576. tor_free(nth_max_bin);
  577. return ret;
  578. }
  579. /**
  580. * Output a histogram of current circuit build times to
  581. * the or_state_t state structure.
  582. */
  583. void
  584. circuit_build_times_update_state(circuit_build_times_t *cbt,
  585. or_state_t *state)
  586. {
  587. uint32_t *histogram;
  588. build_time_t i = 0;
  589. build_time_t nbins = 0;
  590. config_line_t **next, *line;
  591. histogram = circuit_build_times_create_histogram(cbt, &nbins);
  592. // write to state
  593. config_free_lines(state->BuildtimeHistogram);
  594. next = &state->BuildtimeHistogram;
  595. *next = NULL;
  596. state->TotalBuildTimes = cbt->total_build_times;
  597. state->CircuitBuildAbandonedCount = 0;
  598. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  599. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  600. state->CircuitBuildAbandonedCount++;
  601. }
  602. for (i = 0; i < nbins; i++) {
  603. // compress the histogram by skipping the blanks
  604. if (histogram[i] == 0) continue;
  605. *next = line = tor_malloc_zero(sizeof(config_line_t));
  606. line->key = tor_strdup("CircuitBuildTimeBin");
  607. line->value = tor_malloc(25);
  608. tor_snprintf(line->value, 25, "%d %d",
  609. CBT_BIN_TO_MS(i), histogram[i]);
  610. next = &(line->next);
  611. }
  612. if (!unit_tests) {
  613. if (!get_options()->AvoidDiskWrites)
  614. or_state_mark_dirty(get_or_state(), 0);
  615. }
  616. tor_free(histogram);
  617. }
  618. /**
  619. * Shuffle the build times array.
  620. *
  621. * Adapted from http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  622. */
  623. static void
  624. circuit_build_times_shuffle_and_store_array(circuit_build_times_t *cbt,
  625. build_time_t *raw_times,
  626. uint32_t num_times)
  627. {
  628. uint32_t n = num_times;
  629. if (num_times > CBT_NCIRCUITS_TO_OBSERVE) {
  630. log_notice(LD_CIRC, "The number of circuit times that this Tor version "
  631. "uses to calculate build times is less than the number stored "
  632. "in your state file. Decreasing the circuit time history from "
  633. "%lu to %d.", (unsigned long)num_times,
  634. CBT_NCIRCUITS_TO_OBSERVE);
  635. }
  636. if (n > INT_MAX-1) {
  637. log_warn(LD_CIRC, "For some insane reasons, you had %lu circuit build "
  638. "observations in your state file. That's far too many; probably "
  639. "there's a bug here.", (unsigned long)n);
  640. n = INT_MAX-1;
  641. }
  642. /* This code can only be run on a compact array */
  643. while (n-- > 1) {
  644. int k = crypto_rand_int(n + 1); /* 0 <= k <= n. */
  645. build_time_t tmp = raw_times[k];
  646. raw_times[k] = raw_times[n];
  647. raw_times[n] = tmp;
  648. }
  649. /* Since the times are now shuffled, take a random CBT_NCIRCUITS_TO_OBSERVE
  650. * subset (ie the first CBT_NCIRCUITS_TO_OBSERVE values) */
  651. for (n = 0; n < MIN(num_times, CBT_NCIRCUITS_TO_OBSERVE); n++) {
  652. circuit_build_times_add_time(cbt, raw_times[n]);
  653. }
  654. }
  655. /**
  656. * Filter old synthetic timeouts that were created before the
  657. * new right-censored Pareto calculation was deployed.
  658. *
  659. * Once all clients before 0.2.1.13-alpha are gone, this code
  660. * will be unused.
  661. */
  662. static int
  663. circuit_build_times_filter_timeouts(circuit_build_times_t *cbt)
  664. {
  665. int num_filtered=0, i=0;
  666. double timeout_rate = 0;
  667. build_time_t max_timeout = 0;
  668. timeout_rate = circuit_build_times_timeout_rate(cbt);
  669. max_timeout = (build_time_t)cbt->close_ms;
  670. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  671. if (cbt->circuit_build_times[i] > max_timeout) {
  672. build_time_t replaced = cbt->circuit_build_times[i];
  673. num_filtered++;
  674. cbt->circuit_build_times[i] = CBT_BUILD_ABANDONED;
  675. log_debug(LD_CIRC, "Replaced timeout %d with %d", replaced,
  676. cbt->circuit_build_times[i]);
  677. }
  678. }
  679. log_info(LD_CIRC,
  680. "We had %d timeouts out of %d build times, "
  681. "and filtered %d above the max of %u",
  682. (int)(cbt->total_build_times*timeout_rate),
  683. cbt->total_build_times, num_filtered, max_timeout);
  684. return num_filtered;
  685. }
  686. /**
  687. * Load histogram from <b>state</b>, shuffling the resulting array
  688. * after we do so. Use this result to estimate parameters and
  689. * calculate the timeout.
  690. *
  691. * Return -1 on error.
  692. */
  693. int
  694. circuit_build_times_parse_state(circuit_build_times_t *cbt,
  695. or_state_t *state)
  696. {
  697. int tot_values = 0;
  698. uint32_t loaded_cnt = 0, N = 0;
  699. config_line_t *line;
  700. unsigned int i;
  701. build_time_t *loaded_times;
  702. int err = 0;
  703. circuit_build_times_init(cbt);
  704. if (circuit_build_times_disabled()) {
  705. return 0;
  706. }
  707. /* build_time_t 0 means uninitialized */
  708. loaded_times = tor_malloc_zero(sizeof(build_time_t)*state->TotalBuildTimes);
  709. for (line = state->BuildtimeHistogram; line; line = line->next) {
  710. smartlist_t *args = smartlist_create();
  711. smartlist_split_string(args, line->value, " ",
  712. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  713. if (smartlist_len(args) < 2) {
  714. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  715. "Too few arguments to CircuitBuildTime");
  716. err = 1;
  717. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  718. smartlist_free(args);
  719. break;
  720. } else {
  721. const char *ms_str = smartlist_get(args,0);
  722. const char *count_str = smartlist_get(args,1);
  723. uint32_t count, k;
  724. build_time_t ms;
  725. int ok;
  726. ms = (build_time_t)tor_parse_ulong(ms_str, 0, 0,
  727. CBT_BUILD_TIME_MAX, &ok, NULL);
  728. if (!ok) {
  729. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  730. "Unparsable bin number");
  731. err = 1;
  732. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  733. smartlist_free(args);
  734. break;
  735. }
  736. count = (uint32_t)tor_parse_ulong(count_str, 0, 0,
  737. UINT32_MAX, &ok, NULL);
  738. if (!ok) {
  739. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  740. "Unparsable bin count");
  741. err = 1;
  742. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  743. smartlist_free(args);
  744. break;
  745. }
  746. if (loaded_cnt+count+state->CircuitBuildAbandonedCount
  747. > state->TotalBuildTimes) {
  748. log_warn(LD_CIRC,
  749. "Too many build times in state file. "
  750. "Stopping short before %d",
  751. loaded_cnt+count);
  752. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  753. smartlist_free(args);
  754. break;
  755. }
  756. for (k = 0; k < count; k++) {
  757. loaded_times[loaded_cnt++] = ms;
  758. }
  759. N++;
  760. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  761. smartlist_free(args);
  762. }
  763. }
  764. log_info(LD_CIRC,
  765. "Adding %d timeouts.", state->CircuitBuildAbandonedCount);
  766. for (i=0; i < state->CircuitBuildAbandonedCount; i++) {
  767. loaded_times[loaded_cnt++] = CBT_BUILD_ABANDONED;
  768. }
  769. if (loaded_cnt != state->TotalBuildTimes) {
  770. log_warn(LD_CIRC,
  771. "Corrupt state file? Build times count mismatch. "
  772. "Read %d times, but file says %d", loaded_cnt,
  773. state->TotalBuildTimes);
  774. err = 1;
  775. circuit_build_times_reset(cbt);
  776. goto done;
  777. }
  778. circuit_build_times_shuffle_and_store_array(cbt, loaded_times, loaded_cnt);
  779. /* Verify that we didn't overwrite any indexes */
  780. for (i=0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  781. if (!cbt->circuit_build_times[i])
  782. break;
  783. tot_values++;
  784. }
  785. log_info(LD_CIRC,
  786. "Loaded %d/%d values from %d lines in circuit time histogram",
  787. tot_values, cbt->total_build_times, N);
  788. if (cbt->total_build_times != tot_values
  789. || cbt->total_build_times > CBT_NCIRCUITS_TO_OBSERVE) {
  790. log_warn(LD_CIRC,
  791. "Corrupt state file? Shuffled build times mismatch. "
  792. "Read %d times, but file says %d", tot_values,
  793. state->TotalBuildTimes);
  794. err = 1;
  795. circuit_build_times_reset(cbt);
  796. goto done;
  797. }
  798. circuit_build_times_set_timeout(cbt);
  799. if (!state->CircuitBuildAbandonedCount && cbt->total_build_times) {
  800. circuit_build_times_filter_timeouts(cbt);
  801. }
  802. done:
  803. tor_free(loaded_times);
  804. return err ? -1 : 0;
  805. }
  806. /**
  807. * Estimates the Xm and Alpha parameters using
  808. * http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
  809. *
  810. * The notable difference is that we use mode instead of min to estimate Xm.
  811. * This is because our distribution is frechet-like. We claim this is
  812. * an acceptable approximation because we are only concerned with the
  813. * accuracy of the CDF of the tail.
  814. */
  815. int
  816. circuit_build_times_update_alpha(circuit_build_times_t *cbt)
  817. {
  818. build_time_t *x=cbt->circuit_build_times;
  819. double a = 0;
  820. int n=0,i=0,abandoned_count=0;
  821. build_time_t max_time=0;
  822. /* http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation */
  823. /* We sort of cheat here and make our samples slightly more pareto-like
  824. * and less frechet-like. */
  825. cbt->Xm = circuit_build_times_get_xm(cbt);
  826. tor_assert(cbt->Xm > 0);
  827. for (i=0; i< CBT_NCIRCUITS_TO_OBSERVE; i++) {
  828. if (!x[i]) {
  829. continue;
  830. }
  831. if (x[i] < cbt->Xm) {
  832. a += tor_mathlog(cbt->Xm);
  833. } else if (x[i] == CBT_BUILD_ABANDONED) {
  834. abandoned_count++;
  835. } else {
  836. a += tor_mathlog(x[i]);
  837. if (x[i] > max_time)
  838. max_time = x[i];
  839. }
  840. n++;
  841. }
  842. /*
  843. * We are erring and asserting here because this can only happen
  844. * in codepaths other than startup. The startup state parsing code
  845. * performs this same check, and resets state if it hits it. If we
  846. * hit it at runtime, something serious has gone wrong.
  847. */
  848. if (n!=cbt->total_build_times) {
  849. log_err(LD_CIRC, "Discrepancy in build times count: %d vs %d", n,
  850. cbt->total_build_times);
  851. }
  852. tor_assert(n==cbt->total_build_times);
  853. if (max_time <= 0) {
  854. /* This can happen if Xm is actually the *maximum* value in the set.
  855. * It can also happen if we've abandoned every single circuit somehow.
  856. * In either case, tell the caller not to compute a new build timeout. */
  857. log_warn(LD_BUG,
  858. "Could not determine largest build time (%d). "
  859. "Xm is %dms and we've abandoned %d out of %d circuits.", max_time,
  860. cbt->Xm, abandoned_count, n);
  861. return 0;
  862. }
  863. a += abandoned_count*tor_mathlog(max_time);
  864. a -= n*tor_mathlog(cbt->Xm);
  865. // Estimator comes from Eq #4 in:
  866. // "Bayesian estimation based on trimmed samples from Pareto populations"
  867. // by Arturo J. Fernández. We are right-censored only.
  868. a = (n-abandoned_count)/a;
  869. cbt->alpha = a;
  870. return 1;
  871. }
  872. /**
  873. * This is the Pareto Quantile Function. It calculates the point x
  874. * in the distribution such that F(x) = quantile (ie quantile*100%
  875. * of the mass of the density function is below x on the curve).
  876. *
  877. * We use it to calculate the timeout and also to generate synthetic
  878. * values of time for circuits that timeout before completion.
  879. *
  880. * See http://en.wikipedia.org/wiki/Quantile_function,
  881. * http://en.wikipedia.org/wiki/Inverse_transform_sampling and
  882. * http://en.wikipedia.org/wiki/Pareto_distribution#Generating_a_
  883. * random_sample_from_Pareto_distribution
  884. * That's right. I'll cite wikipedia all day long.
  885. *
  886. * Return value is in milliseconds.
  887. */
  888. double
  889. circuit_build_times_calculate_timeout(circuit_build_times_t *cbt,
  890. double quantile)
  891. {
  892. double ret;
  893. tor_assert(quantile >= 0);
  894. tor_assert(1.0-quantile > 0);
  895. tor_assert(cbt->Xm > 0);
  896. ret = cbt->Xm/pow(1.0-quantile,1.0/cbt->alpha);
  897. if (ret > INT32_MAX) {
  898. ret = INT32_MAX;
  899. }
  900. tor_assert(ret > 0);
  901. return ret;
  902. }
  903. /** Pareto CDF */
  904. double
  905. circuit_build_times_cdf(circuit_build_times_t *cbt, double x)
  906. {
  907. double ret;
  908. tor_assert(cbt->Xm > 0);
  909. ret = 1.0-pow(cbt->Xm/x,cbt->alpha);
  910. tor_assert(0 <= ret && ret <= 1.0);
  911. return ret;
  912. }
  913. /**
  914. * Generate a synthetic time using our distribution parameters.
  915. *
  916. * The return value will be within the [q_lo, q_hi) quantile points
  917. * on the CDF.
  918. */
  919. build_time_t
  920. circuit_build_times_generate_sample(circuit_build_times_t *cbt,
  921. double q_lo, double q_hi)
  922. {
  923. double randval = crypto_rand_double();
  924. build_time_t ret;
  925. double u;
  926. /* Generate between [q_lo, q_hi) */
  927. /*XXXX This is what nextafter is supposed to be for; we should use it on the
  928. * platforms that support it. */
  929. q_hi -= 1.0/(INT32_MAX);
  930. tor_assert(q_lo >= 0);
  931. tor_assert(q_hi < 1);
  932. tor_assert(q_lo < q_hi);
  933. u = q_lo + (q_hi-q_lo)*randval;
  934. tor_assert(0 <= u && u < 1.0);
  935. /* circuit_build_times_calculate_timeout returns <= INT32_MAX */
  936. ret = (build_time_t)
  937. tor_lround(circuit_build_times_calculate_timeout(cbt, u));
  938. tor_assert(ret > 0);
  939. return ret;
  940. }
  941. /**
  942. * Estimate an initial alpha parameter by solving the quantile
  943. * function with a quantile point and a specific timeout value.
  944. */
  945. void
  946. circuit_build_times_initial_alpha(circuit_build_times_t *cbt,
  947. double quantile, double timeout_ms)
  948. {
  949. // Q(u) = Xm/((1-u)^(1/a))
  950. // Q(0.8) = Xm/((1-0.8))^(1/a)) = CircBuildTimeout
  951. // CircBuildTimeout = Xm/((1-0.8))^(1/a))
  952. // CircBuildTimeout = Xm*((1-0.8))^(-1/a))
  953. // ln(CircBuildTimeout) = ln(Xm)+ln(((1-0.8)))*(-1/a)
  954. // -ln(1-0.8)/(ln(CircBuildTimeout)-ln(Xm))=a
  955. tor_assert(quantile >= 0);
  956. tor_assert(cbt->Xm > 0);
  957. cbt->alpha = tor_mathlog(1.0-quantile)/
  958. (tor_mathlog(cbt->Xm)-tor_mathlog(timeout_ms));
  959. tor_assert(cbt->alpha > 0);
  960. }
  961. /**
  962. * Returns true if we need circuits to be built
  963. */
  964. int
  965. circuit_build_times_needs_circuits(circuit_build_times_t *cbt)
  966. {
  967. /* Return true if < MIN_CIRCUITS_TO_OBSERVE */
  968. return !circuit_build_times_enough_to_compute(cbt);
  969. }
  970. /**
  971. * Returns true if we should build a timeout test circuit
  972. * right now.
  973. */
  974. int
  975. circuit_build_times_needs_circuits_now(circuit_build_times_t *cbt)
  976. {
  977. return circuit_build_times_needs_circuits(cbt) &&
  978. approx_time()-cbt->last_circ_at > circuit_build_times_test_frequency();
  979. }
  980. /**
  981. * Called to indicate that the network showed some signs of liveness,
  982. * i.e. we received a cell.
  983. *
  984. * This is used by circuit_build_times_network_check_live() to decide
  985. * if we should record the circuit build timeout or not.
  986. *
  987. * This function is called every time we receive a cell. Avoid
  988. * syscalls, events, and other high-intensity work.
  989. */
  990. void
  991. circuit_build_times_network_is_live(circuit_build_times_t *cbt)
  992. {
  993. time_t now = approx_time();
  994. if (cbt->liveness.nonlive_timeouts > 0) {
  995. log_notice(LD_CIRC,
  996. "Tor now sees network activity. Restoring circuit build "
  997. "timeout recording. Network was down for %d seconds "
  998. "during %d circuit attempts.",
  999. (int)(now - cbt->liveness.network_last_live),
  1000. cbt->liveness.nonlive_timeouts);
  1001. }
  1002. cbt->liveness.network_last_live = now;
  1003. cbt->liveness.nonlive_timeouts = 0;
  1004. }
  1005. /**
  1006. * Called to indicate that we completed a circuit. Because this circuit
  1007. * succeeded, it doesn't count as a timeout-after-the-first-hop.
  1008. *
  1009. * This is used by circuit_build_times_network_check_changed() to determine
  1010. * if we had too many recent timeouts and need to reset our learned timeout
  1011. * to something higher.
  1012. */
  1013. void
  1014. circuit_build_times_network_circ_success(circuit_build_times_t *cbt)
  1015. {
  1016. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx] = 0;
  1017. cbt->liveness.after_firsthop_idx++;
  1018. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1019. }
  1020. /**
  1021. * A circuit just timed out. If it failed after the first hop, record it
  1022. * in our history for later deciding if the network speed has changed.
  1023. *
  1024. * This is used by circuit_build_times_network_check_changed() to determine
  1025. * if we had too many recent timeouts and need to reset our learned timeout
  1026. * to something higher.
  1027. */
  1028. static void
  1029. circuit_build_times_network_timeout(circuit_build_times_t *cbt,
  1030. int did_onehop)
  1031. {
  1032. if (did_onehop) {
  1033. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]=1;
  1034. cbt->liveness.after_firsthop_idx++;
  1035. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1036. }
  1037. }
  1038. /**
  1039. * A circuit was just forcibly closed. If there has been no recent network
  1040. * activity at all, but this circuit was launched back when we thought the
  1041. * network was live, increment the number of "nonlive" circuit timeouts.
  1042. *
  1043. * This is used by circuit_build_times_network_check_live() to decide
  1044. * if we should record the circuit build timeout or not.
  1045. */
  1046. static void
  1047. circuit_build_times_network_close(circuit_build_times_t *cbt,
  1048. int did_onehop, time_t start_time)
  1049. {
  1050. time_t now = time(NULL);
  1051. /*
  1052. * Check if this is a timeout that was for a circuit that spent its
  1053. * entire existence during a time where we have had no network activity.
  1054. */
  1055. if (cbt->liveness.network_last_live < start_time) {
  1056. if (did_onehop) {
  1057. char last_live_buf[ISO_TIME_LEN+1];
  1058. char start_time_buf[ISO_TIME_LEN+1];
  1059. char now_buf[ISO_TIME_LEN+1];
  1060. format_local_iso_time(last_live_buf, cbt->liveness.network_last_live);
  1061. format_local_iso_time(start_time_buf, start_time);
  1062. format_local_iso_time(now_buf, now);
  1063. log_warn(LD_BUG,
  1064. "Circuit somehow completed a hop while the network was "
  1065. "not live. Network was last live at %s, but circuit launched "
  1066. "at %s. It's now %s.", last_live_buf, start_time_buf,
  1067. now_buf);
  1068. }
  1069. cbt->liveness.nonlive_timeouts++;
  1070. if (cbt->liveness.nonlive_timeouts == 1) {
  1071. log_notice(LD_CIRC,
  1072. "Tor has not observed any network activity for the past %d "
  1073. "seconds. Disabling circuit build timeout recording.",
  1074. (int)(now - cbt->liveness.network_last_live));
  1075. } else {
  1076. log_info(LD_CIRC,
  1077. "Got non-live timeout. Current count is: %d",
  1078. cbt->liveness.nonlive_timeouts);
  1079. }
  1080. }
  1081. }
  1082. /**
  1083. * When the network is not live, we do not record circuit build times.
  1084. *
  1085. * The network is considered not live if there has been at least one
  1086. * circuit build that began and ended (had its close_ms measurement
  1087. * period expire) since we last received a cell.
  1088. *
  1089. * Also has the side effect of rewinding the circuit time history
  1090. * in the case of recent liveness changes.
  1091. */
  1092. int
  1093. circuit_build_times_network_check_live(circuit_build_times_t *cbt)
  1094. {
  1095. if (cbt->liveness.nonlive_timeouts > 0) {
  1096. return 0;
  1097. }
  1098. return 1;
  1099. }
  1100. /**
  1101. * Returns true if we have seen more than MAX_RECENT_TIMEOUT_COUNT of
  1102. * the past RECENT_CIRCUITS time out after the first hop. Used to detect
  1103. * if the network connection has changed significantly, and if so,
  1104. * resets our circuit build timeout to the default.
  1105. *
  1106. * Also resets the entire timeout history in this case and causes us
  1107. * to restart the process of building test circuits and estimating a
  1108. * new timeout.
  1109. */
  1110. int
  1111. circuit_build_times_network_check_changed(circuit_build_times_t *cbt)
  1112. {
  1113. int total_build_times = cbt->total_build_times;
  1114. int timeout_count=0;
  1115. int i;
  1116. /* how many of our recent circuits made it to the first hop but then
  1117. * timed out? */
  1118. for (i = 0; i < cbt->liveness.num_recent_circs; i++) {
  1119. timeout_count += cbt->liveness.timeouts_after_firsthop[i];
  1120. }
  1121. /* If 80% of our recent circuits are timing out after the first hop,
  1122. * we need to re-estimate a new initial alpha and timeout. */
  1123. if (timeout_count < circuit_build_times_max_timeouts()) {
  1124. return 0;
  1125. }
  1126. circuit_build_times_reset(cbt);
  1127. memset(cbt->liveness.timeouts_after_firsthop, 0,
  1128. sizeof(*cbt->liveness.timeouts_after_firsthop)*
  1129. cbt->liveness.num_recent_circs);
  1130. cbt->liveness.after_firsthop_idx = 0;
  1131. /* Check to see if this has happened before. If so, double the timeout
  1132. * to give people on abysmally bad network connections a shot at access */
  1133. if (cbt->timeout_ms >= circuit_build_times_get_initial_timeout()) {
  1134. if (cbt->timeout_ms > INT32_MAX/2 || cbt->close_ms > INT32_MAX/2) {
  1135. log_warn(LD_CIRC, "Insanely large circuit build timeout value. "
  1136. "(timeout = %fmsec, close = %fmsec)",
  1137. cbt->timeout_ms, cbt->close_ms);
  1138. } else {
  1139. cbt->timeout_ms *= 2;
  1140. cbt->close_ms *= 2;
  1141. }
  1142. } else {
  1143. cbt->close_ms = cbt->timeout_ms
  1144. = circuit_build_times_get_initial_timeout();
  1145. }
  1146. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  1147. log_notice(LD_CIRC,
  1148. "Your network connection speed appears to have changed. Resetting "
  1149. "timeout to %lds after %d timeouts and %d buildtimes.",
  1150. tor_lround(cbt->timeout_ms/1000), timeout_count,
  1151. total_build_times);
  1152. return 1;
  1153. }
  1154. /**
  1155. * Count the number of timeouts in a set of cbt data.
  1156. */
  1157. double
  1158. circuit_build_times_timeout_rate(const circuit_build_times_t *cbt)
  1159. {
  1160. int i=0,timeouts=0;
  1161. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1162. if (cbt->circuit_build_times[i] >= cbt->timeout_ms) {
  1163. timeouts++;
  1164. }
  1165. }
  1166. if (!cbt->total_build_times)
  1167. return 0;
  1168. return ((double)timeouts)/cbt->total_build_times;
  1169. }
  1170. /**
  1171. * Count the number of closed circuits in a set of cbt data.
  1172. */
  1173. double
  1174. circuit_build_times_close_rate(const circuit_build_times_t *cbt)
  1175. {
  1176. int i=0,closed=0;
  1177. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1178. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED) {
  1179. closed++;
  1180. }
  1181. }
  1182. if (!cbt->total_build_times)
  1183. return 0;
  1184. return ((double)closed)/cbt->total_build_times;
  1185. }
  1186. /**
  1187. * Store a timeout as a synthetic value.
  1188. *
  1189. * Returns true if the store was successful and we should possibly
  1190. * update our timeout estimate.
  1191. */
  1192. int
  1193. circuit_build_times_count_close(circuit_build_times_t *cbt,
  1194. int did_onehop,
  1195. time_t start_time)
  1196. {
  1197. if (circuit_build_times_disabled()) {
  1198. cbt->close_ms = cbt->timeout_ms
  1199. = circuit_build_times_get_initial_timeout();
  1200. return 0;
  1201. }
  1202. /* Record this force-close to help determine if the network is dead */
  1203. circuit_build_times_network_close(cbt, did_onehop, start_time);
  1204. /* Only count timeouts if network is live.. */
  1205. if (!circuit_build_times_network_check_live(cbt)) {
  1206. return 0;
  1207. }
  1208. circuit_build_times_add_time(cbt, CBT_BUILD_ABANDONED);
  1209. return 1;
  1210. }
  1211. /**
  1212. * Update timeout counts to determine if we need to expire
  1213. * our build time history due to excessive timeouts.
  1214. *
  1215. * We do not record any actual time values at this stage;
  1216. * we are only interested in recording the fact that a timeout
  1217. * happened. We record the time values via
  1218. * circuit_build_times_count_close() and circuit_build_times_add_time().
  1219. */
  1220. void
  1221. circuit_build_times_count_timeout(circuit_build_times_t *cbt,
  1222. int did_onehop)
  1223. {
  1224. if (circuit_build_times_disabled()) {
  1225. cbt->close_ms = cbt->timeout_ms
  1226. = circuit_build_times_get_initial_timeout();
  1227. return;
  1228. }
  1229. /* Register the fact that a timeout just occurred. */
  1230. circuit_build_times_network_timeout(cbt, did_onehop);
  1231. /* If there are a ton of timeouts, we should reset
  1232. * the circuit build timeout. */
  1233. circuit_build_times_network_check_changed(cbt);
  1234. }
  1235. /**
  1236. * Estimate a new timeout based on history and set our timeout
  1237. * variable accordingly.
  1238. */
  1239. static int
  1240. circuit_build_times_set_timeout_worker(circuit_build_times_t *cbt)
  1241. {
  1242. build_time_t max_time;
  1243. if (!circuit_build_times_enough_to_compute(cbt))
  1244. return 0;
  1245. if (!circuit_build_times_update_alpha(cbt))
  1246. return 0;
  1247. cbt->timeout_ms = circuit_build_times_calculate_timeout(cbt,
  1248. circuit_build_times_quantile_cutoff());
  1249. cbt->close_ms = circuit_build_times_calculate_timeout(cbt,
  1250. circuit_build_times_close_quantile());
  1251. max_time = circuit_build_times_max(cbt);
  1252. /* Sometimes really fast guard nodes give us such a steep curve
  1253. * that this ends up being not that much greater than timeout_ms.
  1254. * Make it be at least 1 min to handle this case. */
  1255. cbt->close_ms = MAX(cbt->close_ms, circuit_build_times_initial_timeout());
  1256. if (cbt->timeout_ms > max_time) {
  1257. log_notice(LD_CIRC,
  1258. "Circuit build timeout of %dms is beyond the maximum build "
  1259. "time we have ever observed. Capping it to %dms.",
  1260. (int)cbt->timeout_ms, max_time);
  1261. cbt->timeout_ms = max_time;
  1262. }
  1263. if (max_time < INT32_MAX/2 && cbt->close_ms > 2*max_time) {
  1264. log_info(LD_CIRC,
  1265. "Circuit build measurement period of %dms is more than twice "
  1266. "the maximum build time we have ever observed. Capping it to "
  1267. "%dms.", (int)cbt->close_ms, 2*max_time);
  1268. cbt->close_ms = 2*max_time;
  1269. }
  1270. cbt->have_computed_timeout = 1;
  1271. return 1;
  1272. }
  1273. /**
  1274. * Exposed function to compute a new timeout. Dispatches events and
  1275. * also filters out extremely high timeout values.
  1276. */
  1277. void
  1278. circuit_build_times_set_timeout(circuit_build_times_t *cbt)
  1279. {
  1280. long prev_timeout = tor_lround(cbt->timeout_ms/1000);
  1281. double timeout_rate;
  1282. if (!circuit_build_times_set_timeout_worker(cbt))
  1283. return;
  1284. if (cbt->timeout_ms < circuit_build_times_min_timeout()) {
  1285. log_warn(LD_CIRC, "Set buildtimeout to low value %fms. Setting to %dms",
  1286. cbt->timeout_ms, circuit_build_times_min_timeout());
  1287. cbt->timeout_ms = circuit_build_times_min_timeout();
  1288. if (cbt->close_ms < cbt->timeout_ms) {
  1289. /* This shouldn't happen because of MAX() in timeout_worker above,
  1290. * but doing it just in case */
  1291. cbt->close_ms = circuit_build_times_initial_timeout();
  1292. }
  1293. }
  1294. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_COMPUTED);
  1295. timeout_rate = circuit_build_times_timeout_rate(cbt);
  1296. if (prev_timeout > tor_lround(cbt->timeout_ms/1000)) {
  1297. log_notice(LD_CIRC,
  1298. "Based on %d circuit times, it looks like we don't need to "
  1299. "wait so long for circuits to finish. We will now assume a "
  1300. "circuit is too slow to use after waiting %ld seconds.",
  1301. cbt->total_build_times,
  1302. tor_lround(cbt->timeout_ms/1000));
  1303. log_info(LD_CIRC,
  1304. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1305. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1306. timeout_rate);
  1307. } else if (prev_timeout < tor_lround(cbt->timeout_ms/1000)) {
  1308. log_notice(LD_CIRC,
  1309. "Based on %d circuit times, it looks like we need to wait "
  1310. "longer for circuits to finish. We will now assume a "
  1311. "circuit is too slow to use after waiting %ld seconds.",
  1312. cbt->total_build_times,
  1313. tor_lround(cbt->timeout_ms/1000));
  1314. log_info(LD_CIRC,
  1315. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1316. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1317. timeout_rate);
  1318. } else {
  1319. log_info(LD_CIRC,
  1320. "Set circuit build timeout to %lds (%fms, %fms, Xm: %d, a: %f,"
  1321. " r: %f) based on %d circuit times",
  1322. tor_lround(cbt->timeout_ms/1000),
  1323. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha, timeout_rate,
  1324. cbt->total_build_times);
  1325. }
  1326. }
  1327. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  1328. * and with the high bit specified by conn-\>circ_id_type, until we get
  1329. * a circ_id that is not in use by any other circuit on that conn.
  1330. *
  1331. * Return it, or 0 if can't get a unique circ_id.
  1332. */
  1333. static circid_t
  1334. get_unique_circ_id_by_conn(or_connection_t *conn)
  1335. {
  1336. circid_t test_circ_id;
  1337. circid_t attempts=0;
  1338. circid_t high_bit;
  1339. tor_assert(conn);
  1340. if (conn->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  1341. log_warn(LD_BUG, "Trying to pick a circuit ID for a connection from "
  1342. "a client with no identity.");
  1343. return 0;
  1344. }
  1345. high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  1346. do {
  1347. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  1348. * circID such that (high_bit|test_circ_id) is not already used. */
  1349. test_circ_id = conn->next_circ_id++;
  1350. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  1351. test_circ_id = 1;
  1352. conn->next_circ_id = 2;
  1353. }
  1354. if (++attempts > 1<<15) {
  1355. /* Make sure we don't loop forever if all circ_id's are used. This
  1356. * matters because it's an external DoS opportunity.
  1357. */
  1358. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  1359. return 0;
  1360. }
  1361. test_circ_id |= high_bit;
  1362. } while (circuit_id_in_use_on_orconn(test_circ_id, conn));
  1363. return test_circ_id;
  1364. }
  1365. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  1366. * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
  1367. * list information about link status in a more verbose format using spaces.
  1368. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  1369. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  1370. * names.
  1371. */
  1372. static char *
  1373. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  1374. {
  1375. crypt_path_t *hop;
  1376. smartlist_t *elements;
  1377. const char *states[] = {"closed", "waiting for keys", "open"};
  1378. char *s;
  1379. elements = smartlist_create();
  1380. if (verbose) {
  1381. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  1382. char *cp;
  1383. tor_asprintf(&cp, "%s%s circ (length %d%s%s):",
  1384. circ->build_state->is_internal ? "internal" : "exit",
  1385. circ->build_state->need_uptime ? " (high-uptime)" : "",
  1386. circ->build_state->desired_path_len,
  1387. circ->_base.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
  1388. circ->_base.state == CIRCUIT_STATE_OPEN ? "" :
  1389. (nickname?nickname:"*unnamed*"));
  1390. smartlist_add(elements, cp);
  1391. }
  1392. hop = circ->cpath;
  1393. do {
  1394. char *elt;
  1395. const char *id;
  1396. const node_t *node;
  1397. if (!hop)
  1398. break;
  1399. if (!verbose && hop->state != CPATH_STATE_OPEN)
  1400. break;
  1401. if (!hop->extend_info)
  1402. break;
  1403. id = hop->extend_info->identity_digest;
  1404. if (verbose_names) {
  1405. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  1406. if ((node = node_get_by_id(id))) {
  1407. node_get_verbose_nickname(node, elt);
  1408. } else if (is_legal_nickname(hop->extend_info->nickname)) {
  1409. elt[0] = '$';
  1410. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  1411. elt[HEX_DIGEST_LEN+1]= '~';
  1412. strlcpy(elt+HEX_DIGEST_LEN+2,
  1413. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  1414. } else {
  1415. elt[0] = '$';
  1416. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  1417. }
  1418. } else { /* ! verbose_names */
  1419. node = node_get_by_id(id);
  1420. if (node && node_is_named(node)) {
  1421. elt = tor_strdup(node_get_nickname(node));
  1422. } else {
  1423. elt = tor_malloc(HEX_DIGEST_LEN+2);
  1424. elt[0] = '$';
  1425. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  1426. }
  1427. }
  1428. tor_assert(elt);
  1429. if (verbose) {
  1430. size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
  1431. char *v = tor_malloc(len);
  1432. tor_assert(hop->state <= 2);
  1433. tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
  1434. smartlist_add(elements, v);
  1435. tor_free(elt);
  1436. } else {
  1437. smartlist_add(elements, elt);
  1438. }
  1439. hop = hop->next;
  1440. } while (hop != circ->cpath);
  1441. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  1442. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  1443. smartlist_free(elements);
  1444. return s;
  1445. }
  1446. /** If <b>verbose</b> is false, allocate and return a comma-separated
  1447. * list of the currently built elements of <b>circ</b>. If
  1448. * <b>verbose</b> is true, also list information about link status in
  1449. * a more verbose format using spaces.
  1450. */
  1451. char *
  1452. circuit_list_path(origin_circuit_t *circ, int verbose)
  1453. {
  1454. return circuit_list_path_impl(circ, verbose, 0);
  1455. }
  1456. /** Allocate and return a comma-separated list of the currently built elements
  1457. * of <b>circ</b>, giving each as a verbose nickname.
  1458. */
  1459. char *
  1460. circuit_list_path_for_controller(origin_circuit_t *circ)
  1461. {
  1462. return circuit_list_path_impl(circ, 0, 1);
  1463. }
  1464. /** Log, at severity <b>severity</b>, the nicknames of each router in
  1465. * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
  1466. * exit point.
  1467. */
  1468. void
  1469. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  1470. {
  1471. char *s = circuit_list_path(circ,1);
  1472. tor_log(severity,domain,"%s",s);
  1473. tor_free(s);
  1474. }
  1475. /** Tell the rep(utation)hist(ory) module about the status of the links
  1476. * in <b>circ</b>. Hops that have become OPEN are marked as successfully
  1477. * extended; the _first_ hop that isn't open (if any) is marked as
  1478. * unable to extend.
  1479. */
  1480. /* XXXX Someday we should learn from OR circuits too. */
  1481. void
  1482. circuit_rep_hist_note_result(origin_circuit_t *circ)
  1483. {
  1484. crypt_path_t *hop;
  1485. const char *prev_digest = NULL;
  1486. hop = circ->cpath;
  1487. if (!hop) /* circuit hasn't started building yet. */
  1488. return;
  1489. if (server_mode(get_options())) {
  1490. const routerinfo_t *me = router_get_my_routerinfo();
  1491. if (!me)
  1492. return;
  1493. prev_digest = me->cache_info.identity_digest;
  1494. }
  1495. do {
  1496. const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
  1497. if (node) { /* Why do we check this? We know the identity. -NM XXXX */
  1498. if (prev_digest) {
  1499. if (hop->state == CPATH_STATE_OPEN)
  1500. rep_hist_note_extend_succeeded(prev_digest, node->identity);
  1501. else {
  1502. rep_hist_note_extend_failed(prev_digest, node->identity);
  1503. break;
  1504. }
  1505. }
  1506. prev_digest = node->identity;
  1507. } else {
  1508. prev_digest = NULL;
  1509. }
  1510. hop=hop->next;
  1511. } while (hop!=circ->cpath);
  1512. }
  1513. /** Pick all the entries in our cpath. Stop and return 0 when we're
  1514. * happy, or return -1 if an error occurs. */
  1515. static int
  1516. onion_populate_cpath(origin_circuit_t *circ)
  1517. {
  1518. int r;
  1519. again:
  1520. r = onion_extend_cpath(circ);
  1521. if (r < 0) {
  1522. log_info(LD_CIRC,"Generating cpath hop failed.");
  1523. return -1;
  1524. }
  1525. if (r == 0)
  1526. goto again;
  1527. return 0; /* if r == 1 */
  1528. }
  1529. /** Create and return a new origin circuit. Initialize its purpose and
  1530. * build-state based on our arguments. The <b>flags</b> argument is a
  1531. * bitfield of CIRCLAUNCH_* flags. */
  1532. origin_circuit_t *
  1533. origin_circuit_init(uint8_t purpose, int flags)
  1534. {
  1535. /* sets circ->p_circ_id and circ->p_conn */
  1536. origin_circuit_t *circ = origin_circuit_new();
  1537. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
  1538. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  1539. circ->build_state->onehop_tunnel =
  1540. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  1541. circ->build_state->need_uptime =
  1542. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  1543. circ->build_state->need_capacity =
  1544. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  1545. circ->build_state->is_internal =
  1546. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  1547. circ->_base.purpose = purpose;
  1548. return circ;
  1549. }
  1550. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  1551. * is defined, then use that as your exit router, else choose a suitable
  1552. * exit node.
  1553. *
  1554. * Also launch a connection to the first OR in the chosen path, if
  1555. * it's not open already.
  1556. */
  1557. origin_circuit_t *
  1558. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  1559. {
  1560. origin_circuit_t *circ;
  1561. int err_reason = 0;
  1562. circ = origin_circuit_init(purpose, flags);
  1563. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  1564. onion_populate_cpath(circ) < 0) {
  1565. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  1566. return NULL;
  1567. }
  1568. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  1569. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  1570. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1571. return NULL;
  1572. }
  1573. return circ;
  1574. }
  1575. /** Start establishing the first hop of our circuit. Figure out what
  1576. * OR we should connect to, and if necessary start the connection to
  1577. * it. If we're already connected, then send the 'create' cell.
  1578. * Return 0 for ok, -reason if circ should be marked-for-close. */
  1579. int
  1580. circuit_handle_first_hop(origin_circuit_t *circ)
  1581. {
  1582. crypt_path_t *firsthop;
  1583. or_connection_t *n_conn;
  1584. int err_reason = 0;
  1585. const char *msg = NULL;
  1586. int should_launch = 0;
  1587. firsthop = onion_next_hop_in_cpath(circ->cpath);
  1588. tor_assert(firsthop);
  1589. tor_assert(firsthop->extend_info);
  1590. /* now see if we're already connected to the first OR in 'route' */
  1591. log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",
  1592. fmt_addr(&firsthop->extend_info->addr),
  1593. firsthop->extend_info->port);
  1594. n_conn = connection_or_get_for_extend(firsthop->extend_info->identity_digest,
  1595. &firsthop->extend_info->addr,
  1596. &msg,
  1597. &should_launch);
  1598. if (!n_conn) {
  1599. /* not currently connected in a useful way. */
  1600. log_info(LD_CIRC, "Next router is %s: %s",
  1601. safe_str_client(extend_info_describe(firsthop->extend_info)),
  1602. msg?msg:"???");
  1603. circ->_base.n_hop = extend_info_dup(firsthop->extend_info);
  1604. if (should_launch) {
  1605. if (circ->build_state->onehop_tunnel)
  1606. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  1607. n_conn = connection_or_connect(&firsthop->extend_info->addr,
  1608. firsthop->extend_info->port,
  1609. firsthop->extend_info->identity_digest);
  1610. if (!n_conn) { /* connect failed, forget the whole thing */
  1611. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  1612. return -END_CIRC_REASON_CONNECTFAILED;
  1613. }
  1614. }
  1615. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  1616. /* return success. The onion/circuit/etc will be taken care of
  1617. * automatically (may already have been) whenever n_conn reaches
  1618. * OR_CONN_STATE_OPEN.
  1619. */
  1620. return 0;
  1621. } else { /* it's already open. use it. */
  1622. tor_assert(!circ->_base.n_hop);
  1623. circ->_base.n_conn = n_conn;
  1624. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  1625. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  1626. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  1627. return err_reason;
  1628. }
  1629. }
  1630. return 0;
  1631. }
  1632. /** Find any circuits that are waiting on <b>or_conn</b> to become
  1633. * open and get them to send their create cells forward.
  1634. *
  1635. * Status is 1 if connect succeeded, or 0 if connect failed.
  1636. */
  1637. void
  1638. circuit_n_conn_done(or_connection_t *or_conn, int status)
  1639. {
  1640. smartlist_t *pending_circs;
  1641. int err_reason = 0;
  1642. log_debug(LD_CIRC,"or_conn to %s/%s, status=%d",
  1643. or_conn->nickname ? or_conn->nickname : "NULL",
  1644. or_conn->_base.address, status);
  1645. pending_circs = smartlist_create();
  1646. circuit_get_all_pending_on_or_conn(pending_circs, or_conn);
  1647. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  1648. {
  1649. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  1650. * leaving them in in case it's possible for the status of a circuit to
  1651. * change as we're going down the list. */
  1652. if (circ->marked_for_close || circ->n_conn || !circ->n_hop ||
  1653. circ->state != CIRCUIT_STATE_OR_WAIT)
  1654. continue;
  1655. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  1656. /* Look at addr/port. This is an unkeyed connection. */
  1657. if (!tor_addr_eq(&circ->n_hop->addr, &or_conn->_base.addr) ||
  1658. circ->n_hop->port != or_conn->_base.port)
  1659. continue;
  1660. } else {
  1661. /* We expected a key. See if it's the right one. */
  1662. if (tor_memneq(or_conn->identity_digest,
  1663. circ->n_hop->identity_digest, DIGEST_LEN))
  1664. continue;
  1665. }
  1666. if (!status) { /* or_conn failed; close circ */
  1667. log_info(LD_CIRC,"or_conn failed. Closing circ.");
  1668. circuit_mark_for_close(circ, END_CIRC_REASON_OR_CONN_CLOSED);
  1669. continue;
  1670. }
  1671. log_debug(LD_CIRC, "Found circ, sending create cell.");
  1672. /* circuit_deliver_create_cell will set n_circ_id and add us to
  1673. * orconn_circuid_circuit_map, so we don't need to call
  1674. * set_circid_orconn here. */
  1675. circ->n_conn = or_conn;
  1676. extend_info_free(circ->n_hop);
  1677. circ->n_hop = NULL;
  1678. if (CIRCUIT_IS_ORIGIN(circ)) {
  1679. if ((err_reason =
  1680. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  1681. log_info(LD_CIRC,
  1682. "send_next_onion_skin failed; circuit marked for closing.");
  1683. circuit_mark_for_close(circ, -err_reason);
  1684. continue;
  1685. /* XXX could this be bad, eg if next_onion_skin failed because conn
  1686. * died? */
  1687. }
  1688. } else {
  1689. /* pull the create cell out of circ->onionskin, and send it */
  1690. tor_assert(circ->n_conn_onionskin);
  1691. if (circuit_deliver_create_cell(circ,CELL_CREATE,
  1692. circ->n_conn_onionskin)<0) {
  1693. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  1694. continue;
  1695. }
  1696. tor_free(circ->n_conn_onionskin);
  1697. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  1698. }
  1699. }
  1700. SMARTLIST_FOREACH_END(circ);
  1701. smartlist_free(pending_circs);
  1702. }
  1703. /** Find a new circid that isn't currently in use on the circ->n_conn
  1704. * for the outgoing
  1705. * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
  1706. * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
  1707. * to this circuit.
  1708. * Return -1 if we failed to find a suitable circid, else return 0.
  1709. */
  1710. static int
  1711. circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type,
  1712. const char *payload)
  1713. {
  1714. cell_t cell;
  1715. circid_t id;
  1716. tor_assert(circ);
  1717. tor_assert(circ->n_conn);
  1718. tor_assert(payload);
  1719. tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
  1720. id = get_unique_circ_id_by_conn(circ->n_conn);
  1721. if (!id) {
  1722. log_warn(LD_CIRC,"failed to get unique circID.");
  1723. return -1;
  1724. }
  1725. log_debug(LD_CIRC,"Chosen circID %u.", id);
  1726. circuit_set_n_circid_orconn(circ, id, circ->n_conn);
  1727. memset(&cell, 0, sizeof(cell_t));
  1728. cell.command = cell_type;
  1729. cell.circ_id = circ->n_circ_id;
  1730. memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
  1731. append_cell_to_circuit_queue(circ, circ->n_conn, &cell,
  1732. CELL_DIRECTION_OUT, 0);
  1733. if (CIRCUIT_IS_ORIGIN(circ)) {
  1734. /* mark it so it gets better rate limiting treatment. */
  1735. circ->n_conn->client_used = time(NULL);
  1736. }
  1737. return 0;
  1738. }
  1739. /** We've decided to start our reachability testing. If all
  1740. * is set, log this to the user. Return 1 if we did, or 0 if
  1741. * we chose not to log anything. */
  1742. int
  1743. inform_testing_reachability(void)
  1744. {
  1745. char dirbuf[128];
  1746. const routerinfo_t *me = router_get_my_routerinfo();
  1747. if (!me)
  1748. return 0;
  1749. control_event_server_status(LOG_NOTICE,
  1750. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  1751. me->address, me->or_port);
  1752. if (me->dir_port) {
  1753. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  1754. me->address, me->dir_port);
  1755. control_event_server_status(LOG_NOTICE,
  1756. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  1757. me->address, me->dir_port);
  1758. }
  1759. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  1760. "(this may take up to %d minutes -- look for log "
  1761. "messages indicating success)",
  1762. me->address, me->or_port,
  1763. me->dir_port ? dirbuf : "",
  1764. me->dir_port ? "are" : "is",
  1765. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  1766. return 1;
  1767. }
  1768. /** Return true iff we should send a create_fast cell to start building a given
  1769. * circuit */
  1770. static INLINE int
  1771. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  1772. {
  1773. const or_options_t *options = get_options();
  1774. tor_assert(circ->cpath);
  1775. tor_assert(circ->cpath->extend_info);
  1776. if (!circ->cpath->extend_info->onion_key)
  1777. return 1; /* our hand is forced: only a create_fast will work. */
  1778. if (!options->FastFirstHopPK)
  1779. return 0; /* we prefer to avoid create_fast */
  1780. if (server_mode(options)) {
  1781. /* We're a server, and we know an onion key. We can choose.
  1782. * Prefer to blend in. */
  1783. return 0;
  1784. }
  1785. return 1;
  1786. }
  1787. /** Return true if <b>circ</b> is the type of circuit we want to count
  1788. * timeouts from. In particular, we want it to have not completed yet
  1789. * (already completing indicates we cannibalized it), and we want it to
  1790. * have exactly three hops.
  1791. */
  1792. int
  1793. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  1794. {
  1795. return !circ->has_opened
  1796. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  1797. }
  1798. /** This is the backbone function for building circuits.
  1799. *
  1800. * If circ's first hop is closed, then we need to build a create
  1801. * cell and send it forward.
  1802. *
  1803. * Otherwise, we need to build a relay extend cell and send it
  1804. * forward.
  1805. *
  1806. * Return -reason if we want to tear down circ, else return 0.
  1807. */
  1808. int
  1809. circuit_send_next_onion_skin(origin_circuit_t *circ)
  1810. {
  1811. crypt_path_t *hop;
  1812. const node_t *node;
  1813. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  1814. char *onionskin;
  1815. size_t payload_len;
  1816. tor_assert(circ);
  1817. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  1818. int fast;
  1819. uint8_t cell_type;
  1820. log_debug(LD_CIRC,"First skin; sending create cell.");
  1821. if (circ->build_state->onehop_tunnel)
  1822. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  1823. else
  1824. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  1825. node = node_get_by_id(circ->_base.n_conn->identity_digest);
  1826. fast = should_use_create_fast_for_circuit(circ);
  1827. if (!fast) {
  1828. /* We are an OR and we know the right onion key: we should
  1829. * send an old slow create cell.
  1830. */
  1831. cell_type = CELL_CREATE;
  1832. if (onion_skin_create(circ->cpath->extend_info->onion_key,
  1833. &(circ->cpath->dh_handshake_state),
  1834. payload) < 0) {
  1835. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  1836. return - END_CIRC_REASON_INTERNAL;
  1837. }
  1838. note_request("cell: create", 1);
  1839. } else {
  1840. /* We are not an OR, and we're building the first hop of a circuit to a
  1841. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  1842. * and a DH operation. */
  1843. cell_type = CELL_CREATE_FAST;
  1844. memset(payload, 0, sizeof(payload));
  1845. crypto_rand((char*) circ->cpath->fast_handshake_state,
  1846. sizeof(circ->cpath->fast_handshake_state));
  1847. memcpy(payload, circ->cpath->fast_handshake_state,
  1848. sizeof(circ->cpath->fast_handshake_state));
  1849. note_request("cell: create fast", 1);
  1850. }
  1851. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
  1852. return - END_CIRC_REASON_RESOURCELIMIT;
  1853. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  1854. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1855. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  1856. fast ? "CREATE_FAST" : "CREATE",
  1857. node ? node_describe(node) : "<unnamed>");
  1858. } else {
  1859. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  1860. tor_assert(circ->_base.state == CIRCUIT_STATE_BUILDING);
  1861. log_debug(LD_CIRC,"starting to send subsequent skin.");
  1862. hop = onion_next_hop_in_cpath(circ->cpath);
  1863. if (!hop) {
  1864. /* done building the circuit. whew. */
  1865. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1866. if (circuit_timeout_want_to_count_circ(circ)) {
  1867. struct timeval end;
  1868. long timediff;
  1869. tor_gettimeofday(&end);
  1870. timediff = tv_mdiff(&circ->_base.timestamp_created, &end);
  1871. /*
  1872. * If the circuit build time is much greater than we would have cut
  1873. * it off at, we probably had a suspend event along this codepath,
  1874. * and we should discard the value.
  1875. */
  1876. if (timediff < 0 || timediff > 2*circ_times.close_ms+1000) {
  1877. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  1878. "Assuming clock jump. Purpose %d (%s)", timediff,
  1879. circ->_base.purpose,
  1880. circuit_purpose_to_string(circ->_base.purpose));
  1881. } else if (!circuit_build_times_disabled()) {
  1882. /* Only count circuit times if the network is live */
  1883. if (circuit_build_times_network_check_live(&circ_times)) {
  1884. circuit_build_times_add_time(&circ_times, (build_time_t)timediff);
  1885. circuit_build_times_set_timeout(&circ_times);
  1886. }
  1887. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1888. circuit_build_times_network_circ_success(&circ_times);
  1889. }
  1890. }
  1891. }
  1892. log_info(LD_CIRC,"circuit built!");
  1893. circuit_reset_failure_count(0);
  1894. if (circ->build_state->onehop_tunnel)
  1895. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  1896. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  1897. const or_options_t *options = get_options();
  1898. can_complete_circuit=1;
  1899. /* FFFF Log a count of known routers here */
  1900. log_notice(LD_GENERAL,
  1901. "Tor has successfully opened a circuit. "
  1902. "Looks like client functionality is working.");
  1903. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  1904. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  1905. clear_broken_connection_map(1);
  1906. if (server_mode(options) && !check_whether_orport_reachable()) {
  1907. inform_testing_reachability();
  1908. consider_testing_reachability(1, 1);
  1909. }
  1910. }
  1911. circuit_rep_hist_note_result(circ);
  1912. circuit_has_opened(circ); /* do other actions as necessary */
  1913. /* We're done with measurement circuits here. Just close them */
  1914. if (circ->_base.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  1915. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  1916. return 0;
  1917. }
  1918. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  1919. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  1920. return - END_CIRC_REASON_INTERNAL;
  1921. }
  1922. set_uint32(payload, tor_addr_to_ipv4n(&hop->extend_info->addr));
  1923. set_uint16(payload+4, htons(hop->extend_info->port));
  1924. onionskin = payload+2+4;
  1925. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
  1926. hop->extend_info->identity_digest, DIGEST_LEN);
  1927. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  1928. if (onion_skin_create(hop->extend_info->onion_key,
  1929. &(hop->dh_handshake_state), onionskin) < 0) {
  1930. log_warn(LD_CIRC,"onion_skin_create failed.");
  1931. return - END_CIRC_REASON_INTERNAL;
  1932. }
  1933. log_info(LD_CIRC,"Sending extend relay cell.");
  1934. note_request("cell: extend", 1);
  1935. /* send it to hop->prev, because it will transfer
  1936. * it to a create cell and then send to hop */
  1937. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  1938. RELAY_COMMAND_EXTEND,
  1939. payload, payload_len, hop->prev) < 0)
  1940. return 0; /* circuit is closed */
  1941. hop->state = CPATH_STATE_AWAITING_KEYS;
  1942. }
  1943. return 0;
  1944. }
  1945. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  1946. * something has also gone wrong with our network: notify the user,
  1947. * and abandon all not-yet-used circuits. */
  1948. void
  1949. circuit_note_clock_jumped(int seconds_elapsed)
  1950. {
  1951. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  1952. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  1953. "assuming established circuits no longer work.",
  1954. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  1955. seconds_elapsed >=0 ? "forward" : "backward");
  1956. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  1957. seconds_elapsed);
  1958. can_complete_circuit=0; /* so it'll log when it works again */
  1959. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  1960. "CLOCK_JUMPED");
  1961. circuit_mark_all_unused_circs();
  1962. circuit_expire_all_dirty_circs();
  1963. }
  1964. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  1965. * skin and identity digest for the next hop. If we're already connected,
  1966. * pass the onion skin to the next hop using a create cell; otherwise
  1967. * launch a new OR connection, and <b>circ</b> will notice when the
  1968. * connection succeeds or fails.
  1969. *
  1970. * Return -1 if we want to warn and tear down the circuit, else return 0.
  1971. */
  1972. int
  1973. circuit_extend(cell_t *cell, circuit_t *circ)
  1974. {
  1975. or_connection_t *n_conn;
  1976. relay_header_t rh;
  1977. char *onionskin;
  1978. char *id_digest=NULL;
  1979. uint32_t n_addr32;
  1980. uint16_t n_port;
  1981. tor_addr_t n_addr;
  1982. const char *msg = NULL;
  1983. int should_launch = 0;
  1984. if (circ->n_conn) {
  1985. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1986. "n_conn already set. Bug/attack. Closing.");
  1987. return -1;
  1988. }
  1989. if (circ->n_hop) {
  1990. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1991. "conn to next hop already launched. Bug/attack. Closing.");
  1992. return -1;
  1993. }
  1994. if (!server_mode(get_options())) {
  1995. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1996. "Got an extend cell, but running as a client. Closing.");
  1997. return -1;
  1998. }
  1999. relay_header_unpack(&rh, cell->payload);
  2000. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  2001. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2002. "Wrong length %d on extend cell. Closing circuit.",
  2003. rh.length);
  2004. return -1;
  2005. }
  2006. n_addr32 = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  2007. n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  2008. onionskin = (char*) cell->payload+RELAY_HEADER_SIZE+4+2;
  2009. id_digest = (char*) cell->payload+RELAY_HEADER_SIZE+4+2+
  2010. ONIONSKIN_CHALLENGE_LEN;
  2011. tor_addr_from_ipv4h(&n_addr, n_addr32);
  2012. if (!n_port || !n_addr32) {
  2013. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2014. "Client asked me to extend to zero destination port or addr.");
  2015. return -1;
  2016. }
  2017. /* Check if they asked us for 0000..0000. We support using
  2018. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  2019. * but we don't want to let people send us extend cells for empty
  2020. * fingerprints -- a) because it opens the user up to a mitm attack,
  2021. * and b) because it lets an attacker force the relay to hold open a
  2022. * new TLS connection for each extend request. */
  2023. if (tor_digest_is_zero(id_digest)) {
  2024. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2025. "Client asked me to extend without specifying an id_digest.");
  2026. return -1;
  2027. }
  2028. /* Next, check if we're being asked to connect to the hop that the
  2029. * extend cell came from. There isn't any reason for that, and it can
  2030. * assist circular-path attacks. */
  2031. if (tor_memeq(id_digest, TO_OR_CIRCUIT(circ)->p_conn->identity_digest,
  2032. DIGEST_LEN)) {
  2033. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2034. "Client asked me to extend back to the previous hop.");
  2035. return -1;
  2036. }
  2037. n_conn = connection_or_get_for_extend(id_digest,
  2038. &n_addr,
  2039. &msg,
  2040. &should_launch);
  2041. if (!n_conn) {
  2042. log_debug(LD_CIRC|LD_OR,"Next router (%s:%d): %s",
  2043. fmt_addr(&n_addr), (int)n_port, msg?msg:"????");
  2044. circ->n_hop = extend_info_alloc(NULL /*nickname*/,
  2045. id_digest,
  2046. NULL /*onion_key*/,
  2047. &n_addr, n_port);
  2048. circ->n_conn_onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
  2049. memcpy(circ->n_conn_onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  2050. circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
  2051. if (should_launch) {
  2052. /* we should try to open a connection */
  2053. n_conn = connection_or_connect(&n_addr, n_port, id_digest);
  2054. if (!n_conn) {
  2055. log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
  2056. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  2057. return 0;
  2058. }
  2059. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  2060. }
  2061. /* return success. The onion/circuit/etc will be taken care of
  2062. * automatically (may already have been) whenever n_conn reaches
  2063. * OR_CONN_STATE_OPEN.
  2064. */
  2065. return 0;
  2066. }
  2067. tor_assert(!circ->n_hop); /* Connection is already established. */
  2068. circ->n_conn = n_conn;
  2069. log_debug(LD_CIRC,"n_conn is %s:%u",
  2070. n_conn->_base.address,n_conn->_base.port);
  2071. if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
  2072. return -1;
  2073. return 0;
  2074. }
  2075. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  2076. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  2077. * used as follows:
  2078. * - 20 to initialize f_digest
  2079. * - 20 to initialize b_digest
  2080. * - 16 to key f_crypto
  2081. * - 16 to key b_crypto
  2082. *
  2083. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  2084. */
  2085. int
  2086. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  2087. int reverse)
  2088. {
  2089. crypto_digest_env_t *tmp_digest;
  2090. crypto_cipher_env_t *tmp_crypto;
  2091. tor_assert(cpath);
  2092. tor_assert(key_data);
  2093. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  2094. cpath->f_digest || cpath->b_digest));
  2095. cpath->f_digest = crypto_new_digest_env();
  2096. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  2097. cpath->b_digest = crypto_new_digest_env();
  2098. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  2099. if (!(cpath->f_crypto =
  2100. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  2101. log_warn(LD_BUG,"Forward cipher initialization failed.");
  2102. return -1;
  2103. }
  2104. if (!(cpath->b_crypto =
  2105. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  2106. log_warn(LD_BUG,"Backward cipher initialization failed.");
  2107. return -1;
  2108. }
  2109. if (reverse) {
  2110. tmp_digest = cpath->f_digest;
  2111. cpath->f_digest = cpath->b_digest;
  2112. cpath->b_digest = tmp_digest;
  2113. tmp_crypto = cpath->f_crypto;
  2114. cpath->f_crypto = cpath->b_crypto;
  2115. cpath->b_crypto = tmp_crypto;
  2116. }
  2117. return 0;
  2118. }
  2119. /** A created or extended cell came back to us on the circuit, and it included
  2120. * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  2121. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  2122. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  2123. *
  2124. * Calculate the appropriate keys and digests, make sure KH is
  2125. * correct, and initialize this hop of the cpath.
  2126. *
  2127. * Return - reason if we want to mark circ for close, else return 0.
  2128. */
  2129. int
  2130. circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
  2131. const uint8_t *reply)
  2132. {
  2133. char keys[CPATH_KEY_MATERIAL_LEN];
  2134. crypt_path_t *hop;
  2135. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  2136. hop = circ->cpath;
  2137. else {
  2138. hop = onion_next_hop_in_cpath(circ->cpath);
  2139. if (!hop) { /* got an extended when we're all done? */
  2140. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  2141. return - END_CIRC_REASON_TORPROTOCOL;
  2142. }
  2143. }
  2144. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  2145. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  2146. if (onion_skin_client_handshake(hop->dh_handshake_state, (char*)reply,keys,
  2147. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  2148. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  2149. return -END_CIRC_REASON_TORPROTOCOL;
  2150. }
  2151. /* Remember hash of g^xy */
  2152. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  2153. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  2154. if (fast_client_handshake(hop->fast_handshake_state, reply,
  2155. (uint8_t*)keys,
  2156. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  2157. log_warn(LD_CIRC,"fast_client_handshake failed.");
  2158. return -END_CIRC_REASON_TORPROTOCOL;
  2159. }
  2160. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  2161. } else {
  2162. log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  2163. return -END_CIRC_REASON_TORPROTOCOL;
  2164. }
  2165. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  2166. hop->dh_handshake_state = NULL;
  2167. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  2168. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  2169. return -END_CIRC_REASON_TORPROTOCOL;
  2170. }
  2171. hop->state = CPATH_STATE_OPEN;
  2172. log_info(LD_CIRC,"Finished building %scircuit hop:",
  2173. (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  2174. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  2175. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  2176. return 0;
  2177. }
  2178. /** We received a relay truncated cell on circ.
  2179. *
  2180. * Since we don't ask for truncates currently, getting a truncated
  2181. * means that a connection broke or an extend failed. For now,
  2182. * just give up: for circ to close, and return 0.
  2183. */
  2184. int
  2185. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
  2186. {
  2187. // crypt_path_t *victim;
  2188. // connection_t *stream;
  2189. tor_assert(circ);
  2190. tor_assert(layer);
  2191. /* XXX Since we don't ask for truncates currently, getting a truncated
  2192. * means that a connection broke or an extend failed. For now,
  2193. * just give up.
  2194. */
  2195. circuit_mark_for_close(TO_CIRCUIT(circ),
  2196. END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
  2197. return 0;
  2198. #if 0
  2199. while (layer->next != circ->cpath) {
  2200. /* we need to clear out layer->next */
  2201. victim = layer->next;
  2202. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  2203. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  2204. if (stream->cpath_layer == victim) {
  2205. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  2206. stream->stream_id);
  2207. /* no need to send 'end' relay cells,
  2208. * because the other side's already dead
  2209. */
  2210. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  2211. }
  2212. }
  2213. layer->next = victim->next;
  2214. circuit_free_cpath_node(victim);
  2215. }
  2216. log_info(LD_CIRC, "finished");
  2217. return 0;
  2218. #endif
  2219. }
  2220. /** Given a response payload and keys, initialize, then send a created
  2221. * cell back.
  2222. */
  2223. int
  2224. onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
  2225. const char *keys)
  2226. {
  2227. cell_t cell;
  2228. crypt_path_t *tmp_cpath;
  2229. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  2230. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  2231. memset(&cell, 0, sizeof(cell_t));
  2232. cell.command = cell_type;
  2233. cell.circ_id = circ->p_circ_id;
  2234. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  2235. memcpy(cell.payload, payload,
  2236. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  2237. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  2238. (unsigned int)get_uint32(keys),
  2239. (unsigned int)get_uint32(keys+20));
  2240. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  2241. log_warn(LD_BUG,"Circuit initialization failed");
  2242. tor_free(tmp_cpath);
  2243. return -1;
  2244. }
  2245. circ->n_digest = tmp_cpath->f_digest;
  2246. circ->n_crypto = tmp_cpath->f_crypto;
  2247. circ->p_digest = tmp_cpath->b_digest;
  2248. circ->p_crypto = tmp_cpath->b_crypto;
  2249. tmp_cpath->magic = 0;
  2250. tor_free(tmp_cpath);
  2251. if (cell_type == CELL_CREATED)
  2252. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  2253. else
  2254. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  2255. circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
  2256. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  2257. circ->p_conn, &cell, CELL_DIRECTION_IN, 0);
  2258. log_debug(LD_CIRC,"Finished sending 'created' cell.");
  2259. if (!is_local_addr(&circ->p_conn->_base.addr) &&
  2260. !connection_or_nonopen_was_started_here(circ->p_conn)) {
  2261. /* record that we could process create cells from a non-local conn
  2262. * that we didn't initiate; presumably this means that create cells
  2263. * can reach us too. */
  2264. router_orport_found_reachable();
  2265. }
  2266. return 0;
  2267. }
  2268. /** Choose a length for a circuit of purpose <b>purpose</b>.
  2269. * Default length is 3 + the number of endpoints that would give something
  2270. * away. If the routerlist <b>routers</b> doesn't have enough routers
  2271. * to handle the desired path length, return as large a path length as
  2272. * is feasible, except if it's less than 2, in which case return -1.
  2273. */
  2274. static int
  2275. new_route_len(uint8_t purpose, extend_info_t *exit,
  2276. smartlist_t *nodes)
  2277. {
  2278. int num_acceptable_routers;
  2279. int routelen;
  2280. tor_assert(nodes);
  2281. routelen = DEFAULT_ROUTE_LEN;
  2282. if (exit &&
  2283. purpose != CIRCUIT_PURPOSE_TESTING &&
  2284. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  2285. routelen++;
  2286. num_acceptable_routers = count_acceptable_nodes(nodes);
  2287. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  2288. routelen, num_acceptable_routers, smartlist_len(nodes));
  2289. if (num_acceptable_routers < 2) {
  2290. log_info(LD_CIRC,
  2291. "Not enough acceptable routers (%d). Discarding this circuit.",
  2292. num_acceptable_routers);
  2293. return -1;
  2294. }
  2295. if (num_acceptable_routers < routelen) {
  2296. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  2297. routelen, num_acceptable_routers);
  2298. routelen = num_acceptable_routers;
  2299. }
  2300. return routelen;
  2301. }
  2302. /** Return a newly allocated list of uint16_t * for each predicted port not
  2303. * handled by a current circuit. */
  2304. static smartlist_t *
  2305. circuit_get_unhandled_ports(time_t now)
  2306. {
  2307. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  2308. circuit_remove_handled_ports(dest);
  2309. return dest;
  2310. }
  2311. /** Return 1 if we already have circuits present or on the way for
  2312. * all anticipated ports. Return 0 if we should make more.
  2313. *
  2314. * If we're returning 0, set need_uptime and need_capacity to
  2315. * indicate any requirements that the unhandled ports have.
  2316. */
  2317. int
  2318. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  2319. int *need_capacity)
  2320. {
  2321. int i, enough;
  2322. uint16_t *port;
  2323. smartlist_t *sl = circuit_get_unhandled_ports(now);
  2324. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  2325. tor_assert(need_uptime);
  2326. tor_assert(need_capacity);
  2327. // Always predict need_capacity
  2328. *need_capacity = 1;
  2329. enough = (smartlist_len(sl) == 0);
  2330. for (i = 0; i < smartlist_len(sl); ++i) {
  2331. port = smartlist_get(sl, i);
  2332. if (smartlist_string_num_isin(LongLivedServices, *port))
  2333. *need_uptime = 1;
  2334. tor_free(port);
  2335. }
  2336. smartlist_free(sl);
  2337. return enough;
  2338. }
  2339. /** Return 1 if <b>node</b> can handle one or more of the ports in
  2340. * <b>needed_ports</b>, else return 0.
  2341. */
  2342. static int
  2343. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  2344. { /* XXXX MOVE */
  2345. int i;
  2346. uint16_t port;
  2347. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  2348. addr_policy_result_t r;
  2349. /* alignment issues aren't a worry for this dereference, since
  2350. needed_ports is explicitly a smartlist of uint16_t's */
  2351. port = *(uint16_t *)smartlist_get(needed_ports, i);
  2352. tor_assert(port);
  2353. if (node)
  2354. r = compare_tor_addr_to_node_policy(NULL, port, node);
  2355. else
  2356. continue;
  2357. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2358. return 1;
  2359. }
  2360. return 0;
  2361. }
  2362. /** Return true iff <b>conn</b> needs another general circuit to be
  2363. * built. */
  2364. static int
  2365. ap_stream_wants_exit_attention(connection_t *conn)
  2366. {
  2367. entry_connection_t *entry;
  2368. if (conn->type != CONN_TYPE_AP)
  2369. return 0;
  2370. entry = TO_ENTRY_CONN(conn);
  2371. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  2372. !conn->marked_for_close &&
  2373. !(entry->want_onehop) && /* ignore one-hop streams */
  2374. !(entry->use_begindir) && /* ignore targeted dir fetches */
  2375. !(entry->chosen_exit_name) && /* ignore defined streams */
  2376. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  2377. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  2378. MIN_CIRCUITS_HANDLING_STREAM))
  2379. return 1;
  2380. return 0;
  2381. }
  2382. /** Return a pointer to a suitable router to be the exit node for the
  2383. * general-purpose circuit we're about to build.
  2384. *
  2385. * Look through the connection array, and choose a router that maximizes
  2386. * the number of pending streams that can exit from this router.
  2387. *
  2388. * Return NULL if we can't find any suitable routers.
  2389. */
  2390. static const node_t *
  2391. choose_good_exit_server_general(int need_uptime, int need_capacity)
  2392. {
  2393. int *n_supported;
  2394. int n_pending_connections = 0;
  2395. smartlist_t *connections;
  2396. int best_support = -1;
  2397. int n_best_support=0;
  2398. const or_options_t *options = get_options();
  2399. const smartlist_t *the_nodes;
  2400. const node_t *node=NULL;
  2401. connections = get_connection_array();
  2402. /* Count how many connections are waiting for a circuit to be built.
  2403. * We use this for log messages now, but in the future we may depend on it.
  2404. */
  2405. SMARTLIST_FOREACH(connections, connection_t *, conn,
  2406. {
  2407. if (ap_stream_wants_exit_attention(conn))
  2408. ++n_pending_connections;
  2409. });
  2410. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  2411. // n_pending_connections);
  2412. /* Now we count, for each of the routers in the directory, how many
  2413. * of the pending connections could possibly exit from that
  2414. * router (n_supported[i]). (We can't be sure about cases where we
  2415. * don't know the IP address of the pending connection.)
  2416. *
  2417. * -1 means "Don't use this router at all."
  2418. */
  2419. the_nodes = nodelist_get_list();
  2420. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  2421. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2422. const int i = node_sl_idx;
  2423. if (router_digest_is_me(node->identity)) {
  2424. n_supported[i] = -1;
  2425. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  2426. /* XXX there's probably a reverse predecessor attack here, but
  2427. * it's slow. should we take this out? -RD
  2428. */
  2429. continue;
  2430. }
  2431. if (!node_has_descriptor(node)) {
  2432. n_supported[i] = -1;
  2433. continue;
  2434. }
  2435. if (!node->is_running || node->is_bad_exit) {
  2436. n_supported[i] = -1;
  2437. continue; /* skip routers that are known to be down or bad exits */
  2438. }
  2439. if (routerset_contains_node(options->_ExcludeExitNodesUnion, node)) {
  2440. n_supported[i] = -1;
  2441. continue; /* user asked us not to use it, no matter what */
  2442. }
  2443. if (options->ExitNodes &&
  2444. !routerset_contains_node(options->ExitNodes, node)) {
  2445. n_supported[i] = -1;
  2446. continue; /* not one of our chosen exit nodes */
  2447. }
  2448. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  2449. n_supported[i] = -1;
  2450. continue; /* skip routers that are not suitable. Don't worry if
  2451. * this makes us reject all the possible routers: if so,
  2452. * we'll retry later in this function with need_update and
  2453. * need_capacity set to 0. */
  2454. }
  2455. if (!(node->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
  2456. /* if it's invalid and we don't want it */
  2457. n_supported[i] = -1;
  2458. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  2459. // router->nickname, i);
  2460. continue; /* skip invalid routers */
  2461. }
  2462. if (options->ExcludeSingleHopRelays &&
  2463. node_allows_single_hop_exits(node)) {
  2464. n_supported[i] = -1;
  2465. continue;
  2466. }
  2467. if (node_exit_policy_rejects_all(node)) {
  2468. n_supported[i] = -1;
  2469. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  2470. // router->nickname, i);
  2471. continue; /* skip routers that reject all */
  2472. }
  2473. n_supported[i] = 0;
  2474. /* iterate over connections */
  2475. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  2476. if (!ap_stream_wants_exit_attention(conn))
  2477. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  2478. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  2479. ++n_supported[i];
  2480. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  2481. // router->nickname, i, n_supported[i]);
  2482. } else {
  2483. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  2484. // router->nickname, i);
  2485. }
  2486. } SMARTLIST_FOREACH_END(conn);
  2487. if (n_pending_connections > 0 && n_supported[i] == 0) {
  2488. /* Leave best_support at -1 if that's where it is, so we can
  2489. * distinguish it later. */
  2490. continue;
  2491. }
  2492. if (n_supported[i] > best_support) {
  2493. /* If this router is better than previous ones, remember its index
  2494. * and goodness, and start counting how many routers are this good. */
  2495. best_support = n_supported[i]; n_best_support=1;
  2496. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  2497. // router->nickname);
  2498. } else if (n_supported[i] == best_support) {
  2499. /* If this router is _as good_ as the best one, just increment the
  2500. * count of equally good routers.*/
  2501. ++n_best_support;
  2502. }
  2503. } SMARTLIST_FOREACH_END(node);
  2504. log_info(LD_CIRC,
  2505. "Found %d servers that might support %d/%d pending connections.",
  2506. n_best_support, best_support >= 0 ? best_support : 0,
  2507. n_pending_connections);
  2508. /* If any routers definitely support any pending connections, choose one
  2509. * at random. */
  2510. if (best_support > 0) {
  2511. smartlist_t *supporting = smartlist_create();
  2512. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  2513. if (n_supported[node_sl_idx] == best_support)
  2514. smartlist_add(supporting, (void*)node);
  2515. });
  2516. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2517. smartlist_free(supporting);
  2518. } else {
  2519. /* Either there are no pending connections, or no routers even seem to
  2520. * possibly support any of them. Choose a router at random that satisfies
  2521. * at least one predicted exit port. */
  2522. int attempt;
  2523. smartlist_t *needed_ports, *supporting;
  2524. if (best_support == -1) {
  2525. if (need_uptime || need_capacity) {
  2526. log_info(LD_CIRC,
  2527. "We couldn't find any live%s%s routers; falling back "
  2528. "to list of all routers.",
  2529. need_capacity?", fast":"",
  2530. need_uptime?", stable":"");
  2531. tor_free(n_supported);
  2532. return choose_good_exit_server_general(0, 0);
  2533. }
  2534. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  2535. "choosing a doomed exit at random.",
  2536. options->_ExcludeExitNodesUnion ? " or are Excluded" : "");
  2537. }
  2538. supporting = smartlist_create();
  2539. needed_ports = circuit_get_unhandled_ports(time(NULL));
  2540. for (attempt = 0; attempt < 2; attempt++) {
  2541. /* try once to pick only from routers that satisfy a needed port,
  2542. * then if there are none, pick from any that support exiting. */
  2543. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2544. if (n_supported[node_sl_idx] != -1 &&
  2545. (attempt || node_handles_some_port(node, needed_ports))) {
  2546. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  2547. // try, router->nickname);
  2548. smartlist_add(supporting, (void*)node);
  2549. }
  2550. } SMARTLIST_FOREACH_END(node);
  2551. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2552. if (node)
  2553. break;
  2554. smartlist_clear(supporting);
  2555. }
  2556. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  2557. smartlist_free(needed_ports);
  2558. smartlist_free(supporting);
  2559. }
  2560. tor_free(n_supported);
  2561. if (node) {
  2562. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  2563. return node;
  2564. }
  2565. if (options->ExitNodes) {
  2566. log_warn(LD_CIRC,
  2567. "No specified %sexit routers seem to be running: "
  2568. "can't choose an exit.",
  2569. options->_ExcludeExitNodesUnion ? "non-excluded " : "");
  2570. }
  2571. return NULL;
  2572. }
  2573. /** Return a pointer to a suitable router to be the exit node for the
  2574. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  2575. * if no router is suitable).
  2576. *
  2577. * For general-purpose circuits, pass it off to
  2578. * choose_good_exit_server_general()
  2579. *
  2580. * For client-side rendezvous circuits, choose a random node, weighted
  2581. * toward the preferences in 'options'.
  2582. */
  2583. static const node_t *
  2584. choose_good_exit_server(uint8_t purpose,
  2585. int need_uptime, int need_capacity, int is_internal)
  2586. {
  2587. const or_options_t *options = get_options();
  2588. router_crn_flags_t flags = CRN_NEED_DESC;
  2589. if (need_uptime)
  2590. flags |= CRN_NEED_UPTIME;
  2591. if (need_capacity)
  2592. flags |= CRN_NEED_CAPACITY;
  2593. switch (purpose) {
  2594. case CIRCUIT_PURPOSE_C_GENERAL:
  2595. if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
  2596. flags |= CRN_ALLOW_INVALID;
  2597. if (is_internal) /* pick it like a middle hop */
  2598. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2599. else
  2600. return choose_good_exit_server_general(need_uptime,need_capacity);
  2601. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2602. if (options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS)
  2603. flags |= CRN_ALLOW_INVALID;
  2604. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2605. }
  2606. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  2607. tor_fragile_assert();
  2608. return NULL;
  2609. }
  2610. /** Log a warning if the user specified an exit for the circuit that
  2611. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  2612. static void
  2613. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  2614. {
  2615. const or_options_t *options = get_options();
  2616. routerset_t *rs = options->ExcludeNodes;
  2617. const char *description;
  2618. uint8_t purpose = circ->_base.purpose;
  2619. if (circ->build_state->onehop_tunnel)
  2620. return;
  2621. switch (purpose)
  2622. {
  2623. default:
  2624. case CIRCUIT_PURPOSE_OR:
  2625. case CIRCUIT_PURPOSE_INTRO_POINT:
  2626. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  2627. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  2628. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  2629. (int)purpose,
  2630. circuit_purpose_to_string(purpose));
  2631. return;
  2632. case CIRCUIT_PURPOSE_C_GENERAL:
  2633. if (circ->build_state->is_internal)
  2634. return;
  2635. description = "requested exit node";
  2636. rs = options->_ExcludeExitNodesUnion;
  2637. break;
  2638. case CIRCUIT_PURPOSE_C_INTRODUCING:
  2639. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  2640. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  2641. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  2642. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  2643. case CIRCUIT_PURPOSE_S_REND_JOINED:
  2644. case CIRCUIT_PURPOSE_TESTING:
  2645. return;
  2646. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2647. case CIRCUIT_PURPOSE_C_REND_READY:
  2648. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  2649. case CIRCUIT_PURPOSE_C_REND_JOINED:
  2650. description = "chosen rendezvous point";
  2651. break;
  2652. case CIRCUIT_PURPOSE_CONTROLLER:
  2653. rs = options->_ExcludeExitNodesUnion;
  2654. description = "controller-selected circuit target";
  2655. break;
  2656. }
  2657. if (routerset_contains_extendinfo(rs, exit)) {
  2658. /* We should never get here if StrictNodes is set to 1. */
  2659. if (options->StrictNodes) {
  2660. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  2661. "even though StrictNodes is set. Please report. "
  2662. "(Circuit purpose: %s)",
  2663. description, extend_info_describe(exit),
  2664. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2665. circuit_purpose_to_string(purpose));
  2666. } else {
  2667. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  2668. "ExcludeNodes%s, because no better options were available. To "
  2669. "prevent this (and possibly break your Tor functionality), "
  2670. "set the StrictNodes configuration option. "
  2671. "(Circuit purpose: %s)",
  2672. description, extend_info_describe(exit),
  2673. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2674. circuit_purpose_to_string(purpose));
  2675. }
  2676. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  2677. }
  2678. return;
  2679. }
  2680. /** Decide a suitable length for circ's cpath, and pick an exit
  2681. * router (or use <b>exit</b> if provided). Store these in the
  2682. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  2683. static int
  2684. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  2685. {
  2686. cpath_build_state_t *state = circ->build_state;
  2687. if (state->onehop_tunnel) {
  2688. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  2689. state->desired_path_len = 1;
  2690. } else {
  2691. int r = new_route_len(circ->_base.purpose, exit, nodelist_get_list());
  2692. if (r < 1) /* must be at least 1 */
  2693. return -1;
  2694. state->desired_path_len = r;
  2695. }
  2696. if (exit) { /* the circuit-builder pre-requested one */
  2697. warn_if_last_router_excluded(circ, exit);
  2698. log_info(LD_CIRC,"Using requested exit node '%s'",
  2699. extend_info_describe(exit));
  2700. exit = extend_info_dup(exit);
  2701. } else { /* we have to decide one */
  2702. const node_t *node =
  2703. choose_good_exit_server(circ->_base.purpose, state->need_uptime,
  2704. state->need_capacity, state->is_internal);
  2705. if (!node) {
  2706. log_warn(LD_CIRC,"failed to choose an exit server");
  2707. return -1;
  2708. }
  2709. exit = extend_info_from_node(node);
  2710. tor_assert(exit);
  2711. }
  2712. state->chosen_exit = exit;
  2713. return 0;
  2714. }
  2715. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  2716. * hop to the cpath reflecting this. Don't send the next extend cell --
  2717. * the caller will do this if it wants to.
  2718. */
  2719. int
  2720. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2721. {
  2722. cpath_build_state_t *state;
  2723. tor_assert(exit);
  2724. tor_assert(circ);
  2725. state = circ->build_state;
  2726. tor_assert(state);
  2727. extend_info_free(state->chosen_exit);
  2728. state->chosen_exit = extend_info_dup(exit);
  2729. ++circ->build_state->desired_path_len;
  2730. onion_append_hop(&circ->cpath, exit);
  2731. return 0;
  2732. }
  2733. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  2734. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  2735. * send the next extend cell to begin connecting to that hop.
  2736. */
  2737. int
  2738. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2739. {
  2740. int err_reason = 0;
  2741. warn_if_last_router_excluded(circ, exit);
  2742. circuit_append_new_exit(circ, exit);
  2743. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2744. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  2745. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  2746. extend_info_describe(exit));
  2747. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2748. return -1;
  2749. }
  2750. return 0;
  2751. }
  2752. /** Return the number of routers in <b>routers</b> that are currently up
  2753. * and available for building circuits through.
  2754. */
  2755. static int
  2756. count_acceptable_nodes(smartlist_t *nodes)
  2757. {
  2758. int num=0;
  2759. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  2760. // log_debug(LD_CIRC,
  2761. // "Contemplating whether router %d (%s) is a new option.",
  2762. // i, r->nickname);
  2763. if (! node->is_running)
  2764. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  2765. continue;
  2766. if (! node->is_valid)
  2767. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  2768. continue;
  2769. if (! node_has_descriptor(node))
  2770. continue;
  2771. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  2772. * allows this node in some places, then we're getting an inaccurate
  2773. * count. For now, be conservative and don't count it. But later we
  2774. * should try to be smarter. */
  2775. ++num;
  2776. } SMARTLIST_FOREACH_END(node);
  2777. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  2778. return num;
  2779. }
  2780. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  2781. * This function is used to extend cpath by another hop.
  2782. */
  2783. void
  2784. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  2785. {
  2786. if (*head_ptr) {
  2787. new_hop->next = (*head_ptr);
  2788. new_hop->prev = (*head_ptr)->prev;
  2789. (*head_ptr)->prev->next = new_hop;
  2790. (*head_ptr)->prev = new_hop;
  2791. } else {
  2792. *head_ptr = new_hop;
  2793. new_hop->prev = new_hop->next = new_hop;
  2794. }
  2795. }
  2796. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  2797. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  2798. * to length <b>cur_len</b> to decide a suitable middle hop for a
  2799. * circuit. In particular, make sure we don't pick the exit node or its
  2800. * family, and make sure we don't duplicate any previous nodes or their
  2801. * families. */
  2802. static const node_t *
  2803. choose_good_middle_server(uint8_t purpose,
  2804. cpath_build_state_t *state,
  2805. crypt_path_t *head,
  2806. int cur_len)
  2807. {
  2808. int i;
  2809. const node_t *r, *choice;
  2810. crypt_path_t *cpath;
  2811. smartlist_t *excluded;
  2812. const or_options_t *options = get_options();
  2813. router_crn_flags_t flags = CRN_NEED_DESC;
  2814. tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
  2815. purpose <= _CIRCUIT_PURPOSE_MAX);
  2816. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  2817. excluded = smartlist_create();
  2818. if ((r = build_state_get_exit_node(state))) {
  2819. nodelist_add_node_and_family(excluded, r);
  2820. }
  2821. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  2822. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  2823. nodelist_add_node_and_family(excluded, r);
  2824. }
  2825. }
  2826. if (state->need_uptime)
  2827. flags |= CRN_NEED_UPTIME;
  2828. if (state->need_capacity)
  2829. flags |= CRN_NEED_CAPACITY;
  2830. if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
  2831. flags |= CRN_ALLOW_INVALID;
  2832. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2833. smartlist_free(excluded);
  2834. return choice;
  2835. }
  2836. /** Pick a good entry server for the circuit to be built according to
  2837. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  2838. * router (if we're an OR), and respect firewall settings; if we're
  2839. * configured to use entry guards, return one.
  2840. *
  2841. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  2842. * guard, not for any particular circuit.
  2843. */
  2844. static const node_t *
  2845. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  2846. {
  2847. const node_t *choice;
  2848. smartlist_t *excluded;
  2849. const or_options_t *options = get_options();
  2850. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  2851. const node_t *node;
  2852. if (state && options->UseEntryGuards &&
  2853. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  2854. /* This is request for an entry server to use for a regular circuit,
  2855. * and we use entry guard nodes. Just return one of the guard nodes. */
  2856. return choose_random_entry(state);
  2857. }
  2858. excluded = smartlist_create();
  2859. if (state && (node = build_state_get_exit_node(state))) {
  2860. /* Exclude the exit node from the state, if we have one. Also exclude its
  2861. * family. */
  2862. nodelist_add_node_and_family(excluded, node);
  2863. }
  2864. if (firewall_is_fascist_or()) {
  2865. /* Exclude all ORs that we can't reach through our firewall */
  2866. smartlist_t *nodes = nodelist_get_list();
  2867. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  2868. if (!fascist_firewall_allows_node(node))
  2869. smartlist_add(excluded, (void*)node);
  2870. });
  2871. }
  2872. /* and exclude current entry guards and their families, if applicable */
  2873. if (options->UseEntryGuards && entry_guards) {
  2874. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2875. {
  2876. if ((node = node_get_by_id(entry->identity))) {
  2877. nodelist_add_node_and_family(excluded, node);
  2878. }
  2879. });
  2880. }
  2881. if (state) {
  2882. if (state->need_uptime)
  2883. flags |= CRN_NEED_UPTIME;
  2884. if (state->need_capacity)
  2885. flags |= CRN_NEED_CAPACITY;
  2886. }
  2887. if (options->_AllowInvalid & ALLOW_INVALID_ENTRY)
  2888. flags |= CRN_ALLOW_INVALID;
  2889. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2890. smartlist_free(excluded);
  2891. return choice;
  2892. }
  2893. /** Return the first non-open hop in cpath, or return NULL if all
  2894. * hops are open. */
  2895. static crypt_path_t *
  2896. onion_next_hop_in_cpath(crypt_path_t *cpath)
  2897. {
  2898. crypt_path_t *hop = cpath;
  2899. do {
  2900. if (hop->state != CPATH_STATE_OPEN)
  2901. return hop;
  2902. hop = hop->next;
  2903. } while (hop != cpath);
  2904. return NULL;
  2905. }
  2906. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  2907. * based on <b>state</b>. Append the hop info to head_ptr.
  2908. */
  2909. static int
  2910. onion_extend_cpath(origin_circuit_t *circ)
  2911. {
  2912. uint8_t purpose = circ->_base.purpose;
  2913. cpath_build_state_t *state = circ->build_state;
  2914. int cur_len = circuit_get_cpath_len(circ);
  2915. extend_info_t *info = NULL;
  2916. if (cur_len >= state->desired_path_len) {
  2917. log_debug(LD_CIRC, "Path is complete: %d steps long",
  2918. state->desired_path_len);
  2919. return 1;
  2920. }
  2921. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  2922. state->desired_path_len);
  2923. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  2924. info = extend_info_dup(state->chosen_exit);
  2925. } else if (cur_len == 0) { /* picking first node */
  2926. const node_t *r = choose_good_entry_server(purpose, state);
  2927. if (r) {
  2928. info = extend_info_from_node(r);
  2929. tor_assert(info);
  2930. }
  2931. } else {
  2932. const node_t *r =
  2933. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  2934. if (r) {
  2935. info = extend_info_from_node(r);
  2936. tor_assert(info);
  2937. }
  2938. }
  2939. if (!info) {
  2940. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  2941. "this circuit.", cur_len);
  2942. return -1;
  2943. }
  2944. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  2945. extend_info_describe(info),
  2946. cur_len+1, build_state_get_exit_nickname(state));
  2947. onion_append_hop(&circ->cpath, info);
  2948. extend_info_free(info);
  2949. return 0;
  2950. }
  2951. /** Create a new hop, annotate it with information about its
  2952. * corresponding router <b>choice</b>, and append it to the
  2953. * end of the cpath <b>head_ptr</b>. */
  2954. static int
  2955. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  2956. {
  2957. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  2958. /* link hop into the cpath, at the end. */
  2959. onion_append_to_cpath(head_ptr, hop);
  2960. hop->magic = CRYPT_PATH_MAGIC;
  2961. hop->state = CPATH_STATE_CLOSED;
  2962. hop->extend_info = extend_info_dup(choice);
  2963. hop->package_window = circuit_initial_package_window();
  2964. hop->deliver_window = CIRCWINDOW_START;
  2965. return 0;
  2966. }
  2967. /** Allocate a new extend_info object based on the various arguments. */
  2968. extend_info_t *
  2969. extend_info_alloc(const char *nickname, const char *digest,
  2970. crypto_pk_env_t *onion_key,
  2971. const tor_addr_t *addr, uint16_t port)
  2972. {
  2973. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  2974. memcpy(info->identity_digest, digest, DIGEST_LEN);
  2975. if (nickname)
  2976. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  2977. if (onion_key)
  2978. info->onion_key = crypto_pk_dup_key(onion_key);
  2979. tor_addr_copy(&info->addr, addr);
  2980. info->port = port;
  2981. return info;
  2982. }
  2983. /** Allocate and return a new extend_info_t that can be used to build a
  2984. * circuit to or through the router <b>r</b>. */
  2985. extend_info_t *
  2986. extend_info_from_router(const routerinfo_t *r)
  2987. {
  2988. tor_addr_t addr;
  2989. tor_assert(r);
  2990. tor_addr_from_ipv4h(&addr, r->addr);
  2991. return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
  2992. r->onion_pkey, &addr, r->or_port);
  2993. }
  2994. /** Allocate and return a new extend_info that can be used to build a ircuit
  2995. * to or through the node <b>node</b>. May return NULL if there is not
  2996. * enough info about <b>node</b> to extend to it--for example, if there
  2997. * is no routerinfo_t or microdesc_t.
  2998. **/
  2999. extend_info_t *
  3000. extend_info_from_node(const node_t *node)
  3001. {
  3002. if (node->ri) {
  3003. return extend_info_from_router(node->ri);
  3004. } else if (node->rs && node->md) {
  3005. tor_addr_t addr;
  3006. tor_addr_from_ipv4h(&addr, node->rs->addr);
  3007. return extend_info_alloc(node->rs->nickname,
  3008. node->identity,
  3009. node->md->onion_pkey,
  3010. &addr,
  3011. node->rs->or_port);
  3012. } else {
  3013. return NULL;
  3014. }
  3015. }
  3016. /** Release storage held by an extend_info_t struct. */
  3017. void
  3018. extend_info_free(extend_info_t *info)
  3019. {
  3020. if (!info)
  3021. return;
  3022. crypto_free_pk_env(info->onion_key);
  3023. tor_free(info);
  3024. }
  3025. /** Allocate and return a new extend_info_t with the same contents as
  3026. * <b>info</b>. */
  3027. extend_info_t *
  3028. extend_info_dup(extend_info_t *info)
  3029. {
  3030. extend_info_t *newinfo;
  3031. tor_assert(info);
  3032. newinfo = tor_malloc(sizeof(extend_info_t));
  3033. memcpy(newinfo, info, sizeof(extend_info_t));
  3034. if (info->onion_key)
  3035. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  3036. else
  3037. newinfo->onion_key = NULL;
  3038. return newinfo;
  3039. }
  3040. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  3041. * If there is no chosen exit, or if we don't know the routerinfo_t for
  3042. * the chosen exit, return NULL.
  3043. */
  3044. const node_t *
  3045. build_state_get_exit_node(cpath_build_state_t *state)
  3046. {
  3047. if (!state || !state->chosen_exit)
  3048. return NULL;
  3049. return node_get_by_id(state->chosen_exit->identity_digest);
  3050. }
  3051. /** Return the nickname for the chosen exit router in <b>state</b>. If
  3052. * there is no chosen exit, or if we don't know the routerinfo_t for the
  3053. * chosen exit, return NULL.
  3054. */
  3055. const char *
  3056. build_state_get_exit_nickname(cpath_build_state_t *state)
  3057. {
  3058. if (!state || !state->chosen_exit)
  3059. return NULL;
  3060. return state->chosen_exit->nickname;
  3061. }
  3062. /** Check whether the entry guard <b>e</b> is usable, given the directory
  3063. * authorities' opinion about the router (stored in <b>ri</b>) and the user's
  3064. * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
  3065. * accordingly. Return true iff the entry guard's status changes.
  3066. *
  3067. * If it's not usable, set *<b>reason</b> to a static string explaining why.
  3068. */
  3069. static int
  3070. entry_guard_set_status(entry_guard_t *e, const node_t *node,
  3071. time_t now, const or_options_t *options,
  3072. const char **reason)
  3073. {
  3074. char buf[HEX_DIGEST_LEN+1];
  3075. int changed = 0;
  3076. *reason = NULL;
  3077. /* Do we want to mark this guard as bad? */
  3078. if (!node)
  3079. *reason = "unlisted";
  3080. else if (!node->is_running)
  3081. *reason = "down";
  3082. else if (options->UseBridges && (!node->ri ||
  3083. node->ri->purpose != ROUTER_PURPOSE_BRIDGE))
  3084. *reason = "not a bridge";
  3085. else if (options->UseBridges && !node_is_a_configured_bridge(node))
  3086. *reason = "not a configured bridge";
  3087. else if (!options->UseBridges && !node->is_possible_guard &&
  3088. !routerset_contains_node(options->EntryNodes,node))
  3089. *reason = "not recommended as a guard";
  3090. else if (routerset_contains_node(options->ExcludeNodes, node))
  3091. *reason = "excluded";
  3092. if (*reason && ! e->bad_since) {
  3093. /* Router is newly bad. */
  3094. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  3095. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  3096. e->nickname, buf, *reason);
  3097. e->bad_since = now;
  3098. control_event_guard(e->nickname, e->identity, "BAD");
  3099. changed = 1;
  3100. } else if (!*reason && e->bad_since) {
  3101. /* There's nothing wrong with the router any more. */
  3102. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  3103. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  3104. "marking as ok.", e->nickname, buf);
  3105. e->bad_since = 0;
  3106. control_event_guard(e->nickname, e->identity, "GOOD");
  3107. changed = 1;
  3108. }
  3109. return changed;
  3110. }
  3111. /** Return true iff enough time has passed since we last tried to connect
  3112. * to the unreachable guard <b>e</b> that we're willing to try again. */
  3113. static int
  3114. entry_is_time_to_retry(entry_guard_t *e, time_t now)
  3115. {
  3116. long diff;
  3117. if (e->last_attempted < e->unreachable_since)
  3118. return 1;
  3119. diff = now - e->unreachable_since;
  3120. if (diff < 6*60*60)
  3121. return now > (e->last_attempted + 60*60);
  3122. else if (diff < 3*24*60*60)
  3123. return now > (e->last_attempted + 4*60*60);
  3124. else if (diff < 7*24*60*60)
  3125. return now > (e->last_attempted + 18*60*60);
  3126. else
  3127. return now > (e->last_attempted + 36*60*60);
  3128. }
  3129. /** Return the node corresponding to <b>e</b>, if <b>e</b> is
  3130. * working well enough that we are willing to use it as an entry
  3131. * right now. (Else return NULL.) In particular, it must be
  3132. * - Listed as either up or never yet contacted;
  3133. * - Present in the routerlist;
  3134. * - Listed as 'stable' or 'fast' by the current dirserver consensus,
  3135. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
  3136. * (unless it's a configured EntryNode);
  3137. * - Allowed by our current ReachableORAddresses config option; and
  3138. * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
  3139. * is true).
  3140. *
  3141. * If the answer is no, set *<b>msg</b> to an explanation of why.
  3142. */
  3143. static INLINE const node_t *
  3144. entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
  3145. int assume_reachable, const char **msg)
  3146. {
  3147. const node_t *node;
  3148. const or_options_t *options = get_options();
  3149. tor_assert(msg);
  3150. if (e->bad_since) {
  3151. *msg = "bad";
  3152. return NULL;
  3153. }
  3154. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  3155. if (!assume_reachable && !e->can_retry &&
  3156. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
  3157. *msg = "unreachable";
  3158. return NULL;
  3159. }
  3160. node = node_get_by_id(e->identity);
  3161. if (!node || !node_has_descriptor(node)) {
  3162. *msg = "no descriptor";
  3163. return NULL;
  3164. }
  3165. if (get_options()->UseBridges) {
  3166. if (node_get_purpose(node) != ROUTER_PURPOSE_BRIDGE) {
  3167. *msg = "not a bridge";
  3168. return NULL;
  3169. }
  3170. if (!node_is_a_configured_bridge(node)) {
  3171. *msg = "not a configured bridge";
  3172. return NULL;
  3173. }
  3174. } else { /* !get_options()->UseBridges */
  3175. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  3176. *msg = "not general-purpose";
  3177. return NULL;
  3178. }
  3179. }
  3180. if (routerset_contains_node(options->EntryNodes, node)) {
  3181. /* they asked for it, they get it */
  3182. need_uptime = need_capacity = 0;
  3183. }
  3184. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  3185. *msg = "not fast/stable";
  3186. return NULL;
  3187. }
  3188. if (!fascist_firewall_allows_node(node)) {
  3189. *msg = "unreachable by config";
  3190. return NULL;
  3191. }
  3192. return node;
  3193. }
  3194. /** Return the number of entry guards that we think are usable. */
  3195. static int
  3196. num_live_entry_guards(void)
  3197. {
  3198. int n = 0;
  3199. const char *msg;
  3200. if (! entry_guards)
  3201. return 0;
  3202. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3203. {
  3204. if (entry_is_live(entry, 0, 1, 0, &msg))
  3205. ++n;
  3206. });
  3207. return n;
  3208. }
  3209. /** If <b>digest</b> matches the identity of any node in the
  3210. * entry_guards list, return that node. Else return NULL. */
  3211. static INLINE entry_guard_t *
  3212. is_an_entry_guard(const char *digest)
  3213. {
  3214. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3215. if (tor_memeq(digest, entry->identity, DIGEST_LEN))
  3216. return entry;
  3217. );
  3218. return NULL;
  3219. }
  3220. /** Dump a description of our list of entry guards to the log at level
  3221. * <b>severity</b>. */
  3222. static void
  3223. log_entry_guards(int severity)
  3224. {
  3225. smartlist_t *elements = smartlist_create();
  3226. char *s;
  3227. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e)
  3228. {
  3229. const char *msg = NULL;
  3230. char *cp;
  3231. if (entry_is_live(e, 0, 1, 0, &msg))
  3232. tor_asprintf(&cp, "%s [%s] (up %s)",
  3233. e->nickname,
  3234. hex_str(e->identity, DIGEST_LEN),
  3235. e->made_contact ? "made-contact" : "never-contacted");
  3236. else
  3237. tor_asprintf(&cp, "%s [%s] (%s, %s)",
  3238. e->nickname,
  3239. hex_str(e->identity, DIGEST_LEN),
  3240. msg,
  3241. e->made_contact ? "made-contact" : "never-contacted");
  3242. smartlist_add(elements, cp);
  3243. }
  3244. SMARTLIST_FOREACH_END(e);
  3245. s = smartlist_join_strings(elements, ",", 0, NULL);
  3246. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  3247. smartlist_free(elements);
  3248. log_fn(severity,LD_CIRC,"%s",s);
  3249. tor_free(s);
  3250. }
  3251. /** Called when one or more guards that we would previously have used for some
  3252. * purpose are no longer in use because a higher-priority guard has become
  3253. * usable again. */
  3254. static void
  3255. control_event_guard_deferred(void)
  3256. {
  3257. /* XXXX We don't actually have a good way to figure out _how many_ entries
  3258. * are live for some purpose. We need an entry_is_even_slightly_live()
  3259. * function for this to work right. NumEntryGuards isn't reliable: if we
  3260. * need guards with weird properties, we can have more than that number
  3261. * live.
  3262. **/
  3263. #if 0
  3264. int n = 0;
  3265. const char *msg;
  3266. const or_options_t *options = get_options();
  3267. if (!entry_guards)
  3268. return;
  3269. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3270. {
  3271. if (entry_is_live(entry, 0, 1, 0, &msg)) {
  3272. if (n++ == options->NumEntryGuards) {
  3273. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  3274. return;
  3275. }
  3276. }
  3277. });
  3278. #endif
  3279. }
  3280. /** Add a new (preferably stable and fast) router to our
  3281. * entry_guards list. Return a pointer to the router if we succeed,
  3282. * or NULL if we can't find any more suitable entries.
  3283. *
  3284. * If <b>chosen</b> is defined, use that one, and if it's not
  3285. * already in our entry_guards list, put it at the *beginning*.
  3286. * Else, put the one we pick at the end of the list. */
  3287. static const node_t *
  3288. add_an_entry_guard(const node_t *chosen, int reset_status, int prepend)
  3289. {
  3290. const node_t *node;
  3291. entry_guard_t *entry;
  3292. if (chosen) {
  3293. node = chosen;
  3294. entry = is_an_entry_guard(node->identity);
  3295. if (entry) {
  3296. if (reset_status) {
  3297. entry->bad_since = 0;
  3298. entry->can_retry = 1;
  3299. }
  3300. return NULL;
  3301. }
  3302. } else {
  3303. node = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  3304. if (!node)
  3305. return NULL;
  3306. }
  3307. entry = tor_malloc_zero(sizeof(entry_guard_t));
  3308. log_info(LD_CIRC, "Chose %s as new entry guard.",
  3309. node_describe(node));
  3310. strlcpy(entry->nickname, node_get_nickname(node), sizeof(entry->nickname));
  3311. memcpy(entry->identity, node->identity, DIGEST_LEN);
  3312. /* Choose expiry time smudged over the past month. The goal here
  3313. * is to a) spread out when Tor clients rotate their guards, so they
  3314. * don't all select them on the same day, and b) avoid leaving a
  3315. * precise timestamp in the state file about when we first picked
  3316. * this guard. For details, see the Jan 2010 or-dev thread. */
  3317. entry->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
  3318. entry->chosen_by_version = tor_strdup(VERSION);
  3319. if (prepend)
  3320. smartlist_insert(entry_guards, 0, entry);
  3321. else
  3322. smartlist_add(entry_guards, entry);
  3323. control_event_guard(entry->nickname, entry->identity, "NEW");
  3324. control_event_guard_deferred();
  3325. log_entry_guards(LOG_INFO);
  3326. return node;
  3327. }
  3328. /** If the use of entry guards is configured, choose more entry guards
  3329. * until we have enough in the list. */
  3330. static void
  3331. pick_entry_guards(const or_options_t *options)
  3332. {
  3333. int changed = 0;
  3334. tor_assert(entry_guards);
  3335. while (num_live_entry_guards() < options->NumEntryGuards) {
  3336. if (!add_an_entry_guard(NULL, 0, 0))
  3337. break;
  3338. changed = 1;
  3339. }
  3340. if (changed)
  3341. entry_guards_changed();
  3342. }
  3343. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  3344. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  3345. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  3346. /** Release all storage held by <b>e</b>. */
  3347. static void
  3348. entry_guard_free(entry_guard_t *e)
  3349. {
  3350. if (!e)
  3351. return;
  3352. tor_free(e->chosen_by_version);
  3353. tor_free(e);
  3354. }
  3355. /** Remove any entry guard which was selected by an unknown version of Tor,
  3356. * or which was selected by a version of Tor that's known to select
  3357. * entry guards badly. */
  3358. static int
  3359. remove_obsolete_entry_guards(time_t now)
  3360. {
  3361. int changed = 0, i;
  3362. for (i = 0; i < smartlist_len(entry_guards); ++i) {
  3363. entry_guard_t *entry = smartlist_get(entry_guards, i);
  3364. const char *ver = entry->chosen_by_version;
  3365. const char *msg = NULL;
  3366. tor_version_t v;
  3367. int version_is_bad = 0, date_is_bad = 0;
  3368. if (!ver) {
  3369. msg = "does not say what version of Tor it was selected by";
  3370. version_is_bad = 1;
  3371. } else if (tor_version_parse(ver, &v)) {
  3372. msg = "does not seem to be from any recognized version of Tor";
  3373. version_is_bad = 1;
  3374. } else {
  3375. size_t len = strlen(ver)+5;
  3376. char *tor_ver = tor_malloc(len);
  3377. tor_snprintf(tor_ver, len, "Tor %s", ver);
  3378. if ((tor_version_as_new_as(tor_ver, "0.1.0.10-alpha") &&
  3379. !tor_version_as_new_as(tor_ver, "0.1.2.16-dev")) ||
  3380. (tor_version_as_new_as(tor_ver, "0.2.0.0-alpha") &&
  3381. !tor_version_as_new_as(tor_ver, "0.2.0.6-alpha")) ||
  3382. /* above are bug 440; below are bug 1217 */
  3383. (tor_version_as_new_as(tor_ver, "0.2.1.3-alpha") &&
  3384. !tor_version_as_new_as(tor_ver, "0.2.1.23")) ||
  3385. (tor_version_as_new_as(tor_ver, "0.2.2.0-alpha") &&
  3386. !tor_version_as_new_as(tor_ver, "0.2.2.7-alpha"))) {
  3387. msg = "was selected without regard for guard bandwidth";
  3388. version_is_bad = 1;
  3389. }
  3390. tor_free(tor_ver);
  3391. }
  3392. if (!version_is_bad && entry->chosen_on_date + 3600*24*60 < now) {
  3393. /* It's been 2 months since the date listed in our state file. */
  3394. msg = "was selected several months ago";
  3395. date_is_bad = 1;
  3396. }
  3397. if (version_is_bad || date_is_bad) { /* we need to drop it */
  3398. char dbuf[HEX_DIGEST_LEN+1];
  3399. tor_assert(msg);
  3400. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  3401. log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
  3402. "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
  3403. entry->nickname, dbuf, msg, ver?escaped(ver):"none");
  3404. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  3405. entry_guard_free(entry);
  3406. smartlist_del_keeporder(entry_guards, i--);
  3407. log_entry_guards(LOG_INFO);
  3408. changed = 1;
  3409. }
  3410. }
  3411. return changed ? 1 : 0;
  3412. }
  3413. /** Remove all entry guards that have been down or unlisted for so
  3414. * long that we don't think they'll come up again. Return 1 if we
  3415. * removed any, or 0 if we did nothing. */
  3416. static int
  3417. remove_dead_entry_guards(time_t now)
  3418. {
  3419. char dbuf[HEX_DIGEST_LEN+1];
  3420. char tbuf[ISO_TIME_LEN+1];
  3421. int i;
  3422. int changed = 0;
  3423. for (i = 0; i < smartlist_len(entry_guards); ) {
  3424. entry_guard_t *entry = smartlist_get(entry_guards, i);
  3425. if (entry->bad_since &&
  3426. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  3427. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  3428. format_local_iso_time(tbuf, entry->bad_since);
  3429. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  3430. "since %s local time; removing.",
  3431. entry->nickname, dbuf, tbuf);
  3432. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  3433. entry_guard_free(entry);
  3434. smartlist_del_keeporder(entry_guards, i);
  3435. log_entry_guards(LOG_INFO);
  3436. changed = 1;
  3437. } else
  3438. ++i;
  3439. }
  3440. return changed ? 1 : 0;
  3441. }
  3442. /** A new directory or router-status has arrived; update the down/listed
  3443. * status of the entry guards.
  3444. *
  3445. * An entry is 'down' if the directory lists it as nonrunning.
  3446. * An entry is 'unlisted' if the directory doesn't include it.
  3447. *
  3448. * Don't call this on startup; only on a fresh download. Otherwise we'll
  3449. * think that things are unlisted.
  3450. */
  3451. void
  3452. entry_guards_compute_status(const or_options_t *options, time_t now)
  3453. {
  3454. int changed = 0;
  3455. digestmap_t *reasons;
  3456. if (! entry_guards)
  3457. return;
  3458. if (options->EntryNodes) /* reshuffle the entry guard list if needed */
  3459. entry_nodes_should_be_added();
  3460. reasons = digestmap_new();
  3461. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry)
  3462. {
  3463. const node_t *r = node_get_by_id(entry->identity);
  3464. const char *reason = NULL;
  3465. if (entry_guard_set_status(entry, r, now, options, &reason))
  3466. changed = 1;
  3467. if (entry->bad_since)
  3468. tor_assert(reason);
  3469. if (reason)
  3470. digestmap_set(reasons, entry->identity, (char*)reason);
  3471. }
  3472. SMARTLIST_FOREACH_END(entry);
  3473. if (remove_dead_entry_guards(now))
  3474. changed = 1;
  3475. if (changed) {
  3476. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
  3477. const char *reason = digestmap_get(reasons, entry->identity);
  3478. const char *live_msg = "";
  3479. const node_t *r = entry_is_live(entry, 0, 1, 0, &live_msg);
  3480. log_info(LD_CIRC, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
  3481. entry->nickname,
  3482. hex_str(entry->identity, DIGEST_LEN),
  3483. entry->unreachable_since ? "unreachable" : "reachable",
  3484. entry->bad_since ? "unusable" : "usable",
  3485. reason ? ", ": "",
  3486. reason ? reason : "",
  3487. r ? "live" : "not live / ",
  3488. r ? "" : live_msg);
  3489. } SMARTLIST_FOREACH_END(entry);
  3490. log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
  3491. num_live_entry_guards(), smartlist_len(entry_guards));
  3492. log_entry_guards(LOG_INFO);
  3493. entry_guards_changed();
  3494. }
  3495. digestmap_free(reasons, NULL);
  3496. }
  3497. /** Called when a connection to an OR with the identity digest <b>digest</b>
  3498. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  3499. * If the OR is an entry, change that entry's up/down status.
  3500. * Return 0 normally, or -1 if we want to tear down the new connection.
  3501. *
  3502. * If <b>mark_relay_status</b>, also call router_set_status() on this
  3503. * relay.
  3504. *
  3505. * XXX023 change succeeded and mark_relay_status into 'int flags'.
  3506. */
  3507. int
  3508. entry_guard_register_connect_status(const char *digest, int succeeded,
  3509. int mark_relay_status, time_t now)
  3510. {
  3511. int changed = 0;
  3512. int refuse_conn = 0;
  3513. int first_contact = 0;
  3514. entry_guard_t *entry = NULL;
  3515. int idx = -1;
  3516. char buf[HEX_DIGEST_LEN+1];
  3517. if (! entry_guards)
  3518. return 0;
  3519. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  3520. {
  3521. if (tor_memeq(e->identity, digest, DIGEST_LEN)) {
  3522. entry = e;
  3523. idx = e_sl_idx;
  3524. break;
  3525. }
  3526. });
  3527. if (!entry)
  3528. return 0;
  3529. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  3530. if (succeeded) {
  3531. if (entry->unreachable_since) {
  3532. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  3533. entry->nickname, buf);
  3534. entry->can_retry = 0;
  3535. entry->unreachable_since = 0;
  3536. entry->last_attempted = now;
  3537. control_event_guard(entry->nickname, entry->identity, "UP");
  3538. changed = 1;
  3539. }
  3540. if (!entry->made_contact) {
  3541. entry->made_contact = 1;
  3542. first_contact = changed = 1;
  3543. }
  3544. } else { /* ! succeeded */
  3545. if (!entry->made_contact) {
  3546. /* We've never connected to this one. */
  3547. log_info(LD_CIRC,
  3548. "Connection to never-contacted entry guard '%s' (%s) failed. "
  3549. "Removing from the list. %d/%d entry guards usable/new.",
  3550. entry->nickname, buf,
  3551. num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
  3552. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  3553. entry_guard_free(entry);
  3554. smartlist_del_keeporder(entry_guards, idx);
  3555. log_entry_guards(LOG_INFO);
  3556. changed = 1;
  3557. } else if (!entry->unreachable_since) {
  3558. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  3559. "Marking as unreachable.", entry->nickname, buf);
  3560. entry->unreachable_since = entry->last_attempted = now;
  3561. control_event_guard(entry->nickname, entry->identity, "DOWN");
  3562. changed = 1;
  3563. entry->can_retry = 0; /* We gave it an early chance; no good. */
  3564. } else {
  3565. char tbuf[ISO_TIME_LEN+1];
  3566. format_iso_time(tbuf, entry->unreachable_since);
  3567. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  3568. "'%s' (%s). It has been unreachable since %s.",
  3569. entry->nickname, buf, tbuf);
  3570. entry->last_attempted = now;
  3571. entry->can_retry = 0; /* We gave it an early chance; no good. */
  3572. }
  3573. }
  3574. /* if the caller asked us to, also update the is_running flags for this
  3575. * relay */
  3576. if (mark_relay_status)
  3577. router_set_status(digest, succeeded);
  3578. if (first_contact) {
  3579. /* We've just added a new long-term entry guard. Perhaps the network just
  3580. * came back? We should give our earlier entries another try too,
  3581. * and close this connection so we don't use it before we've given
  3582. * the others a shot. */
  3583. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  3584. if (e == entry)
  3585. break;
  3586. if (e->made_contact) {
  3587. const char *msg;
  3588. const node_t *r = entry_is_live(e, 0, 1, 1, &msg);
  3589. if (r && e->unreachable_since) {
  3590. refuse_conn = 1;
  3591. e->can_retry = 1;
  3592. }
  3593. }
  3594. });
  3595. if (refuse_conn) {
  3596. log_info(LD_CIRC,
  3597. "Connected to new entry guard '%s' (%s). Marking earlier "
  3598. "entry guards up. %d/%d entry guards usable/new.",
  3599. entry->nickname, buf,
  3600. num_live_entry_guards(), smartlist_len(entry_guards));
  3601. log_entry_guards(LOG_INFO);
  3602. changed = 1;
  3603. }
  3604. }
  3605. if (changed)
  3606. entry_guards_changed();
  3607. return refuse_conn ? -1 : 0;
  3608. }
  3609. /** When we try to choose an entry guard, should we parse and add
  3610. * config's EntryNodes first? */
  3611. static int should_add_entry_nodes = 0;
  3612. /** Called when the value of EntryNodes changes in our configuration. */
  3613. void
  3614. entry_nodes_should_be_added(void)
  3615. {
  3616. log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
  3617. "relays at the front of the entry guard list.");
  3618. should_add_entry_nodes = 1;
  3619. }
  3620. /** Adjust the entry guards list so that it only contains entries from
  3621. * EntryNodes, adding new entries from EntryNodes to the list as needed. */
  3622. static void
  3623. entry_guards_set_from_config(const or_options_t *options)
  3624. {
  3625. smartlist_t *entry_nodes, *worse_entry_nodes, *entry_fps;
  3626. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  3627. tor_assert(entry_guards);
  3628. should_add_entry_nodes = 0;
  3629. if (!options->EntryNodes) {
  3630. /* It's possible that a controller set EntryNodes, thus making
  3631. * should_add_entry_nodes set, then cleared it again, all before the
  3632. * call to choose_random_entry() that triggered us. If so, just return.
  3633. */
  3634. return;
  3635. }
  3636. {
  3637. char *string = routerset_to_string(options->EntryNodes);
  3638. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
  3639. tor_free(string);
  3640. }
  3641. entry_nodes = smartlist_create();
  3642. worse_entry_nodes = smartlist_create();
  3643. entry_fps = smartlist_create();
  3644. old_entry_guards_on_list = smartlist_create();
  3645. old_entry_guards_not_on_list = smartlist_create();
  3646. /* Split entry guards into those on the list and those not. */
  3647. routerset_get_all_nodes(entry_nodes, options->EntryNodes,
  3648. options->ExcludeNodes, 0);
  3649. SMARTLIST_FOREACH(entry_nodes, const node_t *,node,
  3650. smartlist_add(entry_fps, (void*)node->identity));
  3651. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  3652. if (smartlist_digest_isin(entry_fps, e->identity))
  3653. smartlist_add(old_entry_guards_on_list, e);
  3654. else
  3655. smartlist_add(old_entry_guards_not_on_list, e);
  3656. });
  3657. /* Remove all currently configured guard nodes, excluded nodes, unreachable
  3658. * nodes, or non-Guard nodes from entry_nodes. */
  3659. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  3660. if (is_an_entry_guard(node->identity)) {
  3661. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3662. continue;
  3663. } else if (routerset_contains_node(options->ExcludeNodes, node)) {
  3664. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3665. continue;
  3666. } else if (!fascist_firewall_allows_node(node)) {
  3667. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3668. continue;
  3669. } else if (! node->is_possible_guard) {
  3670. smartlist_add(worse_entry_nodes, (node_t*)node);
  3671. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3672. }
  3673. } SMARTLIST_FOREACH_END(node);
  3674. /* Now build the new entry_guards list. */
  3675. smartlist_clear(entry_guards);
  3676. /* First, the previously configured guards that are in EntryNodes. */
  3677. smartlist_add_all(entry_guards, old_entry_guards_on_list);
  3678. /* Next, scramble the rest of EntryNodes, putting the guards first. */
  3679. smartlist_shuffle(entry_nodes);
  3680. smartlist_shuffle(worse_entry_nodes);
  3681. smartlist_add_all(entry_nodes, worse_entry_nodes);
  3682. /* Next, the rest of EntryNodes */
  3683. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  3684. add_an_entry_guard(node, 0, 0);
  3685. if (smartlist_len(entry_guards) > options->NumEntryGuards * 10)
  3686. break;
  3687. } SMARTLIST_FOREACH_END(node);
  3688. log_notice(LD_GENERAL, "%d entries in guards", smartlist_len(entry_guards));
  3689. /* Finally, free the remaining previously configured guards that are not in
  3690. * EntryNodes. */
  3691. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  3692. entry_guard_free(e));
  3693. smartlist_free(entry_nodes);
  3694. smartlist_free(worse_entry_nodes);
  3695. smartlist_free(entry_fps);
  3696. smartlist_free(old_entry_guards_on_list);
  3697. smartlist_free(old_entry_guards_not_on_list);
  3698. entry_guards_changed();
  3699. }
  3700. /** Return 0 if we're fine adding arbitrary routers out of the
  3701. * directory to our entry guard list, or return 1 if we have a
  3702. * list already and we must stick to it.
  3703. */
  3704. int
  3705. entry_list_is_constrained(const or_options_t *options)
  3706. {
  3707. if (options->EntryNodes)
  3708. return 1;
  3709. if (options->UseBridges)
  3710. return 1;
  3711. return 0;
  3712. }
  3713. /** Pick a live (up and listed) entry guard from entry_guards. If
  3714. * <b>state</b> is non-NULL, this is for a specific circuit --
  3715. * make sure not to pick this circuit's exit or any node in the
  3716. * exit's family. If <b>state</b> is NULL, we're looking for a random
  3717. * guard (likely a bridge). */
  3718. const node_t *
  3719. choose_random_entry(cpath_build_state_t *state)
  3720. {
  3721. const or_options_t *options = get_options();
  3722. smartlist_t *live_entry_guards = smartlist_create();
  3723. smartlist_t *exit_family = smartlist_create();
  3724. const node_t *chosen_exit =
  3725. state?build_state_get_exit_node(state) : NULL;
  3726. const node_t *node = NULL;
  3727. int need_uptime = state ? state->need_uptime : 0;
  3728. int need_capacity = state ? state->need_capacity : 0;
  3729. int preferred_min, consider_exit_family = 0;
  3730. if (chosen_exit) {
  3731. nodelist_add_node_and_family(exit_family, chosen_exit);
  3732. consider_exit_family = 1;
  3733. }
  3734. if (!entry_guards)
  3735. entry_guards = smartlist_create();
  3736. if (should_add_entry_nodes)
  3737. entry_guards_set_from_config(options);
  3738. if (!entry_list_is_constrained(options) &&
  3739. smartlist_len(entry_guards) < options->NumEntryGuards)
  3740. pick_entry_guards(options);
  3741. retry:
  3742. smartlist_clear(live_entry_guards);
  3743. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
  3744. const char *msg;
  3745. node = entry_is_live(entry, need_uptime, need_capacity, 0, &msg);
  3746. if (!node)
  3747. continue; /* down, no point */
  3748. if (node == chosen_exit)
  3749. continue; /* don't pick the same node for entry and exit */
  3750. if (consider_exit_family && smartlist_isin(exit_family, node))
  3751. continue; /* avoid relays that are family members of our exit */
  3752. #if 0 /* since EntryNodes is always strict now, this clause is moot */
  3753. if (options->EntryNodes &&
  3754. !routerset_contains_node(options->EntryNodes, node)) {
  3755. /* We've come to the end of our preferred entry nodes. */
  3756. if (smartlist_len(live_entry_guards))
  3757. goto choose_and_finish; /* only choose from the ones we like */
  3758. if (options->StrictNodes) {
  3759. /* in theory this case should never happen, since
  3760. * entry_guards_set_from_config() drops unwanted relays */
  3761. tor_fragile_assert();
  3762. } else {
  3763. log_info(LD_CIRC,
  3764. "No relays from EntryNodes available. Using others.");
  3765. }
  3766. }
  3767. #endif
  3768. smartlist_add(live_entry_guards, (void*)node);
  3769. if (!entry->made_contact) {
  3770. /* Always start with the first not-yet-contacted entry
  3771. * guard. Otherwise we might add several new ones, pick
  3772. * the second new one, and now we've expanded our entry
  3773. * guard list without needing to. */
  3774. goto choose_and_finish;
  3775. }
  3776. if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
  3777. break; /* we have enough */
  3778. } SMARTLIST_FOREACH_END(entry);
  3779. if (entry_list_is_constrained(options)) {
  3780. /* If we prefer the entry nodes we've got, and we have at least
  3781. * one choice, that's great. Use it. */
  3782. preferred_min = 1;
  3783. } else {
  3784. /* Try to have at least 2 choices available. This way we don't
  3785. * get stuck with a single live-but-crummy entry and just keep
  3786. * using him.
  3787. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  3788. preferred_min = 2;
  3789. }
  3790. if (smartlist_len(live_entry_guards) < preferred_min) {
  3791. if (!entry_list_is_constrained(options)) {
  3792. /* still no? try adding a new entry then */
  3793. /* XXX if guard doesn't imply fast and stable, then we need
  3794. * to tell add_an_entry_guard below what we want, or it might
  3795. * be a long time til we get it. -RD */
  3796. node = add_an_entry_guard(NULL, 0, 0);
  3797. if (node) {
  3798. entry_guards_changed();
  3799. /* XXX we start over here in case the new node we added shares
  3800. * a family with our exit node. There's a chance that we'll just
  3801. * load up on entry guards here, if the network we're using is
  3802. * one big family. Perhaps we should teach add_an_entry_guard()
  3803. * to understand nodes-to-avoid-if-possible? -RD */
  3804. goto retry;
  3805. }
  3806. }
  3807. if (!node && need_uptime) {
  3808. need_uptime = 0; /* try without that requirement */
  3809. goto retry;
  3810. }
  3811. if (!node && need_capacity) {
  3812. /* still no? last attempt, try without requiring capacity */
  3813. need_capacity = 0;
  3814. goto retry;
  3815. }
  3816. #if 0
  3817. /* Removing this retry logic: if we only allow one exit, and it is in the
  3818. same family as all our entries, then we are just plain not going to win
  3819. here. */
  3820. if (!node && entry_list_is_constrained(options) && consider_exit_family) {
  3821. /* still no? if we're using bridges or have strictentrynodes
  3822. * set, and our chosen exit is in the same family as all our
  3823. * bridges/entry guards, then be flexible about families. */
  3824. consider_exit_family = 0;
  3825. goto retry;
  3826. }
  3827. #endif
  3828. /* live_entry_guards may be empty below. Oh well, we tried. */
  3829. }
  3830. choose_and_finish:
  3831. if (entry_list_is_constrained(options)) {
  3832. /* We need to weight by bandwidth, because our bridges or entryguards
  3833. * were not already selected proportional to their bandwidth. */
  3834. node = node_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
  3835. } else {
  3836. /* We choose uniformly at random here, because choose_good_entry_server()
  3837. * already weights its choices by bandwidth, so we don't want to
  3838. * *double*-weight our guard selection. */
  3839. node = smartlist_choose(live_entry_guards);
  3840. }
  3841. smartlist_free(live_entry_guards);
  3842. smartlist_free(exit_family);
  3843. return node;
  3844. }
  3845. /** Parse <b>state</b> and learn about the entry guards it describes.
  3846. * If <b>set</b> is true, and there are no errors, replace the global
  3847. * entry_list with what we find.
  3848. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  3849. * describing the error, and return -1.
  3850. */
  3851. int
  3852. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  3853. {
  3854. entry_guard_t *node = NULL;
  3855. smartlist_t *new_entry_guards = smartlist_create();
  3856. config_line_t *line;
  3857. time_t now = time(NULL);
  3858. const char *state_version = state->TorVersion;
  3859. digestmap_t *added_by = digestmap_new();
  3860. *msg = NULL;
  3861. for (line = state->EntryGuards; line; line = line->next) {
  3862. if (!strcasecmp(line->key, "EntryGuard")) {
  3863. smartlist_t *args = smartlist_create();
  3864. node = tor_malloc_zero(sizeof(entry_guard_t));
  3865. /* all entry guards on disk have been contacted */
  3866. node->made_contact = 1;
  3867. smartlist_add(new_entry_guards, node);
  3868. smartlist_split_string(args, line->value, " ",
  3869. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3870. if (smartlist_len(args)<2) {
  3871. *msg = tor_strdup("Unable to parse entry nodes: "
  3872. "Too few arguments to EntryGuard");
  3873. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  3874. *msg = tor_strdup("Unable to parse entry nodes: "
  3875. "Bad nickname for EntryGuard");
  3876. } else {
  3877. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  3878. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  3879. strlen(smartlist_get(args,1)))<0) {
  3880. *msg = tor_strdup("Unable to parse entry nodes: "
  3881. "Bad hex digest for EntryGuard");
  3882. }
  3883. }
  3884. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  3885. smartlist_free(args);
  3886. if (*msg)
  3887. break;
  3888. } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
  3889. !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
  3890. time_t when;
  3891. time_t last_try = 0;
  3892. if (!node) {
  3893. *msg = tor_strdup("Unable to parse entry nodes: "
  3894. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  3895. break;
  3896. }
  3897. if (parse_iso_time(line->value, &when)<0) {
  3898. *msg = tor_strdup("Unable to parse entry nodes: "
  3899. "Bad time in EntryGuardDownSince/UnlistedSince");
  3900. break;
  3901. }
  3902. if (when > now) {
  3903. /* It's a bad idea to believe info in the future: you can wind
  3904. * up with timeouts that aren't allowed to happen for years. */
  3905. continue;
  3906. }
  3907. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  3908. /* ignore failure */
  3909. (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  3910. }
  3911. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  3912. node->unreachable_since = when;
  3913. node->last_attempted = last_try;
  3914. } else {
  3915. node->bad_since = when;
  3916. }
  3917. } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
  3918. char d[DIGEST_LEN];
  3919. /* format is digest version date */
  3920. if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
  3921. log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
  3922. continue;
  3923. }
  3924. if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
  3925. line->value[HEX_DIGEST_LEN] != ' ') {
  3926. log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
  3927. "hex digest", escaped(line->value));
  3928. continue;
  3929. }
  3930. digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
  3931. } else {
  3932. log_warn(LD_BUG, "Unexpected key %s", line->key);
  3933. }
  3934. }
  3935. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  3936. {
  3937. char *sp;
  3938. char *val = digestmap_get(added_by, e->identity);
  3939. if (val && (sp = strchr(val, ' '))) {
  3940. time_t when;
  3941. *sp++ = '\0';
  3942. if (parse_iso_time(sp, &when)<0) {
  3943. log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
  3944. } else {
  3945. e->chosen_by_version = tor_strdup(val);
  3946. e->chosen_on_date = when;
  3947. }
  3948. } else {
  3949. if (state_version) {
  3950. e->chosen_by_version = tor_strdup(state_version);
  3951. e->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
  3952. }
  3953. }
  3954. });
  3955. if (*msg || !set) {
  3956. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  3957. entry_guard_free(e));
  3958. smartlist_free(new_entry_guards);
  3959. } else { /* !err && set */
  3960. if (entry_guards) {
  3961. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  3962. entry_guard_free(e));
  3963. smartlist_free(entry_guards);
  3964. }
  3965. entry_guards = new_entry_guards;
  3966. entry_guards_dirty = 0;
  3967. /* XXX023 hand new_entry_guards to this func, and move it up a
  3968. * few lines, so we don't have to re-dirty it */
  3969. if (remove_obsolete_entry_guards(now))
  3970. entry_guards_dirty = 1;
  3971. }
  3972. digestmap_free(added_by, _tor_free);
  3973. return *msg ? -1 : 0;
  3974. }
  3975. /** Our list of entry guards has changed, or some element of one
  3976. * of our entry guards has changed. Write the changes to disk within
  3977. * the next few minutes.
  3978. */
  3979. static void
  3980. entry_guards_changed(void)
  3981. {
  3982. time_t when;
  3983. entry_guards_dirty = 1;
  3984. /* or_state_save() will call entry_guards_update_state(). */
  3985. when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
  3986. or_state_mark_dirty(get_or_state(), when);
  3987. }
  3988. /** If the entry guard info has not changed, do nothing and return.
  3989. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  3990. * a new one out of the global entry_guards list, and then mark
  3991. * <b>state</b> dirty so it will get saved to disk.
  3992. */
  3993. void
  3994. entry_guards_update_state(or_state_t *state)
  3995. {
  3996. config_line_t **next, *line;
  3997. if (! entry_guards_dirty)
  3998. return;
  3999. config_free_lines(state->EntryGuards);
  4000. next = &state->EntryGuards;
  4001. *next = NULL;
  4002. if (!entry_guards)
  4003. entry_guards = smartlist_create();
  4004. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  4005. {
  4006. char dbuf[HEX_DIGEST_LEN+1];
  4007. if (!e->made_contact)
  4008. continue; /* don't write this one to disk */
  4009. *next = line = tor_malloc_zero(sizeof(config_line_t));
  4010. line->key = tor_strdup("EntryGuard");
  4011. line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
  4012. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  4013. tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
  4014. "%s %s", e->nickname, dbuf);
  4015. next = &(line->next);
  4016. if (e->unreachable_since) {
  4017. *next = line = tor_malloc_zero(sizeof(config_line_t));
  4018. line->key = tor_strdup("EntryGuardDownSince");
  4019. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  4020. format_iso_time(line->value, e->unreachable_since);
  4021. if (e->last_attempted) {
  4022. line->value[ISO_TIME_LEN] = ' ';
  4023. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  4024. }
  4025. next = &(line->next);
  4026. }
  4027. if (e->bad_since) {
  4028. *next = line = tor_malloc_zero(sizeof(config_line_t));
  4029. line->key = tor_strdup("EntryGuardUnlistedSince");
  4030. line->value = tor_malloc(ISO_TIME_LEN+1);
  4031. format_iso_time(line->value, e->bad_since);
  4032. next = &(line->next);
  4033. }
  4034. if (e->chosen_on_date && e->chosen_by_version &&
  4035. !strchr(e->chosen_by_version, ' ')) {
  4036. char d[HEX_DIGEST_LEN+1];
  4037. char t[ISO_TIME_LEN+1];
  4038. size_t val_len;
  4039. *next = line = tor_malloc_zero(sizeof(config_line_t));
  4040. line->key = tor_strdup("EntryGuardAddedBy");
  4041. val_len = (HEX_DIGEST_LEN+1+strlen(e->chosen_by_version)
  4042. +1+ISO_TIME_LEN+1);
  4043. line->value = tor_malloc(val_len);
  4044. base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
  4045. format_iso_time(t, e->chosen_on_date);
  4046. tor_snprintf(line->value, val_len, "%s %s %s",
  4047. d, e->chosen_by_version, t);
  4048. next = &(line->next);
  4049. }
  4050. });
  4051. if (!get_options()->AvoidDiskWrites)
  4052. or_state_mark_dirty(get_or_state(), 0);
  4053. entry_guards_dirty = 0;
  4054. }
  4055. /** If <b>question</b> is the string "entry-guards", then dump
  4056. * to *<b>answer</b> a newly allocated string describing all of
  4057. * the nodes in the global entry_guards list. See control-spec.txt
  4058. * for details.
  4059. * For backward compatibility, we also handle the string "helper-nodes".
  4060. * */
  4061. int
  4062. getinfo_helper_entry_guards(control_connection_t *conn,
  4063. const char *question, char **answer,
  4064. const char **errmsg)
  4065. {
  4066. (void) conn;
  4067. (void) errmsg;
  4068. if (!strcmp(question,"entry-guards") ||
  4069. !strcmp(question,"helper-nodes")) {
  4070. smartlist_t *sl = smartlist_create();
  4071. char tbuf[ISO_TIME_LEN+1];
  4072. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  4073. if (!entry_guards)
  4074. entry_guards = smartlist_create();
  4075. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
  4076. size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
  4077. char *c = tor_malloc(len);
  4078. const char *status = NULL;
  4079. time_t when = 0;
  4080. const node_t *node;
  4081. if (!e->made_contact) {
  4082. status = "never-connected";
  4083. } else if (e->bad_since) {
  4084. when = e->bad_since;
  4085. status = "unusable";
  4086. } else {
  4087. status = "up";
  4088. }
  4089. node = node_get_by_id(e->identity);
  4090. if (node) {
  4091. node_get_verbose_nickname(node, nbuf);
  4092. } else {
  4093. nbuf[0] = '$';
  4094. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  4095. /* e->nickname field is not very reliable if we don't know about
  4096. * this router any longer; don't include it. */
  4097. }
  4098. if (when) {
  4099. format_iso_time(tbuf, when);
  4100. tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
  4101. } else {
  4102. tor_snprintf(c, len, "%s %s\n", nbuf, status);
  4103. }
  4104. smartlist_add(sl, c);
  4105. } SMARTLIST_FOREACH_END(e);
  4106. *answer = smartlist_join_strings(sl, "", 0, NULL);
  4107. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  4108. smartlist_free(sl);
  4109. }
  4110. return 0;
  4111. }
  4112. /** A list of configured bridges. Whenever we actually get a descriptor
  4113. * for one, we add it as an entry guard. Note that the order of bridges
  4114. * in this list does not necessarily correspond to the order of bridges
  4115. * in the torrc. */
  4116. static smartlist_t *bridge_list = NULL;
  4117. /** Mark every entry of the bridge list to be removed on our next call to
  4118. * sweep_bridge_list unless it has first been un-marked. */
  4119. void
  4120. mark_bridge_list(void)
  4121. {
  4122. if (!bridge_list)
  4123. bridge_list = smartlist_create();
  4124. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b,
  4125. b->marked_for_removal = 1);
  4126. }
  4127. /** Remove every entry of the bridge list that was marked with
  4128. * mark_bridge_list if it has not subsequently been un-marked. */
  4129. void
  4130. sweep_bridge_list(void)
  4131. {
  4132. if (!bridge_list)
  4133. bridge_list = smartlist_create();
  4134. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
  4135. if (b->marked_for_removal) {
  4136. SMARTLIST_DEL_CURRENT(bridge_list, b);
  4137. bridge_free(b);
  4138. }
  4139. } SMARTLIST_FOREACH_END(b);
  4140. }
  4141. /** Initialize the bridge list to empty, creating it if needed. */
  4142. static void
  4143. clear_bridge_list(void)
  4144. {
  4145. if (!bridge_list)
  4146. bridge_list = smartlist_create();
  4147. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, bridge_free(b));
  4148. smartlist_clear(bridge_list);
  4149. }
  4150. /** Free the bridge <b>bridge</b>. */
  4151. static void
  4152. bridge_free(bridge_info_t *bridge)
  4153. {
  4154. if (!bridge)
  4155. return;
  4156. tor_free(bridge->transport_name);
  4157. tor_free(bridge);
  4158. }
  4159. /** A list of pluggable transports found in torrc. */
  4160. static smartlist_t *transport_list = NULL;
  4161. /** Initialize the pluggable transports list to empty, creating it if
  4162. * needed. */
  4163. void
  4164. clear_transport_list(void)
  4165. {
  4166. if (!transport_list)
  4167. transport_list = smartlist_create();
  4168. SMARTLIST_FOREACH(transport_list, transport_t *, t, transport_free(t));
  4169. smartlist_clear(transport_list);
  4170. }
  4171. /** Free the pluggable transport struct <b>transport</b>. */
  4172. static void
  4173. transport_free(transport_t *transport)
  4174. {
  4175. if (!transport)
  4176. return;
  4177. tor_free(transport->name);
  4178. tor_free(transport);
  4179. }
  4180. /** Returns the transport in our transport list that has the name <b>name</b>.
  4181. * Else returns NULL. */
  4182. static const transport_t *
  4183. transport_get_by_name(const char *name)
  4184. {
  4185. tor_assert(name);
  4186. if (!transport_list)
  4187. return NULL;
  4188. SMARTLIST_FOREACH_BEGIN(transport_list, const transport_t *, transport) {
  4189. if (!strcmp(transport->name, name))
  4190. return transport;
  4191. } SMARTLIST_FOREACH_END(transport);
  4192. return NULL;
  4193. }
  4194. /** Remember a new pluggable transport proxy at <b>addr</b>:<b>port</b>.
  4195. * <b>name</b> is set to the name of the protocol this proxy uses.
  4196. * <b>socks_ver</b> is set to the SOCKS version of the proxy.
  4197. *
  4198. * Returns 0 on success, -1 on fail. */
  4199. int
  4200. transport_add_from_config(const tor_addr_t *addr, uint16_t port,
  4201. const char *name, int socks_ver)
  4202. {
  4203. transport_t *t;
  4204. if (transport_get_by_name(name)) { /* check for duplicate names */
  4205. log_warn(LD_CONFIG, "More than one transport has '%s' as "
  4206. "its name.", name);
  4207. return -1;
  4208. }
  4209. t = tor_malloc_zero(sizeof(transport_t));
  4210. tor_addr_copy(&t->addr, addr);
  4211. t->port = port;
  4212. t->name = tor_strdup(name);
  4213. t->socks_version = socks_ver;
  4214. if (!transport_list)
  4215. transport_list = smartlist_create();
  4216. smartlist_add(transport_list, t);
  4217. return 0;
  4218. }
  4219. /** Warns the user of possible pluggable transport misconfiguration. */
  4220. void
  4221. validate_pluggable_transports_config(void)
  4222. {
  4223. if (bridge_list) {
  4224. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
  4225. /* Skip bridges without transports. */
  4226. if (!b->transport_name)
  4227. continue;
  4228. /* See if the user has Bridges that specify nonexistent
  4229. pluggable transports. We should warn the user in such case,
  4230. since it's probably misconfiguration. */
  4231. if (!transport_get_by_name(b->transport_name))
  4232. log_warn(LD_CONFIG, "You have a Bridge line using the %s "
  4233. "pluggable transport, but there doesn't seem to be a "
  4234. "corresponding ClientTransportPlugin line.",
  4235. b->transport_name);
  4236. } SMARTLIST_FOREACH_END(b);
  4237. }
  4238. }
  4239. /** Return a bridge pointer if <b>ri</b> is one of our known bridges
  4240. * (either by comparing keys if possible, else by comparing addr/port).
  4241. * Else return NULL. */
  4242. static bridge_info_t *
  4243. get_configured_bridge_by_addr_port_digest(const tor_addr_t *addr,
  4244. uint16_t port,
  4245. const char *digest)
  4246. {
  4247. if (!bridge_list)
  4248. return NULL;
  4249. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  4250. {
  4251. if (tor_digest_is_zero(bridge->identity) &&
  4252. !tor_addr_compare(&bridge->addr, addr, CMP_EXACT) &&
  4253. bridge->port == port)
  4254. return bridge;
  4255. if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
  4256. return bridge;
  4257. }
  4258. SMARTLIST_FOREACH_END(bridge);
  4259. return NULL;
  4260. }
  4261. /** Wrapper around get_configured_bridge_by_addr_port_digest() to look
  4262. * it up via router descriptor <b>ri</b>. */
  4263. static bridge_info_t *
  4264. get_configured_bridge_by_routerinfo(const routerinfo_t *ri)
  4265. {
  4266. tor_addr_t addr;
  4267. tor_addr_from_ipv4h(&addr, ri->addr);
  4268. return get_configured_bridge_by_addr_port_digest(&addr,
  4269. ri->or_port, ri->cache_info.identity_digest);
  4270. }
  4271. /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
  4272. int
  4273. routerinfo_is_a_configured_bridge(const routerinfo_t *ri)
  4274. {
  4275. return get_configured_bridge_by_routerinfo(ri) ? 1 : 0;
  4276. }
  4277. /** Return 1 if <b>node</b> is one of our configured bridges, else 0. */
  4278. int
  4279. node_is_a_configured_bridge(const node_t *node)
  4280. {
  4281. tor_addr_t addr;
  4282. uint16_t orport;
  4283. if (!node)
  4284. return 0;
  4285. if (node_get_addr(node, &addr) < 0)
  4286. return 0;
  4287. orport = node_get_orport(node);
  4288. if (orport == 0)
  4289. return 0;
  4290. return get_configured_bridge_by_addr_port_digest(
  4291. &addr, orport, node->identity) != NULL;
  4292. }
  4293. /** We made a connection to a router at <b>addr</b>:<b>port</b>
  4294. * without knowing its digest. Its digest turned out to be <b>digest</b>.
  4295. * If it was a bridge, and we still don't know its digest, record it.
  4296. */
  4297. void
  4298. learned_router_identity(const tor_addr_t *addr, uint16_t port,
  4299. const char *digest)
  4300. {
  4301. bridge_info_t *bridge =
  4302. get_configured_bridge_by_addr_port_digest(addr, port, digest);
  4303. if (bridge && tor_digest_is_zero(bridge->identity)) {
  4304. memcpy(bridge->identity, digest, DIGEST_LEN);
  4305. log_notice(LD_DIR, "Learned fingerprint %s for bridge %s:%d",
  4306. hex_str(digest, DIGEST_LEN), fmt_addr(addr), port);
  4307. }
  4308. }
  4309. /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
  4310. * is set, it tells us the identity key too. If we already had the
  4311. * bridge in our list, unmark it, and don't actually add anything new.
  4312. * If <b>transport_name</b> is non-NULL - the bridge is associated with a
  4313. * pluggable transport - we assign the transport to the bridge. */
  4314. void
  4315. bridge_add_from_config(const tor_addr_t *addr, uint16_t port,
  4316. const char *digest, const char *transport_name)
  4317. {
  4318. bridge_info_t *b;
  4319. if ((b = get_configured_bridge_by_addr_port_digest(addr, port, digest))) {
  4320. b->marked_for_removal = 0;
  4321. return;
  4322. }
  4323. b = tor_malloc_zero(sizeof(bridge_info_t));
  4324. tor_addr_copy(&b->addr, addr);
  4325. b->port = port;
  4326. if (digest)
  4327. memcpy(b->identity, digest, DIGEST_LEN);
  4328. if (transport_name)
  4329. b->transport_name = tor_strdup(transport_name);
  4330. b->fetch_status.schedule = DL_SCHED_BRIDGE;
  4331. if (!bridge_list)
  4332. bridge_list = smartlist_create();
  4333. smartlist_add(bridge_list, b);
  4334. }
  4335. /** Return true iff <b>routerset</b> contains the bridge <b>bridge</b>. */
  4336. static int
  4337. routerset_contains_bridge(const routerset_t *routerset,
  4338. const bridge_info_t *bridge)
  4339. {
  4340. int result;
  4341. extend_info_t *extinfo;
  4342. tor_assert(bridge);
  4343. if (!routerset)
  4344. return 0;
  4345. extinfo = extend_info_alloc(
  4346. NULL, bridge->identity, NULL, &bridge->addr, bridge->port);
  4347. result = routerset_contains_extendinfo(routerset, extinfo);
  4348. extend_info_free(extinfo);
  4349. return result;
  4350. }
  4351. /** If <b>digest</b> is one of our known bridges, return it. */
  4352. static bridge_info_t *
  4353. find_bridge_by_digest(const char *digest)
  4354. {
  4355. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  4356. {
  4357. if (tor_memeq(bridge->identity, digest, DIGEST_LEN))
  4358. return bridge;
  4359. });
  4360. return NULL;
  4361. }
  4362. /** If <b>addr</b> and <b>port</b> match the address and port of a
  4363. * bridge of ours that uses pluggable transports, place its transport
  4364. * in <b>transport</b>.
  4365. *
  4366. * Return 0 on success (found a transport, or found a bridge with no
  4367. * transport, or found no bridge); return -1 if we should be using a
  4368. * transport, but the transport could not be found.
  4369. */
  4370. int
  4371. find_transport_by_bridge_addrport(const tor_addr_t *addr, uint16_t port,
  4372. const transport_t **transport)
  4373. {
  4374. *transport = NULL;
  4375. if (!bridge_list)
  4376. return 0;
  4377. SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
  4378. if (tor_addr_eq(&bridge->addr, addr) &&
  4379. (bridge->port == port)) { /* bridge matched */
  4380. if (bridge->transport_name) { /* it also uses pluggable transports */
  4381. *transport = transport_get_by_name(bridge->transport_name);
  4382. if (*transport == NULL) { /* it uses pluggable transports, but
  4383. the transport could not be found! */
  4384. return -1;
  4385. }
  4386. return 0;
  4387. } else { /* bridge matched, but it doesn't use transports. */
  4388. break;
  4389. }
  4390. }
  4391. } SMARTLIST_FOREACH_END(bridge);
  4392. *transport = NULL;
  4393. return 0;
  4394. }
  4395. /** We need to ask <b>bridge</b> for its server descriptor. */
  4396. static void
  4397. launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
  4398. {
  4399. char *address;
  4400. const or_options_t *options = get_options();
  4401. if (connection_get_by_type_addr_port_purpose(
  4402. CONN_TYPE_DIR, &bridge->addr, bridge->port,
  4403. DIR_PURPOSE_FETCH_SERVERDESC))
  4404. return; /* it's already on the way */
  4405. address = tor_dup_addr(&bridge->addr);
  4406. if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
  4407. download_status_mark_impossible(&bridge->fetch_status);
  4408. log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
  4409. safe_str_client(fmt_addr(&bridge->addr)));
  4410. return;
  4411. }
  4412. directory_initiate_command(address, &bridge->addr,
  4413. bridge->port, 0,
  4414. 0, /* does not matter */
  4415. 1, bridge->identity,
  4416. DIR_PURPOSE_FETCH_SERVERDESC,
  4417. ROUTER_PURPOSE_BRIDGE,
  4418. 0, "authority.z", NULL, 0, 0);
  4419. tor_free(address);
  4420. }
  4421. /** Fetching the bridge descriptor from the bridge authority returned a
  4422. * "not found". Fall back to trying a direct fetch. */
  4423. void
  4424. retry_bridge_descriptor_fetch_directly(const char *digest)
  4425. {
  4426. bridge_info_t *bridge = find_bridge_by_digest(digest);
  4427. if (!bridge)
  4428. return; /* not found? oh well. */
  4429. launch_direct_bridge_descriptor_fetch(bridge);
  4430. }
  4431. /** For each bridge in our list for which we don't currently have a
  4432. * descriptor, fetch a new copy of its descriptor -- either directly
  4433. * from the bridge or via a bridge authority. */
  4434. void
  4435. fetch_bridge_descriptors(const or_options_t *options, time_t now)
  4436. {
  4437. int num_bridge_auths = get_n_authorities(BRIDGE_DIRINFO);
  4438. int ask_bridge_directly;
  4439. int can_use_bridge_authority;
  4440. if (!bridge_list)
  4441. return;
  4442. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  4443. {
  4444. if (!download_status_is_ready(&bridge->fetch_status, now,
  4445. IMPOSSIBLE_TO_DOWNLOAD))
  4446. continue; /* don't bother, no need to retry yet */
  4447. if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
  4448. download_status_mark_impossible(&bridge->fetch_status);
  4449. log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
  4450. safe_str_client(fmt_addr(&bridge->addr)));
  4451. continue;
  4452. }
  4453. /* schedule another fetch as if this one will fail, in case it does */
  4454. download_status_failed(&bridge->fetch_status, 0);
  4455. can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
  4456. num_bridge_auths;
  4457. ask_bridge_directly = !can_use_bridge_authority ||
  4458. !options->UpdateBridgesFromAuthority;
  4459. log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
  4460. ask_bridge_directly, tor_digest_is_zero(bridge->identity),
  4461. !options->UpdateBridgesFromAuthority, !num_bridge_auths);
  4462. if (ask_bridge_directly &&
  4463. !fascist_firewall_allows_address_or(&bridge->addr, bridge->port)) {
  4464. log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
  4465. "firewall policy. %s.", fmt_addr(&bridge->addr),
  4466. bridge->port,
  4467. can_use_bridge_authority ?
  4468. "Asking bridge authority instead" : "Skipping");
  4469. if (can_use_bridge_authority)
  4470. ask_bridge_directly = 0;
  4471. else
  4472. continue;
  4473. }
  4474. if (ask_bridge_directly) {
  4475. /* we need to ask the bridge itself for its descriptor. */
  4476. launch_direct_bridge_descriptor_fetch(bridge);
  4477. } else {
  4478. /* We have a digest and we want to ask an authority. We could
  4479. * combine all the requests into one, but that may give more
  4480. * hints to the bridge authority than we want to give. */
  4481. char resource[10 + HEX_DIGEST_LEN];
  4482. memcpy(resource, "fp/", 3);
  4483. base16_encode(resource+3, HEX_DIGEST_LEN+1,
  4484. bridge->identity, DIGEST_LEN);
  4485. memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
  4486. log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
  4487. resource);
  4488. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  4489. ROUTER_PURPOSE_BRIDGE, resource, 0);
  4490. }
  4491. }
  4492. SMARTLIST_FOREACH_END(bridge);
  4493. }
  4494. /** If our <b>bridge</b> is configured to be a different address than
  4495. * the bridge gives in <b>node</b>, rewrite the routerinfo
  4496. * we received to use the address we meant to use. Now we handle
  4497. * multihomed bridges better.
  4498. */
  4499. static void
  4500. rewrite_node_address_for_bridge(const bridge_info_t *bridge, node_t *node)
  4501. {
  4502. /* XXXX move this function. */
  4503. /* XXXX overridden addresses should really live in the node_t, so that the
  4504. * routerinfo_t and the microdesc_t can be immutable. But we can only
  4505. * do that safely if we know that no function that connects to an OR
  4506. * does so through an address from any source other than node_get_addr().
  4507. */
  4508. tor_addr_t addr;
  4509. if (node->ri) {
  4510. routerinfo_t *ri = node->ri;
  4511. tor_addr_from_ipv4h(&addr, ri->addr);
  4512. if (!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
  4513. bridge->port == ri->or_port) {
  4514. /* they match, so no need to do anything */
  4515. } else {
  4516. ri->addr = tor_addr_to_ipv4h(&bridge->addr);
  4517. tor_free(ri->address);
  4518. ri->address = tor_dup_ip(ri->addr);
  4519. ri->or_port = bridge->port;
  4520. log_info(LD_DIR,
  4521. "Adjusted bridge routerinfo for '%s' to match configured "
  4522. "address %s:%d.",
  4523. ri->nickname, ri->address, ri->or_port);
  4524. }
  4525. }
  4526. if (node->rs) {
  4527. routerstatus_t *rs = node->rs;
  4528. tor_addr_from_ipv4h(&addr, rs->addr);
  4529. if (!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
  4530. bridge->port == rs->or_port) {
  4531. /* they match, so no need to do anything */
  4532. } else {
  4533. rs->addr = tor_addr_to_ipv4h(&bridge->addr);
  4534. rs->or_port = bridge->port;
  4535. log_info(LD_DIR,
  4536. "Adjusted bridge routerstatus for '%s' to match "
  4537. "configured address %s:%d.",
  4538. rs->nickname, fmt_addr(&bridge->addr), rs->or_port);
  4539. }
  4540. }
  4541. }
  4542. /** We just learned a descriptor for a bridge. See if that
  4543. * digest is in our entry guard list, and add it if not. */
  4544. void
  4545. learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
  4546. {
  4547. tor_assert(ri);
  4548. tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
  4549. if (get_options()->UseBridges) {
  4550. int first = !any_bridge_descriptors_known();
  4551. bridge_info_t *bridge = get_configured_bridge_by_routerinfo(ri);
  4552. time_t now = time(NULL);
  4553. router_set_status(ri->cache_info.identity_digest, 1);
  4554. if (bridge) { /* if we actually want to use this one */
  4555. node_t *node;
  4556. /* it's here; schedule its re-fetch for a long time from now. */
  4557. if (!from_cache)
  4558. download_status_reset(&bridge->fetch_status);
  4559. node = node_get_mutable_by_id(ri->cache_info.identity_digest);
  4560. tor_assert(node);
  4561. rewrite_node_address_for_bridge(bridge, node);
  4562. add_an_entry_guard(node, 1, 1);
  4563. log_notice(LD_DIR, "new bridge descriptor '%s' (%s)", ri->nickname,
  4564. from_cache ? "cached" : "fresh");
  4565. /* set entry->made_contact so if it goes down we don't drop it from
  4566. * our entry node list */
  4567. entry_guard_register_connect_status(ri->cache_info.identity_digest,
  4568. 1, 0, now);
  4569. if (first)
  4570. routerlist_retry_directory_downloads(now);
  4571. }
  4572. }
  4573. }
  4574. /** Return 1 if any of our entry guards have descriptors that
  4575. * are marked with purpose 'bridge' and are running. Else return 0.
  4576. *
  4577. * We use this function to decide if we're ready to start building
  4578. * circuits through our bridges, or if we need to wait until the
  4579. * directory "server/authority" requests finish. */
  4580. int
  4581. any_bridge_descriptors_known(void)
  4582. {
  4583. tor_assert(get_options()->UseBridges);
  4584. return choose_random_entry(NULL)!=NULL ? 1 : 0;
  4585. }
  4586. /** Return 1 if there are any directory conns fetching bridge descriptors
  4587. * that aren't marked for close. We use this to guess if we should tell
  4588. * the controller that we have a problem. */
  4589. int
  4590. any_pending_bridge_descriptor_fetches(void)
  4591. {
  4592. smartlist_t *conns = get_connection_array();
  4593. SMARTLIST_FOREACH(conns, connection_t *, conn,
  4594. {
  4595. if (conn->type == CONN_TYPE_DIR &&
  4596. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  4597. TO_DIR_CONN(conn)->router_purpose == ROUTER_PURPOSE_BRIDGE &&
  4598. !conn->marked_for_close &&
  4599. conn->linked &&
  4600. conn->linked_conn && !conn->linked_conn->marked_for_close) {
  4601. log_debug(LD_DIR, "found one: %s", conn->address);
  4602. return 1;
  4603. }
  4604. });
  4605. return 0;
  4606. }
  4607. /** Return 1 if we have at least one descriptor for an entry guard
  4608. * (bridge or member of EntryNodes) and all descriptors we know are
  4609. * down. Else return 0. If <b>act</b> is 1, then mark the down guards
  4610. * up; else just observe and report. */
  4611. static int
  4612. entries_retry_helper(const or_options_t *options, int act)
  4613. {
  4614. const node_t *node;
  4615. int any_known = 0;
  4616. int any_running = 0;
  4617. int need_bridges = options->UseBridges != 0;
  4618. if (!entry_guards)
  4619. entry_guards = smartlist_create();
  4620. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
  4621. node = node_get_by_id(e->identity);
  4622. if (node && node_has_descriptor(node) &&
  4623. node_is_bridge(node) == need_bridges) {
  4624. any_known = 1;
  4625. if (node->is_running)
  4626. any_running = 1; /* some entry is both known and running */
  4627. else if (act) {
  4628. /* Mark all current connections to this OR as unhealthy, since
  4629. * otherwise there could be one that started 30 seconds
  4630. * ago, and in 30 seconds it will time out, causing us to mark
  4631. * the node down and undermine the retry attempt. We mark even
  4632. * the established conns, since if the network just came back
  4633. * we'll want to attach circuits to fresh conns. */
  4634. connection_or_set_bad_connections(node->identity, 1);
  4635. /* mark this entry node for retry */
  4636. router_set_status(node->identity, 1);
  4637. e->can_retry = 1;
  4638. e->bad_since = 0;
  4639. }
  4640. }
  4641. } SMARTLIST_FOREACH_END(e);
  4642. log_debug(LD_DIR, "%d: any_known %d, any_running %d",
  4643. act, any_known, any_running);
  4644. return any_known && !any_running;
  4645. }
  4646. /** Do we know any descriptors for our bridges / entrynodes, and are
  4647. * all the ones we have descriptors for down? */
  4648. int
  4649. entries_known_but_down(const or_options_t *options)
  4650. {
  4651. tor_assert(entry_list_is_constrained(options));
  4652. return entries_retry_helper(options, 0);
  4653. }
  4654. /** Mark all down known bridges / entrynodes up. */
  4655. void
  4656. entries_retry_all(const or_options_t *options)
  4657. {
  4658. tor_assert(entry_list_is_constrained(options));
  4659. entries_retry_helper(options, 1);
  4660. }
  4661. /** Release all storage held by the list of entry guards and related
  4662. * memory structs. */
  4663. void
  4664. entry_guards_free_all(void)
  4665. {
  4666. if (entry_guards) {
  4667. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  4668. entry_guard_free(e));
  4669. smartlist_free(entry_guards);
  4670. entry_guards = NULL;
  4671. }
  4672. clear_bridge_list();
  4673. clear_transport_list();
  4674. smartlist_free(bridge_list);
  4675. smartlist_free(transport_list);
  4676. bridge_list = NULL;
  4677. transport_list = NULL;
  4678. }