directory.c 146 KB

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