directory.c 132 KB

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