directory.c 132 KB

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