directory.c 136 KB

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