dirclient.c 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #define DIRCLIENT_PRIVATE
  6. #include "core/or/or.h"
  7. #include "app/config/config.h"
  8. #include "core/mainloop/connection.h"
  9. #include "core/mainloop/mainloop.h"
  10. #include "core/or/connection_edge.h"
  11. #include "core/or/policies.h"
  12. #include "feature/client/bridges.h"
  13. #include "feature/client/entrynodes.h"
  14. #include "feature/control/control.h"
  15. #include "feature/dirauth/dirvote.h"
  16. #include "feature/dirauth/authmode.h"
  17. #include "feature/dirauth/shared_random.h"
  18. #include "feature/dircache/dirserv.h"
  19. #include "feature/dirclient/dirclient.h"
  20. #include "feature/dirclient/dlstatus.h"
  21. #include "feature/dircommon/consdiff.h"
  22. #include "feature/dircommon/directory.h"
  23. #include "feature/dircommon/fp_pair.h"
  24. #include "feature/hs/hs_cache.h"
  25. #include "feature/hs/hs_client.h"
  26. #include "feature/hs/hs_control.h"
  27. #include "feature/nodelist/authcert.h"
  28. #include "feature/nodelist/dirlist.h"
  29. #include "feature/nodelist/microdesc.h"
  30. #include "feature/nodelist/networkstatus.h"
  31. #include "feature/nodelist/node_select.h"
  32. #include "feature/nodelist/nodelist.h"
  33. #include "feature/nodelist/routerlist.h"
  34. #include "feature/nodelist/routerset.h"
  35. #include "feature/relay/routermode.h"
  36. #include "feature/relay/selftest.h"
  37. #include "feature/rend/rendcache.h"
  38. #include "feature/rend/rendclient.h"
  39. #include "feature/rend/rendcommon.h"
  40. #include "feature/rend/rendservice.h"
  41. #include "feature/stats/rephist.h"
  42. #include "lib/compress/compress.h"
  43. #include "lib/crypt_ops/crypto_format.h"
  44. #include "lib/crypt_ops/crypto_util.h"
  45. #include "lib/encoding/confline.h"
  46. #include "lib/err/backtrace.h"
  47. #include "core/or/entry_connection_st.h"
  48. #include "feature/dircache/cached_dir_st.h"
  49. #include "feature/dirclient/dir_server_st.h"
  50. #include "feature/dircommon/dir_connection_st.h"
  51. #include "feature/nodelist/networkstatus_st.h"
  52. #include "feature/nodelist/node_st.h"
  53. #include "feature/nodelist/routerinfo_st.h"
  54. #include "feature/rend/rend_service_descriptor_st.h"
  55. /** Maximum size, in bytes, for any directory object that we've downloaded. */
  56. #define MAX_DIR_DL_SIZE ((1<<24)-1) /* 16 MB - 1 */
  57. /** How far in the future do we allow a directory server to tell us it is
  58. * before deciding that one of us has the wrong time? */
  59. #define ALLOW_DIRECTORY_TIME_SKEW (30*60)
  60. static int body_is_plausible(const char *body, size_t body_len, int purpose);
  61. static void connection_dir_download_routerdesc_failed(dir_connection_t *conn);
  62. static void connection_dir_bridge_routerdesc_failed(dir_connection_t *conn);
  63. static void connection_dir_download_cert_failed(
  64. dir_connection_t *conn, int status_code);
  65. static void connection_dir_retry_bridges(smartlist_t *descs);
  66. static void dir_routerdesc_download_failed(smartlist_t *failed,
  67. int status_code,
  68. int router_purpose,
  69. int was_extrainfo,
  70. int was_descriptor_digests);
  71. static void dir_microdesc_download_failed(smartlist_t *failed,
  72. int status_code,
  73. const char *dir_id);
  74. static void directory_send_command(dir_connection_t *conn,
  75. const int direct,
  76. const directory_request_t *req);
  77. static void connection_dir_close_consensus_fetches(
  78. dir_connection_t *except_this_one, const char *resource);
  79. /** Return a string describing a given directory connection purpose. */
  80. STATIC const char *
  81. dir_conn_purpose_to_string(int purpose)
  82. {
  83. switch (purpose)
  84. {
  85. case DIR_PURPOSE_UPLOAD_DIR:
  86. return "server descriptor upload";
  87. case DIR_PURPOSE_UPLOAD_VOTE:
  88. return "server vote upload";
  89. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  90. return "consensus signature upload";
  91. case DIR_PURPOSE_FETCH_SERVERDESC:
  92. return "server descriptor fetch";
  93. case DIR_PURPOSE_FETCH_EXTRAINFO:
  94. return "extra-info fetch";
  95. case DIR_PURPOSE_FETCH_CONSENSUS:
  96. return "consensus network-status fetch";
  97. case DIR_PURPOSE_FETCH_CERTIFICATE:
  98. return "authority cert fetch";
  99. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  100. return "status vote fetch";
  101. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  102. return "consensus signature fetch";
  103. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  104. return "hidden-service v2 descriptor fetch";
  105. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  106. return "hidden-service v2 descriptor upload";
  107. case DIR_PURPOSE_FETCH_HSDESC:
  108. return "hidden-service descriptor fetch";
  109. case DIR_PURPOSE_UPLOAD_HSDESC:
  110. return "hidden-service descriptor upload";
  111. case DIR_PURPOSE_FETCH_MICRODESC:
  112. return "microdescriptor fetch";
  113. }
  114. log_warn(LD_BUG, "Called with unknown purpose %d", purpose);
  115. return "(unknown)";
  116. }
  117. /** Return the requisite directory information types. */
  118. STATIC dirinfo_type_t
  119. dir_fetch_type(int dir_purpose, int router_purpose, const char *resource)
  120. {
  121. dirinfo_type_t type;
  122. switch (dir_purpose) {
  123. case DIR_PURPOSE_FETCH_EXTRAINFO:
  124. type = EXTRAINFO_DIRINFO;
  125. if (router_purpose == ROUTER_PURPOSE_BRIDGE)
  126. type |= BRIDGE_DIRINFO;
  127. else
  128. type |= V3_DIRINFO;
  129. break;
  130. case DIR_PURPOSE_FETCH_SERVERDESC:
  131. if (router_purpose == ROUTER_PURPOSE_BRIDGE)
  132. type = BRIDGE_DIRINFO;
  133. else
  134. type = V3_DIRINFO;
  135. break;
  136. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  137. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  138. case DIR_PURPOSE_FETCH_CERTIFICATE:
  139. type = V3_DIRINFO;
  140. break;
  141. case DIR_PURPOSE_FETCH_CONSENSUS:
  142. type = V3_DIRINFO;
  143. if (resource && !strcmp(resource, "microdesc"))
  144. type |= MICRODESC_DIRINFO;
  145. break;
  146. case DIR_PURPOSE_FETCH_MICRODESC:
  147. type = MICRODESC_DIRINFO;
  148. break;
  149. default:
  150. log_warn(LD_BUG, "Unexpected purpose %d", (int)dir_purpose);
  151. type = NO_DIRINFO;
  152. break;
  153. }
  154. return type;
  155. }
  156. /** Return true iff <b>identity_digest</b> is the digest of a router which
  157. * says that it caches extrainfos. (If <b>is_authority</b> we always
  158. * believe that to be true.) */
  159. int
  160. router_supports_extrainfo(const char *identity_digest, int is_authority)
  161. {
  162. const node_t *node = node_get_by_id(identity_digest);
  163. if (node && node->ri) {
  164. if (node->ri->caches_extra_info)
  165. return 1;
  166. }
  167. if (is_authority) {
  168. return 1;
  169. }
  170. return 0;
  171. }
  172. /** Return true iff any trusted directory authority has accepted our
  173. * server descriptor.
  174. *
  175. * We consider any authority sufficient because waiting for all of
  176. * them means it never happens while any authority is down; we don't
  177. * go for something more complex in the middle (like \>1/3 or \>1/2 or
  178. * \>=1/2) because that doesn't seem necessary yet.
  179. */
  180. int
  181. directories_have_accepted_server_descriptor(void)
  182. {
  183. const smartlist_t *servers = router_get_trusted_dir_servers();
  184. const or_options_t *options = get_options();
  185. SMARTLIST_FOREACH(servers, dir_server_t *, d, {
  186. if ((d->type & options->PublishServerDescriptor_) &&
  187. d->has_accepted_serverdesc) {
  188. return 1;
  189. }
  190. });
  191. return 0;
  192. }
  193. /** Start a connection to every suitable directory authority, using
  194. * connection purpose <b>dir_purpose</b> and uploading <b>payload</b>
  195. * (of length <b>payload_len</b>). The dir_purpose should be one of
  196. * 'DIR_PURPOSE_UPLOAD_{DIR|VOTE|SIGNATURES}'.
  197. *
  198. * <b>router_purpose</b> describes the type of descriptor we're
  199. * publishing, if we're publishing a descriptor -- e.g. general or bridge.
  200. *
  201. * <b>type</b> specifies what sort of dir authorities (V3,
  202. * BRIDGE, etc) we should upload to.
  203. *
  204. * If <b>extrainfo_len</b> is nonzero, the first <b>payload_len</b> bytes of
  205. * <b>payload</b> hold a router descriptor, and the next <b>extrainfo_len</b>
  206. * bytes of <b>payload</b> hold an extra-info document. Upload the descriptor
  207. * to all authorities, and the extra-info document to all authorities that
  208. * support it.
  209. */
  210. void
  211. directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose,
  212. dirinfo_type_t type,
  213. const char *payload,
  214. size_t payload_len, size_t extrainfo_len)
  215. {
  216. const or_options_t *options = get_options();
  217. dir_indirection_t indirection;
  218. const smartlist_t *dirservers = router_get_trusted_dir_servers();
  219. int found = 0;
  220. const int exclude_self = (dir_purpose == DIR_PURPOSE_UPLOAD_VOTE ||
  221. dir_purpose == DIR_PURPOSE_UPLOAD_SIGNATURES);
  222. tor_assert(dirservers);
  223. /* This tries dirservers which we believe to be down, but ultimately, that's
  224. * harmless, and we may as well err on the side of getting things uploaded.
  225. */
  226. SMARTLIST_FOREACH_BEGIN(dirservers, dir_server_t *, ds) {
  227. routerstatus_t *rs = &(ds->fake_status);
  228. size_t upload_len = payload_len;
  229. if ((type & ds->type) == 0)
  230. continue;
  231. if (exclude_self && router_digest_is_me(ds->digest)) {
  232. /* we don't upload to ourselves, but at least there's now at least
  233. * one authority of this type that has what we wanted to upload. */
  234. found = 1;
  235. continue;
  236. }
  237. if (options->StrictNodes &&
  238. routerset_contains_routerstatus(options->ExcludeNodes, rs, -1)) {
  239. log_warn(LD_DIR, "Wanted to contact authority '%s' for %s, but "
  240. "it's in our ExcludedNodes list and StrictNodes is set. "
  241. "Skipping.",
  242. ds->nickname,
  243. dir_conn_purpose_to_string(dir_purpose));
  244. continue;
  245. }
  246. found = 1; /* at least one authority of this type was listed */
  247. if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR)
  248. ds->has_accepted_serverdesc = 0;
  249. if (extrainfo_len && router_supports_extrainfo(ds->digest, 1)) {
  250. upload_len += extrainfo_len;
  251. log_info(LD_DIR, "Uploading an extrainfo too (length %d)",
  252. (int) extrainfo_len);
  253. }
  254. if (purpose_needs_anonymity(dir_purpose, router_purpose, NULL)) {
  255. indirection = DIRIND_ANONYMOUS;
  256. } else if (!fascist_firewall_allows_dir_server(ds,
  257. FIREWALL_DIR_CONNECTION,
  258. 0)) {
  259. if (fascist_firewall_allows_dir_server(ds, FIREWALL_OR_CONNECTION, 0))
  260. indirection = DIRIND_ONEHOP;
  261. else
  262. indirection = DIRIND_ANONYMOUS;
  263. } else {
  264. indirection = DIRIND_DIRECT_CONN;
  265. }
  266. directory_request_t *req = directory_request_new(dir_purpose);
  267. directory_request_set_routerstatus(req, rs);
  268. directory_request_set_router_purpose(req, router_purpose);
  269. directory_request_set_indirection(req, indirection);
  270. directory_request_set_payload(req, payload, upload_len);
  271. directory_initiate_request(req);
  272. directory_request_free(req);
  273. } SMARTLIST_FOREACH_END(ds);
  274. if (!found) {
  275. char *s = authdir_type_to_string(type);
  276. log_warn(LD_DIR, "Publishing server descriptor to directory authorities "
  277. "of type '%s', but no authorities of that type listed!", s);
  278. tor_free(s);
  279. }
  280. }
  281. /** Return true iff, according to the values in <b>options</b>, we should be
  282. * using directory guards for direct downloads of directory information. */
  283. STATIC int
  284. should_use_directory_guards(const or_options_t *options)
  285. {
  286. /* Public (non-bridge) servers never use directory guards. */
  287. if (public_server_mode(options))
  288. return 0;
  289. /* If guards are disabled, we can't use directory guards.
  290. */
  291. if (!options->UseEntryGuards)
  292. return 0;
  293. /* If we're configured to fetch directory info aggressively or of a
  294. * nonstandard type, don't use directory guards. */
  295. if (options->DownloadExtraInfo || options->FetchDirInfoEarly ||
  296. options->FetchDirInfoExtraEarly || options->FetchUselessDescriptors)
  297. return 0;
  298. return 1;
  299. }
  300. /** Pick an unconstrained directory server from among our guards, the latest
  301. * networkstatus, or the fallback dirservers, for use in downloading
  302. * information of type <b>type</b>, and return its routerstatus. */
  303. static const routerstatus_t *
  304. directory_pick_generic_dirserver(dirinfo_type_t type, int pds_flags,
  305. uint8_t dir_purpose,
  306. circuit_guard_state_t **guard_state_out)
  307. {
  308. const routerstatus_t *rs = NULL;
  309. const or_options_t *options = get_options();
  310. if (options->UseBridges)
  311. log_warn(LD_BUG, "Called when we have UseBridges set.");
  312. if (should_use_directory_guards(options)) {
  313. const node_t *node = guards_choose_dirguard(dir_purpose, guard_state_out);
  314. if (node)
  315. rs = node->rs;
  316. } else {
  317. /* anybody with a non-zero dirport will do */
  318. rs = router_pick_directory_server(type, pds_flags);
  319. }
  320. if (!rs) {
  321. log_info(LD_DIR, "No router found for %s; falling back to "
  322. "dirserver list.", dir_conn_purpose_to_string(dir_purpose));
  323. rs = router_pick_fallback_dirserver(type, pds_flags);
  324. }
  325. return rs;
  326. }
  327. /**
  328. * Set the extra fields in <b>req</b> that are used when requesting a
  329. * consensus of type <b>resource</b>.
  330. *
  331. * Right now, these fields are if-modified-since and x-or-diff-from-consensus.
  332. */
  333. static void
  334. dir_consensus_request_set_additional_headers(directory_request_t *req,
  335. const char *resource)
  336. {
  337. time_t if_modified_since = 0;
  338. uint8_t or_diff_from[DIGEST256_LEN];
  339. int or_diff_from_is_set = 0;
  340. /* DEFAULT_IF_MODIFIED_SINCE_DELAY is 1/20 of the default consensus
  341. * period of 1 hour.
  342. */
  343. const int DEFAULT_IF_MODIFIED_SINCE_DELAY = 180;
  344. const int32_t DEFAULT_TRY_DIFF_FOR_CONSENSUS_NEWER = 72;
  345. const int32_t MIN_TRY_DIFF_FOR_CONSENSUS_NEWER = 0;
  346. const int32_t MAX_TRY_DIFF_FOR_CONSENSUS_NEWER = 8192;
  347. const char TRY_DIFF_FOR_CONSENSUS_NEWER_NAME[] =
  348. "try-diff-for-consensus-newer-than";
  349. int flav = FLAV_NS;
  350. if (resource)
  351. flav = networkstatus_parse_flavor_name(resource);
  352. int32_t max_age_for_diff = 3600 *
  353. networkstatus_get_param(NULL,
  354. TRY_DIFF_FOR_CONSENSUS_NEWER_NAME,
  355. DEFAULT_TRY_DIFF_FOR_CONSENSUS_NEWER,
  356. MIN_TRY_DIFF_FOR_CONSENSUS_NEWER,
  357. MAX_TRY_DIFF_FOR_CONSENSUS_NEWER);
  358. if (flav != -1) {
  359. /* IF we have a parsed consensus of this type, we can do an
  360. * if-modified-time based on it. */
  361. networkstatus_t *v;
  362. v = networkstatus_get_latest_consensus_by_flavor(flav);
  363. if (v) {
  364. /* In networks with particularly short V3AuthVotingIntervals,
  365. * ask for the consensus if it's been modified since half the
  366. * V3AuthVotingInterval of the most recent consensus. */
  367. time_t ims_delay = DEFAULT_IF_MODIFIED_SINCE_DELAY;
  368. if (v->fresh_until > v->valid_after
  369. && ims_delay > (v->fresh_until - v->valid_after)/2) {
  370. ims_delay = (v->fresh_until - v->valid_after)/2;
  371. }
  372. if_modified_since = v->valid_after + ims_delay;
  373. if (v->valid_after >= approx_time() - max_age_for_diff) {
  374. memcpy(or_diff_from, v->digest_sha3_as_signed, DIGEST256_LEN);
  375. or_diff_from_is_set = 1;
  376. }
  377. }
  378. } else {
  379. /* Otherwise it might be a consensus we don't parse, but which we
  380. * do cache. Look at the cached copy, perhaps. */
  381. cached_dir_t *cd = dirserv_get_consensus(resource);
  382. /* We have no method of determining the voting interval from an
  383. * unparsed consensus, so we use the default. */
  384. if (cd) {
  385. if_modified_since = cd->published + DEFAULT_IF_MODIFIED_SINCE_DELAY;
  386. if (cd->published >= approx_time() - max_age_for_diff) {
  387. memcpy(or_diff_from, cd->digest_sha3_as_signed, DIGEST256_LEN);
  388. or_diff_from_is_set = 1;
  389. }
  390. }
  391. }
  392. if (if_modified_since > 0)
  393. directory_request_set_if_modified_since(req, if_modified_since);
  394. if (or_diff_from_is_set) {
  395. char hex[HEX_DIGEST256_LEN + 1];
  396. base16_encode(hex, sizeof(hex),
  397. (const char*)or_diff_from, sizeof(or_diff_from));
  398. directory_request_add_header(req, X_OR_DIFF_FROM_CONSENSUS_HEADER, hex);
  399. }
  400. }
  401. /** Start a connection to a random running directory server, using
  402. * connection purpose <b>dir_purpose</b>, intending to fetch descriptors
  403. * of purpose <b>router_purpose</b>, and requesting <b>resource</b>.
  404. * Use <b>pds_flags</b> as arguments to router_pick_directory_server()
  405. * or router_pick_trusteddirserver().
  406. */
  407. MOCK_IMPL(void,
  408. directory_get_from_dirserver,(
  409. uint8_t dir_purpose,
  410. uint8_t router_purpose,
  411. const char *resource,
  412. int pds_flags,
  413. download_want_authority_t want_authority))
  414. {
  415. const routerstatus_t *rs = NULL;
  416. const or_options_t *options = get_options();
  417. int prefer_authority = (directory_fetches_from_authorities(options)
  418. || want_authority == DL_WANT_AUTHORITY);
  419. int require_authority = 0;
  420. int get_via_tor = purpose_needs_anonymity(dir_purpose, router_purpose,
  421. resource);
  422. dirinfo_type_t type = dir_fetch_type(dir_purpose, router_purpose, resource);
  423. if (type == NO_DIRINFO)
  424. return;
  425. if (!options->FetchServerDescriptors)
  426. return;
  427. circuit_guard_state_t *guard_state = NULL;
  428. if (!get_via_tor) {
  429. if (options->UseBridges && !(type & BRIDGE_DIRINFO)) {
  430. /* We want to ask a running bridge for which we have a descriptor.
  431. *
  432. * When we ask choose_random_entry() for a bridge, we specify what
  433. * sort of dir fetch we'll be doing, so it won't return a bridge
  434. * that can't answer our question.
  435. */
  436. const node_t *node = guards_choose_dirguard(dir_purpose, &guard_state);
  437. if (node && node->ri) {
  438. /* every bridge has a routerinfo. */
  439. routerinfo_t *ri = node->ri;
  440. /* clients always make OR connections to bridges */
  441. tor_addr_port_t or_ap;
  442. directory_request_t *req = directory_request_new(dir_purpose);
  443. /* we are willing to use a non-preferred address if we need to */
  444. fascist_firewall_choose_address_node(node, FIREWALL_OR_CONNECTION, 0,
  445. &or_ap);
  446. directory_request_set_or_addr_port(req, &or_ap);
  447. directory_request_set_directory_id_digest(req,
  448. ri->cache_info.identity_digest);
  449. directory_request_set_router_purpose(req, router_purpose);
  450. directory_request_set_resource(req, resource);
  451. if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS)
  452. dir_consensus_request_set_additional_headers(req, resource);
  453. directory_request_set_guard_state(req, guard_state);
  454. directory_initiate_request(req);
  455. directory_request_free(req);
  456. } else {
  457. if (guard_state) {
  458. entry_guard_cancel(&guard_state);
  459. }
  460. log_notice(LD_DIR, "Ignoring directory request, since no bridge "
  461. "nodes are available yet.");
  462. }
  463. return;
  464. } else {
  465. if (prefer_authority || (type & BRIDGE_DIRINFO)) {
  466. /* only ask authdirservers, and don't ask myself */
  467. rs = router_pick_trusteddirserver(type, pds_flags);
  468. if (rs == NULL && (pds_flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  469. PDS_NO_EXISTING_MICRODESC_FETCH))) {
  470. /* We don't want to fetch from any authorities that we're currently
  471. * fetching server descriptors from, and we got no match. Did we
  472. * get no match because all the authorities have connections
  473. * fetching server descriptors (in which case we should just
  474. * return,) or because all the authorities are down or on fire or
  475. * unreachable or something (in which case we should go on with
  476. * our fallback code)? */
  477. pds_flags &= ~(PDS_NO_EXISTING_SERVERDESC_FETCH|
  478. PDS_NO_EXISTING_MICRODESC_FETCH);
  479. rs = router_pick_trusteddirserver(type, pds_flags);
  480. if (rs) {
  481. log_debug(LD_DIR, "Deferring serverdesc fetch: all authorities "
  482. "are in use.");
  483. return;
  484. }
  485. }
  486. if (rs == NULL && require_authority) {
  487. log_info(LD_DIR, "No authorities were available for %s: will try "
  488. "later.", dir_conn_purpose_to_string(dir_purpose));
  489. return;
  490. }
  491. }
  492. if (!rs && !(type & BRIDGE_DIRINFO)) {
  493. rs = directory_pick_generic_dirserver(type, pds_flags,
  494. dir_purpose,
  495. &guard_state);
  496. if (!rs)
  497. get_via_tor = 1; /* last resort: try routing it via Tor */
  498. }
  499. }
  500. }
  501. if (get_via_tor) {
  502. /* Never use fascistfirewall; we're going via Tor. */
  503. pds_flags |= PDS_IGNORE_FASCISTFIREWALL;
  504. rs = router_pick_directory_server(type, pds_flags);
  505. }
  506. /* If we have any hope of building an indirect conn, we know some router
  507. * descriptors. If (rs==NULL), we can't build circuits anyway, so
  508. * there's no point in falling back to the authorities in this case. */
  509. if (rs) {
  510. const dir_indirection_t indirection =
  511. get_via_tor ? DIRIND_ANONYMOUS : DIRIND_ONEHOP;
  512. directory_request_t *req = directory_request_new(dir_purpose);
  513. directory_request_set_routerstatus(req, rs);
  514. directory_request_set_router_purpose(req, router_purpose);
  515. directory_request_set_indirection(req, indirection);
  516. directory_request_set_resource(req, resource);
  517. if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS)
  518. dir_consensus_request_set_additional_headers(req, resource);
  519. if (guard_state)
  520. directory_request_set_guard_state(req, guard_state);
  521. directory_initiate_request(req);
  522. directory_request_free(req);
  523. } else {
  524. log_notice(LD_DIR,
  525. "While fetching directory info, "
  526. "no running dirservers known. Will try again later. "
  527. "(purpose %d)", dir_purpose);
  528. if (!purpose_needs_anonymity(dir_purpose, router_purpose, resource)) {
  529. /* remember we tried them all and failed. */
  530. directory_all_unreachable(time(NULL));
  531. }
  532. }
  533. }
  534. /** As directory_get_from_dirserver, but initiates a request to <i>every</i>
  535. * directory authority other than ourself. Only for use by authorities when
  536. * searching for missing information while voting. */
  537. void
  538. directory_get_from_all_authorities(uint8_t dir_purpose,
  539. uint8_t router_purpose,
  540. const char *resource)
  541. {
  542. tor_assert(dir_purpose == DIR_PURPOSE_FETCH_STATUS_VOTE ||
  543. dir_purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES);
  544. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  545. dir_server_t *, ds) {
  546. if (router_digest_is_me(ds->digest))
  547. continue;
  548. if (!(ds->type & V3_DIRINFO))
  549. continue;
  550. const routerstatus_t *rs = &ds->fake_status;
  551. directory_request_t *req = directory_request_new(dir_purpose);
  552. directory_request_set_routerstatus(req, rs);
  553. directory_request_set_router_purpose(req, router_purpose);
  554. directory_request_set_resource(req, resource);
  555. directory_initiate_request(req);
  556. directory_request_free(req);
  557. } SMARTLIST_FOREACH_END(ds);
  558. }
  559. /** Return true iff <b>ind</b> requires a multihop circuit. */
  560. static int
  561. dirind_is_anon(dir_indirection_t ind)
  562. {
  563. return ind == DIRIND_ANON_DIRPORT || ind == DIRIND_ANONYMOUS;
  564. }
  565. /* Choose reachable OR and Dir addresses and ports from status, copying them
  566. * into use_or_ap and use_dir_ap. If indirection is anonymous, then we're
  567. * connecting via another relay, so choose the primary IPv4 address and ports.
  568. *
  569. * status should have at least one reachable address, if we can't choose a
  570. * reachable address, warn and return -1. Otherwise, return 0.
  571. */
  572. static int
  573. directory_choose_address_routerstatus(const routerstatus_t *status,
  574. dir_indirection_t indirection,
  575. tor_addr_port_t *use_or_ap,
  576. tor_addr_port_t *use_dir_ap)
  577. {
  578. tor_assert(status != NULL);
  579. tor_assert(use_or_ap != NULL);
  580. tor_assert(use_dir_ap != NULL);
  581. const or_options_t *options = get_options();
  582. int have_or = 0, have_dir = 0;
  583. /* We expect status to have at least one reachable address if we're
  584. * connecting to it directly.
  585. *
  586. * Therefore, we can simply use the other address if the one we want isn't
  587. * allowed by the firewall.
  588. *
  589. * (When Tor uploads and downloads a hidden service descriptor, it uses
  590. * DIRIND_ANONYMOUS. Even Single Onion Servers (NYI) use DIRIND_ANONYMOUS,
  591. * to avoid HSDirs denying service by rejecting descriptors.)
  592. */
  593. /* Initialise the OR / Dir addresses */
  594. tor_addr_make_null(&use_or_ap->addr, AF_UNSPEC);
  595. use_or_ap->port = 0;
  596. tor_addr_make_null(&use_dir_ap->addr, AF_UNSPEC);
  597. use_dir_ap->port = 0;
  598. /* ORPort connections */
  599. if (indirection == DIRIND_ANONYMOUS) {
  600. if (status->addr) {
  601. /* Since we're going to build a 3-hop circuit and ask the 2nd relay
  602. * to extend to this address, always use the primary (IPv4) OR address */
  603. tor_addr_from_ipv4h(&use_or_ap->addr, status->addr);
  604. use_or_ap->port = status->or_port;
  605. have_or = 1;
  606. }
  607. } else if (indirection == DIRIND_ONEHOP) {
  608. /* We use an IPv6 address if we have one and we prefer it.
  609. * Use the preferred address and port if they are reachable, otherwise,
  610. * use the alternate address and port (if any).
  611. */
  612. fascist_firewall_choose_address_rs(status, FIREWALL_OR_CONNECTION, 0,
  613. use_or_ap);
  614. have_or = tor_addr_port_is_valid_ap(use_or_ap, 0);
  615. }
  616. /* DirPort connections
  617. * DIRIND_ONEHOP uses ORPort, but may fall back to the DirPort on relays */
  618. if (indirection == DIRIND_DIRECT_CONN ||
  619. indirection == DIRIND_ANON_DIRPORT ||
  620. (indirection == DIRIND_ONEHOP
  621. && !directory_must_use_begindir(options))) {
  622. fascist_firewall_choose_address_rs(status, FIREWALL_DIR_CONNECTION, 0,
  623. use_dir_ap);
  624. have_dir = tor_addr_port_is_valid_ap(use_dir_ap, 0);
  625. }
  626. /* We rejected all addresses in the relay's status. This means we can't
  627. * connect to it. */
  628. if (!have_or && !have_dir) {
  629. static int logged_backtrace = 0;
  630. log_info(LD_BUG, "Rejected all OR and Dir addresses from %s when "
  631. "launching an outgoing directory connection to: IPv4 %s OR %d "
  632. "Dir %d IPv6 %s OR %d Dir %d", routerstatus_describe(status),
  633. fmt_addr32(status->addr), status->or_port,
  634. status->dir_port, fmt_addr(&status->ipv6_addr),
  635. status->ipv6_orport, status->dir_port);
  636. if (!logged_backtrace) {
  637. log_backtrace(LOG_INFO, LD_BUG, "Addresses came from");
  638. logged_backtrace = 1;
  639. }
  640. return -1;
  641. }
  642. return 0;
  643. }
  644. /** Return true iff <b>conn</b> is the client side of a directory connection
  645. * we launched to ourself in order to determine the reachability of our
  646. * dir_port. */
  647. static int
  648. directory_conn_is_self_reachability_test(dir_connection_t *conn)
  649. {
  650. if (conn->requested_resource &&
  651. !strcmpstart(conn->requested_resource,"authority")) {
  652. const routerinfo_t *me = router_get_my_routerinfo();
  653. if (me &&
  654. router_digest_is_me(conn->identity_digest) &&
  655. tor_addr_eq_ipv4h(&conn->base_.addr, me->addr) && /*XXXX prop 118*/
  656. me->dir_port == conn->base_.port)
  657. return 1;
  658. }
  659. return 0;
  660. }
  661. /** Called when we are unable to complete the client's request to a directory
  662. * server due to a network error: Mark the router as down and try again if
  663. * possible.
  664. */
  665. void
  666. connection_dir_client_request_failed(dir_connection_t *conn)
  667. {
  668. if (conn->guard_state) {
  669. /* We haven't seen a success on this guard state, so consider it to have
  670. * failed. */
  671. entry_guard_failed(&conn->guard_state);
  672. }
  673. if (directory_conn_is_self_reachability_test(conn)) {
  674. return; /* this was a test fetch. don't retry. */
  675. }
  676. if (!entry_list_is_constrained(get_options()))
  677. router_set_status(conn->identity_digest, 0); /* don't try this one again */
  678. if (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  679. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
  680. log_info(LD_DIR, "Giving up on serverdesc/extrainfo fetch from "
  681. "directory server at '%s'; retrying",
  682. conn->base_.address);
  683. if (conn->router_purpose == ROUTER_PURPOSE_BRIDGE)
  684. connection_dir_bridge_routerdesc_failed(conn);
  685. connection_dir_download_routerdesc_failed(conn);
  686. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  687. if (conn->requested_resource)
  688. networkstatus_consensus_download_failed(0, conn->requested_resource);
  689. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
  690. log_info(LD_DIR, "Giving up on certificate fetch from directory server "
  691. "at '%s'; retrying",
  692. conn->base_.address);
  693. connection_dir_download_cert_failed(conn, 0);
  694. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
  695. log_info(LD_DIR, "Giving up downloading detached signatures from '%s'",
  696. conn->base_.address);
  697. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
  698. log_info(LD_DIR, "Giving up downloading votes from '%s'",
  699. conn->base_.address);
  700. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  701. log_info(LD_DIR, "Giving up on downloading microdescriptors from "
  702. "directory server at '%s'; will retry", conn->base_.address);
  703. connection_dir_download_routerdesc_failed(conn);
  704. }
  705. }
  706. /** Helper: Attempt to fetch directly the descriptors of each bridge
  707. * listed in <b>failed</b>.
  708. */
  709. static void
  710. connection_dir_retry_bridges(smartlist_t *descs)
  711. {
  712. char digest[DIGEST_LEN];
  713. SMARTLIST_FOREACH(descs, const char *, cp,
  714. {
  715. if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) != DIGEST_LEN) {
  716. log_warn(LD_BUG, "Malformed fingerprint in list: %s",
  717. escaped(cp));
  718. continue;
  719. }
  720. retry_bridge_descriptor_fetch_directly(digest);
  721. });
  722. }
  723. /** Called when an attempt to download one or more router descriptors
  724. * or extra-info documents on connection <b>conn</b> failed.
  725. */
  726. static void
  727. connection_dir_download_routerdesc_failed(dir_connection_t *conn)
  728. {
  729. /* No need to increment the failure count for routerdescs, since
  730. * it's not their fault. */
  731. /* No need to relaunch descriptor downloads here: we already do it
  732. * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  733. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  734. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  735. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  736. (void) conn;
  737. }
  738. /** Called when an attempt to download a bridge's routerdesc from
  739. * one of the authorities failed due to a network error. If
  740. * possible attempt to download descriptors from the bridge directly.
  741. */
  742. static void
  743. connection_dir_bridge_routerdesc_failed(dir_connection_t *conn)
  744. {
  745. smartlist_t *which = NULL;
  746. /* Requests for bridge descriptors are in the form 'fp/', so ignore
  747. anything else. */
  748. if (!conn->requested_resource || strcmpstart(conn->requested_resource,"fp/"))
  749. return;
  750. which = smartlist_new();
  751. dir_split_resource_into_fingerprints(conn->requested_resource
  752. + strlen("fp/"),
  753. which, NULL, 0);
  754. tor_assert(conn->base_.purpose != DIR_PURPOSE_FETCH_EXTRAINFO);
  755. if (smartlist_len(which)) {
  756. connection_dir_retry_bridges(which);
  757. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  758. }
  759. smartlist_free(which);
  760. }
  761. /** Called when an attempt to fetch a certificate fails. */
  762. static void
  763. connection_dir_download_cert_failed(dir_connection_t *conn, int status)
  764. {
  765. const char *fp_pfx = "fp/";
  766. const char *fpsk_pfx = "fp-sk/";
  767. smartlist_t *failed;
  768. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE);
  769. if (!conn->requested_resource)
  770. return;
  771. failed = smartlist_new();
  772. /*
  773. * We have two cases download by fingerprint (resource starts
  774. * with "fp/") or download by fingerprint/signing key pair
  775. * (resource starts with "fp-sk/").
  776. */
  777. if (!strcmpstart(conn->requested_resource, fp_pfx)) {
  778. /* Download by fingerprint case */
  779. dir_split_resource_into_fingerprints(conn->requested_resource +
  780. strlen(fp_pfx),
  781. failed, NULL, DSR_HEX);
  782. SMARTLIST_FOREACH_BEGIN(failed, char *, cp) {
  783. /* Null signing key digest indicates download by fp only */
  784. authority_cert_dl_failed(cp, NULL, status);
  785. tor_free(cp);
  786. } SMARTLIST_FOREACH_END(cp);
  787. } else if (!strcmpstart(conn->requested_resource, fpsk_pfx)) {
  788. /* Download by (fp,sk) pairs */
  789. dir_split_resource_into_fingerprint_pairs(conn->requested_resource +
  790. strlen(fpsk_pfx), failed);
  791. SMARTLIST_FOREACH_BEGIN(failed, fp_pair_t *, cp) {
  792. authority_cert_dl_failed(cp->first, cp->second, status);
  793. tor_free(cp);
  794. } SMARTLIST_FOREACH_END(cp);
  795. } else {
  796. log_warn(LD_DIR,
  797. "Don't know what to do with failure for cert fetch %s",
  798. conn->requested_resource);
  799. }
  800. smartlist_free(failed);
  801. update_certificate_downloads(time(NULL));
  802. }
  803. /* Should this tor instance only use begindir for all its directory requests?
  804. */
  805. int
  806. directory_must_use_begindir(const or_options_t *options)
  807. {
  808. /* Clients, onion services, and bridges must use begindir,
  809. * relays and authorities do not have to */
  810. return !public_server_mode(options);
  811. }
  812. /** Evaluate the situation and decide if we should use an encrypted
  813. * "begindir-style" connection for this directory request.
  814. * 0) If there is no DirPort, yes.
  815. * 1) If or_port is 0, or it's a direct conn and or_port is firewalled
  816. * or we're a dir mirror, no.
  817. * 2) If we prefer to avoid begindir conns, and we're not fetching or
  818. * publishing a bridge relay descriptor, no.
  819. * 3) Else yes.
  820. * If returning 0, return in *reason why we can't use begindir.
  821. * reason must not be NULL.
  822. */
  823. static int
  824. directory_command_should_use_begindir(const or_options_t *options,
  825. const directory_request_t *req,
  826. const char **reason)
  827. {
  828. const tor_addr_t *or_addr = &req->or_addr_port.addr;
  829. //const tor_addr_t *dir_addr = &req->dir_addr_port.addr;
  830. const int or_port = req->or_addr_port.port;
  831. const int dir_port = req->dir_addr_port.port;
  832. const dir_indirection_t indirection = req->indirection;
  833. tor_assert(reason);
  834. *reason = NULL;
  835. /* Reasons why we must use begindir */
  836. if (!dir_port) {
  837. *reason = "(using begindir - directory with no DirPort)";
  838. return 1; /* We don't know a DirPort -- must begindir. */
  839. }
  840. /* Reasons why we can't possibly use begindir */
  841. if (!or_port) {
  842. *reason = "directory with unknown ORPort";
  843. return 0; /* We don't know an ORPort -- no chance. */
  844. }
  845. if (indirection == DIRIND_DIRECT_CONN ||
  846. indirection == DIRIND_ANON_DIRPORT) {
  847. *reason = "DirPort connection";
  848. return 0;
  849. }
  850. if (indirection == DIRIND_ONEHOP) {
  851. /* We're firewalled and want a direct OR connection */
  852. if (!fascist_firewall_allows_address_addr(or_addr, or_port,
  853. FIREWALL_OR_CONNECTION, 0, 0)) {
  854. *reason = "ORPort not reachable";
  855. return 0;
  856. }
  857. }
  858. /* Reasons why we want to avoid using begindir */
  859. if (indirection == DIRIND_ONEHOP) {
  860. if (!directory_must_use_begindir(options)) {
  861. *reason = "in relay mode";
  862. return 0;
  863. }
  864. }
  865. /* DIRIND_ONEHOP on a client, or DIRIND_ANONYMOUS
  866. */
  867. *reason = "(using begindir)";
  868. return 1;
  869. }
  870. /**
  871. * Create and return a new directory_request_t with purpose
  872. * <b>dir_purpose</b>.
  873. */
  874. directory_request_t *
  875. directory_request_new(uint8_t dir_purpose)
  876. {
  877. tor_assert(dir_purpose >= DIR_PURPOSE_MIN_);
  878. tor_assert(dir_purpose <= DIR_PURPOSE_MAX_);
  879. tor_assert(dir_purpose != DIR_PURPOSE_SERVER);
  880. tor_assert(dir_purpose != DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2);
  881. tor_assert(dir_purpose != DIR_PURPOSE_HAS_FETCHED_HSDESC);
  882. directory_request_t *result = tor_malloc_zero(sizeof(*result));
  883. tor_addr_make_null(&result->or_addr_port.addr, AF_INET);
  884. result->or_addr_port.port = 0;
  885. tor_addr_make_null(&result->dir_addr_port.addr, AF_INET);
  886. result->dir_addr_port.port = 0;
  887. result->dir_purpose = dir_purpose;
  888. result->router_purpose = ROUTER_PURPOSE_GENERAL;
  889. result->indirection = DIRIND_ONEHOP;
  890. return result;
  891. }
  892. /**
  893. * Release all resources held by <b>req</b>.
  894. */
  895. void
  896. directory_request_free_(directory_request_t *req)
  897. {
  898. if (req == NULL)
  899. return;
  900. config_free_lines(req->additional_headers);
  901. tor_free(req);
  902. }
  903. /**
  904. * Set the address and OR port to use for this directory request. If there is
  905. * no OR port, we'll have to connect over the dirport. (If there are both,
  906. * the indirection setting determines which to use.)
  907. */
  908. void
  909. directory_request_set_or_addr_port(directory_request_t *req,
  910. const tor_addr_port_t *p)
  911. {
  912. memcpy(&req->or_addr_port, p, sizeof(*p));
  913. }
  914. /**
  915. * Set the address and dirport to use for this directory request. If there
  916. * is no dirport, we'll have to connect over the OR port. (If there are both,
  917. * the indirection setting determines which to use.)
  918. */
  919. void
  920. directory_request_set_dir_addr_port(directory_request_t *req,
  921. const tor_addr_port_t *p)
  922. {
  923. memcpy(&req->dir_addr_port, p, sizeof(*p));
  924. }
  925. /**
  926. * Set the RSA identity digest of the directory to use for this directory
  927. * request.
  928. */
  929. void
  930. directory_request_set_directory_id_digest(directory_request_t *req,
  931. const char *digest)
  932. {
  933. memcpy(req->digest, digest, DIGEST_LEN);
  934. }
  935. /**
  936. * Set the router purpose associated with uploaded and downloaded router
  937. * descriptors and extrainfo documents in this directory request. The purpose
  938. * must be one of ROUTER_PURPOSE_GENERAL (the default) or
  939. * ROUTER_PURPOSE_BRIDGE.
  940. */
  941. void
  942. directory_request_set_router_purpose(directory_request_t *req,
  943. uint8_t router_purpose)
  944. {
  945. tor_assert(router_purpose == ROUTER_PURPOSE_GENERAL ||
  946. router_purpose == ROUTER_PURPOSE_BRIDGE);
  947. // assert that it actually makes sense to set this purpose, given
  948. // the dir_purpose.
  949. req->router_purpose = router_purpose;
  950. }
  951. /**
  952. * Set the indirection to be used for the directory request. The indirection
  953. * parameter configures whether to connect to a DirPort or ORPort, and whether
  954. * to anonymize the connection. DIRIND_ONEHOP (use ORPort, don't anonymize)
  955. * is the default. See dir_indirection_t for more information.
  956. */
  957. void
  958. directory_request_set_indirection(directory_request_t *req,
  959. dir_indirection_t indirection)
  960. {
  961. req->indirection = indirection;
  962. }
  963. /**
  964. * Set a pointer to the resource to request from a directory. Different
  965. * request types use resources to indicate different components of their URL.
  966. * Note that only an alias to <b>resource</b> is stored, so the
  967. * <b>resource</b> must outlive the request.
  968. */
  969. void
  970. directory_request_set_resource(directory_request_t *req,
  971. const char *resource)
  972. {
  973. req->resource = resource;
  974. }
  975. /**
  976. * Set a pointer to the payload to include with this directory request, along
  977. * with its length. Note that only an alias to <b>payload</b> is stored, so
  978. * the <b>payload</b> must outlive the request.
  979. */
  980. void
  981. directory_request_set_payload(directory_request_t *req,
  982. const char *payload,
  983. size_t payload_len)
  984. {
  985. tor_assert(DIR_PURPOSE_IS_UPLOAD(req->dir_purpose));
  986. req->payload = payload;
  987. req->payload_len = payload_len;
  988. }
  989. /**
  990. * Set an if-modified-since date to send along with the request. The
  991. * default is 0 (meaning, send no if-modified-since header).
  992. */
  993. void
  994. directory_request_set_if_modified_since(directory_request_t *req,
  995. time_t if_modified_since)
  996. {
  997. req->if_modified_since = if_modified_since;
  998. }
  999. /** Include a header of name <b>key</b> with content <b>val</b> in the
  1000. * request. Neither may include newlines or other odd characters. Their
  1001. * ordering is not currently guaranteed.
  1002. *
  1003. * Note that, as elsewhere in this module, header keys include a trailing
  1004. * colon and space.
  1005. */
  1006. void
  1007. directory_request_add_header(directory_request_t *req,
  1008. const char *key,
  1009. const char *val)
  1010. {
  1011. config_line_prepend(&req->additional_headers, key, val);
  1012. }
  1013. /**
  1014. * Set an object containing HS data to be associated with this request. Note
  1015. * that only an alias to <b>query</b> is stored, so the <b>query</b> object
  1016. * must outlive the request.
  1017. */
  1018. void
  1019. directory_request_set_rend_query(directory_request_t *req,
  1020. const rend_data_t *query)
  1021. {
  1022. if (query) {
  1023. tor_assert(req->dir_purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 ||
  1024. req->dir_purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2);
  1025. }
  1026. req->rend_query = query;
  1027. }
  1028. /**
  1029. * Set an object containing HS connection identifier to be associated with
  1030. * this request. Note that only an alias to <b>ident</b> is stored, so the
  1031. * <b>ident</b> object must outlive the request.
  1032. */
  1033. void
  1034. directory_request_upload_set_hs_ident(directory_request_t *req,
  1035. const hs_ident_dir_conn_t *ident)
  1036. {
  1037. if (ident) {
  1038. tor_assert(req->dir_purpose == DIR_PURPOSE_UPLOAD_HSDESC);
  1039. }
  1040. req->hs_ident = ident;
  1041. }
  1042. /**
  1043. * Set an object containing HS connection identifier to be associated with
  1044. * this fetch request. Note that only an alias to <b>ident</b> is stored, so
  1045. * the <b>ident</b> object must outlive the request.
  1046. */
  1047. void
  1048. directory_request_fetch_set_hs_ident(directory_request_t *req,
  1049. const hs_ident_dir_conn_t *ident)
  1050. {
  1051. if (ident) {
  1052. tor_assert(req->dir_purpose == DIR_PURPOSE_FETCH_HSDESC);
  1053. }
  1054. req->hs_ident = ident;
  1055. }
  1056. /** Set a static circuit_guard_state_t object to affliate with the request in
  1057. * <b>req</b>. This object will receive notification when the attempt to
  1058. * connect to the guard either succeeds or fails. */
  1059. void
  1060. directory_request_set_guard_state(directory_request_t *req,
  1061. circuit_guard_state_t *state)
  1062. {
  1063. req->guard_state = state;
  1064. }
  1065. /**
  1066. * Internal: Return true if any information for contacting the directory in
  1067. * <b>req</b> has been set, other than by the routerstatus. */
  1068. static int
  1069. directory_request_dir_contact_info_specified(const directory_request_t *req)
  1070. {
  1071. /* We only check for ports here, since we don't use an addr unless the port
  1072. * is set */
  1073. return (req->or_addr_port.port ||
  1074. req->dir_addr_port.port ||
  1075. ! tor_digest_is_zero(req->digest));
  1076. }
  1077. /**
  1078. * Set the routerstatus to use for the directory associated with this
  1079. * request. If this option is set, then no other function to set the
  1080. * directory's address or identity should be called.
  1081. */
  1082. void
  1083. directory_request_set_routerstatus(directory_request_t *req,
  1084. const routerstatus_t *status)
  1085. {
  1086. req->routerstatus = status;
  1087. }
  1088. /**
  1089. * Helper: update the addresses, ports, and identities in <b>req</b>
  1090. * from the routerstatus object in <b>req</b>. Return 0 on success.
  1091. * On failure, warn and return -1.
  1092. */
  1093. static int
  1094. directory_request_set_dir_from_routerstatus(directory_request_t *req)
  1095. {
  1096. const routerstatus_t *status = req->routerstatus;
  1097. if (BUG(status == NULL))
  1098. return -1;
  1099. const or_options_t *options = get_options();
  1100. const node_t *node;
  1101. tor_addr_port_t use_or_ap, use_dir_ap;
  1102. const int anonymized_connection = dirind_is_anon(req->indirection);
  1103. tor_assert(status != NULL);
  1104. node = node_get_by_id(status->identity_digest);
  1105. /* XXX The below check is wrong: !node means it's not in the consensus,
  1106. * but we haven't checked if we have a descriptor for it -- and also,
  1107. * we only care about the descriptor if it's a begindir-style anonymized
  1108. * connection. */
  1109. if (!node && anonymized_connection) {
  1110. log_info(LD_DIR, "Not sending anonymized request to directory '%s'; we "
  1111. "don't have its router descriptor.",
  1112. routerstatus_describe(status));
  1113. return -1;
  1114. }
  1115. if (options->ExcludeNodes && options->StrictNodes &&
  1116. routerset_contains_routerstatus(options->ExcludeNodes, status, -1)) {
  1117. log_warn(LD_DIR, "Wanted to contact directory mirror %s for %s, but "
  1118. "it's in our ExcludedNodes list and StrictNodes is set. "
  1119. "Skipping. This choice might make your Tor not work.",
  1120. routerstatus_describe(status),
  1121. dir_conn_purpose_to_string(req->dir_purpose));
  1122. return -1;
  1123. }
  1124. /* At this point, if we are a client making a direct connection to a
  1125. * directory server, we have selected a server that has at least one address
  1126. * allowed by ClientUseIPv4/6 and Reachable{"",OR,Dir}Addresses. This
  1127. * selection uses the preference in ClientPreferIPv6{OR,Dir}Port, if
  1128. * possible. (If UseBridges is set, clients always use IPv6, and prefer it
  1129. * by default.)
  1130. *
  1131. * Now choose an address that we can use to connect to the directory server.
  1132. */
  1133. if (directory_choose_address_routerstatus(status,
  1134. req->indirection, &use_or_ap,
  1135. &use_dir_ap) < 0) {
  1136. return -1;
  1137. }
  1138. directory_request_set_or_addr_port(req, &use_or_ap);
  1139. directory_request_set_dir_addr_port(req, &use_dir_ap);
  1140. directory_request_set_directory_id_digest(req, status->identity_digest);
  1141. return 0;
  1142. }
  1143. /**
  1144. * Launch the provided directory request, configured in <b>request</b>.
  1145. * After this function is called, you can free <b>request</b>.
  1146. */
  1147. MOCK_IMPL(void,
  1148. directory_initiate_request,(directory_request_t *request))
  1149. {
  1150. tor_assert(request);
  1151. if (request->routerstatus) {
  1152. tor_assert_nonfatal(
  1153. ! directory_request_dir_contact_info_specified(request));
  1154. if (directory_request_set_dir_from_routerstatus(request) < 0) {
  1155. return;
  1156. }
  1157. }
  1158. const tor_addr_port_t *or_addr_port = &request->or_addr_port;
  1159. const tor_addr_port_t *dir_addr_port = &request->dir_addr_port;
  1160. const char *digest = request->digest;
  1161. const uint8_t dir_purpose = request->dir_purpose;
  1162. const uint8_t router_purpose = request->router_purpose;
  1163. const dir_indirection_t indirection = request->indirection;
  1164. const char *resource = request->resource;
  1165. const rend_data_t *rend_query = request->rend_query;
  1166. const hs_ident_dir_conn_t *hs_ident = request->hs_ident;
  1167. circuit_guard_state_t *guard_state = request->guard_state;
  1168. tor_assert(or_addr_port->port || dir_addr_port->port);
  1169. tor_assert(digest);
  1170. dir_connection_t *conn;
  1171. const or_options_t *options = get_options();
  1172. int socket_error = 0;
  1173. const char *begindir_reason = NULL;
  1174. /* Should the connection be to a relay's OR port (and inside that we will
  1175. * send our directory request)? */
  1176. const int use_begindir =
  1177. directory_command_should_use_begindir(options, request, &begindir_reason);
  1178. /* Will the connection go via a three-hop Tor circuit? Note that this
  1179. * is separate from whether it will use_begindir. */
  1180. const int anonymized_connection = dirind_is_anon(indirection);
  1181. /* What is the address we want to make the directory request to? If
  1182. * we're making a begindir request this is the ORPort of the relay
  1183. * we're contacting; if not a begindir request, this is its DirPort.
  1184. * Note that if anonymized_connection is true, we won't be initiating
  1185. * a connection directly to this address. */
  1186. tor_addr_t addr;
  1187. tor_addr_copy(&addr, &(use_begindir ? or_addr_port : dir_addr_port)->addr);
  1188. uint16_t port = (use_begindir ? or_addr_port : dir_addr_port)->port;
  1189. log_debug(LD_DIR, "anonymized %d, use_begindir %d.",
  1190. anonymized_connection, use_begindir);
  1191. log_debug(LD_DIR, "Initiating %s", dir_conn_purpose_to_string(dir_purpose));
  1192. if (purpose_needs_anonymity(dir_purpose, router_purpose, resource)) {
  1193. tor_assert(anonymized_connection ||
  1194. rend_non_anonymous_mode_enabled(options));
  1195. }
  1196. /* use encrypted begindir connections for everything except relays
  1197. * this provides better protection for directory fetches */
  1198. if (!use_begindir && directory_must_use_begindir(options)) {
  1199. log_warn(LD_BUG, "Client could not use begindir connection: %s",
  1200. begindir_reason ? begindir_reason : "(NULL)");
  1201. return;
  1202. }
  1203. /* ensure that we don't make direct connections when a SOCKS server is
  1204. * configured. */
  1205. if (!anonymized_connection && !use_begindir && !options->HTTPProxy &&
  1206. (options->Socks4Proxy || options->Socks5Proxy)) {
  1207. log_warn(LD_DIR, "Cannot connect to a directory server through a "
  1208. "SOCKS proxy!");
  1209. return;
  1210. }
  1211. /* Make sure that the destination addr and port we picked is viable. */
  1212. if (!port || tor_addr_is_null(&addr)) {
  1213. static int logged_backtrace = 0;
  1214. log_warn(LD_DIR,
  1215. "Cannot make an outgoing %sconnection without a remote %sPort.",
  1216. use_begindir ? "begindir " : "",
  1217. use_begindir ? "OR" : "Dir");
  1218. if (!logged_backtrace) {
  1219. log_backtrace(LOG_INFO, LD_BUG, "Address came from");
  1220. logged_backtrace = 1;
  1221. }
  1222. return;
  1223. }
  1224. conn = dir_connection_new(tor_addr_family(&addr));
  1225. /* set up conn so it's got all the data we need to remember */
  1226. tor_addr_copy(&conn->base_.addr, &addr);
  1227. conn->base_.port = port;
  1228. conn->base_.address = tor_addr_to_str_dup(&addr);
  1229. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  1230. conn->base_.purpose = dir_purpose;
  1231. conn->router_purpose = router_purpose;
  1232. /* give it an initial state */
  1233. conn->base_.state = DIR_CONN_STATE_CONNECTING;
  1234. /* decide whether we can learn our IP address from this conn */
  1235. /* XXXX This is a bad name for this field now. */
  1236. conn->dirconn_direct = !anonymized_connection;
  1237. /* copy rendezvous data, if any */
  1238. if (rend_query) {
  1239. /* We can't have both v2 and v3+ identifier. */
  1240. tor_assert_nonfatal(!hs_ident);
  1241. conn->rend_data = rend_data_dup(rend_query);
  1242. }
  1243. if (hs_ident) {
  1244. /* We can't have both v2 and v3+ identifier. */
  1245. tor_assert_nonfatal(!rend_query);
  1246. conn->hs_ident = hs_ident_dir_conn_dup(hs_ident);
  1247. }
  1248. if (!anonymized_connection && !use_begindir) {
  1249. /* then we want to connect to dirport directly */
  1250. if (options->HTTPProxy) {
  1251. tor_addr_copy(&addr, &options->HTTPProxyAddr);
  1252. port = options->HTTPProxyPort;
  1253. }
  1254. // In this case we should not have picked a directory guard.
  1255. if (BUG(guard_state)) {
  1256. entry_guard_cancel(&guard_state);
  1257. }
  1258. switch (connection_connect(TO_CONN(conn), conn->base_.address, &addr,
  1259. port, &socket_error)) {
  1260. case -1:
  1261. connection_mark_for_close(TO_CONN(conn));
  1262. return;
  1263. case 1:
  1264. /* start flushing conn */
  1265. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  1266. /* fall through */
  1267. case 0:
  1268. /* queue the command on the outbuf */
  1269. directory_send_command(conn, 1, request);
  1270. connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
  1271. /* writable indicates finish, readable indicates broken link,
  1272. error indicates broken link in windowsland. */
  1273. }
  1274. } else {
  1275. /* We will use a Tor circuit (maybe 1-hop, maybe 3-hop, maybe with
  1276. * begindir, maybe not with begindir) */
  1277. entry_connection_t *linked_conn;
  1278. /* Anonymized tunneled connections can never share a circuit.
  1279. * One-hop directory connections can share circuits with each other
  1280. * but nothing else. */
  1281. int iso_flags = anonymized_connection ? ISO_STREAM : ISO_SESSIONGRP;
  1282. /* If it's an anonymized connection, remember the fact that we
  1283. * wanted it for later: maybe we'll want it again soon. */
  1284. if (anonymized_connection && use_begindir)
  1285. rep_hist_note_used_internal(time(NULL), 0, 1);
  1286. else if (anonymized_connection && !use_begindir)
  1287. rep_hist_note_used_port(time(NULL), conn->base_.port);
  1288. // In this case we should not have a directory guard; we'll
  1289. // get a regular guard later when we build the circuit.
  1290. if (BUG(anonymized_connection && guard_state)) {
  1291. entry_guard_cancel(&guard_state);
  1292. }
  1293. conn->guard_state = guard_state;
  1294. /* make an AP connection
  1295. * populate it and add it at the right state
  1296. * hook up both sides
  1297. */
  1298. linked_conn =
  1299. connection_ap_make_link(TO_CONN(conn),
  1300. conn->base_.address, conn->base_.port,
  1301. digest,
  1302. SESSION_GROUP_DIRCONN, iso_flags,
  1303. use_begindir, !anonymized_connection);
  1304. if (!linked_conn) {
  1305. log_warn(LD_NET,"Making tunnel to dirserver failed.");
  1306. connection_mark_for_close(TO_CONN(conn));
  1307. return;
  1308. }
  1309. if (connection_add(TO_CONN(conn)) < 0) {
  1310. log_warn(LD_NET,"Unable to add connection for link to dirserver.");
  1311. connection_mark_for_close(TO_CONN(conn));
  1312. return;
  1313. }
  1314. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  1315. /* queue the command on the outbuf */
  1316. directory_send_command(conn, 0, request);
  1317. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  1318. connection_start_reading(ENTRY_TO_CONN(linked_conn));
  1319. }
  1320. }
  1321. /** Helper for sorting
  1322. *
  1323. * sort strings alphabetically
  1324. *
  1325. * XXXX we have a smartlist_sort_strings() function, right?
  1326. */
  1327. static int
  1328. compare_strs_(const void **a, const void **b)
  1329. {
  1330. const char *s1 = *a, *s2 = *b;
  1331. return strcmp(s1, s2);
  1332. }
  1333. #define CONDITIONAL_CONSENSUS_FPR_LEN 3
  1334. #if (CONDITIONAL_CONSENSUS_FPR_LEN > DIGEST_LEN)
  1335. #error "conditional consensus fingerprint length is larger than digest length"
  1336. #endif
  1337. /** Return the URL we should use for a consensus download.
  1338. *
  1339. * Use the "conditional consensus downloading" feature described in
  1340. * dir-spec.txt, i.e.
  1341. * GET .../consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>
  1342. *
  1343. * If 'resource' is provided, it is the name of a consensus flavor to request.
  1344. */
  1345. static char *
  1346. directory_get_consensus_url(const char *resource)
  1347. {
  1348. char *url = NULL;
  1349. const char *hyphen, *flavor;
  1350. if (resource==NULL || strcmp(resource, "ns")==0) {
  1351. flavor = ""; /* Request ns consensuses as "", so older servers will work*/
  1352. hyphen = "";
  1353. } else {
  1354. flavor = resource;
  1355. hyphen = "-";
  1356. }
  1357. {
  1358. char *authority_id_list;
  1359. smartlist_t *authority_digests = smartlist_new();
  1360. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  1361. dir_server_t *, ds) {
  1362. char *hex;
  1363. if (!(ds->type & V3_DIRINFO))
  1364. continue;
  1365. hex = tor_malloc(2*CONDITIONAL_CONSENSUS_FPR_LEN+1);
  1366. base16_encode(hex, 2*CONDITIONAL_CONSENSUS_FPR_LEN+1,
  1367. ds->v3_identity_digest, CONDITIONAL_CONSENSUS_FPR_LEN);
  1368. smartlist_add(authority_digests, hex);
  1369. } SMARTLIST_FOREACH_END(ds);
  1370. smartlist_sort(authority_digests, compare_strs_);
  1371. authority_id_list = smartlist_join_strings(authority_digests,
  1372. "+", 0, NULL);
  1373. tor_asprintf(&url, "/tor/status-vote/current/consensus%s%s/%s.z",
  1374. hyphen, flavor, authority_id_list);
  1375. SMARTLIST_FOREACH(authority_digests, char *, cp, tor_free(cp));
  1376. smartlist_free(authority_digests);
  1377. tor_free(authority_id_list);
  1378. }
  1379. return url;
  1380. }
  1381. /**
  1382. * Copies the ipv6 from source to destination, subject to buffer size limit
  1383. * size. If decorate is true, makes sure the copied address is decorated.
  1384. */
  1385. static void
  1386. copy_ipv6_address(char* destination, const char* source, size_t len,
  1387. int decorate) {
  1388. tor_assert(destination);
  1389. tor_assert(source);
  1390. if (decorate && source[0] != '[') {
  1391. tor_snprintf(destination, len, "[%s]", source);
  1392. } else {
  1393. strlcpy(destination, source, len);
  1394. }
  1395. }
  1396. /** Queue an appropriate HTTP command for <b>request</b> on
  1397. * <b>conn</b>-\>outbuf. If <b>direct</b> is true, we're making a
  1398. * non-anonymized connection to the dirport.
  1399. */
  1400. static void
  1401. directory_send_command(dir_connection_t *conn,
  1402. const int direct,
  1403. const directory_request_t *req)
  1404. {
  1405. tor_assert(req);
  1406. const int purpose = req->dir_purpose;
  1407. const char *resource = req->resource;
  1408. const char *payload = req->payload;
  1409. const size_t payload_len = req->payload_len;
  1410. const time_t if_modified_since = req->if_modified_since;
  1411. const int anonymized_connection = dirind_is_anon(req->indirection);
  1412. char proxystring[256];
  1413. char hoststring[128];
  1414. /* NEEDS to be the same size hoststring.
  1415. Will be decorated with brackets around it if it is ipv6. */
  1416. char decorated_address[128];
  1417. smartlist_t *headers = smartlist_new();
  1418. char *url;
  1419. char *accept_encoding;
  1420. size_t url_len;
  1421. char request[8192];
  1422. size_t request_len, total_request_len = 0;
  1423. const char *httpcommand = NULL;
  1424. tor_assert(conn);
  1425. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  1426. tor_free(conn->requested_resource);
  1427. if (resource)
  1428. conn->requested_resource = tor_strdup(resource);
  1429. /* decorate the ip address if it is ipv6 */
  1430. if (strchr(conn->base_.address, ':')) {
  1431. copy_ipv6_address(decorated_address, conn->base_.address,
  1432. sizeof(decorated_address), 1);
  1433. } else {
  1434. strlcpy(decorated_address, conn->base_.address, sizeof(decorated_address));
  1435. }
  1436. /* come up with a string for which Host: we want */
  1437. if (conn->base_.port == 80) {
  1438. strlcpy(hoststring, decorated_address, sizeof(hoststring));
  1439. } else {
  1440. tor_snprintf(hoststring, sizeof(hoststring), "%s:%d",
  1441. decorated_address, conn->base_.port);
  1442. }
  1443. /* Format if-modified-since */
  1444. if (if_modified_since) {
  1445. char b[RFC1123_TIME_LEN+1];
  1446. format_rfc1123_time(b, if_modified_since);
  1447. smartlist_add_asprintf(headers, "If-Modified-Since: %s\r\n", b);
  1448. }
  1449. /* come up with some proxy lines, if we're using one. */
  1450. if (direct && get_options()->HTTPProxy) {
  1451. char *base64_authenticator=NULL;
  1452. const char *authenticator = get_options()->HTTPProxyAuthenticator;
  1453. tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  1454. if (authenticator) {
  1455. base64_authenticator = alloc_http_authenticator(authenticator);
  1456. if (!base64_authenticator)
  1457. log_warn(LD_BUG, "Encoding http authenticator failed");
  1458. }
  1459. if (base64_authenticator) {
  1460. smartlist_add_asprintf(headers,
  1461. "Proxy-Authorization: Basic %s\r\n",
  1462. base64_authenticator);
  1463. tor_free(base64_authenticator);
  1464. }
  1465. } else {
  1466. proxystring[0] = 0;
  1467. }
  1468. if (! anonymized_connection) {
  1469. /* Add Accept-Encoding. */
  1470. accept_encoding = accept_encoding_header();
  1471. smartlist_add_asprintf(headers, "Accept-Encoding: %s\r\n",
  1472. accept_encoding);
  1473. tor_free(accept_encoding);
  1474. }
  1475. /* Add additional headers, if any */
  1476. {
  1477. config_line_t *h;
  1478. for (h = req->additional_headers; h; h = h->next) {
  1479. smartlist_add_asprintf(headers, "%s%s\r\n", h->key, h->value);
  1480. }
  1481. }
  1482. switch (purpose) {
  1483. case DIR_PURPOSE_FETCH_CONSENSUS:
  1484. /* resource is optional. If present, it's a flavor name */
  1485. tor_assert(!payload);
  1486. httpcommand = "GET";
  1487. url = directory_get_consensus_url(resource);
  1488. log_info(LD_DIR, "Downloading consensus from %s using %s",
  1489. hoststring, url);
  1490. break;
  1491. case DIR_PURPOSE_FETCH_CERTIFICATE:
  1492. tor_assert(resource);
  1493. tor_assert(!payload);
  1494. httpcommand = "GET";
  1495. tor_asprintf(&url, "/tor/keys/%s", resource);
  1496. break;
  1497. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  1498. tor_assert(resource);
  1499. tor_assert(!payload);
  1500. httpcommand = "GET";
  1501. tor_asprintf(&url, "/tor/status-vote/next/%s.z", resource);
  1502. break;
  1503. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  1504. tor_assert(!resource);
  1505. tor_assert(!payload);
  1506. httpcommand = "GET";
  1507. url = tor_strdup("/tor/status-vote/next/consensus-signatures.z");
  1508. break;
  1509. case DIR_PURPOSE_FETCH_SERVERDESC:
  1510. tor_assert(resource);
  1511. httpcommand = "GET";
  1512. tor_asprintf(&url, "/tor/server/%s", resource);
  1513. break;
  1514. case DIR_PURPOSE_FETCH_EXTRAINFO:
  1515. tor_assert(resource);
  1516. httpcommand = "GET";
  1517. tor_asprintf(&url, "/tor/extra/%s", resource);
  1518. break;
  1519. case DIR_PURPOSE_FETCH_MICRODESC:
  1520. tor_assert(resource);
  1521. httpcommand = "GET";
  1522. tor_asprintf(&url, "/tor/micro/%s", resource);
  1523. break;
  1524. case DIR_PURPOSE_UPLOAD_DIR: {
  1525. const char *why = router_get_descriptor_gen_reason();
  1526. tor_assert(!resource);
  1527. tor_assert(payload);
  1528. httpcommand = "POST";
  1529. url = tor_strdup("/tor/");
  1530. if (!why) {
  1531. why = "for no reason at all";
  1532. }
  1533. smartlist_add_asprintf(headers, "X-Desc-Gen-Reason: %s\r\n", why);
  1534. break;
  1535. }
  1536. case DIR_PURPOSE_UPLOAD_VOTE:
  1537. tor_assert(!resource);
  1538. tor_assert(payload);
  1539. httpcommand = "POST";
  1540. url = tor_strdup("/tor/post/vote");
  1541. break;
  1542. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  1543. tor_assert(!resource);
  1544. tor_assert(payload);
  1545. httpcommand = "POST";
  1546. url = tor_strdup("/tor/post/consensus-signature");
  1547. break;
  1548. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  1549. tor_assert(resource);
  1550. tor_assert(strlen(resource) <= REND_DESC_ID_V2_LEN_BASE32);
  1551. tor_assert(!payload);
  1552. httpcommand = "GET";
  1553. tor_asprintf(&url, "/tor/rendezvous2/%s", resource);
  1554. break;
  1555. case DIR_PURPOSE_FETCH_HSDESC:
  1556. tor_assert(resource);
  1557. tor_assert(strlen(resource) <= ED25519_BASE64_LEN);
  1558. tor_assert(!payload);
  1559. httpcommand = "GET";
  1560. tor_asprintf(&url, "/tor/hs/3/%s", resource);
  1561. break;
  1562. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  1563. tor_assert(!resource);
  1564. tor_assert(payload);
  1565. httpcommand = "POST";
  1566. url = tor_strdup("/tor/rendezvous2/publish");
  1567. break;
  1568. case DIR_PURPOSE_UPLOAD_HSDESC:
  1569. tor_assert(resource);
  1570. tor_assert(payload);
  1571. httpcommand = "POST";
  1572. tor_asprintf(&url, "/tor/hs/%s/publish", resource);
  1573. break;
  1574. default:
  1575. tor_assert(0);
  1576. return;
  1577. }
  1578. /* warn in the non-tunneled case */
  1579. if (direct && (strlen(proxystring) + strlen(url) >= 4096)) {
  1580. log_warn(LD_BUG,
  1581. "Squid does not like URLs longer than 4095 bytes, and this "
  1582. "one is %d bytes long: %s%s",
  1583. (int)(strlen(proxystring) + strlen(url)), proxystring, url);
  1584. }
  1585. tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
  1586. request_len = strlen(request);
  1587. total_request_len += request_len;
  1588. connection_buf_add(request, request_len, TO_CONN(conn));
  1589. url_len = strlen(url);
  1590. total_request_len += url_len;
  1591. connection_buf_add(url, url_len, TO_CONN(conn));
  1592. tor_free(url);
  1593. if (!strcmp(httpcommand, "POST") || payload) {
  1594. smartlist_add_asprintf(headers, "Content-Length: %lu\r\n",
  1595. payload ? (unsigned long)payload_len : 0);
  1596. }
  1597. {
  1598. char *header = smartlist_join_strings(headers, "", 0, NULL);
  1599. tor_snprintf(request, sizeof(request), " HTTP/1.0\r\nHost: %s\r\n%s\r\n",
  1600. hoststring, header);
  1601. tor_free(header);
  1602. }
  1603. request_len = strlen(request);
  1604. total_request_len += request_len;
  1605. connection_buf_add(request, request_len, TO_CONN(conn));
  1606. if (payload) {
  1607. /* then send the payload afterwards too */
  1608. connection_buf_add(payload, payload_len, TO_CONN(conn));
  1609. total_request_len += payload_len;
  1610. }
  1611. SMARTLIST_FOREACH(headers, char *, h, tor_free(h));
  1612. smartlist_free(headers);
  1613. log_debug(LD_DIR,
  1614. "Sent request to directory server '%s:%d': "
  1615. "(purpose: %d, request size: %"TOR_PRIuSZ", "
  1616. "payload size: %"TOR_PRIuSZ")",
  1617. conn->base_.address, conn->base_.port,
  1618. conn->base_.purpose,
  1619. (total_request_len),
  1620. (payload ? payload_len : 0));
  1621. }
  1622. /** Return true iff <b>body</b> doesn't start with a plausible router or
  1623. * network-status or microdescriptor opening. This is a sign of possible
  1624. * compression. */
  1625. static int
  1626. body_is_plausible(const char *body, size_t len, int purpose)
  1627. {
  1628. int i;
  1629. if (len == 0)
  1630. return 1; /* empty bodies don't need decompression */
  1631. if (len < 32)
  1632. return 0;
  1633. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  1634. return (!strcmpstart(body,"onion-key"));
  1635. }
  1636. if (!strcmpstart(body,"router") ||
  1637. !strcmpstart(body,"network-status"))
  1638. return 1;
  1639. for (i=0;i<32;++i) {
  1640. if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  1641. return 0;
  1642. }
  1643. return 1;
  1644. }
  1645. /** Called when we've just fetched a bunch of router descriptors in
  1646. * <b>body</b>. The list <b>which</b>, if present, holds digests for
  1647. * descriptors we requested: descriptor digests if <b>descriptor_digests</b>
  1648. * is true, or identity digests otherwise. Parse the descriptors, validate
  1649. * them, and annotate them as having purpose <b>purpose</b> and as having been
  1650. * downloaded from <b>source</b>.
  1651. *
  1652. * Return the number of routers actually added. */
  1653. static int
  1654. load_downloaded_routers(const char *body, smartlist_t *which,
  1655. int descriptor_digests,
  1656. int router_purpose,
  1657. const char *source)
  1658. {
  1659. char buf[256];
  1660. char time_buf[ISO_TIME_LEN+1];
  1661. int added = 0;
  1662. int general = router_purpose == ROUTER_PURPOSE_GENERAL;
  1663. format_iso_time(time_buf, time(NULL));
  1664. tor_assert(source);
  1665. if (tor_snprintf(buf, sizeof(buf),
  1666. "@downloaded-at %s\n"
  1667. "@source %s\n"
  1668. "%s%s%s", time_buf, escaped(source),
  1669. !general ? "@purpose " : "",
  1670. !general ? router_purpose_to_string(router_purpose) : "",
  1671. !general ? "\n" : "")<0)
  1672. return added;
  1673. added = router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  1674. descriptor_digests, buf);
  1675. if (added && general)
  1676. control_event_boot_dir(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  1677. count_loading_descriptors_progress());
  1678. return added;
  1679. }
  1680. static int handle_response_fetch_certificate(dir_connection_t *,
  1681. const response_handler_args_t *);
  1682. static int handle_response_fetch_status_vote(dir_connection_t *,
  1683. const response_handler_args_t *);
  1684. static int handle_response_fetch_detached_signatures(dir_connection_t *,
  1685. const response_handler_args_t *);
  1686. static int handle_response_fetch_desc(dir_connection_t *,
  1687. const response_handler_args_t *);
  1688. static int handle_response_upload_dir(dir_connection_t *,
  1689. const response_handler_args_t *);
  1690. static int handle_response_upload_vote(dir_connection_t *,
  1691. const response_handler_args_t *);
  1692. static int handle_response_upload_signatures(dir_connection_t *,
  1693. const response_handler_args_t *);
  1694. static int handle_response_fetch_renddesc_v2(dir_connection_t *,
  1695. const response_handler_args_t *);
  1696. static int handle_response_upload_renddesc_v2(dir_connection_t *,
  1697. const response_handler_args_t *);
  1698. static int handle_response_upload_hsdesc(dir_connection_t *,
  1699. const response_handler_args_t *);
  1700. static int
  1701. dir_client_decompress_response_body(char **bodyp, size_t *bodylenp,
  1702. dir_connection_t *conn,
  1703. compress_method_t compression,
  1704. int anonymized_connection)
  1705. {
  1706. int rv = 0;
  1707. const char *body = *bodyp;
  1708. size_t body_len = *bodylenp;
  1709. int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  1710. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  1711. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  1712. int plausible = body_is_plausible(body, body_len, conn->base_.purpose);
  1713. if (plausible && compression == NO_METHOD) {
  1714. return 0;
  1715. }
  1716. int severity = LOG_DEBUG;
  1717. char *new_body = NULL;
  1718. size_t new_len = 0;
  1719. const char *description1, *description2;
  1720. int want_to_try_both = 0;
  1721. int tried_both = 0;
  1722. compress_method_t guessed = detect_compression_method(body, body_len);
  1723. description1 = compression_method_get_human_name(compression);
  1724. if (BUG(description1 == NULL))
  1725. description1 = compression_method_get_human_name(UNKNOWN_METHOD);
  1726. if (guessed == UNKNOWN_METHOD && !plausible)
  1727. description2 = "confusing binary junk";
  1728. else
  1729. description2 = compression_method_get_human_name(guessed);
  1730. /* Tell the user if we don't believe what we're told about compression.*/
  1731. want_to_try_both = (compression == UNKNOWN_METHOD ||
  1732. guessed != compression);
  1733. if (want_to_try_both) {
  1734. severity = LOG_PROTOCOL_WARN;
  1735. }
  1736. tor_log(severity, LD_HTTP,
  1737. "HTTP body from server '%s:%d' was labeled as %s, "
  1738. "%s it seems to be %s.%s",
  1739. conn->base_.address, conn->base_.port, description1,
  1740. guessed != compression?"but":"and",
  1741. description2,
  1742. (compression>0 && guessed>0 && want_to_try_both)?
  1743. " Trying both.":"");
  1744. /* Try declared compression first if we can.
  1745. * tor_compress_supports_method() also returns true for NO_METHOD.
  1746. * Ensure that the server is not sending us data compressed using a
  1747. * compression method that is not allowed for anonymous connections. */
  1748. if (anonymized_connection &&
  1749. ! allowed_anonymous_connection_compression_method(compression)) {
  1750. warn_disallowed_anonymous_compression_method(compression);
  1751. rv = -1;
  1752. goto done;
  1753. }
  1754. if (tor_compress_supports_method(compression)) {
  1755. tor_uncompress(&new_body, &new_len, body, body_len, compression,
  1756. !allow_partial, LOG_PROTOCOL_WARN);
  1757. if (new_body) {
  1758. /* We succeeded with the declared compression method. Great! */
  1759. rv = 0;
  1760. goto done;
  1761. }
  1762. }
  1763. /* Okay, if that didn't work, and we think that it was compressed
  1764. * differently, try that. */
  1765. if (anonymized_connection &&
  1766. ! allowed_anonymous_connection_compression_method(guessed)) {
  1767. warn_disallowed_anonymous_compression_method(guessed);
  1768. rv = -1;
  1769. goto done;
  1770. }
  1771. if (tor_compress_supports_method(guessed) &&
  1772. compression != guessed) {
  1773. tor_uncompress(&new_body, &new_len, body, body_len, guessed,
  1774. !allow_partial, LOG_INFO);
  1775. tried_both = 1;
  1776. }
  1777. /* If we're pretty sure that we have a compressed directory, and
  1778. * we didn't manage to uncompress it, then warn and bail. */
  1779. if (!plausible && !new_body) {
  1780. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  1781. "Unable to decompress HTTP body (tried %s%s%s, server '%s:%d').",
  1782. description1,
  1783. tried_both?" and ":"",
  1784. tried_both?description2:"",
  1785. conn->base_.address, conn->base_.port);
  1786. rv = -1;
  1787. goto done;
  1788. }
  1789. done:
  1790. if (new_body) {
  1791. if (rv == 0) {
  1792. /* success! */
  1793. tor_free(*bodyp);
  1794. *bodyp = new_body;
  1795. *bodylenp = new_len;
  1796. } else {
  1797. tor_free(new_body);
  1798. }
  1799. }
  1800. return rv;
  1801. }
  1802. /** We are a client, and we've finished reading the server's
  1803. * response. Parse it and act appropriately.
  1804. *
  1805. * If we're still happy with using this directory server in the future, return
  1806. * 0. Otherwise return -1; and the caller should consider trying the request
  1807. * again.
  1808. *
  1809. * The caller will take care of marking the connection for close.
  1810. */
  1811. static int
  1812. connection_dir_client_reached_eof(dir_connection_t *conn)
  1813. {
  1814. char *body = NULL;
  1815. char *headers = NULL;
  1816. char *reason = NULL;
  1817. size_t body_len = 0;
  1818. int status_code;
  1819. time_t date_header = 0;
  1820. long apparent_skew;
  1821. compress_method_t compression;
  1822. int skewed = 0;
  1823. int rv;
  1824. int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  1825. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  1826. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  1827. size_t received_bytes;
  1828. const int anonymized_connection =
  1829. purpose_needs_anonymity(conn->base_.purpose,
  1830. conn->router_purpose,
  1831. conn->requested_resource);
  1832. received_bytes = connection_get_inbuf_len(TO_CONN(conn));
  1833. switch (connection_fetch_from_buf_http(TO_CONN(conn),
  1834. &headers, MAX_HEADERS_SIZE,
  1835. &body, &body_len, MAX_DIR_DL_SIZE,
  1836. allow_partial)) {
  1837. case -1: /* overflow */
  1838. log_warn(LD_PROTOCOL,
  1839. "'fetch' response too large (server '%s:%d'). Closing.",
  1840. conn->base_.address, conn->base_.port);
  1841. return -1;
  1842. case 0:
  1843. log_info(LD_HTTP,
  1844. "'fetch' response not all here, but we're at eof. Closing.");
  1845. return -1;
  1846. /* case 1, fall through */
  1847. }
  1848. if (parse_http_response(headers, &status_code, &date_header,
  1849. &compression, &reason) < 0) {
  1850. log_warn(LD_HTTP,"Unparseable headers (server '%s:%d'). Closing.",
  1851. conn->base_.address, conn->base_.port);
  1852. rv = -1;
  1853. goto done;
  1854. }
  1855. if (!reason) reason = tor_strdup("[no reason given]");
  1856. tor_log(LOG_DEBUG, LD_DIR,
  1857. "Received response from directory server '%s:%d': %d %s "
  1858. "(purpose: %d, response size: %"TOR_PRIuSZ
  1859. #ifdef MEASUREMENTS_21206
  1860. ", data cells received: %d, data cells sent: %d"
  1861. #endif
  1862. ", compression: %d)",
  1863. conn->base_.address, conn->base_.port, status_code,
  1864. escaped(reason), conn->base_.purpose,
  1865. (received_bytes),
  1866. #ifdef MEASUREMENTS_21206
  1867. conn->data_cells_received, conn->data_cells_sent,
  1868. #endif
  1869. compression);
  1870. if (conn->guard_state) {
  1871. /* we count the connection as successful once we can read from it. We do
  1872. * not, however, delay use of the circuit here, since it's just for a
  1873. * one-hop directory request. */
  1874. /* XXXXprop271 note that this will not do the right thing for other
  1875. * waiting circuits that would be triggered by this circuit becoming
  1876. * complete/usable. But that's ok, I think.
  1877. */
  1878. entry_guard_succeeded(&conn->guard_state);
  1879. circuit_guard_state_free(conn->guard_state);
  1880. conn->guard_state = NULL;
  1881. }
  1882. /* now check if it's got any hints for us about our IP address. */
  1883. if (conn->dirconn_direct) {
  1884. char *guess = http_get_header(headers, X_ADDRESS_HEADER);
  1885. if (guess) {
  1886. router_new_address_suggestion(guess, conn);
  1887. tor_free(guess);
  1888. }
  1889. }
  1890. if (date_header > 0) {
  1891. /* The date header was written very soon after we sent our request,
  1892. * so compute the skew as the difference between sending the request
  1893. * and the date header. (We used to check now-date_header, but that's
  1894. * inaccurate if we spend a lot of time downloading.)
  1895. */
  1896. apparent_skew = conn->base_.timestamp_last_write_allowed - date_header;
  1897. if (labs(apparent_skew)>ALLOW_DIRECTORY_TIME_SKEW) {
  1898. int trusted = router_digest_is_trusted_dir(conn->identity_digest);
  1899. clock_skew_warning(TO_CONN(conn), apparent_skew, trusted, LD_HTTP,
  1900. "directory", "DIRSERV");
  1901. skewed = 1; /* don't check the recommended-versions line */
  1902. } else {
  1903. log_debug(LD_HTTP, "Time on received directory is within tolerance; "
  1904. "we are %ld seconds skewed. (That's okay.)", apparent_skew);
  1905. }
  1906. }
  1907. (void) skewed; /* skewed isn't used yet. */
  1908. if (status_code == 503) {
  1909. routerstatus_t *rs;
  1910. dir_server_t *ds;
  1911. const char *id_digest = conn->identity_digest;
  1912. log_info(LD_DIR,"Received http status code %d (%s) from server "
  1913. "'%s:%d'. I'll try again soon.",
  1914. status_code, escaped(reason), conn->base_.address,
  1915. conn->base_.port);
  1916. time_t now = approx_time();
  1917. if ((rs = router_get_mutable_consensus_status_by_id(id_digest)))
  1918. rs->last_dir_503_at = now;
  1919. if ((ds = router_get_fallback_dirserver_by_digest(id_digest)))
  1920. ds->fake_status.last_dir_503_at = now;
  1921. rv = -1;
  1922. goto done;
  1923. }
  1924. if (dir_client_decompress_response_body(&body, &body_len,
  1925. conn, compression, anonymized_connection) < 0) {
  1926. rv = -1;
  1927. goto done;
  1928. }
  1929. response_handler_args_t args;
  1930. memset(&args, 0, sizeof(args));
  1931. args.status_code = status_code;
  1932. args.reason = reason;
  1933. args.body = body;
  1934. args.body_len = body_len;
  1935. args.headers = headers;
  1936. switch (conn->base_.purpose) {
  1937. case DIR_PURPOSE_FETCH_CONSENSUS:
  1938. rv = handle_response_fetch_consensus(conn, &args);
  1939. break;
  1940. case DIR_PURPOSE_FETCH_CERTIFICATE:
  1941. rv = handle_response_fetch_certificate(conn, &args);
  1942. break;
  1943. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  1944. rv = handle_response_fetch_status_vote(conn, &args);
  1945. break;
  1946. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  1947. rv = handle_response_fetch_detached_signatures(conn, &args);
  1948. break;
  1949. case DIR_PURPOSE_FETCH_SERVERDESC:
  1950. case DIR_PURPOSE_FETCH_EXTRAINFO:
  1951. rv = handle_response_fetch_desc(conn, &args);
  1952. break;
  1953. case DIR_PURPOSE_FETCH_MICRODESC:
  1954. rv = handle_response_fetch_microdesc(conn, &args);
  1955. break;
  1956. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  1957. rv = handle_response_fetch_renddesc_v2(conn, &args);
  1958. break;
  1959. case DIR_PURPOSE_UPLOAD_DIR:
  1960. rv = handle_response_upload_dir(conn, &args);
  1961. break;
  1962. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  1963. rv = handle_response_upload_signatures(conn, &args);
  1964. break;
  1965. case DIR_PURPOSE_UPLOAD_VOTE:
  1966. rv = handle_response_upload_vote(conn, &args);
  1967. break;
  1968. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  1969. rv = handle_response_upload_renddesc_v2(conn, &args);
  1970. break;
  1971. case DIR_PURPOSE_UPLOAD_HSDESC:
  1972. rv = handle_response_upload_hsdesc(conn, &args);
  1973. break;
  1974. case DIR_PURPOSE_FETCH_HSDESC:
  1975. rv = handle_response_fetch_hsdesc_v3(conn, &args);
  1976. break;
  1977. default:
  1978. tor_assert_nonfatal_unreached();
  1979. rv = -1;
  1980. break;
  1981. }
  1982. done:
  1983. tor_free(body);
  1984. tor_free(headers);
  1985. tor_free(reason);
  1986. return rv;
  1987. }
  1988. /**
  1989. * Handler function: processes a response to a request for a networkstatus
  1990. * consensus document by checking the consensus, storing it, and marking
  1991. * router requests as reachable.
  1992. **/
  1993. STATIC int
  1994. handle_response_fetch_consensus(dir_connection_t *conn,
  1995. const response_handler_args_t *args)
  1996. {
  1997. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS);
  1998. const int status_code = args->status_code;
  1999. const char *body = args->body;
  2000. const size_t body_len = args->body_len;
  2001. const char *reason = args->reason;
  2002. const time_t now = approx_time();
  2003. const char *consensus;
  2004. char *new_consensus = NULL;
  2005. const char *sourcename;
  2006. int r;
  2007. const char *flavname = conn->requested_resource;
  2008. if (status_code != 200) {
  2009. int severity = (status_code == 304) ? LOG_INFO : LOG_WARN;
  2010. tor_log(severity, LD_DIR,
  2011. "Received http status code %d (%s) from server "
  2012. "'%s:%d' while fetching consensus directory.",
  2013. status_code, escaped(reason), conn->base_.address,
  2014. conn->base_.port);
  2015. networkstatus_consensus_download_failed(status_code, flavname);
  2016. return -1;
  2017. }
  2018. if (looks_like_a_consensus_diff(body, body_len)) {
  2019. /* First find our previous consensus. Maybe it's in ram, maybe not. */
  2020. cached_dir_t *cd = dirserv_get_consensus(flavname);
  2021. const char *consensus_body;
  2022. char *owned_consensus = NULL;
  2023. if (cd) {
  2024. consensus_body = cd->dir;
  2025. } else {
  2026. owned_consensus = networkstatus_read_cached_consensus(flavname);
  2027. consensus_body = owned_consensus;
  2028. }
  2029. if (!consensus_body) {
  2030. log_warn(LD_DIR, "Received a consensus diff, but we can't find "
  2031. "any %s-flavored consensus in our current cache.",flavname);
  2032. networkstatus_consensus_download_failed(0, flavname);
  2033. // XXXX if this happens too much, see below
  2034. return -1;
  2035. }
  2036. new_consensus = consensus_diff_apply(consensus_body, body);
  2037. tor_free(owned_consensus);
  2038. if (new_consensus == NULL) {
  2039. log_warn(LD_DIR, "Could not apply consensus diff received from server "
  2040. "'%s:%d'", conn->base_.address, conn->base_.port);
  2041. // XXXX If this happens too many times, we should maybe not use
  2042. // XXXX this directory for diffs any more?
  2043. networkstatus_consensus_download_failed(0, flavname);
  2044. return -1;
  2045. }
  2046. log_info(LD_DIR, "Applied consensus diff (size %d) from server "
  2047. "'%s:%d', resulting in a new consensus document (size %d).",
  2048. (int)body_len, conn->base_.address, conn->base_.port,
  2049. (int)strlen(new_consensus));
  2050. consensus = new_consensus;
  2051. sourcename = "generated based on a diff";
  2052. } else {
  2053. log_info(LD_DIR,"Received consensus directory (body size %d) from server "
  2054. "'%s:%d'", (int)body_len, conn->base_.address, conn->base_.port);
  2055. consensus = body;
  2056. sourcename = "downloaded";
  2057. }
  2058. if ((r=networkstatus_set_current_consensus(consensus, flavname, 0,
  2059. conn->identity_digest))<0) {
  2060. log_fn(r<-1?LOG_WARN:LOG_INFO, LD_DIR,
  2061. "Unable to load %s consensus directory %s from "
  2062. "server '%s:%d'. I'll try again soon.",
  2063. flavname, sourcename, conn->base_.address, conn->base_.port);
  2064. networkstatus_consensus_download_failed(0, flavname);
  2065. tor_free(new_consensus);
  2066. return -1;
  2067. }
  2068. /* If we launched other fetches for this consensus, cancel them. */
  2069. connection_dir_close_consensus_fetches(conn, flavname);
  2070. /* update the list of routers and directory guards */
  2071. routers_update_all_from_networkstatus(now, 3);
  2072. update_microdescs_from_networkstatus(now);
  2073. directory_info_has_arrived(now, 0, 0);
  2074. if (authdir_mode_v3(get_options())) {
  2075. sr_act_post_consensus(
  2076. networkstatus_get_latest_consensus_by_flavor(FLAV_NS));
  2077. }
  2078. log_info(LD_DIR, "Successfully loaded consensus.");
  2079. tor_free(new_consensus);
  2080. return 0;
  2081. }
  2082. /**
  2083. * Handler function: processes a response to a request for one or more
  2084. * authority certificates
  2085. **/
  2086. static int
  2087. handle_response_fetch_certificate(dir_connection_t *conn,
  2088. const response_handler_args_t *args)
  2089. {
  2090. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE);
  2091. const int status_code = args->status_code;
  2092. const char *reason = args->reason;
  2093. const char *body = args->body;
  2094. const size_t body_len = args->body_len;
  2095. if (status_code != 200) {
  2096. log_warn(LD_DIR,
  2097. "Received http status code %d (%s) from server "
  2098. "'%s:%d' while fetching \"/tor/keys/%s\".",
  2099. status_code, escaped(reason), conn->base_.address,
  2100. conn->base_.port, conn->requested_resource);
  2101. connection_dir_download_cert_failed(conn, status_code);
  2102. return -1;
  2103. }
  2104. log_info(LD_DIR,"Received authority certificates (body size %d) from "
  2105. "server '%s:%d'",
  2106. (int)body_len, conn->base_.address, conn->base_.port);
  2107. /*
  2108. * Tell trusted_dirs_load_certs_from_string() whether it was by fp
  2109. * or fp-sk pair.
  2110. */
  2111. int src_code = -1;
  2112. if (!strcmpstart(conn->requested_resource, "fp/")) {
  2113. src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST;
  2114. } else if (!strcmpstart(conn->requested_resource, "fp-sk/")) {
  2115. src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST;
  2116. }
  2117. if (src_code != -1) {
  2118. if (trusted_dirs_load_certs_from_string(body, src_code, 1,
  2119. conn->identity_digest)<0) {
  2120. log_warn(LD_DIR, "Unable to parse fetched certificates");
  2121. /* if we fetched more than one and only some failed, the successful
  2122. * ones got flushed to disk so it's safe to call this on them */
  2123. connection_dir_download_cert_failed(conn, status_code);
  2124. } else {
  2125. time_t now = approx_time();
  2126. directory_info_has_arrived(now, 0, 0);
  2127. log_info(LD_DIR, "Successfully loaded certificates from fetch.");
  2128. }
  2129. } else {
  2130. log_warn(LD_DIR,
  2131. "Couldn't figure out what to do with fetched certificates for "
  2132. "unknown resource %s",
  2133. conn->requested_resource);
  2134. connection_dir_download_cert_failed(conn, status_code);
  2135. }
  2136. return 0;
  2137. }
  2138. /**
  2139. * Handler function: processes a response to a request for an authority's
  2140. * current networkstatus vote.
  2141. **/
  2142. static int
  2143. handle_response_fetch_status_vote(dir_connection_t *conn,
  2144. const response_handler_args_t *args)
  2145. {
  2146. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE);
  2147. const int status_code = args->status_code;
  2148. const char *reason = args->reason;
  2149. const char *body = args->body;
  2150. const size_t body_len = args->body_len;
  2151. const char *msg;
  2152. int st;
  2153. log_info(LD_DIR,"Got votes (body size %d) from server %s:%d",
  2154. (int)body_len, conn->base_.address, conn->base_.port);
  2155. if (status_code != 200) {
  2156. log_warn(LD_DIR,
  2157. "Received http status code %d (%s) from server "
  2158. "'%s:%d' while fetching \"/tor/status-vote/next/%s.z\".",
  2159. status_code, escaped(reason), conn->base_.address,
  2160. conn->base_.port, conn->requested_resource);
  2161. return -1;
  2162. }
  2163. dirvote_add_vote(body, &msg, &st);
  2164. if (st > 299) {
  2165. log_warn(LD_DIR, "Error adding retrieved vote: %s", msg);
  2166. } else {
  2167. log_info(LD_DIR, "Added vote(s) successfully [msg: %s]", msg);
  2168. }
  2169. return 0;
  2170. }
  2171. /**
  2172. * Handler function: processes a response to a request for the signatures
  2173. * that an authority knows about on a given consensus.
  2174. **/
  2175. static int
  2176. handle_response_fetch_detached_signatures(dir_connection_t *conn,
  2177. const response_handler_args_t *args)
  2178. {
  2179. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES);
  2180. const int status_code = args->status_code;
  2181. const char *reason = args->reason;
  2182. const char *body = args->body;
  2183. const size_t body_len = args->body_len;
  2184. const char *msg = NULL;
  2185. log_info(LD_DIR,"Got detached signatures (body size %d) from server %s:%d",
  2186. (int)body_len, conn->base_.address, conn->base_.port);
  2187. if (status_code != 200) {
  2188. log_warn(LD_DIR,
  2189. "Received http status code %d (%s) from server '%s:%d' while fetching "
  2190. "\"/tor/status-vote/next/consensus-signatures.z\".",
  2191. status_code, escaped(reason), conn->base_.address,
  2192. conn->base_.port);
  2193. return -1;
  2194. }
  2195. if (dirvote_add_signatures(body, conn->base_.address, &msg)<0) {
  2196. log_warn(LD_DIR, "Problem adding detached signatures from %s:%d: %s",
  2197. conn->base_.address, conn->base_.port, msg?msg:"???");
  2198. }
  2199. return 0;
  2200. }
  2201. /**
  2202. * Handler function: processes a response to a request for a group of server
  2203. * descriptors or an extrainfo documents.
  2204. **/
  2205. static int
  2206. handle_response_fetch_desc(dir_connection_t *conn,
  2207. const response_handler_args_t *args)
  2208. {
  2209. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  2210. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO);
  2211. const int status_code = args->status_code;
  2212. const char *reason = args->reason;
  2213. const char *body = args->body;
  2214. const size_t body_len = args->body_len;
  2215. int was_ei = conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO;
  2216. smartlist_t *which = NULL;
  2217. int n_asked_for = 0;
  2218. int descriptor_digests = conn->requested_resource &&
  2219. !strcmpstart(conn->requested_resource,"d/");
  2220. log_info(LD_DIR,"Received %s (body size %d) from server '%s:%d'",
  2221. was_ei ? "extra server info" : "server info",
  2222. (int)body_len, conn->base_.address, conn->base_.port);
  2223. if (conn->requested_resource &&
  2224. (!strcmpstart(conn->requested_resource,"d/") ||
  2225. !strcmpstart(conn->requested_resource,"fp/"))) {
  2226. which = smartlist_new();
  2227. dir_split_resource_into_fingerprints(conn->requested_resource +
  2228. (descriptor_digests ? 2 : 3),
  2229. which, NULL, 0);
  2230. n_asked_for = smartlist_len(which);
  2231. }
  2232. if (status_code != 200) {
  2233. int dir_okay = status_code == 404 ||
  2234. (status_code == 400 && !strcmp(reason, "Servers unavailable."));
  2235. /* 404 means that it didn't have them; no big deal.
  2236. * Older (pre-0.1.1.8) servers said 400 Servers unavailable instead. */
  2237. log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
  2238. "Received http status code %d (%s) from server '%s:%d' "
  2239. "while fetching \"/tor/server/%s\". I'll try again soon.",
  2240. status_code, escaped(reason), conn->base_.address,
  2241. conn->base_.port, conn->requested_resource);
  2242. if (!which) {
  2243. connection_dir_download_routerdesc_failed(conn);
  2244. } else {
  2245. dir_routerdesc_download_failed(which, status_code,
  2246. conn->router_purpose,
  2247. was_ei, descriptor_digests);
  2248. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2249. smartlist_free(which);
  2250. }
  2251. return dir_okay ? 0 : -1;
  2252. }
  2253. /* Learn the routers, assuming we requested by fingerprint or "all"
  2254. * or "authority".
  2255. *
  2256. * We use "authority" to fetch our own descriptor for
  2257. * testing, and to fetch bridge descriptors for bootstrapping. Ignore
  2258. * the output of "authority" requests unless we are using bridges,
  2259. * since otherwise they'll be the response from reachability tests,
  2260. * and we don't really want to add that to our routerlist. */
  2261. if (which || (conn->requested_resource &&
  2262. (!strcmpstart(conn->requested_resource, "all") ||
  2263. (!strcmpstart(conn->requested_resource, "authority") &&
  2264. get_options()->UseBridges)))) {
  2265. /* as we learn from them, we remove them from 'which' */
  2266. if (was_ei) {
  2267. router_load_extrainfo_from_string(body, NULL, SAVED_NOWHERE, which,
  2268. descriptor_digests);
  2269. } else {
  2270. //router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  2271. // descriptor_digests, conn->router_purpose);
  2272. if (load_downloaded_routers(body, which, descriptor_digests,
  2273. conn->router_purpose,
  2274. conn->base_.address)) {
  2275. time_t now = approx_time();
  2276. directory_info_has_arrived(now, 0, 1);
  2277. }
  2278. }
  2279. }
  2280. if (which) { /* mark remaining ones as failed */
  2281. log_info(LD_DIR, "Received %d/%d %s requested from %s:%d",
  2282. n_asked_for-smartlist_len(which), n_asked_for,
  2283. was_ei ? "extra-info documents" : "router descriptors",
  2284. conn->base_.address, (int)conn->base_.port);
  2285. if (smartlist_len(which)) {
  2286. dir_routerdesc_download_failed(which, status_code,
  2287. conn->router_purpose,
  2288. was_ei, descriptor_digests);
  2289. }
  2290. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2291. smartlist_free(which);
  2292. }
  2293. if (directory_conn_is_self_reachability_test(conn))
  2294. router_dirport_found_reachable();
  2295. return 0;
  2296. }
  2297. /**
  2298. * Handler function: processes a response to a request for a group of
  2299. * microdescriptors
  2300. **/
  2301. STATIC int
  2302. handle_response_fetch_microdesc(dir_connection_t *conn,
  2303. const response_handler_args_t *args)
  2304. {
  2305. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  2306. const int status_code = args->status_code;
  2307. const char *reason = args->reason;
  2308. const char *body = args->body;
  2309. const size_t body_len = args->body_len;
  2310. smartlist_t *which = NULL;
  2311. log_info(LD_DIR,"Received answer to microdescriptor request (status %d, "
  2312. "body size %d) from server '%s:%d'",
  2313. status_code, (int)body_len, conn->base_.address,
  2314. conn->base_.port);
  2315. tor_assert(conn->requested_resource &&
  2316. !strcmpstart(conn->requested_resource, "d/"));
  2317. tor_assert_nonfatal(!tor_mem_is_zero(conn->identity_digest, DIGEST_LEN));
  2318. which = smartlist_new();
  2319. dir_split_resource_into_fingerprints(conn->requested_resource+2,
  2320. which, NULL,
  2321. DSR_DIGEST256|DSR_BASE64);
  2322. if (status_code != 200) {
  2323. log_info(LD_DIR, "Received status code %d (%s) from server "
  2324. "'%s:%d' while fetching \"/tor/micro/%s\". I'll try again "
  2325. "soon.",
  2326. status_code, escaped(reason), conn->base_.address,
  2327. (int)conn->base_.port, conn->requested_resource);
  2328. dir_microdesc_download_failed(which, status_code, conn->identity_digest);
  2329. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2330. smartlist_free(which);
  2331. return 0;
  2332. } else {
  2333. smartlist_t *mds;
  2334. time_t now = approx_time();
  2335. mds = microdescs_add_to_cache(get_microdesc_cache(),
  2336. body, body+body_len, SAVED_NOWHERE, 0,
  2337. now, which);
  2338. if (smartlist_len(which)) {
  2339. /* Mark remaining ones as failed. */
  2340. dir_microdesc_download_failed(which, status_code, conn->identity_digest);
  2341. }
  2342. if (mds && smartlist_len(mds)) {
  2343. control_event_boot_dir(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  2344. count_loading_descriptors_progress());
  2345. directory_info_has_arrived(now, 0, 1);
  2346. }
  2347. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  2348. smartlist_free(which);
  2349. smartlist_free(mds);
  2350. }
  2351. return 0;
  2352. }
  2353. /**
  2354. * Handler function: processes a response to a POST request to upload our
  2355. * router descriptor.
  2356. **/
  2357. static int
  2358. handle_response_upload_dir(dir_connection_t *conn,
  2359. const response_handler_args_t *args)
  2360. {
  2361. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_DIR);
  2362. const int status_code = args->status_code;
  2363. const char *reason = args->reason;
  2364. const char *headers = args->headers;
  2365. switch (status_code) {
  2366. case 200: {
  2367. dir_server_t *ds =
  2368. router_get_trusteddirserver_by_digest(conn->identity_digest);
  2369. char *rejected_hdr = http_get_header(headers,
  2370. "X-Descriptor-Not-New: ");
  2371. if (rejected_hdr) {
  2372. if (!strcmp(rejected_hdr, "Yes")) {
  2373. log_info(LD_GENERAL,
  2374. "Authority '%s' declined our descriptor (not new)",
  2375. ds->nickname);
  2376. /* XXXX use this information; be sure to upload next one
  2377. * sooner. -NM */
  2378. /* XXXX++ On further thought, the task above implies that we're
  2379. * basing our regenerate-descriptor time on when we uploaded the
  2380. * last descriptor, not on the published time of the last
  2381. * descriptor. If those are different, that's a bad thing to
  2382. * do. -NM */
  2383. }
  2384. tor_free(rejected_hdr);
  2385. }
  2386. log_info(LD_GENERAL,"eof (status 200) after uploading server "
  2387. "descriptor: finished.");
  2388. control_event_server_status(
  2389. LOG_NOTICE, "ACCEPTED_SERVER_DESCRIPTOR DIRAUTH=%s:%d",
  2390. conn->base_.address, conn->base_.port);
  2391. ds->has_accepted_serverdesc = 1;
  2392. if (directories_have_accepted_server_descriptor())
  2393. control_event_server_status(LOG_NOTICE, "GOOD_SERVER_DESCRIPTOR");
  2394. }
  2395. break;
  2396. case 400:
  2397. log_warn(LD_GENERAL,"http status 400 (%s) response from "
  2398. "dirserver '%s:%d'. Please correct.",
  2399. escaped(reason), conn->base_.address, conn->base_.port);
  2400. control_event_server_status(LOG_WARN,
  2401. "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
  2402. conn->base_.address, conn->base_.port, escaped(reason));
  2403. break;
  2404. default:
  2405. log_warn(LD_GENERAL,
  2406. "HTTP status %d (%s) was unexpected while uploading "
  2407. "descriptor to server '%s:%d'. Possibly the server is "
  2408. "misconfigured?",
  2409. status_code, escaped(reason), conn->base_.address,
  2410. conn->base_.port);
  2411. break;
  2412. }
  2413. /* return 0 in all cases, since we don't want to mark any
  2414. * dirservers down just because they don't like us. */
  2415. return 0;
  2416. }
  2417. /**
  2418. * Handler function: processes a response to POST request to upload our
  2419. * own networkstatus vote.
  2420. **/
  2421. static int
  2422. handle_response_upload_vote(dir_connection_t *conn,
  2423. const response_handler_args_t *args)
  2424. {
  2425. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_VOTE);
  2426. const int status_code = args->status_code;
  2427. const char *reason = args->reason;
  2428. switch (status_code) {
  2429. case 200: {
  2430. log_notice(LD_DIR,"Uploaded a vote to dirserver %s:%d",
  2431. conn->base_.address, conn->base_.port);
  2432. }
  2433. break;
  2434. case 400:
  2435. log_warn(LD_DIR,"http status 400 (%s) response after uploading "
  2436. "vote to dirserver '%s:%d'. Please correct.",
  2437. escaped(reason), conn->base_.address, conn->base_.port);
  2438. break;
  2439. default:
  2440. log_warn(LD_GENERAL,
  2441. "HTTP status %d (%s) was unexpected while uploading "
  2442. "vote to server '%s:%d'.",
  2443. status_code, escaped(reason), conn->base_.address,
  2444. conn->base_.port);
  2445. break;
  2446. }
  2447. /* return 0 in all cases, since we don't want to mark any
  2448. * dirservers down just because they don't like us. */
  2449. return 0;
  2450. }
  2451. /**
  2452. * Handler function: processes a response to POST request to upload our
  2453. * view of the signatures on the current consensus.
  2454. **/
  2455. static int
  2456. handle_response_upload_signatures(dir_connection_t *conn,
  2457. const response_handler_args_t *args)
  2458. {
  2459. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_SIGNATURES);
  2460. const int status_code = args->status_code;
  2461. const char *reason = args->reason;
  2462. switch (status_code) {
  2463. case 200: {
  2464. log_notice(LD_DIR,"Uploaded signature(s) to dirserver %s:%d",
  2465. conn->base_.address, conn->base_.port);
  2466. }
  2467. break;
  2468. case 400:
  2469. log_warn(LD_DIR,"http status 400 (%s) response after uploading "
  2470. "signatures to dirserver '%s:%d'. Please correct.",
  2471. escaped(reason), conn->base_.address, conn->base_.port);
  2472. break;
  2473. default:
  2474. log_warn(LD_GENERAL,
  2475. "HTTP status %d (%s) was unexpected while uploading "
  2476. "signatures to server '%s:%d'.",
  2477. status_code, escaped(reason), conn->base_.address,
  2478. conn->base_.port);
  2479. break;
  2480. }
  2481. /* return 0 in all cases, since we don't want to mark any
  2482. * dirservers down just because they don't like us. */
  2483. return 0;
  2484. }
  2485. /**
  2486. * Handler function: processes a response to a request for a v3 hidden service
  2487. * descriptor.
  2488. **/
  2489. STATIC int
  2490. handle_response_fetch_hsdesc_v3(dir_connection_t *conn,
  2491. const response_handler_args_t *args)
  2492. {
  2493. const int status_code = args->status_code;
  2494. const char *reason = args->reason;
  2495. const char *body = args->body;
  2496. const size_t body_len = args->body_len;
  2497. tor_assert(conn->hs_ident);
  2498. log_info(LD_REND,"Received v3 hsdesc (body size %d, status %d (%s))",
  2499. (int)body_len, status_code, escaped(reason));
  2500. switch (status_code) {
  2501. case 200:
  2502. /* We got something: Try storing it in the cache. */
  2503. if (hs_cache_store_as_client(body, &conn->hs_ident->identity_pk) < 0) {
  2504. log_warn(LD_REND, "Failed to store hidden service descriptor");
  2505. /* Fire control port FAILED event. */
  2506. hs_control_desc_event_failed(conn->hs_ident, conn->identity_digest,
  2507. "BAD_DESC");
  2508. hs_control_desc_event_content(conn->hs_ident, conn->identity_digest,
  2509. NULL);
  2510. } else {
  2511. log_info(LD_REND, "Stored hidden service descriptor successfully.");
  2512. TO_CONN(conn)->purpose = DIR_PURPOSE_HAS_FETCHED_HSDESC;
  2513. hs_client_desc_has_arrived(conn->hs_ident);
  2514. /* Fire control port RECEIVED event. */
  2515. hs_control_desc_event_received(conn->hs_ident, conn->identity_digest);
  2516. hs_control_desc_event_content(conn->hs_ident, conn->identity_digest,
  2517. body);
  2518. }
  2519. break;
  2520. case 404:
  2521. /* Not there. We'll retry when connection_about_to_close_connection()
  2522. * tries to clean this conn up. */
  2523. log_info(LD_REND, "Fetching hidden service v3 descriptor not found: "
  2524. "Retrying at another directory.");
  2525. /* Fire control port FAILED event. */
  2526. hs_control_desc_event_failed(conn->hs_ident, conn->identity_digest,
  2527. "NOT_FOUND");
  2528. hs_control_desc_event_content(conn->hs_ident, conn->identity_digest,
  2529. NULL);
  2530. break;
  2531. case 400:
  2532. log_warn(LD_REND, "Fetching v3 hidden service descriptor failed: "
  2533. "http status 400 (%s). Dirserver didn't like our "
  2534. "query? Retrying at another directory.",
  2535. escaped(reason));
  2536. /* Fire control port FAILED event. */
  2537. hs_control_desc_event_failed(conn->hs_ident, conn->identity_digest,
  2538. "QUERY_REJECTED");
  2539. hs_control_desc_event_content(conn->hs_ident, conn->identity_digest,
  2540. NULL);
  2541. break;
  2542. default:
  2543. log_warn(LD_REND, "Fetching v3 hidden service descriptor failed: "
  2544. "http status %d (%s) response unexpected from HSDir server "
  2545. "'%s:%d'. Retrying at another directory.",
  2546. status_code, escaped(reason), TO_CONN(conn)->address,
  2547. TO_CONN(conn)->port);
  2548. /* Fire control port FAILED event. */
  2549. hs_control_desc_event_failed(conn->hs_ident, conn->identity_digest,
  2550. "UNEXPECTED");
  2551. hs_control_desc_event_content(conn->hs_ident, conn->identity_digest,
  2552. NULL);
  2553. break;
  2554. }
  2555. return 0;
  2556. }
  2557. /**
  2558. * Handler function: processes a response to a request for a v2 hidden service
  2559. * descriptor.
  2560. **/
  2561. static int
  2562. handle_response_fetch_renddesc_v2(dir_connection_t *conn,
  2563. const response_handler_args_t *args)
  2564. {
  2565. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_RENDDESC_V2);
  2566. const int status_code = args->status_code;
  2567. const char *reason = args->reason;
  2568. const char *body = args->body;
  2569. const size_t body_len = args->body_len;
  2570. #define SEND_HS_DESC_FAILED_EVENT(reason) \
  2571. (control_event_hsv2_descriptor_failed(conn->rend_data, \
  2572. conn->identity_digest, \
  2573. reason))
  2574. #define SEND_HS_DESC_FAILED_CONTENT() \
  2575. (control_event_hs_descriptor_content( \
  2576. rend_data_get_address(conn->rend_data), \
  2577. conn->requested_resource, \
  2578. conn->identity_digest, \
  2579. NULL))
  2580. tor_assert(conn->rend_data);
  2581. log_info(LD_REND,"Received rendezvous descriptor (body size %d, status %d "
  2582. "(%s))",
  2583. (int)body_len, status_code, escaped(reason));
  2584. switch (status_code) {
  2585. case 200:
  2586. {
  2587. rend_cache_entry_t *entry = NULL;
  2588. if (rend_cache_store_v2_desc_as_client(body,
  2589. conn->requested_resource,
  2590. conn->rend_data, &entry) < 0) {
  2591. log_warn(LD_REND,"Fetching v2 rendezvous descriptor failed. "
  2592. "Retrying at another directory.");
  2593. /* We'll retry when connection_about_to_close_connection()
  2594. * cleans this dir conn up. */
  2595. SEND_HS_DESC_FAILED_EVENT("BAD_DESC");
  2596. SEND_HS_DESC_FAILED_CONTENT();
  2597. } else {
  2598. char service_id[REND_SERVICE_ID_LEN_BASE32 + 1];
  2599. /* Should never be NULL here if we found the descriptor. */
  2600. tor_assert(entry);
  2601. rend_get_service_id(entry->parsed->pk, service_id);
  2602. /* success. notify pending connections about this. */
  2603. log_info(LD_REND, "Successfully fetched v2 rendezvous "
  2604. "descriptor.");
  2605. control_event_hsv2_descriptor_received(service_id,
  2606. conn->rend_data,
  2607. conn->identity_digest);
  2608. control_event_hs_descriptor_content(service_id,
  2609. conn->requested_resource,
  2610. conn->identity_digest,
  2611. body);
  2612. conn->base_.purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2;
  2613. rend_client_desc_trynow(service_id);
  2614. memwipe(service_id, 0, sizeof(service_id));
  2615. }
  2616. break;
  2617. }
  2618. case 404:
  2619. /* Not there. We'll retry when
  2620. * connection_about_to_close_connection() cleans this conn up. */
  2621. log_info(LD_REND,"Fetching v2 rendezvous descriptor failed: "
  2622. "Retrying at another directory.");
  2623. SEND_HS_DESC_FAILED_EVENT("NOT_FOUND");
  2624. SEND_HS_DESC_FAILED_CONTENT();
  2625. break;
  2626. case 400:
  2627. log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
  2628. "http status 400 (%s). Dirserver didn't like our "
  2629. "v2 rendezvous query? Retrying at another directory.",
  2630. escaped(reason));
  2631. SEND_HS_DESC_FAILED_EVENT("QUERY_REJECTED");
  2632. SEND_HS_DESC_FAILED_CONTENT();
  2633. break;
  2634. default:
  2635. log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
  2636. "http status %d (%s) response unexpected while "
  2637. "fetching v2 hidden service descriptor (server '%s:%d'). "
  2638. "Retrying at another directory.",
  2639. status_code, escaped(reason), conn->base_.address,
  2640. conn->base_.port);
  2641. SEND_HS_DESC_FAILED_EVENT("UNEXPECTED");
  2642. SEND_HS_DESC_FAILED_CONTENT();
  2643. break;
  2644. }
  2645. return 0;
  2646. }
  2647. /**
  2648. * Handler function: processes a response to a POST request to upload a v2
  2649. * hidden service descriptor.
  2650. **/
  2651. static int
  2652. handle_response_upload_renddesc_v2(dir_connection_t *conn,
  2653. const response_handler_args_t *args)
  2654. {
  2655. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2);
  2656. const int status_code = args->status_code;
  2657. const char *reason = args->reason;
  2658. #define SEND_HS_DESC_UPLOAD_FAILED_EVENT(reason) \
  2659. (control_event_hs_descriptor_upload_failed( \
  2660. conn->identity_digest, \
  2661. rend_data_get_address(conn->rend_data), \
  2662. reason))
  2663. log_info(LD_REND,"Uploaded rendezvous descriptor (status %d "
  2664. "(%s))",
  2665. status_code, escaped(reason));
  2666. /* Without the rend data, we'll have a problem identifying what has been
  2667. * uploaded for which service. */
  2668. tor_assert(conn->rend_data);
  2669. switch (status_code) {
  2670. case 200:
  2671. log_info(LD_REND,
  2672. "Uploading rendezvous descriptor: finished with status "
  2673. "200 (%s)", escaped(reason));
  2674. control_event_hs_descriptor_uploaded(conn->identity_digest,
  2675. rend_data_get_address(conn->rend_data));
  2676. rend_service_desc_has_uploaded(conn->rend_data);
  2677. break;
  2678. case 400:
  2679. log_warn(LD_REND,"http status 400 (%s) response from dirserver "
  2680. "'%s:%d'. Malformed rendezvous descriptor?",
  2681. escaped(reason), conn->base_.address, conn->base_.port);
  2682. SEND_HS_DESC_UPLOAD_FAILED_EVENT("UPLOAD_REJECTED");
  2683. break;
  2684. default:
  2685. log_warn(LD_REND,"http status %d (%s) response unexpected (server "
  2686. "'%s:%d').",
  2687. status_code, escaped(reason), conn->base_.address,
  2688. conn->base_.port);
  2689. SEND_HS_DESC_UPLOAD_FAILED_EVENT("UNEXPECTED");
  2690. break;
  2691. }
  2692. return 0;
  2693. }
  2694. /**
  2695. * Handler function: processes a response to a POST request to upload an
  2696. * hidden service descriptor.
  2697. **/
  2698. static int
  2699. handle_response_upload_hsdesc(dir_connection_t *conn,
  2700. const response_handler_args_t *args)
  2701. {
  2702. const int status_code = args->status_code;
  2703. const char *reason = args->reason;
  2704. tor_assert(conn);
  2705. tor_assert(conn->base_.purpose == DIR_PURPOSE_UPLOAD_HSDESC);
  2706. log_info(LD_REND, "Uploaded hidden service descriptor (status %d "
  2707. "(%s))",
  2708. status_code, escaped(reason));
  2709. /* For this directory response, it MUST have an hidden service identifier on
  2710. * this connection. */
  2711. tor_assert(conn->hs_ident);
  2712. switch (status_code) {
  2713. case 200:
  2714. log_info(LD_REND, "Uploading hidden service descriptor: "
  2715. "finished with status 200 (%s)", escaped(reason));
  2716. hs_control_desc_event_uploaded(conn->hs_ident, conn->identity_digest);
  2717. break;
  2718. case 400:
  2719. log_fn(LOG_PROTOCOL_WARN, LD_REND,
  2720. "Uploading hidden service descriptor: http "
  2721. "status 400 (%s) response from dirserver "
  2722. "'%s:%d'. Malformed hidden service descriptor?",
  2723. escaped(reason), conn->base_.address, conn->base_.port);
  2724. hs_control_desc_event_failed(conn->hs_ident, conn->identity_digest,
  2725. "UPLOAD_REJECTED");
  2726. break;
  2727. default:
  2728. log_warn(LD_REND, "Uploading hidden service descriptor: http "
  2729. "status %d (%s) response unexpected (server "
  2730. "'%s:%d').",
  2731. status_code, escaped(reason), conn->base_.address,
  2732. conn->base_.port);
  2733. hs_control_desc_event_failed(conn->hs_ident, conn->identity_digest,
  2734. "UNEXPECTED");
  2735. break;
  2736. }
  2737. return 0;
  2738. }
  2739. /** Called when a directory connection reaches EOF. */
  2740. int
  2741. connection_dir_reached_eof(dir_connection_t *conn)
  2742. {
  2743. int retval;
  2744. if (conn->base_.state != DIR_CONN_STATE_CLIENT_READING) {
  2745. log_info(LD_HTTP,"conn reached eof, not reading. [state=%d] Closing.",
  2746. conn->base_.state);
  2747. connection_close_immediate(TO_CONN(conn)); /* error: give up on flushing */
  2748. connection_mark_for_close(TO_CONN(conn));
  2749. return -1;
  2750. }
  2751. retval = connection_dir_client_reached_eof(conn);
  2752. if (retval == 0) /* success */
  2753. conn->base_.state = DIR_CONN_STATE_CLIENT_FINISHED;
  2754. connection_mark_for_close(TO_CONN(conn));
  2755. return retval;
  2756. }
  2757. /** We are closing a dir connection: If <b>dir_conn</b> is a dir connection
  2758. * that tried to fetch an HS descriptor, check if it successfully fetched it,
  2759. * or if we need to try again. */
  2760. void
  2761. connection_dir_client_refetch_hsdesc_if_needed(dir_connection_t *dir_conn)
  2762. {
  2763. connection_t *conn = TO_CONN(dir_conn);
  2764. /* If we were trying to fetch a v2 rend desc and did not succeed, retry as
  2765. * needed. (If a fetch is successful, the connection state is changed to
  2766. * DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2 or DIR_PURPOSE_HAS_FETCHED_HSDESC to
  2767. * mark that refetching is unnecessary.) */
  2768. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 &&
  2769. dir_conn->rend_data &&
  2770. rend_valid_v2_service_id(
  2771. rend_data_get_address(dir_conn->rend_data))) {
  2772. rend_client_refetch_v2_renddesc(dir_conn->rend_data);
  2773. }
  2774. /* Check for v3 rend desc fetch */
  2775. if (conn->purpose == DIR_PURPOSE_FETCH_HSDESC &&
  2776. dir_conn->hs_ident &&
  2777. !ed25519_public_key_is_zero(&dir_conn->hs_ident->identity_pk)) {
  2778. hs_client_refetch_hsdesc(&dir_conn->hs_ident->identity_pk);
  2779. }
  2780. }
  2781. /** Array of compression methods to use (if supported) for requesting
  2782. * compressed data, ordered from best to worst. */
  2783. static compress_method_t client_meth_pref[] = {
  2784. LZMA_METHOD,
  2785. ZSTD_METHOD,
  2786. ZLIB_METHOD,
  2787. GZIP_METHOD,
  2788. NO_METHOD
  2789. };
  2790. /** Array of allowed compression methods to use (if supported) when receiving a
  2791. * response from a request that was required to be anonymous. */
  2792. static compress_method_t client_meth_allowed_anonymous_compression[] = {
  2793. ZLIB_METHOD,
  2794. GZIP_METHOD,
  2795. NO_METHOD
  2796. };
  2797. /** Return a newly allocated string containing a comma separated list of
  2798. * supported encodings. */
  2799. STATIC char *
  2800. accept_encoding_header(void)
  2801. {
  2802. smartlist_t *methods = smartlist_new();
  2803. char *header = NULL;
  2804. compress_method_t method;
  2805. unsigned i;
  2806. for (i = 0; i < ARRAY_LENGTH(client_meth_pref); ++i) {
  2807. method = client_meth_pref[i];
  2808. if (tor_compress_supports_method(method))
  2809. smartlist_add(methods, (char *)compression_method_get_name(method));
  2810. }
  2811. header = smartlist_join_strings(methods, ", ", 0, NULL);
  2812. smartlist_free(methods);
  2813. return header;
  2814. }
  2815. /** Check if the given compression method is allowed for a connection that is
  2816. * supposed to be anonymous. Returns 1 if the compression method is allowed,
  2817. * otherwise 0. */
  2818. STATIC int
  2819. allowed_anonymous_connection_compression_method(compress_method_t method)
  2820. {
  2821. unsigned u;
  2822. for (u = 0; u < ARRAY_LENGTH(client_meth_allowed_anonymous_compression);
  2823. ++u) {
  2824. compress_method_t allowed_method =
  2825. client_meth_allowed_anonymous_compression[u];
  2826. if (! tor_compress_supports_method(allowed_method))
  2827. continue;
  2828. if (method == allowed_method)
  2829. return 1;
  2830. }
  2831. return 0;
  2832. }
  2833. /** Log a warning when a remote server has sent us a document using a
  2834. * compression method that is not allowed for anonymous directory requests. */
  2835. STATIC void
  2836. warn_disallowed_anonymous_compression_method(compress_method_t method)
  2837. {
  2838. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  2839. "Received a %s HTTP response, which is not "
  2840. "allowed for anonymous directory requests.",
  2841. compression_method_get_human_name(method));
  2842. }
  2843. /* We just got a new consensus! If there are other in-progress requests
  2844. * for this consensus flavor (for example because we launched several in
  2845. * parallel), cancel them.
  2846. *
  2847. * We do this check here (not just in
  2848. * connection_ap_handshake_attach_circuit()) to handle the edge case where
  2849. * a consensus fetch begins and ends before some other one tries to attach to
  2850. * a circuit, in which case the other one won't know that we're all happy now.
  2851. *
  2852. * Don't mark the conn that just gave us the consensus -- otherwise we
  2853. * would end up double-marking it when it cleans itself up.
  2854. */
  2855. static void
  2856. connection_dir_close_consensus_fetches(dir_connection_t *except_this_one,
  2857. const char *resource)
  2858. {
  2859. smartlist_t *conns_to_close =
  2860. connection_dir_list_by_purpose_and_resource(DIR_PURPOSE_FETCH_CONSENSUS,
  2861. resource);
  2862. SMARTLIST_FOREACH_BEGIN(conns_to_close, dir_connection_t *, d) {
  2863. if (d == except_this_one)
  2864. continue;
  2865. log_info(LD_DIR, "Closing consensus fetch (to %s) since one "
  2866. "has just arrived.", TO_CONN(d)->address);
  2867. connection_mark_for_close(TO_CONN(d));
  2868. } SMARTLIST_FOREACH_END(d);
  2869. smartlist_free(conns_to_close);
  2870. }
  2871. /** Called when one or more routerdesc (or extrainfo, if <b>was_extrainfo</b>)
  2872. * fetches have failed (with uppercase fingerprints listed in <b>failed</b>,
  2873. * either as descriptor digests or as identity digests based on
  2874. * <b>was_descriptor_digests</b>).
  2875. */
  2876. static void
  2877. dir_routerdesc_download_failed(smartlist_t *failed, int status_code,
  2878. int router_purpose,
  2879. int was_extrainfo, int was_descriptor_digests)
  2880. {
  2881. char digest[DIGEST_LEN];
  2882. time_t now = time(NULL);
  2883. int server = directory_fetches_from_authorities(get_options());
  2884. if (!was_descriptor_digests) {
  2885. if (router_purpose == ROUTER_PURPOSE_BRIDGE) {
  2886. tor_assert(!was_extrainfo);
  2887. connection_dir_retry_bridges(failed);
  2888. }
  2889. return; /* FFFF should implement for other-than-router-purpose someday */
  2890. }
  2891. SMARTLIST_FOREACH_BEGIN(failed, const char *, cp) {
  2892. download_status_t *dls = NULL;
  2893. if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) != DIGEST_LEN) {
  2894. log_warn(LD_BUG, "Malformed fingerprint in list: %s", escaped(cp));
  2895. continue;
  2896. }
  2897. if (was_extrainfo) {
  2898. signed_descriptor_t *sd =
  2899. router_get_by_extrainfo_digest(digest);
  2900. if (sd)
  2901. dls = &sd->ei_dl_status;
  2902. } else {
  2903. dls = router_get_dl_status_by_descriptor_digest(digest);
  2904. }
  2905. if (!dls)
  2906. continue;
  2907. download_status_increment_failure(dls, status_code, cp, server, now);
  2908. } SMARTLIST_FOREACH_END(cp);
  2909. /* No need to relaunch descriptor downloads here: we already do it
  2910. * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  2911. }
  2912. /** Called when a connection to download microdescriptors from relay with
  2913. * <b>dir_id</b> has failed in whole or in part. <b>failed</b> is a list
  2914. * of every microdesc digest we didn't get. <b>status_code</b> is the http
  2915. * status code we received. Reschedule the microdesc downloads as
  2916. * appropriate. */
  2917. static void
  2918. dir_microdesc_download_failed(smartlist_t *failed,
  2919. int status_code, const char *dir_id)
  2920. {
  2921. networkstatus_t *consensus
  2922. = networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
  2923. routerstatus_t *rs;
  2924. download_status_t *dls;
  2925. time_t now = time(NULL);
  2926. int server = directory_fetches_from_authorities(get_options());
  2927. if (! consensus)
  2928. return;
  2929. /* We failed to fetch a microdescriptor from 'dir_id', note it down
  2930. * so that we don't try the same relay next time... */
  2931. microdesc_note_outdated_dirserver(dir_id);
  2932. SMARTLIST_FOREACH_BEGIN(failed, const char *, d) {
  2933. rs = router_get_mutable_consensus_status_by_descriptor_digest(consensus,d);
  2934. if (!rs)
  2935. continue;
  2936. dls = &rs->dl_status;
  2937. { /* Increment the failure count for this md fetch */
  2938. char buf[BASE64_DIGEST256_LEN+1];
  2939. digest256_to_base64(buf, d);
  2940. log_info(LD_DIR, "Failed to download md %s from %s",
  2941. buf, hex_str(dir_id, DIGEST_LEN));
  2942. download_status_increment_failure(dls, status_code, buf,
  2943. server, now);
  2944. }
  2945. } SMARTLIST_FOREACH_END(d);
  2946. }