directory.c 210 KB

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