directory.c 212 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2017, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #define DIRECTORY_PRIVATE
  6. #include "or.h"
  7. #include "backtrace.h"
  8. #include "bridges.h"
  9. #include "buffers.h"
  10. #include "circuitbuild.h"
  11. #include "config.h"
  12. #include "connection.h"
  13. #include "connection_edge.h"
  14. #include "conscache.h"
  15. #include "consdiff.h"
  16. #include "consdiffmgr.h"
  17. #include "control.h"
  18. #include "compat.h"
  19. #include "directory.h"
  20. #include "dirserv.h"
  21. #include "dirvote.h"
  22. #include "entrynodes.h"
  23. #include "geoip.h"
  24. #include "hs_cache.h"
  25. #include "hs_common.h"
  26. #include "hs_client.h"
  27. #include "main.h"
  28. #include "microdesc.h"
  29. #include "networkstatus.h"
  30. #include "nodelist.h"
  31. #include "policies.h"
  32. #include "relay.h"
  33. #include "rendclient.h"
  34. #include "rendcommon.h"
  35. #include "rendservice.h"
  36. #include "rephist.h"
  37. #include "router.h"
  38. #include "routerlist.h"
  39. #include "routerparse.h"
  40. #include "routerset.h"
  41. #include "shared_random.h"
  42. #if defined(EXPORTMALLINFO) && defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
  43. #if !defined(OpenBSD)
  44. #include <malloc.h>
  45. #endif
  46. #endif
  47. /**
  48. * \file directory.c
  49. * \brief Code to send and fetch information from directory authorities and
  50. * caches via HTTP.
  51. *
  52. * Directory caches and authorities use dirserv.c to generate the results of a
  53. * query and stream them to the connection; clients use routerparse.c to parse
  54. * them.
  55. *
  56. * Every directory request has a dir_connection_t on the client side and on
  57. * the server side. In most cases, the dir_connection_t object is a linked
  58. * connection, tunneled through an edge_connection_t so that it can be a
  59. * stream on the Tor network. The only non-tunneled connections are those
  60. * that are used to upload material (descriptors and votes) to authorities.
  61. * Among tunneled connections, some use one-hop circuits, and others use
  62. * multi-hop circuits for anonymity.
  63. *
  64. * Directory requests are launched by calling
  65. * directory_initiate_request(). This
  66. * launch the connection, will construct an HTTP request with
  67. * directory_send_command(), send the and wait for a response. The client
  68. * later handles the response with connection_dir_client_reached_eof(),
  69. * which passes the information received to another part of Tor.
  70. *
  71. * On the server side, requests are read in directory_handle_command(),
  72. * which dispatches first on the request type (GET or POST), and then on
  73. * the URL requested. GET requests are processed with a table-based
  74. * dispatcher in url_table[]. The process of handling larger GET requests
  75. * is complicated because we need to avoid allocating a copy of all the
  76. * data to be sent to the client in one huge buffer. Instead, we spool the
  77. * data into the buffer using logic in connection_dirserv_flushed_some() in
  78. * dirserv.c. (TODO: If we extended buf.c to have a zero-copy
  79. * reference-based buffer type, we could remove most of that code, at the
  80. * cost of a bit more reference counting.)
  81. **/
  82. /* In-points to directory.c:
  83. *
  84. * - directory_post_to_dirservers(), called from
  85. * router_upload_dir_desc_to_dirservers() in router.c
  86. * upload_service_descriptor() in rendservice.c
  87. * - directory_get_from_dirserver(), called from
  88. * rend_client_refetch_renddesc() in rendclient.c
  89. * run_scheduled_events() in main.c
  90. * do_hup() in main.c
  91. * - connection_dir_process_inbuf(), called from
  92. * connection_process_inbuf() in connection.c
  93. * - connection_dir_finished_flushing(), called from
  94. * connection_finished_flushing() in connection.c
  95. * - connection_dir_finished_connecting(), called from
  96. * connection_finished_connecting() in connection.c
  97. */
  98. static void directory_send_command(dir_connection_t *conn,
  99. int direct,
  100. const directory_request_t *request);
  101. static int body_is_plausible(const char *body, size_t body_len, int purpose);
  102. static void http_set_address_origin(const char *headers, connection_t *conn);
  103. static void connection_dir_download_routerdesc_failed(dir_connection_t *conn);
  104. static void connection_dir_bridge_routerdesc_failed(dir_connection_t *conn);
  105. static void connection_dir_download_cert_failed(
  106. dir_connection_t *conn, int status_code);
  107. static void connection_dir_retry_bridges(smartlist_t *descs);
  108. static void dir_routerdesc_download_failed(smartlist_t *failed,
  109. int status_code,
  110. int router_purpose,
  111. int was_extrainfo,
  112. int was_descriptor_digests);
  113. static void dir_microdesc_download_failed(smartlist_t *failed,
  114. int status_code);
  115. static int client_likes_consensus(const struct consensus_cache_entry_t *ent,
  116. const char *want_url);
  117. static void connection_dir_close_consensus_fetches(
  118. dir_connection_t *except_this_one, const char *resource);
  119. /********* START VARIABLES **********/
  120. /** How far in the future do we allow a directory server to tell us it is
  121. * before deciding that one of us has the wrong time? */
  122. #define ALLOW_DIRECTORY_TIME_SKEW (30*60)
  123. #define X_ADDRESS_HEADER "X-Your-Address-Is: "
  124. #define X_OR_DIFF_FROM_CONSENSUS_HEADER "X-Or-Diff-From-Consensus: "
  125. /** HTTP cache control: how long do we tell proxies they can cache each
  126. * kind of document we serve? */
  127. #define FULL_DIR_CACHE_LIFETIME (60*60)
  128. #define RUNNINGROUTERS_CACHE_LIFETIME (20*60)
  129. #define DIRPORTFRONTPAGE_CACHE_LIFETIME (20*60)
  130. #define NETWORKSTATUS_CACHE_LIFETIME (5*60)
  131. #define ROUTERDESC_CACHE_LIFETIME (30*60)
  132. #define ROUTERDESC_BY_DIGEST_CACHE_LIFETIME (48*60*60)
  133. #define ROBOTS_CACHE_LIFETIME (24*60*60)
  134. #define MICRODESC_CACHE_LIFETIME (48*60*60)
  135. /********* END VARIABLES ************/
  136. /** Return false if the directory purpose <b>dir_purpose</b>
  137. * does not require an anonymous (three-hop) connection.
  138. *
  139. * Return true 1) by default, 2) if all directory actions have
  140. * specifically been configured to be over an anonymous connection,
  141. * or 3) if the router is a bridge */
  142. int
  143. purpose_needs_anonymity(uint8_t dir_purpose, uint8_t router_purpose,
  144. const char *resource)
  145. {
  146. if (get_options()->AllDirActionsPrivate)
  147. return 1;
  148. if (router_purpose == ROUTER_PURPOSE_BRIDGE) {
  149. if (dir_purpose == DIR_PURPOSE_FETCH_SERVERDESC
  150. && resource && !strcmp(resource, "authority.z")) {
  151. /* We are asking a bridge for its own descriptor. That doesn't need
  152. anonymity. */
  153. return 0;
  154. }
  155. /* Assume all other bridge stuff needs anonymity. */
  156. return 1; /* if no circuits yet, this might break bootstrapping, but it's
  157. * needed to be safe. */
  158. }
  159. switch (dir_purpose)
  160. {
  161. case DIR_PURPOSE_UPLOAD_DIR:
  162. case DIR_PURPOSE_UPLOAD_VOTE:
  163. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  164. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  165. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  166. case DIR_PURPOSE_FETCH_CONSENSUS:
  167. case DIR_PURPOSE_FETCH_CERTIFICATE:
  168. case DIR_PURPOSE_FETCH_SERVERDESC:
  169. case DIR_PURPOSE_FETCH_EXTRAINFO:
  170. case DIR_PURPOSE_FETCH_MICRODESC:
  171. return 0;
  172. case DIR_PURPOSE_HAS_FETCHED_HSDESC:
  173. case DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2:
  174. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  175. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  176. case DIR_PURPOSE_FETCH_HSDESC:
  177. case DIR_PURPOSE_UPLOAD_HSDESC:
  178. return 1;
  179. case DIR_PURPOSE_SERVER:
  180. default:
  181. log_warn(LD_BUG, "Called with dir_purpose=%d, router_purpose=%d",
  182. dir_purpose, router_purpose);
  183. tor_assert_nonfatal_unreached();
  184. return 1; /* Assume it needs anonymity; better safe than sorry. */
  185. }
  186. }
  187. /** Return a newly allocated string describing <b>auth</b>. Only describes
  188. * authority features. */
  189. STATIC char *
  190. authdir_type_to_string(dirinfo_type_t auth)
  191. {
  192. char *result;
  193. smartlist_t *lst = smartlist_new();
  194. if (auth & V3_DIRINFO)
  195. smartlist_add(lst, (void*)"V3");
  196. if (auth & BRIDGE_DIRINFO)
  197. smartlist_add(lst, (void*)"Bridge");
  198. if (smartlist_len(lst)) {
  199. result = smartlist_join_strings(lst, ", ", 0, NULL);
  200. } else {
  201. result = tor_strdup("[Not an authority]");
  202. }
  203. smartlist_free(lst);
  204. return result;
  205. }
  206. /** Return a string describing a given directory connection purpose. */
  207. STATIC const char *
  208. dir_conn_purpose_to_string(int purpose)
  209. {
  210. switch (purpose)
  211. {
  212. case DIR_PURPOSE_UPLOAD_DIR:
  213. return "server descriptor upload";
  214. case DIR_PURPOSE_UPLOAD_VOTE:
  215. return "server vote upload";
  216. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  217. return "consensus signature upload";
  218. case DIR_PURPOSE_FETCH_SERVERDESC:
  219. return "server descriptor fetch";
  220. case DIR_PURPOSE_FETCH_EXTRAINFO:
  221. return "extra-info fetch";
  222. case DIR_PURPOSE_FETCH_CONSENSUS:
  223. return "consensus network-status fetch";
  224. case DIR_PURPOSE_FETCH_CERTIFICATE:
  225. return "authority cert fetch";
  226. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  227. return "status vote fetch";
  228. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  229. return "consensus signature fetch";
  230. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  231. return "hidden-service v2 descriptor fetch";
  232. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  233. return "hidden-service v2 descriptor upload";
  234. case DIR_PURPOSE_FETCH_HSDESC:
  235. return "hidden-service descriptor fetch";
  236. case DIR_PURPOSE_UPLOAD_HSDESC:
  237. return "hidden-service descriptor upload";
  238. case DIR_PURPOSE_FETCH_MICRODESC:
  239. return "microdescriptor fetch";
  240. }
  241. log_warn(LD_BUG, "Called with unknown purpose %d", purpose);
  242. return "(unknown)";
  243. }
  244. /** Return the requisite directory information types. */
  245. STATIC dirinfo_type_t
  246. dir_fetch_type(int dir_purpose, int router_purpose, const char *resource)
  247. {
  248. dirinfo_type_t type;
  249. switch (dir_purpose) {
  250. case DIR_PURPOSE_FETCH_EXTRAINFO:
  251. type = EXTRAINFO_DIRINFO;
  252. if (router_purpose == ROUTER_PURPOSE_BRIDGE)
  253. type |= BRIDGE_DIRINFO;
  254. else
  255. type |= V3_DIRINFO;
  256. break;
  257. case DIR_PURPOSE_FETCH_SERVERDESC:
  258. if (router_purpose == ROUTER_PURPOSE_BRIDGE)
  259. type = BRIDGE_DIRINFO;
  260. else
  261. type = V3_DIRINFO;
  262. break;
  263. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  264. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  265. case DIR_PURPOSE_FETCH_CERTIFICATE:
  266. type = V3_DIRINFO;
  267. break;
  268. case DIR_PURPOSE_FETCH_CONSENSUS:
  269. type = V3_DIRINFO;
  270. if (resource && !strcmp(resource, "microdesc"))
  271. type |= MICRODESC_DIRINFO;
  272. break;
  273. case DIR_PURPOSE_FETCH_MICRODESC:
  274. type = MICRODESC_DIRINFO;
  275. break;
  276. default:
  277. log_warn(LD_BUG, "Unexpected purpose %d", (int)dir_purpose);
  278. type = NO_DIRINFO;
  279. break;
  280. }
  281. return type;
  282. }
  283. /** Return true iff <b>identity_digest</b> is the digest of a router which
  284. * says that it caches extrainfos. (If <b>is_authority</b> we always
  285. * believe that to be true.) */
  286. int
  287. router_supports_extrainfo(const char *identity_digest, int is_authority)
  288. {
  289. const node_t *node = node_get_by_id(identity_digest);
  290. if (node && node->ri) {
  291. if (node->ri->caches_extra_info)
  292. return 1;
  293. }
  294. if (is_authority) {
  295. return 1;
  296. }
  297. return 0;
  298. }
  299. /** Return true iff any trusted directory authority has accepted our
  300. * server descriptor.
  301. *
  302. * We consider any authority sufficient because waiting for all of
  303. * them means it never happens while any authority is down; we don't
  304. * go for something more complex in the middle (like \>1/3 or \>1/2 or
  305. * \>=1/2) because that doesn't seem necessary yet.
  306. */
  307. int
  308. directories_have_accepted_server_descriptor(void)
  309. {
  310. const smartlist_t *servers = router_get_trusted_dir_servers();
  311. const or_options_t *options = get_options();
  312. SMARTLIST_FOREACH(servers, dir_server_t *, d, {
  313. if ((d->type & options->PublishServerDescriptor_) &&
  314. d->has_accepted_serverdesc) {
  315. return 1;
  316. }
  317. });
  318. return 0;
  319. }
  320. /** Start a connection to every suitable directory authority, using
  321. * connection purpose <b>dir_purpose</b> and uploading <b>payload</b>
  322. * (of length <b>payload_len</b>). The dir_purpose should be one of
  323. * 'DIR_PURPOSE_UPLOAD_{DIR|VOTE|SIGNATURES}'.
  324. *
  325. * <b>router_purpose</b> describes the type of descriptor we're
  326. * publishing, if we're publishing a descriptor -- e.g. general or bridge.
  327. *
  328. * <b>type</b> specifies what sort of dir authorities (V3,
  329. * BRIDGE, etc) we should upload to.
  330. *
  331. * If <b>extrainfo_len</b> is nonzero, the first <b>payload_len</b> bytes of
  332. * <b>payload</b> hold a router descriptor, and the next <b>extrainfo_len</b>
  333. * bytes of <b>payload</b> hold an extra-info document. Upload the descriptor
  334. * to all authorities, and the extra-info document to all authorities that
  335. * support it.
  336. */
  337. void
  338. directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose,
  339. dirinfo_type_t type,
  340. const char *payload,
  341. size_t payload_len, size_t extrainfo_len)
  342. {
  343. const or_options_t *options = get_options();
  344. dir_indirection_t indirection;
  345. const smartlist_t *dirservers = router_get_trusted_dir_servers();
  346. int found = 0;
  347. const int exclude_self = (dir_purpose == DIR_PURPOSE_UPLOAD_VOTE ||
  348. dir_purpose == DIR_PURPOSE_UPLOAD_SIGNATURES);
  349. tor_assert(dirservers);
  350. /* This tries dirservers which we believe to be down, but ultimately, that's
  351. * harmless, and we may as well err on the side of getting things uploaded.
  352. */
  353. SMARTLIST_FOREACH_BEGIN(dirservers, dir_server_t *, ds) {
  354. routerstatus_t *rs = &(ds->fake_status);
  355. size_t upload_len = payload_len;
  356. if ((type & ds->type) == 0)
  357. continue;
  358. if (exclude_self && router_digest_is_me(ds->digest)) {
  359. /* we don't upload to ourselves, but at least there's now at least
  360. * one authority of this type that has what we wanted to upload. */
  361. found = 1;
  362. continue;
  363. }
  364. if (options->StrictNodes &&
  365. routerset_contains_routerstatus(options->ExcludeNodes, rs, -1)) {
  366. log_warn(LD_DIR, "Wanted to contact authority '%s' for %s, but "
  367. "it's in our ExcludedNodes list and StrictNodes is set. "
  368. "Skipping.",
  369. ds->nickname,
  370. dir_conn_purpose_to_string(dir_purpose));
  371. continue;
  372. }
  373. found = 1; /* at least one authority of this type was listed */
  374. if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR)
  375. ds->has_accepted_serverdesc = 0;
  376. if (extrainfo_len && router_supports_extrainfo(ds->digest, 1)) {
  377. upload_len += extrainfo_len;
  378. log_info(LD_DIR, "Uploading an extrainfo too (length %d)",
  379. (int) extrainfo_len);
  380. }
  381. if (purpose_needs_anonymity(dir_purpose, router_purpose, NULL)) {
  382. indirection = DIRIND_ANONYMOUS;
  383. } else if (!fascist_firewall_allows_dir_server(ds,
  384. FIREWALL_DIR_CONNECTION,
  385. 0)) {
  386. if (fascist_firewall_allows_dir_server(ds, FIREWALL_OR_CONNECTION, 0))
  387. indirection = DIRIND_ONEHOP;
  388. else
  389. indirection = DIRIND_ANONYMOUS;
  390. } else {
  391. indirection = DIRIND_DIRECT_CONN;
  392. }
  393. directory_request_t *req = directory_request_new(dir_purpose);
  394. directory_request_set_routerstatus(req, rs);
  395. directory_request_set_router_purpose(req, router_purpose);
  396. directory_request_set_indirection(req, indirection);
  397. directory_request_set_payload(req, payload, upload_len);
  398. directory_initiate_request(req);
  399. directory_request_free(req);
  400. } SMARTLIST_FOREACH_END(ds);
  401. if (!found) {
  402. char *s = authdir_type_to_string(type);
  403. log_warn(LD_DIR, "Publishing server descriptor to directory authorities "
  404. "of type '%s', but no authorities of that type listed!", s);
  405. tor_free(s);
  406. }
  407. }
  408. /** Return true iff, according to the values in <b>options</b>, we should be
  409. * using directory guards for direct downloads of directory information. */
  410. STATIC int
  411. should_use_directory_guards(const or_options_t *options)
  412. {
  413. /* Public (non-bridge) servers never use directory guards. */
  414. if (public_server_mode(options))
  415. return 0;
  416. /* If guards are disabled, we can't use directory guards.
  417. */
  418. if (!options->UseEntryGuards)
  419. return 0;
  420. /* If we're configured to fetch directory info aggressively or of a
  421. * nonstandard type, don't use directory guards. */
  422. if (options->DownloadExtraInfo || options->FetchDirInfoEarly ||
  423. options->FetchDirInfoExtraEarly || options->FetchUselessDescriptors)
  424. return 0;
  425. return 1;
  426. }
  427. /** Pick an unconstrained directory server from among our guards, the latest
  428. * networkstatus, or the fallback dirservers, for use in downloading
  429. * information of type <b>type</b>, and return its routerstatus. */
  430. static const routerstatus_t *
  431. directory_pick_generic_dirserver(dirinfo_type_t type, int pds_flags,
  432. uint8_t dir_purpose,
  433. circuit_guard_state_t **guard_state_out)
  434. {
  435. const routerstatus_t *rs = NULL;
  436. const or_options_t *options = get_options();
  437. if (options->UseBridges)
  438. log_warn(LD_BUG, "Called when we have UseBridges set.");
  439. if (should_use_directory_guards(options)) {
  440. const node_t *node = guards_choose_dirguard(guard_state_out);
  441. if (node)
  442. rs = node->rs;
  443. } else {
  444. /* anybody with a non-zero dirport will do */
  445. rs = router_pick_directory_server(type, pds_flags);
  446. }
  447. if (!rs) {
  448. log_info(LD_DIR, "No router found for %s; falling back to "
  449. "dirserver list.", dir_conn_purpose_to_string(dir_purpose));
  450. rs = router_pick_fallback_dirserver(type, pds_flags);
  451. }
  452. return rs;
  453. }
  454. /**
  455. * Set the extra fields in <b>req</b> that are used when requesting a
  456. * consensus of type <b>resource</b>.
  457. *
  458. * Right now, these fields are if-modified-since and x-or-diff-from-consensus.
  459. */
  460. static void
  461. dir_consensus_request_set_additional_headers(directory_request_t *req,
  462. const char *resource)
  463. {
  464. time_t if_modified_since = 0;
  465. uint8_t or_diff_from[DIGEST256_LEN];
  466. int or_diff_from_is_set = 0;
  467. /* DEFAULT_IF_MODIFIED_SINCE_DELAY is 1/20 of the default consensus
  468. * period of 1 hour.
  469. */
  470. const int DEFAULT_IF_MODIFIED_SINCE_DELAY = 180;
  471. const int32_t DEFAULT_TRY_DIFF_FOR_CONSENSUS_NEWER = 72;
  472. const int32_t MIN_TRY_DIFF_FOR_CONSENSUS_NEWER = 0;
  473. const int32_t MAX_TRY_DIFF_FOR_CONSENSUS_NEWER = 8192;
  474. const char TRY_DIFF_FOR_CONSENSUS_NEWER_NAME[] =
  475. "try-diff-for-consensus-newer-than";
  476. int flav = FLAV_NS;
  477. if (resource)
  478. flav = networkstatus_parse_flavor_name(resource);
  479. int32_t max_age_for_diff = 3600 *
  480. networkstatus_get_param(NULL,
  481. TRY_DIFF_FOR_CONSENSUS_NEWER_NAME,
  482. DEFAULT_TRY_DIFF_FOR_CONSENSUS_NEWER,
  483. MIN_TRY_DIFF_FOR_CONSENSUS_NEWER,
  484. MAX_TRY_DIFF_FOR_CONSENSUS_NEWER);
  485. if (flav != -1) {
  486. /* IF we have a parsed consensus of this type, we can do an
  487. * if-modified-time based on it. */
  488. networkstatus_t *v;
  489. v = networkstatus_get_latest_consensus_by_flavor(flav);
  490. if (v) {
  491. /* In networks with particularly short V3AuthVotingIntervals,
  492. * ask for the consensus if it's been modified since half the
  493. * V3AuthVotingInterval of the most recent consensus. */
  494. time_t ims_delay = DEFAULT_IF_MODIFIED_SINCE_DELAY;
  495. if (v->fresh_until > v->valid_after
  496. && ims_delay > (v->fresh_until - v->valid_after)/2) {
  497. ims_delay = (v->fresh_until - v->valid_after)/2;
  498. }
  499. if_modified_since = v->valid_after + ims_delay;
  500. if (v->valid_after >= approx_time() - max_age_for_diff) {
  501. memcpy(or_diff_from, v->digest_sha3_as_signed, DIGEST256_LEN);
  502. or_diff_from_is_set = 1;
  503. }
  504. }
  505. } else {
  506. /* Otherwise it might be a consensus we don't parse, but which we
  507. * do cache. Look at the cached copy, perhaps. */
  508. cached_dir_t *cd = dirserv_get_consensus(resource);
  509. /* We have no method of determining the voting interval from an
  510. * unparsed consensus, so we use the default. */
  511. if (cd) {
  512. if_modified_since = cd->published + DEFAULT_IF_MODIFIED_SINCE_DELAY;
  513. if (cd->published >= approx_time() - max_age_for_diff) {
  514. memcpy(or_diff_from, cd->digest_sha3_as_signed, DIGEST256_LEN);
  515. or_diff_from_is_set = 1;
  516. }
  517. }
  518. }
  519. if (if_modified_since > 0)
  520. directory_request_set_if_modified_since(req, if_modified_since);
  521. if (or_diff_from_is_set) {
  522. char hex[HEX_DIGEST256_LEN + 1];
  523. base16_encode(hex, sizeof(hex),
  524. (const char*)or_diff_from, sizeof(or_diff_from));
  525. directory_request_add_header(req, X_OR_DIFF_FROM_CONSENSUS_HEADER, hex);
  526. }
  527. }
  528. /** Start a connection to a random running directory server, using
  529. * connection purpose <b>dir_purpose</b>, intending to fetch descriptors
  530. * of purpose <b>router_purpose</b>, and requesting <b>resource</b>.
  531. * Use <b>pds_flags</b> as arguments to router_pick_directory_server()
  532. * or router_pick_trusteddirserver().
  533. */
  534. MOCK_IMPL(void,
  535. directory_get_from_dirserver,(
  536. uint8_t dir_purpose,
  537. uint8_t router_purpose,
  538. const char *resource,
  539. int pds_flags,
  540. download_want_authority_t want_authority))
  541. {
  542. const routerstatus_t *rs = NULL;
  543. const or_options_t *options = get_options();
  544. int prefer_authority = (directory_fetches_from_authorities(options)
  545. || want_authority == DL_WANT_AUTHORITY);
  546. int require_authority = 0;
  547. int get_via_tor = purpose_needs_anonymity(dir_purpose, router_purpose,
  548. resource);
  549. dirinfo_type_t type = dir_fetch_type(dir_purpose, router_purpose, resource);
  550. if (type == NO_DIRINFO)
  551. return;
  552. if (!options->FetchServerDescriptors)
  553. return;
  554. circuit_guard_state_t *guard_state = NULL;
  555. if (!get_via_tor) {
  556. if (options->UseBridges && !(type & BRIDGE_DIRINFO)) {
  557. /* We want to ask a running bridge for which we have a descriptor.
  558. *
  559. * When we ask choose_random_entry() for a bridge, we specify what
  560. * sort of dir fetch we'll be doing, so it won't return a bridge
  561. * that can't answer our question.
  562. */
  563. const node_t *node = guards_choose_dirguard(&guard_state);
  564. if (node && node->ri) {
  565. /* every bridge has a routerinfo. */
  566. routerinfo_t *ri = node->ri;
  567. /* clients always make OR connections to bridges */
  568. tor_addr_port_t or_ap;
  569. directory_request_t *req = directory_request_new(dir_purpose);
  570. /* we are willing to use a non-preferred address if we need to */
  571. fascist_firewall_choose_address_node(node, FIREWALL_OR_CONNECTION, 0,
  572. &or_ap);
  573. directory_request_set_or_addr_port(req, &or_ap);
  574. directory_request_set_directory_id_digest(req,
  575. ri->cache_info.identity_digest);
  576. directory_request_set_router_purpose(req, router_purpose);
  577. directory_request_set_resource(req, resource);
  578. if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS)
  579. dir_consensus_request_set_additional_headers(req, resource);
  580. directory_request_set_guard_state(req, guard_state);
  581. directory_initiate_request(req);
  582. directory_request_free(req);
  583. } else {
  584. if (guard_state) {
  585. entry_guard_cancel(&guard_state);
  586. }
  587. log_notice(LD_DIR, "Ignoring directory request, since no bridge "
  588. "nodes are available yet.");
  589. }
  590. return;
  591. } else {
  592. if (prefer_authority || (type & BRIDGE_DIRINFO)) {
  593. /* only ask authdirservers, and don't ask myself */
  594. rs = router_pick_trusteddirserver(type, pds_flags);
  595. if (rs == NULL && (pds_flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  596. PDS_NO_EXISTING_MICRODESC_FETCH))) {
  597. /* We don't want to fetch from any authorities that we're currently
  598. * fetching server descriptors from, and we got no match. Did we
  599. * get no match because all the authorities have connections
  600. * fetching server descriptors (in which case we should just
  601. * return,) or because all the authorities are down or on fire or
  602. * unreachable or something (in which case we should go on with
  603. * our fallback code)? */
  604. pds_flags &= ~(PDS_NO_EXISTING_SERVERDESC_FETCH|
  605. PDS_NO_EXISTING_MICRODESC_FETCH);
  606. rs = router_pick_trusteddirserver(type, pds_flags);
  607. if (rs) {
  608. log_debug(LD_DIR, "Deferring serverdesc fetch: all authorities "
  609. "are in use.");
  610. return;
  611. }
  612. }
  613. if (rs == NULL && require_authority) {
  614. log_info(LD_DIR, "No authorities were available for %s: will try "
  615. "later.", dir_conn_purpose_to_string(dir_purpose));
  616. return;
  617. }
  618. }
  619. if (!rs && !(type & BRIDGE_DIRINFO)) {
  620. rs = directory_pick_generic_dirserver(type, pds_flags,
  621. dir_purpose,
  622. &guard_state);
  623. if (!rs)
  624. get_via_tor = 1; /* last resort: try routing it via Tor */
  625. }
  626. }
  627. }
  628. if (get_via_tor) {
  629. /* Never use fascistfirewall; we're going via Tor. */
  630. pds_flags |= PDS_IGNORE_FASCISTFIREWALL;
  631. rs = router_pick_directory_server(type, pds_flags);
  632. }
  633. /* If we have any hope of building an indirect conn, we know some router
  634. * descriptors. If (rs==NULL), we can't build circuits anyway, so
  635. * there's no point in falling back to the authorities in this case. */
  636. if (rs) {
  637. const dir_indirection_t indirection =
  638. get_via_tor ? DIRIND_ANONYMOUS : DIRIND_ONEHOP;
  639. directory_request_t *req = directory_request_new(dir_purpose);
  640. directory_request_set_routerstatus(req, rs);
  641. directory_request_set_router_purpose(req, router_purpose);
  642. directory_request_set_indirection(req, indirection);
  643. directory_request_set_resource(req, resource);
  644. if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS)
  645. dir_consensus_request_set_additional_headers(req, resource);
  646. if (guard_state)
  647. directory_request_set_guard_state(req, guard_state);
  648. directory_initiate_request(req);
  649. directory_request_free(req);
  650. } else {
  651. log_notice(LD_DIR,
  652. "While fetching directory info, "
  653. "no running dirservers known. Will try again later. "
  654. "(purpose %d)", dir_purpose);
  655. if (!purpose_needs_anonymity(dir_purpose, router_purpose, resource)) {
  656. /* remember we tried them all and failed. */
  657. directory_all_unreachable(time(NULL));
  658. }
  659. }
  660. }
  661. /** As directory_get_from_dirserver, but initiates a request to <i>every</i>
  662. * directory authority other than ourself. Only for use by authorities when
  663. * searching for missing information while voting. */
  664. void
  665. directory_get_from_all_authorities(uint8_t dir_purpose,
  666. uint8_t router_purpose,
  667. const char *resource)
  668. {
  669. tor_assert(dir_purpose == DIR_PURPOSE_FETCH_STATUS_VOTE ||
  670. dir_purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES);
  671. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  672. dir_server_t *, ds) {
  673. if (router_digest_is_me(ds->digest))
  674. continue;
  675. if (!(ds->type & V3_DIRINFO))
  676. continue;
  677. const routerstatus_t *rs = &ds->fake_status;
  678. directory_request_t *req = directory_request_new(dir_purpose);
  679. directory_request_set_routerstatus(req, rs);
  680. directory_request_set_router_purpose(req, router_purpose);
  681. directory_request_set_resource(req, resource);
  682. directory_initiate_request(req);
  683. directory_request_free(req);
  684. } SMARTLIST_FOREACH_END(ds);
  685. }
  686. /** Return true iff <b>ind</b> requires a multihop circuit. */
  687. static int
  688. dirind_is_anon(dir_indirection_t ind)
  689. {
  690. return ind == DIRIND_ANON_DIRPORT || ind == DIRIND_ANONYMOUS;
  691. }
  692. /* Choose reachable OR and Dir addresses and ports from status, copying them
  693. * into use_or_ap and use_dir_ap. If indirection is anonymous, then we're
  694. * connecting via another relay, so choose the primary IPv4 address and ports.
  695. *
  696. * status should have at least one reachable address, if we can't choose a
  697. * reachable address, warn and return -1. Otherwise, return 0.
  698. */
  699. static int
  700. directory_choose_address_routerstatus(const routerstatus_t *status,
  701. dir_indirection_t indirection,
  702. tor_addr_port_t *use_or_ap,
  703. tor_addr_port_t *use_dir_ap)
  704. {
  705. tor_assert(status != NULL);
  706. tor_assert(use_or_ap != NULL);
  707. tor_assert(use_dir_ap != NULL);
  708. const or_options_t *options = get_options();
  709. int have_or = 0, have_dir = 0;
  710. /* We expect status to have at least one reachable address if we're
  711. * connecting to it directly.
  712. *
  713. * Therefore, we can simply use the other address if the one we want isn't
  714. * allowed by the firewall.
  715. *
  716. * (When Tor uploads and downloads a hidden service descriptor, it uses
  717. * DIRIND_ANONYMOUS, except for Tor2Web, which uses DIRIND_ONEHOP.
  718. * So this code will only modify the address for Tor2Web's HS descriptor
  719. * fetches. Even Single Onion Servers (NYI) use DIRIND_ANONYMOUS, to avoid
  720. * HSDirs denying service by rejecting descriptors.)
  721. */
  722. /* Initialise the OR / Dir addresses */
  723. tor_addr_make_null(&use_or_ap->addr, AF_UNSPEC);
  724. use_or_ap->port = 0;
  725. tor_addr_make_null(&use_dir_ap->addr, AF_UNSPEC);
  726. use_dir_ap->port = 0;
  727. /* ORPort connections */
  728. if (indirection == DIRIND_ANONYMOUS) {
  729. if (status->addr) {
  730. /* Since we're going to build a 3-hop circuit and ask the 2nd relay
  731. * to extend to this address, always use the primary (IPv4) OR address */
  732. tor_addr_from_ipv4h(&use_or_ap->addr, status->addr);
  733. use_or_ap->port = status->or_port;
  734. have_or = 1;
  735. }
  736. } else if (indirection == DIRIND_ONEHOP) {
  737. /* We use an IPv6 address if we have one and we prefer it.
  738. * Use the preferred address and port if they are reachable, otherwise,
  739. * use the alternate address and port (if any).
  740. */
  741. have_or = fascist_firewall_choose_address_rs(status,
  742. FIREWALL_OR_CONNECTION, 0,
  743. use_or_ap);
  744. }
  745. /* DirPort connections
  746. * DIRIND_ONEHOP uses ORPort, but may fall back to the DirPort on relays */
  747. if (indirection == DIRIND_DIRECT_CONN ||
  748. indirection == DIRIND_ANON_DIRPORT ||
  749. (indirection == DIRIND_ONEHOP
  750. && !directory_must_use_begindir(options))) {
  751. have_dir = fascist_firewall_choose_address_rs(status,
  752. FIREWALL_DIR_CONNECTION, 0,
  753. use_dir_ap);
  754. }
  755. /* We rejected all addresses in the relay's status. This means we can't
  756. * connect to it. */
  757. if (!have_or && !have_dir) {
  758. static int logged_backtrace = 0;
  759. log_info(LD_BUG, "Rejected all OR and Dir addresses from %s when "
  760. "launching an outgoing directory connection to: IPv4 %s OR %d "
  761. "Dir %d IPv6 %s OR %d Dir %d", routerstatus_describe(status),
  762. fmt_addr32(status->addr), status->or_port,
  763. status->dir_port, fmt_addr(&status->ipv6_addr),
  764. status->ipv6_orport, status->dir_port);
  765. if (!logged_backtrace) {
  766. log_backtrace(LOG_INFO, LD_BUG, "Addresses came from");
  767. logged_backtrace = 1;
  768. }
  769. return -1;
  770. }
  771. return 0;
  772. }
  773. /** Return true iff <b>conn</b> is the client side of a directory connection
  774. * we launched to ourself in order to determine the reachability of our
  775. * dir_port. */
  776. static int
  777. directory_conn_is_self_reachability_test(dir_connection_t *conn)
  778. {
  779. if (conn->requested_resource &&
  780. !strcmpstart(conn->requested_resource,"authority")) {
  781. const routerinfo_t *me = router_get_my_routerinfo();
  782. if (me &&
  783. router_digest_is_me(conn->identity_digest) &&
  784. tor_addr_eq_ipv4h(&conn->base_.addr, me->addr) && /*XXXX prop 118*/
  785. me->dir_port == conn->base_.port)
  786. return 1;
  787. }
  788. return 0;
  789. }
  790. /** Called when we are unable to complete the client's request to a directory
  791. * server due to a network error: Mark the router as down and try again if
  792. * possible.
  793. */
  794. static void
  795. connection_dir_request_failed(dir_connection_t *conn)
  796. {
  797. if (conn->guard_state) {
  798. /* We haven't seen a success on this guard state, so consider it to have
  799. * failed. */
  800. entry_guard_failed(&conn->guard_state);
  801. }
  802. if (directory_conn_is_self_reachability_test(conn)) {
  803. return; /* this was a test fetch. don't retry. */
  804. }
  805. if (!entry_list_is_constrained(get_options()))
  806. router_set_status(conn->identity_digest, 0); /* don't try this one again */
  807. if (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  808. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
  809. log_info(LD_DIR, "Giving up on serverdesc/extrainfo fetch from "
  810. "directory server at '%s'; retrying",
  811. conn->base_.address);
  812. if (conn->router_purpose == ROUTER_PURPOSE_BRIDGE)
  813. connection_dir_bridge_routerdesc_failed(conn);
  814. connection_dir_download_routerdesc_failed(conn);
  815. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  816. if (conn->requested_resource)
  817. networkstatus_consensus_download_failed(0, conn->requested_resource);
  818. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
  819. log_info(LD_DIR, "Giving up on certificate fetch from directory server "
  820. "at '%s'; retrying",
  821. conn->base_.address);
  822. connection_dir_download_cert_failed(conn, 0);
  823. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
  824. log_info(LD_DIR, "Giving up downloading detached signatures from '%s'",
  825. conn->base_.address);
  826. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
  827. log_info(LD_DIR, "Giving up downloading votes from '%s'",
  828. conn->base_.address);
  829. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  830. log_info(LD_DIR, "Giving up on downloading microdescriptors from "
  831. "directory server at '%s'; will retry", conn->base_.address);
  832. connection_dir_download_routerdesc_failed(conn);
  833. }
  834. }
  835. /** Helper: Attempt to fetch directly the descriptors of each bridge
  836. * listed in <b>failed</b>.
  837. */
  838. static void
  839. connection_dir_retry_bridges(smartlist_t *descs)
  840. {
  841. char digest[DIGEST_LEN];
  842. SMARTLIST_FOREACH(descs, const char *, cp,
  843. {
  844. if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) != DIGEST_LEN) {
  845. log_warn(LD_BUG, "Malformed fingerprint in list: %s",
  846. escaped(cp));
  847. continue;
  848. }
  849. retry_bridge_descriptor_fetch_directly(digest);
  850. });
  851. }
  852. /** Called when an attempt to download one or more router descriptors
  853. * or extra-info documents on connection <b>conn</b> failed.
  854. */
  855. static void
  856. connection_dir_download_routerdesc_failed(dir_connection_t *conn)
  857. {
  858. /* No need to increment the failure count for routerdescs, since
  859. * it's not their fault. */
  860. /* No need to relaunch descriptor downloads here: we already do it
  861. * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  862. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  863. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  864. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  865. (void) conn;
  866. }
  867. /** Called when an attempt to download a bridge's routerdesc from
  868. * one of the authorities failed due to a network error. If
  869. * possible attempt to download descriptors from the bridge directly.
  870. */
  871. static void
  872. connection_dir_bridge_routerdesc_failed(dir_connection_t *conn)
  873. {
  874. smartlist_t *which = NULL;
  875. /* Requests for bridge descriptors are in the form 'fp/', so ignore
  876. anything else. */
  877. if (!conn->requested_resource || strcmpstart(conn->requested_resource,"fp/"))
  878. return;
  879. which = smartlist_new();
  880. dir_split_resource_into_fingerprints(conn->requested_resource
  881. + strlen("fp/"),
  882. which, NULL, 0);
  883. tor_assert(conn->base_.purpose != DIR_PURPOSE_FETCH_EXTRAINFO);
  884. if (smartlist_len(which)) {
  885. connection_dir_retry_bridges(which);
  886. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  887. }
  888. smartlist_free(which);
  889. }
  890. /** Called when an attempt to fetch a certificate fails. */
  891. static void
  892. connection_dir_download_cert_failed(dir_connection_t *conn, int status)
  893. {
  894. const char *fp_pfx = "fp/";
  895. const char *fpsk_pfx = "fp-sk/";
  896. smartlist_t *failed;
  897. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE);
  898. if (!conn->requested_resource)
  899. return;
  900. failed = smartlist_new();
  901. /*
  902. * We have two cases download by fingerprint (resource starts
  903. * with "fp/") or download by fingerprint/signing key pair
  904. * (resource starts with "fp-sk/").
  905. */
  906. if (!strcmpstart(conn->requested_resource, fp_pfx)) {
  907. /* Download by fingerprint case */
  908. dir_split_resource_into_fingerprints(conn->requested_resource +
  909. strlen(fp_pfx),
  910. failed, NULL, DSR_HEX);
  911. SMARTLIST_FOREACH_BEGIN(failed, char *, cp) {
  912. /* Null signing key digest indicates download by fp only */
  913. authority_cert_dl_failed(cp, NULL, status);
  914. tor_free(cp);
  915. } SMARTLIST_FOREACH_END(cp);
  916. } else if (!strcmpstart(conn->requested_resource, fpsk_pfx)) {
  917. /* Download by (fp,sk) pairs */
  918. dir_split_resource_into_fingerprint_pairs(conn->requested_resource +
  919. strlen(fpsk_pfx), failed);
  920. SMARTLIST_FOREACH_BEGIN(failed, fp_pair_t *, cp) {
  921. authority_cert_dl_failed(cp->first, cp->second, status);
  922. tor_free(cp);
  923. } SMARTLIST_FOREACH_END(cp);
  924. } else {
  925. log_warn(LD_DIR,
  926. "Don't know what to do with failure for cert fetch %s",
  927. conn->requested_resource);
  928. }
  929. smartlist_free(failed);
  930. update_certificate_downloads(time(NULL));
  931. }
  932. /* Should this tor instance only use begindir for all its directory requests?
  933. */
  934. int
  935. directory_must_use_begindir(const or_options_t *options)
  936. {
  937. /* Clients, onion services, and bridges must use begindir,
  938. * relays and authorities do not have to */
  939. return !public_server_mode(options);
  940. }
  941. struct directory_request_t {
  942. /**
  943. * These fields specify which directory we're contacting. Routerstatus,
  944. * if present, overrides the other fields.
  945. *
  946. * @{ */
  947. tor_addr_port_t or_addr_port;
  948. tor_addr_port_t dir_addr_port;
  949. char digest[DIGEST_LEN];
  950. const routerstatus_t *routerstatus;
  951. /** @} */
  952. /** One of DIR_PURPOSE_* other than DIR_PURPOSE_SERVER. Describes what
  953. * kind of operation we'll be doing (upload/download), and of what kind
  954. * of document. */
  955. uint8_t dir_purpose;
  956. /** One of ROUTER_PURPOSE_*; used for uploads and downloads of routerinfo
  957. * and extrainfo docs. */
  958. uint8_t router_purpose;
  959. /** Enum: determines whether to anonymize, and whether to use dirport or
  960. * orport. */
  961. dir_indirection_t indirection;
  962. /** Alias to the variable part of the URL for this request */
  963. const char *resource;
  964. /** Alias to the payload to upload (if any) */
  965. const char *payload;
  966. /** Number of bytes to upload from payload</b> */
  967. size_t payload_len;
  968. /** Value to send in an if-modified-since header, or 0 for none. */
  969. time_t if_modified_since;
  970. /** Hidden-service-specific information v2. */
  971. const rend_data_t *rend_query;
  972. /** Extra headers to append to the request */
  973. config_line_t *additional_headers;
  974. /** Hidden-service-specific information for v3+. */
  975. const hs_ident_dir_conn_t *hs_ident;
  976. /** Used internally to directory.c: gets informed when the attempt to
  977. * connect to the directory succeeds or fails, if that attempt bears on the
  978. * directory's usability as a directory guard. */
  979. circuit_guard_state_t *guard_state;
  980. };
  981. /** Evaluate the situation and decide if we should use an encrypted
  982. * "begindir-style" connection for this directory request.
  983. * 0) If there is no DirPort, yes.
  984. * 1) If or_port is 0, or it's a direct conn and or_port is firewalled
  985. * or we're a dir mirror, no.
  986. * 2) If we prefer to avoid begindir conns, and we're not fetching or
  987. * publishing a bridge relay descriptor, no.
  988. * 3) Else yes.
  989. * If returning 0, return in *reason why we can't use begindir.
  990. * reason must not be NULL.
  991. */
  992. static int
  993. directory_command_should_use_begindir(const or_options_t *options,
  994. const directory_request_t *req,
  995. const char **reason)
  996. {
  997. const tor_addr_t *or_addr = &req->or_addr_port.addr;
  998. //const tor_addr_t *dir_addr = &req->dir_addr_port.addr;
  999. const int or_port = req->or_addr_port.port;
  1000. const int dir_port = req->dir_addr_port.port;
  1001. const dir_indirection_t indirection = req->indirection;
  1002. tor_assert(reason);
  1003. *reason = NULL;
  1004. /* Reasons why we must use begindir */
  1005. if (!dir_port) {
  1006. *reason = "(using begindir - directory with no DirPort)";
  1007. return 1; /* We don't know a DirPort -- must begindir. */
  1008. }
  1009. /* Reasons why we can't possibly use begindir */
  1010. if (!or_port) {
  1011. *reason = "directory with unknown ORPort";
  1012. return 0; /* We don't know an ORPort -- no chance. */
  1013. }
  1014. if (indirection == DIRIND_DIRECT_CONN ||
  1015. indirection == DIRIND_ANON_DIRPORT) {
  1016. *reason = "DirPort connection";
  1017. return 0;
  1018. }
  1019. if (indirection == DIRIND_ONEHOP) {
  1020. /* We're firewalled and want a direct OR connection */
  1021. if (!fascist_firewall_allows_address_addr(or_addr, or_port,
  1022. FIREWALL_OR_CONNECTION, 0, 0)) {
  1023. *reason = "ORPort not reachable";
  1024. return 0;
  1025. }
  1026. }
  1027. /* Reasons why we want to avoid using begindir */
  1028. if (indirection == DIRIND_ONEHOP) {
  1029. if (!directory_must_use_begindir(options)) {
  1030. *reason = "in relay mode";
  1031. return 0;
  1032. }
  1033. }
  1034. /* DIRIND_ONEHOP on a client, or DIRIND_ANONYMOUS
  1035. */
  1036. *reason = "(using begindir)";
  1037. return 1;
  1038. }
  1039. /**
  1040. * Create and return a new directory_request_t with purpose
  1041. * <b>dir_purpose</b>.
  1042. */
  1043. directory_request_t *
  1044. directory_request_new(uint8_t dir_purpose)
  1045. {
  1046. tor_assert(dir_purpose >= DIR_PURPOSE_MIN_);
  1047. tor_assert(dir_purpose <= DIR_PURPOSE_MAX_);
  1048. tor_assert(dir_purpose != DIR_PURPOSE_SERVER);
  1049. tor_assert(dir_purpose != DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2);
  1050. tor_assert(dir_purpose != DIR_PURPOSE_HAS_FETCHED_HSDESC);
  1051. directory_request_t *result = tor_malloc_zero(sizeof(*result));
  1052. tor_addr_make_null(&result->or_addr_port.addr, AF_INET);
  1053. result->or_addr_port.port = 0;
  1054. tor_addr_make_null(&result->dir_addr_port.addr, AF_INET);
  1055. result->dir_addr_port.port = 0;
  1056. result->dir_purpose = dir_purpose;
  1057. result->router_purpose = ROUTER_PURPOSE_GENERAL;
  1058. result->indirection = DIRIND_ONEHOP;
  1059. return result;
  1060. }
  1061. /**
  1062. * Release all resources held by <b>req</b>.
  1063. */
  1064. void
  1065. directory_request_free(directory_request_t *req)
  1066. {
  1067. if (req == NULL)
  1068. return;
  1069. config_free_lines(req->additional_headers);
  1070. tor_free(req);
  1071. }
  1072. /**
  1073. * Set the address and OR port to use for this directory request. If there is
  1074. * no OR port, we'll have to connect over the dirport. (If there are both,
  1075. * the indirection setting determins which to use.)
  1076. */
  1077. void
  1078. directory_request_set_or_addr_port(directory_request_t *req,
  1079. const tor_addr_port_t *p)
  1080. {
  1081. memcpy(&req->or_addr_port, p, sizeof(*p));
  1082. }
  1083. /**
  1084. * Set the address and dirport to use for this directory request. If there
  1085. * is no dirport, we'll have to connect over the OR port. (If there are both,
  1086. * the indirection setting determins which to use.)
  1087. */
  1088. void
  1089. directory_request_set_dir_addr_port(directory_request_t *req,
  1090. const tor_addr_port_t *p)
  1091. {
  1092. memcpy(&req->dir_addr_port, p, sizeof(*p));
  1093. }
  1094. /**
  1095. * Set the RSA identity digest of the directory to use for this directory
  1096. * request.
  1097. */
  1098. void
  1099. directory_request_set_directory_id_digest(directory_request_t *req,
  1100. const char *digest)
  1101. {
  1102. memcpy(req->digest, digest, DIGEST_LEN);
  1103. }
  1104. /**
  1105. * Set the router purpose associated with uploaded and downloaded router
  1106. * descriptors and extrainfo documents in this directory request. The purpose
  1107. * must be one of ROUTER_PURPOSE_GENERAL (the default) or
  1108. * ROUTER_PURPOSE_BRIDGE.
  1109. */
  1110. void
  1111. directory_request_set_router_purpose(directory_request_t *req,
  1112. uint8_t router_purpose)
  1113. {
  1114. tor_assert(router_purpose == ROUTER_PURPOSE_GENERAL ||
  1115. router_purpose == ROUTER_PURPOSE_BRIDGE);
  1116. // assert that it actually makes sense to set this purpose, given
  1117. // the dir_purpose.
  1118. req->router_purpose = router_purpose;
  1119. }
  1120. /**
  1121. * Set the indirection to be used for the directory request. The indirection
  1122. * parameter configures whether to connect to a DirPort or ORPort, and whether
  1123. * to anonymize the connection. DIRIND_ONEHOP (use ORPort, don't anonymize)
  1124. * is the default. See dir_indirection_t for more information.
  1125. */
  1126. void
  1127. directory_request_set_indirection(directory_request_t *req,
  1128. dir_indirection_t indirection)
  1129. {
  1130. req->indirection = indirection;
  1131. }
  1132. /**
  1133. * Set a pointer to the resource to request from a directory. Different
  1134. * request types use resources to indicate different components of their URL.
  1135. * Note that only an alias to <b>resource</b> is stored, so the
  1136. * <b>resource</b> must outlive the request.
  1137. */
  1138. void
  1139. directory_request_set_resource(directory_request_t *req,
  1140. const char *resource)
  1141. {
  1142. req->resource = resource;
  1143. }
  1144. /**
  1145. * Set a pointer to the payload to include with this directory request, along
  1146. * with its length. Note that only an alias to <b>payload</b> is stored, so
  1147. * the <b>payload</b> must outlive the request.
  1148. */
  1149. void
  1150. directory_request_set_payload(directory_request_t *req,
  1151. const char *payload,
  1152. size_t payload_len)
  1153. {
  1154. tor_assert(DIR_PURPOSE_IS_UPLOAD(req->dir_purpose));
  1155. req->payload = payload;
  1156. req->payload_len = payload_len;
  1157. }
  1158. /**
  1159. * Set an if-modified-since date to send along with the request. The
  1160. * default is 0 (meaning, send no if-modified-since header).
  1161. */
  1162. void
  1163. directory_request_set_if_modified_since(directory_request_t *req,
  1164. time_t if_modified_since)
  1165. {
  1166. req->if_modified_since = if_modified_since;
  1167. }
  1168. /** Include a header of name <b>key</b> with content <b>val</b> in the
  1169. * request. Neither may include newlines or other odd characters. Their
  1170. * ordering is not currently guaranteed.
  1171. *
  1172. * Note that, as elsewhere in this module, header keys include a trailing
  1173. * colon and space.
  1174. */
  1175. void
  1176. directory_request_add_header(directory_request_t *req,
  1177. const char *key,
  1178. const char *val)
  1179. {
  1180. config_line_prepend(&req->additional_headers, key, val);
  1181. }
  1182. /**
  1183. * Set an object containing HS data to be associated with this request. Note
  1184. * that only an alias to <b>query</b> is stored, so the <b>query</b> object
  1185. * must outlive the request.
  1186. */
  1187. void
  1188. directory_request_set_rend_query(directory_request_t *req,
  1189. const rend_data_t *query)
  1190. {
  1191. if (query) {
  1192. tor_assert(req->dir_purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 ||
  1193. req->dir_purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2);
  1194. }
  1195. req->rend_query = query;
  1196. }
  1197. /**
  1198. * Set an object containing HS connection identifier to be associated with
  1199. * this request. Note that only an alias to <b>ident</b> is stored, so the
  1200. * <b>ident</b> object must outlive the request.
  1201. */
  1202. void
  1203. directory_request_upload_set_hs_ident(directory_request_t *req,
  1204. const hs_ident_dir_conn_t *ident)
  1205. {
  1206. if (ident) {
  1207. tor_assert(req->dir_purpose == DIR_PURPOSE_UPLOAD_HSDESC);
  1208. }
  1209. req->hs_ident = ident;
  1210. }
  1211. /**
  1212. * Set an object containing HS connection identifier to be associated with
  1213. * this fetch request. Note that only an alias to <b>ident</b> is stored, so
  1214. * the <b>ident</b> object must outlive the request.
  1215. */
  1216. void
  1217. directory_request_fetch_set_hs_ident(directory_request_t *req,
  1218. const hs_ident_dir_conn_t *ident)
  1219. {
  1220. if (ident) {
  1221. tor_assert(req->dir_purpose == DIR_PURPOSE_FETCH_HSDESC);
  1222. }
  1223. req->hs_ident = ident;
  1224. }
  1225. /** Set a static circuit_guard_state_t object to affliate with the request in
  1226. * <b>req</b>. This object will receive notification when the attempt to
  1227. * connect to the guard either succeeds or fails. */
  1228. void
  1229. directory_request_set_guard_state(directory_request_t *req,
  1230. circuit_guard_state_t *state)
  1231. {
  1232. req->guard_state = state;
  1233. }
  1234. /**
  1235. * Internal: Return true if any information for contacting the directory in
  1236. * <b>req</b> has been set, other than by the routerstatus. */
  1237. static int
  1238. directory_request_dir_contact_info_specified(const directory_request_t *req)
  1239. {
  1240. /* We only check for ports here, since we don't use an addr unless the port
  1241. * is set */
  1242. return (req->or_addr_port.port ||
  1243. req->dir_addr_port.port ||
  1244. ! tor_digest_is_zero(req->digest));
  1245. }
  1246. /**
  1247. * Set the routerstatus to use for the directory associated with this
  1248. * request. If this option is set, then no other function to set the
  1249. * directory's address or identity should be called.
  1250. */
  1251. void
  1252. directory_request_set_routerstatus(directory_request_t *req,
  1253. const routerstatus_t *status)
  1254. {
  1255. req->routerstatus = status;
  1256. }
  1257. /**
  1258. * Helper: update the addresses, ports, and identities in <b>req</b>
  1259. * from the routerstatus object in <b>req</b>. Return 0 on success.
  1260. * On failure, warn and return -1.
  1261. */
  1262. static int
  1263. directory_request_set_dir_from_routerstatus(directory_request_t *req)
  1264. {
  1265. const routerstatus_t *status = req->routerstatus;
  1266. if (BUG(status == NULL))
  1267. return -1;
  1268. const or_options_t *options = get_options();
  1269. const node_t *node;
  1270. tor_addr_port_t use_or_ap, use_dir_ap;
  1271. const int anonymized_connection = dirind_is_anon(req->indirection);
  1272. tor_assert(status != NULL);
  1273. node = node_get_by_id(status->identity_digest);
  1274. /* XXX The below check is wrong: !node means it's not in the consensus,
  1275. * but we haven't checked if we have a descriptor for it -- and also,
  1276. * we only care about the descriptor if it's a begindir-style anonymized
  1277. * connection. */
  1278. if (!node && anonymized_connection) {
  1279. log_info(LD_DIR, "Not sending anonymized request to directory '%s'; we "
  1280. "don't have its router descriptor.",
  1281. routerstatus_describe(status));
  1282. return -1;
  1283. }
  1284. if (options->ExcludeNodes && options->StrictNodes &&
  1285. routerset_contains_routerstatus(options->ExcludeNodes, status, -1)) {
  1286. log_warn(LD_DIR, "Wanted to contact directory mirror %s for %s, but "
  1287. "it's in our ExcludedNodes list and StrictNodes is set. "
  1288. "Skipping. This choice might make your Tor not work.",
  1289. routerstatus_describe(status),
  1290. dir_conn_purpose_to_string(req->dir_purpose));
  1291. return -1;
  1292. }
  1293. /* At this point, if we are a client making a direct connection to a
  1294. * directory server, we have selected a server that has at least one address
  1295. * allowed by ClientUseIPv4/6 and Reachable{"",OR,Dir}Addresses. This
  1296. * selection uses the preference in ClientPreferIPv6{OR,Dir}Port, if
  1297. * possible. (If UseBridges is set, clients always use IPv6, and prefer it
  1298. * by default.)
  1299. *
  1300. * Now choose an address that we can use to connect to the directory server.
  1301. */
  1302. if (directory_choose_address_routerstatus(status,
  1303. req->indirection, &use_or_ap,
  1304. &use_dir_ap) < 0) {
  1305. return -1;
  1306. }
  1307. directory_request_set_or_addr_port(req, &use_or_ap);
  1308. directory_request_set_dir_addr_port(req, &use_dir_ap);
  1309. directory_request_set_directory_id_digest(req, status->identity_digest);
  1310. return 0;
  1311. }
  1312. /**
  1313. * Launch the provided directory request, configured in <b>request</b>.
  1314. * After this function is called, you can free <b>request</b>.
  1315. */
  1316. MOCK_IMPL(void,
  1317. directory_initiate_request,(directory_request_t *request))
  1318. {
  1319. tor_assert(request);
  1320. if (request->routerstatus) {
  1321. tor_assert_nonfatal(
  1322. ! directory_request_dir_contact_info_specified(request));
  1323. if (directory_request_set_dir_from_routerstatus(request) < 0) {
  1324. return;
  1325. }
  1326. }
  1327. const tor_addr_port_t *or_addr_port = &request->or_addr_port;
  1328. const tor_addr_port_t *dir_addr_port = &request->dir_addr_port;
  1329. const char *digest = request->digest;
  1330. const uint8_t dir_purpose = request->dir_purpose;
  1331. const uint8_t router_purpose = request->router_purpose;
  1332. const dir_indirection_t indirection = request->indirection;
  1333. const char *resource = request->resource;
  1334. const rend_data_t *rend_query = request->rend_query;
  1335. const hs_ident_dir_conn_t *hs_ident = request->hs_ident;
  1336. circuit_guard_state_t *guard_state = request->guard_state;
  1337. tor_assert(or_addr_port->port || dir_addr_port->port);
  1338. tor_assert(digest);
  1339. dir_connection_t *conn;
  1340. const or_options_t *options = get_options();
  1341. int socket_error = 0;
  1342. const char *begindir_reason = NULL;
  1343. /* Should the connection be to a relay's OR port (and inside that we will
  1344. * send our directory request)? */
  1345. const int use_begindir =
  1346. directory_command_should_use_begindir(options, request, &begindir_reason);
  1347. /* Will the connection go via a three-hop Tor circuit? Note that this
  1348. * is separate from whether it will use_begindir. */
  1349. const int anonymized_connection = dirind_is_anon(indirection);
  1350. /* What is the address we want to make the directory request to? If
  1351. * we're making a begindir request this is the ORPort of the relay
  1352. * we're contacting; if not a begindir request, this is its DirPort.
  1353. * Note that if anonymized_connection is true, we won't be initiating
  1354. * a connection directly to this address. */
  1355. tor_addr_t addr;
  1356. tor_addr_copy(&addr, &(use_begindir ? or_addr_port : dir_addr_port)->addr);
  1357. uint16_t port = (use_begindir ? or_addr_port : dir_addr_port)->port;
  1358. log_debug(LD_DIR, "anonymized %d, use_begindir %d.",
  1359. anonymized_connection, use_begindir);
  1360. log_debug(LD_DIR, "Initiating %s", dir_conn_purpose_to_string(dir_purpose));
  1361. if (purpose_needs_anonymity(dir_purpose, router_purpose, resource)) {
  1362. tor_assert(anonymized_connection ||
  1363. rend_non_anonymous_mode_enabled(options));
  1364. }
  1365. /* use encrypted begindir connections for everything except relays
  1366. * this provides better protection for directory fetches */
  1367. if (!use_begindir && directory_must_use_begindir(options)) {
  1368. log_warn(LD_BUG, "Client could not use begindir connection: %s",
  1369. begindir_reason ? begindir_reason : "(NULL)");
  1370. return;
  1371. }
  1372. /* ensure that we don't make direct connections when a SOCKS server is
  1373. * configured. */
  1374. if (!anonymized_connection && !use_begindir && !options->HTTPProxy &&
  1375. (options->Socks4Proxy || options->Socks5Proxy)) {
  1376. log_warn(LD_DIR, "Cannot connect to a directory server through a "
  1377. "SOCKS proxy!");
  1378. return;
  1379. }
  1380. /* Make sure that the destination addr and port we picked is viable. */
  1381. if (!port || tor_addr_is_null(&addr)) {
  1382. static int logged_backtrace = 0;
  1383. log_warn(LD_DIR,
  1384. "Cannot make an outgoing %sconnection without a remote %sPort.",
  1385. use_begindir ? "begindir " : "",
  1386. use_begindir ? "OR" : "Dir");
  1387. if (!logged_backtrace) {
  1388. log_backtrace(LOG_INFO, LD_BUG, "Address came from");
  1389. logged_backtrace = 1;
  1390. }
  1391. return;
  1392. }
  1393. conn = dir_connection_new(tor_addr_family(&addr));
  1394. /* set up conn so it's got all the data we need to remember */
  1395. tor_addr_copy(&conn->base_.addr, &addr);
  1396. conn->base_.port = port;
  1397. conn->base_.address = tor_addr_to_str_dup(&addr);
  1398. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  1399. conn->base_.purpose = dir_purpose;
  1400. conn->router_purpose = router_purpose;
  1401. /* give it an initial state */
  1402. conn->base_.state = DIR_CONN_STATE_CONNECTING;
  1403. /* decide whether we can learn our IP address from this conn */
  1404. /* XXXX This is a bad name for this field now. */
  1405. conn->dirconn_direct = !anonymized_connection;
  1406. /* copy rendezvous data, if any */
  1407. if (rend_query) {
  1408. /* We can't have both v2 and v3+ identifier. */
  1409. tor_assert_nonfatal(!hs_ident);
  1410. conn->rend_data = rend_data_dup(rend_query);
  1411. }
  1412. if (hs_ident) {
  1413. /* We can't have both v2 and v3+ identifier. */
  1414. tor_assert_nonfatal(!rend_query);
  1415. conn->hs_ident = hs_ident_dir_conn_dup(hs_ident);
  1416. }
  1417. if (!anonymized_connection && !use_begindir) {
  1418. /* then we want to connect to dirport directly */
  1419. if (options->HTTPProxy) {
  1420. tor_addr_copy(&addr, &options->HTTPProxyAddr);
  1421. port = options->HTTPProxyPort;
  1422. }
  1423. // In this case we should not have picked a directory guard.
  1424. if (BUG(guard_state)) {
  1425. entry_guard_cancel(&guard_state);
  1426. }
  1427. switch (connection_connect(TO_CONN(conn), conn->base_.address, &addr,
  1428. port, &socket_error)) {
  1429. case -1:
  1430. connection_mark_for_close(TO_CONN(conn));
  1431. return;
  1432. case 1:
  1433. /* start flushing conn */
  1434. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  1435. /* fall through */
  1436. case 0:
  1437. /* queue the command on the outbuf */
  1438. directory_send_command(conn, 1, request);
  1439. connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
  1440. /* writable indicates finish, readable indicates broken link,
  1441. error indicates broken link in windowsland. */
  1442. }
  1443. } else {
  1444. /* We will use a Tor circuit (maybe 1-hop, maybe 3-hop, maybe with
  1445. * begindir, maybe not with begindir) */
  1446. entry_connection_t *linked_conn;
  1447. /* Anonymized tunneled connections can never share a circuit.
  1448. * One-hop directory connections can share circuits with each other
  1449. * but nothing else. */
  1450. int iso_flags = anonymized_connection ? ISO_STREAM : ISO_SESSIONGRP;
  1451. /* If it's an anonymized connection, remember the fact that we
  1452. * wanted it for later: maybe we'll want it again soon. */
  1453. if (anonymized_connection && use_begindir)
  1454. rep_hist_note_used_internal(time(NULL), 0, 1);
  1455. else if (anonymized_connection && !use_begindir)
  1456. rep_hist_note_used_port(time(NULL), conn->base_.port);
  1457. // In this case we should not have a directory guard; we'll
  1458. // get a regular guard later when we build the circuit.
  1459. if (BUG(anonymized_connection && guard_state)) {
  1460. entry_guard_cancel(&guard_state);
  1461. }
  1462. conn->guard_state = guard_state;
  1463. /* make an AP connection
  1464. * populate it and add it at the right state
  1465. * hook up both sides
  1466. */
  1467. linked_conn =
  1468. connection_ap_make_link(TO_CONN(conn),
  1469. conn->base_.address, conn->base_.port,
  1470. digest,
  1471. SESSION_GROUP_DIRCONN, iso_flags,
  1472. use_begindir, !anonymized_connection);
  1473. if (!linked_conn) {
  1474. log_warn(LD_NET,"Making tunnel to dirserver failed.");
  1475. connection_mark_for_close(TO_CONN(conn));
  1476. return;
  1477. }
  1478. if (connection_add(TO_CONN(conn)) < 0) {
  1479. log_warn(LD_NET,"Unable to add connection for link to dirserver.");
  1480. connection_mark_for_close(TO_CONN(conn));
  1481. return;
  1482. }
  1483. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  1484. /* queue the command on the outbuf */
  1485. directory_send_command(conn, 0, request);
  1486. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  1487. connection_start_reading(ENTRY_TO_CONN(linked_conn));
  1488. }
  1489. }
  1490. /** Return true iff anything we say on <b>conn</b> is being encrypted before
  1491. * we send it to the client/server. */
  1492. int
  1493. connection_dir_is_encrypted(const dir_connection_t *conn)
  1494. {
  1495. /* Right now it's sufficient to see if conn is or has been linked, since
  1496. * the only thing it could be linked to is an edge connection on a
  1497. * circuit, and the only way it could have been unlinked is at the edge
  1498. * connection getting closed.
  1499. */
  1500. return TO_CONN(conn)->linked;
  1501. }
  1502. /** Helper for sorting
  1503. *
  1504. * sort strings alphabetically
  1505. */
  1506. static int
  1507. compare_strs_(const void **a, const void **b)
  1508. {
  1509. const char *s1 = *a, *s2 = *b;
  1510. return strcmp(s1, s2);
  1511. }
  1512. #define CONDITIONAL_CONSENSUS_FPR_LEN 3
  1513. #if (CONDITIONAL_CONSENSUS_FPR_LEN > DIGEST_LEN)
  1514. #error "conditional consensus fingerprint length is larger than digest length"
  1515. #endif
  1516. /** Return the URL we should use for a consensus download.
  1517. *
  1518. * Use the "conditional consensus downloading" feature described in
  1519. * dir-spec.txt, i.e.
  1520. * GET .../consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>
  1521. *
  1522. * If 'resource' is provided, it is the name of a consensus flavor to request.
  1523. */
  1524. static char *
  1525. directory_get_consensus_url(const char *resource)
  1526. {
  1527. char *url = NULL;
  1528. const char *hyphen, *flavor;
  1529. if (resource==NULL || strcmp(resource, "ns")==0) {
  1530. flavor = ""; /* Request ns consensuses as "", so older servers will work*/
  1531. hyphen = "";
  1532. } else {
  1533. flavor = resource;
  1534. hyphen = "-";
  1535. }
  1536. {
  1537. char *authority_id_list;
  1538. smartlist_t *authority_digests = smartlist_new();
  1539. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  1540. dir_server_t *, ds) {
  1541. char *hex;
  1542. if (!(ds->type & V3_DIRINFO))
  1543. continue;
  1544. hex = tor_malloc(2*CONDITIONAL_CONSENSUS_FPR_LEN+1);
  1545. base16_encode(hex, 2*CONDITIONAL_CONSENSUS_FPR_LEN+1,
  1546. ds->v3_identity_digest, CONDITIONAL_CONSENSUS_FPR_LEN);
  1547. smartlist_add(authority_digests, hex);
  1548. } SMARTLIST_FOREACH_END(ds);
  1549. smartlist_sort(authority_digests, compare_strs_);
  1550. authority_id_list = smartlist_join_strings(authority_digests,
  1551. "+", 0, NULL);
  1552. tor_asprintf(&url, "/tor/status-vote/current/consensus%s%s/%s.z",
  1553. hyphen, flavor, authority_id_list);
  1554. SMARTLIST_FOREACH(authority_digests, char *, cp, tor_free(cp));
  1555. smartlist_free(authority_digests);
  1556. tor_free(authority_id_list);
  1557. }
  1558. return url;
  1559. }
  1560. /**
  1561. * Copies the ipv6 from source to destination, subject to buffer size limit
  1562. * size. If decorate is true, makes sure the copied address is decorated.
  1563. */
  1564. static void
  1565. copy_ipv6_address(char* destination, const char* source, size_t len,
  1566. int decorate) {
  1567. tor_assert(destination);
  1568. tor_assert(source);
  1569. if (decorate && source[0] != '[') {
  1570. tor_snprintf(destination, len, "[%s]", source);
  1571. } else {
  1572. strlcpy(destination, source, len);
  1573. }
  1574. }
  1575. /** Queue an appropriate HTTP command for <b>request</b> on
  1576. * <b>conn</b>-\>outbuf. If <b>direct</b> is true, we're making a
  1577. * non-anonymized connection to the dirport.
  1578. */
  1579. static void
  1580. directory_send_command(dir_connection_t *conn,
  1581. const int direct,
  1582. const directory_request_t *req)
  1583. {
  1584. tor_assert(req);
  1585. const int purpose = req->dir_purpose;
  1586. const char *resource = req->resource;
  1587. const char *payload = req->payload;
  1588. const size_t payload_len = req->payload_len;
  1589. const time_t if_modified_since = req->if_modified_since;
  1590. const int anonymized_connection = dirind_is_anon(req->indirection);
  1591. char proxystring[256];
  1592. char hoststring[128];
  1593. /* NEEDS to be the same size hoststring.
  1594. Will be decorated with brackets around it if it is ipv6. */
  1595. char decorated_address[128];
  1596. smartlist_t *headers = smartlist_new();
  1597. char *url;
  1598. char *accept_encoding;
  1599. size_t url_len;
  1600. char request[8192];
  1601. size_t request_len, total_request_len = 0;
  1602. const char *httpcommand = NULL;
  1603. tor_assert(conn);
  1604. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  1605. tor_free(conn->requested_resource);
  1606. if (resource)
  1607. conn->requested_resource = tor_strdup(resource);
  1608. /* decorate the ip address if it is ipv6 */
  1609. if (strchr(conn->base_.address, ':')) {
  1610. copy_ipv6_address(decorated_address, conn->base_.address,
  1611. sizeof(decorated_address), 1);
  1612. } else {
  1613. strlcpy(decorated_address, conn->base_.address, sizeof(decorated_address));
  1614. }
  1615. /* come up with a string for which Host: we want */
  1616. if (conn->base_.port == 80) {
  1617. strlcpy(hoststring, decorated_address, sizeof(hoststring));
  1618. } else {
  1619. tor_snprintf(hoststring, sizeof(hoststring), "%s:%d",
  1620. decorated_address, conn->base_.port);
  1621. }
  1622. /* Format if-modified-since */
  1623. if (if_modified_since) {
  1624. char b[RFC1123_TIME_LEN+1];
  1625. format_rfc1123_time(b, if_modified_since);
  1626. smartlist_add_asprintf(headers, "If-Modified-Since: %s\r\n", b);
  1627. }
  1628. /* come up with some proxy lines, if we're using one. */
  1629. if (direct && get_options()->HTTPProxy) {
  1630. char *base64_authenticator=NULL;
  1631. const char *authenticator = get_options()->HTTPProxyAuthenticator;
  1632. tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  1633. if (authenticator) {
  1634. base64_authenticator = alloc_http_authenticator(authenticator);
  1635. if (!base64_authenticator)
  1636. log_warn(LD_BUG, "Encoding http authenticator failed");
  1637. }
  1638. if (base64_authenticator) {
  1639. smartlist_add_asprintf(headers,
  1640. "Proxy-Authorization: Basic %s\r\n",
  1641. base64_authenticator);
  1642. tor_free(base64_authenticator);
  1643. }
  1644. } else {
  1645. proxystring[0] = 0;
  1646. }
  1647. if (! anonymized_connection) {
  1648. /* Add Accept-Encoding. */
  1649. accept_encoding = accept_encoding_header();
  1650. smartlist_add_asprintf(headers, "Accept-Encoding: %s\r\n",
  1651. accept_encoding);
  1652. tor_free(accept_encoding);
  1653. }
  1654. /* Add additional headers, if any */
  1655. {
  1656. config_line_t *h;
  1657. for (h = req->additional_headers; h; h = h->next) {
  1658. smartlist_add_asprintf(headers, "%s%s\r\n", h->key, h->value);
  1659. }
  1660. }
  1661. switch (purpose) {
  1662. case DIR_PURPOSE_FETCH_CONSENSUS:
  1663. /* resource is optional. If present, it's a flavor name */
  1664. tor_assert(!payload);
  1665. httpcommand = "GET";
  1666. url = directory_get_consensus_url(resource);
  1667. log_info(LD_DIR, "Downloading consensus from %s using %s",
  1668. hoststring, url);
  1669. break;
  1670. case DIR_PURPOSE_FETCH_CERTIFICATE:
  1671. tor_assert(resource);
  1672. tor_assert(!payload);
  1673. httpcommand = "GET";
  1674. tor_asprintf(&url, "/tor/keys/%s", resource);
  1675. break;
  1676. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  1677. tor_assert(resource);
  1678. tor_assert(!payload);
  1679. httpcommand = "GET";
  1680. tor_asprintf(&url, "/tor/status-vote/next/%s.z", resource);
  1681. break;
  1682. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  1683. tor_assert(!resource);
  1684. tor_assert(!payload);
  1685. httpcommand = "GET";
  1686. url = tor_strdup("/tor/status-vote/next/consensus-signatures.z");
  1687. break;
  1688. case DIR_PURPOSE_FETCH_SERVERDESC:
  1689. tor_assert(resource);
  1690. httpcommand = "GET";
  1691. tor_asprintf(&url, "/tor/server/%s", resource);
  1692. break;
  1693. case DIR_PURPOSE_FETCH_EXTRAINFO:
  1694. tor_assert(resource);
  1695. httpcommand = "GET";
  1696. tor_asprintf(&url, "/tor/extra/%s", resource);
  1697. break;
  1698. case DIR_PURPOSE_FETCH_MICRODESC:
  1699. tor_assert(resource);
  1700. httpcommand = "GET";
  1701. tor_asprintf(&url, "/tor/micro/%s", resource);
  1702. break;
  1703. case DIR_PURPOSE_UPLOAD_DIR: {
  1704. const char *why = router_get_descriptor_gen_reason();
  1705. tor_assert(!resource);
  1706. tor_assert(payload);
  1707. httpcommand = "POST";
  1708. url = tor_strdup("/tor/");
  1709. if (why) {
  1710. smartlist_add_asprintf(headers, "X-Desc-Gen-Reason: %s\r\n", why);
  1711. }
  1712. break;
  1713. }
  1714. case DIR_PURPOSE_UPLOAD_VOTE:
  1715. tor_assert(!resource);
  1716. tor_assert(payload);
  1717. httpcommand = "POST";
  1718. url = tor_strdup("/tor/post/vote");
  1719. break;
  1720. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  1721. tor_assert(!resource);
  1722. tor_assert(payload);
  1723. httpcommand = "POST";
  1724. url = tor_strdup("/tor/post/consensus-signature");
  1725. break;
  1726. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  1727. tor_assert(resource);
  1728. tor_assert(strlen(resource) <= REND_DESC_ID_V2_LEN_BASE32);
  1729. tor_assert(!payload);
  1730. httpcommand = "GET";
  1731. tor_asprintf(&url, "/tor/rendezvous2/%s", resource);
  1732. break;
  1733. case DIR_PURPOSE_FETCH_HSDESC:
  1734. tor_assert(resource);
  1735. tor_assert(strlen(resource) <= ED25519_BASE64_LEN);
  1736. tor_assert(!payload);
  1737. httpcommand = "GET";
  1738. tor_asprintf(&url, "/tor/hs/3/%s", resource);
  1739. break;
  1740. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  1741. tor_assert(!resource);
  1742. tor_assert(payload);
  1743. httpcommand = "POST";
  1744. url = tor_strdup("/tor/rendezvous2/publish");
  1745. break;
  1746. case DIR_PURPOSE_UPLOAD_HSDESC:
  1747. tor_assert(resource);
  1748. tor_assert(payload);
  1749. httpcommand = "POST";
  1750. tor_asprintf(&url, "/tor/hs/%s/publish", resource);
  1751. break;
  1752. default:
  1753. tor_assert(0);
  1754. return;
  1755. }
  1756. /* warn in the non-tunneled case */
  1757. if (direct && (strlen(proxystring) + strlen(url) >= 4096)) {
  1758. log_warn(LD_BUG,
  1759. "Squid does not like URLs longer than 4095 bytes, and this "
  1760. "one is %d bytes long: %s%s",
  1761. (int)(strlen(proxystring) + strlen(url)), proxystring, url);
  1762. }
  1763. tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
  1764. request_len = strlen(request);
  1765. total_request_len += request_len;
  1766. connection_buf_add(request, request_len, TO_CONN(conn));
  1767. url_len = strlen(url);
  1768. total_request_len += url_len;
  1769. connection_buf_add(url, url_len, TO_CONN(conn));
  1770. tor_free(url);
  1771. if (!strcmp(httpcommand, "POST") || payload) {
  1772. smartlist_add_asprintf(headers, "Content-Length: %lu\r\n",
  1773. payload ? (unsigned long)payload_len : 0);
  1774. }
  1775. {
  1776. char *header = smartlist_join_strings(headers, "", 0, NULL);
  1777. tor_snprintf(request, sizeof(request), " HTTP/1.0\r\nHost: %s\r\n%s\r\n",
  1778. hoststring, header);
  1779. tor_free(header);
  1780. }
  1781. request_len = strlen(request);
  1782. total_request_len += request_len;
  1783. connection_buf_add(request, request_len, TO_CONN(conn));
  1784. if (payload) {
  1785. /* then send the payload afterwards too */
  1786. connection_buf_add(payload, payload_len, TO_CONN(conn));
  1787. total_request_len += payload_len;
  1788. }
  1789. SMARTLIST_FOREACH(headers, char *, h, tor_free(h));
  1790. smartlist_free(headers);
  1791. log_debug(LD_DIR,
  1792. "Sent request to directory server '%s:%d': "
  1793. "(purpose: %d, request size: " U64_FORMAT ", "
  1794. "payload size: " U64_FORMAT ")",
  1795. conn->base_.address, conn->base_.port,
  1796. conn->base_.purpose,
  1797. U64_PRINTF_ARG(total_request_len),
  1798. U64_PRINTF_ARG(payload ? payload_len : 0));
  1799. }
  1800. /** Parse an HTTP request string <b>headers</b> of the form
  1801. * \verbatim
  1802. * "\%s [http[s]://]\%s HTTP/1..."
  1803. * \endverbatim
  1804. * If it's well-formed, strdup the second \%s into *<b>url</b>, and
  1805. * nul-terminate it. If the url doesn't start with "/tor/", rewrite it
  1806. * so it does. Return 0.
  1807. * Otherwise, return -1.
  1808. */
  1809. STATIC int
  1810. parse_http_url(const char *headers, char **url)
  1811. {
  1812. char *command = NULL;
  1813. if (parse_http_command(headers, &command, url) < 0) {
  1814. return -1;
  1815. }
  1816. if (strcmpstart(*url, "/tor/")) {
  1817. char *new_url = NULL;
  1818. tor_asprintf(&new_url, "/tor%s%s",
  1819. *url[0] == '/' ? "" : "/",
  1820. *url);
  1821. tor_free(*url);
  1822. *url = new_url;
  1823. }
  1824. tor_free(command);
  1825. return 0;
  1826. }
  1827. /** Parse an HTTP request line at the start of a headers string. On failure,
  1828. * return -1. On success, set *<b>command_out</b> to a copy of the HTTP
  1829. * command ("get", "post", etc), set *<b>url_out</b> to a copy of the URL, and
  1830. * return 0. */
  1831. int
  1832. parse_http_command(const char *headers, char **command_out, char **url_out)
  1833. {
  1834. const char *command, *end_of_command;
  1835. char *s, *start, *tmp;
  1836. s = (char *)eat_whitespace_no_nl(headers);
  1837. if (!*s) return -1;
  1838. command = s;
  1839. s = (char *)find_whitespace(s); /* get past GET/POST */
  1840. if (!*s) return -1;
  1841. end_of_command = s;
  1842. s = (char *)eat_whitespace_no_nl(s);
  1843. if (!*s) return -1;
  1844. start = s; /* this is the URL, assuming it's valid */
  1845. s = (char *)find_whitespace(start);
  1846. if (!*s) return -1;
  1847. /* tolerate the http[s] proxy style of putting the hostname in the url */
  1848. if (s-start >= 4 && !strcmpstart(start,"http")) {
  1849. tmp = start + 4;
  1850. if (*tmp == 's')
  1851. tmp++;
  1852. if (s-tmp >= 3 && !strcmpstart(tmp,"://")) {
  1853. tmp = strchr(tmp+3, '/');
  1854. if (tmp && tmp < s) {
  1855. log_debug(LD_DIR,"Skipping over 'http[s]://hostname/' string");
  1856. start = tmp;
  1857. }
  1858. }
  1859. }
  1860. /* Check if the header is well formed (next sequence
  1861. * should be HTTP/1.X\r\n). Assumes we're supporting 1.0? */
  1862. {
  1863. unsigned minor_ver;
  1864. char ch;
  1865. char *e = (char *)eat_whitespace_no_nl(s);
  1866. if (2 != tor_sscanf(e, "HTTP/1.%u%c", &minor_ver, &ch)) {
  1867. return -1;
  1868. }
  1869. if (ch != '\r')
  1870. return -1;
  1871. }
  1872. *url_out = tor_memdup_nulterm(start, s-start);
  1873. *command_out = tor_memdup_nulterm(command, end_of_command - command);
  1874. return 0;
  1875. }
  1876. /** Return a copy of the first HTTP header in <b>headers</b> whose key is
  1877. * <b>which</b>. The key should be given with a terminating colon and space;
  1878. * this function copies everything after, up to but not including the
  1879. * following \\r\\n. */
  1880. char *
  1881. http_get_header(const char *headers, const char *which)
  1882. {
  1883. const char *cp = headers;
  1884. while (cp) {
  1885. if (!strcasecmpstart(cp, which)) {
  1886. char *eos;
  1887. cp += strlen(which);
  1888. if ((eos = strchr(cp,'\r')))
  1889. return tor_strndup(cp, eos-cp);
  1890. else
  1891. return tor_strdup(cp);
  1892. }
  1893. cp = strchr(cp, '\n');
  1894. if (cp)
  1895. ++cp;
  1896. }
  1897. return NULL;
  1898. }
  1899. /** If <b>headers</b> indicates that a proxy was involved, then rewrite
  1900. * <b>conn</b>-\>address to describe our best guess of the address that
  1901. * originated this HTTP request. */
  1902. static void
  1903. http_set_address_origin(const char *headers, connection_t *conn)
  1904. {
  1905. char *fwd;
  1906. fwd = http_get_header(headers, "Forwarded-For: ");
  1907. if (!fwd)
  1908. fwd = http_get_header(headers, "X-Forwarded-For: ");
  1909. if (fwd) {
  1910. tor_addr_t toraddr;
  1911. if (tor_addr_parse(&toraddr,fwd) == -1 ||
  1912. tor_addr_is_internal(&toraddr,0)) {
  1913. log_debug(LD_DIR, "Ignoring local/internal IP %s", escaped(fwd));
  1914. tor_free(fwd);
  1915. return;
  1916. }
  1917. tor_free(conn->address);
  1918. conn->address = tor_strdup(fwd);
  1919. tor_free(fwd);
  1920. }
  1921. }
  1922. /** Parse an HTTP response string <b>headers</b> of the form
  1923. * \verbatim
  1924. * "HTTP/1.\%d \%d\%s\r\n...".
  1925. * \endverbatim
  1926. *
  1927. * If it's well-formed, assign the status code to *<b>code</b> and
  1928. * return 0. Otherwise, return -1.
  1929. *
  1930. * On success: If <b>date</b> is provided, set *date to the Date
  1931. * header in the http headers, or 0 if no such header is found. If
  1932. * <b>compression</b> is provided, set *<b>compression</b> to the
  1933. * compression method given in the Content-Encoding header, or 0 if no
  1934. * such header is found, or -1 if the value of the header is not
  1935. * recognized. If <b>reason</b> is provided, strdup the reason string
  1936. * into it.
  1937. */
  1938. int
  1939. parse_http_response(const char *headers, int *code, time_t *date,
  1940. compress_method_t *compression, char **reason)
  1941. {
  1942. unsigned n1, n2;
  1943. char datestr[RFC1123_TIME_LEN+1];
  1944. smartlist_t *parsed_headers;
  1945. tor_assert(headers);
  1946. tor_assert(code);
  1947. while (TOR_ISSPACE(*headers)) headers++; /* tolerate leading whitespace */
  1948. if (tor_sscanf(headers, "HTTP/1.%u %u", &n1, &n2) < 2 ||
  1949. (n1 != 0 && n1 != 1) ||
  1950. (n2 < 100 || n2 >= 600)) {
  1951. log_warn(LD_HTTP,"Failed to parse header %s",escaped(headers));
  1952. return -1;
  1953. }
  1954. *code = n2;
  1955. parsed_headers = smartlist_new();
  1956. smartlist_split_string(parsed_headers, headers, "\n",
  1957. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  1958. if (reason) {
  1959. smartlist_t *status_line_elements = smartlist_new();
  1960. tor_assert(smartlist_len(parsed_headers));
  1961. smartlist_split_string(status_line_elements,
  1962. smartlist_get(parsed_headers, 0),
  1963. " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1964. tor_assert(smartlist_len(status_line_elements) <= 3);
  1965. if (smartlist_len(status_line_elements) == 3) {
  1966. *reason = smartlist_get(status_line_elements, 2);
  1967. smartlist_set(status_line_elements, 2, NULL); /* Prevent free */
  1968. }
  1969. SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
  1970. smartlist_free(status_line_elements);
  1971. }
  1972. if (date) {
  1973. *date = 0;
  1974. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  1975. if (!strcmpstart(s, "Date: ")) {
  1976. strlcpy(datestr, s+6, sizeof(datestr));
  1977. /* This will do nothing on failure, so we don't need to check
  1978. the result. We shouldn't warn, since there are many other valid
  1979. date formats besides the one we use. */
  1980. parse_rfc1123_time(datestr, date);
  1981. break;
  1982. });
  1983. }
  1984. if (compression) {
  1985. const char *enc = NULL;
  1986. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  1987. if (!strcmpstart(s, "Content-Encoding: ")) {
  1988. enc = s+18; break;
  1989. });
  1990. if (enc == NULL)
  1991. *compression = NO_METHOD;
  1992. else {
  1993. *compression = compression_method_get_by_name(enc);
  1994. if (*compression == UNKNOWN_METHOD)
  1995. log_info(LD_HTTP, "Unrecognized content encoding: %s. Trying to deal.",
  1996. escaped(enc));
  1997. }
  1998. }
  1999. SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  2000. smartlist_free(parsed_headers);
  2001. return 0;
  2002. }
  2003. /** Return true iff <b>body</b> doesn't start with a plausible router or
  2004. * network-status or microdescriptor opening. This is a sign of possible
  2005. * compression. */
  2006. static int
  2007. body_is_plausible(const char *body, size_t len, int purpose)
  2008. {
  2009. int i;
  2010. if (len == 0)
  2011. return 1; /* empty bodies don't need decompression */
  2012. if (len < 32)
  2013. return 0;
  2014. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  2015. return (!strcmpstart(body,"onion-key"));
  2016. }
  2017. if (!strcmpstart(body,"router") ||
  2018. !strcmpstart(body,"network-status"))
  2019. return 1;
  2020. for (i=0;i<32;++i) {
  2021. if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  2022. return 0;
  2023. }
  2024. return 1;
  2025. }
  2026. /** Called when we've just fetched a bunch of router descriptors in
  2027. * <b>body</b>. The list <b>which</b>, if present, holds digests for
  2028. * descriptors we requested: descriptor digests if <b>descriptor_digests</b>
  2029. * is true, or identity digests otherwise. Parse the descriptors, validate
  2030. * them, and annotate them as having purpose <b>purpose</b> and as having been
  2031. * downloaded from <b>source</b>.
  2032. *
  2033. * Return the number of routers actually added. */
  2034. static int
  2035. load_downloaded_routers(const char *body, smartlist_t *which,
  2036. int descriptor_digests,
  2037. int router_purpose,
  2038. const char *source)
  2039. {
  2040. char buf[256];
  2041. char time_buf[ISO_TIME_LEN+1];
  2042. int added = 0;
  2043. int general = router_purpose == ROUTER_PURPOSE_GENERAL;
  2044. format_iso_time(time_buf, time(NULL));
  2045. tor_assert(source);
  2046. if (tor_snprintf(buf, sizeof(buf),
  2047. "@downloaded-at %s\n"
  2048. "@source %s\n"
  2049. "%s%s%s", time_buf, escaped(source),
  2050. !general ? "@purpose " : "",
  2051. !general ? router_purpose_to_string(router_purpose) : "",
  2052. !general ? "\n" : "")<0)
  2053. return added;
  2054. added = router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  2055. descriptor_digests, buf);
  2056. if (added && general)
  2057. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  2058. count_loading_descriptors_progress());
  2059. return added;
  2060. }
  2061. static int handle_response_fetch_consensus(dir_connection_t *,
  2062. const response_handler_args_t *);
  2063. static int handle_response_fetch_certificate(dir_connection_t *,
  2064. const response_handler_args_t *);
  2065. static int handle_response_fetch_status_vote(dir_connection_t *,
  2066. const response_handler_args_t *);
  2067. static int handle_response_fetch_detached_signatures(dir_connection_t *,
  2068. const response_handler_args_t *);
  2069. static int handle_response_fetch_desc(dir_connection_t *,
  2070. const response_handler_args_t *);
  2071. static int handle_response_fetch_microdesc(dir_connection_t *,
  2072. const response_handler_args_t *);
  2073. static int handle_response_upload_dir(dir_connection_t *,
  2074. const response_handler_args_t *);
  2075. static int handle_response_upload_vote(dir_connection_t *,
  2076. const response_handler_args_t *);
  2077. static int handle_response_upload_signatures(dir_connection_t *,
  2078. const response_handler_args_t *);
  2079. static int handle_response_fetch_renddesc_v2(dir_connection_t *,
  2080. const response_handler_args_t *);
  2081. static int handle_response_upload_renddesc_v2(dir_connection_t *,
  2082. const response_handler_args_t *);
  2083. static int handle_response_upload_hsdesc(dir_connection_t *,
  2084. const response_handler_args_t *);
  2085. static int
  2086. dir_client_decompress_response_body(char **bodyp, size_t *bodylenp,
  2087. dir_connection_t *conn,
  2088. compress_method_t compression,
  2089. int anonymized_connection)
  2090. {
  2091. int rv = 0;
  2092. const char *body = *bodyp;
  2093. size_t body_len = *bodylenp;
  2094. int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  2095. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  2096. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  2097. int plausible = body_is_plausible(body, body_len, conn->base_.purpose);
  2098. if (plausible && compression == NO_METHOD) {
  2099. return 0;
  2100. }
  2101. int severity = LOG_DEBUG;
  2102. char *new_body = NULL;
  2103. size_t new_len = 0;
  2104. const char *description1, *description2;
  2105. int want_to_try_both = 0;
  2106. int tried_both = 0;
  2107. compress_method_t guessed = detect_compression_method(body, body_len);
  2108. description1 = compression_method_get_human_name(compression);
  2109. if (BUG(description1 == NULL))
  2110. description1 = compression_method_get_human_name(UNKNOWN_METHOD);
  2111. if (guessed == UNKNOWN_METHOD && !plausible)
  2112. description2 = "confusing binary junk";
  2113. else
  2114. description2 = compression_method_get_human_name(guessed);
  2115. /* Tell the user if we don't believe what we're told about compression.*/
  2116. want_to_try_both = (compression == UNKNOWN_METHOD ||
  2117. guessed != compression);
  2118. if (want_to_try_both) {
  2119. severity = LOG_PROTOCOL_WARN;
  2120. }
  2121. tor_log(severity, LD_HTTP,
  2122. "HTTP body from server '%s:%d' was labeled as %s, "
  2123. "%s it seems to be %s.%s",
  2124. conn->base_.address, conn->base_.port, description1,
  2125. guessed != compression?"but":"and",
  2126. description2,
  2127. (compression>0 && guessed>0 && want_to_try_both)?
  2128. " Trying both.":"");
  2129. /* Try declared compression first if we can.
  2130. * tor_compress_supports_method() also returns true for NO_METHOD.
  2131. * Ensure that the server is not sending us data compressed using a
  2132. * compression method that is not allowed for anonymous connections. */
  2133. if (anonymized_connection &&
  2134. ! allowed_anonymous_connection_compression_method(compression)) {
  2135. warn_disallowed_anonymous_compression_method(compression);
  2136. rv = -1;
  2137. goto done;
  2138. }
  2139. if (tor_compress_supports_method(compression)) {
  2140. tor_uncompress(&new_body, &new_len, body, body_len, compression,
  2141. !allow_partial, LOG_PROTOCOL_WARN);
  2142. if (new_body) {
  2143. /* We succeeded with the declared compression method. Great! */
  2144. rv = 0;
  2145. goto done;
  2146. }
  2147. }
  2148. /* Okay, if that didn't work, and we think that it was compressed
  2149. * differently, try that. */
  2150. if (anonymized_connection &&
  2151. ! allowed_anonymous_connection_compression_method(guessed)) {
  2152. warn_disallowed_anonymous_compression_method(guessed);
  2153. rv = -1;
  2154. goto done;
  2155. }
  2156. if (tor_compress_supports_method(guessed) &&
  2157. compression != guessed) {
  2158. tor_uncompress(&new_body, &new_len, body, body_len, guessed,
  2159. !allow_partial, LOG_INFO);
  2160. tried_both = 1;
  2161. }
  2162. /* If we're pretty sure that we have a compressed directory, and
  2163. * we didn't manage to uncompress it, then warn and bail. */
  2164. if (!plausible && !new_body) {
  2165. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  2166. "Unable to decompress HTTP body (tried %s%s%s, server '%s:%d').",
  2167. description1,
  2168. tried_both?" and ":"",
  2169. tried_both?description2:"",
  2170. conn->base_.address, conn->base_.port);
  2171. rv = -1;
  2172. goto done;
  2173. }
  2174. done:
  2175. if (new_body) {
  2176. if (rv == 0) {
  2177. /* success! */
  2178. tor_free(*bodyp);
  2179. *bodyp = new_body;
  2180. *bodylenp = new_len;
  2181. } else {
  2182. tor_free(new_body);
  2183. }
  2184. }
  2185. return rv;
  2186. }
  2187. /** We are a client, and we've finished reading the server's
  2188. * response. Parse it and act appropriately.
  2189. *
  2190. * If we're still happy with using this directory server in the future, return
  2191. * 0. Otherwise return -1; and the caller should consider trying the request
  2192. * again.
  2193. *
  2194. * The caller will take care of marking the connection for close.
  2195. */
  2196. static int
  2197. connection_dir_client_reached_eof(dir_connection_t *conn)
  2198. {
  2199. char *body = NULL;
  2200. char *headers = NULL;
  2201. char *reason = NULL;
  2202. size_t body_len = 0;
  2203. int status_code;
  2204. time_t date_header = 0;
  2205. long apparent_skew;
  2206. compress_method_t compression;
  2207. int skewed = 0;
  2208. int rv;
  2209. int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  2210. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  2211. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  2212. size_t received_bytes;
  2213. const int anonymized_connection =
  2214. purpose_needs_anonymity(conn->base_.purpose,
  2215. conn->router_purpose,
  2216. conn->requested_resource);
  2217. received_bytes = connection_get_inbuf_len(TO_CONN(conn));
  2218. switch (connection_fetch_from_buf_http(TO_CONN(conn),
  2219. &headers, MAX_HEADERS_SIZE,
  2220. &body, &body_len, MAX_DIR_DL_SIZE,
  2221. allow_partial)) {
  2222. case -1: /* overflow */
  2223. log_warn(LD_PROTOCOL,
  2224. "'fetch' response too large (server '%s:%d'). Closing.",
  2225. conn->base_.address, conn->base_.port);
  2226. return -1;
  2227. case 0:
  2228. log_info(LD_HTTP,
  2229. "'fetch' response not all here, but we're at eof. Closing.");
  2230. return -1;
  2231. /* case 1, fall through */
  2232. }
  2233. if (parse_http_response(headers, &status_code, &date_header,
  2234. &compression, &reason) < 0) {
  2235. log_warn(LD_HTTP,"Unparseable headers (server '%s:%d'). Closing.",
  2236. conn->base_.address, conn->base_.port);
  2237. rv = -1;
  2238. goto done;
  2239. }
  2240. if (!reason) reason = tor_strdup("[no reason given]");
  2241. tor_log(LOG_DEBUG, LD_DIR,
  2242. "Received response from directory server '%s:%d': %d %s "
  2243. "(purpose: %d, response size: " U64_FORMAT
  2244. #ifdef MEASUREMENTS_21206
  2245. ", data cells received: %d, data cells sent: %d"
  2246. #endif
  2247. ", compression: %d)",
  2248. conn->base_.address, conn->base_.port, status_code,
  2249. escaped(reason), conn->base_.purpose,
  2250. U64_PRINTF_ARG(received_bytes),
  2251. #ifdef MEASUREMENTS_21206
  2252. conn->data_cells_received, conn->data_cells_sent,
  2253. #endif
  2254. compression);
  2255. if (conn->guard_state) {
  2256. /* we count the connection as successful once we can read from it. We do
  2257. * not, however, delay use of the circuit here, since it's just for a
  2258. * one-hop directory request. */
  2259. /* XXXXprop271 note that this will not do the right thing for other
  2260. * waiting circuits that would be triggered by this circuit becoming
  2261. * complete/usable. But that's ok, I think.
  2262. */
  2263. entry_guard_succeeded(&conn->guard_state);
  2264. circuit_guard_state_free(conn->guard_state);
  2265. conn->guard_state = NULL;
  2266. }
  2267. /* now check if it's got any hints for us about our IP address. */
  2268. if (conn->dirconn_direct) {
  2269. char *guess = http_get_header(headers, X_ADDRESS_HEADER);
  2270. if (guess) {
  2271. router_new_address_suggestion(guess, conn);
  2272. tor_free(guess);
  2273. }
  2274. }
  2275. if (date_header > 0) {
  2276. /* The date header was written very soon after we sent our request,
  2277. * so compute the skew as the difference between sending the request
  2278. * and the date header. (We used to check now-date_header, but that's
  2279. * inaccurate if we spend a lot of time downloading.)
  2280. */
  2281. apparent_skew = conn->base_.timestamp_lastwritten - date_header;
  2282. if (labs(apparent_skew)>ALLOW_DIRECTORY_TIME_SKEW) {
  2283. int trusted = router_digest_is_trusted_dir(conn->identity_digest);
  2284. clock_skew_warning(TO_CONN(conn), apparent_skew, trusted, LD_HTTP,
  2285. "directory", "DIRSERV");
  2286. skewed = 1; /* don't check the recommended-versions line */
  2287. } else {
  2288. log_debug(LD_HTTP, "Time on received directory is within tolerance; "
  2289. "we are %ld seconds skewed. (That's okay.)", apparent_skew);
  2290. }
  2291. }
  2292. (void) skewed; /* skewed isn't used yet. */
  2293. if (status_code == 503) {
  2294. routerstatus_t *rs;
  2295. dir_server_t *ds;
  2296. const char *id_digest = conn->identity_digest;
  2297. log_info(LD_DIR,"Received http status code %d (%s) from server "
  2298. "'%s:%d'. I'll try again soon.",
  2299. status_code, escaped(reason), conn->base_.address,
  2300. conn->base_.port);
  2301. time_t now = approx_time();
  2302. if ((rs = router_get_mutable_consensus_status_by_id(id_digest)))
  2303. rs->last_dir_503_at = now;
  2304. if ((ds = router_get_fallback_dirserver_by_digest(id_digest)))
  2305. ds->fake_status.last_dir_503_at = now;
  2306. rv = -1;
  2307. goto done;
  2308. }
  2309. if (dir_client_decompress_response_body(&body, &body_len,
  2310. conn, compression, anonymized_connection) < 0) {
  2311. rv = -1;
  2312. goto done;
  2313. }
  2314. response_handler_args_t args;
  2315. memset(&args, 0, sizeof(args));
  2316. args.status_code = status_code;
  2317. args.reason = reason;
  2318. args.body = body;
  2319. args.body_len = body_len;
  2320. args.headers = headers;
  2321. switch (conn->base_.purpose) {
  2322. case DIR_PURPOSE_FETCH_CONSENSUS:
  2323. rv = handle_response_fetch_consensus(conn, &args);
  2324. break;
  2325. case DIR_PURPOSE_FETCH_CERTIFICATE:
  2326. rv = handle_response_fetch_certificate(conn, &args);
  2327. break;
  2328. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  2329. rv = handle_response_fetch_status_vote(conn, &args);
  2330. break;
  2331. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  2332. rv = handle_response_fetch_detached_signatures(conn, &args);
  2333. break;
  2334. case DIR_PURPOSE_FETCH_SERVERDESC:
  2335. case DIR_PURPOSE_FETCH_EXTRAINFO:
  2336. rv = handle_response_fetch_desc(conn, &args);
  2337. break;
  2338. case DIR_PURPOSE_FETCH_MICRODESC:
  2339. rv = handle_response_fetch_microdesc(conn, &args);
  2340. break;
  2341. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  2342. rv = handle_response_fetch_renddesc_v2(conn, &args);
  2343. break;
  2344. case DIR_PURPOSE_UPLOAD_DIR:
  2345. rv = handle_response_upload_dir(conn, &args);
  2346. break;
  2347. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  2348. rv = handle_response_upload_signatures(conn, &args);
  2349. break;
  2350. case DIR_PURPOSE_UPLOAD_VOTE:
  2351. rv = handle_response_upload_vote(conn, &args);
  2352. break;
  2353. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  2354. rv = handle_response_upload_renddesc_v2(conn, &args);
  2355. break;
  2356. case DIR_PURPOSE_UPLOAD_HSDESC:
  2357. rv = handle_response_upload_hsdesc(conn, &args);
  2358. break;
  2359. case DIR_PURPOSE_FETCH_HSDESC:
  2360. rv = handle_response_fetch_hsdesc_v3(conn, &args);
  2361. break;
  2362. default:
  2363. tor_assert_nonfatal_unreached();
  2364. rv = -1;
  2365. break;
  2366. }
  2367. done:
  2368. tor_free(body);
  2369. tor_free(headers);
  2370. tor_free(reason);
  2371. return rv;
  2372. }
  2373. /**
  2374. * Handler function: processes a response to a request for a networkstatus
  2375. * consensus document by checking the consensus, storing it, and marking
  2376. * router requests as reachable.
  2377. **/
  2378. static int
  2379. handle_response_fetch_consensus(dir_connection_t *conn,
  2380. const response_handler_args_t *args)
  2381. {
  2382. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS);
  2383. const int status_code = args->status_code;
  2384. const char *body = args->body;
  2385. const size_t body_len = args->body_len;
  2386. const char *reason = args->reason;
  2387. const time_t now = approx_time();
  2388. const char *consensus;
  2389. char *new_consensus = NULL;
  2390. const char *sourcename;
  2391. int r;
  2392. const char *flavname = conn->requested_resource;
  2393. if (status_code != 200) {
  2394. int severity = (status_code == 304) ? LOG_INFO : LOG_WARN;
  2395. tor_log(severity, LD_DIR,
  2396. "Received http status code %d (%s) from server "
  2397. "'%s:%d' while fetching consensus directory.",
  2398. status_code, escaped(reason), conn->base_.address,
  2399. conn->base_.port);
  2400. networkstatus_consensus_download_failed(status_code, flavname);
  2401. return -1;
  2402. }
  2403. if (looks_like_a_consensus_diff(body, body_len)) {
  2404. /* First find our previous consensus. Maybe it's in ram, maybe not. */
  2405. cached_dir_t *cd = dirserv_get_consensus(flavname);
  2406. const char *consensus_body;
  2407. char *owned_consensus = NULL;
  2408. if (cd) {
  2409. consensus_body = cd->dir;
  2410. } else {
  2411. owned_consensus = networkstatus_read_cached_consensus(flavname);
  2412. consensus_body = owned_consensus;
  2413. }
  2414. if (!consensus_body) {
  2415. log_warn(LD_DIR, "Received a consensus diff, but we can't find "
  2416. "any %s-flavored consensus in our current cache.",flavname);
  2417. networkstatus_consensus_download_failed(0, flavname);
  2418. // XXXX if this happens too much, see below
  2419. return -1;
  2420. }
  2421. new_consensus = consensus_diff_apply(consensus_body, body);
  2422. tor_free(owned_consensus);
  2423. if (new_consensus == NULL) {
  2424. log_warn(LD_DIR, "Could not apply consensus diff received from server "
  2425. "'%s:%d'", conn->base_.address, conn->base_.port);
  2426. // XXXX If this happens too many times, we should maybe not use
  2427. // XXXX this directory for diffs any more?
  2428. networkstatus_consensus_download_failed(0, flavname);
  2429. return -1;
  2430. }
  2431. log_info(LD_DIR, "Applied consensus diff (size %d) from server "
  2432. "'%s:%d', resulting in a new consensus document (size %d).",
  2433. (int)body_len, conn->base_.address, conn->base_.port,
  2434. (int)strlen(new_consensus));
  2435. consensus = new_consensus;
  2436. sourcename = "generated based on a diff";
  2437. } else {
  2438. log_info(LD_DIR,"Received consensus directory (body size %d) from server "
  2439. "'%s:%d'", (int)body_len, conn->base_.address, conn->base_.port);
  2440. consensus = body;
  2441. sourcename = "downloaded";
  2442. }
  2443. if ((r=networkstatus_set_current_consensus(consensus, flavname, 0,
  2444. conn->identity_digest))<0) {
  2445. log_fn(r<-1?LOG_WARN:LOG_INFO, LD_DIR,
  2446. "Unable to load %s consensus directory %s from "
  2447. "server '%s:%d'. I'll try again soon.",
  2448. flavname, sourcename, conn->base_.address, conn->base_.port);
  2449. networkstatus_consensus_download_failed(0, flavname);
  2450. tor_free(new_consensus);
  2451. return -1;
  2452. }
  2453. /* If we launched other fetches for this consensus, cancel them. */
  2454. connection_dir_close_consensus_fetches(conn, flavname);
  2455. /* launches router downloads as needed */
  2456. routers_update_all_from_networkstatus(now, 3);
  2457. update_microdescs_from_networkstatus(now);
  2458. update_microdesc_downloads(now);
  2459. directory_info_has_arrived(now, 0, 0);
  2460. if (authdir_mode_v3(get_options())) {
  2461. sr_act_post_consensus(
  2462. networkstatus_get_latest_consensus_by_flavor(FLAV_NS));
  2463. }
  2464. log_info(LD_DIR, "Successfully loaded consensus.");
  2465. tor_free(new_consensus);
  2466. return 0;
  2467. }
  2468. /**
  2469. * Handler function: processes a response to a request for one or more
  2470. * authority certificates
  2471. **/
  2472. static int
  2473. handle_response_fetch_certificate(dir_connection_t *conn,
  2474. const response_handler_args_t *args)
  2475. {
  2476. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE);
  2477. const int status_code = args->status_code;
  2478. const char *reason = args->reason;
  2479. const char *body = args->body;
  2480. const size_t body_len = args->body_len;
  2481. if (status_code != 200) {
  2482. log_warn(LD_DIR,
  2483. "Received http status code %d (%s) from server "
  2484. "'%s:%d' while fetching \"/tor/keys/%s\".",
  2485. status_code, escaped(reason), conn->base_.address,
  2486. conn->base_.port, conn->requested_resource);
  2487. connection_dir_download_cert_failed(conn, status_code);
  2488. return -1;
  2489. }
  2490. log_info(LD_DIR,"Received authority certificates (body size %d) from "
  2491. "server '%s:%d'",
  2492. (int)body_len, conn->base_.address, conn->base_.port);
  2493. /*
  2494. * Tell trusted_dirs_load_certs_from_string() whether it was by fp
  2495. * or fp-sk pair.
  2496. */
  2497. int src_code = -1;
  2498. if (!strcmpstart(conn->requested_resource, "fp/")) {
  2499. src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST;
  2500. } else if (!strcmpstart(conn->requested_resource, "fp-sk/")) {
  2501. src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST;
  2502. }
  2503. if (src_code != -1) {
  2504. if (trusted_dirs_load_certs_from_string(body, src_code, 1,
  2505. conn->identity_digest)<0) {
  2506. log_warn(LD_DIR, "Unable to parse fetched certificates");
  2507. /* if we fetched more than one and only some failed, the successful
  2508. * ones got flushed to disk so it's safe to call this on them */
  2509. connection_dir_download_cert_failed(conn, status_code);
  2510. } else {
  2511. time_t now = approx_time();
  2512. directory_info_has_arrived(now, 0, 0);
  2513. log_info(LD_DIR, "Successfully loaded certificates from fetch.");
  2514. }
  2515. } else {
  2516. log_warn(LD_DIR,
  2517. "Couldn't figure out what to do with fetched certificates for "
  2518. "unknown resource %s",
  2519. conn->requested_resource);
  2520. connection_dir_download_cert_failed(conn, status_code);
  2521. }
  2522. return 0;
  2523. }
  2524. /**
  2525. * Handler function: processes a response to a request for an authority's
  2526. * current networkstatus vote.
  2527. **/
  2528. static int
  2529. handle_response_fetch_status_vote(dir_connection_t *conn,
  2530. const response_handler_args_t *args)
  2531. {
  2532. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE);
  2533. const int status_code = args->status_code;
  2534. const char *reason = args->reason;
  2535. const char *body = args->body;
  2536. const size_t body_len = args->body_len;
  2537. const char *msg;
  2538. int st;
  2539. log_info(LD_DIR,"Got votes (body size %d) from server %s:%d",
  2540. (int)body_len, conn->base_.address, conn->base_.port);
  2541. if (status_code != 200) {
  2542. log_warn(LD_DIR,
  2543. "Received http status code %d (%s) from server "
  2544. "'%s:%d' while fetching \"/tor/status-vote/next/%s.z\".",
  2545. status_code, escaped(reason), conn->base_.address,
  2546. conn->base_.port, conn->requested_resource);
  2547. return -1;
  2548. }
  2549. dirvote_add_vote(body, &msg, &st);
  2550. if (st > 299) {
  2551. log_warn(LD_DIR, "Error adding retrieved vote: %s", msg);
  2552. } else {
  2553. log_info(LD_DIR, "Added vote(s) successfully [msg: %s]", msg);
  2554. }
  2555. return 0;
  2556. }
  2557. /**
  2558. * Handler function: processes a response to a request for the signatures
  2559. * that an authority knows about on a given consensus.
  2560. **/
  2561. static int
  2562. handle_response_fetch_detached_signatures(dir_connection_t *conn,
  2563. const response_handler_args_t *args)
  2564. {
  2565. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES);
  2566. const int status_code = args->status_code;
  2567. const char *reason = args->reason;
  2568. const char *body = args->body;
  2569. const size_t body_len = args->body_len;
  2570. const char *msg = NULL;
  2571. log_info(LD_DIR,"Got detached signatures (body size %d) from server %s:%d",
  2572. (int)body_len, conn->base_.address, conn->base_.port);
  2573. if (status_code != 200) {
  2574. log_warn(LD_DIR,
  2575. "Received http status code %d (%s) from server '%s:%d' while fetching "
  2576. "\"/tor/status-vote/next/consensus-signatures.z\".",
  2577. status_code, escaped(reason), conn->base_.address,
  2578. conn->base_.port);
  2579. return -1;
  2580. }
  2581. if (dirvote_add_signatures(body, conn->base_.address, &msg)<0) {
  2582. log_warn(LD_DIR, "Problem adding detached signatures from %s:%d: %s",
  2583. conn->base_.address, conn->base_.port, msg?msg:"???");
  2584. }
  2585. return 0;
  2586. }
  2587. /**
  2588. * Handler function: processes a response to a request for a group of server
  2589. * descriptors or an extrainfo documents.
  2590. **/
  2591. static int
  2592. handle_response_fetch_desc(dir_connection_t *conn,
  2593. const response_handler_args_t *args)
  2594. {
  2595. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  2596. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO);
  2597. const int status_code = args->status_code;
  2598. const char *reason = args->reason;
  2599. const char *body = args->body;
  2600. const size_t body_len = args->body_len;
  2601. int was_ei = conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO;
  2602. smartlist_t *which = NULL;
  2603. int n_asked_for = 0;
  2604. int descriptor_digests = conn->requested_resource &&
  2605. !strcmpstart(conn->requested_resource,"d/");
  2606. log_info(LD_DIR,"Received %s (body size %d) from server '%s:%d'",
  2607. was_ei ? "extra server info" : "server info",
  2608. (int)body_len, conn->base_.address, conn->base_.port);
  2609. if (conn->requested_resource &&
  2610. (!strcmpstart(conn->requested_resource,"d/") ||
  2611. !strcmpstart(conn->requested_resource,"fp/"))) {
  2612. which = smartlist_new();
  2613. dir_split_resource_into_fingerprints(conn->requested_resource +
  2614. (descriptor_digests ? 2 : 3),
  2615. which, NULL, 0);
  2616. n_asked_for = smartlist_len(which);
  2617. }
  2618. if (status_code != 200) {
  2619. int dir_okay = status_code == 404 ||
  2620. (status_code == 400 && !strcmp(reason, "Servers unavailable."));
  2621. /* 404 means that it didn't have them; no big deal.
  2622. * Older (pre-0.1.1.8) servers said 400 Servers unavailable instead. */
  2623. log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
  2624. "Received http status code %d (%s) from server '%s:%d' "
  2625. "while fetching \"/tor/server/%s\". I'll try again soon.",
  2626. status_code, escaped(reason), conn->base_.address,
  2627. conn->base_.port, conn->requested_resource);
  2628. if (!which) {
  2629. connection_dir_download_routerdesc_failed(conn);
  2630. } else {
  2631. dir_routerdesc_download_failed(which, status_code,
  2632. conn->router_purpose,
  2633. was_ei, descriptor_digests);
  2634. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2635. smartlist_free(which);
  2636. }
  2637. return dir_okay ? 0 : -1;
  2638. }
  2639. /* Learn the routers, assuming we requested by fingerprint or "all"
  2640. * or "authority".
  2641. *
  2642. * We use "authority" to fetch our own descriptor for
  2643. * testing, and to fetch bridge descriptors for bootstrapping. Ignore
  2644. * the output of "authority" requests unless we are using bridges,
  2645. * since otherwise they'll be the response from reachability tests,
  2646. * and we don't really want to add that to our routerlist. */
  2647. if (which || (conn->requested_resource &&
  2648. (!strcmpstart(conn->requested_resource, "all") ||
  2649. (!strcmpstart(conn->requested_resource, "authority") &&
  2650. get_options()->UseBridges)))) {
  2651. /* as we learn from them, we remove them from 'which' */
  2652. if (was_ei) {
  2653. router_load_extrainfo_from_string(body, NULL, SAVED_NOWHERE, which,
  2654. descriptor_digests);
  2655. } else {
  2656. //router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  2657. // descriptor_digests, conn->router_purpose);
  2658. if (load_downloaded_routers(body, which, descriptor_digests,
  2659. conn->router_purpose,
  2660. conn->base_.address)) {
  2661. time_t now = approx_time();
  2662. directory_info_has_arrived(now, 0, 0);
  2663. }
  2664. }
  2665. }
  2666. if (which) { /* mark remaining ones as failed */
  2667. log_info(LD_DIR, "Received %d/%d %s requested from %s:%d",
  2668. n_asked_for-smartlist_len(which), n_asked_for,
  2669. was_ei ? "extra-info documents" : "router descriptors",
  2670. conn->base_.address, (int)conn->base_.port);
  2671. if (smartlist_len(which)) {
  2672. dir_routerdesc_download_failed(which, status_code,
  2673. conn->router_purpose,
  2674. was_ei, descriptor_digests);
  2675. }
  2676. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2677. smartlist_free(which);
  2678. }
  2679. if (directory_conn_is_self_reachability_test(conn))
  2680. router_dirport_found_reachable();
  2681. return 0;
  2682. }
  2683. /**
  2684. * Handler function: processes a response to a request for a group of
  2685. * microdescriptors
  2686. **/
  2687. static int
  2688. handle_response_fetch_microdesc(dir_connection_t *conn,
  2689. const response_handler_args_t *args)
  2690. {
  2691. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  2692. const int status_code = args->status_code;
  2693. const char *reason = args->reason;
  2694. const char *body = args->body;
  2695. const size_t body_len = args->body_len;
  2696. smartlist_t *which = NULL;
  2697. log_info(LD_DIR,"Received answer to microdescriptor request (status %d, "
  2698. "body size %d) from server '%s:%d'",
  2699. status_code, (int)body_len, conn->base_.address,
  2700. conn->base_.port);
  2701. tor_assert(conn->requested_resource &&
  2702. !strcmpstart(conn->requested_resource, "d/"));
  2703. which = smartlist_new();
  2704. dir_split_resource_into_fingerprints(conn->requested_resource+2,
  2705. which, NULL,
  2706. DSR_DIGEST256|DSR_BASE64);
  2707. if (status_code != 200) {
  2708. log_info(LD_DIR, "Received status code %d (%s) from server "
  2709. "'%s:%d' while fetching \"/tor/micro/%s\". I'll try again "
  2710. "soon.",
  2711. status_code, escaped(reason), conn->base_.address,
  2712. (int)conn->base_.port, conn->requested_resource);
  2713. dir_microdesc_download_failed(which, status_code);
  2714. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2715. smartlist_free(which);
  2716. return 0;
  2717. } else {
  2718. smartlist_t *mds;
  2719. time_t now = approx_time();
  2720. mds = microdescs_add_to_cache(get_microdesc_cache(),
  2721. body, body+body_len, SAVED_NOWHERE, 0,
  2722. now, which);
  2723. if (smartlist_len(which)) {
  2724. /* Mark remaining ones as failed. */
  2725. dir_microdesc_download_failed(which, status_code);
  2726. }
  2727. if (mds && smartlist_len(mds)) {
  2728. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  2729. count_loading_descriptors_progress());
  2730. directory_info_has_arrived(now, 0, 1);
  2731. }
  2732. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2733. smartlist_free(which);
  2734. smartlist_free(mds);
  2735. }
  2736. return 0;
  2737. }
  2738. /**
  2739. * Handler function: processes a response to a POST request to upload our
  2740. * router descriptor.
  2741. **/
  2742. static int
  2743. handle_response_upload_dir(dir_connection_t *conn,
  2744. const response_handler_args_t *args)
  2745. {
  2746. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_DIR);
  2747. const int status_code = args->status_code;
  2748. const char *reason = args->reason;
  2749. const char *headers = args->headers;
  2750. switch (status_code) {
  2751. case 200: {
  2752. dir_server_t *ds =
  2753. router_get_trusteddirserver_by_digest(conn->identity_digest);
  2754. char *rejected_hdr = http_get_header(headers,
  2755. "X-Descriptor-Not-New: ");
  2756. if (rejected_hdr) {
  2757. if (!strcmp(rejected_hdr, "Yes")) {
  2758. log_info(LD_GENERAL,
  2759. "Authority '%s' declined our descriptor (not new)",
  2760. ds->nickname);
  2761. /* XXXX use this information; be sure to upload next one
  2762. * sooner. -NM */
  2763. /* XXXX++ On further thought, the task above implies that we're
  2764. * basing our regenerate-descriptor time on when we uploaded the
  2765. * last descriptor, not on the published time of the last
  2766. * descriptor. If those are different, that's a bad thing to
  2767. * do. -NM */
  2768. }
  2769. tor_free(rejected_hdr);
  2770. }
  2771. log_info(LD_GENERAL,"eof (status 200) after uploading server "
  2772. "descriptor: finished.");
  2773. control_event_server_status(
  2774. LOG_NOTICE, "ACCEPTED_SERVER_DESCRIPTOR DIRAUTH=%s:%d",
  2775. conn->base_.address, conn->base_.port);
  2776. ds->has_accepted_serverdesc = 1;
  2777. if (directories_have_accepted_server_descriptor())
  2778. control_event_server_status(LOG_NOTICE, "GOOD_SERVER_DESCRIPTOR");
  2779. }
  2780. break;
  2781. case 400:
  2782. log_warn(LD_GENERAL,"http status 400 (%s) response from "
  2783. "dirserver '%s:%d'. Please correct.",
  2784. escaped(reason), conn->base_.address, conn->base_.port);
  2785. control_event_server_status(LOG_WARN,
  2786. "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
  2787. conn->base_.address, conn->base_.port, escaped(reason));
  2788. break;
  2789. default:
  2790. log_warn(LD_GENERAL,
  2791. "HTTP status %d (%s) was unexpected while uploading "
  2792. "descriptor to server '%s:%d'. Possibly the server is "
  2793. "misconfigured?",
  2794. status_code, escaped(reason), conn->base_.address,
  2795. conn->base_.port);
  2796. break;
  2797. }
  2798. /* return 0 in all cases, since we don't want to mark any
  2799. * dirservers down just because they don't like us. */
  2800. return 0;
  2801. }
  2802. /**
  2803. * Handler function: processes a response to POST request to upload our
  2804. * own networkstatus vote.
  2805. **/
  2806. static int
  2807. handle_response_upload_vote(dir_connection_t *conn,
  2808. const response_handler_args_t *args)
  2809. {
  2810. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_VOTE);
  2811. const int status_code = args->status_code;
  2812. const char *reason = args->reason;
  2813. switch (status_code) {
  2814. case 200: {
  2815. log_notice(LD_DIR,"Uploaded a vote to dirserver %s:%d",
  2816. conn->base_.address, conn->base_.port);
  2817. }
  2818. break;
  2819. case 400:
  2820. log_warn(LD_DIR,"http status 400 (%s) response after uploading "
  2821. "vote to dirserver '%s:%d'. Please correct.",
  2822. escaped(reason), conn->base_.address, conn->base_.port);
  2823. break;
  2824. default:
  2825. log_warn(LD_GENERAL,
  2826. "HTTP status %d (%s) was unexpected while uploading "
  2827. "vote to server '%s:%d'.",
  2828. status_code, escaped(reason), conn->base_.address,
  2829. conn->base_.port);
  2830. break;
  2831. }
  2832. /* return 0 in all cases, since we don't want to mark any
  2833. * dirservers down just because they don't like us. */
  2834. return 0;
  2835. }
  2836. /**
  2837. * Handler function: processes a response to POST request to upload our
  2838. * view of the signatures on the current consensus.
  2839. **/
  2840. static int
  2841. handle_response_upload_signatures(dir_connection_t *conn,
  2842. const response_handler_args_t *args)
  2843. {
  2844. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_SIGNATURES);
  2845. const int status_code = args->status_code;
  2846. const char *reason = args->reason;
  2847. switch (status_code) {
  2848. case 200: {
  2849. log_notice(LD_DIR,"Uploaded signature(s) to dirserver %s:%d",
  2850. conn->base_.address, conn->base_.port);
  2851. }
  2852. break;
  2853. case 400:
  2854. log_warn(LD_DIR,"http status 400 (%s) response after uploading "
  2855. "signatures to dirserver '%s:%d'. Please correct.",
  2856. escaped(reason), conn->base_.address, conn->base_.port);
  2857. break;
  2858. default:
  2859. log_warn(LD_GENERAL,
  2860. "HTTP status %d (%s) was unexpected while uploading "
  2861. "signatures to server '%s:%d'.",
  2862. status_code, escaped(reason), conn->base_.address,
  2863. conn->base_.port);
  2864. break;
  2865. }
  2866. /* return 0 in all cases, since we don't want to mark any
  2867. * dirservers down just because they don't like us. */
  2868. return 0;
  2869. }
  2870. /**
  2871. * Handler function: processes a response to a request for a v3 hidden service
  2872. * descriptor.
  2873. **/
  2874. STATIC int
  2875. handle_response_fetch_hsdesc_v3(dir_connection_t *conn,
  2876. const response_handler_args_t *args)
  2877. {
  2878. const int status_code = args->status_code;
  2879. const char *reason = args->reason;
  2880. const char *body = args->body;
  2881. const size_t body_len = args->body_len;
  2882. tor_assert(conn->hs_ident);
  2883. log_info(LD_REND,"Received v3 hsdesc (body size %d, status %d (%s))",
  2884. (int)body_len, status_code, escaped(reason));
  2885. switch (status_code) {
  2886. case 200:
  2887. /* We got something: Try storing it in the cache. */
  2888. if (hs_cache_store_as_client(body, &conn->hs_ident->identity_pk) < 0) {
  2889. log_warn(LD_REND, "Failed to store hidden service descriptor");
  2890. } else {
  2891. log_info(LD_REND, "Stored hidden service descriptor successfully.");
  2892. TO_CONN(conn)->purpose = DIR_PURPOSE_HAS_FETCHED_HSDESC;
  2893. hs_client_desc_has_arrived(conn->hs_ident);
  2894. }
  2895. break;
  2896. case 404:
  2897. /* Not there. We'll retry when connection_about_to_close_connection()
  2898. * tries to clean this conn up. */
  2899. log_info(LD_REND, "Fetching hidden service v3 descriptor not found: "
  2900. "Retrying at another directory.");
  2901. /* TODO: Inform the control port */
  2902. break;
  2903. case 400:
  2904. log_warn(LD_REND, "Fetching v3 hidden service descriptor failed: "
  2905. "http status 400 (%s). Dirserver didn't like our "
  2906. "query? Retrying at another directory.",
  2907. escaped(reason));
  2908. break;
  2909. default:
  2910. log_warn(LD_REND, "Fetching v3 hidden service descriptor failed: "
  2911. "http status %d (%s) response unexpected from HSDir server "
  2912. "'%s:%d'. Retrying at another directory.",
  2913. status_code, escaped(reason), TO_CONN(conn)->address,
  2914. TO_CONN(conn)->port);
  2915. break;
  2916. }
  2917. return 0;
  2918. }
  2919. /**
  2920. * Handler function: processes a response to a request for a v2 hidden service
  2921. * descriptor.
  2922. **/
  2923. static int
  2924. handle_response_fetch_renddesc_v2(dir_connection_t *conn,
  2925. const response_handler_args_t *args)
  2926. {
  2927. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_RENDDESC_V2);
  2928. const int status_code = args->status_code;
  2929. const char *reason = args->reason;
  2930. const char *body = args->body;
  2931. const size_t body_len = args->body_len;
  2932. #define SEND_HS_DESC_FAILED_EVENT(reason) \
  2933. (control_event_hs_descriptor_failed(conn->rend_data, \
  2934. conn->identity_digest, \
  2935. reason))
  2936. #define SEND_HS_DESC_FAILED_CONTENT() \
  2937. (control_event_hs_descriptor_content( \
  2938. rend_data_get_address(conn->rend_data), \
  2939. conn->requested_resource, \
  2940. conn->identity_digest, \
  2941. NULL))
  2942. tor_assert(conn->rend_data);
  2943. log_info(LD_REND,"Received rendezvous descriptor (body size %d, status %d "
  2944. "(%s))",
  2945. (int)body_len, status_code, escaped(reason));
  2946. switch (status_code) {
  2947. case 200:
  2948. {
  2949. rend_cache_entry_t *entry = NULL;
  2950. if (rend_cache_store_v2_desc_as_client(body,
  2951. conn->requested_resource,
  2952. conn->rend_data, &entry) < 0) {
  2953. log_warn(LD_REND,"Fetching v2 rendezvous descriptor failed. "
  2954. "Retrying at another directory.");
  2955. /* We'll retry when connection_about_to_close_connection()
  2956. * cleans this dir conn up. */
  2957. SEND_HS_DESC_FAILED_EVENT("BAD_DESC");
  2958. SEND_HS_DESC_FAILED_CONTENT();
  2959. } else {
  2960. char service_id[REND_SERVICE_ID_LEN_BASE32 + 1];
  2961. /* Should never be NULL here if we found the descriptor. */
  2962. tor_assert(entry);
  2963. rend_get_service_id(entry->parsed->pk, service_id);
  2964. /* success. notify pending connections about this. */
  2965. log_info(LD_REND, "Successfully fetched v2 rendezvous "
  2966. "descriptor.");
  2967. control_event_hs_descriptor_received(service_id,
  2968. conn->rend_data,
  2969. conn->identity_digest);
  2970. control_event_hs_descriptor_content(service_id,
  2971. conn->requested_resource,
  2972. conn->identity_digest,
  2973. body);
  2974. conn->base_.purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2;
  2975. rend_client_desc_trynow(service_id);
  2976. memwipe(service_id, 0, sizeof(service_id));
  2977. }
  2978. break;
  2979. }
  2980. case 404:
  2981. /* Not there. We'll retry when
  2982. * connection_about_to_close_connection() cleans this conn up. */
  2983. log_info(LD_REND,"Fetching v2 rendezvous descriptor failed: "
  2984. "Retrying at another directory.");
  2985. SEND_HS_DESC_FAILED_EVENT("NOT_FOUND");
  2986. SEND_HS_DESC_FAILED_CONTENT();
  2987. break;
  2988. case 400:
  2989. log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
  2990. "http status 400 (%s). Dirserver didn't like our "
  2991. "v2 rendezvous query? Retrying at another directory.",
  2992. escaped(reason));
  2993. SEND_HS_DESC_FAILED_EVENT("QUERY_REJECTED");
  2994. SEND_HS_DESC_FAILED_CONTENT();
  2995. break;
  2996. default:
  2997. log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
  2998. "http status %d (%s) response unexpected while "
  2999. "fetching v2 hidden service descriptor (server '%s:%d'). "
  3000. "Retrying at another directory.",
  3001. status_code, escaped(reason), conn->base_.address,
  3002. conn->base_.port);
  3003. SEND_HS_DESC_FAILED_EVENT("UNEXPECTED");
  3004. SEND_HS_DESC_FAILED_CONTENT();
  3005. break;
  3006. }
  3007. return 0;
  3008. }
  3009. /**
  3010. * Handler function: processes a response to a POST request to upload a v2
  3011. * hidden service descriptor.
  3012. **/
  3013. static int
  3014. handle_response_upload_renddesc_v2(dir_connection_t *conn,
  3015. const response_handler_args_t *args)
  3016. {
  3017. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2);
  3018. const int status_code = args->status_code;
  3019. const char *reason = args->reason;
  3020. #define SEND_HS_DESC_UPLOAD_FAILED_EVENT(reason) \
  3021. (control_event_hs_descriptor_upload_failed( \
  3022. conn->identity_digest, \
  3023. rend_data_get_address(conn->rend_data), \
  3024. reason))
  3025. log_info(LD_REND,"Uploaded rendezvous descriptor (status %d "
  3026. "(%s))",
  3027. status_code, escaped(reason));
  3028. /* Without the rend data, we'll have a problem identifying what has been
  3029. * uploaded for which service. */
  3030. tor_assert(conn->rend_data);
  3031. switch (status_code) {
  3032. case 200:
  3033. log_info(LD_REND,
  3034. "Uploading rendezvous descriptor: finished with status "
  3035. "200 (%s)", escaped(reason));
  3036. control_event_hs_descriptor_uploaded(conn->identity_digest,
  3037. rend_data_get_address(conn->rend_data));
  3038. rend_service_desc_has_uploaded(conn->rend_data);
  3039. break;
  3040. case 400:
  3041. log_warn(LD_REND,"http status 400 (%s) response from dirserver "
  3042. "'%s:%d'. Malformed rendezvous descriptor?",
  3043. escaped(reason), conn->base_.address, conn->base_.port);
  3044. SEND_HS_DESC_UPLOAD_FAILED_EVENT("UPLOAD_REJECTED");
  3045. break;
  3046. default:
  3047. log_warn(LD_REND,"http status %d (%s) response unexpected (server "
  3048. "'%s:%d').",
  3049. status_code, escaped(reason), conn->base_.address,
  3050. conn->base_.port);
  3051. SEND_HS_DESC_UPLOAD_FAILED_EVENT("UNEXPECTED");
  3052. break;
  3053. }
  3054. return 0;
  3055. }
  3056. /**
  3057. * Handler function: processes a response to a POST request to upload an
  3058. * hidden service descriptor.
  3059. **/
  3060. static int
  3061. handle_response_upload_hsdesc(dir_connection_t *conn,
  3062. const response_handler_args_t *args)
  3063. {
  3064. const int status_code = args->status_code;
  3065. const char *reason = args->reason;
  3066. tor_assert(conn);
  3067. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_HSDESC);
  3068. log_info(LD_REND, "Uploaded hidden service descriptor (status %d "
  3069. "(%s))",
  3070. status_code, escaped(reason));
  3071. /* For this directory response, it MUST have an hidden service identifier on
  3072. * this connection. */
  3073. tor_assert(conn->hs_ident);
  3074. switch (status_code) {
  3075. case 200:
  3076. log_info(LD_REND, "Uploading hidden service descriptor: "
  3077. "finished with status 200 (%s)", escaped(reason));
  3078. /* XXX: Trigger control event. */
  3079. break;
  3080. case 400:
  3081. log_warn(LD_REND, "Uploading hidden service descriptor: http "
  3082. "status 400 (%s) response from dirserver "
  3083. "'%s:%d'. Malformed hidden service descriptor?",
  3084. escaped(reason), conn->base_.address, conn->base_.port);
  3085. /* XXX: Trigger control event. */
  3086. break;
  3087. default:
  3088. log_warn(LD_REND, "Uploading hidden service descriptor: http "
  3089. "status %d (%s) response unexpected (server "
  3090. "'%s:%d').",
  3091. status_code, escaped(reason), conn->base_.address,
  3092. conn->base_.port);
  3093. /* XXX: Trigger control event. */
  3094. break;
  3095. }
  3096. return 0;
  3097. }
  3098. /** Called when a directory connection reaches EOF. */
  3099. int
  3100. connection_dir_reached_eof(dir_connection_t *conn)
  3101. {
  3102. int retval;
  3103. if (conn->base_.state != DIR_CONN_STATE_CLIENT_READING) {
  3104. log_info(LD_HTTP,"conn reached eof, not reading. [state=%d] Closing.",
  3105. conn->base_.state);
  3106. connection_close_immediate(TO_CONN(conn)); /* error: give up on flushing */
  3107. connection_mark_for_close(TO_CONN(conn));
  3108. return -1;
  3109. }
  3110. retval = connection_dir_client_reached_eof(conn);
  3111. if (retval == 0) /* success */
  3112. conn->base_.state = DIR_CONN_STATE_CLIENT_FINISHED;
  3113. connection_mark_for_close(TO_CONN(conn));
  3114. return retval;
  3115. }
  3116. /** If any directory object is arriving, and it's over 10MB large, we're
  3117. * getting DoS'd. (As of 0.1.2.x, raw directories are about 1MB, and we never
  3118. * ask for more than 96 router descriptors at a time.)
  3119. */
  3120. #define MAX_DIRECTORY_OBJECT_SIZE (10*(1<<20))
  3121. #define MAX_VOTE_DL_SIZE (MAX_DIRECTORY_OBJECT_SIZE * 5)
  3122. /** Read handler for directory connections. (That's connections <em>to</em>
  3123. * directory servers and connections <em>at</em> directory servers.)
  3124. */
  3125. int
  3126. connection_dir_process_inbuf(dir_connection_t *conn)
  3127. {
  3128. size_t max_size;
  3129. tor_assert(conn);
  3130. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  3131. /* Directory clients write, then read data until they receive EOF;
  3132. * directory servers read data until they get an HTTP command, then
  3133. * write their response (when it's finished flushing, they mark for
  3134. * close).
  3135. */
  3136. /* If we're on the dirserver side, look for a command. */
  3137. if (conn->base_.state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  3138. if (directory_handle_command(conn) < 0) {
  3139. connection_mark_for_close(TO_CONN(conn));
  3140. return -1;
  3141. }
  3142. return 0;
  3143. }
  3144. max_size =
  3145. (TO_CONN(conn)->purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) ?
  3146. MAX_VOTE_DL_SIZE : MAX_DIRECTORY_OBJECT_SIZE;
  3147. if (connection_get_inbuf_len(TO_CONN(conn)) > max_size) {
  3148. log_warn(LD_HTTP,
  3149. "Too much data received from directory connection (%s): "
  3150. "denial of service attempt, or you need to upgrade?",
  3151. conn->base_.address);
  3152. connection_mark_for_close(TO_CONN(conn));
  3153. return -1;
  3154. }
  3155. if (!conn->base_.inbuf_reached_eof)
  3156. log_debug(LD_HTTP,"Got data, not eof. Leaving on inbuf.");
  3157. return 0;
  3158. }
  3159. /** We are closing a dir connection: If <b>dir_conn</b> is a dir connection
  3160. * that tried to fetch an HS descriptor, check if it successfuly fetched it,
  3161. * or if we need to try again. */
  3162. static void
  3163. refetch_hsdesc_if_needed(dir_connection_t *dir_conn)
  3164. {
  3165. connection_t *conn = TO_CONN(dir_conn);
  3166. /* If we were trying to fetch a v2 rend desc and did not succeed, retry as
  3167. * needed. (If a fetch is successful, the connection state is changed to
  3168. * DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2 or DIR_PURPOSE_HAS_FETCHED_HSDESC to
  3169. * mark that refetching is unnecessary.) */
  3170. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 &&
  3171. dir_conn->rend_data &&
  3172. rend_valid_v2_service_id(
  3173. rend_data_get_address(dir_conn->rend_data))) {
  3174. rend_client_refetch_v2_renddesc(dir_conn->rend_data);
  3175. }
  3176. /* Check for v3 rend desc fetch */
  3177. if (conn->purpose == DIR_PURPOSE_FETCH_HSDESC &&
  3178. dir_conn->hs_ident &&
  3179. !ed25519_public_key_is_zero(&dir_conn->hs_ident->identity_pk)) {
  3180. hs_client_refetch_hsdesc(&dir_conn->hs_ident->identity_pk);
  3181. }
  3182. }
  3183. /** Called when we're about to finally unlink and free a directory connection:
  3184. * perform necessary accounting and cleanup */
  3185. void
  3186. connection_dir_about_to_close(dir_connection_t *dir_conn)
  3187. {
  3188. connection_t *conn = TO_CONN(dir_conn);
  3189. if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
  3190. /* It's a directory connection and connecting or fetching
  3191. * failed: forget about this router, and maybe try again. */
  3192. connection_dir_request_failed(dir_conn);
  3193. }
  3194. refetch_hsdesc_if_needed(dir_conn);
  3195. }
  3196. /** Create an http response for the client <b>conn</b> out of
  3197. * <b>status</b> and <b>reason_phrase</b>. Write it to <b>conn</b>.
  3198. */
  3199. static void
  3200. write_short_http_response(dir_connection_t *conn, int status,
  3201. const char *reason_phrase)
  3202. {
  3203. char *buf = NULL;
  3204. char *datestring = NULL;
  3205. IF_BUG_ONCE(!reason_phrase) { /* bullet-proofing */
  3206. reason_phrase = "unspecified";
  3207. }
  3208. if (server_mode(get_options())) {
  3209. /* include the Date: header, but only if we're a relay or bridge */
  3210. char datebuf[RFC1123_TIME_LEN+1];
  3211. format_rfc1123_time(datebuf, time(NULL));
  3212. tor_asprintf(&datestring, "Date: %s\r\n", datebuf);
  3213. }
  3214. tor_asprintf(&buf, "HTTP/1.0 %d %s\r\n%s\r\n",
  3215. status, reason_phrase, datestring?datestring:"");
  3216. log_debug(LD_DIRSERV,"Wrote status 'HTTP/1.0 %d %s'", status, reason_phrase);
  3217. connection_buf_add(buf, strlen(buf), TO_CONN(conn));
  3218. tor_free(datestring);
  3219. tor_free(buf);
  3220. }
  3221. /** Write the header for an HTTP/1.0 response onto <b>conn</b>-\>outbuf,
  3222. * with <b>type</b> as the Content-Type.
  3223. *
  3224. * If <b>length</b> is nonnegative, it is the Content-Length.
  3225. * If <b>encoding</b> is provided, it is the Content-Encoding.
  3226. * If <b>cache_lifetime</b> is greater than 0, the content may be cached for
  3227. * up to cache_lifetime seconds. Otherwise, the content may not be cached. */
  3228. static void
  3229. write_http_response_header_impl(dir_connection_t *conn, ssize_t length,
  3230. const char *type, const char *encoding,
  3231. const char *extra_headers,
  3232. long cache_lifetime)
  3233. {
  3234. char date[RFC1123_TIME_LEN+1];
  3235. char tmp[1024];
  3236. char *cp;
  3237. time_t now = time(NULL);
  3238. tor_assert(conn);
  3239. format_rfc1123_time(date, now);
  3240. cp = tmp;
  3241. tor_snprintf(cp, sizeof(tmp),
  3242. "HTTP/1.0 200 OK\r\nDate: %s\r\n",
  3243. date);
  3244. cp += strlen(tmp);
  3245. if (type) {
  3246. tor_snprintf(cp, sizeof(tmp)-(cp-tmp), "Content-Type: %s\r\n", type);
  3247. cp += strlen(cp);
  3248. }
  3249. if (!is_local_addr(&conn->base_.addr)) {
  3250. /* Don't report the source address for a nearby/private connection.
  3251. * Otherwise we tend to mis-report in cases where incoming ports are
  3252. * being forwarded to a Tor server running behind the firewall. */
  3253. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  3254. X_ADDRESS_HEADER "%s\r\n", conn->base_.address);
  3255. cp += strlen(cp);
  3256. }
  3257. if (encoding) {
  3258. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  3259. "Content-Encoding: %s\r\n", encoding);
  3260. cp += strlen(cp);
  3261. }
  3262. if (length >= 0) {
  3263. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  3264. "Content-Length: %ld\r\n", (long)length);
  3265. cp += strlen(cp);
  3266. }
  3267. if (cache_lifetime > 0) {
  3268. char expbuf[RFC1123_TIME_LEN+1];
  3269. format_rfc1123_time(expbuf, (time_t)(now + cache_lifetime));
  3270. /* We could say 'Cache-control: max-age=%d' here if we start doing
  3271. * http/1.1 */
  3272. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  3273. "Expires: %s\r\n", expbuf);
  3274. cp += strlen(cp);
  3275. } else if (cache_lifetime == 0) {
  3276. /* We could say 'Cache-control: no-cache' here if we start doing
  3277. * http/1.1 */
  3278. strlcpy(cp, "Pragma: no-cache\r\n", sizeof(tmp)-(cp-tmp));
  3279. cp += strlen(cp);
  3280. }
  3281. if (extra_headers) {
  3282. strlcpy(cp, extra_headers, sizeof(tmp)-(cp-tmp));
  3283. cp += strlen(cp);
  3284. }
  3285. if (sizeof(tmp)-(cp-tmp) > 3)
  3286. memcpy(cp, "\r\n", 3);
  3287. else
  3288. tor_assert(0);
  3289. connection_buf_add(tmp, strlen(tmp), TO_CONN(conn));
  3290. }
  3291. /** As write_http_response_header_impl, but sets encoding and content-typed
  3292. * based on whether the response will be <b>compressed</b> or not. */
  3293. static void
  3294. write_http_response_headers(dir_connection_t *conn, ssize_t length,
  3295. compress_method_t method,
  3296. const char *extra_headers, long cache_lifetime)
  3297. {
  3298. const char *methodname = compression_method_get_name(method);
  3299. const char *doctype;
  3300. if (method == NO_METHOD)
  3301. doctype = "text/plain";
  3302. else
  3303. doctype = "application/octet-stream";
  3304. write_http_response_header_impl(conn, length,
  3305. doctype,
  3306. methodname,
  3307. extra_headers,
  3308. cache_lifetime);
  3309. }
  3310. /** As write_http_response_headers, but assumes extra_headers is NULL */
  3311. static void
  3312. write_http_response_header(dir_connection_t *conn, ssize_t length,
  3313. compress_method_t method,
  3314. long cache_lifetime)
  3315. {
  3316. write_http_response_headers(conn, length, method, NULL, cache_lifetime);
  3317. }
  3318. /** Array of compression methods to use (if supported) for serving
  3319. * precompressed data, ordered from best to worst. */
  3320. static compress_method_t srv_meth_pref_precompressed[] = {
  3321. LZMA_METHOD,
  3322. ZSTD_METHOD,
  3323. ZLIB_METHOD,
  3324. GZIP_METHOD,
  3325. NO_METHOD
  3326. };
  3327. /** Array of compression methods to use (if supported) for serving
  3328. * streamed data, ordered from best to worst. */
  3329. static compress_method_t srv_meth_pref_streaming_compression[] = {
  3330. ZSTD_METHOD,
  3331. ZLIB_METHOD,
  3332. GZIP_METHOD,
  3333. NO_METHOD
  3334. };
  3335. /** Array of allowed compression methods to use (if supported) when receiving a
  3336. * response from a request that was required to be anonymous. */
  3337. static compress_method_t client_meth_allowed_anonymous_compression[] = {
  3338. ZLIB_METHOD,
  3339. GZIP_METHOD,
  3340. NO_METHOD
  3341. };
  3342. /** Parse the compression methods listed in an Accept-Encoding header <b>h</b>,
  3343. * and convert them to a bitfield where compression method x is supported if
  3344. * and only if 1 &lt;&lt; x is set in the bitfield. */
  3345. STATIC unsigned
  3346. parse_accept_encoding_header(const char *h)
  3347. {
  3348. unsigned result = (1u << NO_METHOD);
  3349. smartlist_t *methods = smartlist_new();
  3350. smartlist_split_string(methods, h, ",",
  3351. SPLIT_SKIP_SPACE|SPLIT_STRIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3352. SMARTLIST_FOREACH_BEGIN(methods, const char *, m) {
  3353. compress_method_t method = compression_method_get_by_name(m);
  3354. if (method != UNKNOWN_METHOD) {
  3355. tor_assert(((unsigned)method) < 8*sizeof(unsigned));
  3356. result |= (1u << method);
  3357. }
  3358. } SMARTLIST_FOREACH_END(m);
  3359. SMARTLIST_FOREACH_BEGIN(methods, char *, m) {
  3360. tor_free(m);
  3361. } SMARTLIST_FOREACH_END(m);
  3362. smartlist_free(methods);
  3363. return result;
  3364. }
  3365. /** Array of compression methods to use (if supported) for requesting
  3366. * compressed data, ordered from best to worst. */
  3367. static compress_method_t client_meth_pref[] = {
  3368. LZMA_METHOD,
  3369. ZSTD_METHOD,
  3370. ZLIB_METHOD,
  3371. GZIP_METHOD,
  3372. NO_METHOD
  3373. };
  3374. /** Return a newly allocated string containing a comma separated list of
  3375. * supported encodings. */
  3376. STATIC char *
  3377. accept_encoding_header(void)
  3378. {
  3379. smartlist_t *methods = smartlist_new();
  3380. char *header = NULL;
  3381. compress_method_t method;
  3382. unsigned i;
  3383. for (i = 0; i < ARRAY_LENGTH(client_meth_pref); ++i) {
  3384. method = client_meth_pref[i];
  3385. if (tor_compress_supports_method(method))
  3386. smartlist_add(methods, (char *)compression_method_get_name(method));
  3387. }
  3388. header = smartlist_join_strings(methods, ", ", 0, NULL);
  3389. smartlist_free(methods);
  3390. return header;
  3391. }
  3392. /** Decide whether a client would accept the consensus we have.
  3393. *
  3394. * Clients can say they only want a consensus if it's signed by more
  3395. * than half the authorities in a list. They pass this list in
  3396. * the url as "...consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>".
  3397. *
  3398. * <b>fpr</b> may be an abbreviated fingerprint, i.e. only a left substring
  3399. * of the full authority identity digest. (Only strings of even length,
  3400. * i.e. encodings of full bytes, are handled correctly. In the case
  3401. * of an odd number of hex digits the last one is silently ignored.)
  3402. *
  3403. * Returns 1 if more than half of the requested authorities signed the
  3404. * consensus, 0 otherwise.
  3405. */
  3406. int
  3407. client_likes_consensus(const struct consensus_cache_entry_t *ent,
  3408. const char *want_url)
  3409. {
  3410. smartlist_t *voters = smartlist_new();
  3411. int need_at_least;
  3412. int have = 0;
  3413. if (consensus_cache_entry_get_voter_id_digests(ent, voters) != 0) {
  3414. return 1; // We don't know the voters; assume the client won't mind. */
  3415. }
  3416. smartlist_t *want_authorities = smartlist_new();
  3417. dir_split_resource_into_fingerprints(want_url, want_authorities, NULL, 0);
  3418. need_at_least = smartlist_len(want_authorities)/2+1;
  3419. SMARTLIST_FOREACH_BEGIN(want_authorities, const char *, want_digest) {
  3420. SMARTLIST_FOREACH_BEGIN(voters, const char *, digest) {
  3421. if (!strcasecmpstart(digest, want_digest)) {
  3422. have++;
  3423. break;
  3424. };
  3425. } SMARTLIST_FOREACH_END(digest);
  3426. /* early exit, if we already have enough */
  3427. if (have >= need_at_least)
  3428. break;
  3429. } SMARTLIST_FOREACH_END(want_digest);
  3430. SMARTLIST_FOREACH(want_authorities, char *, d, tor_free(d));
  3431. smartlist_free(want_authorities);
  3432. SMARTLIST_FOREACH(voters, char *, cp, tor_free(cp));
  3433. smartlist_free(voters);
  3434. return (have >= need_at_least);
  3435. }
  3436. /** Return the compression level we should use for sending a compressed
  3437. * response of size <b>n_bytes</b>. */
  3438. STATIC compression_level_t
  3439. choose_compression_level(ssize_t n_bytes)
  3440. {
  3441. if (! have_been_under_memory_pressure()) {
  3442. return HIGH_COMPRESSION; /* we have plenty of RAM. */
  3443. } else if (n_bytes < 0) {
  3444. return HIGH_COMPRESSION; /* unknown; might be big. */
  3445. } else if (n_bytes < 1024) {
  3446. return LOW_COMPRESSION;
  3447. } else if (n_bytes < 2048) {
  3448. return MEDIUM_COMPRESSION;
  3449. } else {
  3450. return HIGH_COMPRESSION;
  3451. }
  3452. }
  3453. /** Information passed to handle a GET request. */
  3454. typedef struct get_handler_args_t {
  3455. /** Bitmask of compression methods that the client said (or implied) it
  3456. * supported. */
  3457. unsigned compression_supported;
  3458. /** If nonzero, the time included an if-modified-since header with this
  3459. * value. */
  3460. time_t if_modified_since;
  3461. /** String containing the requested URL or resource. */
  3462. const char *url;
  3463. /** String containing the HTTP headers */
  3464. const char *headers;
  3465. } get_handler_args_t;
  3466. /** Entry for handling an HTTP GET request.
  3467. *
  3468. * This entry matches a request if "string" is equal to the requested
  3469. * resource, or if "is_prefix" is true and "string" is a prefix of the
  3470. * requested resource.
  3471. *
  3472. * The 'handler' function is called to handle the request. It receives
  3473. * an arguments structure, and must return 0 on success or -1 if we should
  3474. * close the connection.
  3475. **/
  3476. typedef struct url_table_ent_s {
  3477. const char *string;
  3478. int is_prefix;
  3479. int (*handler)(dir_connection_t *conn, const get_handler_args_t *args);
  3480. } url_table_ent_t;
  3481. static int handle_get_frontpage(dir_connection_t *conn,
  3482. const get_handler_args_t *args);
  3483. static int handle_get_current_consensus(dir_connection_t *conn,
  3484. const get_handler_args_t *args);
  3485. static int handle_get_status_vote(dir_connection_t *conn,
  3486. const get_handler_args_t *args);
  3487. static int handle_get_microdesc(dir_connection_t *conn,
  3488. const get_handler_args_t *args);
  3489. static int handle_get_descriptor(dir_connection_t *conn,
  3490. const get_handler_args_t *args);
  3491. static int handle_get_keys(dir_connection_t *conn,
  3492. const get_handler_args_t *args);
  3493. static int handle_get_hs_descriptor_v2(dir_connection_t *conn,
  3494. const get_handler_args_t *args);
  3495. static int handle_get_robots(dir_connection_t *conn,
  3496. const get_handler_args_t *args);
  3497. static int handle_get_networkstatus_bridges(dir_connection_t *conn,
  3498. const get_handler_args_t *args);
  3499. /** Table for handling GET requests. */
  3500. static const url_table_ent_t url_table[] = {
  3501. { "/tor/", 0, handle_get_frontpage },
  3502. { "/tor/status-vote/current/consensus", 1, handle_get_current_consensus },
  3503. { "/tor/status-vote/current/", 1, handle_get_status_vote },
  3504. { "/tor/status-vote/next/", 1, handle_get_status_vote },
  3505. { "/tor/micro/d/", 1, handle_get_microdesc },
  3506. { "/tor/server/", 1, handle_get_descriptor },
  3507. { "/tor/extra/", 1, handle_get_descriptor },
  3508. { "/tor/keys/", 1, handle_get_keys },
  3509. { "/tor/rendezvous2/", 1, handle_get_hs_descriptor_v2 },
  3510. { "/tor/hs/3/", 1, handle_get_hs_descriptor_v3 },
  3511. { "/tor/robots.txt", 0, handle_get_robots },
  3512. { "/tor/networkstatus-bridges", 0, handle_get_networkstatus_bridges },
  3513. { NULL, 0, NULL },
  3514. };
  3515. /** Helper function: called when a dirserver gets a complete HTTP GET
  3516. * request. Look for a request for a directory or for a rendezvous
  3517. * service descriptor. On finding one, write a response into
  3518. * conn-\>outbuf. If the request is unrecognized, send a 404.
  3519. * Return 0 if we handled this successfully, or -1 if we need to close
  3520. * the connection. */
  3521. MOCK_IMPL(STATIC int,
  3522. directory_handle_command_get,(dir_connection_t *conn, const char *headers,
  3523. const char *req_body, size_t req_body_len))
  3524. {
  3525. char *url, *url_mem, *header;
  3526. time_t if_modified_since = 0;
  3527. int zlib_compressed_in_url;
  3528. unsigned compression_methods_supported;
  3529. /* We ignore the body of a GET request. */
  3530. (void)req_body;
  3531. (void)req_body_len;
  3532. log_debug(LD_DIRSERV,"Received GET command.");
  3533. conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
  3534. if (parse_http_url(headers, &url) < 0) {
  3535. write_short_http_response(conn, 400, "Bad request");
  3536. return 0;
  3537. }
  3538. if ((header = http_get_header(headers, "If-Modified-Since: "))) {
  3539. struct tm tm;
  3540. if (parse_http_time(header, &tm) == 0) {
  3541. if (tor_timegm(&tm, &if_modified_since)<0) {
  3542. if_modified_since = 0;
  3543. } else {
  3544. log_debug(LD_DIRSERV, "If-Modified-Since is '%s'.", escaped(header));
  3545. }
  3546. }
  3547. /* The correct behavior on a malformed If-Modified-Since header is to
  3548. * act as if no If-Modified-Since header had been given. */
  3549. tor_free(header);
  3550. }
  3551. log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
  3552. url_mem = url;
  3553. {
  3554. size_t url_len = strlen(url);
  3555. zlib_compressed_in_url = url_len > 2 && !strcmp(url+url_len-2, ".z");
  3556. if (zlib_compressed_in_url) {
  3557. url[url_len-2] = '\0';
  3558. }
  3559. }
  3560. if ((header = http_get_header(headers, "Accept-Encoding: "))) {
  3561. compression_methods_supported = parse_accept_encoding_header(header);
  3562. tor_free(header);
  3563. } else {
  3564. compression_methods_supported = (1u << NO_METHOD);
  3565. }
  3566. if (zlib_compressed_in_url) {
  3567. compression_methods_supported |= (1u << ZLIB_METHOD);
  3568. }
  3569. /* Remove all methods that we don't both support. */
  3570. compression_methods_supported &= tor_compress_get_supported_method_bitmask();
  3571. get_handler_args_t args;
  3572. args.url = url;
  3573. args.headers = headers;
  3574. args.if_modified_since = if_modified_since;
  3575. args.compression_supported = compression_methods_supported;
  3576. int i, result = -1;
  3577. for (i = 0; url_table[i].string; ++i) {
  3578. int match;
  3579. if (url_table[i].is_prefix) {
  3580. match = !strcmpstart(url, url_table[i].string);
  3581. } else {
  3582. match = !strcmp(url, url_table[i].string);
  3583. }
  3584. if (match) {
  3585. result = url_table[i].handler(conn, &args);
  3586. goto done;
  3587. }
  3588. }
  3589. /* we didn't recognize the url */
  3590. write_short_http_response(conn, 404, "Not found");
  3591. result = 0;
  3592. done:
  3593. tor_free(url_mem);
  3594. return result;
  3595. }
  3596. /** Helper function for GET / or GET /tor/
  3597. */
  3598. static int
  3599. handle_get_frontpage(dir_connection_t *conn, const get_handler_args_t *args)
  3600. {
  3601. (void) args; /* unused */
  3602. const char *frontpage = get_dirportfrontpage();
  3603. if (frontpage) {
  3604. size_t dlen;
  3605. dlen = strlen(frontpage);
  3606. /* Let's return a disclaimer page (users shouldn't use V1 anymore,
  3607. and caches don't fetch '/', so this is safe). */
  3608. /* [We don't check for write_bucket_low here, since we want to serve
  3609. * this page no matter what.] */
  3610. write_http_response_header_impl(conn, dlen, "text/html", "identity",
  3611. NULL, DIRPORTFRONTPAGE_CACHE_LIFETIME);
  3612. connection_buf_add(frontpage, dlen, TO_CONN(conn));
  3613. } else {
  3614. write_short_http_response(conn, 404, "Not found");
  3615. }
  3616. return 0;
  3617. }
  3618. /** Warn that the cached consensus <b>consensus</b> of type
  3619. * <b>flavor</b> is too old and will not be served to clients. Rate-limit the
  3620. * warning to avoid logging an entry on every request.
  3621. */
  3622. static void
  3623. warn_consensus_is_too_old(const struct consensus_cache_entry_t *consensus,
  3624. const char *flavor, time_t now)
  3625. {
  3626. #define TOO_OLD_WARNING_INTERVAL (60*60)
  3627. static ratelim_t warned = RATELIM_INIT(TOO_OLD_WARNING_INTERVAL);
  3628. char timestamp[ISO_TIME_LEN+1];
  3629. time_t valid_until;
  3630. char *dupes;
  3631. if (consensus_cache_entry_get_valid_until(consensus, &valid_until))
  3632. return;
  3633. if ((dupes = rate_limit_log(&warned, now))) {
  3634. format_local_iso_time(timestamp, valid_until);
  3635. log_warn(LD_DIRSERV, "Our %s%sconsensus is too old, so we will not "
  3636. "serve it to clients. It was valid until %s local time and we "
  3637. "continued to serve it for up to 24 hours after it expired.%s",
  3638. flavor ? flavor : "", flavor ? " " : "", timestamp, dupes);
  3639. tor_free(dupes);
  3640. }
  3641. }
  3642. /**
  3643. * Parse a single hex-encoded sha3-256 digest from <b>hex</b> into
  3644. * <b>digest</b>. Return 0 on success. On failure, report that the hash came
  3645. * from <b>location</b>, report that we are taking <b>action</b> with it, and
  3646. * return -1.
  3647. */
  3648. static int
  3649. parse_one_diff_hash(uint8_t *digest, const char *hex, const char *location,
  3650. const char *action)
  3651. {
  3652. if (base16_decode((char*)digest, DIGEST256_LEN, hex, strlen(hex)) ==
  3653. DIGEST256_LEN) {
  3654. return 0;
  3655. } else {
  3656. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  3657. "%s contained bogus digest %s; %s.",
  3658. location, escaped(hex), action);
  3659. return -1;
  3660. }
  3661. }
  3662. /** If there is an X-Or-Diff-From-Consensus header included in <b>headers</b>,
  3663. * set <b>digest_out<b> to a new smartlist containing every 256-bit
  3664. * hex-encoded digest listed in that header and return 0. Otherwise return
  3665. * -1. */
  3666. static int
  3667. parse_or_diff_from_header(smartlist_t **digests_out, const char *headers)
  3668. {
  3669. char *hdr = http_get_header(headers, X_OR_DIFF_FROM_CONSENSUS_HEADER);
  3670. if (hdr == NULL) {
  3671. return -1;
  3672. }
  3673. smartlist_t *hex_digests = smartlist_new();
  3674. *digests_out = smartlist_new();
  3675. smartlist_split_string(hex_digests, hdr, " ",
  3676. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  3677. SMARTLIST_FOREACH_BEGIN(hex_digests, const char *, hex) {
  3678. uint8_t digest[DIGEST256_LEN];
  3679. if (!parse_one_diff_hash(digest, hex, "X-Or-Diff-From-Consensus header",
  3680. "ignoring")) {
  3681. smartlist_add(*digests_out, tor_memdup(digest, sizeof(digest)));
  3682. }
  3683. } SMARTLIST_FOREACH_END(hex);
  3684. SMARTLIST_FOREACH(hex_digests, char *, cp, tor_free(cp));
  3685. smartlist_free(hex_digests);
  3686. tor_free(hdr);
  3687. return 0;
  3688. }
  3689. /** Fallback compression method. The fallback compression method is used in
  3690. * case a client requests a non-compressed document. We only store compressed
  3691. * documents, so we use this compression method to fetch the document and let
  3692. * the spooling system do the streaming decompression.
  3693. */
  3694. #define FALLBACK_COMPRESS_METHOD ZLIB_METHOD
  3695. /**
  3696. * Try to find the best consensus diff possible in order to serve a client
  3697. * request for a diff from one of the consensuses in <b>digests</b> to the
  3698. * current consensus of flavor <b>flav</b>. The client supports the
  3699. * compression methods listed in the <b>compression_methods</b> bitfield:
  3700. * place the method chosen (if any) into <b>compression_used_out</b>.
  3701. */
  3702. static struct consensus_cache_entry_t *
  3703. find_best_diff(const smartlist_t *digests, int flav,
  3704. unsigned compression_methods,
  3705. compress_method_t *compression_used_out)
  3706. {
  3707. struct consensus_cache_entry_t *result = NULL;
  3708. SMARTLIST_FOREACH_BEGIN(digests, const uint8_t *, diff_from) {
  3709. unsigned u;
  3710. for (u = 0; u < ARRAY_LENGTH(srv_meth_pref_precompressed); ++u) {
  3711. compress_method_t method = srv_meth_pref_precompressed[u];
  3712. if (0 == (compression_methods & (1u<<method)))
  3713. continue; // client doesn't like this one, or we don't have it.
  3714. if (consdiffmgr_find_diff_from(&result, flav, DIGEST_SHA3_256,
  3715. diff_from, DIGEST256_LEN,
  3716. method) == CONSDIFF_AVAILABLE) {
  3717. tor_assert_nonfatal(result);
  3718. *compression_used_out = method;
  3719. return result;
  3720. }
  3721. }
  3722. } SMARTLIST_FOREACH_END(diff_from);
  3723. SMARTLIST_FOREACH_BEGIN(digests, const uint8_t *, diff_from) {
  3724. if (consdiffmgr_find_diff_from(&result, flav, DIGEST_SHA3_256, diff_from,
  3725. DIGEST256_LEN, FALLBACK_COMPRESS_METHOD) == CONSDIFF_AVAILABLE) {
  3726. tor_assert_nonfatal(result);
  3727. *compression_used_out = FALLBACK_COMPRESS_METHOD;
  3728. return result;
  3729. }
  3730. } SMARTLIST_FOREACH_END(diff_from);
  3731. return NULL;
  3732. }
  3733. /** Lookup the cached consensus document by the flavor found in <b>flav</b>.
  3734. * The prefered set of compression methods should be listed in the
  3735. * <b>compression_methods</b> bitfield. The compression method chosen (if any)
  3736. * is stored in <b>compression_used_out</b>. */
  3737. static struct consensus_cache_entry_t *
  3738. find_best_consensus(int flav,
  3739. unsigned compression_methods,
  3740. compress_method_t *compression_used_out)
  3741. {
  3742. struct consensus_cache_entry_t *result = NULL;
  3743. unsigned u;
  3744. for (u = 0; u < ARRAY_LENGTH(srv_meth_pref_precompressed); ++u) {
  3745. compress_method_t method = srv_meth_pref_precompressed[u];
  3746. if (0 == (compression_methods & (1u<<method)))
  3747. continue;
  3748. if (consdiffmgr_find_consensus(&result, flav,
  3749. method) == CONSDIFF_AVAILABLE) {
  3750. tor_assert_nonfatal(result);
  3751. *compression_used_out = method;
  3752. return result;
  3753. }
  3754. }
  3755. if (consdiffmgr_find_consensus(&result, flav,
  3756. FALLBACK_COMPRESS_METHOD) == CONSDIFF_AVAILABLE) {
  3757. tor_assert_nonfatal(result);
  3758. *compression_used_out = FALLBACK_COMPRESS_METHOD;
  3759. return result;
  3760. }
  3761. return NULL;
  3762. }
  3763. /** Try to find the best supported compression method possible from a given
  3764. * <b>compression_methods</b>. Return NO_METHOD if no mutually supported
  3765. * compression method could be found. */
  3766. static compress_method_t
  3767. find_best_compression_method(unsigned compression_methods, int stream)
  3768. {
  3769. unsigned u;
  3770. compress_method_t *methods;
  3771. size_t length;
  3772. if (stream) {
  3773. methods = srv_meth_pref_streaming_compression;
  3774. length = ARRAY_LENGTH(srv_meth_pref_streaming_compression);
  3775. } else {
  3776. methods = srv_meth_pref_precompressed;
  3777. length = ARRAY_LENGTH(srv_meth_pref_precompressed);
  3778. }
  3779. for (u = 0; u < length; ++u) {
  3780. compress_method_t method = methods[u];
  3781. if (compression_methods & (1u<<method))
  3782. return method;
  3783. }
  3784. return NO_METHOD;
  3785. }
  3786. /** Check if any of the digests in <b>digests</b> matches the latest consensus
  3787. * flavor (given in <b>flavor</b>) that we have available. */
  3788. static int
  3789. digest_list_contains_best_consensus(consensus_flavor_t flavor,
  3790. const smartlist_t *digests)
  3791. {
  3792. const networkstatus_t *ns = NULL;
  3793. if (digests == NULL)
  3794. return 0;
  3795. ns = networkstatus_get_latest_consensus_by_flavor(flavor);
  3796. if (ns == NULL)
  3797. return 0;
  3798. SMARTLIST_FOREACH_BEGIN(digests, const uint8_t *, digest) {
  3799. if (tor_memeq(ns->digest_sha3_as_signed, digest, DIGEST256_LEN))
  3800. return 1;
  3801. } SMARTLIST_FOREACH_END(digest);
  3802. return 0;
  3803. }
  3804. /** Check if the given compression method is allowed for a connection that is
  3805. * supposed to be anonymous. Returns 1 if the compression method is allowed,
  3806. * otherwise 0. */
  3807. STATIC int
  3808. allowed_anonymous_connection_compression_method(compress_method_t method)
  3809. {
  3810. unsigned u;
  3811. for (u = 0; u < ARRAY_LENGTH(client_meth_allowed_anonymous_compression);
  3812. ++u) {
  3813. compress_method_t allowed_method =
  3814. client_meth_allowed_anonymous_compression[u];
  3815. if (! tor_compress_supports_method(allowed_method))
  3816. continue;
  3817. if (method == allowed_method)
  3818. return 1;
  3819. }
  3820. return 0;
  3821. }
  3822. /** Log a warning when a remote server has sent us a document using a
  3823. * compression method that is not allowed for anonymous directory requests. */
  3824. STATIC void
  3825. warn_disallowed_anonymous_compression_method(compress_method_t method)
  3826. {
  3827. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  3828. "Received a %s HTTP response, which is not "
  3829. "allowed for anonymous directory requests.",
  3830. compression_method_get_human_name(method));
  3831. }
  3832. /** Encodes the results of parsing a consensus request to figure out what
  3833. * consensus, and possibly what diffs, the user asked for. */
  3834. typedef struct {
  3835. /** name of the flavor to retrieve. */
  3836. char *flavor;
  3837. /** flavor to retrive, as enum. */
  3838. consensus_flavor_t flav;
  3839. /** plus-separated list of authority fingerprints; see
  3840. * client_likes_consensus(). Aliases the URL in the request passed to
  3841. * parse_consensus_request(). */
  3842. const char *want_fps;
  3843. /** Optionally, a smartlist of sha3 digests-as-signed of the consensuses
  3844. * to return a diff from. */
  3845. smartlist_t *diff_from_digests;
  3846. /** If true, never send a full consensus. If there is no diff, send
  3847. * a 404 instead. */
  3848. int diff_only;
  3849. } parsed_consensus_request_t;
  3850. /** Remove all data held in <b>req</b>. Do not free <b>req</b> itself, since
  3851. * it is stack-allocated. */
  3852. static void
  3853. parsed_consensus_request_clear(parsed_consensus_request_t *req)
  3854. {
  3855. if (!req)
  3856. return;
  3857. tor_free(req->flavor);
  3858. if (req->diff_from_digests) {
  3859. SMARTLIST_FOREACH(req->diff_from_digests, uint8_t *, d, tor_free(d));
  3860. smartlist_free(req->diff_from_digests);
  3861. }
  3862. memset(req, 0, sizeof(parsed_consensus_request_t));
  3863. }
  3864. /**
  3865. * Parse the URL and relevant headers of <b>args</b> for a current-consensus
  3866. * request to learn what flavor of consensus we want, what keys it must be
  3867. * signed with, and what diffs we would accept (or demand) instead. Return 0
  3868. * on success and -1 on failure.
  3869. */
  3870. static int
  3871. parse_consensus_request(parsed_consensus_request_t *out,
  3872. const get_handler_args_t *args)
  3873. {
  3874. const char *url = args->url;
  3875. memset(out, 0, sizeof(parsed_consensus_request_t));
  3876. out->flav = FLAV_NS;
  3877. const char CONSENSUS_URL_PREFIX[] = "/tor/status-vote/current/consensus/";
  3878. const char CONSENSUS_FLAVORED_PREFIX[] =
  3879. "/tor/status-vote/current/consensus-";
  3880. /* figure out the flavor if any, and who we wanted to sign the thing */
  3881. const char *after_flavor = NULL;
  3882. if (!strcmpstart(url, CONSENSUS_FLAVORED_PREFIX)) {
  3883. const char *f, *cp;
  3884. f = url + strlen(CONSENSUS_FLAVORED_PREFIX);
  3885. cp = strchr(f, '/');
  3886. if (cp) {
  3887. after_flavor = cp+1;
  3888. out->flavor = tor_strndup(f, cp-f);
  3889. } else {
  3890. out->flavor = tor_strdup(f);
  3891. }
  3892. int flav = networkstatus_parse_flavor_name(out->flavor);
  3893. if (flav < 0)
  3894. flav = FLAV_NS;
  3895. out->flav = flav;
  3896. } else {
  3897. if (!strcmpstart(url, CONSENSUS_URL_PREFIX))
  3898. after_flavor = url+strlen(CONSENSUS_URL_PREFIX);
  3899. }
  3900. /* see whether we've been asked explicitly for a diff from an older
  3901. * consensus. (The user might also have said that a diff would be okay,
  3902. * via X-Or-Diff-From-Consensus */
  3903. const char DIFF_COMPONENT[] = "diff/";
  3904. char *diff_hash_in_url = NULL;
  3905. if (after_flavor && !strcmpstart(after_flavor, DIFF_COMPONENT)) {
  3906. after_flavor += strlen(DIFF_COMPONENT);
  3907. const char *cp = strchr(after_flavor, '/');
  3908. if (cp) {
  3909. diff_hash_in_url = tor_strndup(after_flavor, cp-after_flavor);
  3910. out->want_fps = cp+1;
  3911. } else {
  3912. diff_hash_in_url = tor_strdup(after_flavor);
  3913. out->want_fps = NULL;
  3914. }
  3915. } else {
  3916. out->want_fps = after_flavor;
  3917. }
  3918. if (diff_hash_in_url) {
  3919. uint8_t diff_from[DIGEST256_LEN];
  3920. out->diff_from_digests = smartlist_new();
  3921. out->diff_only = 1;
  3922. int ok = !parse_one_diff_hash(diff_from, diff_hash_in_url, "URL",
  3923. "rejecting");
  3924. tor_free(diff_hash_in_url);
  3925. if (ok) {
  3926. smartlist_add(out->diff_from_digests,
  3927. tor_memdup(diff_from, DIGEST256_LEN));
  3928. } else {
  3929. return -1;
  3930. }
  3931. } else {
  3932. parse_or_diff_from_header(&out->diff_from_digests, args->headers);
  3933. }
  3934. return 0;
  3935. }
  3936. /** Helper function for GET /tor/status-vote/current/consensus
  3937. */
  3938. static int
  3939. handle_get_current_consensus(dir_connection_t *conn,
  3940. const get_handler_args_t *args)
  3941. {
  3942. const compress_method_t compress_method =
  3943. find_best_compression_method(args->compression_supported, 0);
  3944. const time_t if_modified_since = args->if_modified_since;
  3945. int clear_spool = 0;
  3946. /* v3 network status fetch. */
  3947. long lifetime = NETWORKSTATUS_CACHE_LIFETIME;
  3948. time_t now = time(NULL);
  3949. parsed_consensus_request_t req;
  3950. if (parse_consensus_request(&req, args) < 0) {
  3951. write_short_http_response(conn, 404, "Couldn't parse request");
  3952. goto done;
  3953. }
  3954. if (digest_list_contains_best_consensus(req.flav,
  3955. req.diff_from_digests)) {
  3956. write_short_http_response(conn, 304, "Not modified");
  3957. geoip_note_ns_response(GEOIP_REJECT_NOT_MODIFIED);
  3958. goto done;
  3959. }
  3960. struct consensus_cache_entry_t *cached_consensus = NULL;
  3961. compress_method_t compression_used = NO_METHOD;
  3962. if (req.diff_from_digests) {
  3963. cached_consensus = find_best_diff(req.diff_from_digests, req.flav,
  3964. args->compression_supported,
  3965. &compression_used);
  3966. }
  3967. if (req.diff_only && !cached_consensus) {
  3968. write_short_http_response(conn, 404, "No such diff available");
  3969. // XXXX warn_consensus_is_too_old(v, req.flavor, now);
  3970. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  3971. goto done;
  3972. }
  3973. if (! cached_consensus) {
  3974. cached_consensus = find_best_consensus(req.flav,
  3975. args->compression_supported,
  3976. &compression_used);
  3977. }
  3978. time_t fresh_until, valid_until;
  3979. int have_fresh_until = 0, have_valid_until = 0;
  3980. if (cached_consensus) {
  3981. have_fresh_until =
  3982. !consensus_cache_entry_get_fresh_until(cached_consensus, &fresh_until);
  3983. have_valid_until =
  3984. !consensus_cache_entry_get_valid_until(cached_consensus, &valid_until);
  3985. }
  3986. if (cached_consensus && have_valid_until &&
  3987. !networkstatus_valid_until_is_reasonably_live(valid_until, now)) {
  3988. write_short_http_response(conn, 404, "Consensus is too old");
  3989. warn_consensus_is_too_old(cached_consensus, req.flavor, now);
  3990. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  3991. goto done;
  3992. }
  3993. if (cached_consensus && req.want_fps &&
  3994. !client_likes_consensus(cached_consensus, req.want_fps)) {
  3995. write_short_http_response(conn, 404, "Consensus not signed by sufficient "
  3996. "number of requested authorities");
  3997. geoip_note_ns_response(GEOIP_REJECT_NOT_ENOUGH_SIGS);
  3998. goto done;
  3999. }
  4000. conn->spool = smartlist_new();
  4001. clear_spool = 1;
  4002. {
  4003. spooled_resource_t *spooled;
  4004. if (cached_consensus) {
  4005. spooled = spooled_resource_new_from_cache_entry(cached_consensus);
  4006. smartlist_add(conn->spool, spooled);
  4007. }
  4008. }
  4009. lifetime = (have_fresh_until && fresh_until > now) ? fresh_until - now : 0;
  4010. size_t size_guess = 0;
  4011. int n_expired = 0;
  4012. dirserv_spool_remove_missing_and_guess_size(conn, if_modified_since,
  4013. compress_method != NO_METHOD,
  4014. &size_guess,
  4015. &n_expired);
  4016. if (!smartlist_len(conn->spool) && !n_expired) {
  4017. write_short_http_response(conn, 404, "Not found");
  4018. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  4019. goto done;
  4020. } else if (!smartlist_len(conn->spool)) {
  4021. write_short_http_response(conn, 304, "Not modified");
  4022. geoip_note_ns_response(GEOIP_REJECT_NOT_MODIFIED);
  4023. goto done;
  4024. }
  4025. if (global_write_bucket_low(TO_CONN(conn), size_guess, 2)) {
  4026. log_debug(LD_DIRSERV,
  4027. "Client asked for network status lists, but we've been "
  4028. "writing too many bytes lately. Sending 503 Dir busy.");
  4029. write_short_http_response(conn, 503, "Directory busy, try again later");
  4030. geoip_note_ns_response(GEOIP_REJECT_BUSY);
  4031. goto done;
  4032. }
  4033. tor_addr_t addr;
  4034. if (tor_addr_parse(&addr, (TO_CONN(conn))->address) >= 0) {
  4035. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS,
  4036. &addr, NULL,
  4037. time(NULL));
  4038. geoip_note_ns_response(GEOIP_SUCCESS);
  4039. /* Note that a request for a network status has started, so that we
  4040. * can measure the download time later on. */
  4041. if (conn->dirreq_id)
  4042. geoip_start_dirreq(conn->dirreq_id, size_guess, DIRREQ_TUNNELED);
  4043. else
  4044. geoip_start_dirreq(TO_CONN(conn)->global_identifier, size_guess,
  4045. DIRREQ_DIRECT);
  4046. }
  4047. /* Use this header to tell caches that the response depends on the
  4048. * X-Or-Diff-From-Consensus header (or lack thereof). */
  4049. const char vary_header[] = "Vary: X-Or-Diff-From-Consensus\r\n";
  4050. clear_spool = 0;
  4051. // The compress_method might have been NO_METHOD, but we store the data
  4052. // compressed. Decompress them using `compression_used`. See fallback code in
  4053. // find_best_consensus() and find_best_diff().
  4054. write_http_response_headers(conn, -1,
  4055. compress_method == NO_METHOD ?
  4056. NO_METHOD : compression_used,
  4057. vary_header,
  4058. smartlist_len(conn->spool) == 1 ? lifetime : 0);
  4059. if (compress_method == NO_METHOD && smartlist_len(conn->spool))
  4060. conn->compress_state = tor_compress_new(0, compression_used,
  4061. HIGH_COMPRESSION);
  4062. /* Prime the connection with some data. */
  4063. const int initial_flush_result = connection_dirserv_flushed_some(conn);
  4064. tor_assert_nonfatal(initial_flush_result == 0);
  4065. goto done;
  4066. done:
  4067. parsed_consensus_request_clear(&req);
  4068. if (clear_spool) {
  4069. dir_conn_clear_spool(conn);
  4070. }
  4071. return 0;
  4072. }
  4073. /** Helper function for GET /tor/status-vote/{current,next}/...
  4074. */
  4075. static int
  4076. handle_get_status_vote(dir_connection_t *conn, const get_handler_args_t *args)
  4077. {
  4078. const char *url = args->url;
  4079. {
  4080. int current;
  4081. ssize_t body_len = 0;
  4082. ssize_t estimated_len = 0;
  4083. /* This smartlist holds strings that we can compress on the fly. */
  4084. smartlist_t *items = smartlist_new();
  4085. /* This smartlist holds cached_dir_t objects that have a precompressed
  4086. * deflated version. */
  4087. smartlist_t *dir_items = smartlist_new();
  4088. int lifetime = 60; /* XXXX?? should actually use vote intervals. */
  4089. url += strlen("/tor/status-vote/");
  4090. current = !strcmpstart(url, "current/");
  4091. url = strchr(url, '/');
  4092. tor_assert(url);
  4093. ++url;
  4094. if (!strcmp(url, "consensus")) {
  4095. const char *item;
  4096. tor_assert(!current); /* we handle current consensus specially above,
  4097. * since it wants to be spooled. */
  4098. if ((item = dirvote_get_pending_consensus(FLAV_NS)))
  4099. smartlist_add(items, (char*)item);
  4100. } else if (!current && !strcmp(url, "consensus-signatures")) {
  4101. /* XXXX the spec says that we should implement
  4102. * current/consensus-signatures too. It doesn't seem to be needed,
  4103. * though. */
  4104. const char *item;
  4105. if ((item=dirvote_get_pending_detached_signatures()))
  4106. smartlist_add(items, (char*)item);
  4107. } else if (!strcmp(url, "authority")) {
  4108. const cached_dir_t *d;
  4109. int flags = DGV_BY_ID |
  4110. (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
  4111. if ((d=dirvote_get_vote(NULL, flags)))
  4112. smartlist_add(dir_items, (cached_dir_t*)d);
  4113. } else {
  4114. const cached_dir_t *d;
  4115. smartlist_t *fps = smartlist_new();
  4116. int flags;
  4117. if (!strcmpstart(url, "d/")) {
  4118. url += 2;
  4119. flags = DGV_INCLUDE_PENDING | DGV_INCLUDE_PREVIOUS;
  4120. } else {
  4121. flags = DGV_BY_ID |
  4122. (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
  4123. }
  4124. dir_split_resource_into_fingerprints(url, fps, NULL,
  4125. DSR_HEX|DSR_SORT_UNIQ);
  4126. SMARTLIST_FOREACH(fps, char *, fp, {
  4127. if ((d = dirvote_get_vote(fp, flags)))
  4128. smartlist_add(dir_items, (cached_dir_t*)d);
  4129. tor_free(fp);
  4130. });
  4131. smartlist_free(fps);
  4132. }
  4133. if (!smartlist_len(dir_items) && !smartlist_len(items)) {
  4134. write_short_http_response(conn, 404, "Not found");
  4135. goto vote_done;
  4136. }
  4137. /* We're sending items from at most one kind of source */
  4138. tor_assert_nonfatal(smartlist_len(items) == 0 ||
  4139. smartlist_len(dir_items) == 0);
  4140. int streaming;
  4141. unsigned mask;
  4142. if (smartlist_len(items)) {
  4143. /* We're taking strings and compressing them on the fly. */
  4144. streaming = 1;
  4145. mask = ~0u;
  4146. } else {
  4147. /* We're taking cached_dir_t objects. We only have them uncompressed
  4148. * or deflated. */
  4149. streaming = 0;
  4150. mask = (1u<<NO_METHOD) | (1u<<ZLIB_METHOD);
  4151. }
  4152. const compress_method_t compress_method = find_best_compression_method(
  4153. args->compression_supported&mask, streaming);
  4154. SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
  4155. body_len += compress_method != NO_METHOD ?
  4156. d->dir_compressed_len : d->dir_len);
  4157. estimated_len += body_len;
  4158. SMARTLIST_FOREACH(items, const char *, item, {
  4159. size_t ln = strlen(item);
  4160. if (compress_method != NO_METHOD) {
  4161. estimated_len += ln/2;
  4162. } else {
  4163. body_len += ln; estimated_len += ln;
  4164. }
  4165. });
  4166. if (global_write_bucket_low(TO_CONN(conn), estimated_len, 2)) {
  4167. write_short_http_response(conn, 503, "Directory busy, try again later");
  4168. goto vote_done;
  4169. }
  4170. write_http_response_header(conn, body_len ? body_len : -1,
  4171. compress_method,
  4172. lifetime);
  4173. if (smartlist_len(items)) {
  4174. if (compress_method != NO_METHOD) {
  4175. conn->compress_state = tor_compress_new(1, compress_method,
  4176. choose_compression_level(estimated_len));
  4177. SMARTLIST_FOREACH(items, const char *, c,
  4178. connection_buf_add_compress(c, strlen(c), conn, 0));
  4179. connection_buf_add_compress("", 0, conn, 1);
  4180. } else {
  4181. SMARTLIST_FOREACH(items, const char *, c,
  4182. connection_buf_add(c, strlen(c), TO_CONN(conn)));
  4183. }
  4184. } else {
  4185. SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
  4186. connection_buf_add(compress_method != NO_METHOD ?
  4187. d->dir_compressed : d->dir,
  4188. compress_method != NO_METHOD ?
  4189. d->dir_compressed_len : d->dir_len,
  4190. TO_CONN(conn)));
  4191. }
  4192. vote_done:
  4193. smartlist_free(items);
  4194. smartlist_free(dir_items);
  4195. goto done;
  4196. }
  4197. done:
  4198. return 0;
  4199. }
  4200. /** Helper function for GET /tor/micro/d/...
  4201. */
  4202. static int
  4203. handle_get_microdesc(dir_connection_t *conn, const get_handler_args_t *args)
  4204. {
  4205. const char *url = args->url;
  4206. const compress_method_t compress_method =
  4207. find_best_compression_method(args->compression_supported, 1);
  4208. int clear_spool = 1;
  4209. {
  4210. conn->spool = smartlist_new();
  4211. dir_split_resource_into_spoolable(url+strlen("/tor/micro/d/"),
  4212. DIR_SPOOL_MICRODESC,
  4213. conn->spool, NULL,
  4214. DSR_DIGEST256|DSR_BASE64|DSR_SORT_UNIQ);
  4215. size_t size_guess = 0;
  4216. dirserv_spool_remove_missing_and_guess_size(conn, 0,
  4217. compress_method != NO_METHOD,
  4218. &size_guess, NULL);
  4219. if (smartlist_len(conn->spool) == 0) {
  4220. write_short_http_response(conn, 404, "Not found");
  4221. goto done;
  4222. }
  4223. if (global_write_bucket_low(TO_CONN(conn), size_guess, 2)) {
  4224. log_info(LD_DIRSERV,
  4225. "Client asked for server descriptors, but we've been "
  4226. "writing too many bytes lately. Sending 503 Dir busy.");
  4227. write_short_http_response(conn, 503, "Directory busy, try again later");
  4228. goto done;
  4229. }
  4230. clear_spool = 0;
  4231. write_http_response_header(conn, -1,
  4232. compress_method,
  4233. MICRODESC_CACHE_LIFETIME);
  4234. if (compress_method != NO_METHOD)
  4235. conn->compress_state = tor_compress_new(1, compress_method,
  4236. choose_compression_level(size_guess));
  4237. const int initial_flush_result = connection_dirserv_flushed_some(conn);
  4238. tor_assert_nonfatal(initial_flush_result == 0);
  4239. goto done;
  4240. }
  4241. done:
  4242. if (clear_spool) {
  4243. dir_conn_clear_spool(conn);
  4244. }
  4245. return 0;
  4246. }
  4247. /** Helper function for GET /tor/{server,extra}/...
  4248. */
  4249. static int
  4250. handle_get_descriptor(dir_connection_t *conn, const get_handler_args_t *args)
  4251. {
  4252. const char *url = args->url;
  4253. const compress_method_t compress_method =
  4254. find_best_compression_method(args->compression_supported, 1);
  4255. const or_options_t *options = get_options();
  4256. int clear_spool = 1;
  4257. if (!strcmpstart(url,"/tor/server/") ||
  4258. (!options->BridgeAuthoritativeDir &&
  4259. !options->BridgeRelay && !strcmpstart(url,"/tor/extra/"))) {
  4260. int res;
  4261. const char *msg = NULL;
  4262. int cache_lifetime = 0;
  4263. int is_extra = !strcmpstart(url,"/tor/extra/");
  4264. url += is_extra ? strlen("/tor/extra/") : strlen("/tor/server/");
  4265. dir_spool_source_t source;
  4266. time_t publish_cutoff = 0;
  4267. if (!strcmpstart(url, "d/")) {
  4268. source =
  4269. is_extra ? DIR_SPOOL_EXTRA_BY_DIGEST : DIR_SPOOL_SERVER_BY_DIGEST;
  4270. } else {
  4271. source =
  4272. is_extra ? DIR_SPOOL_EXTRA_BY_FP : DIR_SPOOL_SERVER_BY_FP;
  4273. /* We only want to apply a publish cutoff when we're requesting
  4274. * resources by fingerprint. */
  4275. publish_cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
  4276. }
  4277. conn->spool = smartlist_new();
  4278. res = dirserv_get_routerdesc_spool(conn->spool, url,
  4279. source,
  4280. connection_dir_is_encrypted(conn),
  4281. &msg);
  4282. if (!strcmpstart(url, "all")) {
  4283. cache_lifetime = FULL_DIR_CACHE_LIFETIME;
  4284. } else if (smartlist_len(conn->spool) == 1) {
  4285. cache_lifetime = ROUTERDESC_BY_DIGEST_CACHE_LIFETIME;
  4286. }
  4287. size_t size_guess = 0;
  4288. int n_expired = 0;
  4289. dirserv_spool_remove_missing_and_guess_size(conn, publish_cutoff,
  4290. compress_method != NO_METHOD,
  4291. &size_guess, &n_expired);
  4292. /* If we are the bridge authority and the descriptor is a bridge
  4293. * descriptor, remember that we served this descriptor for desc stats. */
  4294. /* XXXX it's a bit of a kludge to have this here. */
  4295. if (get_options()->BridgeAuthoritativeDir &&
  4296. source == DIR_SPOOL_SERVER_BY_FP) {
  4297. SMARTLIST_FOREACH_BEGIN(conn->spool, spooled_resource_t *, spooled) {
  4298. const routerinfo_t *router =
  4299. router_get_by_id_digest((const char *)spooled->digest);
  4300. /* router can be NULL here when the bridge auth is asked for its own
  4301. * descriptor. */
  4302. if (router && router->purpose == ROUTER_PURPOSE_BRIDGE)
  4303. rep_hist_note_desc_served(router->cache_info.identity_digest);
  4304. } SMARTLIST_FOREACH_END(spooled);
  4305. }
  4306. if (res < 0 || size_guess == 0 || smartlist_len(conn->spool) == 0) {
  4307. if (msg == NULL)
  4308. msg = "Not found";
  4309. write_short_http_response(conn, 404, msg);
  4310. } else {
  4311. if (global_write_bucket_low(TO_CONN(conn), size_guess, 2)) {
  4312. log_info(LD_DIRSERV,
  4313. "Client asked for server descriptors, but we've been "
  4314. "writing too many bytes lately. Sending 503 Dir busy.");
  4315. write_short_http_response(conn, 503,
  4316. "Directory busy, try again later");
  4317. dir_conn_clear_spool(conn);
  4318. goto done;
  4319. }
  4320. write_http_response_header(conn, -1, compress_method, cache_lifetime);
  4321. if (compress_method != NO_METHOD)
  4322. conn->compress_state = tor_compress_new(1, compress_method,
  4323. choose_compression_level(size_guess));
  4324. clear_spool = 0;
  4325. /* Prime the connection with some data. */
  4326. int initial_flush_result = connection_dirserv_flushed_some(conn);
  4327. tor_assert_nonfatal(initial_flush_result == 0);
  4328. }
  4329. goto done;
  4330. }
  4331. done:
  4332. if (clear_spool)
  4333. dir_conn_clear_spool(conn);
  4334. return 0;
  4335. }
  4336. /** Helper function for GET /tor/keys/...
  4337. */
  4338. static int
  4339. handle_get_keys(dir_connection_t *conn, const get_handler_args_t *args)
  4340. {
  4341. const char *url = args->url;
  4342. const compress_method_t compress_method =
  4343. find_best_compression_method(args->compression_supported, 1);
  4344. const time_t if_modified_since = args->if_modified_since;
  4345. {
  4346. smartlist_t *certs = smartlist_new();
  4347. ssize_t len = -1;
  4348. if (!strcmp(url, "/tor/keys/all")) {
  4349. authority_cert_get_all(certs);
  4350. } else if (!strcmp(url, "/tor/keys/authority")) {
  4351. authority_cert_t *cert = get_my_v3_authority_cert();
  4352. if (cert)
  4353. smartlist_add(certs, cert);
  4354. } else if (!strcmpstart(url, "/tor/keys/fp/")) {
  4355. smartlist_t *fps = smartlist_new();
  4356. dir_split_resource_into_fingerprints(url+strlen("/tor/keys/fp/"),
  4357. fps, NULL,
  4358. DSR_HEX|DSR_SORT_UNIQ);
  4359. SMARTLIST_FOREACH(fps, char *, d, {
  4360. authority_cert_t *c = authority_cert_get_newest_by_id(d);
  4361. if (c) smartlist_add(certs, c);
  4362. tor_free(d);
  4363. });
  4364. smartlist_free(fps);
  4365. } else if (!strcmpstart(url, "/tor/keys/sk/")) {
  4366. smartlist_t *fps = smartlist_new();
  4367. dir_split_resource_into_fingerprints(url+strlen("/tor/keys/sk/"),
  4368. fps, NULL,
  4369. DSR_HEX|DSR_SORT_UNIQ);
  4370. SMARTLIST_FOREACH(fps, char *, d, {
  4371. authority_cert_t *c = authority_cert_get_by_sk_digest(d);
  4372. if (c) smartlist_add(certs, c);
  4373. tor_free(d);
  4374. });
  4375. smartlist_free(fps);
  4376. } else if (!strcmpstart(url, "/tor/keys/fp-sk/")) {
  4377. smartlist_t *fp_sks = smartlist_new();
  4378. dir_split_resource_into_fingerprint_pairs(url+strlen("/tor/keys/fp-sk/"),
  4379. fp_sks);
  4380. SMARTLIST_FOREACH(fp_sks, fp_pair_t *, pair, {
  4381. authority_cert_t *c = authority_cert_get_by_digests(pair->first,
  4382. pair->second);
  4383. if (c) smartlist_add(certs, c);
  4384. tor_free(pair);
  4385. });
  4386. smartlist_free(fp_sks);
  4387. } else {
  4388. write_short_http_response(conn, 400, "Bad request");
  4389. goto keys_done;
  4390. }
  4391. if (!smartlist_len(certs)) {
  4392. write_short_http_response(conn, 404, "Not found");
  4393. goto keys_done;
  4394. }
  4395. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  4396. if (c->cache_info.published_on < if_modified_since)
  4397. SMARTLIST_DEL_CURRENT(certs, c));
  4398. if (!smartlist_len(certs)) {
  4399. write_short_http_response(conn, 304, "Not modified");
  4400. goto keys_done;
  4401. }
  4402. len = 0;
  4403. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  4404. len += c->cache_info.signed_descriptor_len);
  4405. if (global_write_bucket_low(TO_CONN(conn),
  4406. compress_method != NO_METHOD ? len/2 : len,
  4407. 2)) {
  4408. write_short_http_response(conn, 503, "Directory busy, try again later");
  4409. goto keys_done;
  4410. }
  4411. write_http_response_header(conn,
  4412. compress_method != NO_METHOD ? -1 : len,
  4413. compress_method,
  4414. 60*60);
  4415. if (compress_method != NO_METHOD) {
  4416. conn->compress_state = tor_compress_new(1, compress_method,
  4417. choose_compression_level(len));
  4418. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  4419. connection_buf_add_compress(
  4420. c->cache_info.signed_descriptor_body,
  4421. c->cache_info.signed_descriptor_len,
  4422. conn, 0));
  4423. connection_buf_add_compress("", 0, conn, 1);
  4424. } else {
  4425. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  4426. connection_buf_add(c->cache_info.signed_descriptor_body,
  4427. c->cache_info.signed_descriptor_len,
  4428. TO_CONN(conn)));
  4429. }
  4430. keys_done:
  4431. smartlist_free(certs);
  4432. goto done;
  4433. }
  4434. done:
  4435. return 0;
  4436. }
  4437. /** Helper function for GET /tor/rendezvous2/
  4438. */
  4439. static int
  4440. handle_get_hs_descriptor_v2(dir_connection_t *conn,
  4441. const get_handler_args_t *args)
  4442. {
  4443. const char *url = args->url;
  4444. if (connection_dir_is_encrypted(conn)) {
  4445. /* Handle v2 rendezvous descriptor fetch request. */
  4446. const char *descp;
  4447. const char *query = url + strlen("/tor/rendezvous2/");
  4448. if (rend_valid_descriptor_id(query)) {
  4449. log_info(LD_REND, "Got a v2 rendezvous descriptor request for ID '%s'",
  4450. safe_str(escaped(query)));
  4451. switch (rend_cache_lookup_v2_desc_as_dir(query, &descp)) {
  4452. case 1: /* valid */
  4453. write_http_response_header(conn, strlen(descp), NO_METHOD, 0);
  4454. connection_buf_add(descp, strlen(descp), TO_CONN(conn));
  4455. break;
  4456. case 0: /* well-formed but not present */
  4457. write_short_http_response(conn, 404, "Not found");
  4458. break;
  4459. case -1: /* not well-formed */
  4460. write_short_http_response(conn, 400, "Bad request");
  4461. break;
  4462. }
  4463. } else { /* not well-formed */
  4464. write_short_http_response(conn, 400, "Bad request");
  4465. }
  4466. goto done;
  4467. } else {
  4468. /* Not encrypted! */
  4469. write_short_http_response(conn, 404, "Not found");
  4470. }
  4471. done:
  4472. return 0;
  4473. }
  4474. /** Helper function for GET /tor/hs/3/<z>. Only for version 3.
  4475. */
  4476. STATIC int
  4477. handle_get_hs_descriptor_v3(dir_connection_t *conn,
  4478. const get_handler_args_t *args)
  4479. {
  4480. int retval;
  4481. const char *desc_str = NULL;
  4482. const char *pubkey_str = NULL;
  4483. const char *url = args->url;
  4484. /* Reject unencrypted dir connections */
  4485. if (!connection_dir_is_encrypted(conn)) {
  4486. write_short_http_response(conn, 404, "Not found");
  4487. goto done;
  4488. }
  4489. /* After the path prefix follows the base64 encoded blinded pubkey which we
  4490. * use to get the descriptor from the cache. Skip the prefix and get the
  4491. * pubkey. */
  4492. tor_assert(!strcmpstart(url, "/tor/hs/3/"));
  4493. pubkey_str = url + strlen("/tor/hs/3/");
  4494. retval = hs_cache_lookup_as_dir(HS_VERSION_THREE,
  4495. pubkey_str, &desc_str);
  4496. if (retval <= 0 || desc_str == NULL) {
  4497. write_short_http_response(conn, 404, "Not found");
  4498. goto done;
  4499. }
  4500. /* Found requested descriptor! Pass it to this nice client. */
  4501. write_http_response_header(conn, strlen(desc_str), NO_METHOD, 0);
  4502. connection_buf_add(desc_str, strlen(desc_str), TO_CONN(conn));
  4503. done:
  4504. return 0;
  4505. }
  4506. /** Helper function for GET /tor/networkstatus-bridges
  4507. */
  4508. static int
  4509. handle_get_networkstatus_bridges(dir_connection_t *conn,
  4510. const get_handler_args_t *args)
  4511. {
  4512. const char *headers = args->headers;
  4513. const or_options_t *options = get_options();
  4514. if (options->BridgeAuthoritativeDir &&
  4515. options->BridgePassword_AuthDigest_ &&
  4516. connection_dir_is_encrypted(conn)) {
  4517. char *status;
  4518. char digest[DIGEST256_LEN];
  4519. char *header = http_get_header(headers, "Authorization: Basic ");
  4520. if (header)
  4521. crypto_digest256(digest, header, strlen(header), DIGEST_SHA256);
  4522. /* now make sure the password is there and right */
  4523. if (!header ||
  4524. tor_memneq(digest,
  4525. options->BridgePassword_AuthDigest_, DIGEST256_LEN)) {
  4526. write_short_http_response(conn, 404, "Not found");
  4527. tor_free(header);
  4528. goto done;
  4529. }
  4530. tor_free(header);
  4531. /* all happy now. send an answer. */
  4532. status = networkstatus_getinfo_by_purpose("bridge", time(NULL));
  4533. size_t dlen = strlen(status);
  4534. write_http_response_header(conn, dlen, NO_METHOD, 0);
  4535. connection_buf_add(status, dlen, TO_CONN(conn));
  4536. tor_free(status);
  4537. goto done;
  4538. }
  4539. done:
  4540. return 0;
  4541. }
  4542. /** Helper function for GET robots.txt or /tor/robots.txt */
  4543. static int
  4544. handle_get_robots(dir_connection_t *conn, const get_handler_args_t *args)
  4545. {
  4546. (void)args;
  4547. {
  4548. const char robots[] = "User-agent: *\r\nDisallow: /\r\n";
  4549. size_t len = strlen(robots);
  4550. write_http_response_header(conn, len, NO_METHOD, ROBOTS_CACHE_LIFETIME);
  4551. connection_buf_add(robots, len, TO_CONN(conn));
  4552. }
  4553. return 0;
  4554. }
  4555. /* Given the <b>url</b> from a POST request, try to extract the version number
  4556. * using the provided <b>prefix</b>. The version should be after the prefix and
  4557. * ending with the seperator "/". For instance:
  4558. * /tor/hs/3/publish
  4559. *
  4560. * On success, <b>end_pos</b> points to the position right after the version
  4561. * was found. On error, it is set to NULL.
  4562. *
  4563. * Return version on success else negative value. */
  4564. STATIC int
  4565. parse_hs_version_from_post(const char *url, const char *prefix,
  4566. const char **end_pos)
  4567. {
  4568. int ok;
  4569. unsigned long version;
  4570. const char *start;
  4571. char *end = NULL;
  4572. tor_assert(url);
  4573. tor_assert(prefix);
  4574. tor_assert(end_pos);
  4575. /* Check if the prefix does start the url. */
  4576. if (strcmpstart(url, prefix)) {
  4577. goto err;
  4578. }
  4579. /* Move pointer to the end of the prefix string. */
  4580. start = url + strlen(prefix);
  4581. /* Try this to be the HS version and if we are still at the separator, next
  4582. * will be move to the right value. */
  4583. version = tor_parse_long(start, 10, 0, INT_MAX, &ok, &end);
  4584. if (!ok) {
  4585. goto err;
  4586. }
  4587. *end_pos = end;
  4588. return (int) version;
  4589. err:
  4590. *end_pos = NULL;
  4591. return -1;
  4592. }
  4593. /* Handle the POST request for a hidden service descripror. The request is in
  4594. * <b>url</b>, the body of the request is in <b>body</b>. Return 200 on success
  4595. * else return 400 indicating a bad request. */
  4596. STATIC int
  4597. handle_post_hs_descriptor(const char *url, const char *body)
  4598. {
  4599. int version;
  4600. const char *end_pos;
  4601. tor_assert(url);
  4602. tor_assert(body);
  4603. version = parse_hs_version_from_post(url, "/tor/hs/", &end_pos);
  4604. if (version < 0) {
  4605. goto err;
  4606. }
  4607. /* We have a valid version number, now make sure it's a publish request. Use
  4608. * the end position just after the version and check for the command. */
  4609. if (strcmpstart(end_pos, "/publish")) {
  4610. goto err;
  4611. }
  4612. switch (version) {
  4613. case HS_VERSION_THREE:
  4614. if (hs_cache_store_as_dir(body) < 0) {
  4615. goto err;
  4616. }
  4617. log_info(LD_REND, "Publish request for HS descriptor handled "
  4618. "successfully.");
  4619. break;
  4620. default:
  4621. /* Unsupported version, return a bad request. */
  4622. goto err;
  4623. }
  4624. return 200;
  4625. err:
  4626. /* Bad request. */
  4627. return 400;
  4628. }
  4629. /** Helper function: called when a dirserver gets a complete HTTP POST
  4630. * request. Look for an uploaded server descriptor or rendezvous
  4631. * service descriptor. On finding one, process it and write a
  4632. * response into conn-\>outbuf. If the request is unrecognized, send a
  4633. * 400. Always return 0. */
  4634. MOCK_IMPL(STATIC int,
  4635. directory_handle_command_post,(dir_connection_t *conn, const char *headers,
  4636. const char *body, size_t body_len))
  4637. {
  4638. char *url = NULL;
  4639. const or_options_t *options = get_options();
  4640. log_debug(LD_DIRSERV,"Received POST command.");
  4641. conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
  4642. if (!public_server_mode(options)) {
  4643. log_info(LD_DIR, "Rejected dir post request from %s "
  4644. "since we're not a public relay.", conn->base_.address);
  4645. write_short_http_response(conn, 503, "Not acting as a public relay");
  4646. goto done;
  4647. }
  4648. if (parse_http_url(headers, &url) < 0) {
  4649. write_short_http_response(conn, 400, "Bad request");
  4650. return 0;
  4651. }
  4652. log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
  4653. /* Handle v2 rendezvous service publish request. */
  4654. if (connection_dir_is_encrypted(conn) &&
  4655. !strcmpstart(url,"/tor/rendezvous2/publish")) {
  4656. if (rend_cache_store_v2_desc_as_dir(body) < 0) {
  4657. log_warn(LD_REND, "Rejected v2 rend descriptor (body size %d) from %s.",
  4658. (int)body_len, conn->base_.address);
  4659. write_short_http_response(conn, 400,
  4660. "Invalid v2 service descriptor rejected");
  4661. } else {
  4662. write_short_http_response(conn, 200, "Service descriptor (v2) stored");
  4663. log_info(LD_REND, "Handled v2 rendezvous descriptor post: accepted");
  4664. }
  4665. goto done;
  4666. }
  4667. /* Handle HS descriptor publish request. */
  4668. /* XXX: This should be disabled with a consensus param until we want to
  4669. * the prop224 be deployed and thus use. */
  4670. if (connection_dir_is_encrypted(conn) && !strcmpstart(url, "/tor/hs/")) {
  4671. const char *msg = "HS descriptor stored successfully.";
  4672. /* We most probably have a publish request for an HS descriptor. */
  4673. int code = handle_post_hs_descriptor(url, body);
  4674. if (code != 200) {
  4675. msg = "Invalid HS descriptor. Rejected.";
  4676. }
  4677. write_short_http_response(conn, code, msg);
  4678. goto done;
  4679. }
  4680. if (!authdir_mode(options)) {
  4681. /* we just provide cached directories; we don't want to
  4682. * receive anything. */
  4683. write_short_http_response(conn, 400, "Nonauthoritative directory does not "
  4684. "accept posted server descriptors");
  4685. goto done;
  4686. }
  4687. if (authdir_mode(options) &&
  4688. !strcmp(url,"/tor/")) { /* server descriptor post */
  4689. const char *msg = "[None]";
  4690. uint8_t purpose = authdir_mode_bridge(options) ?
  4691. ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  4692. was_router_added_t r = dirserv_add_multiple_descriptors(body, purpose,
  4693. conn->base_.address, &msg);
  4694. tor_assert(msg);
  4695. if (r == ROUTER_ADDED_SUCCESSFULLY) {
  4696. write_short_http_response(conn, 200, msg);
  4697. } else if (WRA_WAS_OUTDATED(r)) {
  4698. write_http_response_header_impl(conn, -1, NULL, NULL,
  4699. "X-Descriptor-Not-New: Yes\r\n", -1);
  4700. } else {
  4701. log_info(LD_DIRSERV,
  4702. "Rejected router descriptor or extra-info from %s "
  4703. "(\"%s\").",
  4704. conn->base_.address, msg);
  4705. write_short_http_response(conn, 400, msg);
  4706. }
  4707. goto done;
  4708. }
  4709. if (authdir_mode_v3(options) &&
  4710. !strcmp(url,"/tor/post/vote")) { /* v3 networkstatus vote */
  4711. const char *msg = "OK";
  4712. int status;
  4713. if (dirvote_add_vote(body, &msg, &status)) {
  4714. write_short_http_response(conn, status, "Vote stored");
  4715. } else {
  4716. tor_assert(msg);
  4717. log_warn(LD_DIRSERV, "Rejected vote from %s (\"%s\").",
  4718. conn->base_.address, msg);
  4719. write_short_http_response(conn, status, msg);
  4720. }
  4721. goto done;
  4722. }
  4723. if (authdir_mode_v3(options) &&
  4724. !strcmp(url,"/tor/post/consensus-signature")) { /* sigs on consensus. */
  4725. const char *msg = NULL;
  4726. if (dirvote_add_signatures(body, conn->base_.address, &msg)>=0) {
  4727. write_short_http_response(conn, 200, msg?msg:"Signatures stored");
  4728. } else {
  4729. log_warn(LD_DIR, "Unable to store signatures posted by %s: %s",
  4730. conn->base_.address, msg?msg:"???");
  4731. write_short_http_response(conn, 400,
  4732. msg?msg:"Unable to store signatures");
  4733. }
  4734. goto done;
  4735. }
  4736. /* we didn't recognize the url */
  4737. write_short_http_response(conn, 404, "Not found");
  4738. done:
  4739. tor_free(url);
  4740. return 0;
  4741. }
  4742. /** Called when a dirserver receives data on a directory connection;
  4743. * looks for an HTTP request. If the request is complete, remove it
  4744. * from the inbuf, try to process it; otherwise, leave it on the
  4745. * buffer. Return a 0 on success, or -1 on error.
  4746. */
  4747. STATIC int
  4748. directory_handle_command(dir_connection_t *conn)
  4749. {
  4750. char *headers=NULL, *body=NULL;
  4751. size_t body_len=0;
  4752. int r;
  4753. tor_assert(conn);
  4754. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  4755. switch (connection_fetch_from_buf_http(TO_CONN(conn),
  4756. &headers, MAX_HEADERS_SIZE,
  4757. &body, &body_len, MAX_DIR_UL_SIZE, 0)) {
  4758. case -1: /* overflow */
  4759. log_warn(LD_DIRSERV,
  4760. "Request too large from address '%s' to DirPort. Closing.",
  4761. safe_str(conn->base_.address));
  4762. return -1;
  4763. case 0:
  4764. log_debug(LD_DIRSERV,"command not all here yet.");
  4765. return 0;
  4766. /* case 1, fall through */
  4767. }
  4768. http_set_address_origin(headers, TO_CONN(conn));
  4769. // we should escape headers here as well,
  4770. // but we can't call escaped() twice, as it uses the same buffer
  4771. //log_debug(LD_DIRSERV,"headers %s, body %s.", headers, escaped(body));
  4772. if (!strncasecmp(headers,"GET",3))
  4773. r = directory_handle_command_get(conn, headers, body, body_len);
  4774. else if (!strncasecmp(headers,"POST",4))
  4775. r = directory_handle_command_post(conn, headers, body, body_len);
  4776. else {
  4777. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  4778. "Got headers %s with unknown command. Closing.",
  4779. escaped(headers));
  4780. r = -1;
  4781. }
  4782. tor_free(headers); tor_free(body);
  4783. return r;
  4784. }
  4785. /** Write handler for directory connections; called when all data has
  4786. * been flushed. Close the connection or wait for a response as
  4787. * appropriate.
  4788. */
  4789. int
  4790. connection_dir_finished_flushing(dir_connection_t *conn)
  4791. {
  4792. tor_assert(conn);
  4793. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  4794. /* Note that we have finished writing the directory response. For direct
  4795. * connections this means we're done; for tunneled connections it's only
  4796. * an intermediate step. */
  4797. if (conn->dirreq_id)
  4798. geoip_change_dirreq_state(conn->dirreq_id, DIRREQ_TUNNELED,
  4799. DIRREQ_FLUSHING_DIR_CONN_FINISHED);
  4800. else
  4801. geoip_change_dirreq_state(TO_CONN(conn)->global_identifier,
  4802. DIRREQ_DIRECT,
  4803. DIRREQ_FLUSHING_DIR_CONN_FINISHED);
  4804. switch (conn->base_.state) {
  4805. case DIR_CONN_STATE_CONNECTING:
  4806. case DIR_CONN_STATE_CLIENT_SENDING:
  4807. log_debug(LD_DIR,"client finished sending command.");
  4808. conn->base_.state = DIR_CONN_STATE_CLIENT_READING;
  4809. return 0;
  4810. case DIR_CONN_STATE_SERVER_WRITING:
  4811. if (conn->spool) {
  4812. log_warn(LD_BUG, "Emptied a dirserv buffer, but it's still spooling!");
  4813. connection_mark_for_close(TO_CONN(conn));
  4814. } else {
  4815. log_debug(LD_DIRSERV, "Finished writing server response. Closing.");
  4816. connection_mark_for_close(TO_CONN(conn));
  4817. }
  4818. return 0;
  4819. default:
  4820. log_warn(LD_BUG,"called in unexpected state %d.",
  4821. conn->base_.state);
  4822. tor_fragile_assert();
  4823. return -1;
  4824. }
  4825. return 0;
  4826. }
  4827. /* We just got a new consensus! If there are other in-progress requests
  4828. * for this consensus flavor (for example because we launched several in
  4829. * parallel), cancel them.
  4830. *
  4831. * We do this check here (not just in
  4832. * connection_ap_handshake_attach_circuit()) to handle the edge case where
  4833. * a consensus fetch begins and ends before some other one tries to attach to
  4834. * a circuit, in which case the other one won't know that we're all happy now.
  4835. *
  4836. * Don't mark the conn that just gave us the consensus -- otherwise we
  4837. * would end up double-marking it when it cleans itself up.
  4838. */
  4839. static void
  4840. connection_dir_close_consensus_fetches(dir_connection_t *except_this_one,
  4841. const char *resource)
  4842. {
  4843. smartlist_t *conns_to_close =
  4844. connection_dir_list_by_purpose_and_resource(DIR_PURPOSE_FETCH_CONSENSUS,
  4845. resource);
  4846. SMARTLIST_FOREACH_BEGIN(conns_to_close, dir_connection_t *, d) {
  4847. if (d == except_this_one)
  4848. continue;
  4849. log_info(LD_DIR, "Closing consensus fetch (to %s) since one "
  4850. "has just arrived.", TO_CONN(d)->address);
  4851. connection_mark_for_close(TO_CONN(d));
  4852. } SMARTLIST_FOREACH_END(d);
  4853. smartlist_free(conns_to_close);
  4854. }
  4855. /** Connected handler for directory connections: begin sending data to the
  4856. * server, and return 0.
  4857. * Only used when connections don't immediately connect. */
  4858. int
  4859. connection_dir_finished_connecting(dir_connection_t *conn)
  4860. {
  4861. tor_assert(conn);
  4862. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  4863. tor_assert(conn->base_.state == DIR_CONN_STATE_CONNECTING);
  4864. log_debug(LD_HTTP,"Dir connection to router %s:%u established.",
  4865. conn->base_.address,conn->base_.port);
  4866. /* start flushing conn */
  4867. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  4868. return 0;
  4869. }
  4870. /** Decide which download schedule we want to use based on descriptor type
  4871. * in <b>dls</b> and <b>options</b>.
  4872. * Then return a list of int pointers defining download delays in seconds.
  4873. * Helper function for download_status_increment_failure(),
  4874. * download_status_reset(), and download_status_increment_attempt(). */
  4875. STATIC const smartlist_t *
  4876. find_dl_schedule(const download_status_t *dls, const or_options_t *options)
  4877. {
  4878. switch (dls->schedule) {
  4879. case DL_SCHED_GENERIC:
  4880. /* Any other directory document */
  4881. if (dir_server_mode(options)) {
  4882. /* A directory authority or directory mirror */
  4883. return options->TestingServerDownloadSchedule;
  4884. } else {
  4885. return options->TestingClientDownloadSchedule;
  4886. }
  4887. case DL_SCHED_CONSENSUS:
  4888. if (!networkstatus_consensus_can_use_multiple_directories(options)) {
  4889. /* A public relay */
  4890. return options->TestingServerConsensusDownloadSchedule;
  4891. } else {
  4892. /* A client or bridge */
  4893. if (networkstatus_consensus_is_bootstrapping(time(NULL))) {
  4894. /* During bootstrapping */
  4895. if (!networkstatus_consensus_can_use_extra_fallbacks(options)) {
  4896. /* A bootstrapping client without extra fallback directories */
  4897. return
  4898. options->ClientBootstrapConsensusAuthorityOnlyDownloadSchedule;
  4899. } else if (dls->want_authority) {
  4900. /* A bootstrapping client with extra fallback directories, but
  4901. * connecting to an authority */
  4902. return
  4903. options->ClientBootstrapConsensusAuthorityDownloadSchedule;
  4904. } else {
  4905. /* A bootstrapping client connecting to extra fallback directories
  4906. */
  4907. return
  4908. options->ClientBootstrapConsensusFallbackDownloadSchedule;
  4909. }
  4910. } else {
  4911. /* A client with a reasonably live consensus, with or without
  4912. * certificates */
  4913. return options->TestingClientConsensusDownloadSchedule;
  4914. }
  4915. }
  4916. case DL_SCHED_BRIDGE:
  4917. /* A bridge client downloading bridge descriptors */
  4918. if (options->UseBridges && any_bridge_descriptors_known()) {
  4919. /* A bridge client with one or more running bridges */
  4920. return options->TestingBridgeDownloadSchedule;
  4921. } else {
  4922. /* A bridge client with no running bridges */
  4923. return options->TestingBridgeBootstrapDownloadSchedule;
  4924. }
  4925. default:
  4926. tor_assert(0);
  4927. }
  4928. /* Impossible, but gcc will fail with -Werror without a `return`. */
  4929. return NULL;
  4930. }
  4931. /** Decide which minimum and maximum delay step we want to use based on
  4932. * descriptor type in <b>dls</b> and <b>options</b>.
  4933. * Helper function for download_status_schedule_get_delay(). */
  4934. STATIC void
  4935. find_dl_min_and_max_delay(download_status_t *dls, const or_options_t *options,
  4936. int *min, int *max)
  4937. {
  4938. tor_assert(dls);
  4939. tor_assert(options);
  4940. tor_assert(min);
  4941. tor_assert(max);
  4942. /*
  4943. * For now, just use the existing schedule config stuff and pick the
  4944. * first/last entries off to get min/max delay for backoff purposes
  4945. */
  4946. const smartlist_t *schedule = find_dl_schedule(dls, options);
  4947. tor_assert(schedule != NULL && smartlist_len(schedule) >= 2);
  4948. *min = *((int *)(smartlist_get(schedule, 0)));
  4949. /* Increment on failure schedules always use exponential backoff, but they
  4950. * have a smaller limit when they're deterministic */
  4951. if (dls->backoff == DL_SCHED_DETERMINISTIC)
  4952. *max = *((int *)((smartlist_get(schedule, smartlist_len(schedule) - 1))));
  4953. else
  4954. *max = INT_MAX;
  4955. }
  4956. /** Advance one delay step. The algorithm is to use the previous delay to
  4957. * compute an increment, we construct a value uniformly at random between
  4958. * delay+1 and (delay*(DIR_DEFAULT_RANDOM_MULTIPLIER+1))+1 (or
  4959. * DIR_TEST_NET_RANDOM_MULTIPLIER in test networks).
  4960. * We then clamp that value to be no larger than max_delay, and return it.
  4961. *
  4962. * Requires that delay is less than INT_MAX, and delay is in [0,max_delay].
  4963. */
  4964. STATIC int
  4965. next_random_exponential_delay(int delay, int max_delay)
  4966. {
  4967. /* Check preconditions */
  4968. if (BUG(max_delay < 0))
  4969. max_delay = 0;
  4970. if (BUG(delay > max_delay))
  4971. delay = max_delay;
  4972. if (delay == INT_MAX)
  4973. return INT_MAX; /* prevent overflow */
  4974. if (BUG(delay < 0))
  4975. delay = 0;
  4976. /* How much are we willing to add to the delay? */
  4977. int max_increment;
  4978. int multiplier = DIR_DEFAULT_RANDOM_MULTIPLIER;
  4979. if (get_options()->TestingTorNetwork) {
  4980. /* Decrease the multiplier in testing networks. This reduces the variance,
  4981. * so that bootstrap is more reliable. */
  4982. multiplier = DIR_TEST_NET_RANDOM_MULTIPLIER;
  4983. }
  4984. if (delay && delay < (INT_MAX-1) / multiplier) {
  4985. max_increment = delay * multiplier;
  4986. } else if (delay) {
  4987. max_increment = INT_MAX-1;
  4988. } else {
  4989. max_increment = 1;
  4990. }
  4991. if (BUG(max_increment < 1))
  4992. max_increment = 1;
  4993. /* the + 1 here is so that we always wait longer than last time. */
  4994. int increment = crypto_rand_int(max_increment)+1;
  4995. if (increment < max_delay - delay)
  4996. return delay + increment;
  4997. else
  4998. return max_delay;
  4999. }
  5000. /** Find the current delay for dls based on schedule or min_delay/
  5001. * max_delay if we're using exponential backoff. If dls->backoff is
  5002. * DL_SCHED_RANDOM_EXPONENTIAL, we must have 0 <= min_delay <= max_delay <=
  5003. * INT_MAX, but schedule may be set to NULL; otherwise schedule is required.
  5004. * This function sets dls->next_attempt_at based on now, and returns the delay.
  5005. * Helper for download_status_increment_failure and
  5006. * download_status_increment_attempt. */
  5007. STATIC int
  5008. download_status_schedule_get_delay(download_status_t *dls,
  5009. const smartlist_t *schedule,
  5010. int min_delay, int max_delay,
  5011. time_t now)
  5012. {
  5013. tor_assert(dls);
  5014. /* We don't need a schedule if we're using random exponential backoff */
  5015. tor_assert(dls->backoff == DL_SCHED_RANDOM_EXPONENTIAL ||
  5016. schedule != NULL);
  5017. /* If we're using random exponential backoff, we do need min/max delay */
  5018. tor_assert(dls->backoff != DL_SCHED_RANDOM_EXPONENTIAL ||
  5019. (min_delay >= 0 && max_delay >= min_delay));
  5020. int delay = INT_MAX;
  5021. uint8_t dls_schedule_position = (dls->increment_on
  5022. == DL_SCHED_INCREMENT_ATTEMPT
  5023. ? dls->n_download_attempts
  5024. : dls->n_download_failures);
  5025. if (dls->backoff == DL_SCHED_DETERMINISTIC) {
  5026. if (dls_schedule_position < smartlist_len(schedule))
  5027. delay = *(int *)smartlist_get(schedule, dls_schedule_position);
  5028. else if (dls_schedule_position == IMPOSSIBLE_TO_DOWNLOAD)
  5029. delay = INT_MAX;
  5030. else
  5031. delay = *(int *)smartlist_get(schedule, smartlist_len(schedule) - 1);
  5032. } else if (dls->backoff == DL_SCHED_RANDOM_EXPONENTIAL) {
  5033. /* Check if we missed a reset somehow */
  5034. IF_BUG_ONCE(dls->last_backoff_position > dls_schedule_position) {
  5035. dls->last_backoff_position = 0;
  5036. dls->last_delay_used = 0;
  5037. }
  5038. if (dls_schedule_position > 0) {
  5039. delay = dls->last_delay_used;
  5040. while (dls->last_backoff_position < dls_schedule_position) {
  5041. /* Do one increment step */
  5042. delay = next_random_exponential_delay(delay, max_delay);
  5043. /* Update our position */
  5044. ++(dls->last_backoff_position);
  5045. }
  5046. } else {
  5047. /* If we're just starting out, use the minimum delay */
  5048. delay = min_delay;
  5049. }
  5050. /* Clamp it within min/max if we have them */
  5051. if (min_delay >= 0 && delay < min_delay) delay = min_delay;
  5052. if (max_delay != INT_MAX && delay > max_delay) delay = max_delay;
  5053. /* Store it for next time */
  5054. dls->last_backoff_position = dls_schedule_position;
  5055. dls->last_delay_used = delay;
  5056. }
  5057. /* A negative delay makes no sense. Knowing that delay is
  5058. * non-negative allows us to safely do the wrapping check below. */
  5059. tor_assert(delay >= 0);
  5060. /* Avoid now+delay overflowing TIME_MAX, by comparing with a subtraction
  5061. * that won't overflow (since delay is non-negative). */
  5062. if (delay < INT_MAX && now <= TIME_MAX - delay) {
  5063. dls->next_attempt_at = now+delay;
  5064. } else {
  5065. dls->next_attempt_at = TIME_MAX;
  5066. }
  5067. return delay;
  5068. }
  5069. /* Log a debug message about item, which increments on increment_action, has
  5070. * incremented dls_n_download_increments times. The message varies based on
  5071. * was_schedule_incremented (if not, not_incremented_response is logged), and
  5072. * the values of increment, dls_next_attempt_at, and now.
  5073. * Helper for download_status_increment_failure and
  5074. * download_status_increment_attempt. */
  5075. static void
  5076. download_status_log_helper(const char *item, int was_schedule_incremented,
  5077. const char *increment_action,
  5078. const char *not_incremented_response,
  5079. uint8_t dls_n_download_increments, int increment,
  5080. time_t dls_next_attempt_at, time_t now)
  5081. {
  5082. if (item) {
  5083. if (!was_schedule_incremented)
  5084. log_debug(LD_DIR, "%s %s %d time(s); I'll try again %s.",
  5085. item, increment_action, (int)dls_n_download_increments,
  5086. not_incremented_response);
  5087. else if (increment == 0)
  5088. log_debug(LD_DIR, "%s %s %d time(s); I'll try again immediately.",
  5089. item, increment_action, (int)dls_n_download_increments);
  5090. else if (dls_next_attempt_at < TIME_MAX)
  5091. log_debug(LD_DIR, "%s %s %d time(s); I'll try again in %d seconds.",
  5092. item, increment_action, (int)dls_n_download_increments,
  5093. (int)(dls_next_attempt_at-now));
  5094. else
  5095. log_debug(LD_DIR, "%s %s %d time(s); Giving up for a while.",
  5096. item, increment_action, (int)dls_n_download_increments);
  5097. }
  5098. }
  5099. /** Determine when a failed download attempt should be retried.
  5100. * Called when an attempt to download <b>dls</b> has failed with HTTP status
  5101. * <b>status_code</b>. Increment the failure count (if the code indicates a
  5102. * real failure, or if we're a server) and set <b>dls</b>-\>next_attempt_at to
  5103. * an appropriate time in the future and return it.
  5104. * If <b>dls->increment_on</b> is DL_SCHED_INCREMENT_ATTEMPT, increment the
  5105. * failure count, and return a time in the far future for the next attempt (to
  5106. * avoid an immediate retry). */
  5107. time_t
  5108. download_status_increment_failure(download_status_t *dls, int status_code,
  5109. const char *item, int server, time_t now)
  5110. {
  5111. (void) status_code; // XXXX no longer used.
  5112. (void) server; // XXXX no longer used.
  5113. int increment = -1;
  5114. int min_delay = 0, max_delay = INT_MAX;
  5115. tor_assert(dls);
  5116. /* dls wasn't reset before it was used */
  5117. if (dls->next_attempt_at == 0) {
  5118. download_status_reset(dls);
  5119. }
  5120. /* count the failure */
  5121. if (dls->n_download_failures < IMPOSSIBLE_TO_DOWNLOAD-1) {
  5122. ++dls->n_download_failures;
  5123. }
  5124. if (dls->increment_on == DL_SCHED_INCREMENT_FAILURE) {
  5125. /* We don't find out that a failure-based schedule has attempted a
  5126. * connection until that connection fails.
  5127. * We'll never find out about successful connections, but this doesn't
  5128. * matter, because schedules are reset after a successful download.
  5129. */
  5130. if (dls->n_download_attempts < IMPOSSIBLE_TO_DOWNLOAD-1)
  5131. ++dls->n_download_attempts;
  5132. /* only return a failure retry time if this schedule increments on failures
  5133. */
  5134. const smartlist_t *schedule = find_dl_schedule(dls, get_options());
  5135. find_dl_min_and_max_delay(dls, get_options(), &min_delay, &max_delay);
  5136. increment = download_status_schedule_get_delay(dls, schedule,
  5137. min_delay, max_delay, now);
  5138. }
  5139. download_status_log_helper(item, !dls->increment_on, "failed",
  5140. "concurrently", dls->n_download_failures,
  5141. increment,
  5142. download_status_get_next_attempt_at(dls),
  5143. now);
  5144. if (dls->increment_on == DL_SCHED_INCREMENT_ATTEMPT) {
  5145. /* stop this schedule retrying on failure, it will launch concurrent
  5146. * connections instead */
  5147. return TIME_MAX;
  5148. } else {
  5149. return download_status_get_next_attempt_at(dls);
  5150. }
  5151. }
  5152. /** Determine when the next download attempt should be made when using an
  5153. * attempt-based (potentially concurrent) download schedule.
  5154. * Called when an attempt to download <b>dls</b> is being initiated.
  5155. * Increment the attempt count and set <b>dls</b>-\>next_attempt_at to an
  5156. * appropriate time in the future and return it.
  5157. * If <b>dls->increment_on</b> is DL_SCHED_INCREMENT_FAILURE, don't increment
  5158. * the attempts, and return a time in the far future (to avoid launching a
  5159. * concurrent attempt). */
  5160. time_t
  5161. download_status_increment_attempt(download_status_t *dls, const char *item,
  5162. time_t now)
  5163. {
  5164. int delay = -1;
  5165. int min_delay = 0, max_delay = INT_MAX;
  5166. tor_assert(dls);
  5167. /* dls wasn't reset before it was used */
  5168. if (dls->next_attempt_at == 0) {
  5169. download_status_reset(dls);
  5170. }
  5171. if (dls->increment_on == DL_SCHED_INCREMENT_FAILURE) {
  5172. /* this schedule should retry on failure, and not launch any concurrent
  5173. attempts */
  5174. log_warn(LD_BUG, "Tried to launch an attempt-based connection on a "
  5175. "failure-based schedule.");
  5176. return TIME_MAX;
  5177. }
  5178. if (dls->n_download_attempts < IMPOSSIBLE_TO_DOWNLOAD-1)
  5179. ++dls->n_download_attempts;
  5180. const smartlist_t *schedule = find_dl_schedule(dls, get_options());
  5181. find_dl_min_and_max_delay(dls, get_options(), &min_delay, &max_delay);
  5182. delay = download_status_schedule_get_delay(dls, schedule,
  5183. min_delay, max_delay, now);
  5184. download_status_log_helper(item, dls->increment_on, "attempted",
  5185. "on failure", dls->n_download_attempts,
  5186. delay, download_status_get_next_attempt_at(dls),
  5187. now);
  5188. return download_status_get_next_attempt_at(dls);
  5189. }
  5190. static time_t
  5191. download_status_get_initial_delay_from_now(const download_status_t *dls)
  5192. {
  5193. const smartlist_t *schedule = find_dl_schedule(dls, get_options());
  5194. /* We use constant initial delays, even in exponential backoff
  5195. * schedules. */
  5196. return time(NULL) + *(int *)smartlist_get(schedule, 0);
  5197. }
  5198. /** Reset <b>dls</b> so that it will be considered downloadable
  5199. * immediately, and/or to show that we don't need it anymore.
  5200. *
  5201. * Must be called to initialise a download schedule, otherwise the zeroth item
  5202. * in the schedule will never be used.
  5203. *
  5204. * (We find the zeroth element of the download schedule, and set
  5205. * next_attempt_at to be the appropriate offset from 'now'. In most
  5206. * cases this means setting it to 'now', so the item will be immediately
  5207. * downloadable; when using authorities with fallbacks, there is a few seconds'
  5208. * delay.) */
  5209. void
  5210. download_status_reset(download_status_t *dls)
  5211. {
  5212. if (dls->n_download_failures == IMPOSSIBLE_TO_DOWNLOAD
  5213. || dls->n_download_attempts == IMPOSSIBLE_TO_DOWNLOAD)
  5214. return; /* Don't reset this. */
  5215. dls->n_download_failures = 0;
  5216. dls->n_download_attempts = 0;
  5217. dls->next_attempt_at = download_status_get_initial_delay_from_now(dls);
  5218. dls->last_backoff_position = 0;
  5219. dls->last_delay_used = 0;
  5220. /* Don't reset dls->want_authority or dls->increment_on */
  5221. }
  5222. /** Return the number of failures on <b>dls</b> since the last success (if
  5223. * any). */
  5224. int
  5225. download_status_get_n_failures(const download_status_t *dls)
  5226. {
  5227. return dls->n_download_failures;
  5228. }
  5229. /** Return the number of attempts to download <b>dls</b> since the last success
  5230. * (if any). This can differ from download_status_get_n_failures() due to
  5231. * outstanding concurrent attempts. */
  5232. int
  5233. download_status_get_n_attempts(const download_status_t *dls)
  5234. {
  5235. return dls->n_download_attempts;
  5236. }
  5237. /** Return the next time to attempt to download <b>dls</b>. */
  5238. time_t
  5239. download_status_get_next_attempt_at(const download_status_t *dls)
  5240. {
  5241. /* dls wasn't reset before it was used */
  5242. if (dls->next_attempt_at == 0) {
  5243. /* so give the answer we would have given if it had been */
  5244. return download_status_get_initial_delay_from_now(dls);
  5245. }
  5246. return dls->next_attempt_at;
  5247. }
  5248. /** Called when one or more routerdesc (or extrainfo, if <b>was_extrainfo</b>)
  5249. * fetches have failed (with uppercase fingerprints listed in <b>failed</b>,
  5250. * either as descriptor digests or as identity digests based on
  5251. * <b>was_descriptor_digests</b>).
  5252. */
  5253. static void
  5254. dir_routerdesc_download_failed(smartlist_t *failed, int status_code,
  5255. int router_purpose,
  5256. int was_extrainfo, int was_descriptor_digests)
  5257. {
  5258. char digest[DIGEST_LEN];
  5259. time_t now = time(NULL);
  5260. int server = directory_fetches_from_authorities(get_options());
  5261. if (!was_descriptor_digests) {
  5262. if (router_purpose == ROUTER_PURPOSE_BRIDGE) {
  5263. tor_assert(!was_extrainfo);
  5264. connection_dir_retry_bridges(failed);
  5265. }
  5266. return; /* FFFF should implement for other-than-router-purpose someday */
  5267. }
  5268. SMARTLIST_FOREACH_BEGIN(failed, const char *, cp) {
  5269. download_status_t *dls = NULL;
  5270. if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) != DIGEST_LEN) {
  5271. log_warn(LD_BUG, "Malformed fingerprint in list: %s", escaped(cp));
  5272. continue;
  5273. }
  5274. if (was_extrainfo) {
  5275. signed_descriptor_t *sd =
  5276. router_get_by_extrainfo_digest(digest);
  5277. if (sd)
  5278. dls = &sd->ei_dl_status;
  5279. } else {
  5280. dls = router_get_dl_status_by_descriptor_digest(digest);
  5281. }
  5282. if (!dls || dls->n_download_failures >=
  5283. get_options()->TestingDescriptorMaxDownloadTries)
  5284. continue;
  5285. download_status_increment_failure(dls, status_code, cp, server, now);
  5286. } SMARTLIST_FOREACH_END(cp);
  5287. /* No need to relaunch descriptor downloads here: we already do it
  5288. * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  5289. }
  5290. /** Called when a connection to download microdescriptors has failed in whole
  5291. * or in part. <b>failed</b> is a list of every microdesc digest we didn't
  5292. * get. <b>status_code</b> is the http status code we received. Reschedule the
  5293. * microdesc downloads as appropriate. */
  5294. static void
  5295. dir_microdesc_download_failed(smartlist_t *failed,
  5296. int status_code)
  5297. {
  5298. networkstatus_t *consensus
  5299. = networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
  5300. routerstatus_t *rs;
  5301. download_status_t *dls;
  5302. time_t now = time(NULL);
  5303. int server = directory_fetches_from_authorities(get_options());
  5304. if (! consensus)
  5305. return;
  5306. SMARTLIST_FOREACH_BEGIN(failed, const char *, d) {
  5307. rs = router_get_mutable_consensus_status_by_descriptor_digest(consensus,d);
  5308. if (!rs)
  5309. continue;
  5310. dls = &rs->dl_status;
  5311. if (dls->n_download_failures >=
  5312. get_options()->TestingMicrodescMaxDownloadTries)
  5313. continue;
  5314. {
  5315. char buf[BASE64_DIGEST256_LEN+1];
  5316. digest256_to_base64(buf, d);
  5317. download_status_increment_failure(dls, status_code, buf,
  5318. server, now);
  5319. }
  5320. } SMARTLIST_FOREACH_END(d);
  5321. }
  5322. /** Helper. Compare two fp_pair_t objects, and return negative, 0, or
  5323. * positive as appropriate. */
  5324. static int
  5325. compare_pairs_(const void **a, const void **b)
  5326. {
  5327. const fp_pair_t *fp1 = *a, *fp2 = *b;
  5328. int r;
  5329. if ((r = fast_memcmp(fp1->first, fp2->first, DIGEST_LEN)))
  5330. return r;
  5331. else
  5332. return fast_memcmp(fp1->second, fp2->second, DIGEST_LEN);
  5333. }
  5334. /** Divide a string <b>res</b> of the form FP1-FP2+FP3-FP4...[.z], where each
  5335. * FP is a hex-encoded fingerprint, into a sequence of distinct sorted
  5336. * fp_pair_t. Skip malformed pairs. On success, return 0 and add those
  5337. * fp_pair_t into <b>pairs_out</b>. On failure, return -1. */
  5338. int
  5339. dir_split_resource_into_fingerprint_pairs(const char *res,
  5340. smartlist_t *pairs_out)
  5341. {
  5342. smartlist_t *pairs_tmp = smartlist_new();
  5343. smartlist_t *pairs_result = smartlist_new();
  5344. smartlist_split_string(pairs_tmp, res, "+", 0, 0);
  5345. if (smartlist_len(pairs_tmp)) {
  5346. char *last = smartlist_get(pairs_tmp,smartlist_len(pairs_tmp)-1);
  5347. size_t last_len = strlen(last);
  5348. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  5349. last[last_len-2] = '\0';
  5350. }
  5351. }
  5352. SMARTLIST_FOREACH_BEGIN(pairs_tmp, char *, cp) {
  5353. if (strlen(cp) != HEX_DIGEST_LEN*2+1) {
  5354. log_info(LD_DIR,
  5355. "Skipping digest pair %s with non-standard length.", escaped(cp));
  5356. } else if (cp[HEX_DIGEST_LEN] != '-') {
  5357. log_info(LD_DIR,
  5358. "Skipping digest pair %s with missing dash.", escaped(cp));
  5359. } else {
  5360. fp_pair_t pair;
  5361. if (base16_decode(pair.first, DIGEST_LEN,
  5362. cp, HEX_DIGEST_LEN) != DIGEST_LEN ||
  5363. base16_decode(pair.second,DIGEST_LEN,
  5364. cp+HEX_DIGEST_LEN+1, HEX_DIGEST_LEN) != DIGEST_LEN) {
  5365. log_info(LD_DIR, "Skipping non-decodable digest pair %s", escaped(cp));
  5366. } else {
  5367. smartlist_add(pairs_result, tor_memdup(&pair, sizeof(pair)));
  5368. }
  5369. }
  5370. tor_free(cp);
  5371. } SMARTLIST_FOREACH_END(cp);
  5372. smartlist_free(pairs_tmp);
  5373. /* Uniq-and-sort */
  5374. smartlist_sort(pairs_result, compare_pairs_);
  5375. smartlist_uniq(pairs_result, compare_pairs_, tor_free_);
  5376. smartlist_add_all(pairs_out, pairs_result);
  5377. smartlist_free(pairs_result);
  5378. return 0;
  5379. }
  5380. /** Given a directory <b>resource</b> request, containing zero
  5381. * or more strings separated by plus signs, followed optionally by ".z", store
  5382. * the strings, in order, into <b>fp_out</b>. If <b>compressed_out</b> is
  5383. * non-NULL, set it to 1 if the resource ends in ".z", else set it to 0.
  5384. *
  5385. * If (flags & DSR_HEX), then delete all elements that aren't hex digests, and
  5386. * decode the rest. If (flags & DSR_BASE64), then use "-" rather than "+" as
  5387. * a separator, delete all the elements that aren't base64-encoded digests,
  5388. * and decode the rest. If (flags & DSR_DIGEST256), these digests should be
  5389. * 256 bits long; else they should be 160.
  5390. *
  5391. * If (flags & DSR_SORT_UNIQ), then sort the list and remove all duplicates.
  5392. */
  5393. int
  5394. dir_split_resource_into_fingerprints(const char *resource,
  5395. smartlist_t *fp_out, int *compressed_out,
  5396. int flags)
  5397. {
  5398. const int decode_hex = flags & DSR_HEX;
  5399. const int decode_base64 = flags & DSR_BASE64;
  5400. const int digests_are_256 = flags & DSR_DIGEST256;
  5401. const int sort_uniq = flags & DSR_SORT_UNIQ;
  5402. const int digest_len = digests_are_256 ? DIGEST256_LEN : DIGEST_LEN;
  5403. const int hex_digest_len = digests_are_256 ?
  5404. HEX_DIGEST256_LEN : HEX_DIGEST_LEN;
  5405. const int base64_digest_len = digests_are_256 ?
  5406. BASE64_DIGEST256_LEN : BASE64_DIGEST_LEN;
  5407. smartlist_t *fp_tmp = smartlist_new();
  5408. tor_assert(!(decode_hex && decode_base64));
  5409. tor_assert(fp_out);
  5410. smartlist_split_string(fp_tmp, resource, decode_base64?"-":"+", 0, 0);
  5411. if (compressed_out)
  5412. *compressed_out = 0;
  5413. if (smartlist_len(fp_tmp)) {
  5414. char *last = smartlist_get(fp_tmp,smartlist_len(fp_tmp)-1);
  5415. size_t last_len = strlen(last);
  5416. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  5417. last[last_len-2] = '\0';
  5418. if (compressed_out)
  5419. *compressed_out = 1;
  5420. }
  5421. }
  5422. if (decode_hex || decode_base64) {
  5423. const size_t encoded_len = decode_hex ? hex_digest_len : base64_digest_len;
  5424. int i;
  5425. char *cp, *d = NULL;
  5426. for (i = 0; i < smartlist_len(fp_tmp); ++i) {
  5427. cp = smartlist_get(fp_tmp, i);
  5428. if (strlen(cp) != encoded_len) {
  5429. log_info(LD_DIR,
  5430. "Skipping digest %s with non-standard length.", escaped(cp));
  5431. smartlist_del_keeporder(fp_tmp, i--);
  5432. goto again;
  5433. }
  5434. d = tor_malloc_zero(digest_len);
  5435. if (decode_hex ?
  5436. (base16_decode(d, digest_len, cp, hex_digest_len) != digest_len) :
  5437. (base64_decode(d, digest_len, cp, base64_digest_len)
  5438. != digest_len)) {
  5439. log_info(LD_DIR, "Skipping non-decodable digest %s", escaped(cp));
  5440. smartlist_del_keeporder(fp_tmp, i--);
  5441. goto again;
  5442. }
  5443. smartlist_set(fp_tmp, i, d);
  5444. d = NULL;
  5445. again:
  5446. tor_free(cp);
  5447. tor_free(d);
  5448. }
  5449. }
  5450. if (sort_uniq) {
  5451. if (decode_hex || decode_base64) {
  5452. if (digests_are_256) {
  5453. smartlist_sort_digests256(fp_tmp);
  5454. smartlist_uniq_digests256(fp_tmp);
  5455. } else {
  5456. smartlist_sort_digests(fp_tmp);
  5457. smartlist_uniq_digests(fp_tmp);
  5458. }
  5459. } else {
  5460. smartlist_sort_strings(fp_tmp);
  5461. smartlist_uniq_strings(fp_tmp);
  5462. }
  5463. }
  5464. smartlist_add_all(fp_out, fp_tmp);
  5465. smartlist_free(fp_tmp);
  5466. return 0;
  5467. }
  5468. /** As dir_split_resource_into_fingerprints, but instead fills
  5469. * <b>spool_out</b> with a list of spoolable_resource_t for the resource
  5470. * identified through <b>source</b>. */
  5471. int
  5472. dir_split_resource_into_spoolable(const char *resource,
  5473. dir_spool_source_t source,
  5474. smartlist_t *spool_out,
  5475. int *compressed_out,
  5476. int flags)
  5477. {
  5478. smartlist_t *fingerprints = smartlist_new();
  5479. tor_assert(flags & (DSR_HEX|DSR_BASE64));
  5480. const size_t digest_len =
  5481. (flags & DSR_DIGEST256) ? DIGEST256_LEN : DIGEST_LEN;
  5482. int r = dir_split_resource_into_fingerprints(resource, fingerprints,
  5483. compressed_out, flags);
  5484. /* This is not a very efficient implementation XXXX */
  5485. SMARTLIST_FOREACH_BEGIN(fingerprints, uint8_t *, digest) {
  5486. spooled_resource_t *spooled =
  5487. spooled_resource_new(source, digest, digest_len);
  5488. if (spooled)
  5489. smartlist_add(spool_out, spooled);
  5490. tor_free(digest);
  5491. } SMARTLIST_FOREACH_END(digest);
  5492. smartlist_free(fingerprints);
  5493. return r;
  5494. }