directory.c 137 KB

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