directory.c 168 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #define DIRECTORY_PRIVATE
  6. #include "or.h"
  7. #include "backtrace.h"
  8. #include "bridges.h"
  9. #include "buffers.h"
  10. #include "circuitbuild.h"
  11. #include "config.h"
  12. #include "connection.h"
  13. #include "connection_edge.h"
  14. #include "control.h"
  15. #define DIRECTORY_PRIVATE
  16. #include "directory.h"
  17. #include "dirserv.h"
  18. #include "dirvote.h"
  19. #include "entrynodes.h"
  20. #include "geoip.h"
  21. #include "hs_cache.h"
  22. #include "hs_common.h"
  23. #include "main.h"
  24. #include "microdesc.h"
  25. #include "networkstatus.h"
  26. #include "nodelist.h"
  27. #include "policies.h"
  28. #include "relay.h"
  29. #include "rendclient.h"
  30. #include "rendcommon.h"
  31. #include "rendservice.h"
  32. #include "rephist.h"
  33. #include "router.h"
  34. #include "routerlist.h"
  35. #include "routerparse.h"
  36. #include "routerset.h"
  37. #include "shared_random.h"
  38. #if defined(EXPORTMALLINFO) && defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
  39. #if !defined(OpenBSD)
  40. #include <malloc.h>
  41. #endif
  42. #endif
  43. /**
  44. * \file directory.c
  45. * \brief Code to send and fetch information from directory authorities and
  46. * caches via HTTP.
  47. *
  48. * Directory caches and authorities use dirserv.c to generate the results of a
  49. * query and stream them to the connection; clients use routerparse.c to parse
  50. * them.
  51. *
  52. * Every directory request has a dir_connection_t on the client side and on
  53. * the server side. In most cases, the dir_connection_t object is a linked
  54. * connection, tunneled through an edge_connection_t so that it can be a
  55. * stream on the Tor network. The only non-tunneled connections are those
  56. * that are used to upload material (descriptors and votes) to authorities.
  57. * Among tunneled connections, some use one-hop circuits, and others use
  58. * multi-hop circuits for anonymity.
  59. *
  60. * Directory requests are launched by calling
  61. * directory_initiate_command_rend() or one of its numerous variants. This
  62. * launch the connection, will construct an HTTP request with
  63. * directory_send_command(), send the and wait for a response. The client
  64. * later handles the response with connection_dir_client_reached_eof(),
  65. * which passes the information received to another part of Tor.
  66. *
  67. * On the server side, requests are read in directory_handle_command(),
  68. * which dispatches first on the request type (GET or POST), and then on
  69. * the URL requested. GET requests are processed with a table-based
  70. * dispatcher in url_table[]. The process of handling larger GET requests
  71. * is complicated because we need to avoid allocating a copy of all the
  72. * data to be sent to the client in one huge buffer. Instead, we spool the
  73. * data into the buffer using logic in connection_dirserv_flushed_some() in
  74. * dirserv.c. (TODO: If we extended buf.c to have a zero-copy
  75. * reference-based buffer type, we could remove most of that code, at the
  76. * cost of a bit more reference counting.)
  77. **/
  78. /* In-points to directory.c:
  79. *
  80. * - directory_post_to_dirservers(), called from
  81. * router_upload_dir_desc_to_dirservers() in router.c
  82. * upload_service_descriptor() in rendservice.c
  83. * - directory_get_from_dirserver(), called from
  84. * rend_client_refetch_renddesc() in rendclient.c
  85. * run_scheduled_events() in main.c
  86. * do_hup() in main.c
  87. * - connection_dir_process_inbuf(), called from
  88. * connection_process_inbuf() in connection.c
  89. * - connection_dir_finished_flushing(), called from
  90. * connection_finished_flushing() in connection.c
  91. * - connection_dir_finished_connecting(), called from
  92. * connection_finished_connecting() in connection.c
  93. */
  94. static void directory_send_command(dir_connection_t *conn,
  95. int purpose, int direct, const char *resource,
  96. const char *payload, size_t payload_len,
  97. time_t if_modified_since);
  98. static int body_is_plausible(const char *body, size_t body_len, int purpose);
  99. static char *http_get_header(const char *headers, const char *which);
  100. static void http_set_address_origin(const char *headers, connection_t *conn);
  101. static void connection_dir_download_routerdesc_failed(dir_connection_t *conn);
  102. static void connection_dir_bridge_routerdesc_failed(dir_connection_t *conn);
  103. static void connection_dir_download_cert_failed(
  104. dir_connection_t *conn, int status_code);
  105. static void connection_dir_retry_bridges(smartlist_t *descs);
  106. static void dir_routerdesc_download_failed(smartlist_t *failed,
  107. int status_code,
  108. int router_purpose,
  109. int was_extrainfo,
  110. int was_descriptor_digests);
  111. static void dir_microdesc_download_failed(smartlist_t *failed,
  112. int status_code);
  113. static int client_likes_consensus(networkstatus_t *v, const char *want_url);
  114. static void directory_initiate_command_rend(
  115. const tor_addr_port_t *or_addr_port,
  116. const tor_addr_port_t *dir_addr_port,
  117. const char *digest,
  118. uint8_t dir_purpose,
  119. uint8_t router_purpose,
  120. dir_indirection_t indirection,
  121. const char *resource,
  122. const char *payload,
  123. size_t payload_len,
  124. time_t if_modified_since,
  125. const rend_data_t *rend_query,
  126. circuit_guard_state_t *guard_state);
  127. static void connection_dir_close_consensus_fetches(
  128. dir_connection_t *except_this_one, const char *resource);
  129. /********* START VARIABLES **********/
  130. /** How far in the future do we allow a directory server to tell us it is
  131. * before deciding that one of us has the wrong time? */
  132. #define ALLOW_DIRECTORY_TIME_SKEW (30*60)
  133. #define X_ADDRESS_HEADER "X-Your-Address-Is: "
  134. /** HTTP cache control: how long do we tell proxies they can cache each
  135. * kind of document we serve? */
  136. #define FULL_DIR_CACHE_LIFETIME (60*60)
  137. #define RUNNINGROUTERS_CACHE_LIFETIME (20*60)
  138. #define DIRPORTFRONTPAGE_CACHE_LIFETIME (20*60)
  139. #define NETWORKSTATUS_CACHE_LIFETIME (5*60)
  140. #define ROUTERDESC_CACHE_LIFETIME (30*60)
  141. #define ROUTERDESC_BY_DIGEST_CACHE_LIFETIME (48*60*60)
  142. #define ROBOTS_CACHE_LIFETIME (24*60*60)
  143. #define MICRODESC_CACHE_LIFETIME (48*60*60)
  144. /********* END VARIABLES ************/
  145. /** Return false if the directory purpose <b>dir_purpose</b>
  146. * does not require an anonymous (three-hop) connection.
  147. *
  148. * Return true 1) by default, 2) if all directory actions have
  149. * specifically been configured to be over an anonymous connection,
  150. * or 3) if the router is a bridge */
  151. int
  152. purpose_needs_anonymity(uint8_t dir_purpose, uint8_t router_purpose,
  153. const char *resource)
  154. {
  155. if (get_options()->AllDirActionsPrivate)
  156. return 1;
  157. if (router_purpose == ROUTER_PURPOSE_BRIDGE) {
  158. if (dir_purpose == DIR_PURPOSE_FETCH_SERVERDESC
  159. && resource && !strcmp(resource, "authority.z")) {
  160. /* We are asking a bridge for its own descriptor. That doesn't need
  161. anonymity. */
  162. return 0;
  163. }
  164. /* Assume all other bridge stuff needs anonymity. */
  165. return 1; /* if no circuits yet, this might break bootstrapping, but it's
  166. * needed to be safe. */
  167. }
  168. switch (dir_purpose)
  169. {
  170. case DIR_PURPOSE_UPLOAD_DIR:
  171. case DIR_PURPOSE_UPLOAD_VOTE:
  172. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  173. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  174. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  175. case DIR_PURPOSE_FETCH_CONSENSUS:
  176. case DIR_PURPOSE_FETCH_CERTIFICATE:
  177. case DIR_PURPOSE_FETCH_SERVERDESC:
  178. case DIR_PURPOSE_FETCH_EXTRAINFO:
  179. case DIR_PURPOSE_FETCH_MICRODESC:
  180. return 0;
  181. case DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2:
  182. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  183. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  184. return 1;
  185. case DIR_PURPOSE_SERVER:
  186. default:
  187. log_warn(LD_BUG, "Called with dir_purpose=%d, router_purpose=%d",
  188. dir_purpose, router_purpose);
  189. tor_assert_nonfatal_unreached();
  190. return 1; /* Assume it needs anonymity; better safe than sorry. */
  191. }
  192. }
  193. /** Return a newly allocated string describing <b>auth</b>. Only describes
  194. * authority features. */
  195. STATIC char *
  196. authdir_type_to_string(dirinfo_type_t auth)
  197. {
  198. char *result;
  199. smartlist_t *lst = smartlist_new();
  200. if (auth & V3_DIRINFO)
  201. smartlist_add(lst, (void*)"V3");
  202. if (auth & BRIDGE_DIRINFO)
  203. smartlist_add(lst, (void*)"Bridge");
  204. if (smartlist_len(lst)) {
  205. result = smartlist_join_strings(lst, ", ", 0, NULL);
  206. } else {
  207. result = tor_strdup("[Not an authority]");
  208. }
  209. smartlist_free(lst);
  210. return result;
  211. }
  212. /** Return a string describing a given directory connection purpose. */
  213. STATIC const char *
  214. dir_conn_purpose_to_string(int purpose)
  215. {
  216. switch (purpose)
  217. {
  218. case DIR_PURPOSE_UPLOAD_DIR:
  219. return "server descriptor upload";
  220. case DIR_PURPOSE_UPLOAD_VOTE:
  221. return "server vote upload";
  222. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  223. return "consensus signature upload";
  224. case DIR_PURPOSE_FETCH_SERVERDESC:
  225. return "server descriptor fetch";
  226. case DIR_PURPOSE_FETCH_EXTRAINFO:
  227. return "extra-info fetch";
  228. case DIR_PURPOSE_FETCH_CONSENSUS:
  229. return "consensus network-status fetch";
  230. case DIR_PURPOSE_FETCH_CERTIFICATE:
  231. return "authority cert fetch";
  232. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  233. return "status vote fetch";
  234. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  235. return "consensus signature fetch";
  236. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  237. return "hidden-service v2 descriptor fetch";
  238. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  239. return "hidden-service v2 descriptor upload";
  240. case DIR_PURPOSE_FETCH_MICRODESC:
  241. return "microdescriptor fetch";
  242. }
  243. log_warn(LD_BUG, "Called with unknown purpose %d", purpose);
  244. return "(unknown)";
  245. }
  246. /** Return the requisite directory information types. */
  247. STATIC dirinfo_type_t
  248. dir_fetch_type(int dir_purpose, int router_purpose, const char *resource)
  249. {
  250. dirinfo_type_t type;
  251. switch (dir_purpose) {
  252. case DIR_PURPOSE_FETCH_EXTRAINFO:
  253. type = EXTRAINFO_DIRINFO;
  254. if (router_purpose == ROUTER_PURPOSE_BRIDGE)
  255. type |= BRIDGE_DIRINFO;
  256. else
  257. type |= V3_DIRINFO;
  258. break;
  259. case DIR_PURPOSE_FETCH_SERVERDESC:
  260. if (router_purpose == ROUTER_PURPOSE_BRIDGE)
  261. type = BRIDGE_DIRINFO;
  262. else
  263. type = V3_DIRINFO;
  264. break;
  265. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  266. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  267. case DIR_PURPOSE_FETCH_CERTIFICATE:
  268. type = V3_DIRINFO;
  269. break;
  270. case DIR_PURPOSE_FETCH_CONSENSUS:
  271. type = V3_DIRINFO;
  272. if (resource && !strcmp(resource, "microdesc"))
  273. type |= MICRODESC_DIRINFO;
  274. break;
  275. case DIR_PURPOSE_FETCH_MICRODESC:
  276. type = MICRODESC_DIRINFO;
  277. break;
  278. default:
  279. log_warn(LD_BUG, "Unexpected purpose %d", (int)dir_purpose);
  280. type = NO_DIRINFO;
  281. break;
  282. }
  283. return type;
  284. }
  285. /** Return true iff <b>identity_digest</b> is the digest of a router which
  286. * says that it caches extrainfos. (If <b>is_authority</b> we always
  287. * believe that to be true.) */
  288. int
  289. router_supports_extrainfo(const char *identity_digest, int is_authority)
  290. {
  291. const node_t *node = node_get_by_id(identity_digest);
  292. if (node && node->ri) {
  293. if (node->ri->caches_extra_info)
  294. return 1;
  295. }
  296. if (is_authority) {
  297. return 1;
  298. }
  299. return 0;
  300. }
  301. /** Return true iff any trusted directory authority has accepted our
  302. * server descriptor.
  303. *
  304. * We consider any authority sufficient because waiting for all of
  305. * them means it never happens while any authority is down; we don't
  306. * go for something more complex in the middle (like \>1/3 or \>1/2 or
  307. * \>=1/2) because that doesn't seem necessary yet.
  308. */
  309. int
  310. directories_have_accepted_server_descriptor(void)
  311. {
  312. const smartlist_t *servers = router_get_trusted_dir_servers();
  313. const or_options_t *options = get_options();
  314. SMARTLIST_FOREACH(servers, dir_server_t *, d, {
  315. if ((d->type & options->PublishServerDescriptor_) &&
  316. d->has_accepted_serverdesc) {
  317. return 1;
  318. }
  319. });
  320. return 0;
  321. }
  322. /** Start a connection to every suitable directory authority, using
  323. * connection purpose <b>dir_purpose</b> and uploading <b>payload</b>
  324. * (of length <b>payload_len</b>). The dir_purpose should be one of
  325. * 'DIR_PURPOSE_UPLOAD_{DIR|VOTE|SIGNATURES}'.
  326. *
  327. * <b>router_purpose</b> describes the type of descriptor we're
  328. * publishing, if we're publishing a descriptor -- e.g. general or bridge.
  329. *
  330. * <b>type</b> specifies what sort of dir authorities (V3,
  331. * BRIDGE, etc) we should upload to.
  332. *
  333. * If <b>extrainfo_len</b> is nonzero, the first <b>payload_len</b> bytes of
  334. * <b>payload</b> hold a router descriptor, and the next <b>extrainfo_len</b>
  335. * bytes of <b>payload</b> hold an extra-info document. Upload the descriptor
  336. * to all authorities, and the extra-info document to all authorities that
  337. * support it.
  338. */
  339. void
  340. directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose,
  341. dirinfo_type_t type,
  342. const char *payload,
  343. size_t payload_len, size_t extrainfo_len)
  344. {
  345. const or_options_t *options = get_options();
  346. dir_indirection_t indirection;
  347. const smartlist_t *dirservers = router_get_trusted_dir_servers();
  348. int found = 0;
  349. const int exclude_self = (dir_purpose == DIR_PURPOSE_UPLOAD_VOTE ||
  350. dir_purpose == DIR_PURPOSE_UPLOAD_SIGNATURES);
  351. tor_assert(dirservers);
  352. /* This tries dirservers which we believe to be down, but ultimately, that's
  353. * harmless, and we may as well err on the side of getting things uploaded.
  354. */
  355. SMARTLIST_FOREACH_BEGIN(dirservers, dir_server_t *, ds) {
  356. routerstatus_t *rs = &(ds->fake_status);
  357. size_t upload_len = payload_len;
  358. if ((type & ds->type) == 0)
  359. continue;
  360. if (exclude_self && router_digest_is_me(ds->digest)) {
  361. /* we don't upload to ourselves, but at least there's now at least
  362. * one authority of this type that has what we wanted to upload. */
  363. found = 1;
  364. continue;
  365. }
  366. if (options->StrictNodes &&
  367. routerset_contains_routerstatus(options->ExcludeNodes, rs, -1)) {
  368. log_warn(LD_DIR, "Wanted to contact authority '%s' for %s, but "
  369. "it's in our ExcludedNodes list and StrictNodes is set. "
  370. "Skipping.",
  371. ds->nickname,
  372. dir_conn_purpose_to_string(dir_purpose));
  373. continue;
  374. }
  375. found = 1; /* at least one authority of this type was listed */
  376. if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR)
  377. ds->has_accepted_serverdesc = 0;
  378. if (extrainfo_len && router_supports_extrainfo(ds->digest, 1)) {
  379. upload_len += extrainfo_len;
  380. log_info(LD_DIR, "Uploading an extrainfo too (length %d)",
  381. (int) extrainfo_len);
  382. }
  383. if (purpose_needs_anonymity(dir_purpose, router_purpose, NULL)) {
  384. indirection = DIRIND_ANONYMOUS;
  385. } else if (!fascist_firewall_allows_dir_server(ds,
  386. FIREWALL_DIR_CONNECTION,
  387. 0)) {
  388. if (fascist_firewall_allows_dir_server(ds, FIREWALL_OR_CONNECTION, 0))
  389. indirection = DIRIND_ONEHOP;
  390. else
  391. indirection = DIRIND_ANONYMOUS;
  392. } else {
  393. indirection = DIRIND_DIRECT_CONN;
  394. }
  395. directory_initiate_command_routerstatus(rs, dir_purpose,
  396. router_purpose,
  397. indirection,
  398. NULL, payload, upload_len, 0,
  399. NULL);
  400. } SMARTLIST_FOREACH_END(ds);
  401. if (!found) {
  402. char *s = authdir_type_to_string(type);
  403. log_warn(LD_DIR, "Publishing server descriptor to directory authorities "
  404. "of type '%s', but no authorities of that type listed!", s);
  405. tor_free(s);
  406. }
  407. }
  408. /** Return true iff, according to the values in <b>options</b>, we should be
  409. * using directory guards for direct downloads of directory information. */
  410. STATIC int
  411. should_use_directory_guards(const or_options_t *options)
  412. {
  413. /* Public (non-bridge) servers never use directory guards. */
  414. if (public_server_mode(options))
  415. return 0;
  416. /* If guards are disabled, we can't use directory guards.
  417. */
  418. if (!options->UseEntryGuards)
  419. return 0;
  420. /* If we're configured to fetch directory info aggressively or of a
  421. * nonstandard type, don't use directory guards. */
  422. if (options->DownloadExtraInfo || options->FetchDirInfoEarly ||
  423. options->FetchDirInfoExtraEarly || options->FetchUselessDescriptors)
  424. return 0;
  425. return 1;
  426. }
  427. /** Pick an unconstrained directory server from among our guards, the latest
  428. * networkstatus, or the fallback dirservers, for use in downloading
  429. * information of type <b>type</b>, and return its routerstatus. */
  430. static const routerstatus_t *
  431. directory_pick_generic_dirserver(dirinfo_type_t type, int pds_flags,
  432. uint8_t dir_purpose,
  433. circuit_guard_state_t **guard_state_out)
  434. {
  435. const routerstatus_t *rs = NULL;
  436. const or_options_t *options = get_options();
  437. if (options->UseBridges)
  438. log_warn(LD_BUG, "Called when we have UseBridges set.");
  439. if (should_use_directory_guards(options)) {
  440. const node_t *node = guards_choose_dirguard(guard_state_out);
  441. if (node)
  442. rs = node->rs;
  443. } else {
  444. /* anybody with a non-zero dirport will do */
  445. rs = router_pick_directory_server(type, pds_flags);
  446. }
  447. if (!rs) {
  448. log_info(LD_DIR, "No router found for %s; falling back to "
  449. "dirserver list.", dir_conn_purpose_to_string(dir_purpose));
  450. rs = router_pick_fallback_dirserver(type, pds_flags);
  451. }
  452. return rs;
  453. }
  454. /** Start a connection to a random running directory server, using
  455. * connection purpose <b>dir_purpose</b>, intending to fetch descriptors
  456. * of purpose <b>router_purpose</b>, and requesting <b>resource</b>.
  457. * Use <b>pds_flags</b> as arguments to router_pick_directory_server()
  458. * or router_pick_trusteddirserver().
  459. */
  460. MOCK_IMPL(void, directory_get_from_dirserver, (
  461. uint8_t dir_purpose,
  462. uint8_t router_purpose,
  463. const char *resource,
  464. int pds_flags,
  465. download_want_authority_t want_authority))
  466. {
  467. const routerstatus_t *rs = NULL;
  468. const or_options_t *options = get_options();
  469. int prefer_authority = (directory_fetches_from_authorities(options)
  470. || want_authority == DL_WANT_AUTHORITY);
  471. int require_authority = 0;
  472. int get_via_tor = purpose_needs_anonymity(dir_purpose, router_purpose,
  473. resource);
  474. dirinfo_type_t type = dir_fetch_type(dir_purpose, router_purpose, resource);
  475. time_t if_modified_since = 0;
  476. if (type == NO_DIRINFO)
  477. return;
  478. if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  479. int flav = FLAV_NS;
  480. networkstatus_t *v;
  481. if (resource)
  482. flav = networkstatus_parse_flavor_name(resource);
  483. /* DEFAULT_IF_MODIFIED_SINCE_DELAY is 1/20 of the default consensus
  484. * period of 1 hour.
  485. */
  486. #define DEFAULT_IF_MODIFIED_SINCE_DELAY (180)
  487. if (flav != -1) {
  488. /* IF we have a parsed consensus of this type, we can do an
  489. * if-modified-time based on it. */
  490. v = networkstatus_get_latest_consensus_by_flavor(flav);
  491. if (v) {
  492. /* In networks with particularly short V3AuthVotingIntervals,
  493. * ask for the consensus if it's been modified since half the
  494. * V3AuthVotingInterval of the most recent consensus. */
  495. time_t ims_delay = DEFAULT_IF_MODIFIED_SINCE_DELAY;
  496. if (v->fresh_until > v->valid_after
  497. && ims_delay > (v->fresh_until - v->valid_after)/2) {
  498. ims_delay = (v->fresh_until - v->valid_after)/2;
  499. }
  500. if_modified_since = v->valid_after + ims_delay;
  501. }
  502. } else {
  503. /* Otherwise it might be a consensus we don't parse, but which we
  504. * do cache. Look at the cached copy, perhaps. */
  505. cached_dir_t *cd = dirserv_get_consensus(resource);
  506. /* We have no method of determining the voting interval from an
  507. * unparsed consensus, so we use the default. */
  508. if (cd)
  509. if_modified_since = cd->published + DEFAULT_IF_MODIFIED_SINCE_DELAY;
  510. }
  511. }
  512. if (!options->FetchServerDescriptors)
  513. return;
  514. circuit_guard_state_t *guard_state = NULL;
  515. if (!get_via_tor) {
  516. if (options->UseBridges && !(type & BRIDGE_DIRINFO)) {
  517. /* We want to ask a running bridge for which we have a descriptor.
  518. *
  519. * When we ask choose_random_entry() for a bridge, we specify what
  520. * sort of dir fetch we'll be doing, so it won't return a bridge
  521. * that can't answer our question.
  522. */
  523. const node_t *node = guards_choose_dirguard(&guard_state);
  524. if (node && node->ri) {
  525. /* every bridge has a routerinfo. */
  526. routerinfo_t *ri = node->ri;
  527. /* clients always make OR connections to bridges */
  528. tor_addr_port_t or_ap;
  529. tor_addr_port_t nil_dir_ap;
  530. /* we are willing to use a non-preferred address if we need to */
  531. fascist_firewall_choose_address_node(node, FIREWALL_OR_CONNECTION, 0,
  532. &or_ap);
  533. tor_addr_make_null(&nil_dir_ap.addr, AF_INET);
  534. nil_dir_ap.port = 0;
  535. directory_initiate_command_rend(&or_ap,
  536. &nil_dir_ap,
  537. ri->cache_info.identity_digest,
  538. dir_purpose,
  539. router_purpose,
  540. DIRIND_ONEHOP,
  541. resource, NULL, 0, if_modified_since,
  542. NULL, guard_state);
  543. } else {
  544. if (guard_state) {
  545. entry_guard_cancel(&guard_state);
  546. }
  547. log_notice(LD_DIR, "Ignoring directory request, since no bridge "
  548. "nodes are available yet.");
  549. }
  550. return;
  551. } else {
  552. if (prefer_authority || (type & BRIDGE_DIRINFO)) {
  553. /* only ask authdirservers, and don't ask myself */
  554. rs = router_pick_trusteddirserver(type, pds_flags);
  555. if (rs == NULL && (pds_flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  556. PDS_NO_EXISTING_MICRODESC_FETCH))) {
  557. /* We don't want to fetch from any authorities that we're currently
  558. * fetching server descriptors from, and we got no match. Did we
  559. * get no match because all the authorities have connections
  560. * fetching server descriptors (in which case we should just
  561. * return,) or because all the authorities are down or on fire or
  562. * unreachable or something (in which case we should go on with
  563. * our fallback code)? */
  564. pds_flags &= ~(PDS_NO_EXISTING_SERVERDESC_FETCH|
  565. PDS_NO_EXISTING_MICRODESC_FETCH);
  566. rs = router_pick_trusteddirserver(type, pds_flags);
  567. if (rs) {
  568. log_debug(LD_DIR, "Deferring serverdesc fetch: all authorities "
  569. "are in use.");
  570. return;
  571. }
  572. }
  573. if (rs == NULL && require_authority) {
  574. log_info(LD_DIR, "No authorities were available for %s: will try "
  575. "later.", dir_conn_purpose_to_string(dir_purpose));
  576. return;
  577. }
  578. }
  579. if (!rs && !(type & BRIDGE_DIRINFO)) {
  580. rs = directory_pick_generic_dirserver(type, pds_flags,
  581. dir_purpose,
  582. &guard_state);
  583. if (!rs)
  584. get_via_tor = 1; /* last resort: try routing it via Tor */
  585. }
  586. }
  587. }
  588. if (get_via_tor) {
  589. /* Never use fascistfirewall; we're going via Tor. */
  590. pds_flags |= PDS_IGNORE_FASCISTFIREWALL;
  591. rs = router_pick_directory_server(type, pds_flags);
  592. }
  593. /* If we have any hope of building an indirect conn, we know some router
  594. * descriptors. If (rs==NULL), we can't build circuits anyway, so
  595. * there's no point in falling back to the authorities in this case. */
  596. if (rs) {
  597. const dir_indirection_t indirection =
  598. get_via_tor ? DIRIND_ANONYMOUS : DIRIND_ONEHOP;
  599. directory_initiate_command_routerstatus(rs, dir_purpose,
  600. router_purpose,
  601. indirection,
  602. resource, NULL, 0,
  603. if_modified_since,
  604. guard_state);
  605. } else {
  606. log_notice(LD_DIR,
  607. "While fetching directory info, "
  608. "no running dirservers known. Will try again later. "
  609. "(purpose %d)", dir_purpose);
  610. if (!purpose_needs_anonymity(dir_purpose, router_purpose, resource)) {
  611. /* remember we tried them all and failed. */
  612. directory_all_unreachable(time(NULL));
  613. }
  614. }
  615. }
  616. /** As directory_get_from_dirserver, but initiates a request to <i>every</i>
  617. * directory authority other than ourself. Only for use by authorities when
  618. * searching for missing information while voting. */
  619. void
  620. directory_get_from_all_authorities(uint8_t dir_purpose,
  621. uint8_t router_purpose,
  622. const char *resource)
  623. {
  624. tor_assert(dir_purpose == DIR_PURPOSE_FETCH_STATUS_VOTE ||
  625. dir_purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES);
  626. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  627. dir_server_t *, ds) {
  628. routerstatus_t *rs;
  629. if (router_digest_is_me(ds->digest))
  630. continue;
  631. if (!(ds->type & V3_DIRINFO))
  632. continue;
  633. rs = &ds->fake_status;
  634. directory_initiate_command_routerstatus(rs, dir_purpose, router_purpose,
  635. DIRIND_ONEHOP, resource, NULL,
  636. 0, 0, NULL);
  637. } SMARTLIST_FOREACH_END(ds);
  638. }
  639. /** Return true iff <b>ind</b> requires a multihop circuit. */
  640. static int
  641. dirind_is_anon(dir_indirection_t ind)
  642. {
  643. return ind == DIRIND_ANON_DIRPORT || ind == DIRIND_ANONYMOUS;
  644. }
  645. /* Choose reachable OR and Dir addresses and ports from status, copying them
  646. * into use_or_ap and use_dir_ap. If indirection is anonymous, then we're
  647. * connecting via another relay, so choose the primary IPv4 address and ports.
  648. *
  649. * status should have at least one reachable address, if we can't choose a
  650. * reachable address, warn and return -1. Otherwise, return 0.
  651. */
  652. static int
  653. directory_choose_address_routerstatus(const routerstatus_t *status,
  654. dir_indirection_t indirection,
  655. tor_addr_port_t *use_or_ap,
  656. tor_addr_port_t *use_dir_ap)
  657. {
  658. tor_assert(status != NULL);
  659. tor_assert(use_or_ap != NULL);
  660. tor_assert(use_dir_ap != NULL);
  661. const or_options_t *options = get_options();
  662. int have_or = 0, have_dir = 0;
  663. /* We expect status to have at least one reachable address if we're
  664. * connecting to it directly.
  665. *
  666. * Therefore, we can simply use the other address if the one we want isn't
  667. * allowed by the firewall.
  668. *
  669. * (When Tor uploads and downloads a hidden service descriptor, it uses
  670. * DIRIND_ANONYMOUS, except for Tor2Web, which uses DIRIND_ONEHOP.
  671. * So this code will only modify the address for Tor2Web's HS descriptor
  672. * fetches. Even Single Onion Servers (NYI) use DIRIND_ANONYMOUS, to avoid
  673. * HSDirs denying service by rejecting descriptors.)
  674. */
  675. /* Initialise the OR / Dir addresses */
  676. tor_addr_make_null(&use_or_ap->addr, AF_UNSPEC);
  677. use_or_ap->port = 0;
  678. tor_addr_make_null(&use_dir_ap->addr, AF_UNSPEC);
  679. use_dir_ap->port = 0;
  680. /* ORPort connections */
  681. if (indirection == DIRIND_ANONYMOUS) {
  682. if (status->addr) {
  683. /* Since we're going to build a 3-hop circuit and ask the 2nd relay
  684. * to extend to this address, always use the primary (IPv4) OR address */
  685. tor_addr_from_ipv4h(&use_or_ap->addr, status->addr);
  686. use_or_ap->port = status->or_port;
  687. have_or = 1;
  688. }
  689. } else if (indirection == DIRIND_ONEHOP) {
  690. /* We use an IPv6 address if we have one and we prefer it.
  691. * Use the preferred address and port if they are reachable, otherwise,
  692. * use the alternate address and port (if any).
  693. */
  694. have_or = fascist_firewall_choose_address_rs(status,
  695. FIREWALL_OR_CONNECTION, 0,
  696. use_or_ap);
  697. }
  698. /* DirPort connections
  699. * DIRIND_ONEHOP uses ORPort, but may fall back to the DirPort on relays */
  700. if (indirection == DIRIND_DIRECT_CONN ||
  701. indirection == DIRIND_ANON_DIRPORT ||
  702. (indirection == DIRIND_ONEHOP
  703. && !directory_must_use_begindir(options))) {
  704. have_dir = fascist_firewall_choose_address_rs(status,
  705. FIREWALL_DIR_CONNECTION, 0,
  706. use_dir_ap);
  707. }
  708. /* We rejected all addresses in the relay's status. This means we can't
  709. * connect to it. */
  710. if (!have_or && !have_dir) {
  711. static int logged_backtrace = 0;
  712. log_info(LD_BUG, "Rejected all OR and Dir addresses from %s when "
  713. "launching an outgoing directory connection to: IPv4 %s OR %d "
  714. "Dir %d IPv6 %s OR %d Dir %d", routerstatus_describe(status),
  715. fmt_addr32(status->addr), status->or_port,
  716. status->dir_port, fmt_addr(&status->ipv6_addr),
  717. status->ipv6_orport, status->dir_port);
  718. if (!logged_backtrace) {
  719. log_backtrace(LOG_INFO, LD_BUG, "Addresses came from");
  720. logged_backtrace = 1;
  721. }
  722. return -1;
  723. }
  724. return 0;
  725. }
  726. /** Same as directory_initiate_command_routerstatus(), but accepts
  727. * rendezvous data to fetch a hidden service descriptor. */
  728. void
  729. directory_initiate_command_routerstatus_rend(const routerstatus_t *status,
  730. uint8_t dir_purpose,
  731. uint8_t router_purpose,
  732. dir_indirection_t indirection,
  733. const char *resource,
  734. const char *payload,
  735. size_t payload_len,
  736. time_t if_modified_since,
  737. const rend_data_t *rend_query,
  738. circuit_guard_state_t *guard_state)
  739. {
  740. const or_options_t *options = get_options();
  741. const node_t *node;
  742. tor_addr_port_t use_or_ap, use_dir_ap;
  743. const int anonymized_connection = dirind_is_anon(indirection);
  744. tor_assert(status != NULL);
  745. node = node_get_by_id(status->identity_digest);
  746. /* XXX The below check is wrong: !node means it's not in the consensus,
  747. * but we haven't checked if we have a descriptor for it -- and also,
  748. * we only care about the descriptor if it's a begindir-style anonymized
  749. * connection. */
  750. if (!node && anonymized_connection) {
  751. log_info(LD_DIR, "Not sending anonymized request to directory '%s'; we "
  752. "don't have its router descriptor.",
  753. routerstatus_describe(status));
  754. return;
  755. }
  756. if (options->ExcludeNodes && options->StrictNodes &&
  757. routerset_contains_routerstatus(options->ExcludeNodes, status, -1)) {
  758. log_warn(LD_DIR, "Wanted to contact directory mirror %s for %s, but "
  759. "it's in our ExcludedNodes list and StrictNodes is set. "
  760. "Skipping. This choice might make your Tor not work.",
  761. routerstatus_describe(status),
  762. dir_conn_purpose_to_string(dir_purpose));
  763. return;
  764. }
  765. /* At this point, if we are a client making a direct connection to a
  766. * directory server, we have selected a server that has at least one address
  767. * allowed by ClientUseIPv4/6 and Reachable{"",OR,Dir}Addresses. This
  768. * selection uses the preference in ClientPreferIPv6{OR,Dir}Port, if
  769. * possible. (If UseBridges is set, clients always use IPv6, and prefer it
  770. * by default.)
  771. *
  772. * Now choose an address that we can use to connect to the directory server.
  773. */
  774. if (directory_choose_address_routerstatus(status, indirection, &use_or_ap,
  775. &use_dir_ap) < 0) {
  776. return;
  777. }
  778. /* We don't retry the alternate OR/Dir address for the same directory if
  779. * the address we choose fails (#6772).
  780. * Instead, we'll retry another directory on failure. */
  781. directory_initiate_command_rend(&use_or_ap, &use_dir_ap,
  782. status->identity_digest,
  783. dir_purpose, router_purpose,
  784. indirection, resource,
  785. payload, payload_len, if_modified_since,
  786. rend_query,
  787. guard_state);
  788. }
  789. /** Launch a new connection to the directory server <b>status</b> to
  790. * upload or download a server or rendezvous
  791. * descriptor. <b>dir_purpose</b> determines what
  792. * kind of directory connection we're launching, and must be one of
  793. * DIR_PURPOSE_{FETCH|UPLOAD}_{DIR|RENDDESC_V2}. <b>router_purpose</b>
  794. * specifies the descriptor purposes we have in mind (currently only
  795. * used for FETCH_DIR).
  796. *
  797. * When uploading, <b>payload</b> and <b>payload_len</b> determine the content
  798. * of the HTTP post. Otherwise, <b>payload</b> should be NULL.
  799. *
  800. * When fetching a rendezvous descriptor, <b>resource</b> is the service ID we
  801. * want to fetch.
  802. */
  803. MOCK_IMPL(void, directory_initiate_command_routerstatus,
  804. (const routerstatus_t *status,
  805. uint8_t dir_purpose,
  806. uint8_t router_purpose,
  807. dir_indirection_t indirection,
  808. const char *resource,
  809. const char *payload,
  810. size_t payload_len,
  811. time_t if_modified_since,
  812. circuit_guard_state_t *guard_state))
  813. {
  814. directory_initiate_command_routerstatus_rend(status, dir_purpose,
  815. router_purpose,
  816. indirection, resource,
  817. payload, payload_len,
  818. if_modified_since, NULL,
  819. guard_state);
  820. }
  821. /** Return true iff <b>conn</b> is the client side of a directory connection
  822. * we launched to ourself in order to determine the reachability of our
  823. * dir_port. */
  824. static int
  825. directory_conn_is_self_reachability_test(dir_connection_t *conn)
  826. {
  827. if (conn->requested_resource &&
  828. !strcmpstart(conn->requested_resource,"authority")) {
  829. const routerinfo_t *me = router_get_my_routerinfo();
  830. if (me &&
  831. router_digest_is_me(conn->identity_digest) &&
  832. tor_addr_eq_ipv4h(&conn->base_.addr, me->addr) && /*XXXX prop 118*/
  833. me->dir_port == conn->base_.port)
  834. return 1;
  835. }
  836. return 0;
  837. }
  838. /** Called when we are unable to complete the client's request to a directory
  839. * server due to a network error: Mark the router as down and try again if
  840. * possible.
  841. */
  842. static void
  843. connection_dir_request_failed(dir_connection_t *conn)
  844. {
  845. if (conn->guard_state) {
  846. /* We haven't seen a success on this guard state, so consider it to have
  847. * failed. */
  848. entry_guard_failed(&conn->guard_state);
  849. }
  850. if (directory_conn_is_self_reachability_test(conn)) {
  851. return; /* this was a test fetch. don't retry. */
  852. }
  853. if (!entry_list_is_constrained(get_options()))
  854. router_set_status(conn->identity_digest, 0); /* don't try this one again */
  855. if (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  856. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
  857. log_info(LD_DIR, "Giving up on serverdesc/extrainfo fetch from "
  858. "directory server at '%s'; retrying",
  859. conn->base_.address);
  860. if (conn->router_purpose == ROUTER_PURPOSE_BRIDGE)
  861. connection_dir_bridge_routerdesc_failed(conn);
  862. connection_dir_download_routerdesc_failed(conn);
  863. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  864. if (conn->requested_resource)
  865. networkstatus_consensus_download_failed(0, conn->requested_resource);
  866. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
  867. log_info(LD_DIR, "Giving up on certificate fetch from directory server "
  868. "at '%s'; retrying",
  869. conn->base_.address);
  870. connection_dir_download_cert_failed(conn, 0);
  871. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
  872. log_info(LD_DIR, "Giving up downloading detached signatures from '%s'",
  873. conn->base_.address);
  874. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
  875. log_info(LD_DIR, "Giving up downloading votes from '%s'",
  876. conn->base_.address);
  877. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  878. log_info(LD_DIR, "Giving up on downloading microdescriptors from "
  879. "directory server at '%s'; will retry", conn->base_.address);
  880. connection_dir_download_routerdesc_failed(conn);
  881. }
  882. }
  883. /** Helper: Attempt to fetch directly the descriptors of each bridge
  884. * listed in <b>failed</b>.
  885. */
  886. static void
  887. connection_dir_retry_bridges(smartlist_t *descs)
  888. {
  889. char digest[DIGEST_LEN];
  890. SMARTLIST_FOREACH(descs, const char *, cp,
  891. {
  892. if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) != DIGEST_LEN) {
  893. log_warn(LD_BUG, "Malformed fingerprint in list: %s",
  894. escaped(cp));
  895. continue;
  896. }
  897. retry_bridge_descriptor_fetch_directly(digest);
  898. });
  899. }
  900. /** Called when an attempt to download one or more router descriptors
  901. * or extra-info documents on connection <b>conn</b> failed.
  902. */
  903. static void
  904. connection_dir_download_routerdesc_failed(dir_connection_t *conn)
  905. {
  906. /* No need to increment the failure count for routerdescs, since
  907. * it's not their fault. */
  908. /* No need to relaunch descriptor downloads here: we already do it
  909. * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  910. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  911. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  912. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  913. (void) conn;
  914. }
  915. /** Called when an attempt to download a bridge's routerdesc from
  916. * one of the authorities failed due to a network error. If
  917. * possible attempt to download descriptors from the bridge directly.
  918. */
  919. static void
  920. connection_dir_bridge_routerdesc_failed(dir_connection_t *conn)
  921. {
  922. smartlist_t *which = NULL;
  923. /* Requests for bridge descriptors are in the form 'fp/', so ignore
  924. anything else. */
  925. if (!conn->requested_resource || strcmpstart(conn->requested_resource,"fp/"))
  926. return;
  927. which = smartlist_new();
  928. dir_split_resource_into_fingerprints(conn->requested_resource
  929. + strlen("fp/"),
  930. which, NULL, 0);
  931. tor_assert(conn->base_.purpose != DIR_PURPOSE_FETCH_EXTRAINFO);
  932. if (smartlist_len(which)) {
  933. connection_dir_retry_bridges(which);
  934. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  935. }
  936. smartlist_free(which);
  937. }
  938. /** Called when an attempt to fetch a certificate fails. */
  939. static void
  940. connection_dir_download_cert_failed(dir_connection_t *conn, int status)
  941. {
  942. const char *fp_pfx = "fp/";
  943. const char *fpsk_pfx = "fp-sk/";
  944. smartlist_t *failed;
  945. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE);
  946. if (!conn->requested_resource)
  947. return;
  948. failed = smartlist_new();
  949. /*
  950. * We have two cases download by fingerprint (resource starts
  951. * with "fp/") or download by fingerprint/signing key pair
  952. * (resource starts with "fp-sk/").
  953. */
  954. if (!strcmpstart(conn->requested_resource, fp_pfx)) {
  955. /* Download by fingerprint case */
  956. dir_split_resource_into_fingerprints(conn->requested_resource +
  957. strlen(fp_pfx),
  958. failed, NULL, DSR_HEX);
  959. SMARTLIST_FOREACH_BEGIN(failed, char *, cp) {
  960. /* Null signing key digest indicates download by fp only */
  961. authority_cert_dl_failed(cp, NULL, status);
  962. tor_free(cp);
  963. } SMARTLIST_FOREACH_END(cp);
  964. } else if (!strcmpstart(conn->requested_resource, fpsk_pfx)) {
  965. /* Download by (fp,sk) pairs */
  966. dir_split_resource_into_fingerprint_pairs(conn->requested_resource +
  967. strlen(fpsk_pfx), failed);
  968. SMARTLIST_FOREACH_BEGIN(failed, fp_pair_t *, cp) {
  969. authority_cert_dl_failed(cp->first, cp->second, status);
  970. tor_free(cp);
  971. } SMARTLIST_FOREACH_END(cp);
  972. } else {
  973. log_warn(LD_DIR,
  974. "Don't know what to do with failure for cert fetch %s",
  975. conn->requested_resource);
  976. }
  977. smartlist_free(failed);
  978. update_certificate_downloads(time(NULL));
  979. }
  980. /* Should this tor instance only use begindir for all its directory requests?
  981. */
  982. int
  983. directory_must_use_begindir(const or_options_t *options)
  984. {
  985. /* Clients, onion services, and bridges must use begindir,
  986. * relays and authorities do not have to */
  987. return !public_server_mode(options);
  988. }
  989. /** Evaluate the situation and decide if we should use an encrypted
  990. * "begindir-style" connection for this directory request.
  991. * 1) If or_port is 0, or it's a direct conn and or_port is firewalled
  992. * or we're a dir mirror, no.
  993. * 2) If we prefer to avoid begindir conns, and we're not fetching or
  994. * publishing a bridge relay descriptor, no.
  995. * 3) Else yes.
  996. * If returning 0, return in *reason why we can't use begindir.
  997. * reason must not be NULL.
  998. */
  999. static int
  1000. directory_command_should_use_begindir(const or_options_t *options,
  1001. const tor_addr_t *addr,
  1002. int or_port, uint8_t router_purpose,
  1003. dir_indirection_t indirection,
  1004. const char **reason)
  1005. {
  1006. (void) router_purpose;
  1007. tor_assert(reason);
  1008. *reason = NULL;
  1009. /* Reasons why we can't possibly use begindir */
  1010. if (!or_port) {
  1011. *reason = "directory with unknown ORPort";
  1012. return 0; /* We don't know an ORPort -- no chance. */
  1013. }
  1014. if (indirection == DIRIND_DIRECT_CONN ||
  1015. indirection == DIRIND_ANON_DIRPORT) {
  1016. *reason = "DirPort connection";
  1017. return 0;
  1018. }
  1019. if (indirection == DIRIND_ONEHOP) {
  1020. /* We're firewalled and want a direct OR connection */
  1021. if (!fascist_firewall_allows_address_addr(addr, or_port,
  1022. FIREWALL_OR_CONNECTION, 0, 0)) {
  1023. *reason = "ORPort not reachable";
  1024. return 0;
  1025. }
  1026. }
  1027. /* Reasons why we want to avoid using begindir */
  1028. if (indirection == DIRIND_ONEHOP) {
  1029. if (!directory_must_use_begindir(options)) {
  1030. *reason = "in relay mode";
  1031. return 0;
  1032. }
  1033. }
  1034. /* DIRIND_ONEHOP on a client, or DIRIND_ANONYMOUS
  1035. */
  1036. *reason = "(using begindir)";
  1037. return 1;
  1038. }
  1039. /** Helper for directory_initiate_command_rend: send the
  1040. * command to a server whose OR address/port is <b>or_addr</b>/<b>or_port</b>,
  1041. * whose directory address/port is <b>dir_addr</b>/<b>dir_port</b>, whose
  1042. * identity key digest is <b>digest</b>, with purposes <b>dir_purpose</b> and
  1043. * <b>router_purpose</b>, making an (in)direct connection as specified in
  1044. * <b>indirection</b>, with command <b>resource</b>, <b>payload</b> of
  1045. * <b>payload_len</b>, and asking for a result only <b>if_modified_since</b>.
  1046. */
  1047. void
  1048. directory_initiate_command(const tor_addr_t *or_addr, uint16_t or_port,
  1049. const tor_addr_t *dir_addr, uint16_t dir_port,
  1050. const char *digest,
  1051. uint8_t dir_purpose, uint8_t router_purpose,
  1052. dir_indirection_t indirection, const char *resource,
  1053. const char *payload, size_t payload_len,
  1054. time_t if_modified_since)
  1055. {
  1056. tor_addr_port_t or_ap, dir_ap;
  1057. /* Use the null tor_addr and 0 port if the address or port isn't valid. */
  1058. if (tor_addr_port_is_valid(or_addr, or_port, 0)) {
  1059. tor_addr_copy(&or_ap.addr, or_addr);
  1060. or_ap.port = or_port;
  1061. } else {
  1062. /* the family doesn't matter here, so make it IPv4 */
  1063. tor_addr_make_null(&or_ap.addr, AF_INET);
  1064. or_ap.port = or_port = 0;
  1065. }
  1066. if (tor_addr_port_is_valid(dir_addr, dir_port, 0)) {
  1067. tor_addr_copy(&dir_ap.addr, dir_addr);
  1068. dir_ap.port = dir_port;
  1069. } else {
  1070. /* the family doesn't matter here, so make it IPv4 */
  1071. tor_addr_make_null(&dir_ap.addr, AF_INET);
  1072. dir_ap.port = dir_port = 0;
  1073. }
  1074. directory_initiate_command_rend(&or_ap, &dir_ap,
  1075. digest, dir_purpose,
  1076. router_purpose, indirection,
  1077. resource, payload, payload_len,
  1078. if_modified_since, NULL, NULL);
  1079. }
  1080. /** Same as directory_initiate_command(), but accepts rendezvous data to
  1081. * fetch a hidden service descriptor, and takes its address & port arguments
  1082. * as tor_addr_port_t. */
  1083. static void
  1084. directory_initiate_command_rend(const tor_addr_port_t *or_addr_port,
  1085. const tor_addr_port_t *dir_addr_port,
  1086. const char *digest,
  1087. uint8_t dir_purpose, uint8_t router_purpose,
  1088. dir_indirection_t indirection,
  1089. const char *resource,
  1090. const char *payload, size_t payload_len,
  1091. time_t if_modified_since,
  1092. const rend_data_t *rend_query,
  1093. circuit_guard_state_t *guard_state)
  1094. {
  1095. tor_assert(or_addr_port);
  1096. tor_assert(dir_addr_port);
  1097. tor_assert(or_addr_port->port || dir_addr_port->port);
  1098. tor_assert(digest);
  1099. dir_connection_t *conn;
  1100. const or_options_t *options = get_options();
  1101. int socket_error = 0;
  1102. const char *begindir_reason = NULL;
  1103. /* Should the connection be to a relay's OR port (and inside that we will
  1104. * send our directory request)? */
  1105. const int use_begindir = directory_command_should_use_begindir(options,
  1106. &or_addr_port->addr, or_addr_port->port,
  1107. router_purpose, indirection,
  1108. &begindir_reason);
  1109. /* Will the connection go via a three-hop Tor circuit? Note that this
  1110. * is separate from whether it will use_begindir. */
  1111. const int anonymized_connection = dirind_is_anon(indirection);
  1112. /* What is the address we want to make the directory request to? If
  1113. * we're making a begindir request this is the ORPort of the relay
  1114. * we're contacting; if not a begindir request, this is its DirPort.
  1115. * Note that if anonymized_connection is true, we won't be initiating
  1116. * a connection directly to this address. */
  1117. tor_addr_t addr;
  1118. tor_addr_copy(&addr, &(use_begindir ? or_addr_port : dir_addr_port)->addr);
  1119. uint16_t port = (use_begindir ? or_addr_port : dir_addr_port)->port;
  1120. log_debug(LD_DIR, "anonymized %d, use_begindir %d.",
  1121. anonymized_connection, use_begindir);
  1122. log_debug(LD_DIR, "Initiating %s", dir_conn_purpose_to_string(dir_purpose));
  1123. if (purpose_needs_anonymity(dir_purpose, router_purpose, resource)) {
  1124. tor_assert(anonymized_connection ||
  1125. rend_non_anonymous_mode_enabled(options));
  1126. }
  1127. /* use encrypted begindir connections for everything except relays
  1128. * this provides better protection for directory fetches */
  1129. if (!use_begindir && directory_must_use_begindir(options)) {
  1130. log_warn(LD_BUG, "Client could not use begindir connection: %s",
  1131. begindir_reason ? begindir_reason : "(NULL)");
  1132. return;
  1133. }
  1134. /* ensure that we don't make direct connections when a SOCKS server is
  1135. * configured. */
  1136. if (!anonymized_connection && !use_begindir && !options->HTTPProxy &&
  1137. (options->Socks4Proxy || options->Socks5Proxy)) {
  1138. log_warn(LD_DIR, "Cannot connect to a directory server through a "
  1139. "SOCKS proxy!");
  1140. return;
  1141. }
  1142. /* Make sure that the destination addr and port we picked is viable. */
  1143. if (!port || tor_addr_is_null(&addr)) {
  1144. static int logged_backtrace = 0;
  1145. log_warn(LD_DIR,
  1146. "Cannot make an outgoing %sconnection without %sPort.",
  1147. use_begindir ? "begindir " : "",
  1148. use_begindir ? "an OR" : "a Dir");
  1149. if (!logged_backtrace) {
  1150. log_backtrace(LOG_INFO, LD_BUG, "Address came from");
  1151. logged_backtrace = 1;
  1152. }
  1153. return;
  1154. }
  1155. conn = dir_connection_new(tor_addr_family(&addr));
  1156. /* set up conn so it's got all the data we need to remember */
  1157. tor_addr_copy(&conn->base_.addr, &addr);
  1158. conn->base_.port = port;
  1159. conn->base_.address = tor_addr_to_str_dup(&addr);
  1160. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  1161. conn->base_.purpose = dir_purpose;
  1162. conn->router_purpose = router_purpose;
  1163. /* give it an initial state */
  1164. conn->base_.state = DIR_CONN_STATE_CONNECTING;
  1165. /* decide whether we can learn our IP address from this conn */
  1166. /* XXXX This is a bad name for this field now. */
  1167. conn->dirconn_direct = !anonymized_connection;
  1168. /* copy rendezvous data, if any */
  1169. if (rend_query)
  1170. conn->rend_data = rend_data_dup(rend_query);
  1171. if (!anonymized_connection && !use_begindir) {
  1172. /* then we want to connect to dirport directly */
  1173. // XXXX prop271 I think that we never use guards in this case.
  1174. if (options->HTTPProxy) {
  1175. tor_addr_copy(&addr, &options->HTTPProxyAddr);
  1176. port = options->HTTPProxyPort;
  1177. }
  1178. // In this case we should not have picked a directory guard.
  1179. if (BUG(guard_state)) {
  1180. entry_guard_cancel(&guard_state);
  1181. }
  1182. switch (connection_connect(TO_CONN(conn), conn->base_.address, &addr,
  1183. port, &socket_error)) {
  1184. case -1:
  1185. connection_mark_for_close(TO_CONN(conn));
  1186. return;
  1187. case 1:
  1188. /* start flushing conn */
  1189. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  1190. /* fall through */
  1191. case 0:
  1192. /* queue the command on the outbuf */
  1193. directory_send_command(conn, dir_purpose, 1, resource,
  1194. payload, payload_len,
  1195. if_modified_since);
  1196. connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
  1197. /* writable indicates finish, readable indicates broken link,
  1198. error indicates broken link in windowsland. */
  1199. }
  1200. } else {
  1201. /* We will use a Tor circuit (maybe 1-hop, maybe 3-hop, maybe with
  1202. * begindir, maybe not with begindir) */
  1203. entry_connection_t *linked_conn;
  1204. /* Anonymized tunneled connections can never share a circuit.
  1205. * One-hop directory connections can share circuits with each other
  1206. * but nothing else. */
  1207. int iso_flags = anonymized_connection ? ISO_STREAM : ISO_SESSIONGRP;
  1208. /* If it's an anonymized connection, remember the fact that we
  1209. * wanted it for later: maybe we'll want it again soon. */
  1210. if (anonymized_connection && use_begindir)
  1211. rep_hist_note_used_internal(time(NULL), 0, 1);
  1212. else if (anonymized_connection && !use_begindir)
  1213. rep_hist_note_used_port(time(NULL), conn->base_.port);
  1214. // In this case we should not have a directory guard; we'll
  1215. // get a regular guard later when we build the circuit.
  1216. if (BUG(anonymized_connection && guard_state)) {
  1217. entry_guard_cancel(&guard_state);
  1218. }
  1219. conn->guard_state = guard_state;
  1220. /* make an AP connection
  1221. * populate it and add it at the right state
  1222. * hook up both sides
  1223. */
  1224. linked_conn =
  1225. connection_ap_make_link(TO_CONN(conn),
  1226. conn->base_.address, conn->base_.port,
  1227. digest,
  1228. SESSION_GROUP_DIRCONN, iso_flags,
  1229. use_begindir, !anonymized_connection);
  1230. if (!linked_conn) {
  1231. log_warn(LD_NET,"Making tunnel to dirserver failed.");
  1232. connection_mark_for_close(TO_CONN(conn));
  1233. return;
  1234. }
  1235. if (connection_add(TO_CONN(conn)) < 0) {
  1236. log_warn(LD_NET,"Unable to add connection for link to dirserver.");
  1237. connection_mark_for_close(TO_CONN(conn));
  1238. return;
  1239. }
  1240. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  1241. /* queue the command on the outbuf */
  1242. directory_send_command(conn, dir_purpose, 0, resource,
  1243. payload, payload_len,
  1244. if_modified_since);
  1245. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  1246. connection_start_reading(ENTRY_TO_CONN(linked_conn));
  1247. }
  1248. }
  1249. /** Return true iff anything we say on <b>conn</b> is being encrypted before
  1250. * we send it to the client/server. */
  1251. int
  1252. connection_dir_is_encrypted(dir_connection_t *conn)
  1253. {
  1254. /* Right now it's sufficient to see if conn is or has been linked, since
  1255. * the only thing it could be linked to is an edge connection on a
  1256. * circuit, and the only way it could have been unlinked is at the edge
  1257. * connection getting closed.
  1258. */
  1259. return TO_CONN(conn)->linked;
  1260. }
  1261. /** Helper for sorting
  1262. *
  1263. * sort strings alphabetically
  1264. */
  1265. static int
  1266. compare_strs_(const void **a, const void **b)
  1267. {
  1268. const char *s1 = *a, *s2 = *b;
  1269. return strcmp(s1, s2);
  1270. }
  1271. #define CONDITIONAL_CONSENSUS_FPR_LEN 3
  1272. #if (CONDITIONAL_CONSENSUS_FPR_LEN > DIGEST_LEN)
  1273. #error "conditional consensus fingerprint length is larger than digest length"
  1274. #endif
  1275. /** Return the URL we should use for a consensus download.
  1276. *
  1277. * Use the "conditional consensus downloading" feature described in
  1278. * dir-spec.txt, i.e.
  1279. * GET .../consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>
  1280. *
  1281. * If 'resource' is provided, it is the name of a consensus flavor to request.
  1282. */
  1283. static char *
  1284. directory_get_consensus_url(const char *resource)
  1285. {
  1286. char *url = NULL;
  1287. const char *hyphen, *flavor;
  1288. if (resource==NULL || strcmp(resource, "ns")==0) {
  1289. flavor = ""; /* Request ns consensuses as "", so older servers will work*/
  1290. hyphen = "";
  1291. } else {
  1292. flavor = resource;
  1293. hyphen = "-";
  1294. }
  1295. {
  1296. char *authority_id_list;
  1297. smartlist_t *authority_digests = smartlist_new();
  1298. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  1299. dir_server_t *, ds) {
  1300. char *hex;
  1301. if (!(ds->type & V3_DIRINFO))
  1302. continue;
  1303. hex = tor_malloc(2*CONDITIONAL_CONSENSUS_FPR_LEN+1);
  1304. base16_encode(hex, 2*CONDITIONAL_CONSENSUS_FPR_LEN+1,
  1305. ds->v3_identity_digest, CONDITIONAL_CONSENSUS_FPR_LEN);
  1306. smartlist_add(authority_digests, hex);
  1307. } SMARTLIST_FOREACH_END(ds);
  1308. smartlist_sort(authority_digests, compare_strs_);
  1309. authority_id_list = smartlist_join_strings(authority_digests,
  1310. "+", 0, NULL);
  1311. tor_asprintf(&url, "/tor/status-vote/current/consensus%s%s/%s.z",
  1312. hyphen, flavor, authority_id_list);
  1313. SMARTLIST_FOREACH(authority_digests, char *, cp, tor_free(cp));
  1314. smartlist_free(authority_digests);
  1315. tor_free(authority_id_list);
  1316. }
  1317. return url;
  1318. }
  1319. /**
  1320. * Copies the ipv6 from source to destination, subject to buffer size limit
  1321. * size. If decorate is true, makes sure the copied address is decorated.
  1322. */
  1323. static void
  1324. copy_ipv6_address(char* destination, const char* source, size_t len,
  1325. int decorate) {
  1326. tor_assert(destination);
  1327. tor_assert(source);
  1328. if (decorate && source[0] != '[') {
  1329. tor_snprintf(destination, len, "[%s]", source);
  1330. } else {
  1331. strlcpy(destination, source, len);
  1332. }
  1333. }
  1334. /** Queue an appropriate HTTP command on conn-\>outbuf. The other args
  1335. * are as in directory_initiate_command().
  1336. */
  1337. static void
  1338. directory_send_command(dir_connection_t *conn,
  1339. int purpose, int direct, const char *resource,
  1340. const char *payload, size_t payload_len,
  1341. time_t if_modified_since)
  1342. {
  1343. char proxystring[256];
  1344. char hoststring[128];
  1345. /* NEEDS to be the same size hoststring.
  1346. Will be decorated with brackets around it if it is ipv6. */
  1347. char decorated_address[128];
  1348. smartlist_t *headers = smartlist_new();
  1349. char *url;
  1350. char request[8192];
  1351. const char *httpcommand = NULL;
  1352. tor_assert(conn);
  1353. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  1354. tor_free(conn->requested_resource);
  1355. if (resource)
  1356. conn->requested_resource = tor_strdup(resource);
  1357. /* decorate the ip address if it is ipv6 */
  1358. if (strchr(conn->base_.address, ':')) {
  1359. copy_ipv6_address(decorated_address, conn->base_.address,
  1360. sizeof(decorated_address), 1);
  1361. } else {
  1362. strlcpy(decorated_address, conn->base_.address, sizeof(decorated_address));
  1363. }
  1364. /* come up with a string for which Host: we want */
  1365. if (conn->base_.port == 80) {
  1366. strlcpy(hoststring, decorated_address, sizeof(hoststring));
  1367. } else {
  1368. tor_snprintf(hoststring, sizeof(hoststring), "%s:%d",
  1369. decorated_address, conn->base_.port);
  1370. }
  1371. /* Format if-modified-since */
  1372. if (if_modified_since) {
  1373. char b[RFC1123_TIME_LEN+1];
  1374. format_rfc1123_time(b, if_modified_since);
  1375. smartlist_add_asprintf(headers, "If-Modified-Since: %s\r\n", b);
  1376. }
  1377. /* come up with some proxy lines, if we're using one. */
  1378. if (direct && get_options()->HTTPProxy) {
  1379. char *base64_authenticator=NULL;
  1380. const char *authenticator = get_options()->HTTPProxyAuthenticator;
  1381. tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  1382. if (authenticator) {
  1383. base64_authenticator = alloc_http_authenticator(authenticator);
  1384. if (!base64_authenticator)
  1385. log_warn(LD_BUG, "Encoding http authenticator failed");
  1386. }
  1387. if (base64_authenticator) {
  1388. smartlist_add_asprintf(headers,
  1389. "Proxy-Authorization: Basic %s\r\n",
  1390. base64_authenticator);
  1391. tor_free(base64_authenticator);
  1392. }
  1393. } else {
  1394. proxystring[0] = 0;
  1395. }
  1396. switch (purpose) {
  1397. case DIR_PURPOSE_FETCH_CONSENSUS:
  1398. /* resource is optional. If present, it's a flavor name */
  1399. tor_assert(!payload);
  1400. httpcommand = "GET";
  1401. url = directory_get_consensus_url(resource);
  1402. log_info(LD_DIR, "Downloading consensus from %s using %s",
  1403. hoststring, url);
  1404. break;
  1405. case DIR_PURPOSE_FETCH_CERTIFICATE:
  1406. tor_assert(resource);
  1407. tor_assert(!payload);
  1408. httpcommand = "GET";
  1409. tor_asprintf(&url, "/tor/keys/%s", resource);
  1410. break;
  1411. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  1412. tor_assert(resource);
  1413. tor_assert(!payload);
  1414. httpcommand = "GET";
  1415. tor_asprintf(&url, "/tor/status-vote/next/%s.z", resource);
  1416. break;
  1417. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  1418. tor_assert(!resource);
  1419. tor_assert(!payload);
  1420. httpcommand = "GET";
  1421. url = tor_strdup("/tor/status-vote/next/consensus-signatures.z");
  1422. break;
  1423. case DIR_PURPOSE_FETCH_SERVERDESC:
  1424. tor_assert(resource);
  1425. httpcommand = "GET";
  1426. tor_asprintf(&url, "/tor/server/%s", resource);
  1427. break;
  1428. case DIR_PURPOSE_FETCH_EXTRAINFO:
  1429. tor_assert(resource);
  1430. httpcommand = "GET";
  1431. tor_asprintf(&url, "/tor/extra/%s", resource);
  1432. break;
  1433. case DIR_PURPOSE_FETCH_MICRODESC:
  1434. tor_assert(resource);
  1435. httpcommand = "GET";
  1436. tor_asprintf(&url, "/tor/micro/%s", resource);
  1437. break;
  1438. case DIR_PURPOSE_UPLOAD_DIR: {
  1439. const char *why = router_get_descriptor_gen_reason();
  1440. tor_assert(!resource);
  1441. tor_assert(payload);
  1442. httpcommand = "POST";
  1443. url = tor_strdup("/tor/");
  1444. if (why) {
  1445. smartlist_add_asprintf(headers, "X-Desc-Gen-Reason: %s\r\n", why);
  1446. }
  1447. break;
  1448. }
  1449. case DIR_PURPOSE_UPLOAD_VOTE:
  1450. tor_assert(!resource);
  1451. tor_assert(payload);
  1452. httpcommand = "POST";
  1453. url = tor_strdup("/tor/post/vote");
  1454. break;
  1455. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  1456. tor_assert(!resource);
  1457. tor_assert(payload);
  1458. httpcommand = "POST";
  1459. url = tor_strdup("/tor/post/consensus-signature");
  1460. break;
  1461. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  1462. tor_assert(resource);
  1463. tor_assert(strlen(resource) <= REND_DESC_ID_V2_LEN_BASE32);
  1464. tor_assert(!payload);
  1465. httpcommand = "GET";
  1466. tor_asprintf(&url, "/tor/rendezvous2/%s", resource);
  1467. break;
  1468. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  1469. tor_assert(!resource);
  1470. tor_assert(payload);
  1471. httpcommand = "POST";
  1472. url = tor_strdup("/tor/rendezvous2/publish");
  1473. break;
  1474. default:
  1475. tor_assert(0);
  1476. return;
  1477. }
  1478. /* warn in the non-tunneled case */
  1479. if (direct && (strlen(proxystring) + strlen(url) >= 4096)) {
  1480. log_warn(LD_BUG,
  1481. "Squid does not like URLs longer than 4095 bytes, and this "
  1482. "one is %d bytes long: %s%s",
  1483. (int)(strlen(proxystring) + strlen(url)), proxystring, url);
  1484. }
  1485. tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
  1486. connection_write_to_buf(request, strlen(request), TO_CONN(conn));
  1487. connection_write_to_buf(url, strlen(url), TO_CONN(conn));
  1488. tor_free(url);
  1489. if (!strcmp(httpcommand, "POST") || payload) {
  1490. smartlist_add_asprintf(headers, "Content-Length: %lu\r\n",
  1491. payload ? (unsigned long)payload_len : 0);
  1492. }
  1493. {
  1494. char *header = smartlist_join_strings(headers, "", 0, NULL);
  1495. tor_snprintf(request, sizeof(request), " HTTP/1.0\r\nHost: %s\r\n%s\r\n",
  1496. hoststring, header);
  1497. tor_free(header);
  1498. }
  1499. connection_write_to_buf(request, strlen(request), TO_CONN(conn));
  1500. if (payload) {
  1501. /* then send the payload afterwards too */
  1502. connection_write_to_buf(payload, payload_len, TO_CONN(conn));
  1503. }
  1504. SMARTLIST_FOREACH(headers, char *, h, tor_free(h));
  1505. smartlist_free(headers);
  1506. }
  1507. /** Parse an HTTP request string <b>headers</b> of the form
  1508. * \verbatim
  1509. * "\%s [http[s]://]\%s HTTP/1..."
  1510. * \endverbatim
  1511. * If it's well-formed, strdup the second \%s into *<b>url</b>, and
  1512. * nul-terminate it. If the url doesn't start with "/tor/", rewrite it
  1513. * so it does. Return 0.
  1514. * Otherwise, return -1.
  1515. */
  1516. STATIC int
  1517. parse_http_url(const char *headers, char **url)
  1518. {
  1519. char *s, *start, *tmp;
  1520. s = (char *)eat_whitespace_no_nl(headers);
  1521. if (!*s) return -1;
  1522. s = (char *)find_whitespace(s); /* get past GET/POST */
  1523. if (!*s) return -1;
  1524. s = (char *)eat_whitespace_no_nl(s);
  1525. if (!*s) return -1;
  1526. start = s; /* this is it, assuming it's valid */
  1527. s = (char *)find_whitespace(start);
  1528. if (!*s) return -1;
  1529. /* tolerate the http[s] proxy style of putting the hostname in the url */
  1530. if (s-start >= 4 && !strcmpstart(start,"http")) {
  1531. tmp = start + 4;
  1532. if (*tmp == 's')
  1533. tmp++;
  1534. if (s-tmp >= 3 && !strcmpstart(tmp,"://")) {
  1535. tmp = strchr(tmp+3, '/');
  1536. if (tmp && tmp < s) {
  1537. log_debug(LD_DIR,"Skipping over 'http[s]://hostname/' string");
  1538. start = tmp;
  1539. }
  1540. }
  1541. }
  1542. /* Check if the header is well formed (next sequence
  1543. * should be HTTP/1.X\r\n). Assumes we're supporting 1.0? */
  1544. {
  1545. unsigned minor_ver;
  1546. char ch;
  1547. char *e = (char *)eat_whitespace_no_nl(s);
  1548. if (2 != tor_sscanf(e, "HTTP/1.%u%c", &minor_ver, &ch)) {
  1549. return -1;
  1550. }
  1551. if (ch != '\r')
  1552. return -1;
  1553. }
  1554. if (s-start < 5 || strcmpstart(start,"/tor/")) { /* need to rewrite it */
  1555. *url = tor_malloc(s - start + 5);
  1556. strlcpy(*url,"/tor", s-start+5);
  1557. strlcat((*url)+4, start, s-start+1);
  1558. } else {
  1559. *url = tor_strndup(start, s-start);
  1560. }
  1561. return 0;
  1562. }
  1563. /** Return a copy of the first HTTP header in <b>headers</b> whose key is
  1564. * <b>which</b>. The key should be given with a terminating colon and space;
  1565. * this function copies everything after, up to but not including the
  1566. * following \\r\\n. */
  1567. static char *
  1568. http_get_header(const char *headers, const char *which)
  1569. {
  1570. const char *cp = headers;
  1571. while (cp) {
  1572. if (!strcasecmpstart(cp, which)) {
  1573. char *eos;
  1574. cp += strlen(which);
  1575. if ((eos = strchr(cp,'\r')))
  1576. return tor_strndup(cp, eos-cp);
  1577. else
  1578. return tor_strdup(cp);
  1579. }
  1580. cp = strchr(cp, '\n');
  1581. if (cp)
  1582. ++cp;
  1583. }
  1584. return NULL;
  1585. }
  1586. /** If <b>headers</b> indicates that a proxy was involved, then rewrite
  1587. * <b>conn</b>-\>address to describe our best guess of the address that
  1588. * originated this HTTP request. */
  1589. static void
  1590. http_set_address_origin(const char *headers, connection_t *conn)
  1591. {
  1592. char *fwd;
  1593. fwd = http_get_header(headers, "Forwarded-For: ");
  1594. if (!fwd)
  1595. fwd = http_get_header(headers, "X-Forwarded-For: ");
  1596. if (fwd) {
  1597. tor_addr_t toraddr;
  1598. if (tor_addr_parse(&toraddr,fwd) == -1 ||
  1599. tor_addr_is_internal(&toraddr,0)) {
  1600. log_debug(LD_DIR, "Ignoring local/internal IP %s", escaped(fwd));
  1601. tor_free(fwd);
  1602. return;
  1603. }
  1604. tor_free(conn->address);
  1605. conn->address = tor_strdup(fwd);
  1606. tor_free(fwd);
  1607. }
  1608. }
  1609. /** Parse an HTTP response string <b>headers</b> of the form
  1610. * \verbatim
  1611. * "HTTP/1.\%d \%d\%s\r\n...".
  1612. * \endverbatim
  1613. *
  1614. * If it's well-formed, assign the status code to *<b>code</b> and
  1615. * return 0. Otherwise, return -1.
  1616. *
  1617. * On success: If <b>date</b> is provided, set *date to the Date
  1618. * header in the http headers, or 0 if no such header is found. If
  1619. * <b>compression</b> is provided, set *<b>compression</b> to the
  1620. * compression method given in the Content-Encoding header, or 0 if no
  1621. * such header is found, or -1 if the value of the header is not
  1622. * recognized. If <b>reason</b> is provided, strdup the reason string
  1623. * into it.
  1624. */
  1625. int
  1626. parse_http_response(const char *headers, int *code, time_t *date,
  1627. compress_method_t *compression, char **reason)
  1628. {
  1629. unsigned n1, n2;
  1630. char datestr[RFC1123_TIME_LEN+1];
  1631. smartlist_t *parsed_headers;
  1632. tor_assert(headers);
  1633. tor_assert(code);
  1634. while (TOR_ISSPACE(*headers)) headers++; /* tolerate leading whitespace */
  1635. if (tor_sscanf(headers, "HTTP/1.%u %u", &n1, &n2) < 2 ||
  1636. (n1 != 0 && n1 != 1) ||
  1637. (n2 < 100 || n2 >= 600)) {
  1638. log_warn(LD_HTTP,"Failed to parse header %s",escaped(headers));
  1639. return -1;
  1640. }
  1641. *code = n2;
  1642. parsed_headers = smartlist_new();
  1643. smartlist_split_string(parsed_headers, headers, "\n",
  1644. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  1645. if (reason) {
  1646. smartlist_t *status_line_elements = smartlist_new();
  1647. tor_assert(smartlist_len(parsed_headers));
  1648. smartlist_split_string(status_line_elements,
  1649. smartlist_get(parsed_headers, 0),
  1650. " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1651. tor_assert(smartlist_len(status_line_elements) <= 3);
  1652. if (smartlist_len(status_line_elements) == 3) {
  1653. *reason = smartlist_get(status_line_elements, 2);
  1654. smartlist_set(status_line_elements, 2, NULL); /* Prevent free */
  1655. }
  1656. SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
  1657. smartlist_free(status_line_elements);
  1658. }
  1659. if (date) {
  1660. *date = 0;
  1661. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  1662. if (!strcmpstart(s, "Date: ")) {
  1663. strlcpy(datestr, s+6, sizeof(datestr));
  1664. /* This will do nothing on failure, so we don't need to check
  1665. the result. We shouldn't warn, since there are many other valid
  1666. date formats besides the one we use. */
  1667. parse_rfc1123_time(datestr, date);
  1668. break;
  1669. });
  1670. }
  1671. if (compression) {
  1672. const char *enc = NULL;
  1673. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  1674. if (!strcmpstart(s, "Content-Encoding: ")) {
  1675. enc = s+18; break;
  1676. });
  1677. if (!enc || !strcmp(enc, "identity")) {
  1678. *compression = NO_METHOD;
  1679. } else if (!strcmp(enc, "deflate") || !strcmp(enc, "x-deflate")) {
  1680. *compression = ZLIB_METHOD;
  1681. } else if (!strcmp(enc, "gzip") || !strcmp(enc, "x-gzip")) {
  1682. *compression = GZIP_METHOD;
  1683. } else {
  1684. log_info(LD_HTTP, "Unrecognized content encoding: %s. Trying to deal.",
  1685. escaped(enc));
  1686. *compression = UNKNOWN_METHOD;
  1687. }
  1688. }
  1689. SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  1690. smartlist_free(parsed_headers);
  1691. return 0;
  1692. }
  1693. /** Return true iff <b>body</b> doesn't start with a plausible router or
  1694. * network-status or microdescriptor opening. This is a sign of possible
  1695. * compression. */
  1696. static int
  1697. body_is_plausible(const char *body, size_t len, int purpose)
  1698. {
  1699. int i;
  1700. if (len == 0)
  1701. return 1; /* empty bodies don't need decompression */
  1702. if (len < 32)
  1703. return 0;
  1704. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  1705. return (!strcmpstart(body,"onion-key"));
  1706. }
  1707. if (!strcmpstart(body,"router") ||
  1708. !strcmpstart(body,"network-status"))
  1709. return 1;
  1710. for (i=0;i<32;++i) {
  1711. if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  1712. return 0;
  1713. }
  1714. return 1;
  1715. }
  1716. /** Called when we've just fetched a bunch of router descriptors in
  1717. * <b>body</b>. The list <b>which</b>, if present, holds digests for
  1718. * descriptors we requested: descriptor digests if <b>descriptor_digests</b>
  1719. * is true, or identity digests otherwise. Parse the descriptors, validate
  1720. * them, and annotate them as having purpose <b>purpose</b> and as having been
  1721. * downloaded from <b>source</b>.
  1722. *
  1723. * Return the number of routers actually added. */
  1724. static int
  1725. load_downloaded_routers(const char *body, smartlist_t *which,
  1726. int descriptor_digests,
  1727. int router_purpose,
  1728. const char *source)
  1729. {
  1730. char buf[256];
  1731. char time_buf[ISO_TIME_LEN+1];
  1732. int added = 0;
  1733. int general = router_purpose == ROUTER_PURPOSE_GENERAL;
  1734. format_iso_time(time_buf, time(NULL));
  1735. tor_assert(source);
  1736. if (tor_snprintf(buf, sizeof(buf),
  1737. "@downloaded-at %s\n"
  1738. "@source %s\n"
  1739. "%s%s%s", time_buf, escaped(source),
  1740. !general ? "@purpose " : "",
  1741. !general ? router_purpose_to_string(router_purpose) : "",
  1742. !general ? "\n" : "")<0)
  1743. return added;
  1744. added = router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  1745. descriptor_digests, buf);
  1746. if (added && general)
  1747. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  1748. count_loading_descriptors_progress());
  1749. return added;
  1750. }
  1751. /** We are a client, and we've finished reading the server's
  1752. * response. Parse it and act appropriately.
  1753. *
  1754. * If we're still happy with using this directory server in the future, return
  1755. * 0. Otherwise return -1; and the caller should consider trying the request
  1756. * again.
  1757. *
  1758. * The caller will take care of marking the connection for close.
  1759. */
  1760. static int
  1761. connection_dir_client_reached_eof(dir_connection_t *conn)
  1762. {
  1763. char *body;
  1764. char *headers;
  1765. char *reason = NULL;
  1766. size_t body_len = 0;
  1767. int status_code;
  1768. time_t date_header = 0;
  1769. long apparent_skew;
  1770. compress_method_t compression;
  1771. int plausible;
  1772. int skewed = 0;
  1773. int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  1774. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  1775. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  1776. time_t now = time(NULL);
  1777. int src_code;
  1778. switch (connection_fetch_from_buf_http(TO_CONN(conn),
  1779. &headers, MAX_HEADERS_SIZE,
  1780. &body, &body_len, MAX_DIR_DL_SIZE,
  1781. allow_partial)) {
  1782. case -1: /* overflow */
  1783. log_warn(LD_PROTOCOL,
  1784. "'fetch' response too large (server '%s:%d'). Closing.",
  1785. conn->base_.address, conn->base_.port);
  1786. return -1;
  1787. case 0:
  1788. log_info(LD_HTTP,
  1789. "'fetch' response not all here, but we're at eof. Closing.");
  1790. return -1;
  1791. /* case 1, fall through */
  1792. }
  1793. if (parse_http_response(headers, &status_code, &date_header,
  1794. &compression, &reason) < 0) {
  1795. log_warn(LD_HTTP,"Unparseable headers (server '%s:%d'). Closing.",
  1796. conn->base_.address, conn->base_.port);
  1797. tor_free(body); tor_free(headers);
  1798. return -1;
  1799. }
  1800. if (!reason) reason = tor_strdup("[no reason given]");
  1801. log_debug(LD_DIR,
  1802. "Received response from directory server '%s:%d': %d %s "
  1803. "(purpose: %d)",
  1804. conn->base_.address, conn->base_.port, status_code,
  1805. escaped(reason),
  1806. conn->base_.purpose);
  1807. if (conn->guard_state) {
  1808. /* we count the connection as successful once we can read from it. We do
  1809. * not, however, delay use of the circuit here, since it's just for a
  1810. * one-hop directory request. */
  1811. /* XXXXprop271 note that this will not do the right thing for other
  1812. * waiting circuits that would be triggered by this circuit becoming
  1813. * complete/usable. But that's ok, I think.
  1814. */
  1815. /* XXXXprop271 should we count this as only a partial success somehow?
  1816. */
  1817. entry_guard_succeeded(&conn->guard_state);
  1818. circuit_guard_state_free(conn->guard_state);
  1819. conn->guard_state = NULL;
  1820. }
  1821. /* now check if it's got any hints for us about our IP address. */
  1822. if (conn->dirconn_direct) {
  1823. char *guess = http_get_header(headers, X_ADDRESS_HEADER);
  1824. if (guess) {
  1825. router_new_address_suggestion(guess, conn);
  1826. tor_free(guess);
  1827. }
  1828. }
  1829. if (date_header > 0) {
  1830. /* The date header was written very soon after we sent our request,
  1831. * so compute the skew as the difference between sending the request
  1832. * and the date header. (We used to check now-date_header, but that's
  1833. * inaccurate if we spend a lot of time downloading.)
  1834. */
  1835. apparent_skew = conn->base_.timestamp_lastwritten - date_header;
  1836. if (labs(apparent_skew)>ALLOW_DIRECTORY_TIME_SKEW) {
  1837. int trusted = router_digest_is_trusted_dir(conn->identity_digest);
  1838. clock_skew_warning(TO_CONN(conn), apparent_skew, trusted, LD_HTTP,
  1839. "directory", "DIRSERV");
  1840. skewed = 1; /* don't check the recommended-versions line */
  1841. } else {
  1842. log_debug(LD_HTTP, "Time on received directory is within tolerance; "
  1843. "we are %ld seconds skewed. (That's okay.)", apparent_skew);
  1844. }
  1845. }
  1846. (void) skewed; /* skewed isn't used yet. */
  1847. if (status_code == 503) {
  1848. routerstatus_t *rs;
  1849. dir_server_t *ds;
  1850. const char *id_digest = conn->identity_digest;
  1851. log_info(LD_DIR,"Received http status code %d (%s) from server "
  1852. "'%s:%d'. I'll try again soon.",
  1853. status_code, escaped(reason), conn->base_.address,
  1854. conn->base_.port);
  1855. if ((rs = router_get_mutable_consensus_status_by_id(id_digest)))
  1856. rs->last_dir_503_at = now;
  1857. if ((ds = router_get_fallback_dirserver_by_digest(id_digest)))
  1858. ds->fake_status.last_dir_503_at = now;
  1859. tor_free(body); tor_free(headers); tor_free(reason);
  1860. return -1;
  1861. }
  1862. plausible = body_is_plausible(body, body_len, conn->base_.purpose);
  1863. if (compression != NO_METHOD || !plausible) {
  1864. char *new_body = NULL;
  1865. size_t new_len = 0;
  1866. compress_method_t guessed = detect_compression_method(body, body_len);
  1867. if (compression == UNKNOWN_METHOD || guessed != compression) {
  1868. /* Tell the user if we don't believe what we're told about compression.*/
  1869. const char *description1, *description2;
  1870. if (compression == ZLIB_METHOD)
  1871. description1 = "as deflated";
  1872. else if (compression == GZIP_METHOD)
  1873. description1 = "as gzipped";
  1874. else if (compression == NO_METHOD)
  1875. description1 = "as uncompressed";
  1876. else
  1877. description1 = "with an unknown Content-Encoding";
  1878. if (guessed == ZLIB_METHOD)
  1879. description2 = "deflated";
  1880. else if (guessed == GZIP_METHOD)
  1881. description2 = "gzipped";
  1882. else if (!plausible)
  1883. description2 = "confusing binary junk";
  1884. else
  1885. description2 = "uncompressed";
  1886. log_info(LD_HTTP, "HTTP body from server '%s:%d' was labeled %s, "
  1887. "but it seems to be %s.%s",
  1888. conn->base_.address, conn->base_.port, description1,
  1889. description2,
  1890. (compression>0 && guessed>0)?" Trying both.":"");
  1891. }
  1892. /* Try declared compression first if we can. */
  1893. if (compression == GZIP_METHOD || compression == ZLIB_METHOD)
  1894. tor_gzip_uncompress(&new_body, &new_len, body, body_len, compression,
  1895. !allow_partial, LOG_PROTOCOL_WARN);
  1896. /* Okay, if that didn't work, and we think that it was compressed
  1897. * differently, try that. */
  1898. if (!new_body &&
  1899. (guessed == GZIP_METHOD || guessed == ZLIB_METHOD) &&
  1900. compression != guessed)
  1901. tor_gzip_uncompress(&new_body, &new_len, body, body_len, guessed,
  1902. !allow_partial, LOG_PROTOCOL_WARN);
  1903. /* If we're pretty sure that we have a compressed directory, and
  1904. * we didn't manage to uncompress it, then warn and bail. */
  1905. if (!plausible && !new_body) {
  1906. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  1907. "Unable to decompress HTTP body (server '%s:%d').",
  1908. conn->base_.address, conn->base_.port);
  1909. tor_free(body); tor_free(headers); tor_free(reason);
  1910. return -1;
  1911. }
  1912. if (new_body) {
  1913. tor_free(body);
  1914. body = new_body;
  1915. body_len = new_len;
  1916. }
  1917. }
  1918. if (conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  1919. int r;
  1920. const char *flavname = conn->requested_resource;
  1921. if (status_code != 200) {
  1922. int severity = (status_code == 304) ? LOG_INFO : LOG_WARN;
  1923. tor_log(severity, LD_DIR,
  1924. "Received http status code %d (%s) from server "
  1925. "'%s:%d' while fetching consensus directory.",
  1926. status_code, escaped(reason), conn->base_.address,
  1927. conn->base_.port);
  1928. tor_free(body); tor_free(headers); tor_free(reason);
  1929. networkstatus_consensus_download_failed(status_code, flavname);
  1930. return -1;
  1931. }
  1932. log_info(LD_DIR,"Received consensus directory (size %d) from server "
  1933. "'%s:%d'", (int)body_len, conn->base_.address, conn->base_.port);
  1934. if ((r=networkstatus_set_current_consensus(body, flavname, 0,
  1935. conn->identity_digest))<0) {
  1936. log_fn(r<-1?LOG_WARN:LOG_INFO, LD_DIR,
  1937. "Unable to load %s consensus directory downloaded from "
  1938. "server '%s:%d'. I'll try again soon.",
  1939. flavname, conn->base_.address, conn->base_.port);
  1940. tor_free(body); tor_free(headers); tor_free(reason);
  1941. networkstatus_consensus_download_failed(0, flavname);
  1942. return -1;
  1943. }
  1944. /* If we launched other fetches for this consensus, cancel them. */
  1945. connection_dir_close_consensus_fetches(conn, flavname);
  1946. /* launches router downloads as needed */
  1947. routers_update_all_from_networkstatus(now, 3);
  1948. update_microdescs_from_networkstatus(now);
  1949. update_microdesc_downloads(now);
  1950. directory_info_has_arrived(now, 0, 0);
  1951. if (authdir_mode_v3(get_options())) {
  1952. sr_act_post_consensus(
  1953. networkstatus_get_latest_consensus_by_flavor(FLAV_NS));
  1954. }
  1955. log_info(LD_DIR, "Successfully loaded consensus.");
  1956. }
  1957. if (conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
  1958. if (status_code != 200) {
  1959. log_warn(LD_DIR,
  1960. "Received http status code %d (%s) from server "
  1961. "'%s:%d' while fetching \"/tor/keys/%s\".",
  1962. status_code, escaped(reason), conn->base_.address,
  1963. conn->base_.port, conn->requested_resource);
  1964. connection_dir_download_cert_failed(conn, status_code);
  1965. tor_free(body); tor_free(headers); tor_free(reason);
  1966. return -1;
  1967. }
  1968. log_info(LD_DIR,"Received authority certificates (size %d) from server "
  1969. "'%s:%d'", (int)body_len, conn->base_.address, conn->base_.port);
  1970. /*
  1971. * Tell trusted_dirs_load_certs_from_string() whether it was by fp
  1972. * or fp-sk pair.
  1973. */
  1974. src_code = -1;
  1975. if (!strcmpstart(conn->requested_resource, "fp/")) {
  1976. src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST;
  1977. } else if (!strcmpstart(conn->requested_resource, "fp-sk/")) {
  1978. src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST;
  1979. }
  1980. if (src_code != -1) {
  1981. if (trusted_dirs_load_certs_from_string(body, src_code, 1,
  1982. conn->identity_digest)<0) {
  1983. log_warn(LD_DIR, "Unable to parse fetched certificates");
  1984. /* if we fetched more than one and only some failed, the successful
  1985. * ones got flushed to disk so it's safe to call this on them */
  1986. connection_dir_download_cert_failed(conn, status_code);
  1987. } else {
  1988. directory_info_has_arrived(now, 0, 0);
  1989. log_info(LD_DIR, "Successfully loaded certificates from fetch.");
  1990. }
  1991. } else {
  1992. log_warn(LD_DIR,
  1993. "Couldn't figure out what to do with fetched certificates for "
  1994. "unknown resource %s",
  1995. conn->requested_resource);
  1996. connection_dir_download_cert_failed(conn, status_code);
  1997. }
  1998. }
  1999. if (conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
  2000. const char *msg;
  2001. int st;
  2002. log_info(LD_DIR,"Got votes (size %d) from server %s:%d",
  2003. (int)body_len, conn->base_.address, conn->base_.port);
  2004. if (status_code != 200) {
  2005. log_warn(LD_DIR,
  2006. "Received http status code %d (%s) from server "
  2007. "'%s:%d' while fetching \"/tor/status-vote/next/%s.z\".",
  2008. status_code, escaped(reason), conn->base_.address,
  2009. conn->base_.port, conn->requested_resource);
  2010. tor_free(body); tor_free(headers); tor_free(reason);
  2011. return -1;
  2012. }
  2013. dirvote_add_vote(body, &msg, &st);
  2014. if (st > 299) {
  2015. log_warn(LD_DIR, "Error adding retrieved vote: %s", msg);
  2016. } else {
  2017. log_info(LD_DIR, "Added vote(s) successfully [msg: %s]", msg);
  2018. }
  2019. }
  2020. if (conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
  2021. const char *msg = NULL;
  2022. log_info(LD_DIR,"Got detached signatures (size %d) from server %s:%d",
  2023. (int)body_len, conn->base_.address, conn->base_.port);
  2024. if (status_code != 200) {
  2025. log_warn(LD_DIR,
  2026. "Received http status code %d (%s) from server '%s:%d' while fetching "
  2027. "\"/tor/status-vote/next/consensus-signatures.z\".",
  2028. status_code, escaped(reason), conn->base_.address,
  2029. conn->base_.port);
  2030. tor_free(body); tor_free(headers); tor_free(reason);
  2031. return -1;
  2032. }
  2033. if (dirvote_add_signatures(body, conn->base_.address, &msg)<0) {
  2034. log_warn(LD_DIR, "Problem adding detached signatures from %s:%d: %s",
  2035. conn->base_.address, conn->base_.port, msg?msg:"???");
  2036. }
  2037. }
  2038. if (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  2039. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
  2040. int was_ei = conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO;
  2041. smartlist_t *which = NULL;
  2042. int n_asked_for = 0;
  2043. int descriptor_digests = conn->requested_resource &&
  2044. !strcmpstart(conn->requested_resource,"d/");
  2045. log_info(LD_DIR,"Received %s (size %d) from server '%s:%d'",
  2046. was_ei ? "extra server info" : "server info",
  2047. (int)body_len, conn->base_.address, conn->base_.port);
  2048. if (conn->requested_resource &&
  2049. (!strcmpstart(conn->requested_resource,"d/") ||
  2050. !strcmpstart(conn->requested_resource,"fp/"))) {
  2051. which = smartlist_new();
  2052. dir_split_resource_into_fingerprints(conn->requested_resource +
  2053. (descriptor_digests ? 2 : 3),
  2054. which, NULL, 0);
  2055. n_asked_for = smartlist_len(which);
  2056. }
  2057. if (status_code != 200) {
  2058. int dir_okay = status_code == 404 ||
  2059. (status_code == 400 && !strcmp(reason, "Servers unavailable."));
  2060. /* 404 means that it didn't have them; no big deal.
  2061. * Older (pre-0.1.1.8) servers said 400 Servers unavailable instead. */
  2062. log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
  2063. "Received http status code %d (%s) from server '%s:%d' "
  2064. "while fetching \"/tor/server/%s\". I'll try again soon.",
  2065. status_code, escaped(reason), conn->base_.address,
  2066. conn->base_.port, conn->requested_resource);
  2067. if (!which) {
  2068. connection_dir_download_routerdesc_failed(conn);
  2069. } else {
  2070. dir_routerdesc_download_failed(which, status_code,
  2071. conn->router_purpose,
  2072. was_ei, descriptor_digests);
  2073. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2074. smartlist_free(which);
  2075. }
  2076. tor_free(body); tor_free(headers); tor_free(reason);
  2077. return dir_okay ? 0 : -1;
  2078. }
  2079. /* Learn the routers, assuming we requested by fingerprint or "all"
  2080. * or "authority".
  2081. *
  2082. * We use "authority" to fetch our own descriptor for
  2083. * testing, and to fetch bridge descriptors for bootstrapping. Ignore
  2084. * the output of "authority" requests unless we are using bridges,
  2085. * since otherwise they'll be the response from reachability tests,
  2086. * and we don't really want to add that to our routerlist. */
  2087. if (which || (conn->requested_resource &&
  2088. (!strcmpstart(conn->requested_resource, "all") ||
  2089. (!strcmpstart(conn->requested_resource, "authority") &&
  2090. get_options()->UseBridges)))) {
  2091. /* as we learn from them, we remove them from 'which' */
  2092. if (was_ei) {
  2093. router_load_extrainfo_from_string(body, NULL, SAVED_NOWHERE, which,
  2094. descriptor_digests);
  2095. } else {
  2096. //router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  2097. // descriptor_digests, conn->router_purpose);
  2098. if (load_downloaded_routers(body, which, descriptor_digests,
  2099. conn->router_purpose,
  2100. conn->base_.address))
  2101. directory_info_has_arrived(now, 0, 0);
  2102. }
  2103. }
  2104. if (which) { /* mark remaining ones as failed */
  2105. log_info(LD_DIR, "Received %d/%d %s requested from %s:%d",
  2106. n_asked_for-smartlist_len(which), n_asked_for,
  2107. was_ei ? "extra-info documents" : "router descriptors",
  2108. conn->base_.address, (int)conn->base_.port);
  2109. if (smartlist_len(which)) {
  2110. dir_routerdesc_download_failed(which, status_code,
  2111. conn->router_purpose,
  2112. was_ei, descriptor_digests);
  2113. }
  2114. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2115. smartlist_free(which);
  2116. }
  2117. if (directory_conn_is_self_reachability_test(conn))
  2118. router_dirport_found_reachable();
  2119. }
  2120. if (conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  2121. smartlist_t *which = NULL;
  2122. log_info(LD_DIR,"Received answer to microdescriptor request (status %d, "
  2123. "size %d) from server '%s:%d'",
  2124. status_code, (int)body_len, conn->base_.address,
  2125. conn->base_.port);
  2126. tor_assert(conn->requested_resource &&
  2127. !strcmpstart(conn->requested_resource, "d/"));
  2128. which = smartlist_new();
  2129. dir_split_resource_into_fingerprints(conn->requested_resource+2,
  2130. which, NULL,
  2131. DSR_DIGEST256|DSR_BASE64);
  2132. if (status_code != 200) {
  2133. log_info(LD_DIR, "Received status code %d (%s) from server "
  2134. "'%s:%d' while fetching \"/tor/micro/%s\". I'll try again "
  2135. "soon.",
  2136. status_code, escaped(reason), conn->base_.address,
  2137. (int)conn->base_.port, conn->requested_resource);
  2138. dir_microdesc_download_failed(which, status_code);
  2139. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2140. smartlist_free(which);
  2141. tor_free(body); tor_free(headers); tor_free(reason);
  2142. return 0;
  2143. } else {
  2144. smartlist_t *mds;
  2145. mds = microdescs_add_to_cache(get_microdesc_cache(),
  2146. body, body+body_len, SAVED_NOWHERE, 0,
  2147. now, which);
  2148. if (smartlist_len(which)) {
  2149. /* Mark remaining ones as failed. */
  2150. dir_microdesc_download_failed(which, status_code);
  2151. }
  2152. if (mds && smartlist_len(mds)) {
  2153. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  2154. count_loading_descriptors_progress());
  2155. directory_info_has_arrived(now, 0, 1);
  2156. }
  2157. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2158. smartlist_free(which);
  2159. smartlist_free(mds);
  2160. }
  2161. }
  2162. if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_DIR) {
  2163. switch (status_code) {
  2164. case 200: {
  2165. dir_server_t *ds =
  2166. router_get_trusteddirserver_by_digest(conn->identity_digest);
  2167. char *rejected_hdr = http_get_header(headers,
  2168. "X-Descriptor-Not-New: ");
  2169. if (rejected_hdr) {
  2170. if (!strcmp(rejected_hdr, "Yes")) {
  2171. log_info(LD_GENERAL,
  2172. "Authority '%s' declined our descriptor (not new)",
  2173. ds->nickname);
  2174. /* XXXX use this information; be sure to upload next one
  2175. * sooner. -NM */
  2176. /* XXXX++ On further thought, the task above implies that we're
  2177. * basing our regenerate-descriptor time on when we uploaded the
  2178. * last descriptor, not on the published time of the last
  2179. * descriptor. If those are different, that's a bad thing to
  2180. * do. -NM */
  2181. }
  2182. tor_free(rejected_hdr);
  2183. }
  2184. log_info(LD_GENERAL,"eof (status 200) after uploading server "
  2185. "descriptor: finished.");
  2186. control_event_server_status(
  2187. LOG_NOTICE, "ACCEPTED_SERVER_DESCRIPTOR DIRAUTH=%s:%d",
  2188. conn->base_.address, conn->base_.port);
  2189. ds->has_accepted_serverdesc = 1;
  2190. if (directories_have_accepted_server_descriptor())
  2191. control_event_server_status(LOG_NOTICE, "GOOD_SERVER_DESCRIPTOR");
  2192. }
  2193. break;
  2194. case 400:
  2195. log_warn(LD_GENERAL,"http status 400 (%s) response from "
  2196. "dirserver '%s:%d'. Please correct.",
  2197. escaped(reason), conn->base_.address, conn->base_.port);
  2198. control_event_server_status(LOG_WARN,
  2199. "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
  2200. conn->base_.address, conn->base_.port, escaped(reason));
  2201. break;
  2202. default:
  2203. log_warn(LD_GENERAL,
  2204. "http status %d (%s) reason unexpected while uploading "
  2205. "descriptor to server '%s:%d').",
  2206. status_code, escaped(reason), conn->base_.address,
  2207. conn->base_.port);
  2208. break;
  2209. }
  2210. /* return 0 in all cases, since we don't want to mark any
  2211. * dirservers down just because they don't like us. */
  2212. }
  2213. if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_VOTE) {
  2214. switch (status_code) {
  2215. case 200: {
  2216. log_notice(LD_DIR,"Uploaded a vote to dirserver %s:%d",
  2217. conn->base_.address, conn->base_.port);
  2218. }
  2219. break;
  2220. case 400:
  2221. log_warn(LD_DIR,"http status 400 (%s) response after uploading "
  2222. "vote to dirserver '%s:%d'. Please correct.",
  2223. escaped(reason), conn->base_.address, conn->base_.port);
  2224. break;
  2225. default:
  2226. log_warn(LD_GENERAL,
  2227. "http status %d (%s) reason unexpected while uploading "
  2228. "vote to server '%s:%d').",
  2229. status_code, escaped(reason), conn->base_.address,
  2230. conn->base_.port);
  2231. break;
  2232. }
  2233. /* return 0 in all cases, since we don't want to mark any
  2234. * dirservers down just because they don't like us. */
  2235. }
  2236. if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_SIGNATURES) {
  2237. switch (status_code) {
  2238. case 200: {
  2239. log_notice(LD_DIR,"Uploaded signature(s) to dirserver %s:%d",
  2240. conn->base_.address, conn->base_.port);
  2241. }
  2242. break;
  2243. case 400:
  2244. log_warn(LD_DIR,"http status 400 (%s) response after uploading "
  2245. "signatures to dirserver '%s:%d'. Please correct.",
  2246. escaped(reason), conn->base_.address, conn->base_.port);
  2247. break;
  2248. default:
  2249. log_warn(LD_GENERAL,
  2250. "http status %d (%s) reason unexpected while uploading "
  2251. "signatures to server '%s:%d').",
  2252. status_code, escaped(reason), conn->base_.address,
  2253. conn->base_.port);
  2254. break;
  2255. }
  2256. /* return 0 in all cases, since we don't want to mark any
  2257. * dirservers down just because they don't like us. */
  2258. }
  2259. if (conn->base_.purpose == DIR_PURPOSE_FETCH_RENDDESC_V2) {
  2260. #define SEND_HS_DESC_FAILED_EVENT(reason) ( \
  2261. control_event_hs_descriptor_failed(conn->rend_data, \
  2262. conn->identity_digest, \
  2263. reason) )
  2264. #define SEND_HS_DESC_FAILED_CONTENT() ( \
  2265. control_event_hs_descriptor_content(rend_data_get_address(conn->rend_data), \
  2266. conn->requested_resource, \
  2267. conn->identity_digest, \
  2268. NULL) )
  2269. tor_assert(conn->rend_data);
  2270. log_info(LD_REND,"Received rendezvous descriptor (size %d, status %d "
  2271. "(%s))",
  2272. (int)body_len, status_code, escaped(reason));
  2273. switch (status_code) {
  2274. case 200:
  2275. {
  2276. rend_cache_entry_t *entry = NULL;
  2277. if (rend_cache_store_v2_desc_as_client(body,
  2278. conn->requested_resource, conn->rend_data, &entry) < 0) {
  2279. log_warn(LD_REND,"Fetching v2 rendezvous descriptor failed. "
  2280. "Retrying at another directory.");
  2281. /* We'll retry when connection_about_to_close_connection()
  2282. * cleans this dir conn up. */
  2283. SEND_HS_DESC_FAILED_EVENT("BAD_DESC");
  2284. SEND_HS_DESC_FAILED_CONTENT();
  2285. } else {
  2286. char service_id[REND_SERVICE_ID_LEN_BASE32 + 1];
  2287. /* Should never be NULL here if we found the descriptor. */
  2288. tor_assert(entry);
  2289. rend_get_service_id(entry->parsed->pk, service_id);
  2290. /* success. notify pending connections about this. */
  2291. log_info(LD_REND, "Successfully fetched v2 rendezvous "
  2292. "descriptor.");
  2293. control_event_hs_descriptor_received(service_id,
  2294. conn->rend_data,
  2295. conn->identity_digest);
  2296. control_event_hs_descriptor_content(service_id,
  2297. conn->requested_resource,
  2298. conn->identity_digest,
  2299. body);
  2300. conn->base_.purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2;
  2301. rend_client_desc_trynow(service_id);
  2302. memwipe(service_id, 0, sizeof(service_id));
  2303. }
  2304. break;
  2305. }
  2306. case 404:
  2307. /* Not there. We'll retry when
  2308. * connection_about_to_close_connection() cleans this conn up. */
  2309. log_info(LD_REND,"Fetching v2 rendezvous descriptor failed: "
  2310. "Retrying at another directory.");
  2311. SEND_HS_DESC_FAILED_EVENT("NOT_FOUND");
  2312. SEND_HS_DESC_FAILED_CONTENT();
  2313. break;
  2314. case 400:
  2315. log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
  2316. "http status 400 (%s). Dirserver didn't like our "
  2317. "v2 rendezvous query? Retrying at another directory.",
  2318. escaped(reason));
  2319. SEND_HS_DESC_FAILED_EVENT("QUERY_REJECTED");
  2320. SEND_HS_DESC_FAILED_CONTENT();
  2321. break;
  2322. default:
  2323. log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
  2324. "http status %d (%s) response unexpected while "
  2325. "fetching v2 hidden service descriptor (server '%s:%d'). "
  2326. "Retrying at another directory.",
  2327. status_code, escaped(reason), conn->base_.address,
  2328. conn->base_.port);
  2329. SEND_HS_DESC_FAILED_EVENT("UNEXPECTED");
  2330. SEND_HS_DESC_FAILED_CONTENT();
  2331. break;
  2332. }
  2333. }
  2334. if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2) {
  2335. #define SEND_HS_DESC_UPLOAD_FAILED_EVENT(reason) ( \
  2336. control_event_hs_descriptor_upload_failed( \
  2337. conn->identity_digest, \
  2338. rend_data_get_address(conn->rend_data), \
  2339. reason) )
  2340. log_info(LD_REND,"Uploaded rendezvous descriptor (status %d "
  2341. "(%s))",
  2342. status_code, escaped(reason));
  2343. /* Without the rend data, we'll have a problem identifying what has been
  2344. * uploaded for which service. */
  2345. tor_assert(conn->rend_data);
  2346. switch (status_code) {
  2347. case 200:
  2348. log_info(LD_REND,
  2349. "Uploading rendezvous descriptor: finished with status "
  2350. "200 (%s)", escaped(reason));
  2351. control_event_hs_descriptor_uploaded(conn->identity_digest,
  2352. rend_data_get_address(conn->rend_data));
  2353. rend_service_desc_has_uploaded(conn->rend_data);
  2354. break;
  2355. case 400:
  2356. log_warn(LD_REND,"http status 400 (%s) response from dirserver "
  2357. "'%s:%d'. Malformed rendezvous descriptor?",
  2358. escaped(reason), conn->base_.address, conn->base_.port);
  2359. SEND_HS_DESC_UPLOAD_FAILED_EVENT("UPLOAD_REJECTED");
  2360. break;
  2361. default:
  2362. log_warn(LD_REND,"http status %d (%s) response unexpected (server "
  2363. "'%s:%d').",
  2364. status_code, escaped(reason), conn->base_.address,
  2365. conn->base_.port);
  2366. SEND_HS_DESC_UPLOAD_FAILED_EVENT("UNEXPECTED");
  2367. break;
  2368. }
  2369. }
  2370. tor_free(body); tor_free(headers); tor_free(reason);
  2371. return 0;
  2372. }
  2373. /** Called when a directory connection reaches EOF. */
  2374. int
  2375. connection_dir_reached_eof(dir_connection_t *conn)
  2376. {
  2377. int retval;
  2378. if (conn->base_.state != DIR_CONN_STATE_CLIENT_READING) {
  2379. log_info(LD_HTTP,"conn reached eof, not reading. [state=%d] Closing.",
  2380. conn->base_.state);
  2381. connection_close_immediate(TO_CONN(conn)); /* error: give up on flushing */
  2382. connection_mark_for_close(TO_CONN(conn));
  2383. return -1;
  2384. }
  2385. retval = connection_dir_client_reached_eof(conn);
  2386. if (retval == 0) /* success */
  2387. conn->base_.state = DIR_CONN_STATE_CLIENT_FINISHED;
  2388. connection_mark_for_close(TO_CONN(conn));
  2389. return retval;
  2390. }
  2391. /** If any directory object is arriving, and it's over 10MB large, we're
  2392. * getting DoS'd. (As of 0.1.2.x, raw directories are about 1MB, and we never
  2393. * ask for more than 96 router descriptors at a time.)
  2394. */
  2395. #define MAX_DIRECTORY_OBJECT_SIZE (10*(1<<20))
  2396. #define MAX_VOTE_DL_SIZE (MAX_DIRECTORY_OBJECT_SIZE * 5)
  2397. /** Read handler for directory connections. (That's connections <em>to</em>
  2398. * directory servers and connections <em>at</em> directory servers.)
  2399. */
  2400. int
  2401. connection_dir_process_inbuf(dir_connection_t *conn)
  2402. {
  2403. size_t max_size;
  2404. tor_assert(conn);
  2405. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  2406. /* Directory clients write, then read data until they receive EOF;
  2407. * directory servers read data until they get an HTTP command, then
  2408. * write their response (when it's finished flushing, they mark for
  2409. * close).
  2410. */
  2411. /* If we're on the dirserver side, look for a command. */
  2412. if (conn->base_.state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  2413. if (directory_handle_command(conn) < 0) {
  2414. connection_mark_for_close(TO_CONN(conn));
  2415. return -1;
  2416. }
  2417. return 0;
  2418. }
  2419. max_size =
  2420. (TO_CONN(conn)->purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) ?
  2421. MAX_VOTE_DL_SIZE : MAX_DIRECTORY_OBJECT_SIZE;
  2422. if (connection_get_inbuf_len(TO_CONN(conn)) > max_size) {
  2423. log_warn(LD_HTTP,
  2424. "Too much data received from directory connection (%s): "
  2425. "denial of service attempt, or you need to upgrade?",
  2426. conn->base_.address);
  2427. connection_mark_for_close(TO_CONN(conn));
  2428. return -1;
  2429. }
  2430. if (!conn->base_.inbuf_reached_eof)
  2431. log_debug(LD_HTTP,"Got data, not eof. Leaving on inbuf.");
  2432. return 0;
  2433. }
  2434. /** Called when we're about to finally unlink and free a directory connection:
  2435. * perform necessary accounting and cleanup */
  2436. void
  2437. connection_dir_about_to_close(dir_connection_t *dir_conn)
  2438. {
  2439. connection_t *conn = TO_CONN(dir_conn);
  2440. if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
  2441. /* It's a directory connection and connecting or fetching
  2442. * failed: forget about this router, and maybe try again. */
  2443. connection_dir_request_failed(dir_conn);
  2444. }
  2445. /* If we were trying to fetch a v2 rend desc and did not succeed,
  2446. * retry as needed. (If a fetch is successful, the connection state
  2447. * is changed to DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2 to mark that
  2448. * refetching is unnecessary.) */
  2449. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 &&
  2450. dir_conn->rend_data &&
  2451. strlen(rend_data_get_address(dir_conn->rend_data)) ==
  2452. REND_SERVICE_ID_LEN_BASE32)
  2453. rend_client_refetch_v2_renddesc(dir_conn->rend_data);
  2454. }
  2455. /** Create an http response for the client <b>conn</b> out of
  2456. * <b>status</b> and <b>reason_phrase</b>. Write it to <b>conn</b>.
  2457. */
  2458. static void
  2459. write_http_status_line(dir_connection_t *conn, int status,
  2460. const char *reason_phrase)
  2461. {
  2462. char buf[256];
  2463. if (tor_snprintf(buf, sizeof(buf), "HTTP/1.0 %d %s\r\n\r\n",
  2464. status, reason_phrase ? reason_phrase : "OK") < 0) {
  2465. log_warn(LD_BUG,"status line too long.");
  2466. return;
  2467. }
  2468. log_debug(LD_DIRSERV,"Wrote status 'HTTP/1.0 %d %s'", status, reason_phrase);
  2469. connection_write_to_buf(buf, strlen(buf), TO_CONN(conn));
  2470. }
  2471. /** Write the header for an HTTP/1.0 response onto <b>conn</b>-\>outbuf,
  2472. * with <b>type</b> as the Content-Type.
  2473. *
  2474. * If <b>length</b> is nonnegative, it is the Content-Length.
  2475. * If <b>encoding</b> is provided, it is the Content-Encoding.
  2476. * If <b>cache_lifetime</b> is greater than 0, the content may be cached for
  2477. * up to cache_lifetime seconds. Otherwise, the content may not be cached. */
  2478. static void
  2479. write_http_response_header_impl(dir_connection_t *conn, ssize_t length,
  2480. const char *type, const char *encoding,
  2481. const char *extra_headers,
  2482. long cache_lifetime)
  2483. {
  2484. char date[RFC1123_TIME_LEN+1];
  2485. char tmp[1024];
  2486. char *cp;
  2487. time_t now = time(NULL);
  2488. tor_assert(conn);
  2489. format_rfc1123_time(date, now);
  2490. cp = tmp;
  2491. tor_snprintf(cp, sizeof(tmp),
  2492. "HTTP/1.0 200 OK\r\nDate: %s\r\n",
  2493. date);
  2494. cp += strlen(tmp);
  2495. if (type) {
  2496. tor_snprintf(cp, sizeof(tmp)-(cp-tmp), "Content-Type: %s\r\n", type);
  2497. cp += strlen(cp);
  2498. }
  2499. if (!is_local_addr(&conn->base_.addr)) {
  2500. /* Don't report the source address for a nearby/private connection.
  2501. * Otherwise we tend to mis-report in cases where incoming ports are
  2502. * being forwarded to a Tor server running behind the firewall. */
  2503. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  2504. X_ADDRESS_HEADER "%s\r\n", conn->base_.address);
  2505. cp += strlen(cp);
  2506. }
  2507. if (encoding) {
  2508. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  2509. "Content-Encoding: %s\r\n", encoding);
  2510. cp += strlen(cp);
  2511. }
  2512. if (length >= 0) {
  2513. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  2514. "Content-Length: %ld\r\n", (long)length);
  2515. cp += strlen(cp);
  2516. }
  2517. if (cache_lifetime > 0) {
  2518. char expbuf[RFC1123_TIME_LEN+1];
  2519. format_rfc1123_time(expbuf, (time_t)(now + cache_lifetime));
  2520. /* We could say 'Cache-control: max-age=%d' here if we start doing
  2521. * http/1.1 */
  2522. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  2523. "Expires: %s\r\n", expbuf);
  2524. cp += strlen(cp);
  2525. } else if (cache_lifetime == 0) {
  2526. /* We could say 'Cache-control: no-cache' here if we start doing
  2527. * http/1.1 */
  2528. strlcpy(cp, "Pragma: no-cache\r\n", sizeof(tmp)-(cp-tmp));
  2529. cp += strlen(cp);
  2530. }
  2531. if (extra_headers) {
  2532. strlcpy(cp, extra_headers, sizeof(tmp)-(cp-tmp));
  2533. cp += strlen(cp);
  2534. }
  2535. if (sizeof(tmp)-(cp-tmp) > 3)
  2536. memcpy(cp, "\r\n", 3);
  2537. else
  2538. tor_assert(0);
  2539. connection_write_to_buf(tmp, strlen(tmp), TO_CONN(conn));
  2540. }
  2541. /** As write_http_response_header_impl, but sets encoding and content-typed
  2542. * based on whether the response will be <b>compressed</b> or not. */
  2543. static void
  2544. write_http_response_header(dir_connection_t *conn, ssize_t length,
  2545. int compressed, long cache_lifetime)
  2546. {
  2547. write_http_response_header_impl(conn, length,
  2548. compressed?"application/octet-stream":"text/plain",
  2549. compressed?"deflate":"identity",
  2550. NULL,
  2551. cache_lifetime);
  2552. }
  2553. /** Decide whether a client would accept the consensus we have.
  2554. *
  2555. * Clients can say they only want a consensus if it's signed by more
  2556. * than half the authorities in a list. They pass this list in
  2557. * the url as "...consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>".
  2558. *
  2559. * <b>fpr</b> may be an abbreviated fingerprint, i.e. only a left substring
  2560. * of the full authority identity digest. (Only strings of even length,
  2561. * i.e. encodings of full bytes, are handled correctly. In the case
  2562. * of an odd number of hex digits the last one is silently ignored.)
  2563. *
  2564. * Returns 1 if more than half of the requested authorities signed the
  2565. * consensus, 0 otherwise.
  2566. */
  2567. int
  2568. client_likes_consensus(networkstatus_t *v, const char *want_url)
  2569. {
  2570. smartlist_t *want_authorities = smartlist_new();
  2571. int need_at_least;
  2572. int have = 0;
  2573. dir_split_resource_into_fingerprints(want_url, want_authorities, NULL, 0);
  2574. need_at_least = smartlist_len(want_authorities)/2+1;
  2575. SMARTLIST_FOREACH_BEGIN(want_authorities, const char *, d) {
  2576. char want_digest[DIGEST_LEN];
  2577. size_t want_len = strlen(d)/2;
  2578. if (want_len > DIGEST_LEN)
  2579. want_len = DIGEST_LEN;
  2580. if (base16_decode(want_digest, DIGEST_LEN, d, want_len*2)
  2581. != (int) want_len) {
  2582. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2583. "Failed to decode requested authority digest %s.", escaped(d));
  2584. continue;
  2585. };
  2586. SMARTLIST_FOREACH_BEGIN(v->voters, networkstatus_voter_info_t *, vi) {
  2587. if (smartlist_len(vi->sigs) &&
  2588. tor_memeq(vi->identity_digest, want_digest, want_len)) {
  2589. have++;
  2590. break;
  2591. };
  2592. } SMARTLIST_FOREACH_END(vi);
  2593. /* early exit, if we already have enough */
  2594. if (have >= need_at_least)
  2595. break;
  2596. } SMARTLIST_FOREACH_END(d);
  2597. SMARTLIST_FOREACH(want_authorities, char *, d, tor_free(d));
  2598. smartlist_free(want_authorities);
  2599. return (have >= need_at_least);
  2600. }
  2601. /** Return the compression level we should use for sending a compressed
  2602. * response of size <b>n_bytes</b>. */
  2603. STATIC zlib_compression_level_t
  2604. choose_compression_level(ssize_t n_bytes)
  2605. {
  2606. if (! have_been_under_memory_pressure()) {
  2607. return HIGH_COMPRESSION; /* we have plenty of RAM. */
  2608. } else if (n_bytes < 0) {
  2609. return HIGH_COMPRESSION; /* unknown; might be big. */
  2610. } else if (n_bytes < 1024) {
  2611. return LOW_COMPRESSION;
  2612. } else if (n_bytes < 2048) {
  2613. return MEDIUM_COMPRESSION;
  2614. } else {
  2615. return HIGH_COMPRESSION;
  2616. }
  2617. }
  2618. /** Information passed to handle a GET request. */
  2619. typedef struct get_handler_args_t {
  2620. /** True if the client asked for compressed data. */
  2621. int compressed;
  2622. /** If nonzero, the time included an if-modified-since header with this
  2623. * value. */
  2624. time_t if_modified_since;
  2625. /** String containing the requested URL or resource. */
  2626. const char *url;
  2627. /** String containing the HTTP headers */
  2628. const char *headers;
  2629. } get_handler_args_t;
  2630. /** Entry for handling an HTTP GET request.
  2631. *
  2632. * This entry matches a request if "string" is equal to the requested
  2633. * resource, or if "is_prefix" is true and "string" is a prefix of the
  2634. * requested resource.
  2635. *
  2636. * The 'handler' function is called to handle the request. It receives
  2637. * an arguments structure, and must return 0 on success or -1 if we should
  2638. * close the connection.
  2639. **/
  2640. typedef struct url_table_ent_s {
  2641. const char *string;
  2642. int is_prefix;
  2643. int (*handler)(dir_connection_t *conn, const get_handler_args_t *args);
  2644. } url_table_ent_t;
  2645. static int handle_get_frontpage(dir_connection_t *conn,
  2646. const get_handler_args_t *args);
  2647. static int handle_get_current_consensus(dir_connection_t *conn,
  2648. const get_handler_args_t *args);
  2649. static int handle_get_status_vote(dir_connection_t *conn,
  2650. const get_handler_args_t *args);
  2651. static int handle_get_microdesc(dir_connection_t *conn,
  2652. const get_handler_args_t *args);
  2653. static int handle_get_descriptor(dir_connection_t *conn,
  2654. const get_handler_args_t *args);
  2655. static int handle_get_keys(dir_connection_t *conn,
  2656. const get_handler_args_t *args);
  2657. static int handle_get_hs_descriptor_v2(dir_connection_t *conn,
  2658. const get_handler_args_t *args);
  2659. static int handle_get_robots(dir_connection_t *conn,
  2660. const get_handler_args_t *args);
  2661. static int handle_get_networkstatus_bridges(dir_connection_t *conn,
  2662. const get_handler_args_t *args);
  2663. /** Table for handling GET requests. */
  2664. static const url_table_ent_t url_table[] = {
  2665. { "/tor/", 0, handle_get_frontpage },
  2666. { "/tor/status-vote/current/consensus", 1, handle_get_current_consensus },
  2667. { "/tor/status-vote/current/", 1, handle_get_status_vote },
  2668. { "/tor/status-vote/next/", 1, handle_get_status_vote },
  2669. { "/tor/micro/d/", 1, handle_get_microdesc },
  2670. { "/tor/server/", 1, handle_get_descriptor },
  2671. { "/tor/extra/", 1, handle_get_descriptor },
  2672. { "/tor/keys/", 1, handle_get_keys },
  2673. { "/tor/rendezvous2/", 1, handle_get_hs_descriptor_v2 },
  2674. { "/tor/hs/3/", 1, handle_get_hs_descriptor_v3 },
  2675. { "/tor/robots.txt", 0, handle_get_robots },
  2676. { "/tor/networkstatus-bridges", 0, handle_get_networkstatus_bridges },
  2677. { NULL, 0, NULL },
  2678. };
  2679. /** Helper function: called when a dirserver gets a complete HTTP GET
  2680. * request. Look for a request for a directory or for a rendezvous
  2681. * service descriptor. On finding one, write a response into
  2682. * conn-\>outbuf. If the request is unrecognized, send a 404.
  2683. * Return 0 if we handled this successfully, or -1 if we need to close
  2684. * the connection. */
  2685. MOCK_IMPL(STATIC int,
  2686. directory_handle_command_get,(dir_connection_t *conn, const char *headers,
  2687. const char *req_body, size_t req_body_len))
  2688. {
  2689. char *url, *url_mem, *header;
  2690. time_t if_modified_since = 0;
  2691. int compressed;
  2692. size_t url_len;
  2693. /* We ignore the body of a GET request. */
  2694. (void)req_body;
  2695. (void)req_body_len;
  2696. log_debug(LD_DIRSERV,"Received GET command.");
  2697. conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
  2698. if (parse_http_url(headers, &url) < 0) {
  2699. write_http_status_line(conn, 400, "Bad request");
  2700. return 0;
  2701. }
  2702. if ((header = http_get_header(headers, "If-Modified-Since: "))) {
  2703. struct tm tm;
  2704. if (parse_http_time(header, &tm) == 0) {
  2705. if (tor_timegm(&tm, &if_modified_since)<0) {
  2706. if_modified_since = 0;
  2707. } else {
  2708. log_debug(LD_DIRSERV, "If-Modified-Since is '%s'.", escaped(header));
  2709. }
  2710. }
  2711. /* The correct behavior on a malformed If-Modified-Since header is to
  2712. * act as if no If-Modified-Since header had been given. */
  2713. tor_free(header);
  2714. }
  2715. log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
  2716. url_mem = url;
  2717. url_len = strlen(url);
  2718. compressed = url_len > 2 && !strcmp(url+url_len-2, ".z");
  2719. if (compressed) {
  2720. url[url_len-2] = '\0';
  2721. url_len -= 2;
  2722. }
  2723. get_handler_args_t args;
  2724. args.url = url;
  2725. args.headers = headers;
  2726. args.if_modified_since = if_modified_since;
  2727. args.compressed = compressed;
  2728. int i, result = -1;
  2729. for (i = 0; url_table[i].string; ++i) {
  2730. int match;
  2731. if (url_table[i].is_prefix) {
  2732. match = !strcmpstart(url, url_table[i].string);
  2733. } else {
  2734. match = !strcmp(url, url_table[i].string);
  2735. }
  2736. if (match) {
  2737. result = url_table[i].handler(conn, &args);
  2738. goto done;
  2739. }
  2740. }
  2741. /* we didn't recognize the url */
  2742. write_http_status_line(conn, 404, "Not found");
  2743. result = 0;
  2744. done:
  2745. tor_free(url_mem);
  2746. return result;
  2747. }
  2748. /** Helper function for GET / or GET /tor/
  2749. */
  2750. static int
  2751. handle_get_frontpage(dir_connection_t *conn, const get_handler_args_t *args)
  2752. {
  2753. (void) args; /* unused */
  2754. const char *frontpage = get_dirportfrontpage();
  2755. if (frontpage) {
  2756. size_t dlen;
  2757. dlen = strlen(frontpage);
  2758. /* Let's return a disclaimer page (users shouldn't use V1 anymore,
  2759. and caches don't fetch '/', so this is safe). */
  2760. /* [We don't check for write_bucket_low here, since we want to serve
  2761. * this page no matter what.] */
  2762. write_http_response_header_impl(conn, dlen, "text/html", "identity",
  2763. NULL, DIRPORTFRONTPAGE_CACHE_LIFETIME);
  2764. connection_write_to_buf(frontpage, dlen, TO_CONN(conn));
  2765. } else {
  2766. write_http_status_line(conn, 404, "Not found");
  2767. }
  2768. return 0;
  2769. }
  2770. /** Warn that the consensus <b>v</b> of type <b>flavor</b> is too old and will
  2771. * not be served to clients. Rate-limit the warning to avoid logging an entry
  2772. * on every request.
  2773. */
  2774. static void
  2775. warn_consensus_is_too_old(networkstatus_t *v, const char *flavor, time_t now)
  2776. {
  2777. #define TOO_OLD_WARNING_INTERVAL (60*60)
  2778. static ratelim_t warned = RATELIM_INIT(TOO_OLD_WARNING_INTERVAL);
  2779. char timestamp[ISO_TIME_LEN+1];
  2780. char *dupes;
  2781. if ((dupes = rate_limit_log(&warned, now))) {
  2782. format_local_iso_time(timestamp, v->valid_until);
  2783. log_warn(LD_DIRSERV, "Our %s%sconsensus is too old, so we will not "
  2784. "serve it to clients. It was valid until %s local time and we "
  2785. "continued to serve it for up to 24 hours after it expired.%s",
  2786. flavor ? flavor : "", flavor ? " " : "", timestamp, dupes);
  2787. tor_free(dupes);
  2788. }
  2789. }
  2790. /** Helper function for GET /tor/status-vote/current/consensus
  2791. */
  2792. static int
  2793. handle_get_current_consensus(dir_connection_t *conn,
  2794. const get_handler_args_t *args)
  2795. {
  2796. const char *url = args->url;
  2797. const int compressed = args->compressed;
  2798. const time_t if_modified_since = args->if_modified_since;
  2799. {
  2800. /* v3 network status fetch. */
  2801. smartlist_t *dir_fps = smartlist_new();
  2802. long lifetime = NETWORKSTATUS_CACHE_LIFETIME;
  2803. networkstatus_t *v;
  2804. time_t now = time(NULL);
  2805. const char *want_fps = NULL;
  2806. char *flavor = NULL;
  2807. int flav = FLAV_NS;
  2808. #define CONSENSUS_URL_PREFIX "/tor/status-vote/current/consensus/"
  2809. #define CONSENSUS_FLAVORED_PREFIX "/tor/status-vote/current/consensus-"
  2810. /* figure out the flavor if any, and who we wanted to sign the thing */
  2811. if (!strcmpstart(url, CONSENSUS_FLAVORED_PREFIX)) {
  2812. const char *f, *cp;
  2813. f = url + strlen(CONSENSUS_FLAVORED_PREFIX);
  2814. cp = strchr(f, '/');
  2815. if (cp) {
  2816. want_fps = cp+1;
  2817. flavor = tor_strndup(f, cp-f);
  2818. } else {
  2819. flavor = tor_strdup(f);
  2820. }
  2821. flav = networkstatus_parse_flavor_name(flavor);
  2822. if (flav < 0)
  2823. flav = FLAV_NS;
  2824. } else {
  2825. if (!strcmpstart(url, CONSENSUS_URL_PREFIX))
  2826. want_fps = url+strlen(CONSENSUS_URL_PREFIX);
  2827. }
  2828. v = networkstatus_get_latest_consensus_by_flavor(flav);
  2829. if (v && !networkstatus_consensus_reasonably_live(v, now)) {
  2830. write_http_status_line(conn, 404, "Consensus is too old");
  2831. warn_consensus_is_too_old(v, flavor, now);
  2832. smartlist_free(dir_fps);
  2833. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  2834. tor_free(flavor);
  2835. goto done;
  2836. }
  2837. if (v && want_fps &&
  2838. !client_likes_consensus(v, want_fps)) {
  2839. write_http_status_line(conn, 404, "Consensus not signed by sufficient "
  2840. "number of requested authorities");
  2841. smartlist_free(dir_fps);
  2842. geoip_note_ns_response(GEOIP_REJECT_NOT_ENOUGH_SIGS);
  2843. tor_free(flavor);
  2844. goto done;
  2845. }
  2846. {
  2847. char *fp = tor_malloc_zero(DIGEST_LEN);
  2848. if (flavor)
  2849. strlcpy(fp, flavor, DIGEST_LEN);
  2850. tor_free(flavor);
  2851. smartlist_add(dir_fps, fp);
  2852. }
  2853. lifetime = (v && v->fresh_until > now) ? v->fresh_until - now : 0;
  2854. if (!smartlist_len(dir_fps)) { /* we failed to create/cache cp */
  2855. write_http_status_line(conn, 503, "Network status object unavailable");
  2856. smartlist_free(dir_fps);
  2857. geoip_note_ns_response(GEOIP_REJECT_UNAVAILABLE);
  2858. goto done;
  2859. }
  2860. if (!dirserv_remove_old_statuses(dir_fps, if_modified_since)) {
  2861. write_http_status_line(conn, 404, "Not found");
  2862. SMARTLIST_FOREACH(dir_fps, char *, cp, tor_free(cp));
  2863. smartlist_free(dir_fps);
  2864. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  2865. goto done;
  2866. } else if (!smartlist_len(dir_fps)) {
  2867. write_http_status_line(conn, 304, "Not modified");
  2868. SMARTLIST_FOREACH(dir_fps, char *, cp, tor_free(cp));
  2869. smartlist_free(dir_fps);
  2870. geoip_note_ns_response(GEOIP_REJECT_NOT_MODIFIED);
  2871. goto done;
  2872. }
  2873. size_t dlen = dirserv_estimate_data_size(dir_fps, 0, compressed);
  2874. if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
  2875. log_debug(LD_DIRSERV,
  2876. "Client asked for network status lists, but we've been "
  2877. "writing too many bytes lately. Sending 503 Dir busy.");
  2878. write_http_status_line(conn, 503, "Directory busy, try again later");
  2879. SMARTLIST_FOREACH(dir_fps, char *, fp, tor_free(fp));
  2880. smartlist_free(dir_fps);
  2881. geoip_note_ns_response(GEOIP_REJECT_BUSY);
  2882. goto done;
  2883. }
  2884. tor_addr_t addr;
  2885. if (tor_addr_parse(&addr, (TO_CONN(conn))->address) >= 0) {
  2886. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS,
  2887. &addr, NULL,
  2888. time(NULL));
  2889. geoip_note_ns_response(GEOIP_SUCCESS);
  2890. /* Note that a request for a network status has started, so that we
  2891. * can measure the download time later on. */
  2892. if (conn->dirreq_id)
  2893. geoip_start_dirreq(conn->dirreq_id, dlen, DIRREQ_TUNNELED);
  2894. else
  2895. geoip_start_dirreq(TO_CONN(conn)->global_identifier, dlen,
  2896. DIRREQ_DIRECT);
  2897. }
  2898. write_http_response_header(conn, -1, compressed,
  2899. smartlist_len(dir_fps) == 1 ? lifetime : 0);
  2900. conn->fingerprint_stack = dir_fps;
  2901. if (! compressed)
  2902. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD, HIGH_COMPRESSION);
  2903. /* Prime the connection with some data. */
  2904. conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
  2905. connection_dirserv_flushed_some(conn);
  2906. goto done;
  2907. }
  2908. done:
  2909. return 0;
  2910. }
  2911. /** Helper function for GET /tor/status-vote/{current,next}/...
  2912. */
  2913. static int
  2914. handle_get_status_vote(dir_connection_t *conn, const get_handler_args_t *args)
  2915. {
  2916. const char *url = args->url;
  2917. const int compressed = args->compressed;
  2918. {
  2919. int current;
  2920. ssize_t body_len = 0;
  2921. ssize_t estimated_len = 0;
  2922. smartlist_t *items = smartlist_new();
  2923. smartlist_t *dir_items = smartlist_new();
  2924. int lifetime = 60; /* XXXX?? should actually use vote intervals. */
  2925. url += strlen("/tor/status-vote/");
  2926. current = !strcmpstart(url, "current/");
  2927. url = strchr(url, '/');
  2928. tor_assert(url);
  2929. ++url;
  2930. if (!strcmp(url, "consensus")) {
  2931. const char *item;
  2932. tor_assert(!current); /* we handle current consensus specially above,
  2933. * since it wants to be spooled. */
  2934. if ((item = dirvote_get_pending_consensus(FLAV_NS)))
  2935. smartlist_add(items, (char*)item);
  2936. } else if (!current && !strcmp(url, "consensus-signatures")) {
  2937. /* XXXX the spec says that we should implement
  2938. * current/consensus-signatures too. It doesn't seem to be needed,
  2939. * though. */
  2940. const char *item;
  2941. if ((item=dirvote_get_pending_detached_signatures()))
  2942. smartlist_add(items, (char*)item);
  2943. } else if (!strcmp(url, "authority")) {
  2944. const cached_dir_t *d;
  2945. int flags = DGV_BY_ID |
  2946. (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
  2947. if ((d=dirvote_get_vote(NULL, flags)))
  2948. smartlist_add(dir_items, (cached_dir_t*)d);
  2949. } else {
  2950. const cached_dir_t *d;
  2951. smartlist_t *fps = smartlist_new();
  2952. int flags;
  2953. if (!strcmpstart(url, "d/")) {
  2954. url += 2;
  2955. flags = DGV_INCLUDE_PENDING | DGV_INCLUDE_PREVIOUS;
  2956. } else {
  2957. flags = DGV_BY_ID |
  2958. (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
  2959. }
  2960. dir_split_resource_into_fingerprints(url, fps, NULL,
  2961. DSR_HEX|DSR_SORT_UNIQ);
  2962. SMARTLIST_FOREACH(fps, char *, fp, {
  2963. if ((d = dirvote_get_vote(fp, flags)))
  2964. smartlist_add(dir_items, (cached_dir_t*)d);
  2965. tor_free(fp);
  2966. });
  2967. smartlist_free(fps);
  2968. }
  2969. if (!smartlist_len(dir_items) && !smartlist_len(items)) {
  2970. write_http_status_line(conn, 404, "Not found");
  2971. goto vote_done;
  2972. }
  2973. SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
  2974. body_len += compressed ? d->dir_z_len : d->dir_len);
  2975. estimated_len += body_len;
  2976. SMARTLIST_FOREACH(items, const char *, item, {
  2977. size_t ln = strlen(item);
  2978. if (compressed) {
  2979. estimated_len += ln/2;
  2980. } else {
  2981. body_len += ln; estimated_len += ln;
  2982. }
  2983. });
  2984. if (global_write_bucket_low(TO_CONN(conn), estimated_len, 2)) {
  2985. write_http_status_line(conn, 503, "Directory busy, try again later");
  2986. goto vote_done;
  2987. }
  2988. write_http_response_header(conn, body_len ? body_len : -1, compressed,
  2989. lifetime);
  2990. if (smartlist_len(items)) {
  2991. if (compressed) {
  2992. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD,
  2993. choose_compression_level(estimated_len));
  2994. SMARTLIST_FOREACH(items, const char *, c,
  2995. connection_write_to_buf_zlib(c, strlen(c), conn, 0));
  2996. connection_write_to_buf_zlib("", 0, conn, 1);
  2997. } else {
  2998. SMARTLIST_FOREACH(items, const char *, c,
  2999. connection_write_to_buf(c, strlen(c), TO_CONN(conn)));
  3000. }
  3001. } else {
  3002. SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
  3003. connection_write_to_buf(compressed ? d->dir_z : d->dir,
  3004. compressed ? d->dir_z_len : d->dir_len,
  3005. TO_CONN(conn)));
  3006. }
  3007. vote_done:
  3008. smartlist_free(items);
  3009. smartlist_free(dir_items);
  3010. goto done;
  3011. }
  3012. done:
  3013. return 0;
  3014. }
  3015. /** Helper function for GET /tor/micro/d/...
  3016. */
  3017. static int
  3018. handle_get_microdesc(dir_connection_t *conn, const get_handler_args_t *args)
  3019. {
  3020. const char *url = args->url;
  3021. const int compressed = args->compressed;
  3022. {
  3023. smartlist_t *fps = smartlist_new();
  3024. dir_split_resource_into_fingerprints(url+strlen("/tor/micro/d/"),
  3025. fps, NULL,
  3026. DSR_DIGEST256|DSR_BASE64|DSR_SORT_UNIQ);
  3027. if (!dirserv_have_any_microdesc(fps)) {
  3028. write_http_status_line(conn, 404, "Not found");
  3029. SMARTLIST_FOREACH(fps, char *, fp, tor_free(fp));
  3030. smartlist_free(fps);
  3031. goto done;
  3032. }
  3033. size_t dlen = dirserv_estimate_microdesc_size(fps, compressed);
  3034. if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
  3035. log_info(LD_DIRSERV,
  3036. "Client asked for server descriptors, but we've been "
  3037. "writing too many bytes lately. Sending 503 Dir busy.");
  3038. write_http_status_line(conn, 503, "Directory busy, try again later");
  3039. SMARTLIST_FOREACH(fps, char *, fp, tor_free(fp));
  3040. smartlist_free(fps);
  3041. goto done;
  3042. }
  3043. write_http_response_header(conn, -1, compressed, MICRODESC_CACHE_LIFETIME);
  3044. conn->dir_spool_src = DIR_SPOOL_MICRODESC;
  3045. conn->fingerprint_stack = fps;
  3046. if (compressed)
  3047. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD,
  3048. choose_compression_level(dlen));
  3049. connection_dirserv_flushed_some(conn);
  3050. goto done;
  3051. }
  3052. done:
  3053. return 0;
  3054. }
  3055. /** Helper function for GET /tor/{server,extra}/...
  3056. */
  3057. static int
  3058. handle_get_descriptor(dir_connection_t *conn, const get_handler_args_t *args)
  3059. {
  3060. const char *url = args->url;
  3061. const int compressed = args->compressed;
  3062. const or_options_t *options = get_options();
  3063. if (!strcmpstart(url,"/tor/server/") ||
  3064. (!options->BridgeAuthoritativeDir &&
  3065. !options->BridgeRelay && !strcmpstart(url,"/tor/extra/"))) {
  3066. size_t dlen;
  3067. int res;
  3068. const char *msg;
  3069. int cache_lifetime = 0;
  3070. int is_extra = !strcmpstart(url,"/tor/extra/");
  3071. url += is_extra ? strlen("/tor/extra/") : strlen("/tor/server/");
  3072. conn->fingerprint_stack = smartlist_new();
  3073. res = dirserv_get_routerdesc_fingerprints(conn->fingerprint_stack, url,
  3074. &msg,
  3075. !connection_dir_is_encrypted(conn),
  3076. is_extra);
  3077. if (!strcmpstart(url, "fp/")) {
  3078. if (smartlist_len(conn->fingerprint_stack) == 1)
  3079. cache_lifetime = ROUTERDESC_CACHE_LIFETIME;
  3080. } else if (!strcmpstart(url, "authority")) {
  3081. cache_lifetime = ROUTERDESC_CACHE_LIFETIME;
  3082. } else if (!strcmpstart(url, "all")) {
  3083. cache_lifetime = FULL_DIR_CACHE_LIFETIME;
  3084. } else if (!strcmpstart(url, "d/")) {
  3085. if (smartlist_len(conn->fingerprint_stack) == 1)
  3086. cache_lifetime = ROUTERDESC_BY_DIGEST_CACHE_LIFETIME;
  3087. }
  3088. if (!strcmpstart(url, "d/"))
  3089. conn->dir_spool_src =
  3090. is_extra ? DIR_SPOOL_EXTRA_BY_DIGEST : DIR_SPOOL_SERVER_BY_DIGEST;
  3091. else
  3092. conn->dir_spool_src =
  3093. is_extra ? DIR_SPOOL_EXTRA_BY_FP : DIR_SPOOL_SERVER_BY_FP;
  3094. if (!dirserv_have_any_serverdesc(conn->fingerprint_stack,
  3095. conn->dir_spool_src)) {
  3096. res = -1;
  3097. msg = "Not found";
  3098. }
  3099. if (res < 0)
  3100. write_http_status_line(conn, 404, msg);
  3101. else {
  3102. dlen = dirserv_estimate_data_size(conn->fingerprint_stack,
  3103. 1, compressed);
  3104. if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
  3105. log_info(LD_DIRSERV,
  3106. "Client asked for server descriptors, but we've been "
  3107. "writing too many bytes lately. Sending 503 Dir busy.");
  3108. write_http_status_line(conn, 503, "Directory busy, try again later");
  3109. conn->dir_spool_src = DIR_SPOOL_NONE;
  3110. goto done;
  3111. }
  3112. write_http_response_header(conn, -1, compressed, cache_lifetime);
  3113. if (compressed)
  3114. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD,
  3115. choose_compression_level(dlen));
  3116. /* Prime the connection with some data. */
  3117. connection_dirserv_flushed_some(conn);
  3118. }
  3119. goto done;
  3120. }
  3121. done:
  3122. return 0;
  3123. }
  3124. /** Helper function for GET /tor/keys/...
  3125. */
  3126. static int
  3127. handle_get_keys(dir_connection_t *conn, const get_handler_args_t *args)
  3128. {
  3129. const char *url = args->url;
  3130. const int compressed = args->compressed;
  3131. const time_t if_modified_since = args->if_modified_since;
  3132. {
  3133. smartlist_t *certs = smartlist_new();
  3134. ssize_t len = -1;
  3135. if (!strcmp(url, "/tor/keys/all")) {
  3136. authority_cert_get_all(certs);
  3137. } else if (!strcmp(url, "/tor/keys/authority")) {
  3138. authority_cert_t *cert = get_my_v3_authority_cert();
  3139. if (cert)
  3140. smartlist_add(certs, cert);
  3141. } else if (!strcmpstart(url, "/tor/keys/fp/")) {
  3142. smartlist_t *fps = smartlist_new();
  3143. dir_split_resource_into_fingerprints(url+strlen("/tor/keys/fp/"),
  3144. fps, NULL,
  3145. DSR_HEX|DSR_SORT_UNIQ);
  3146. SMARTLIST_FOREACH(fps, char *, d, {
  3147. authority_cert_t *c = authority_cert_get_newest_by_id(d);
  3148. if (c) smartlist_add(certs, c);
  3149. tor_free(d);
  3150. });
  3151. smartlist_free(fps);
  3152. } else if (!strcmpstart(url, "/tor/keys/sk/")) {
  3153. smartlist_t *fps = smartlist_new();
  3154. dir_split_resource_into_fingerprints(url+strlen("/tor/keys/sk/"),
  3155. fps, NULL,
  3156. DSR_HEX|DSR_SORT_UNIQ);
  3157. SMARTLIST_FOREACH(fps, char *, d, {
  3158. authority_cert_t *c = authority_cert_get_by_sk_digest(d);
  3159. if (c) smartlist_add(certs, c);
  3160. tor_free(d);
  3161. });
  3162. smartlist_free(fps);
  3163. } else if (!strcmpstart(url, "/tor/keys/fp-sk/")) {
  3164. smartlist_t *fp_sks = smartlist_new();
  3165. dir_split_resource_into_fingerprint_pairs(url+strlen("/tor/keys/fp-sk/"),
  3166. fp_sks);
  3167. SMARTLIST_FOREACH(fp_sks, fp_pair_t *, pair, {
  3168. authority_cert_t *c = authority_cert_get_by_digests(pair->first,
  3169. pair->second);
  3170. if (c) smartlist_add(certs, c);
  3171. tor_free(pair);
  3172. });
  3173. smartlist_free(fp_sks);
  3174. } else {
  3175. write_http_status_line(conn, 400, "Bad request");
  3176. goto keys_done;
  3177. }
  3178. if (!smartlist_len(certs)) {
  3179. write_http_status_line(conn, 404, "Not found");
  3180. goto keys_done;
  3181. }
  3182. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  3183. if (c->cache_info.published_on < if_modified_since)
  3184. SMARTLIST_DEL_CURRENT(certs, c));
  3185. if (!smartlist_len(certs)) {
  3186. write_http_status_line(conn, 304, "Not modified");
  3187. goto keys_done;
  3188. }
  3189. len = 0;
  3190. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  3191. len += c->cache_info.signed_descriptor_len);
  3192. if (global_write_bucket_low(TO_CONN(conn), compressed?len/2:len, 2)) {
  3193. write_http_status_line(conn, 503, "Directory busy, try again later");
  3194. goto keys_done;
  3195. }
  3196. write_http_response_header(conn, compressed?-1:len, compressed, 60*60);
  3197. if (compressed) {
  3198. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD,
  3199. choose_compression_level(len));
  3200. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  3201. connection_write_to_buf_zlib(c->cache_info.signed_descriptor_body,
  3202. c->cache_info.signed_descriptor_len,
  3203. conn, 0));
  3204. connection_write_to_buf_zlib("", 0, conn, 1);
  3205. } else {
  3206. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  3207. connection_write_to_buf(c->cache_info.signed_descriptor_body,
  3208. c->cache_info.signed_descriptor_len,
  3209. TO_CONN(conn)));
  3210. }
  3211. keys_done:
  3212. smartlist_free(certs);
  3213. goto done;
  3214. }
  3215. done:
  3216. return 0;
  3217. }
  3218. /** Helper function for GET /tor/rendezvous2/
  3219. */
  3220. static int
  3221. handle_get_hs_descriptor_v2(dir_connection_t *conn,
  3222. const get_handler_args_t *args)
  3223. {
  3224. const char *url = args->url;
  3225. if (connection_dir_is_encrypted(conn)) {
  3226. /* Handle v2 rendezvous descriptor fetch request. */
  3227. const char *descp;
  3228. const char *query = url + strlen("/tor/rendezvous2/");
  3229. if (rend_valid_descriptor_id(query)) {
  3230. log_info(LD_REND, "Got a v2 rendezvous descriptor request for ID '%s'",
  3231. safe_str(escaped(query)));
  3232. switch (rend_cache_lookup_v2_desc_as_dir(query, &descp)) {
  3233. case 1: /* valid */
  3234. write_http_response_header(conn, strlen(descp), 0, 0);
  3235. connection_write_to_buf(descp, strlen(descp), TO_CONN(conn));
  3236. break;
  3237. case 0: /* well-formed but not present */
  3238. write_http_status_line(conn, 404, "Not found");
  3239. break;
  3240. case -1: /* not well-formed */
  3241. write_http_status_line(conn, 400, "Bad request");
  3242. break;
  3243. }
  3244. } else { /* not well-formed */
  3245. write_http_status_line(conn, 400, "Bad request");
  3246. }
  3247. goto done;
  3248. } else {
  3249. /* Not encrypted! */
  3250. write_http_status_line(conn, 404, "Not found");
  3251. }
  3252. done:
  3253. return 0;
  3254. }
  3255. /** Helper function for GET /tor/hs/3/<z>. Only for version 3.
  3256. */
  3257. STATIC int
  3258. handle_get_hs_descriptor_v3(dir_connection_t *conn,
  3259. const get_handler_args_t *args)
  3260. {
  3261. int retval;
  3262. const char *desc_str = NULL;
  3263. const char *pubkey_str = NULL;
  3264. const char *url = args->url;
  3265. /* Reject unencrypted dir connections */
  3266. if (!connection_dir_is_encrypted(conn)) {
  3267. write_http_status_line(conn, 404, "Not found");
  3268. goto done;
  3269. }
  3270. /* After the path prefix follows the base64 encoded blinded pubkey which we
  3271. * use to get the descriptor from the cache. Skip the prefix and get the
  3272. * pubkey. */
  3273. tor_assert(!strcmpstart(url, "/tor/hs/3/"));
  3274. pubkey_str = url + strlen("/tor/hs/3/");
  3275. retval = hs_cache_lookup_as_dir(HS_VERSION_THREE,
  3276. pubkey_str, &desc_str);
  3277. if (retval < 0) {
  3278. write_http_status_line(conn, 404, "Not found");
  3279. goto done;
  3280. }
  3281. /* Found requested descriptor! Pass it to this nice client. */
  3282. write_http_response_header(conn, strlen(desc_str), 0, 0);
  3283. connection_write_to_buf(desc_str, strlen(desc_str), TO_CONN(conn));
  3284. done:
  3285. return 0;
  3286. }
  3287. /** Helper function for GET /tor/networkstatus-bridges
  3288. */
  3289. static int
  3290. handle_get_networkstatus_bridges(dir_connection_t *conn,
  3291. const get_handler_args_t *args)
  3292. {
  3293. const char *headers = args->headers;
  3294. const or_options_t *options = get_options();
  3295. if (options->BridgeAuthoritativeDir &&
  3296. options->BridgePassword_AuthDigest_ &&
  3297. connection_dir_is_encrypted(conn)) {
  3298. char *status;
  3299. char digest[DIGEST256_LEN];
  3300. char *header = http_get_header(headers, "Authorization: Basic ");
  3301. if (header)
  3302. crypto_digest256(digest, header, strlen(header), DIGEST_SHA256);
  3303. /* now make sure the password is there and right */
  3304. if (!header ||
  3305. tor_memneq(digest,
  3306. options->BridgePassword_AuthDigest_, DIGEST256_LEN)) {
  3307. write_http_status_line(conn, 404, "Not found");
  3308. tor_free(header);
  3309. goto done;
  3310. }
  3311. tor_free(header);
  3312. /* all happy now. send an answer. */
  3313. status = networkstatus_getinfo_by_purpose("bridge", time(NULL));
  3314. size_t dlen = strlen(status);
  3315. write_http_response_header(conn, dlen, 0, 0);
  3316. connection_write_to_buf(status, dlen, TO_CONN(conn));
  3317. tor_free(status);
  3318. goto done;
  3319. }
  3320. done:
  3321. return 0;
  3322. }
  3323. /** Helper function for GET robots.txt or /tor/robots.txt */
  3324. static int
  3325. handle_get_robots(dir_connection_t *conn, const get_handler_args_t *args)
  3326. {
  3327. (void)args;
  3328. {
  3329. const char robots[] = "User-agent: *\r\nDisallow: /\r\n";
  3330. size_t len = strlen(robots);
  3331. write_http_response_header(conn, len, 0, ROBOTS_CACHE_LIFETIME);
  3332. connection_write_to_buf(robots, len, TO_CONN(conn));
  3333. }
  3334. return 0;
  3335. }
  3336. /* Given the <b>url</b> from a POST request, try to extract the version number
  3337. * using the provided <b>prefix</b>. The version should be after the prefix and
  3338. * ending with the seperator "/". For instance:
  3339. * /tor/hs/3/publish
  3340. *
  3341. * On success, <b>end_pos</b> points to the position right after the version
  3342. * was found. On error, it is set to NULL.
  3343. *
  3344. * Return version on success else negative value. */
  3345. STATIC int
  3346. parse_hs_version_from_post(const char *url, const char *prefix,
  3347. const char **end_pos)
  3348. {
  3349. int ok;
  3350. unsigned long version;
  3351. const char *start;
  3352. char *end = NULL;
  3353. tor_assert(url);
  3354. tor_assert(prefix);
  3355. tor_assert(end_pos);
  3356. /* Check if the prefix does start the url. */
  3357. if (strcmpstart(url, prefix)) {
  3358. goto err;
  3359. }
  3360. /* Move pointer to the end of the prefix string. */
  3361. start = url + strlen(prefix);
  3362. /* Try this to be the HS version and if we are still at the separator, next
  3363. * will be move to the right value. */
  3364. version = tor_parse_long(start, 10, 0, INT_MAX, &ok, &end);
  3365. if (!ok) {
  3366. goto err;
  3367. }
  3368. *end_pos = end;
  3369. return (int) version;
  3370. err:
  3371. *end_pos = NULL;
  3372. return -1;
  3373. }
  3374. /* Handle the POST request for a hidden service descripror. The request is in
  3375. * <b>url</b>, the body of the request is in <b>body</b>. Return 200 on success
  3376. * else return 400 indicating a bad request. */
  3377. STATIC int
  3378. handle_post_hs_descriptor(const char *url, const char *body)
  3379. {
  3380. int version;
  3381. const char *end_pos;
  3382. tor_assert(url);
  3383. tor_assert(body);
  3384. version = parse_hs_version_from_post(url, "/tor/hs/", &end_pos);
  3385. if (version < 0) {
  3386. goto err;
  3387. }
  3388. /* We have a valid version number, now make sure it's a publish request. Use
  3389. * the end position just after the version and check for the command. */
  3390. if (strcmpstart(end_pos, "/publish")) {
  3391. goto err;
  3392. }
  3393. switch (version) {
  3394. case HS_VERSION_THREE:
  3395. if (hs_cache_store_as_dir(body) < 0) {
  3396. goto err;
  3397. }
  3398. log_info(LD_REND, "Publish request for HS descriptor handled "
  3399. "successfully.");
  3400. break;
  3401. default:
  3402. /* Unsupported version, return a bad request. */
  3403. goto err;
  3404. }
  3405. return 200;
  3406. err:
  3407. /* Bad request. */
  3408. return 400;
  3409. }
  3410. /** Helper function: called when a dirserver gets a complete HTTP POST
  3411. * request. Look for an uploaded server descriptor or rendezvous
  3412. * service descriptor. On finding one, process it and write a
  3413. * response into conn-\>outbuf. If the request is unrecognized, send a
  3414. * 400. Always return 0. */
  3415. MOCK_IMPL(STATIC int,
  3416. directory_handle_command_post,(dir_connection_t *conn, const char *headers,
  3417. const char *body, size_t body_len))
  3418. {
  3419. char *url = NULL;
  3420. const or_options_t *options = get_options();
  3421. log_debug(LD_DIRSERV,"Received POST command.");
  3422. conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
  3423. if (!public_server_mode(options)) {
  3424. log_info(LD_DIR, "Rejected dir post request from %s "
  3425. "since we're not a public relay.", conn->base_.address);
  3426. write_http_status_line(conn, 503, "Not acting as a public relay");
  3427. goto done;
  3428. }
  3429. if (parse_http_url(headers, &url) < 0) {
  3430. write_http_status_line(conn, 400, "Bad request");
  3431. return 0;
  3432. }
  3433. log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
  3434. /* Handle v2 rendezvous service publish request. */
  3435. if (connection_dir_is_encrypted(conn) &&
  3436. !strcmpstart(url,"/tor/rendezvous2/publish")) {
  3437. if (rend_cache_store_v2_desc_as_dir(body) < 0) {
  3438. log_warn(LD_REND, "Rejected v2 rend descriptor (length %d) from %s.",
  3439. (int)body_len, conn->base_.address);
  3440. write_http_status_line(conn, 400,
  3441. "Invalid v2 service descriptor rejected");
  3442. } else {
  3443. write_http_status_line(conn, 200, "Service descriptor (v2) stored");
  3444. log_info(LD_REND, "Handled v2 rendezvous descriptor post: accepted");
  3445. }
  3446. goto done;
  3447. }
  3448. /* Handle HS descriptor publish request. */
  3449. /* XXX: This should be disabled with a consensus param until we want to
  3450. * the prop224 be deployed and thus use. */
  3451. if (connection_dir_is_encrypted(conn) && !strcmpstart(url, "/tor/hs/")) {
  3452. const char *msg = "HS descriptor stored successfully.";
  3453. /* We most probably have a publish request for an HS descriptor. */
  3454. int code = handle_post_hs_descriptor(url, body);
  3455. if (code != 200) {
  3456. msg = "Invalid HS descriptor. Rejected.";
  3457. }
  3458. write_http_status_line(conn, code, msg);
  3459. goto done;
  3460. }
  3461. if (!authdir_mode(options)) {
  3462. /* we just provide cached directories; we don't want to
  3463. * receive anything. */
  3464. write_http_status_line(conn, 400, "Nonauthoritative directory does not "
  3465. "accept posted server descriptors");
  3466. goto done;
  3467. }
  3468. if (authdir_mode_handles_descs(options, -1) &&
  3469. !strcmp(url,"/tor/")) { /* server descriptor post */
  3470. const char *msg = "[None]";
  3471. uint8_t purpose = authdir_mode_bridge(options) ?
  3472. ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  3473. was_router_added_t r = dirserv_add_multiple_descriptors(body, purpose,
  3474. conn->base_.address, &msg);
  3475. tor_assert(msg);
  3476. if (r == ROUTER_ADDED_NOTIFY_GENERATOR) {
  3477. /* Accepted with a message. */
  3478. log_info(LD_DIRSERV,
  3479. "Problematic router descriptor or extra-info from %s "
  3480. "(\"%s\").",
  3481. conn->base_.address, msg);
  3482. write_http_status_line(conn, 400, msg);
  3483. } else if (r == ROUTER_ADDED_SUCCESSFULLY) {
  3484. write_http_status_line(conn, 200, msg);
  3485. } else if (WRA_WAS_OUTDATED(r)) {
  3486. write_http_response_header_impl(conn, -1, NULL, NULL,
  3487. "X-Descriptor-Not-New: Yes\r\n", -1);
  3488. } else {
  3489. log_info(LD_DIRSERV,
  3490. "Rejected router descriptor or extra-info from %s "
  3491. "(\"%s\").",
  3492. conn->base_.address, msg);
  3493. write_http_status_line(conn, 400, msg);
  3494. }
  3495. goto done;
  3496. }
  3497. if (authdir_mode_v3(options) &&
  3498. !strcmp(url,"/tor/post/vote")) { /* v3 networkstatus vote */
  3499. const char *msg = "OK";
  3500. int status;
  3501. if (dirvote_add_vote(body, &msg, &status)) {
  3502. write_http_status_line(conn, status, "Vote stored");
  3503. } else {
  3504. tor_assert(msg);
  3505. log_warn(LD_DIRSERV, "Rejected vote from %s (\"%s\").",
  3506. conn->base_.address, msg);
  3507. write_http_status_line(conn, status, msg);
  3508. }
  3509. goto done;
  3510. }
  3511. if (authdir_mode_v3(options) &&
  3512. !strcmp(url,"/tor/post/consensus-signature")) { /* sigs on consensus. */
  3513. const char *msg = NULL;
  3514. if (dirvote_add_signatures(body, conn->base_.address, &msg)>=0) {
  3515. write_http_status_line(conn, 200, msg?msg:"Signatures stored");
  3516. } else {
  3517. log_warn(LD_DIR, "Unable to store signatures posted by %s: %s",
  3518. conn->base_.address, msg?msg:"???");
  3519. write_http_status_line(conn, 400, msg?msg:"Unable to store signatures");
  3520. }
  3521. goto done;
  3522. }
  3523. /* we didn't recognize the url */
  3524. write_http_status_line(conn, 404, "Not found");
  3525. done:
  3526. tor_free(url);
  3527. return 0;
  3528. }
  3529. /** Called when a dirserver receives data on a directory connection;
  3530. * looks for an HTTP request. If the request is complete, remove it
  3531. * from the inbuf, try to process it; otherwise, leave it on the
  3532. * buffer. Return a 0 on success, or -1 on error.
  3533. */
  3534. STATIC int
  3535. directory_handle_command(dir_connection_t *conn)
  3536. {
  3537. char *headers=NULL, *body=NULL;
  3538. size_t body_len=0;
  3539. int r;
  3540. tor_assert(conn);
  3541. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  3542. switch (connection_fetch_from_buf_http(TO_CONN(conn),
  3543. &headers, MAX_HEADERS_SIZE,
  3544. &body, &body_len, MAX_DIR_UL_SIZE, 0)) {
  3545. case -1: /* overflow */
  3546. log_warn(LD_DIRSERV,
  3547. "Request too large from address '%s' to DirPort. Closing.",
  3548. safe_str(conn->base_.address));
  3549. return -1;
  3550. case 0:
  3551. log_debug(LD_DIRSERV,"command not all here yet.");
  3552. return 0;
  3553. /* case 1, fall through */
  3554. }
  3555. http_set_address_origin(headers, TO_CONN(conn));
  3556. // we should escape headers here as well,
  3557. // but we can't call escaped() twice, as it uses the same buffer
  3558. //log_debug(LD_DIRSERV,"headers %s, body %s.", headers, escaped(body));
  3559. if (!strncasecmp(headers,"GET",3))
  3560. r = directory_handle_command_get(conn, headers, body, body_len);
  3561. else if (!strncasecmp(headers,"POST",4))
  3562. r = directory_handle_command_post(conn, headers, body, body_len);
  3563. else {
  3564. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3565. "Got headers %s with unknown command. Closing.",
  3566. escaped(headers));
  3567. r = -1;
  3568. }
  3569. tor_free(headers); tor_free(body);
  3570. return r;
  3571. }
  3572. /** Write handler for directory connections; called when all data has
  3573. * been flushed. Close the connection or wait for a response as
  3574. * appropriate.
  3575. */
  3576. int
  3577. connection_dir_finished_flushing(dir_connection_t *conn)
  3578. {
  3579. tor_assert(conn);
  3580. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  3581. /* Note that we have finished writing the directory response. For direct
  3582. * connections this means we're done; for tunneled connections it's only
  3583. * an intermediate step. */
  3584. if (conn->dirreq_id)
  3585. geoip_change_dirreq_state(conn->dirreq_id, DIRREQ_TUNNELED,
  3586. DIRREQ_FLUSHING_DIR_CONN_FINISHED);
  3587. else
  3588. geoip_change_dirreq_state(TO_CONN(conn)->global_identifier,
  3589. DIRREQ_DIRECT,
  3590. DIRREQ_FLUSHING_DIR_CONN_FINISHED);
  3591. switch (conn->base_.state) {
  3592. case DIR_CONN_STATE_CONNECTING:
  3593. case DIR_CONN_STATE_CLIENT_SENDING:
  3594. log_debug(LD_DIR,"client finished sending command.");
  3595. conn->base_.state = DIR_CONN_STATE_CLIENT_READING;
  3596. return 0;
  3597. case DIR_CONN_STATE_SERVER_WRITING:
  3598. if (conn->dir_spool_src != DIR_SPOOL_NONE) {
  3599. log_warn(LD_BUG, "Emptied a dirserv buffer, but it's still spooling!");
  3600. connection_mark_for_close(TO_CONN(conn));
  3601. } else {
  3602. log_debug(LD_DIRSERV, "Finished writing server response. Closing.");
  3603. connection_mark_for_close(TO_CONN(conn));
  3604. }
  3605. return 0;
  3606. default:
  3607. log_warn(LD_BUG,"called in unexpected state %d.",
  3608. conn->base_.state);
  3609. tor_fragile_assert();
  3610. return -1;
  3611. }
  3612. return 0;
  3613. }
  3614. /* We just got a new consensus! If there are other in-progress requests
  3615. * for this consensus flavor (for example because we launched several in
  3616. * parallel), cancel them.
  3617. *
  3618. * We do this check here (not just in
  3619. * connection_ap_handshake_attach_circuit()) to handle the edge case where
  3620. * a consensus fetch begins and ends before some other one tries to attach to
  3621. * a circuit, in which case the other one won't know that we're all happy now.
  3622. *
  3623. * Don't mark the conn that just gave us the consensus -- otherwise we
  3624. * would end up double-marking it when it cleans itself up.
  3625. */
  3626. static void
  3627. connection_dir_close_consensus_fetches(dir_connection_t *except_this_one,
  3628. const char *resource)
  3629. {
  3630. smartlist_t *conns_to_close =
  3631. connection_dir_list_by_purpose_and_resource(DIR_PURPOSE_FETCH_CONSENSUS,
  3632. resource);
  3633. SMARTLIST_FOREACH_BEGIN(conns_to_close, dir_connection_t *, d) {
  3634. if (d == except_this_one)
  3635. continue;
  3636. log_info(LD_DIR, "Closing consensus fetch (to %s) since one "
  3637. "has just arrived.", TO_CONN(d)->address);
  3638. connection_mark_for_close(TO_CONN(d));
  3639. } SMARTLIST_FOREACH_END(d);
  3640. smartlist_free(conns_to_close);
  3641. }
  3642. /** Connected handler for directory connections: begin sending data to the
  3643. * server, and return 0.
  3644. * Only used when connections don't immediately connect. */
  3645. int
  3646. connection_dir_finished_connecting(dir_connection_t *conn)
  3647. {
  3648. tor_assert(conn);
  3649. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  3650. tor_assert(conn->base_.state == DIR_CONN_STATE_CONNECTING);
  3651. log_debug(LD_HTTP,"Dir connection to router %s:%u established.",
  3652. conn->base_.address,conn->base_.port);
  3653. /* start flushing conn */
  3654. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  3655. return 0;
  3656. }
  3657. /** Decide which download schedule we want to use based on descriptor type
  3658. * in <b>dls</b> and <b>options</b>.
  3659. * Then return a list of int pointers defining download delays in seconds.
  3660. * Helper function for download_status_increment_failure(),
  3661. * download_status_reset(), and download_status_increment_attempt(). */
  3662. STATIC const smartlist_t *
  3663. find_dl_schedule(download_status_t *dls, const or_options_t *options)
  3664. {
  3665. const int dir_server = dir_server_mode(options);
  3666. const int multi_d = networkstatus_consensus_can_use_multiple_directories(
  3667. options);
  3668. const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
  3669. time(NULL));
  3670. const int use_fallbacks = networkstatus_consensus_can_use_extra_fallbacks(
  3671. options);
  3672. switch (dls->schedule) {
  3673. case DL_SCHED_GENERIC:
  3674. if (dir_server) {
  3675. return options->TestingServerDownloadSchedule;
  3676. } else {
  3677. return options->TestingClientDownloadSchedule;
  3678. }
  3679. case DL_SCHED_CONSENSUS:
  3680. if (!multi_d) {
  3681. return options->TestingServerConsensusDownloadSchedule;
  3682. } else {
  3683. if (we_are_bootstrapping) {
  3684. if (!use_fallbacks) {
  3685. /* A bootstrapping client without extra fallback directories */
  3686. return
  3687. options->ClientBootstrapConsensusAuthorityOnlyDownloadSchedule;
  3688. } else if (dls->want_authority) {
  3689. /* A bootstrapping client with extra fallback directories, but
  3690. * connecting to an authority */
  3691. return
  3692. options->ClientBootstrapConsensusAuthorityDownloadSchedule;
  3693. } else {
  3694. /* A bootstrapping client connecting to extra fallback directories
  3695. */
  3696. return
  3697. options->ClientBootstrapConsensusFallbackDownloadSchedule;
  3698. }
  3699. } else {
  3700. return options->TestingClientConsensusDownloadSchedule;
  3701. }
  3702. }
  3703. case DL_SCHED_BRIDGE:
  3704. return options->TestingBridgeDownloadSchedule;
  3705. default:
  3706. tor_assert(0);
  3707. }
  3708. /* Impossible, but gcc will fail with -Werror without a `return`. */
  3709. return NULL;
  3710. }
  3711. /** Decide which minimum and maximum delay step we want to use based on
  3712. * descriptor type in <b>dls</b> and <b>options</b>.
  3713. * Helper function for download_status_schedule_get_delay(). */
  3714. STATIC void
  3715. find_dl_min_and_max_delay(download_status_t *dls, const or_options_t *options,
  3716. int *min, int *max)
  3717. {
  3718. tor_assert(dls);
  3719. tor_assert(options);
  3720. tor_assert(min);
  3721. tor_assert(max);
  3722. /*
  3723. * For now, just use the existing schedule config stuff and pick the
  3724. * first/last entries off to get min/max delay for backoff purposes
  3725. */
  3726. const smartlist_t *schedule = find_dl_schedule(dls, options);
  3727. tor_assert(schedule != NULL && smartlist_len(schedule) >= 2);
  3728. *min = *((int *)(smartlist_get(schedule, 0)));
  3729. if (dls->backoff == DL_SCHED_DETERMINISTIC)
  3730. *max = *((int *)((smartlist_get(schedule, smartlist_len(schedule) - 1))));
  3731. else
  3732. *max = INT_MAX;
  3733. }
  3734. /** Advance one delay step. The algorithm is to use the previous delay to
  3735. * compute an increment, we construct a value uniformly at random between
  3736. * delay and MAX(delay*2,delay+1). We then clamp that value to be no larger
  3737. * than max_delay, and return it.
  3738. *
  3739. * Requires that delay is less than INT_MAX, and delay is in [0,max_delay].
  3740. */
  3741. STATIC int
  3742. next_random_exponential_delay(int delay, int max_delay)
  3743. {
  3744. /* Check preconditions */
  3745. if (BUG(max_delay < 0))
  3746. max_delay = 0;
  3747. if (BUG(delay > max_delay))
  3748. delay = max_delay;
  3749. if (delay == INT_MAX)
  3750. return INT_MAX; /* prevent overflow */
  3751. if (BUG(delay < 0))
  3752. delay = 0;
  3753. /* How much are we willing to add to the delay? */
  3754. int max_increment;
  3755. int multiplier = 3; /* no more than quadruple the previous delay */
  3756. if (get_options()->TestingTorNetwork) {
  3757. /* Decrease the multiplier in testing networks. This reduces the variance,
  3758. * so that bootstrap is more reliable. */
  3759. multiplier = 2; /* no more than triple the previous delay */
  3760. }
  3761. if (delay && delay < (INT_MAX-1) / multiplier) {
  3762. max_increment = delay * multiplier;
  3763. } else if (delay) {
  3764. max_increment = INT_MAX-1;
  3765. } else {
  3766. max_increment = 1;
  3767. }
  3768. if (BUG(max_increment < 1))
  3769. max_increment = 1;
  3770. /* the + 1 here is so that we always wait longer than last time. */
  3771. int increment = crypto_rand_int(max_increment)+1;
  3772. if (increment < max_delay - delay)
  3773. return delay + increment;
  3774. else
  3775. return max_delay;
  3776. }
  3777. /** Find the current delay for dls based on schedule or min_delay/
  3778. * max_delay if we're using exponential backoff. If dls->backoff is
  3779. * DL_SCHED_RANDOM_EXPONENTIAL, we must have 0 <= min_delay <= max_delay <=
  3780. * INT_MAX, but schedule may be set to NULL; otherwise schedule is required.
  3781. * This function sets dls->next_attempt_at based on now, and returns the delay.
  3782. * Helper for download_status_increment_failure and
  3783. * download_status_increment_attempt. */
  3784. STATIC int
  3785. download_status_schedule_get_delay(download_status_t *dls,
  3786. const smartlist_t *schedule,
  3787. int min_delay, int max_delay,
  3788. time_t now)
  3789. {
  3790. tor_assert(dls);
  3791. /* We don't need a schedule if we're using random exponential backoff */
  3792. tor_assert(dls->backoff == DL_SCHED_RANDOM_EXPONENTIAL ||
  3793. schedule != NULL);
  3794. /* If we're using random exponential backoff, we do need min/max delay */
  3795. tor_assert(dls->backoff != DL_SCHED_RANDOM_EXPONENTIAL ||
  3796. (min_delay >= 0 && max_delay >= min_delay));
  3797. int delay = INT_MAX;
  3798. uint8_t dls_schedule_position = (dls->increment_on
  3799. == DL_SCHED_INCREMENT_ATTEMPT
  3800. ? dls->n_download_attempts
  3801. : dls->n_download_failures);
  3802. if (dls->backoff == DL_SCHED_DETERMINISTIC) {
  3803. if (dls_schedule_position < smartlist_len(schedule))
  3804. delay = *(int *)smartlist_get(schedule, dls_schedule_position);
  3805. else if (dls_schedule_position == IMPOSSIBLE_TO_DOWNLOAD)
  3806. delay = INT_MAX;
  3807. else
  3808. delay = *(int *)smartlist_get(schedule, smartlist_len(schedule) - 1);
  3809. } else if (dls->backoff == DL_SCHED_RANDOM_EXPONENTIAL) {
  3810. /* Check if we missed a reset somehow */
  3811. IF_BUG_ONCE(dls->last_backoff_position > dls_schedule_position) {
  3812. dls->last_backoff_position = 0;
  3813. dls->last_delay_used = 0;
  3814. }
  3815. if (dls_schedule_position > 0) {
  3816. delay = dls->last_delay_used;
  3817. while (dls->last_backoff_position < dls_schedule_position) {
  3818. /* Do one increment step */
  3819. delay = next_random_exponential_delay(delay, max_delay);
  3820. /* Update our position */
  3821. ++(dls->last_backoff_position);
  3822. }
  3823. } else {
  3824. /* If we're just starting out, use the minimum delay */
  3825. delay = min_delay;
  3826. }
  3827. /* Clamp it within min/max if we have them */
  3828. if (min_delay >= 0 && delay < min_delay) delay = min_delay;
  3829. if (max_delay != INT_MAX && delay > max_delay) delay = max_delay;
  3830. /* Store it for next time */
  3831. dls->last_backoff_position = dls_schedule_position;
  3832. dls->last_delay_used = delay;
  3833. }
  3834. /* A negative delay makes no sense. Knowing that delay is
  3835. * non-negative allows us to safely do the wrapping check below. */
  3836. tor_assert(delay >= 0);
  3837. /* Avoid now+delay overflowing TIME_MAX, by comparing with a subtraction
  3838. * that won't overflow (since delay is non-negative). */
  3839. if (delay < INT_MAX && now <= TIME_MAX - delay) {
  3840. dls->next_attempt_at = now+delay;
  3841. } else {
  3842. dls->next_attempt_at = TIME_MAX;
  3843. }
  3844. return delay;
  3845. }
  3846. /* Log a debug message about item, which increments on increment_action, has
  3847. * incremented dls_n_download_increments times. The message varies based on
  3848. * was_schedule_incremented (if not, not_incremented_response is logged), and
  3849. * the values of increment, dls_next_attempt_at, and now.
  3850. * Helper for download_status_increment_failure and
  3851. * download_status_increment_attempt. */
  3852. static void
  3853. download_status_log_helper(const char *item, int was_schedule_incremented,
  3854. const char *increment_action,
  3855. const char *not_incremented_response,
  3856. uint8_t dls_n_download_increments, int increment,
  3857. time_t dls_next_attempt_at, time_t now)
  3858. {
  3859. if (item) {
  3860. if (!was_schedule_incremented)
  3861. log_debug(LD_DIR, "%s %s %d time(s); I'll try again %s.",
  3862. item, increment_action, (int)dls_n_download_increments,
  3863. not_incremented_response);
  3864. else if (increment == 0)
  3865. log_debug(LD_DIR, "%s %s %d time(s); I'll try again immediately.",
  3866. item, increment_action, (int)dls_n_download_increments);
  3867. else if (dls_next_attempt_at < TIME_MAX)
  3868. log_debug(LD_DIR, "%s %s %d time(s); I'll try again in %d seconds.",
  3869. item, increment_action, (int)dls_n_download_increments,
  3870. (int)(dls_next_attempt_at-now));
  3871. else
  3872. log_debug(LD_DIR, "%s %s %d time(s); Giving up for a while.",
  3873. item, increment_action, (int)dls_n_download_increments);
  3874. }
  3875. }
  3876. /** Determine when a failed download attempt should be retried.
  3877. * Called when an attempt to download <b>dls</b> has failed with HTTP status
  3878. * <b>status_code</b>. Increment the failure count (if the code indicates a
  3879. * real failure, or if we're a server) and set <b>dls</b>-\>next_attempt_at to
  3880. * an appropriate time in the future and return it.
  3881. * If <b>dls->increment_on</b> is DL_SCHED_INCREMENT_ATTEMPT, increment the
  3882. * failure count, and return a time in the far future for the next attempt (to
  3883. * avoid an immediate retry). */
  3884. time_t
  3885. download_status_increment_failure(download_status_t *dls, int status_code,
  3886. const char *item, int server, time_t now)
  3887. {
  3888. (void) status_code; // XXXX no longer used.
  3889. (void) server; // XXXX no longer used.
  3890. int increment = -1;
  3891. int min_delay = 0, max_delay = INT_MAX;
  3892. tor_assert(dls);
  3893. /* count the failure */
  3894. if (dls->n_download_failures < IMPOSSIBLE_TO_DOWNLOAD-1) {
  3895. ++dls->n_download_failures;
  3896. }
  3897. if (dls->increment_on == DL_SCHED_INCREMENT_FAILURE) {
  3898. /* We don't find out that a failure-based schedule has attempted a
  3899. * connection until that connection fails.
  3900. * We'll never find out about successful connections, but this doesn't
  3901. * matter, because schedules are reset after a successful download.
  3902. */
  3903. if (dls->n_download_attempts < IMPOSSIBLE_TO_DOWNLOAD-1)
  3904. ++dls->n_download_attempts;
  3905. /* only return a failure retry time if this schedule increments on failures
  3906. */
  3907. const smartlist_t *schedule = find_dl_schedule(dls, get_options());
  3908. find_dl_min_and_max_delay(dls, get_options(), &min_delay, &max_delay);
  3909. increment = download_status_schedule_get_delay(dls, schedule,
  3910. min_delay, max_delay, now);
  3911. }
  3912. download_status_log_helper(item, !dls->increment_on, "failed",
  3913. "concurrently", dls->n_download_failures,
  3914. increment, dls->next_attempt_at, now);
  3915. if (dls->increment_on == DL_SCHED_INCREMENT_ATTEMPT) {
  3916. /* stop this schedule retrying on failure, it will launch concurrent
  3917. * connections instead */
  3918. return TIME_MAX;
  3919. } else {
  3920. return dls->next_attempt_at;
  3921. }
  3922. }
  3923. /** Determine when the next download attempt should be made when using an
  3924. * attempt-based (potentially concurrent) download schedule.
  3925. * Called when an attempt to download <b>dls</b> is being initiated.
  3926. * Increment the attempt count and set <b>dls</b>-\>next_attempt_at to an
  3927. * appropriate time in the future and return it.
  3928. * If <b>dls->increment_on</b> is DL_SCHED_INCREMENT_FAILURE, don't increment
  3929. * the attempts, and return a time in the far future (to avoid launching a
  3930. * concurrent attempt). */
  3931. time_t
  3932. download_status_increment_attempt(download_status_t *dls, const char *item,
  3933. time_t now)
  3934. {
  3935. int delay = -1;
  3936. int min_delay = 0, max_delay = INT_MAX;
  3937. tor_assert(dls);
  3938. if (dls->increment_on == DL_SCHED_INCREMENT_FAILURE) {
  3939. /* this schedule should retry on failure, and not launch any concurrent
  3940. attempts */
  3941. log_warn(LD_BUG, "Tried to launch an attempt-based connection on a "
  3942. "failure-based schedule.");
  3943. return TIME_MAX;
  3944. }
  3945. if (dls->n_download_attempts < IMPOSSIBLE_TO_DOWNLOAD-1)
  3946. ++dls->n_download_attempts;
  3947. const smartlist_t *schedule = find_dl_schedule(dls, get_options());
  3948. find_dl_min_and_max_delay(dls, get_options(), &min_delay, &max_delay);
  3949. delay = download_status_schedule_get_delay(dls, schedule,
  3950. min_delay, max_delay, now);
  3951. download_status_log_helper(item, dls->increment_on, "attempted",
  3952. "on failure", dls->n_download_attempts,
  3953. delay, dls->next_attempt_at, now);
  3954. return dls->next_attempt_at;
  3955. }
  3956. /** Reset <b>dls</b> so that it will be considered downloadable
  3957. * immediately, and/or to show that we don't need it anymore.
  3958. *
  3959. * Must be called to initialise a download schedule, otherwise the zeroth item
  3960. * in the schedule will never be used.
  3961. *
  3962. * (We find the zeroth element of the download schedule, and set
  3963. * next_attempt_at to be the appropriate offset from 'now'. In most
  3964. * cases this means setting it to 'now', so the item will be immediately
  3965. * downloadable; in the case of bridge descriptors, the zeroth element
  3966. * is an hour from now.) */
  3967. void
  3968. download_status_reset(download_status_t *dls)
  3969. {
  3970. if (dls->n_download_failures == IMPOSSIBLE_TO_DOWNLOAD
  3971. || dls->n_download_attempts == IMPOSSIBLE_TO_DOWNLOAD)
  3972. return; /* Don't reset this. */
  3973. const smartlist_t *schedule = find_dl_schedule(dls, get_options());
  3974. dls->n_download_failures = 0;
  3975. dls->n_download_attempts = 0;
  3976. dls->next_attempt_at = time(NULL) + *(int *)smartlist_get(schedule, 0);
  3977. dls->last_backoff_position = 0;
  3978. dls->last_delay_used = 0;
  3979. /* Don't reset dls->want_authority or dls->increment_on */
  3980. }
  3981. /** Return the number of failures on <b>dls</b> since the last success (if
  3982. * any). */
  3983. int
  3984. download_status_get_n_failures(const download_status_t *dls)
  3985. {
  3986. return dls->n_download_failures;
  3987. }
  3988. /** Return the number of attempts to download <b>dls</b> since the last success
  3989. * (if any). This can differ from download_status_get_n_failures() due to
  3990. * outstanding concurrent attempts. */
  3991. int
  3992. download_status_get_n_attempts(const download_status_t *dls)
  3993. {
  3994. return dls->n_download_attempts;
  3995. }
  3996. /** Return the next time to attempt to download <b>dls</b>. */
  3997. time_t
  3998. download_status_get_next_attempt_at(const download_status_t *dls)
  3999. {
  4000. return dls->next_attempt_at;
  4001. }
  4002. /** Called when one or more routerdesc (or extrainfo, if <b>was_extrainfo</b>)
  4003. * fetches have failed (with uppercase fingerprints listed in <b>failed</b>,
  4004. * either as descriptor digests or as identity digests based on
  4005. * <b>was_descriptor_digests</b>).
  4006. */
  4007. static void
  4008. dir_routerdesc_download_failed(smartlist_t *failed, int status_code,
  4009. int router_purpose,
  4010. int was_extrainfo, int was_descriptor_digests)
  4011. {
  4012. char digest[DIGEST_LEN];
  4013. time_t now = time(NULL);
  4014. int server = directory_fetches_from_authorities(get_options());
  4015. if (!was_descriptor_digests) {
  4016. if (router_purpose == ROUTER_PURPOSE_BRIDGE) {
  4017. tor_assert(!was_extrainfo);
  4018. connection_dir_retry_bridges(failed);
  4019. }
  4020. return; /* FFFF should implement for other-than-router-purpose someday */
  4021. }
  4022. SMARTLIST_FOREACH_BEGIN(failed, const char *, cp) {
  4023. download_status_t *dls = NULL;
  4024. if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) != DIGEST_LEN) {
  4025. log_warn(LD_BUG, "Malformed fingerprint in list: %s", escaped(cp));
  4026. continue;
  4027. }
  4028. if (was_extrainfo) {
  4029. signed_descriptor_t *sd =
  4030. router_get_by_extrainfo_digest(digest);
  4031. if (sd)
  4032. dls = &sd->ei_dl_status;
  4033. } else {
  4034. dls = router_get_dl_status_by_descriptor_digest(digest);
  4035. }
  4036. if (!dls || dls->n_download_failures >=
  4037. get_options()->TestingDescriptorMaxDownloadTries)
  4038. continue;
  4039. download_status_increment_failure(dls, status_code, cp, server, now);
  4040. } SMARTLIST_FOREACH_END(cp);
  4041. /* No need to relaunch descriptor downloads here: we already do it
  4042. * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  4043. }
  4044. /** Called when a connection to download microdescriptors has failed in whole
  4045. * or in part. <b>failed</b> is a list of every microdesc digest we didn't
  4046. * get. <b>status_code</b> is the http status code we received. Reschedule the
  4047. * microdesc downloads as appropriate. */
  4048. static void
  4049. dir_microdesc_download_failed(smartlist_t *failed,
  4050. int status_code)
  4051. {
  4052. networkstatus_t *consensus
  4053. = networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
  4054. routerstatus_t *rs;
  4055. download_status_t *dls;
  4056. time_t now = time(NULL);
  4057. int server = directory_fetches_from_authorities(get_options());
  4058. if (! consensus)
  4059. return;
  4060. SMARTLIST_FOREACH_BEGIN(failed, const char *, d) {
  4061. rs = router_get_mutable_consensus_status_by_descriptor_digest(consensus,d);
  4062. if (!rs)
  4063. continue;
  4064. dls = &rs->dl_status;
  4065. if (dls->n_download_failures >=
  4066. get_options()->TestingMicrodescMaxDownloadTries)
  4067. continue;
  4068. {
  4069. char buf[BASE64_DIGEST256_LEN+1];
  4070. digest256_to_base64(buf, d);
  4071. download_status_increment_failure(dls, status_code, buf,
  4072. server, now);
  4073. }
  4074. } SMARTLIST_FOREACH_END(d);
  4075. }
  4076. /** Helper. Compare two fp_pair_t objects, and return negative, 0, or
  4077. * positive as appropriate. */
  4078. static int
  4079. compare_pairs_(const void **a, const void **b)
  4080. {
  4081. const fp_pair_t *fp1 = *a, *fp2 = *b;
  4082. int r;
  4083. if ((r = fast_memcmp(fp1->first, fp2->first, DIGEST_LEN)))
  4084. return r;
  4085. else
  4086. return fast_memcmp(fp1->second, fp2->second, DIGEST_LEN);
  4087. }
  4088. /** Divide a string <b>res</b> of the form FP1-FP2+FP3-FP4...[.z], where each
  4089. * FP is a hex-encoded fingerprint, into a sequence of distinct sorted
  4090. * fp_pair_t. Skip malformed pairs. On success, return 0 and add those
  4091. * fp_pair_t into <b>pairs_out</b>. On failure, return -1. */
  4092. int
  4093. dir_split_resource_into_fingerprint_pairs(const char *res,
  4094. smartlist_t *pairs_out)
  4095. {
  4096. smartlist_t *pairs_tmp = smartlist_new();
  4097. smartlist_t *pairs_result = smartlist_new();
  4098. smartlist_split_string(pairs_tmp, res, "+", 0, 0);
  4099. if (smartlist_len(pairs_tmp)) {
  4100. char *last = smartlist_get(pairs_tmp,smartlist_len(pairs_tmp)-1);
  4101. size_t last_len = strlen(last);
  4102. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  4103. last[last_len-2] = '\0';
  4104. }
  4105. }
  4106. SMARTLIST_FOREACH_BEGIN(pairs_tmp, char *, cp) {
  4107. if (strlen(cp) != HEX_DIGEST_LEN*2+1) {
  4108. log_info(LD_DIR,
  4109. "Skipping digest pair %s with non-standard length.", escaped(cp));
  4110. } else if (cp[HEX_DIGEST_LEN] != '-') {
  4111. log_info(LD_DIR,
  4112. "Skipping digest pair %s with missing dash.", escaped(cp));
  4113. } else {
  4114. fp_pair_t pair;
  4115. if (base16_decode(pair.first, DIGEST_LEN,
  4116. cp, HEX_DIGEST_LEN) != DIGEST_LEN ||
  4117. base16_decode(pair.second,DIGEST_LEN,
  4118. cp+HEX_DIGEST_LEN+1, HEX_DIGEST_LEN) != DIGEST_LEN) {
  4119. log_info(LD_DIR, "Skipping non-decodable digest pair %s", escaped(cp));
  4120. } else {
  4121. smartlist_add(pairs_result, tor_memdup(&pair, sizeof(pair)));
  4122. }
  4123. }
  4124. tor_free(cp);
  4125. } SMARTLIST_FOREACH_END(cp);
  4126. smartlist_free(pairs_tmp);
  4127. /* Uniq-and-sort */
  4128. smartlist_sort(pairs_result, compare_pairs_);
  4129. smartlist_uniq(pairs_result, compare_pairs_, tor_free_);
  4130. smartlist_add_all(pairs_out, pairs_result);
  4131. smartlist_free(pairs_result);
  4132. return 0;
  4133. }
  4134. /** Given a directory <b>resource</b> request, containing zero
  4135. * or more strings separated by plus signs, followed optionally by ".z", store
  4136. * the strings, in order, into <b>fp_out</b>. If <b>compressed_out</b> is
  4137. * non-NULL, set it to 1 if the resource ends in ".z", else set it to 0.
  4138. *
  4139. * If (flags & DSR_HEX), then delete all elements that aren't hex digests, and
  4140. * decode the rest. If (flags & DSR_BASE64), then use "-" rather than "+" as
  4141. * a separator, delete all the elements that aren't base64-encoded digests,
  4142. * and decode the rest. If (flags & DSR_DIGEST256), these digests should be
  4143. * 256 bits long; else they should be 160.
  4144. *
  4145. * If (flags & DSR_SORT_UNIQ), then sort the list and remove all duplicates.
  4146. */
  4147. int
  4148. dir_split_resource_into_fingerprints(const char *resource,
  4149. smartlist_t *fp_out, int *compressed_out,
  4150. int flags)
  4151. {
  4152. const int decode_hex = flags & DSR_HEX;
  4153. const int decode_base64 = flags & DSR_BASE64;
  4154. const int digests_are_256 = flags & DSR_DIGEST256;
  4155. const int sort_uniq = flags & DSR_SORT_UNIQ;
  4156. const int digest_len = digests_are_256 ? DIGEST256_LEN : DIGEST_LEN;
  4157. const int hex_digest_len = digests_are_256 ?
  4158. HEX_DIGEST256_LEN : HEX_DIGEST_LEN;
  4159. const int base64_digest_len = digests_are_256 ?
  4160. BASE64_DIGEST256_LEN : BASE64_DIGEST_LEN;
  4161. smartlist_t *fp_tmp = smartlist_new();
  4162. tor_assert(!(decode_hex && decode_base64));
  4163. tor_assert(fp_out);
  4164. smartlist_split_string(fp_tmp, resource, decode_base64?"-":"+", 0, 0);
  4165. if (compressed_out)
  4166. *compressed_out = 0;
  4167. if (smartlist_len(fp_tmp)) {
  4168. char *last = smartlist_get(fp_tmp,smartlist_len(fp_tmp)-1);
  4169. size_t last_len = strlen(last);
  4170. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  4171. last[last_len-2] = '\0';
  4172. if (compressed_out)
  4173. *compressed_out = 1;
  4174. }
  4175. }
  4176. if (decode_hex || decode_base64) {
  4177. const size_t encoded_len = decode_hex ? hex_digest_len : base64_digest_len;
  4178. int i;
  4179. char *cp, *d = NULL;
  4180. for (i = 0; i < smartlist_len(fp_tmp); ++i) {
  4181. cp = smartlist_get(fp_tmp, i);
  4182. if (strlen(cp) != encoded_len) {
  4183. log_info(LD_DIR,
  4184. "Skipping digest %s with non-standard length.", escaped(cp));
  4185. smartlist_del_keeporder(fp_tmp, i--);
  4186. goto again;
  4187. }
  4188. d = tor_malloc_zero(digest_len);
  4189. if (decode_hex ?
  4190. (base16_decode(d, digest_len, cp, hex_digest_len) != digest_len) :
  4191. (base64_decode(d, digest_len, cp, base64_digest_len)
  4192. != digest_len)) {
  4193. log_info(LD_DIR, "Skipping non-decodable digest %s", escaped(cp));
  4194. smartlist_del_keeporder(fp_tmp, i--);
  4195. goto again;
  4196. }
  4197. smartlist_set(fp_tmp, i, d);
  4198. d = NULL;
  4199. again:
  4200. tor_free(cp);
  4201. tor_free(d);
  4202. }
  4203. }
  4204. if (sort_uniq) {
  4205. if (decode_hex || decode_base64) {
  4206. if (digests_are_256) {
  4207. smartlist_sort_digests256(fp_tmp);
  4208. smartlist_uniq_digests256(fp_tmp);
  4209. } else {
  4210. smartlist_sort_digests(fp_tmp);
  4211. smartlist_uniq_digests(fp_tmp);
  4212. }
  4213. } else {
  4214. smartlist_sort_strings(fp_tmp);
  4215. smartlist_uniq_strings(fp_tmp);
  4216. }
  4217. }
  4218. smartlist_add_all(fp_out, fp_tmp);
  4219. smartlist_free(fp_tmp);
  4220. return 0;
  4221. }