directory.c 160 KB

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