directory.c 132 KB

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