directory.c 144 KB

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