dirclient.c 122 KB

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