routerlist.c 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerlist_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file routerlist.c
  10. * \brief Code to
  11. * maintain and access the global list of routerinfos for known
  12. * servers.
  13. **/
  14. #include "or.h"
  15. // #define DEBUG_ROUTERLIST
  16. /****************************************************************************/
  17. /* static function prototypes */
  18. static routerstatus_t *router_pick_directory_server_impl(int requireother,
  19. int fascistfirewall,
  20. int prefer_tunnel,
  21. authority_type_t auth);
  22. static routerstatus_t *router_pick_trusteddirserver_impl(
  23. authority_type_t type, int requireother,
  24. int fascistfirewall, int prefer_tunnel);
  25. static void mark_all_trusteddirservers_up(void);
  26. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  27. static void trusted_dir_server_free(trusted_dir_server_t *ds);
  28. static void launch_router_descriptor_downloads(smartlist_t *downloadable,
  29. time_t now);
  30. static void update_consensus_router_descriptor_downloads(time_t now);
  31. static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
  32. static void update_router_have_minimum_dir_info(void);
  33. static const char *signed_descriptor_get_body_impl(signed_descriptor_t *desc,
  34. int with_annotations);
  35. static void list_pending_downloads(digestmap_t *result,
  36. int purpose, const char *prefix);
  37. DECLARE_TYPED_DIGESTMAP_FNS(sdmap_, digest_sd_map_t, signed_descriptor_t)
  38. DECLARE_TYPED_DIGESTMAP_FNS(rimap_, digest_ri_map_t, routerinfo_t)
  39. DECLARE_TYPED_DIGESTMAP_FNS(eimap_, digest_ei_map_t, extrainfo_t)
  40. /****************************************************************************/
  41. /** Global list of a trusted_dir_server_t object for each trusted directory
  42. * server. */
  43. static smartlist_t *trusted_dir_servers = NULL;
  44. /** True iff the key certificate in at least one member of
  45. * <b>trusted_dir_server_t</b> has changed since we last flushed the
  46. * certificates to disk. */
  47. static int trusted_dir_servers_certs_changed = 0;
  48. /** Global list of all of the routers that we know about. */
  49. static routerlist_t *routerlist = NULL;
  50. /** List of strings for nicknames we've already warned about and that are
  51. * still unknown / unavailable. */
  52. static smartlist_t *warned_nicknames = NULL;
  53. /** The last time we tried to download any routerdesc, or 0 for "never". We
  54. * use this to rate-limit download attempts when the number of routerdescs to
  55. * download is low. */
  56. static time_t last_routerdesc_download_attempted = 0;
  57. /** Return the number of directory authorities whose type matches some bit set
  58. * in <b>type</b> */
  59. int
  60. get_n_authorities(authority_type_t type)
  61. {
  62. int n = 0;
  63. if (!trusted_dir_servers)
  64. return 0;
  65. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  66. if (ds->type & type)
  67. ++n);
  68. return n;
  69. }
  70. #define get_n_v2_authorities() get_n_authorities(V2_AUTHORITY)
  71. /** Reload the cached v3 key certificates from the cached-certs file in
  72. * the data directory. Return 0 on success, -1 on failure. */
  73. int
  74. trusted_dirs_reload_certs(void)
  75. {
  76. char filename[512];
  77. char *contents;
  78. int r;
  79. tor_snprintf(filename,sizeof(filename),"%s"PATH_SEPARATOR"cached-certs",
  80. get_options()->DataDirectory);
  81. contents = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  82. if (!contents)
  83. return 0;
  84. r = trusted_dirs_load_certs_from_string(contents, 1);
  85. tor_free(contents);
  86. return r;
  87. }
  88. /** Load a bunch of new key certificates from the string <b>contents</b>. If
  89. * <b>from_store</b> is true, the certificates are from the cache, and we
  90. * don't need to flush them to disk. If <b>from_store</b> is false, we need
  91. * to flush any changed certificates to disk. Return 0 on success, -1 on
  92. * failure. */
  93. int
  94. trusted_dirs_load_certs_from_string(const char *contents, int from_store)
  95. {
  96. trusted_dir_server_t *ds;
  97. const char *s, *eos;
  98. for (s = contents; *s; s = eos) {
  99. authority_cert_t *cert = authority_cert_parse_from_string(s, &eos);
  100. int found = 0;
  101. if (!cert)
  102. break;
  103. ds = trusteddirserver_get_by_v3_auth_digest(
  104. cert->cache_info.identity_digest);
  105. if (!ds) {
  106. log_info(LD_DIR, "Found cached certificate whose key didn't match "
  107. "any v3 authority we recognized; skipping.");
  108. authority_cert_free(cert);
  109. continue;
  110. }
  111. if (!ds->v3_certs)
  112. ds->v3_certs = smartlist_create();
  113. SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, c,
  114. {
  115. if (!memcmp(c->cache_info.signed_descriptor_digest,
  116. cert->cache_info.signed_descriptor_digest,
  117. DIGEST_LEN)) {
  118. /* we already have this one. continue. */
  119. authority_cert_free(cert);
  120. found = 1;
  121. break;
  122. }
  123. });
  124. if (found)
  125. continue;
  126. cert->cache_info.signed_descriptor_body = tor_strndup(s, eos-s);
  127. cert->cache_info.signed_descriptor_len = eos-s;
  128. smartlist_add(ds->v3_certs, cert);
  129. if (!from_store)
  130. trusted_dir_servers_certs_changed = 1;
  131. }
  132. trusted_dirs_flush_certs_to_disk();
  133. networkstatus_note_certs_arrived();
  134. return 0;
  135. }
  136. /** Save all v3 key certifiacates to the cached-certs file. */
  137. void
  138. trusted_dirs_flush_certs_to_disk(void)
  139. {
  140. char filename[512];
  141. smartlist_t *chunks;
  142. if (!trusted_dir_servers_certs_changed)
  143. return;
  144. chunks = smartlist_create();
  145. tor_snprintf(filename,sizeof(filename),"%s"PATH_SEPARATOR"cached-certs",
  146. get_options()->DataDirectory);
  147. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  148. {
  149. if (ds->v3_certs) {
  150. SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
  151. {
  152. sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
  153. c->bytes = cert->cache_info.signed_descriptor_body;
  154. c->len = cert->cache_info.signed_descriptor_len;
  155. smartlist_add(chunks, c);
  156. });
  157. }
  158. });
  159. if (write_chunks_to_file(filename, chunks, 0)) {
  160. log_warn(LD_FS, "Error writing certificates to disk.");
  161. }
  162. SMARTLIST_FOREACH(chunks, sized_chunk_t *, c, tor_free(c));
  163. smartlist_free(chunks);
  164. trusted_dir_servers_certs_changed = 0;
  165. }
  166. /** Remove all v3 authority certificates that have been superseded for more
  167. * than 48 hours. (If the most recent cert was published more than 48 hours
  168. * ago, then we aren't going to get any consensuses signed with older
  169. * keys.) */
  170. static void
  171. trusted_dirs_remove_old_certs(void)
  172. {
  173. #define OLD_CERT_LIFETIME (48*60*60)
  174. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  175. {
  176. authority_cert_t *newest = NULL;
  177. if (!ds->v3_certs)
  178. continue;
  179. SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
  180. if (!newest || (cert->cache_info.published_on >
  181. newest->cache_info.published_on))
  182. newest = cert);
  183. SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
  184. if (newest && (newest->cache_info.published_on >
  185. cert->cache_info.published_on + OLD_CERT_LIFETIME)) {
  186. SMARTLIST_DEL_CURRENT(ds->v3_certs, cert);
  187. authority_cert_free(cert);
  188. trusted_dir_servers_certs_changed = 1;
  189. });
  190. });
  191. #undef OLD_CERT_LIFETIME
  192. trusted_dirs_flush_certs_to_disk();
  193. }
  194. /** Return the newest v3 authority certificate whose v3 authority identity key
  195. * has digest <b>id_digest</b>. Return NULL if no such authority is known,
  196. * or it has no certificate. */
  197. authority_cert_t *
  198. authority_cert_get_newest_by_id(const char *id_digest)
  199. {
  200. trusted_dir_server_t *ds = trusteddirserver_get_by_v3_auth_digest(id_digest);
  201. authority_cert_t *best = NULL;
  202. if (!ds || !ds->v3_certs)
  203. return NULL;
  204. SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
  205. {
  206. if (!best || cert->cache_info.published_on > best->cache_info.published_on)
  207. best = cert;
  208. });
  209. return best;
  210. }
  211. /** Return the newest v3 authority certificate whose directory signing key has
  212. * giest <sk_digest</b>. Return NULL if no such certificate is known.
  213. */
  214. authority_cert_t *
  215. authority_cert_get_by_sk_digest(const char *sk_digest)
  216. {
  217. if (!trusted_dir_servers)
  218. return NULL;
  219. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  220. {
  221. if (!ds->v3_certs)
  222. continue;
  223. SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
  224. {
  225. if (!memcmp(cert->signing_key_digest, sk_digest, DIGEST_LEN))
  226. return cert;
  227. });
  228. });
  229. return NULL;
  230. }
  231. /** Return the v3 authority certificate with signing key matching
  232. * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
  233. * Return NULL if no such authority is known. */
  234. authority_cert_t *
  235. authority_cert_get_by_digests(const char *id_digest,
  236. const char *sk_digest)
  237. {
  238. trusted_dir_server_t *ds = trusteddirserver_get_by_v3_auth_digest(id_digest);
  239. if (!ds || !ds->v3_certs)
  240. return NULL;
  241. SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
  242. if (!memcmp(cert->signing_key_digest, sk_digest, DIGEST_LEN))
  243. return cert; );
  244. return NULL;
  245. }
  246. /** How many times will we try to fetch a certificate before giving up? */
  247. #define MAX_CERT_DL_FAILURES 8
  248. /** Try to download any v3 authority certificates that we may be missing. If
  249. * <b>status</b> is provided, try to get all the ones that were used to sign
  250. * <b>status</b>. Additionally, try to have a non-expired certificate for
  251. * every V3 authority in trusted_dir_servers. Don't fetch certificates we
  252. * already have.
  253. **/
  254. void
  255. authority_certs_fetch_missing(networkstatus_vote_t *status, time_t now)
  256. {
  257. digestmap_t *pending = digestmap_new();
  258. smartlist_t *missing_digests = smartlist_create();
  259. char *resource = NULL;
  260. list_pending_downloads(pending, DIR_PURPOSE_FETCH_CERTIFICATE, "fp/");
  261. if (status) {
  262. SMARTLIST_FOREACH(status->voters, networkstatus_voter_info_t *, voter,
  263. {
  264. trusted_dir_server_t *ds
  265. = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
  266. if (!ds)
  267. continue;
  268. if (authority_cert_get_by_digests(voter->identity_digest,
  269. voter->signing_key_digest)) {
  270. download_status_reset(&ds->cert_dl_status);
  271. continue;
  272. }
  273. if (download_status_is_ready(&ds->cert_dl_status, now,
  274. MAX_CERT_DL_FAILURES))
  275. smartlist_add(missing_digests, voter->identity_digest);
  276. });
  277. }
  278. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  279. {
  280. int found = 0;
  281. if (!(ds->type & V3_AUTHORITY))
  282. continue;
  283. if (smartlist_digest_isin(missing_digests, ds->v3_identity_digest))
  284. continue;
  285. if (!ds->v3_certs)
  286. ds->v3_certs = smartlist_create();
  287. SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
  288. {
  289. if (!ftime_definitely_after(now, cert->expires)) {
  290. /* It's not expired, and we weren't looking for something to
  291. * verify a consensus with. Call it done. */
  292. download_status_reset(&ds->cert_dl_status);
  293. found = 1;
  294. break;
  295. }
  296. });
  297. if (!found && download_status_is_ready(&ds->cert_dl_status, now,
  298. MAX_CERT_DL_FAILURES))
  299. smartlist_add(missing_digests, ds->v3_identity_digest);
  300. });
  301. if (!smartlist_len(missing_digests)) {
  302. goto done;
  303. } else {
  304. smartlist_t *fps = smartlist_create();
  305. smartlist_add(fps, tor_strdup("fp/"));
  306. SMARTLIST_FOREACH(missing_digests, const char *, d, {
  307. char *fp;
  308. if (digestmap_get(pending, d))
  309. continue;
  310. fp = tor_malloc(HEX_DIGEST_LEN+2);
  311. base16_encode(fp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
  312. fp[HEX_DIGEST_LEN] = '+';
  313. fp[HEX_DIGEST_LEN+1] = '\0';
  314. smartlist_add(fps, fp);
  315. });
  316. resource = smartlist_join_strings(fps, "", 0, NULL);
  317. resource[strlen(resource)-1] = '\0';
  318. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  319. smartlist_free(fps);
  320. }
  321. log_notice(LD_DIR, "Launching request for %d missing certificates",
  322. smartlist_len(missing_digests));
  323. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
  324. resource, 1);
  325. done:
  326. tor_free(resource);
  327. smartlist_free(missing_digests);
  328. digestmap_free(pending, NULL);
  329. }
  330. /* Router descriptor storage.
  331. *
  332. * Routerdescs are stored in a big file, named "cached-descriptors". As new
  333. * routerdescs arrive, we append them to a journal file named
  334. * "cached-descriptors.new".
  335. *
  336. * From time to time, we replace "cached-descriptors" with a new file
  337. * containing only the live, non-superseded descriptors, and clear
  338. * cached-routers.new.
  339. *
  340. * On startup, we read both files.
  341. */
  342. /** Helper: return 1 iff the router log is so big we want to rebuild the
  343. * store. */
  344. static int
  345. router_should_rebuild_store(desc_store_t *store)
  346. {
  347. if (store->store_len > (1<<16))
  348. return (store->journal_len > store->store_len / 2 ||
  349. store->bytes_dropped > store->store_len / 2);
  350. else
  351. return store->journal_len > (1<<15);
  352. }
  353. static INLINE desc_store_t *
  354. desc_get_store(routerlist_t *rl, signed_descriptor_t *sd)
  355. {
  356. if (sd->is_extrainfo)
  357. return &rl->extrainfo_store;
  358. else
  359. return &rl->desc_store;
  360. }
  361. static INLINE desc_store_t *
  362. router_get_store(routerlist_t *rl, routerinfo_t *ri)
  363. {
  364. return desc_get_store(rl, &ri->cache_info);
  365. }
  366. /** Add the signed_descriptor_t in <b>desc</b> to the router
  367. * journal; change its saved_location to SAVED_IN_JOURNAL and set its
  368. * offset appropriately. */
  369. static int
  370. signed_desc_append_to_journal(signed_descriptor_t *desc,
  371. desc_store_t *store)
  372. {
  373. or_options_t *options = get_options();
  374. size_t fname_len = strlen(options->DataDirectory)+32;
  375. char *fname;
  376. const char *body = signed_descriptor_get_body_impl(desc,1);
  377. size_t len = desc->signed_descriptor_len + desc->annotations_len;
  378. fname = tor_malloc(fname_len);
  379. tor_snprintf(fname, fname_len, "%s"PATH_SEPARATOR"%s.new",
  380. options->DataDirectory, store->fname_base);
  381. tor_assert(len == strlen(body));
  382. if (append_bytes_to_file(fname, body, len, 1)) {
  383. log_warn(LD_FS, "Unable to store router descriptor");
  384. tor_free(fname);
  385. return -1;
  386. }
  387. desc->saved_location = SAVED_IN_JOURNAL;
  388. tor_free(fname);
  389. desc->saved_offset = store->journal_len;
  390. store->journal_len += len;
  391. return 0;
  392. }
  393. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  394. * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
  395. * the signed_descriptor_t* in *<b>b</b>. */
  396. static int
  397. _compare_signed_descriptors_by_age(const void **_a, const void **_b)
  398. {
  399. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  400. return r1->published_on - r2->published_on;
  401. }
  402. /** If the journal is too long, or if <b>force</b> is true, then atomically
  403. * replace the router store with the routers currently in our routerlist, and
  404. * clear the journal. Return 0 on success, -1 on failure.
  405. *
  406. * If <b>extrainfo</b> is true, rebuild the extrainfo store; else rebuild the
  407. * router descriptor store.
  408. */
  409. static int
  410. router_rebuild_store(int force, desc_store_t *store)
  411. {
  412. or_options_t *options;
  413. size_t fname_len;
  414. smartlist_t *chunk_list = NULL;
  415. char *fname = NULL, *fname_tmp = NULL;
  416. int r = -1;
  417. off_t offset = 0;
  418. smartlist_t *signed_descriptors = NULL;
  419. int nocache=0;
  420. if (!force && !router_should_rebuild_store(store))
  421. return 0;
  422. if (!routerlist)
  423. return 0;
  424. routerlist_assert_ok(routerlist);
  425. /* Don't save deadweight. */
  426. routerlist_remove_old_routers();
  427. log_info(LD_DIR, "Rebuilding %s cache", store->description);
  428. options = get_options();
  429. fname_len = strlen(options->DataDirectory)+32;
  430. fname = tor_malloc(fname_len);
  431. fname_tmp = tor_malloc(fname_len);
  432. tor_snprintf(fname, fname_len, "%s"PATH_SEPARATOR"%s",
  433. options->DataDirectory, store->fname_base);
  434. tor_snprintf(fname_tmp, fname_len, "%s"PATH_SEPARATOR"%s.tmp",
  435. options->DataDirectory, store->fname_base);
  436. chunk_list = smartlist_create();
  437. /* We sort the routers by age to enhance locality on disk. */
  438. signed_descriptors = smartlist_create();
  439. if (store->type == EXTRAINFO_STORE) {
  440. eimap_iter_t *iter;
  441. for (iter = eimap_iter_init(routerlist->extra_info_map);
  442. !eimap_iter_done(iter);
  443. iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
  444. const char *key;
  445. extrainfo_t *ei;
  446. eimap_iter_get(iter, &key, &ei);
  447. smartlist_add(signed_descriptors, &ei->cache_info);
  448. }
  449. } else {
  450. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  451. smartlist_add(signed_descriptors, sd));
  452. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  453. smartlist_add(signed_descriptors, &ri->cache_info));
  454. }
  455. smartlist_sort(signed_descriptors, _compare_signed_descriptors_by_age);
  456. /* Now, add the appropriate members to chunk_list */
  457. SMARTLIST_FOREACH(signed_descriptors, signed_descriptor_t *, sd,
  458. {
  459. sized_chunk_t *c;
  460. const char *body = signed_descriptor_get_body_impl(sd, 1);
  461. if (!body) {
  462. log_warn(LD_BUG, "No descriptor available for router.");
  463. goto done;
  464. }
  465. if (sd->do_not_cache) {
  466. ++nocache;
  467. continue;
  468. }
  469. c = tor_malloc(sizeof(sized_chunk_t));
  470. c->bytes = body;
  471. c->len = sd->signed_descriptor_len + sd->annotations_len;
  472. smartlist_add(chunk_list, c);
  473. });
  474. if (write_chunks_to_file(fname_tmp, chunk_list, 1)<0) {
  475. log_warn(LD_FS, "Error writing router store to disk.");
  476. goto done;
  477. }
  478. /* Our mmap is now invalid. */
  479. if (store->mmap) {
  480. tor_munmap_file(store->mmap);
  481. store->mmap = NULL;
  482. }
  483. if (replace_file(fname_tmp, fname)<0) {
  484. log_warn(LD_FS, "Error replacing old router store.");
  485. goto done;
  486. }
  487. store->mmap = tor_mmap_file(fname);
  488. if (! store->mmap) {
  489. log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
  490. //tor_assert(0);
  491. }
  492. log_info(LD_DIR, "Reconstructing pointers into cache");
  493. offset = 0;
  494. SMARTLIST_FOREACH(signed_descriptors, signed_descriptor_t *, sd,
  495. {
  496. if (sd->do_not_cache)
  497. continue;
  498. sd->saved_location = SAVED_IN_CACHE;
  499. if (store->mmap) {
  500. tor_free(sd->signed_descriptor_body); // sets it to null
  501. sd->saved_offset = offset;
  502. }
  503. offset += sd->signed_descriptor_len + sd->annotations_len;
  504. signed_descriptor_get_body(sd); /* reconstruct and assert */
  505. });
  506. tor_snprintf(fname, fname_len, "%s"PATH_SEPARATOR"%s.new",
  507. options->DataDirectory, store->fname_base);
  508. write_str_to_file(fname, "", 1);
  509. r = 0;
  510. store->store_len = (size_t) offset;
  511. store->journal_len = 0;
  512. store->bytes_dropped = 0;
  513. done:
  514. if (signed_descriptors)
  515. smartlist_free(signed_descriptors);
  516. tor_free(fname);
  517. tor_free(fname_tmp);
  518. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  519. smartlist_free(chunk_list);
  520. return r;
  521. }
  522. /** Helper: Reload a cache file and its associated journal, setting metadata
  523. * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
  524. * else reload the router descriptor store. */
  525. static int
  526. router_reload_router_list_impl(desc_store_t *store)
  527. {
  528. or_options_t *options = get_options();
  529. size_t fname_len = strlen(options->DataDirectory)+32;
  530. char *fname = tor_malloc(fname_len), *altname = NULL,
  531. *contents = NULL;
  532. struct stat st;
  533. int read_from_old_location = 0;
  534. int extrainfo = (store->type == EXTRAINFO_STORE);
  535. time_t now = time(NULL);
  536. store->journal_len = store->store_len = 0;
  537. tor_snprintf(fname, fname_len, "%s"PATH_SEPARATOR"%s",
  538. options->DataDirectory, store->fname_base);
  539. if (store->fname_alt_base) {
  540. altname = tor_malloc(fname_len);
  541. tor_snprintf(altname, fname_len, "%s"PATH_SEPARATOR"%s",
  542. options->DataDirectory, store->fname_alt_base);
  543. }
  544. if (store->mmap) /* get rid of it first */
  545. tor_munmap_file(store->mmap);
  546. store->mmap = NULL;
  547. store->mmap = tor_mmap_file(fname);
  548. if (!store->mmap && altname && file_status(altname) == FN_FILE) {
  549. read_from_old_location = 1;
  550. log_notice(LD_DIR, "Couldn't read %s; trying to load routers from old "
  551. "location %s.", fname, altname);
  552. if ((store->mmap = tor_mmap_file(altname)))
  553. read_from_old_location = 1;
  554. }
  555. if (altname && !read_from_old_location) {
  556. remove_file_if_very_old(altname, now);
  557. }
  558. if (store->mmap) {
  559. store->store_len = store->mmap->size;
  560. if (extrainfo)
  561. router_load_extrainfo_from_string(store->mmap->data,
  562. store->mmap->data+store->mmap->size,
  563. SAVED_IN_CACHE, NULL, 0);
  564. else
  565. router_load_routers_from_string(store->mmap->data,
  566. store->mmap->data+store->mmap->size,
  567. SAVED_IN_CACHE, NULL, 0, NULL);
  568. }
  569. tor_snprintf(fname, fname_len, "%s"PATH_SEPARATOR"%s.new",
  570. options->DataDirectory, store->fname_base);
  571. if (file_status(fname) == FN_FILE)
  572. contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  573. if (read_from_old_location) {
  574. tor_snprintf(altname, fname_len, "%s"PATH_SEPARATOR"%s.new",
  575. options->DataDirectory, store->fname_alt_base);
  576. if (!contents)
  577. contents = read_file_to_str(altname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  578. else
  579. remove_file_if_very_old(altname, now);
  580. }
  581. if (contents) {
  582. if (extrainfo)
  583. router_load_extrainfo_from_string(contents, NULL,SAVED_IN_JOURNAL,
  584. NULL, 0);
  585. else
  586. router_load_routers_from_string(contents, NULL, SAVED_IN_JOURNAL,
  587. NULL, 0, NULL);
  588. store->journal_len = (size_t) st.st_size;
  589. tor_free(contents);
  590. }
  591. tor_free(fname);
  592. tor_free(altname);
  593. if (store->journal_len || read_from_old_location) {
  594. /* Always clear the journal on startup.*/
  595. router_rebuild_store(1, store);
  596. } else if (!extrainfo) {
  597. /* Don't cache expired routers. (This is in an else because
  598. * router_rebuild_store() also calls remove_old_routers().) */
  599. routerlist_remove_old_routers();
  600. }
  601. return 0;
  602. }
  603. /** Load all cached router descriptors and extra-info documents from the
  604. * store. Return 0 on success and -1 on failure.
  605. */
  606. int
  607. router_reload_router_list(void)
  608. {
  609. routerlist_t *rl = router_get_routerlist();
  610. if (router_reload_router_list_impl(&rl->desc_store))
  611. return -1;
  612. if (router_reload_router_list_impl(&rl->extrainfo_store))
  613. return -1;
  614. return 0;
  615. }
  616. /** Return a smartlist containing a list of trusted_dir_server_t * for all
  617. * known trusted dirservers. Callers must not modify the list or its
  618. * contents.
  619. */
  620. smartlist_t *
  621. router_get_trusted_dir_servers(void)
  622. {
  623. if (!trusted_dir_servers)
  624. trusted_dir_servers = smartlist_create();
  625. return trusted_dir_servers;
  626. }
  627. /** Try to find a running dirserver. If there are no running dirservers
  628. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  629. * set all the authoritative ones as running again, and pick one;
  630. * if there are then no dirservers at all in our routerlist,
  631. * reload the routerlist and try one last time. If for_runningrouters is
  632. * true, then only pick a dirserver that can answer runningrouters queries
  633. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  634. * Don't pick an authority if any non-authority is viable.
  635. * Other args are as in router_pick_directory_server_impl().
  636. */
  637. routerstatus_t *
  638. router_pick_directory_server(int requireother,
  639. int fascistfirewall,
  640. authority_type_t type,
  641. int retry_if_no_servers)
  642. {
  643. routerstatus_t *choice;
  644. int prefer_tunnel = get_options()->PreferTunneledDirConns;
  645. if (!routerlist)
  646. return NULL;
  647. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  648. prefer_tunnel, type);
  649. if (choice || !retry_if_no_servers)
  650. return choice;
  651. log_info(LD_DIR,
  652. "No reachable router entries for dirservers. "
  653. "Trying them all again.");
  654. /* mark all authdirservers as up again */
  655. mark_all_trusteddirservers_up();
  656. /* try again */
  657. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  658. prefer_tunnel, type);
  659. if (choice)
  660. return choice;
  661. log_info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
  662. fascistfirewall ? "reachable" : "known");
  663. if (router_reload_router_list()) {
  664. return NULL;
  665. }
  666. /* give it one last try */
  667. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  668. prefer_tunnel, type);
  669. return choice;
  670. }
  671. /** Return the trusted_dir_server_t for the directory authority whose identity
  672. * key hashes to <b>digest</b>, or NULL if no such authority is known.
  673. */
  674. trusted_dir_server_t *
  675. router_get_trusteddirserver_by_digest(const char *digest)
  676. {
  677. if (!trusted_dir_servers)
  678. return NULL;
  679. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  680. {
  681. if (!memcmp(ds->digest, digest, DIGEST_LEN))
  682. return ds;
  683. });
  684. return NULL;
  685. }
  686. /** Return the trusted_dir_server_t for the directory authority whose identity
  687. * key hashes to <b>digest</b>, or NULL if no such authority is known.
  688. */
  689. trusted_dir_server_t *
  690. trusteddirserver_get_by_v3_auth_digest(const char *digest)
  691. {
  692. if (!trusted_dir_servers)
  693. return NULL;
  694. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  695. {
  696. if (!memcmp(ds->v3_identity_digest, digest, DIGEST_LEN))
  697. return ds;
  698. });
  699. return NULL;
  700. }
  701. /** Try to find a running trusted dirserver. If there are no running
  702. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  703. * set them all as running again, and try again.
  704. * <b>type> specifies the type of authoritative dir we require.
  705. * Other args are as in router_pick_trusteddirserver_impl().
  706. */
  707. routerstatus_t *
  708. router_pick_trusteddirserver(authority_type_t type,
  709. int requireother,
  710. int fascistfirewall,
  711. int retry_if_no_servers)
  712. {
  713. routerstatus_t *choice;
  714. int prefer_tunnel = get_options()->PreferTunneledDirConns;
  715. choice = router_pick_trusteddirserver_impl(type, requireother,
  716. fascistfirewall, prefer_tunnel);
  717. if (choice || !retry_if_no_servers)
  718. return choice;
  719. log_info(LD_DIR,
  720. "No trusted dirservers are reachable. Trying them all again.");
  721. mark_all_trusteddirservers_up();
  722. return router_pick_trusteddirserver_impl(type, requireother,
  723. fascistfirewall, prefer_tunnel);
  724. }
  725. /** How long do we avoid using a directory server after it's given us a 503? */
  726. #define DIR_503_TIMEOUT (60*60)
  727. /** Pick a random running valid directory server/mirror from our
  728. * routerlist.
  729. *
  730. * If <b>fascistfirewall</b>, make sure the router we pick is allowed
  731. * by our firewall options.
  732. * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
  733. * choose a directory server new enough to support the v2 directory
  734. * functionality.
  735. * If <b>prefer_tunnel</b>, choose a directory server that is reachable
  736. * and supports BEGIN_DIR cells, if possible.
  737. *
  738. * Don't pick an authority if any non-authorities are viable. Try to
  739. * avoid using servers that are overloaded (have returned 503 recently).
  740. */
  741. static routerstatus_t *
  742. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  743. int prefer_tunnel, authority_type_t type)
  744. {
  745. routerstatus_t *result;
  746. smartlist_t *direct, *tunnel;
  747. smartlist_t *trusted_direct, *trusted_tunnel;
  748. smartlist_t *overloaded_direct, *overloaded_tunnel;
  749. time_t now = time(NULL);
  750. const networkstatus_vote_t *consensus = networkstatus_get_latest_consensus();
  751. if (!consensus)
  752. return NULL;
  753. direct = smartlist_create();
  754. tunnel = smartlist_create();
  755. trusted_direct = smartlist_create();
  756. trusted_tunnel = smartlist_create();
  757. overloaded_direct = smartlist_create();
  758. overloaded_tunnel = smartlist_create();
  759. /* Find all the running dirservers we know about. */
  760. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, status,
  761. {
  762. int is_trusted;
  763. int is_overloaded = status->last_dir_503_at + DIR_503_TIMEOUT > now;
  764. if (!status->is_running || !status->dir_port || !status->is_valid)
  765. continue;
  766. if (status->is_bad_directory)
  767. continue;
  768. if (requireother && router_digest_is_me(status->identity_digest))
  769. continue;
  770. if (type & V3_AUTHORITY) {
  771. if (!(status->version_supports_v3_dir ||
  772. router_digest_is_trusted_dir_type(status->identity_digest,
  773. V3_AUTHORITY)))
  774. continue;
  775. }
  776. is_trusted = router_digest_is_trusted_dir(status->identity_digest);
  777. if ((type & V2_AUTHORITY) && !(status->is_v2_dir || is_trusted))
  778. continue;
  779. if ((type & EXTRAINFO_CACHE) &&
  780. !router_supports_extrainfo(status->identity_digest, 0))
  781. continue;
  782. if (prefer_tunnel &&
  783. status->version_supports_begindir &&
  784. (!fascistfirewall ||
  785. fascist_firewall_allows_address_or(status->addr, status->or_port)))
  786. smartlist_add(is_trusted ? trusted_tunnel :
  787. is_overloaded ? overloaded_tunnel : tunnel, status);
  788. else if (!fascistfirewall ||
  789. fascist_firewall_allows_address_dir(status->addr,
  790. status->dir_port))
  791. smartlist_add(is_trusted ? trusted_direct :
  792. is_overloaded ? overloaded_direct : direct, status);
  793. });
  794. if (smartlist_len(tunnel)) {
  795. result = routerstatus_sl_choose_by_bandwidth(tunnel);
  796. } else if (smartlist_len(overloaded_tunnel)) {
  797. result = routerstatus_sl_choose_by_bandwidth(overloaded_tunnel);
  798. } else if (smartlist_len(trusted_tunnel)) {
  799. /* FFFF We don't distinguish between trusteds and overloaded trusteds
  800. * yet. Maybe one day we should. */
  801. /* FFFF We also don't load balance over authorities yet. I think this
  802. * is a feature, but it could easily be a bug. -RD */
  803. result = smartlist_choose(trusted_tunnel);
  804. } else if (smartlist_len(direct)) {
  805. result = routerstatus_sl_choose_by_bandwidth(direct);
  806. } else if (smartlist_len(overloaded_direct)) {
  807. result = routerstatus_sl_choose_by_bandwidth(overloaded_direct);
  808. } else {
  809. result = smartlist_choose(trusted_direct);
  810. }
  811. smartlist_free(direct);
  812. smartlist_free(tunnel);
  813. smartlist_free(trusted_direct);
  814. smartlist_free(trusted_tunnel);
  815. smartlist_free(overloaded_direct);
  816. smartlist_free(overloaded_tunnel);
  817. return result;
  818. }
  819. /** Choose randomly from among the trusted dirservers that are up. If
  820. * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
  821. * firewall options. If <b>requireother</b>, it cannot be us.
  822. * <b>type> specifies the type of authoritative dir we require.
  823. */
  824. static routerstatus_t *
  825. router_pick_trusteddirserver_impl(authority_type_t type,
  826. int requireother, int fascistfirewall,
  827. int prefer_tunnel)
  828. {
  829. smartlist_t *direct, *tunnel;
  830. smartlist_t *overloaded_direct, *overloaded_tunnel;
  831. routerinfo_t *me = router_get_my_routerinfo();
  832. routerstatus_t *result;
  833. time_t now = time(NULL);
  834. direct = smartlist_create();
  835. tunnel = smartlist_create();
  836. overloaded_direct = smartlist_create();
  837. overloaded_tunnel = smartlist_create();
  838. if (!trusted_dir_servers)
  839. return NULL;
  840. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  841. {
  842. int is_overloaded =
  843. d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
  844. if (!d->is_running) continue;
  845. if ((type & d->type) == 0)
  846. continue;
  847. if ((type & EXTRAINFO_CACHE) &&
  848. !router_supports_extrainfo(d->digest, 1))
  849. continue;
  850. if (requireother && me && router_digest_is_me(d->digest))
  851. continue;
  852. if (prefer_tunnel &&
  853. d->or_port &&
  854. (!fascistfirewall ||
  855. fascist_firewall_allows_address_or(d->addr, d->or_port)))
  856. smartlist_add(is_overloaded ? overloaded_tunnel : tunnel,
  857. &d->fake_status);
  858. else if (!fascistfirewall ||
  859. fascist_firewall_allows_address_dir(d->addr, d->dir_port))
  860. smartlist_add(is_overloaded ? overloaded_direct : direct,
  861. &d->fake_status);
  862. });
  863. if (smartlist_len(tunnel)) {
  864. result = smartlist_choose(tunnel);
  865. } else if (smartlist_len(overloaded_tunnel)) {
  866. result = smartlist_choose(overloaded_tunnel);
  867. } else if (smartlist_len(direct)) {
  868. result = smartlist_choose(direct);
  869. } else {
  870. result = smartlist_choose(overloaded_direct);
  871. }
  872. smartlist_free(direct);
  873. smartlist_free(tunnel);
  874. smartlist_free(overloaded_direct);
  875. smartlist_free(overloaded_tunnel);
  876. return result;
  877. }
  878. /** Go through and mark the authoritative dirservers as up. */
  879. static void
  880. mark_all_trusteddirservers_up(void)
  881. {
  882. if (routerlist) {
  883. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  884. if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
  885. router->dir_port > 0) {
  886. router->is_running = 1;
  887. });
  888. }
  889. if (trusted_dir_servers) {
  890. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  891. {
  892. routerstatus_t *rs;
  893. dir->is_running = 1;
  894. download_status_reset(&dir->v2_ns_dl_status);
  895. rs = router_get_consensus_status_by_id(dir->digest);
  896. if (rs && !rs->is_running) {
  897. rs->is_running = 1;
  898. rs->last_dir_503_at = 0;
  899. control_event_networkstatus_changed_single(rs);
  900. }
  901. });
  902. }
  903. router_dir_info_changed();
  904. }
  905. /** Reset all internal variables used to count failed downloads of network
  906. * status objects. */
  907. void
  908. router_reset_status_download_failures(void)
  909. {
  910. mark_all_trusteddirservers_up();
  911. }
  912. /** Return true iff router1 and router2 have the same /16 network. */
  913. static INLINE int
  914. routers_in_same_network_family(routerinfo_t *r1, routerinfo_t *r2)
  915. {
  916. return (r1->addr & 0xffff0000) == (r2->addr & 0xffff0000);
  917. }
  918. /** Look through the routerlist and identify routers that
  919. * advertise the same /16 network address as <b>router</b>.
  920. * Add each of them to <b>sl</b>.
  921. */
  922. static void
  923. routerlist_add_network_family(smartlist_t *sl, routerinfo_t *router)
  924. {
  925. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  926. {
  927. if (router != r && routers_in_same_network_family(router, r))
  928. smartlist_add(sl, r);
  929. });
  930. }
  931. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  932. * This is used to make sure we don't pick siblings in a single path.
  933. */
  934. void
  935. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  936. {
  937. routerinfo_t *r;
  938. config_line_t *cl;
  939. or_options_t *options = get_options();
  940. /* First, add any routers with similar network addresses. */
  941. if (options->EnforceDistinctSubnets)
  942. routerlist_add_network_family(sl, router);
  943. if (router->declared_family) {
  944. /* Add every r such that router declares familyness with r, and r
  945. * declares familyhood with router. */
  946. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  947. {
  948. if (!(r = router_get_by_nickname(n, 0)))
  949. continue;
  950. if (!r->declared_family)
  951. continue;
  952. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  953. {
  954. if (router_nickname_matches(router, n2))
  955. smartlist_add(sl, r);
  956. });
  957. });
  958. }
  959. /* If the user declared any families locally, honor those too. */
  960. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  961. if (router_nickname_is_in_list(router, cl->value)) {
  962. add_nickname_list_to_smartlist(sl, cl->value, 0);
  963. }
  964. }
  965. }
  966. /** Return true iff r is named by some nickname in <b>lst</b>. */
  967. static INLINE int
  968. router_in_nickname_smartlist(smartlist_t *lst, routerinfo_t *r)
  969. {
  970. if (!lst) return 0;
  971. SMARTLIST_FOREACH(lst, const char *, name,
  972. if (router_nickname_matches(r, name))
  973. return 1;);
  974. return 0;
  975. }
  976. /** Return true iff r1 and r2 are in the same family, but not the same
  977. * router. */
  978. int
  979. routers_in_same_family(routerinfo_t *r1, routerinfo_t *r2)
  980. {
  981. or_options_t *options = get_options();
  982. config_line_t *cl;
  983. if (options->EnforceDistinctSubnets && routers_in_same_network_family(r1,r2))
  984. return 1;
  985. if (router_in_nickname_smartlist(r1->declared_family, r2) &&
  986. router_in_nickname_smartlist(r2->declared_family, r1))
  987. return 1;
  988. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  989. if (router_nickname_is_in_list(r1, cl->value) &&
  990. router_nickname_is_in_list(r2, cl->value))
  991. return 1;
  992. }
  993. return 0;
  994. }
  995. /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
  996. * see which nicknames in <b>list</b> name routers in our routerlist, and add
  997. * the routerinfos for those routers to <b>sl</b>. If <b>must_be_running</b>,
  998. * only include routers that we think are running.
  999. * Warn if any non-Named routers are specified by nickname.
  1000. */
  1001. void
  1002. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
  1003. int must_be_running)
  1004. {
  1005. routerinfo_t *router;
  1006. smartlist_t *nickname_list;
  1007. int have_dir_info = router_have_minimum_dir_info();
  1008. if (!list)
  1009. return; /* nothing to do */
  1010. tor_assert(sl);
  1011. nickname_list = smartlist_create();
  1012. if (!warned_nicknames)
  1013. warned_nicknames = smartlist_create();
  1014. smartlist_split_string(nickname_list, list, ",",
  1015. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1016. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  1017. int warned;
  1018. if (!is_legal_nickname_or_hexdigest(nick)) {
  1019. log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
  1020. continue;
  1021. }
  1022. router = router_get_by_nickname(nick, 1);
  1023. warned = smartlist_string_isin(warned_nicknames, nick);
  1024. if (router) {
  1025. if (!must_be_running || router->is_running) {
  1026. smartlist_add(sl,router);
  1027. }
  1028. } else if (!router_get_consensus_status_by_nickname(nick,1)) {
  1029. if (!warned) {
  1030. log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
  1031. "Nickname list includes '%s' which isn't a known router.",nick);
  1032. smartlist_add(warned_nicknames, tor_strdup(nick));
  1033. }
  1034. }
  1035. });
  1036. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  1037. smartlist_free(nickname_list);
  1038. }
  1039. /** Return 1 iff any member of the (possibly NULL) comma-separated list
  1040. * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
  1041. * return 0.
  1042. */
  1043. int
  1044. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  1045. {
  1046. smartlist_t *nickname_list;
  1047. int v = 0;
  1048. if (!list)
  1049. return 0; /* definitely not */
  1050. tor_assert(router);
  1051. nickname_list = smartlist_create();
  1052. smartlist_split_string(nickname_list, list, ",",
  1053. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1054. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  1055. if (router_nickname_matches(router, cp)) {v=1;break;});
  1056. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  1057. smartlist_free(nickname_list);
  1058. return v;
  1059. }
  1060. /** Add every suitable router from our routerlist to <b>sl</b>, so that
  1061. * we can pick a node for a circuit.
  1062. */
  1063. static void
  1064. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_invalid,
  1065. int need_uptime, int need_capacity,
  1066. int need_guard)
  1067. {
  1068. if (!routerlist)
  1069. return;
  1070. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1071. {
  1072. if (router->is_running &&
  1073. router->purpose == ROUTER_PURPOSE_GENERAL &&
  1074. (router->is_valid || allow_invalid) &&
  1075. !router_is_unreliable(router, need_uptime,
  1076. need_capacity, need_guard)) {
  1077. /* If it's running, and it's suitable according to the
  1078. * other flags we had in mind */
  1079. smartlist_add(sl, router);
  1080. }
  1081. });
  1082. }
  1083. /** Look through the routerlist until we find a router that has my key.
  1084. Return it. */
  1085. routerinfo_t *
  1086. routerlist_find_my_routerinfo(void)
  1087. {
  1088. if (!routerlist)
  1089. return NULL;
  1090. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1091. {
  1092. if (router_is_me(router))
  1093. return router;
  1094. });
  1095. return NULL;
  1096. }
  1097. /** Find a router that's up, that has this IP address, and
  1098. * that allows exit to this address:port, or return NULL if there
  1099. * isn't a good one.
  1100. */
  1101. routerinfo_t *
  1102. router_find_exact_exit_enclave(const char *address, uint16_t port)
  1103. {
  1104. uint32_t addr;
  1105. struct in_addr in;
  1106. if (!tor_inet_aton(address, &in))
  1107. return NULL; /* it's not an IP already */
  1108. addr = ntohl(in.s_addr);
  1109. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1110. {
  1111. if (router->is_running &&
  1112. router->addr == addr &&
  1113. compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
  1114. ADDR_POLICY_ACCEPTED)
  1115. return router;
  1116. });
  1117. return NULL;
  1118. }
  1119. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  1120. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  1121. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  1122. * bandwidth.
  1123. * If <b>need_guard</b>, we require that the router is a possible entry guard.
  1124. */
  1125. int
  1126. router_is_unreliable(routerinfo_t *router, int need_uptime,
  1127. int need_capacity, int need_guard)
  1128. {
  1129. if (need_uptime && !router->is_stable)
  1130. return 1;
  1131. if (need_capacity && !router->is_fast)
  1132. return 1;
  1133. if (need_guard && !router->is_possible_guard)
  1134. return 1;
  1135. return 0;
  1136. }
  1137. /** Return the smaller of the router's configured BandwidthRate
  1138. * and its advertised capacity. */
  1139. uint32_t
  1140. router_get_advertised_bandwidth(routerinfo_t *router)
  1141. {
  1142. if (router->bandwidthcapacity < router->bandwidthrate)
  1143. return router->bandwidthcapacity;
  1144. return router->bandwidthrate;
  1145. }
  1146. /** Do not weight any declared bandwidth more than this much when picking
  1147. * routers by bandwidth. */
  1148. #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
  1149. /** Eventually, the number we return will come from the directory
  1150. * consensus, so clients can dynamically update to better numbers.
  1151. *
  1152. * But for now, or in case there is no consensus available, just return
  1153. * a sufficient default. */
  1154. static uint32_t
  1155. get_max_believable_bandwidth(void)
  1156. {
  1157. return DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
  1158. }
  1159. /** Helper function:
  1160. * choose a random element of smartlist <b>sl</b>, weighted by
  1161. * the advertised bandwidth of each element.
  1162. *
  1163. * If <b>statuses</b> is zero, then <b>sl</b> is a list of
  1164. * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
  1165. *
  1166. * If <b>for_exit</b>, we're picking an exit node: consider all nodes'
  1167. * bandwidth equally regardless of their Exit status, since there may be
  1168. * some in the list because they exit to obscure ports. If not <b>for_exit</b>,
  1169. * we're picking a non-exit node: weight exit-node's bandwidth less
  1170. * depending on the smallness of the fraction of Exit-to-total bandwidth.
  1171. *
  1172. * If <b>for_guard</b>, we're picking a guard node: consider all guard's
  1173. * bandwidth equally. Otherwise, weight guards proportionally less.
  1174. *
  1175. */
  1176. static void *
  1177. smartlist_choose_by_bandwidth(smartlist_t *sl, bandwidth_weight_rule_t rule,
  1178. int statuses)
  1179. {
  1180. unsigned int i;
  1181. routerinfo_t *router;
  1182. routerstatus_t *status=NULL;
  1183. int32_t *bandwidths;
  1184. int is_exit;
  1185. int is_guard;
  1186. uint64_t total_nonexit_bw = 0, total_exit_bw = 0, total_bw = 0;
  1187. uint64_t total_nonguard_bw = 0, total_guard_bw = 0;
  1188. uint64_t rand_bw, tmp;
  1189. double exit_weight;
  1190. double guard_weight;
  1191. int n_unknown = 0;
  1192. bitarray_t *exit_bits;
  1193. bitarray_t *guard_bits;
  1194. uint32_t max_believable_bw = get_max_believable_bandwidth();
  1195. /* Can't choose exit and guard at same time */
  1196. tor_assert(rule == NO_WEIGHTING ||
  1197. rule == WEIGHT_FOR_EXIT ||
  1198. rule == WEIGHT_FOR_GUARD);
  1199. /* First count the total bandwidth weight, and make a list
  1200. * of each value. <0 means "unknown; no routerinfo." We use the
  1201. * bits of negative values to remember whether the router was fast (-x)&1
  1202. * and whether it was an exit (-x)&2 or guard (-x)&4. Yes, it's a hack. */
  1203. bandwidths = tor_malloc(sizeof(int32_t)*smartlist_len(sl));
  1204. exit_bits = bitarray_init_zero(smartlist_len(sl));
  1205. guard_bits = bitarray_init_zero(smartlist_len(sl));
  1206. /* Iterate over all the routerinfo_t or routerstatus_t, and */
  1207. for (i = 0; i < (unsigned)smartlist_len(sl); ++i) {
  1208. /* first, learn what bandwidth we think i has */
  1209. int is_known = 1;
  1210. int32_t flags = 0;
  1211. uint32_t this_bw = 0;
  1212. if (statuses) {
  1213. /* need to extract router info */
  1214. status = smartlist_get(sl, i);
  1215. router = router_get_by_digest(status->identity_digest);
  1216. is_exit = status->is_exit;
  1217. is_guard = status->is_possible_guard;
  1218. if (router) {
  1219. this_bw = router_get_advertised_bandwidth(router);
  1220. } else { /* guess */
  1221. is_known = 0;
  1222. flags = status->is_fast ? 1 : 0;
  1223. flags |= is_exit ? 2 : 0;
  1224. flags |= is_guard ? 4 : 0;
  1225. }
  1226. } else {
  1227. router = smartlist_get(sl, i);
  1228. is_exit = router->is_exit;
  1229. is_guard = router->is_possible_guard;
  1230. this_bw = router_get_advertised_bandwidth(router);
  1231. }
  1232. if (is_exit)
  1233. bitarray_set(exit_bits, i);
  1234. if (is_guard)
  1235. bitarray_set(guard_bits, i);
  1236. /* if they claim something huge, don't believe it */
  1237. if (this_bw > max_believable_bw) {
  1238. char fp[HEX_DIGEST_LEN+1];
  1239. base16_encode(fp, sizeof(fp), statuses ?
  1240. status->identity_digest :
  1241. router->cache_info.identity_digest,
  1242. DIGEST_LEN);
  1243. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1244. "Bandwidth %d for router %s (%s) exceeds allowed max %d, capping",
  1245. this_bw, router ? router->nickname : "(null)",
  1246. fp, max_believable_bw);
  1247. this_bw = max_believable_bw;
  1248. }
  1249. if (is_known) {
  1250. bandwidths[i] = (int32_t) this_bw; // safe since MAX_BELIEVABLE<INT32_MAX
  1251. if (is_guard)
  1252. total_guard_bw += this_bw;
  1253. else
  1254. total_nonguard_bw += this_bw;
  1255. if (is_exit)
  1256. total_exit_bw += this_bw;
  1257. else
  1258. total_nonexit_bw += this_bw;
  1259. } else {
  1260. ++n_unknown;
  1261. bandwidths[i] = -flags;
  1262. }
  1263. }
  1264. /* Now, fill in the unknown values. */
  1265. if (n_unknown) {
  1266. int32_t avg_fast, avg_slow;
  1267. if (total_exit_bw+total_nonexit_bw) {
  1268. /* if there's some bandwidth, there's at least one known router,
  1269. * so no worries about div by 0 here */
  1270. int n_known = smartlist_len(sl)-n_unknown;
  1271. avg_fast = avg_slow = (int32_t)
  1272. ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
  1273. } else {
  1274. avg_fast = 40000;
  1275. avg_slow = 20000;
  1276. }
  1277. for (i=0; i<(unsigned)smartlist_len(sl); ++i) {
  1278. int32_t bw = bandwidths[i];
  1279. if (bw>=0)
  1280. continue;
  1281. is_exit = ((-bw)&2);
  1282. is_guard = ((-bw)&4);
  1283. bandwidths[i] = ((-bw)&1) ? avg_fast : avg_slow;
  1284. if (is_exit)
  1285. total_exit_bw += bandwidths[i];
  1286. else
  1287. total_nonexit_bw += bandwidths[i];
  1288. if (is_guard)
  1289. total_guard_bw += bandwidths[i];
  1290. else
  1291. total_nonguard_bw += bandwidths[i];
  1292. }
  1293. }
  1294. /* If there's no bandwidth at all, pick at random. */
  1295. if (!(total_exit_bw+total_nonexit_bw)) {
  1296. tor_free(bandwidths);
  1297. tor_free(exit_bits);
  1298. tor_free(guard_bits);
  1299. return smartlist_choose(sl);
  1300. }
  1301. /* Figure out how to weight exits and guards */
  1302. {
  1303. double all_bw = U64_TO_DBL(total_exit_bw+total_nonexit_bw);
  1304. double exit_bw = U64_TO_DBL(total_exit_bw);
  1305. double guard_bw = U64_TO_DBL(total_guard_bw);
  1306. /*
  1307. * For detailed derivation of this formula, see
  1308. * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
  1309. */
  1310. if (rule == WEIGHT_FOR_EXIT)
  1311. exit_weight = 1.0;
  1312. else
  1313. exit_weight = 1.0 - all_bw/(3.0*exit_bw);
  1314. if (rule == WEIGHT_FOR_GUARD)
  1315. guard_weight = 1.0;
  1316. else
  1317. guard_weight = 1.0 - all_bw/(3.0*guard_bw);
  1318. if (exit_weight <= 0.0)
  1319. exit_weight = 0.0;
  1320. if (guard_weight <= 0.0)
  1321. guard_weight = 0.0;
  1322. total_bw = 0;
  1323. for (i=0; i < (unsigned)smartlist_len(sl); i++) {
  1324. is_exit = bitarray_is_set(exit_bits, i);
  1325. is_guard = bitarray_is_set(guard_bits, i);
  1326. if (is_exit && is_guard)
  1327. total_bw += ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
  1328. else if (is_guard)
  1329. total_bw += ((uint64_t)(bandwidths[i] * guard_weight));
  1330. else if (is_exit)
  1331. total_bw += ((uint64_t)(bandwidths[i] * exit_weight));
  1332. else
  1333. total_bw += bandwidths[i];
  1334. }
  1335. }
  1336. log_debug(LD_CIRC, "Total bw = "U64_FORMAT
  1337. ", exit bw = "U64_FORMAT
  1338. ", nonexit bw = "U64_FORMAT", exit weight = %lf "
  1339. "(for exit == %d)"
  1340. ", guard bw = "U64_FORMAT
  1341. ", nonguard bw = "U64_FORMAT", guard weight = %lf "
  1342. "(for guard == %d)",
  1343. U64_PRINTF_ARG(total_bw),
  1344. U64_PRINTF_ARG(total_exit_bw), U64_PRINTF_ARG(total_nonexit_bw),
  1345. exit_weight, (int)(rule == WEIGHT_FOR_EXIT),
  1346. U64_PRINTF_ARG(total_guard_bw), U64_PRINTF_ARG(total_nonguard_bw),
  1347. guard_weight, (int)(rule == WEIGHT_FOR_GUARD));
  1348. /* Almost done: choose a random value from the bandwidth weights. */
  1349. rand_bw = crypto_rand_uint64(total_bw);
  1350. /* Last, count through sl until we get to the element we picked */
  1351. tmp = 0;
  1352. for (i=0; i < (unsigned)smartlist_len(sl); i++) {
  1353. is_exit = bitarray_is_set(exit_bits, i);
  1354. is_guard = bitarray_is_set(guard_bits, i);
  1355. /* Weights can be 0 if not counting guards/exits */
  1356. if (is_exit && is_guard)
  1357. tmp += ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
  1358. else if (is_guard)
  1359. tmp += ((uint64_t)(bandwidths[i] * guard_weight));
  1360. else if (is_exit)
  1361. tmp += ((uint64_t)(bandwidths[i] * exit_weight));
  1362. else
  1363. tmp += bandwidths[i];
  1364. if (tmp >= rand_bw)
  1365. break;
  1366. }
  1367. if (i == (unsigned)smartlist_len(sl)) {
  1368. /* This was once possible due to round-off error, but shouldn't be able
  1369. * to occur any longer. */
  1370. tor_fragile_assert();
  1371. --i;
  1372. log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
  1373. " which router we chose. Please tell the developers. "
  1374. U64_FORMAT " " U64_FORMAT " " U64_FORMAT, U64_PRINTF_ARG(tmp),
  1375. U64_PRINTF_ARG(rand_bw), U64_PRINTF_ARG(total_bw));
  1376. }
  1377. tor_free(bandwidths);
  1378. tor_free(exit_bits);
  1379. tor_free(guard_bits);
  1380. return smartlist_get(sl, i);
  1381. }
  1382. /** Choose a random element of router list <b>sl</b>, weighted by
  1383. * the advertised bandwidth of each router.
  1384. */
  1385. routerinfo_t *
  1386. routerlist_sl_choose_by_bandwidth(smartlist_t *sl,
  1387. bandwidth_weight_rule_t rule)
  1388. {
  1389. return smartlist_choose_by_bandwidth(sl, rule, 0);
  1390. }
  1391. /** Choose a random element of status list <b>sl</b>, weighted by
  1392. * the advertised bandwidth of each status.
  1393. */
  1394. routerstatus_t *
  1395. routerstatus_sl_choose_by_bandwidth(smartlist_t *sl)
  1396. {
  1397. /* We are choosing neither exit nor guard here. Weight accordingly. */
  1398. return smartlist_choose_by_bandwidth(sl, NO_WEIGHTING, 1);
  1399. }
  1400. /** Return a random running router from the routerlist. If any node
  1401. * named in <b>preferred</b> is available, pick one of those. Never
  1402. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  1403. * <b>excludedsmartlist</b>, even if they are the only nodes
  1404. * available. If <b>strict</b> is true, never pick any node besides
  1405. * those in <b>preferred</b>.
  1406. * If <b>need_uptime</b> is non-zero and any router has more than
  1407. * a minimum uptime, return one of those.
  1408. * If <b>need_capacity</b> is non-zero, weight your choice by the
  1409. * advertised capacity of each router.
  1410. * If ! <b>allow_invalid</b>, consider only Valid routers.
  1411. * If <b>need_guard</b>, consider only Guard routers.
  1412. * If <b>weight_for_exit</b>, we weight bandwidths as if picking an exit node,
  1413. * otherwise we weight bandwidths for picking a relay node (that is, possibly
  1414. * discounting exit nodes).
  1415. */
  1416. routerinfo_t *
  1417. router_choose_random_node(const char *preferred,
  1418. const char *excluded,
  1419. smartlist_t *excludedsmartlist,
  1420. int need_uptime, int need_capacity,
  1421. int need_guard,
  1422. int allow_invalid, int strict,
  1423. int weight_for_exit)
  1424. {
  1425. smartlist_t *sl, *excludednodes;
  1426. routerinfo_t *choice = NULL;
  1427. bandwidth_weight_rule_t rule;
  1428. tor_assert(!(weight_for_exit && need_guard));
  1429. rule = weight_for_exit ? WEIGHT_FOR_EXIT :
  1430. (need_guard ? WEIGHT_FOR_GUARD : NO_WEIGHTING);
  1431. excludednodes = smartlist_create();
  1432. add_nickname_list_to_smartlist(excludednodes,excluded,0);
  1433. /* Try the preferred nodes first. Ignore need_uptime and need_capacity
  1434. * and need_guard, since the user explicitly asked for these nodes. */
  1435. if (preferred) {
  1436. sl = smartlist_create();
  1437. add_nickname_list_to_smartlist(sl,preferred,1);
  1438. smartlist_subtract(sl,excludednodes);
  1439. if (excludedsmartlist)
  1440. smartlist_subtract(sl,excludedsmartlist);
  1441. choice = smartlist_choose(sl);
  1442. smartlist_free(sl);
  1443. }
  1444. if (!choice && !strict) {
  1445. /* Then give up on our preferred choices: any node
  1446. * will do that has the required attributes. */
  1447. sl = smartlist_create();
  1448. router_add_running_routers_to_smartlist(sl, allow_invalid,
  1449. need_uptime, need_capacity,
  1450. need_guard);
  1451. smartlist_subtract(sl,excludednodes);
  1452. if (excludedsmartlist)
  1453. smartlist_subtract(sl,excludedsmartlist);
  1454. if (need_capacity || need_guard)
  1455. choice = routerlist_sl_choose_by_bandwidth(sl, rule);
  1456. else
  1457. choice = smartlist_choose(sl);
  1458. smartlist_free(sl);
  1459. if (!choice && (need_uptime || need_capacity || need_guard)) {
  1460. /* try once more -- recurse but with fewer restrictions. */
  1461. log_info(LD_CIRC,
  1462. "We couldn't find any live%s%s%s routers; falling back "
  1463. "to list of all routers.",
  1464. need_capacity?", fast":"",
  1465. need_uptime?", stable":"",
  1466. need_guard?", guard":"");
  1467. choice = router_choose_random_node(
  1468. NULL, excluded, excludedsmartlist,
  1469. 0, 0, 0, allow_invalid, 0, weight_for_exit);
  1470. }
  1471. }
  1472. smartlist_free(excludednodes);
  1473. if (!choice) {
  1474. if (strict) {
  1475. log_warn(LD_CIRC, "All preferred nodes were down when trying to choose "
  1476. "node, and the Strict[...]Nodes option is set. Failing.");
  1477. } else {
  1478. log_warn(LD_CIRC,
  1479. "No available nodes when trying to choose node. Failing.");
  1480. }
  1481. }
  1482. return choice;
  1483. }
  1484. /** Return true iff the digest of <b>router</b>'s identity key,
  1485. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  1486. * optionally prefixed with a single dollar sign). Return false if
  1487. * <b>hexdigest</b> is malformed, or it doesn't match. */
  1488. static INLINE int
  1489. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  1490. {
  1491. char digest[DIGEST_LEN];
  1492. size_t len;
  1493. tor_assert(hexdigest);
  1494. if (hexdigest[0] == '$')
  1495. ++hexdigest;
  1496. len = strlen(hexdigest);
  1497. if (len < HEX_DIGEST_LEN)
  1498. return 0;
  1499. else if (len > HEX_DIGEST_LEN &&
  1500. (hexdigest[HEX_DIGEST_LEN] == '=' ||
  1501. hexdigest[HEX_DIGEST_LEN] == '~')) {
  1502. if (strcasecmp(hexdigest+HEX_DIGEST_LEN+1, router->nickname))
  1503. return 0;
  1504. if (hexdigest[HEX_DIGEST_LEN] == '=' && !router->is_named)
  1505. return 0;
  1506. }
  1507. if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  1508. return 0;
  1509. return (!memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
  1510. }
  1511. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  1512. * (case-insensitive), or if <b>router's</b> identity key digest
  1513. * matches a hexadecimal value stored in <b>nickname</b>. Return
  1514. * false otherwise. */
  1515. static int
  1516. router_nickname_matches(routerinfo_t *router, const char *nickname)
  1517. {
  1518. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  1519. return 1;
  1520. return router_hex_digest_matches(router, nickname);
  1521. }
  1522. /** Return the router in our routerlist whose (case-insensitive)
  1523. * nickname or (case-sensitive) hexadecimal key digest is
  1524. * <b>nickname</b>. Return NULL if no such router is known.
  1525. */
  1526. routerinfo_t *
  1527. router_get_by_nickname(const char *nickname, int warn_if_unnamed)
  1528. {
  1529. int maybedigest;
  1530. char digest[DIGEST_LEN];
  1531. routerinfo_t *best_match=NULL;
  1532. int n_matches = 0;
  1533. const char *named_digest = NULL;
  1534. tor_assert(nickname);
  1535. if (!routerlist)
  1536. return NULL;
  1537. if (nickname[0] == '$')
  1538. return router_get_by_hexdigest(nickname);
  1539. if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
  1540. return NULL;
  1541. if (server_mode(get_options()) &&
  1542. !strcasecmp(nickname, get_options()->Nickname))
  1543. return router_get_my_routerinfo();
  1544. maybedigest = (strlen(nickname) >= HEX_DIGEST_LEN) &&
  1545. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  1546. if ((named_digest = networkstatus_get_router_digest_by_nickname(nickname))) {
  1547. return rimap_get(routerlist->identity_map, named_digest);
  1548. }
  1549. /* If we reach this point, there's no canonical value for the nickname. */
  1550. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1551. {
  1552. if (!strcasecmp(router->nickname, nickname)) {
  1553. ++n_matches;
  1554. if (n_matches <= 1 || router->is_running)
  1555. best_match = router;
  1556. } else if (maybedigest &&
  1557. !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
  1558. ) {
  1559. if (router_hex_digest_matches(router, nickname))
  1560. return router;
  1561. else
  1562. best_match = router; // XXXX020 NM not exactly right.
  1563. }
  1564. });
  1565. if (best_match) {
  1566. if (warn_if_unnamed && n_matches > 1) {
  1567. smartlist_t *fps = smartlist_create();
  1568. int any_unwarned = 0;
  1569. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1570. {
  1571. routerstatus_t *rs;
  1572. char *desc;
  1573. size_t dlen;
  1574. char fp[HEX_DIGEST_LEN+1];
  1575. if (strcasecmp(router->nickname, nickname))
  1576. continue;
  1577. rs = router_get_consensus_status_by_id(
  1578. router->cache_info.identity_digest);
  1579. if (rs && !rs->name_lookup_warned) {
  1580. rs->name_lookup_warned = 1;
  1581. any_unwarned = 1;
  1582. }
  1583. base16_encode(fp, sizeof(fp),
  1584. router->cache_info.identity_digest, DIGEST_LEN);
  1585. dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
  1586. desc = tor_malloc(dlen);
  1587. tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
  1588. fp, router->address, router->or_port);
  1589. smartlist_add(fps, desc);
  1590. });
  1591. if (any_unwarned) {
  1592. char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
  1593. log_warn(LD_CONFIG,
  1594. "There are multiple matches for the nickname \"%s\","
  1595. " but none is listed as named by the directory authorities. "
  1596. "Choosing one arbitrarily. If you meant one in particular, "
  1597. "you should say %s.", nickname, alternatives);
  1598. tor_free(alternatives);
  1599. }
  1600. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  1601. smartlist_free(fps);
  1602. } else if (warn_if_unnamed) {
  1603. routerstatus_t *rs = router_get_consensus_status_by_id(
  1604. best_match->cache_info.identity_digest);
  1605. if (rs && !rs->name_lookup_warned) {
  1606. char fp[HEX_DIGEST_LEN+1];
  1607. base16_encode(fp, sizeof(fp),
  1608. best_match->cache_info.identity_digest, DIGEST_LEN);
  1609. log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
  1610. "name is not registered, so it could be used by any server, "
  1611. "not just the one you meant. "
  1612. "To make sure you get the same server in the future, refer to "
  1613. "it by key, as \"$%s\".", nickname, fp);
  1614. rs->name_lookup_warned = 1;
  1615. }
  1616. }
  1617. return best_match;
  1618. }
  1619. return NULL;
  1620. }
  1621. /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
  1622. * return 1. If we do, ask tor_version_as_new_as() for the answer.
  1623. */
  1624. int
  1625. router_digest_version_as_new_as(const char *digest, const char *cutoff)
  1626. {
  1627. routerinfo_t *router = router_get_by_digest(digest);
  1628. if (!router)
  1629. return 1;
  1630. return tor_version_as_new_as(router->platform, cutoff);
  1631. }
  1632. /** Return true iff <b>digest</b> is the digest of the identity key of a
  1633. * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
  1634. * is zero, any authority is okay. */
  1635. int
  1636. router_digest_is_trusted_dir_type(const char *digest, authority_type_t type)
  1637. {
  1638. if (!trusted_dir_servers)
  1639. return 0;
  1640. if (authdir_mode(get_options()) && router_digest_is_me(digest))
  1641. return 1;
  1642. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1643. if (!memcmp(digest, ent->digest, DIGEST_LEN)) {
  1644. return (!type) || ((type & ent->type) != 0);
  1645. });
  1646. return 0;
  1647. }
  1648. /** Return true iff <b>addr</b> is the address of one of our trusted
  1649. * directory authorities. */
  1650. int
  1651. router_addr_is_trusted_dir(uint32_t addr)
  1652. {
  1653. if (!trusted_dir_servers)
  1654. return 0;
  1655. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1656. if (ent->addr == addr)
  1657. return 1;
  1658. );
  1659. return 0;
  1660. }
  1661. /** If hexdigest is correctly formed, base16_decode it into
  1662. * digest, which must have DIGEST_LEN space in it.
  1663. * Return 0 on success, -1 on failure.
  1664. */
  1665. int
  1666. hexdigest_to_digest(const char *hexdigest, char *digest)
  1667. {
  1668. if (hexdigest[0]=='$')
  1669. ++hexdigest;
  1670. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1671. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  1672. return -1;
  1673. return 0;
  1674. }
  1675. /** Return the router in our routerlist whose hexadecimal key digest
  1676. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  1677. routerinfo_t *
  1678. router_get_by_hexdigest(const char *hexdigest)
  1679. {
  1680. char digest[DIGEST_LEN];
  1681. size_t len;
  1682. routerinfo_t *ri;
  1683. tor_assert(hexdigest);
  1684. if (!routerlist)
  1685. return NULL;
  1686. if (hexdigest[0]=='$')
  1687. ++hexdigest;
  1688. len = strlen(hexdigest);
  1689. if (hexdigest_to_digest(hexdigest, digest) < 0)
  1690. return NULL;
  1691. ri = router_get_by_digest(digest);
  1692. if (len > HEX_DIGEST_LEN) {
  1693. if (hexdigest[HEX_DIGEST_LEN] == '=') {
  1694. if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1) ||
  1695. !ri->is_named)
  1696. return NULL;
  1697. } else if (hexdigest[HEX_DIGEST_LEN] == '~') {
  1698. if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1))
  1699. return NULL;
  1700. } else {
  1701. return NULL;
  1702. }
  1703. }
  1704. return ri;
  1705. }
  1706. /** Return the router in our routerlist whose 20-byte key digest
  1707. * is <b>digest</b>. Return NULL if no such router is known. */
  1708. routerinfo_t *
  1709. router_get_by_digest(const char *digest)
  1710. {
  1711. tor_assert(digest);
  1712. if (!routerlist) return NULL;
  1713. // routerlist_assert_ok(routerlist);
  1714. return rimap_get(routerlist->identity_map, digest);
  1715. }
  1716. /** Return the router in our routerlist whose 20-byte descriptor
  1717. * is <b>digest</b>. Return NULL if no such router is known. */
  1718. signed_descriptor_t *
  1719. router_get_by_descriptor_digest(const char *digest)
  1720. {
  1721. tor_assert(digest);
  1722. if (!routerlist) return NULL;
  1723. return sdmap_get(routerlist->desc_digest_map, digest);
  1724. }
  1725. /** Return the signed descriptor for the router in our routerlist whose
  1726. * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
  1727. * is known. */
  1728. signed_descriptor_t *
  1729. router_get_by_extrainfo_digest(const char *digest)
  1730. {
  1731. tor_assert(digest);
  1732. if (!routerlist) return NULL;
  1733. return sdmap_get(routerlist->desc_by_eid_map, digest);
  1734. }
  1735. /** Return the signed descriptor for the extrainfo_t in our routerlist whose
  1736. * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
  1737. * document is known. */
  1738. signed_descriptor_t *
  1739. extrainfo_get_by_descriptor_digest(const char *digest)
  1740. {
  1741. extrainfo_t *ei;
  1742. tor_assert(digest);
  1743. if (!routerlist) return NULL;
  1744. ei = eimap_get(routerlist->extra_info_map, digest);
  1745. return ei ? &ei->cache_info : NULL;
  1746. }
  1747. /** Return a pointer to the signed textual representation of a descriptor.
  1748. * The returned string is not guaranteed to be NUL-terminated: the string's
  1749. * length will be in desc-\>signed_descriptor_len.
  1750. *
  1751. * If with_annotations is set, the returned string will include the annotations
  1752. * (if any) preceding the descriptor. This will increase the length of the
  1753. * string by desc-\>annotations_len.
  1754. *
  1755. * The caller must not free the string returned.
  1756. */
  1757. static const char *
  1758. signed_descriptor_get_body_impl(signed_descriptor_t *desc,
  1759. int with_annotations)
  1760. {
  1761. const char *r = NULL;
  1762. size_t len = desc->signed_descriptor_len;
  1763. off_t offset = desc->saved_offset;
  1764. if (with_annotations)
  1765. len += desc->annotations_len;
  1766. else
  1767. offset += desc->annotations_len;
  1768. tor_assert(len > 32);
  1769. if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
  1770. desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
  1771. if (store && store->mmap) {
  1772. tor_assert(desc->saved_offset + len <= store->mmap->size);
  1773. r = store->mmap->data + offset;
  1774. }
  1775. }
  1776. if (!r) /* no mmap, or not in cache. */
  1777. r = desc->signed_descriptor_body +
  1778. (with_annotations ? 0 : desc->annotations_len);
  1779. tor_assert(r);
  1780. if (!with_annotations) {
  1781. if (memcmp("router ", r, 7) && memcmp("extra-info ", r, 11)) {
  1782. log_err(LD_DIR, "descriptor at %p begins with unexpected string %s",
  1783. desc, tor_strndup(r, 64));
  1784. }
  1785. tor_assert(!memcmp("router ", r, 7) || !memcmp("extra-info ", r, 11));
  1786. }
  1787. return r;
  1788. }
  1789. /** Return a pointer to the signed textual representation of a descriptor.
  1790. * The returned string is not guaranteed to be NUL-terminated: the string's
  1791. * length will be in desc-\>signed_descriptor_len.
  1792. *
  1793. * The caller must not free the string returned.
  1794. */
  1795. const char *
  1796. signed_descriptor_get_body(signed_descriptor_t *desc)
  1797. {
  1798. return signed_descriptor_get_body_impl(desc, 0);
  1799. }
  1800. /** Return the current list of all known routers. */
  1801. routerlist_t *
  1802. router_get_routerlist(void)
  1803. {
  1804. if (PREDICT_UNLIKELY(!routerlist)) {
  1805. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  1806. routerlist->routers = smartlist_create();
  1807. routerlist->old_routers = smartlist_create();
  1808. routerlist->identity_map = rimap_new();
  1809. routerlist->desc_digest_map = sdmap_new();
  1810. routerlist->desc_by_eid_map = sdmap_new();
  1811. routerlist->extra_info_map = eimap_new();
  1812. routerlist->desc_store.fname_base = "cached-descriptors";
  1813. routerlist->desc_store.fname_alt_base = "cached-routers";
  1814. routerlist->extrainfo_store.fname_base = "cached-extrainfo";
  1815. routerlist->desc_store.type = ROUTER_STORE;
  1816. routerlist->extrainfo_store.type = EXTRAINFO_STORE;
  1817. routerlist->desc_store.description = "router descriptors";
  1818. routerlist->extrainfo_store.description = "extra-info documents";
  1819. }
  1820. return routerlist;
  1821. }
  1822. /** Free all storage held by <b>router</b>. */
  1823. void
  1824. routerinfo_free(routerinfo_t *router)
  1825. {
  1826. if (!router)
  1827. return;
  1828. tor_free(router->cache_info.signed_descriptor_body);
  1829. tor_free(router->address);
  1830. tor_free(router->nickname);
  1831. tor_free(router->platform);
  1832. tor_free(router->contact_info);
  1833. if (router->onion_pkey)
  1834. crypto_free_pk_env(router->onion_pkey);
  1835. if (router->identity_pkey)
  1836. crypto_free_pk_env(router->identity_pkey);
  1837. if (router->declared_family) {
  1838. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  1839. smartlist_free(router->declared_family);
  1840. }
  1841. addr_policy_free(router->exit_policy);
  1842. /* XXXX020 Remove once 414/417 is fixed. But I have a hunch... */
  1843. memset(router, 77, sizeof(routerinfo_t));
  1844. tor_free(router);
  1845. }
  1846. /** Release all storage held by <b>extrainfo</b> */
  1847. void
  1848. extrainfo_free(extrainfo_t *extrainfo)
  1849. {
  1850. if (!extrainfo)
  1851. return;
  1852. tor_free(extrainfo->cache_info.signed_descriptor_body);
  1853. tor_free(extrainfo->pending_sig);
  1854. /* XXXX020 remove this once more bugs go away. */
  1855. memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
  1856. tor_free(extrainfo);
  1857. }
  1858. /** Release storage held by <b>sd</b>. */
  1859. static void
  1860. signed_descriptor_free(signed_descriptor_t *sd)
  1861. {
  1862. tor_free(sd->signed_descriptor_body);
  1863. /* XXXX020 remove this once more bugs go away. */
  1864. memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
  1865. tor_free(sd);
  1866. }
  1867. /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
  1868. */
  1869. static signed_descriptor_t *
  1870. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  1871. {
  1872. signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  1873. memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
  1874. ri->cache_info.signed_descriptor_body = NULL;
  1875. routerinfo_free(ri);
  1876. return sd;
  1877. }
  1878. /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
  1879. static void
  1880. _extrainfo_free(void *e)
  1881. {
  1882. extrainfo_free(e);
  1883. }
  1884. /** Free all storage held by a routerlist <b>rl</b>. */
  1885. void
  1886. routerlist_free(routerlist_t *rl)
  1887. {
  1888. tor_assert(rl);
  1889. rimap_free(rl->identity_map, NULL);
  1890. sdmap_free(rl->desc_digest_map, NULL);
  1891. sdmap_free(rl->desc_by_eid_map, NULL);
  1892. eimap_free(rl->extra_info_map, _extrainfo_free);
  1893. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1894. routerinfo_free(r));
  1895. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  1896. signed_descriptor_free(sd));
  1897. smartlist_free(rl->routers);
  1898. smartlist_free(rl->old_routers);
  1899. if (routerlist->desc_store.mmap)
  1900. tor_munmap_file(routerlist->desc_store.mmap);
  1901. if (routerlist->extrainfo_store.mmap)
  1902. tor_munmap_file(routerlist->extrainfo_store.mmap);
  1903. tor_free(rl);
  1904. router_dir_info_changed();
  1905. }
  1906. /** DOCDOC */
  1907. void
  1908. dump_routerlist_mem_usage(int severity)
  1909. {
  1910. uint64_t livedescs = 0;
  1911. uint64_t olddescs = 0;
  1912. if (!routerlist)
  1913. return;
  1914. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  1915. livedescs += r->cache_info.signed_descriptor_len);
  1916. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  1917. olddescs += sd->signed_descriptor_len);
  1918. log(severity, LD_GENERAL,
  1919. "In %d live descriptors: "U64_FORMAT" bytes. "
  1920. "In %d old descriptors: "U64_FORMAT" bytes.",
  1921. smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
  1922. smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
  1923. }
  1924. /** Return non-zero if we have a lot of extra descriptors in our
  1925. * routerlist, and should get rid of some of them. Else return 0.
  1926. *
  1927. * We should be careful to not return true too eagerly, since we
  1928. * could churn. By using "+1" below, we make sure this function
  1929. * only returns true at most every smartlist_len(rl-\>routers)
  1930. * new descriptors.
  1931. */
  1932. static INLINE int
  1933. routerlist_is_overfull(routerlist_t *rl)
  1934. {
  1935. /*XXXX020 no longer wholly logical.*/
  1936. if (dirserver_mode(get_options())) {
  1937. return smartlist_len(rl->old_routers) > smartlist_len(rl->routers)*5;
  1938. } else {
  1939. return smartlist_len(rl->old_routers) > smartlist_len(rl->routers)*2;
  1940. }
  1941. }
  1942. static INLINE int
  1943. _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
  1944. {
  1945. if (idx < 0) {
  1946. idx = -1;
  1947. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  1948. if (r == ri) {
  1949. idx = r_sl_idx;
  1950. break;
  1951. });
  1952. } else {
  1953. tor_assert(idx < smartlist_len(sl));
  1954. tor_assert(smartlist_get(sl, idx) == ri);
  1955. };
  1956. return idx;
  1957. }
  1958. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  1959. * as needed. There must be no previous member of <b>rl</b> with the same
  1960. * identity digest as <b>ri</b>: If there is, call routerlist_replace
  1961. * instead.
  1962. */
  1963. static void
  1964. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  1965. {
  1966. routerinfo_t *ri_old;
  1967. {
  1968. /* XXXX020 remove this code once bug 417/404 is fixed. */
  1969. routerinfo_t *ri_generated = router_get_my_routerinfo();
  1970. tor_assert(ri_generated != ri);
  1971. }
  1972. tor_assert(ri->routerlist_index == -1);
  1973. ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  1974. tor_assert(!ri_old);
  1975. sdmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
  1976. &(ri->cache_info));
  1977. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  1978. sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
  1979. &ri->cache_info);
  1980. smartlist_add(rl->routers, ri);
  1981. ri->routerlist_index = smartlist_len(rl->routers) - 1;
  1982. router_dir_info_changed();
  1983. #ifdef DEBUG_ROUTERLIST
  1984. routerlist_assert_ok(rl);
  1985. #endif
  1986. }
  1987. /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
  1988. * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
  1989. * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
  1990. static int
  1991. extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
  1992. {
  1993. int r = 0;
  1994. routerinfo_t *ri = rimap_get(rl->identity_map,
  1995. ei->cache_info.identity_digest);
  1996. signed_descriptor_t *sd;
  1997. extrainfo_t *ei_tmp;
  1998. {
  1999. /* XXXX020 remove this code once bug 417/404 is fixed. */
  2000. extrainfo_t *ei_generated = router_get_my_extrainfo();
  2001. tor_assert(ei_generated != ei);
  2002. }
  2003. if (!ri) {
  2004. /* This router is unknown; we can't even verify the signature. Give up.*/
  2005. goto done;
  2006. }
  2007. if (routerinfo_incompatible_with_extrainfo(ri, ei, NULL)) {
  2008. if (ei->bad_sig) /* If the signature didn't check, it's just wrong. */
  2009. goto done;
  2010. sd = sdmap_get(rl->desc_by_eid_map,
  2011. ei->cache_info.signed_descriptor_digest);
  2012. if (!sd ||
  2013. memcmp(sd->identity_digest, ei->cache_info.identity_digest,
  2014. DIGEST_LEN) ||
  2015. sd->published_on != ei->cache_info.published_on)
  2016. goto done;
  2017. }
  2018. /* Okay, if we make it here, we definitely have a router corresponding to
  2019. * this extrainfo. */
  2020. ei_tmp = eimap_set(rl->extra_info_map,
  2021. ei->cache_info.signed_descriptor_digest,
  2022. ei);
  2023. r = 1;
  2024. if (ei_tmp) {
  2025. rl->extrainfo_store.bytes_dropped +=
  2026. ei_tmp->cache_info.signed_descriptor_len;
  2027. extrainfo_free(ei_tmp);
  2028. }
  2029. done:
  2030. if (r == 0)
  2031. extrainfo_free(ei);
  2032. #ifdef DEBUG_ROUTERLIST
  2033. routerlist_assert_ok(rl);
  2034. #endif
  2035. return r;
  2036. }
  2037. #define should_cache_old_descriptors() dirserver_mode(get_options())
  2038. /** If we're a directory cache and routerlist <b>rl</b> doesn't have
  2039. * a copy of router <b>ri</b> yet, add it to the list of old (not
  2040. * recommended but still served) descriptors. Else free it. */
  2041. static void
  2042. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  2043. {
  2044. {
  2045. /* XXXX020 remove this code once bug 417/404 is fixed. */
  2046. routerinfo_t *ri_generated = router_get_my_routerinfo();
  2047. tor_assert(ri_generated != ri);
  2048. }
  2049. tor_assert(ri->routerlist_index == -1);
  2050. if (should_cache_old_descriptors() &&
  2051. ri->purpose == ROUTER_PURPOSE_GENERAL &&
  2052. !sdmap_get(rl->desc_digest_map,
  2053. ri->cache_info.signed_descriptor_digest)) {
  2054. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  2055. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2056. smartlist_add(rl->old_routers, sd);
  2057. if (!tor_digest_is_zero(sd->extra_info_digest))
  2058. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2059. } else {
  2060. routerinfo_free(ri);
  2061. }
  2062. #ifdef DEBUG_ROUTERLIST
  2063. routerlist_assert_ok(rl);
  2064. #endif
  2065. }
  2066. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  2067. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  2068. * idx) == ri, we don't need to do a linear search over the list to decide
  2069. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  2070. * the list, if any exists. <b>ri</b> is freed.
  2071. *
  2072. * If <b>make_old</b> is true, instead of deleting the router, we try adding
  2073. * it to rl-&gt;old_routers. */
  2074. void
  2075. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old)
  2076. {
  2077. routerinfo_t *ri_tmp;
  2078. extrainfo_t *ei_tmp;
  2079. int idx = ri->routerlist_index;
  2080. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2081. tor_assert(smartlist_get(rl->routers, idx) == ri);
  2082. ri->routerlist_index = -1;
  2083. smartlist_del(rl->routers, idx);
  2084. if (idx < smartlist_len(rl->routers)) {
  2085. routerinfo_t *r = smartlist_get(rl->routers, idx);
  2086. r->routerlist_index = idx;
  2087. }
  2088. ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
  2089. router_dir_info_changed();
  2090. tor_assert(ri_tmp == ri);
  2091. if (make_old && should_cache_old_descriptors() &&
  2092. ri->purpose == ROUTER_PURPOSE_GENERAL) {
  2093. signed_descriptor_t *sd;
  2094. sd = signed_descriptor_from_routerinfo(ri);
  2095. smartlist_add(rl->old_routers, sd);
  2096. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2097. if (!tor_digest_is_zero(sd->extra_info_digest))
  2098. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2099. } else {
  2100. signed_descriptor_t *sd_tmp;
  2101. desc_store_t *store = router_get_store(rl, ri);
  2102. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2103. ri->cache_info.signed_descriptor_digest);
  2104. tor_assert(sd_tmp == &(ri->cache_info));
  2105. if (store)
  2106. store->bytes_dropped += ri->cache_info.signed_descriptor_len;
  2107. ei_tmp = eimap_remove(rl->extra_info_map,
  2108. ri->cache_info.extra_info_digest);
  2109. if (ei_tmp) {
  2110. rl->extrainfo_store.bytes_dropped +=
  2111. ei_tmp->cache_info.signed_descriptor_len;
  2112. extrainfo_free(ei_tmp);
  2113. }
  2114. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2115. sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
  2116. routerinfo_free(ri);
  2117. }
  2118. #ifdef DEBUG_ROUTERLIST
  2119. routerlist_assert_ok(rl);
  2120. #endif
  2121. }
  2122. /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
  2123. * adjust <b>rl</b> as appropriate. <b>idx</i> is -1, or the index of
  2124. * <b>sd</b>. */
  2125. static void
  2126. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  2127. {
  2128. signed_descriptor_t *sd_tmp;
  2129. extrainfo_t *ei_tmp;
  2130. desc_store_t *store;
  2131. tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
  2132. tor_assert(smartlist_get(rl->old_routers, idx) == sd);
  2133. smartlist_del(rl->old_routers, idx);
  2134. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2135. sd->signed_descriptor_digest);
  2136. tor_assert(sd_tmp == sd);
  2137. store = desc_get_store(rl, sd);
  2138. if (store)
  2139. store->bytes_dropped += sd->signed_descriptor_len;
  2140. ei_tmp = eimap_remove(rl->extra_info_map,
  2141. sd->extra_info_digest);
  2142. if (ei_tmp) {
  2143. rl->extrainfo_store.bytes_dropped +=
  2144. ei_tmp->cache_info.signed_descriptor_len;
  2145. extrainfo_free(ei_tmp);
  2146. }
  2147. if (!tor_digest_is_zero(sd->extra_info_digest))
  2148. sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
  2149. signed_descriptor_free(sd);
  2150. #ifdef DEBUG_ROUTERLIST
  2151. routerlist_assert_ok(rl);
  2152. #endif
  2153. }
  2154. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  2155. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  2156. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  2157. * search over the list to decide which to remove. We put ri_new in the same
  2158. * index as ri_old, if possible. ri is freed as appropriate.
  2159. *
  2160. * If <b>make_old</b> is true, instead of deleting the router, we try adding
  2161. * it to rl-&gt;old_routers. */
  2162. static void
  2163. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  2164. routerinfo_t *ri_new)
  2165. {
  2166. int idx;
  2167. routerinfo_t *ri_tmp;
  2168. extrainfo_t *ei_tmp;
  2169. {
  2170. /* XXXX020 remove this code once bug 417/404 is fixed. */
  2171. routerinfo_t *ri_generated = router_get_my_routerinfo();
  2172. tor_assert(ri_generated != ri_new);
  2173. }
  2174. tor_assert(ri_old != ri_new);
  2175. tor_assert(ri_new->routerlist_index == -1);
  2176. idx = ri_old->routerlist_index;
  2177. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2178. tor_assert(smartlist_get(rl->routers, idx) == ri_old);
  2179. router_dir_info_changed();
  2180. if (idx >= 0) {
  2181. smartlist_set(rl->routers, idx, ri_new);
  2182. ri_old->routerlist_index = -1;
  2183. ri_new->routerlist_index = idx;
  2184. /* Check that ri_old is not in rl->routers anymore: */
  2185. tor_assert( _routerlist_find_elt(rl->routers, ri_old, -1) == -1 );
  2186. } else {
  2187. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  2188. routerlist_insert(rl, ri_new);
  2189. return;
  2190. }
  2191. if (memcmp(ri_old->cache_info.identity_digest,
  2192. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  2193. /* digests don't match; digestmap_set won't replace */
  2194. rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  2195. }
  2196. ri_tmp = rimap_set(rl->identity_map,
  2197. ri_new->cache_info.identity_digest, ri_new);
  2198. tor_assert(!ri_tmp || ri_tmp == ri_old);
  2199. sdmap_set(rl->desc_digest_map,
  2200. ri_new->cache_info.signed_descriptor_digest,
  2201. &(ri_new->cache_info));
  2202. if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
  2203. sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
  2204. &ri_new->cache_info);
  2205. }
  2206. if (should_cache_old_descriptors() &&
  2207. ri_old->purpose == ROUTER_PURPOSE_GENERAL) {
  2208. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  2209. smartlist_add(rl->old_routers, sd);
  2210. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2211. if (!tor_digest_is_zero(sd->extra_info_digest))
  2212. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2213. } else {
  2214. desc_store_t *store;
  2215. if (memcmp(ri_old->cache_info.signed_descriptor_digest,
  2216. ri_new->cache_info.signed_descriptor_digest,
  2217. DIGEST_LEN)) {
  2218. /* digests don't match; digestmap_set didn't replace */
  2219. sdmap_remove(rl->desc_digest_map,
  2220. ri_old->cache_info.signed_descriptor_digest);
  2221. }
  2222. ei_tmp = eimap_remove(rl->extra_info_map,
  2223. ri_old->cache_info.extra_info_digest);
  2224. if (ei_tmp) {
  2225. rl->extrainfo_store.bytes_dropped +=
  2226. ei_tmp->cache_info.signed_descriptor_len;
  2227. extrainfo_free(ei_tmp);
  2228. }
  2229. if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
  2230. sdmap_remove(rl->desc_by_eid_map,
  2231. ri_old->cache_info.extra_info_digest);
  2232. }
  2233. store = router_get_store(rl, ri_old);
  2234. if (store)
  2235. store->bytes_dropped += ri_old->cache_info.signed_descriptor_len;
  2236. routerinfo_free(ri_old);
  2237. }
  2238. #ifdef DEBUG_ROUTERLIST
  2239. routerlist_assert_ok(rl);
  2240. #endif
  2241. }
  2242. /** Free all memory held by the routerlist module. */
  2243. void
  2244. routerlist_free_all(void)
  2245. {
  2246. if (routerlist)
  2247. routerlist_free(routerlist);
  2248. routerlist = NULL;
  2249. if (warned_nicknames) {
  2250. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2251. smartlist_free(warned_nicknames);
  2252. warned_nicknames = NULL;
  2253. }
  2254. if (trusted_dir_servers) {
  2255. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2256. trusted_dir_server_free(ds));
  2257. smartlist_free(trusted_dir_servers);
  2258. trusted_dir_servers = NULL;
  2259. }
  2260. }
  2261. /** Forget that we have issued any router-related warnings, so that we'll
  2262. * warn again if we see the same errors. */
  2263. void
  2264. routerlist_reset_warnings(void)
  2265. {
  2266. if (!warned_nicknames)
  2267. warned_nicknames = smartlist_create();
  2268. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2269. smartlist_clear(warned_nicknames); /* now the list is empty. */
  2270. networkstatus_reset_warnings();
  2271. }
  2272. /** Mark the router with ID <b>digest</b> as running or non-running
  2273. * in our routerlist. */
  2274. void
  2275. router_set_status(const char *digest, int up)
  2276. {
  2277. routerinfo_t *router;
  2278. routerstatus_t *status;
  2279. tor_assert(digest);
  2280. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  2281. if (!memcmp(d->digest, digest, DIGEST_LEN))
  2282. d->is_running = up);
  2283. router = router_get_by_digest(digest);
  2284. if (router) {
  2285. log_debug(LD_DIR,"Marking router '%s' as %s.",
  2286. router->nickname, up ? "up" : "down");
  2287. if (!up && router_is_me(router) && !we_are_hibernating())
  2288. log_warn(LD_NET, "We just marked ourself as down. Are your external "
  2289. "addresses reachable?");
  2290. router->is_running = up;
  2291. }
  2292. status = router_get_consensus_status_by_id(digest);
  2293. if (status && status->is_running != up) {
  2294. status->is_running = up;
  2295. control_event_networkstatus_changed_single(status);
  2296. }
  2297. router_dir_info_changed();
  2298. }
  2299. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  2300. * older entries (if any) with the same key. Note: Callers should not hold
  2301. * their pointers to <b>router</b> if this function fails; <b>router</b>
  2302. * will either be inserted into the routerlist or freed. Similarly, even
  2303. * if this call succeeds, they should not hold their pointers to
  2304. * <b>router</b> after subsequent calls with other routerinfo's -- they
  2305. * might cause the original routerinfo to get freed.
  2306. *
  2307. * Returns >= 0 if the router was added; less than 0 if it was not.
  2308. *
  2309. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  2310. * describing the reason for not liking the routerinfo.
  2311. *
  2312. * If the return value is less than -1, there was a problem with the
  2313. * routerinfo. If the return value is equal to -1, then the routerinfo was
  2314. * fine, but out-of-date. If the return value is equal to 1, the
  2315. * routerinfo was accepted, but we should notify the generator of the
  2316. * descriptor using the message *<b>msg</b>.
  2317. *
  2318. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  2319. * <b>from_fetch</b>, we received it in response to a request we made.
  2320. * (If both are false, that means it was uploaded to us as an auth dir
  2321. * server or via the controller.)
  2322. *
  2323. * This function should be called *after*
  2324. * routers_update_status_from_consensus_networkstatus; subsequently, you
  2325. * should call router_rebuild_store and routerlist_descriptors_added.
  2326. */
  2327. int
  2328. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  2329. int from_cache, int from_fetch)
  2330. {
  2331. const char *id_digest;
  2332. int authdir = authdir_mode(get_options());
  2333. int authdir_believes_valid = 0;
  2334. routerinfo_t *old_router;
  2335. /* router_have_minimum_dir_info() has side effects, so do it before we
  2336. * start the real work */
  2337. int authdir_may_warn_about_unreachable_server =
  2338. authdir && !from_cache && !from_fetch &&
  2339. router_have_minimum_dir_info();
  2340. networkstatus_vote_t *consensus = networkstatus_get_latest_consensus();
  2341. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  2342. int in_consensus = 0;
  2343. tor_assert(msg);
  2344. if (!routerlist)
  2345. router_get_routerlist();
  2346. id_digest = router->cache_info.identity_digest;
  2347. /* Make sure that we haven't already got this exact descriptor. */
  2348. if (sdmap_get(routerlist->desc_digest_map,
  2349. router->cache_info.signed_descriptor_digest)) {
  2350. log_info(LD_DIR,
  2351. "Dropping descriptor that we already have for router '%s'",
  2352. router->nickname);
  2353. *msg = "Router descriptor was not new.";
  2354. routerinfo_free(router);
  2355. return -1;
  2356. }
  2357. if (routerlist_is_overfull(routerlist))
  2358. routerlist_remove_old_routers();
  2359. if (authdir) {
  2360. if (authdir_wants_to_reject_router(router, msg,
  2361. !from_cache && !from_fetch)) {
  2362. tor_assert(*msg);
  2363. routerinfo_free(router);
  2364. return -2;
  2365. }
  2366. authdir_believes_valid = router->is_valid;
  2367. } else if (from_fetch) {
  2368. /* Only check the descriptor digest against the network statuses when
  2369. * we are receiving in response to a fetch. */
  2370. if (!signed_desc_digest_is_recognized(&router->cache_info) &&
  2371. !routerinfo_is_a_configured_bridge(router)) {
  2372. /* We asked for it, so some networkstatus must have listed it when we
  2373. * did. Save it if we're a cache in case somebody else asks for it. */
  2374. log_info(LD_DIR,
  2375. "Received a no-longer-recognized descriptor for router '%s'",
  2376. router->nickname);
  2377. *msg = "Router descriptor is not referenced by any network-status.";
  2378. /* Only journal this desc if we'll be serving it. */
  2379. if (!from_cache && should_cache_old_descriptors())
  2380. signed_desc_append_to_journal(&router->cache_info,
  2381. router_get_store(routerlist, router));
  2382. routerlist_insert_old(routerlist, router);
  2383. return -1;
  2384. }
  2385. }
  2386. /* We no longer need a router with this descriptor digest. */
  2387. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  2388. {
  2389. routerstatus_t *rs =
  2390. networkstatus_v2_find_entry(ns, router->cache_info.identity_digest);
  2391. if (rs && !memcmp(rs->descriptor_digest,
  2392. router->cache_info.signed_descriptor_digest,
  2393. DIGEST_LEN))
  2394. rs->need_to_mirror = 0;
  2395. });
  2396. if (consensus) {
  2397. routerstatus_t *rs = networkstatus_vote_find_entry(consensus,
  2398. router->cache_info.identity_digest);
  2399. if (rs && !memcmp(rs->descriptor_digest,
  2400. router->cache_info.signed_descriptor_digest,
  2401. DIGEST_LEN)) {
  2402. in_consensus = 1;
  2403. rs->need_to_mirror = 0;
  2404. }
  2405. }
  2406. /*XXXX020 I had suspicions about whether this was correct, but now I
  2407. * can't remember why. :( -NM */
  2408. if (consensus && !in_consensus && !authdir_mode(get_options())) {
  2409. /* If it's not listed in the consensus, then don't consider replacing
  2410. * the latest router with it. */
  2411. if (!from_cache && should_cache_old_descriptors())
  2412. signed_desc_append_to_journal(&router->cache_info,
  2413. router_get_store(routerlist, router));
  2414. routerlist_insert_old(routerlist, router);
  2415. return -1;
  2416. }
  2417. /* If we have a router with the same identity key, choose the newer one. */
  2418. old_router = rimap_get(routerlist->identity_map,
  2419. router->cache_info.identity_digest);
  2420. if (old_router) {
  2421. if (router->cache_info.published_on <=
  2422. old_router->cache_info.published_on) {
  2423. /* Same key, but old */
  2424. log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
  2425. router->nickname);
  2426. /* Only journal this desc if we'll be serving it. */
  2427. if (!from_cache && should_cache_old_descriptors())
  2428. signed_desc_append_to_journal(&router->cache_info,
  2429. router_get_store(routerlist, router));
  2430. routerlist_insert_old(routerlist, router);
  2431. *msg = "Router descriptor was not new.";
  2432. return -1;
  2433. } else {
  2434. /* Same key, new. */
  2435. int unreachable = 0;
  2436. log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
  2437. router->nickname, old_router->nickname,
  2438. hex_str(id_digest,DIGEST_LEN));
  2439. if (router->addr == old_router->addr &&
  2440. router->or_port == old_router->or_port) {
  2441. /* these carry over when the address and orport are unchanged.*/
  2442. router->last_reachable = old_router->last_reachable;
  2443. router->testing_since = old_router->testing_since;
  2444. router->num_unreachable_notifications =
  2445. old_router->num_unreachable_notifications;
  2446. }
  2447. if (authdir_may_warn_about_unreachable_server &&
  2448. dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
  2449. if (router->num_unreachable_notifications >= 3) {
  2450. unreachable = 1;
  2451. log_notice(LD_DIR, "Notifying server '%s' that it's unreachable. "
  2452. "(ContactInfo '%s', platform '%s').",
  2453. router->nickname,
  2454. router->contact_info ? router->contact_info : "",
  2455. router->platform ? router->platform : "");
  2456. } else {
  2457. log_info(LD_DIR,"'%s' may be unreachable -- the %d previous "
  2458. "descriptors were thought to be unreachable.",
  2459. router->nickname, router->num_unreachable_notifications);
  2460. router->num_unreachable_notifications++;
  2461. }
  2462. }
  2463. routerlist_replace(routerlist, old_router, router);
  2464. if (!from_cache) {
  2465. signed_desc_append_to_journal(&router->cache_info,
  2466. router_get_store(routerlist, router));
  2467. }
  2468. directory_set_dirty();
  2469. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  2470. authdir_believes_valid ? "Valid server updated" :
  2471. ("Invalid server updated. (This dirserver is marking your "
  2472. "server as unapproved.)");
  2473. return unreachable ? 1 : 0;
  2474. }
  2475. }
  2476. /* We haven't seen a router with this identity before. Add it to the end of
  2477. * the list. */
  2478. routerlist_insert(routerlist, router);
  2479. if (!from_cache)
  2480. signed_desc_append_to_journal(&router->cache_info,
  2481. router_get_store(routerlist, router));
  2482. directory_set_dirty();
  2483. return 0;
  2484. }
  2485. /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
  2486. * as for router_add_to_routerlist(). */
  2487. void
  2488. router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
  2489. int from_cache, int from_fetch)
  2490. {
  2491. int inserted;
  2492. (void)from_fetch;
  2493. if (msg) *msg = NULL;
  2494. inserted = extrainfo_insert(router_get_routerlist(), ei);
  2495. if (inserted && !from_cache)
  2496. signed_desc_append_to_journal(&ei->cache_info,
  2497. &routerlist->extrainfo_store);
  2498. }
  2499. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  2500. * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
  2501. * to, or later than that of *<b>b</b>. */
  2502. static int
  2503. _compare_old_routers_by_identity(const void **_a, const void **_b)
  2504. {
  2505. int i;
  2506. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  2507. if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  2508. return i;
  2509. return r1->published_on - r2->published_on;
  2510. }
  2511. /** Internal type used to represent how long an old descriptor was valid,
  2512. * where it appeared in the list of old descriptors, and whether it's extra
  2513. * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
  2514. struct duration_idx_t {
  2515. int duration;
  2516. int idx;
  2517. int old;
  2518. };
  2519. /** Sorting helper: compare two duration_idx_t by their duration. */
  2520. static int
  2521. _compare_duration_idx(const void *_d1, const void *_d2)
  2522. {
  2523. const struct duration_idx_t *d1 = _d1;
  2524. const struct duration_idx_t *d2 = _d2;
  2525. return d1->duration - d2->duration;
  2526. }
  2527. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  2528. * must contain routerinfo_t with the same identity and with publication time
  2529. * in ascending order. Remove members from this range until there are no more
  2530. * than max_descriptors_per_router() remaining. Start by removing the oldest
  2531. * members from before <b>cutoff</b>, then remove members which were current
  2532. * for the lowest amount of time. The order of members of old_routers at
  2533. * indices <b>lo</b> or higher may be changed.
  2534. */
  2535. static void
  2536. routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi,
  2537. digestmap_t *retain)
  2538. {
  2539. int i, n = hi-lo+1;
  2540. unsigned n_extra, n_rmv = 0;
  2541. struct duration_idx_t *lifespans;
  2542. uint8_t *rmv, *must_keep;
  2543. smartlist_t *lst = routerlist->old_routers;
  2544. #if 1
  2545. const char *ident;
  2546. tor_assert(hi < smartlist_len(lst));
  2547. tor_assert(lo <= hi);
  2548. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  2549. for (i = lo+1; i <= hi; ++i) {
  2550. signed_descriptor_t *r = smartlist_get(lst, i);
  2551. tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
  2552. }
  2553. #endif
  2554. /* Check whether we need to do anything at all. */
  2555. {
  2556. int mdpr = dirserver_mode(get_options()) ? 5 : 2;
  2557. if (n <= mdpr)
  2558. return;
  2559. n_extra = n - mdpr;
  2560. }
  2561. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  2562. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  2563. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  2564. /* Set lifespans to contain the lifespan and index of each server. */
  2565. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  2566. for (i = lo; i <= hi; ++i) {
  2567. signed_descriptor_t *r = smartlist_get(lst, i);
  2568. signed_descriptor_t *r_next;
  2569. lifespans[i-lo].idx = i;
  2570. if (retain && digestmap_get(retain, r->signed_descriptor_digest)) {
  2571. must_keep[i-lo] = 1;
  2572. }
  2573. if (i < hi) {
  2574. r_next = smartlist_get(lst, i+1);
  2575. tor_assert(r->published_on <= r_next->published_on);
  2576. lifespans[i-lo].duration = (r_next->published_on - r->published_on);
  2577. } else {
  2578. r_next = NULL;
  2579. lifespans[i-lo].duration = INT_MAX;
  2580. }
  2581. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  2582. ++n_rmv;
  2583. lifespans[i-lo].old = 1;
  2584. rmv[i-lo] = 1;
  2585. }
  2586. }
  2587. if (n_rmv < n_extra) {
  2588. /**
  2589. * We aren't removing enough servers for being old. Sort lifespans by
  2590. * the duration of liveness, and remove the ones we're not already going to
  2591. * remove based on how long they were alive.
  2592. **/
  2593. qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
  2594. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  2595. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  2596. rmv[lifespans[i].idx-lo] = 1;
  2597. ++n_rmv;
  2598. }
  2599. }
  2600. }
  2601. i = hi;
  2602. do {
  2603. if (rmv[i-lo])
  2604. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  2605. } while (--i >= lo);
  2606. tor_free(must_keep);
  2607. tor_free(rmv);
  2608. tor_free(lifespans);
  2609. }
  2610. /** Deactivate any routers from the routerlist that are more than
  2611. * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
  2612. * remove old routers from the list of cached routers if we have too many.
  2613. */
  2614. void
  2615. routerlist_remove_old_routers(void)
  2616. {
  2617. int i, hi=-1;
  2618. const char *cur_id = NULL;
  2619. time_t now = time(NULL);
  2620. time_t cutoff;
  2621. routerinfo_t *router;
  2622. signed_descriptor_t *sd;
  2623. digestmap_t *retain;
  2624. int dirserv = dirserver_mode(get_options());
  2625. const networkstatus_vote_t *consensus = networkstatus_get_latest_consensus();
  2626. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  2627. trusted_dirs_remove_old_certs();
  2628. if (!routerlist || !consensus)
  2629. return;
  2630. routerlist_assert_ok(routerlist);
  2631. retain = digestmap_new();
  2632. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  2633. /* Build a list of all the descriptors that _anybody_ lists. */
  2634. if (dirserv) {
  2635. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  2636. {
  2637. /* XXXX The inner loop here gets pretty expensive, and actually shows up
  2638. * on some profiles. It may be the reason digestmap_set shows up in
  2639. * profiles too. If instead we kept a per-descriptor digest count of
  2640. * how many networkstatuses recommended each descriptor, and changed
  2641. * that only when the networkstatuses changed, that would be a speed
  2642. * improvement, possibly 1-4% if it also removes digestmap_set from the
  2643. * profile. Not worth it for 0.1.2.x, though. The new directory
  2644. * system will obsolete this whole thing in 0.2.0.x. */
  2645. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  2646. if (rs->published_on >= cutoff)
  2647. digestmap_set(retain, rs->descriptor_digest, (void*)1));
  2648. });
  2649. }
  2650. /* Retain anything listed in the consensus. */
  2651. if (consensus) {
  2652. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
  2653. if (rs->published_on >= cutoff)
  2654. digestmap_set(retain, rs->descriptor_digest, (void*)1));
  2655. }
  2656. /* If we have a bunch of networkstatuses, we should consider pruning current
  2657. * routers that are too old and that nobody recommends. (If we don't have
  2658. * enough networkstatuses, then we should get more before we decide to kill
  2659. * routers.) */
  2660. if (!dirserv ||
  2661. smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2) {
  2662. cutoff = now - ROUTER_MAX_AGE;
  2663. /* Remove too-old unrecommended members of routerlist->routers. */
  2664. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  2665. router = smartlist_get(routerlist->routers, i);
  2666. if (router->cache_info.published_on <= cutoff &&
  2667. !digestmap_get(retain,router->cache_info.signed_descriptor_digest)) {
  2668. /* Too old: remove it. (If we're a cache, just move it into
  2669. * old_routers.) */
  2670. log_info(LD_DIR,
  2671. "Forgetting obsolete (too old) routerinfo for router '%s'",
  2672. router->nickname);
  2673. routerlist_remove(routerlist, router, 1);
  2674. i--;
  2675. }
  2676. }
  2677. }
  2678. routerlist_assert_ok(routerlist);
  2679. /* Remove far-too-old members of routerlist->old_routers. */
  2680. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  2681. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  2682. sd = smartlist_get(routerlist->old_routers, i);
  2683. if (sd->published_on <= cutoff &&
  2684. !digestmap_get(retain, sd->signed_descriptor_digest)) {
  2685. /* Too old. Remove it. */
  2686. routerlist_remove_old(routerlist, sd, i--);
  2687. }
  2688. }
  2689. routerlist_assert_ok(routerlist);
  2690. /* Now we might have to look at routerlist->old_routers for extraneous
  2691. * members. (We'd keep all the members if we could, but we need to save
  2692. * space.) First, check whether we have too many router descriptors, total.
  2693. * We're okay with having too many for some given router, so long as the
  2694. * total number doesn't approach max_descriptors_per_router()*len(router).
  2695. */
  2696. if (smartlist_len(routerlist->old_routers) <
  2697. smartlist_len(routerlist->routers) * (dirserver_mode(get_options())?4:2))
  2698. goto done;
  2699. smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
  2700. /* Iterate through the list from back to front, so when we remove descriptors
  2701. * we don't mess up groups we haven't gotten to. */
  2702. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  2703. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  2704. if (!cur_id) {
  2705. cur_id = r->identity_digest;
  2706. hi = i;
  2707. }
  2708. if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
  2709. routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi, retain);
  2710. cur_id = r->identity_digest;
  2711. hi = i;
  2712. }
  2713. }
  2714. if (hi>=0)
  2715. routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi, retain);
  2716. routerlist_assert_ok(routerlist);
  2717. done:
  2718. digestmap_free(retain, NULL);
  2719. }
  2720. /** We just added a new descriptor that isn't of purpose
  2721. * ROUTER_PURPOSE_GENERAL. Take whatever extra steps we need. */
  2722. static void
  2723. routerlist_descriptors_added(smartlist_t *sl)
  2724. {
  2725. tor_assert(sl);
  2726. control_event_descriptors_changed(sl);
  2727. SMARTLIST_FOREACH(sl, routerinfo_t *, ri,
  2728. if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
  2729. learned_bridge_descriptor(ri);
  2730. );
  2731. }
  2732. /**
  2733. * Code to parse a single router descriptor and insert it into the
  2734. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  2735. * descriptor was well-formed but could not be added; and 1 if the
  2736. * descriptor was added.
  2737. *
  2738. * If we don't add it and <b>msg</b> is not NULL, then assign to
  2739. * *<b>msg</b> a static string describing the reason for refusing the
  2740. * descriptor.
  2741. *
  2742. * This is used only by the controller.
  2743. */
  2744. int
  2745. router_load_single_router(const char *s, uint8_t purpose, int cache,
  2746. const char **msg)
  2747. {
  2748. routerinfo_t *ri;
  2749. int r;
  2750. smartlist_t *lst;
  2751. char annotation_buf[256];
  2752. tor_assert(msg);
  2753. *msg = NULL;
  2754. tor_snprintf(annotation_buf, sizeof(annotation_buf),
  2755. "@source controller\n"
  2756. "@purpose %s\n", router_purpose_to_string(purpose));
  2757. if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
  2758. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  2759. *msg = "Couldn't parse router descriptor.";
  2760. return -1;
  2761. }
  2762. tor_assert(ri->purpose == purpose);
  2763. if (router_is_me(ri)) {
  2764. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  2765. *msg = "Router's identity key matches mine.";
  2766. routerinfo_free(ri);
  2767. return 0;
  2768. }
  2769. if (!cache) /* obey the preference of the controller */
  2770. ri->cache_info.do_not_cache = 1;
  2771. lst = smartlist_create();
  2772. smartlist_add(lst, ri);
  2773. routers_update_status_from_consensus_networkstatus(lst, 0);
  2774. if ((r=router_add_to_routerlist(ri, msg, 0, 0))<0) {
  2775. /* we've already assigned to *msg now, and ri is already freed */
  2776. tor_assert(*msg);
  2777. if (r < -1)
  2778. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  2779. smartlist_free(lst);
  2780. return 0;
  2781. } else {
  2782. routerlist_descriptors_added(lst);
  2783. smartlist_free(lst);
  2784. log_debug(LD_DIR, "Added router to list");
  2785. return 1;
  2786. }
  2787. }
  2788. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  2789. * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
  2790. * are in response to a query to the network: cache them by adding them to
  2791. * the journal.
  2792. *
  2793. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  2794. * uppercased fingerprints. Do not update any router whose
  2795. * fingerprint is not on the list; after updating a router, remove its
  2796. * fingerprint from the list.
  2797. *
  2798. * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
  2799. * are descriptor digests. Otherwise they are identity digests.
  2800. */
  2801. void
  2802. router_load_routers_from_string(const char *s, const char *eos,
  2803. saved_location_t saved_location,
  2804. smartlist_t *requested_fingerprints,
  2805. int descriptor_digests,
  2806. const char *prepend_annotations)
  2807. {
  2808. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  2809. char fp[HEX_DIGEST_LEN+1];
  2810. const char *msg;
  2811. int from_cache = (saved_location != SAVED_NOWHERE);
  2812. int allow_annotations = (saved_location != SAVED_NOWHERE);
  2813. router_parse_list_from_string(&s, eos, routers, saved_location, 0,
  2814. allow_annotations, prepend_annotations);
  2815. routers_update_status_from_consensus_networkstatus(routers, !from_cache);
  2816. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  2817. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  2818. {
  2819. if (requested_fingerprints) {
  2820. base16_encode(fp, sizeof(fp), descriptor_digests ?
  2821. ri->cache_info.signed_descriptor_digest :
  2822. ri->cache_info.identity_digest,
  2823. DIGEST_LEN);
  2824. if (smartlist_string_isin(requested_fingerprints, fp)) {
  2825. smartlist_string_remove(requested_fingerprints, fp);
  2826. } else {
  2827. char *requested =
  2828. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  2829. log_warn(LD_DIR,
  2830. "We received a router descriptor with a fingerprint (%s) "
  2831. "that we never requested. (We asked for: %s.) Dropping.",
  2832. fp, requested);
  2833. tor_free(requested);
  2834. routerinfo_free(ri);
  2835. continue;
  2836. }
  2837. }
  2838. if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0) {
  2839. smartlist_add(changed, ri);
  2840. routerlist_descriptors_added(changed);
  2841. smartlist_clear(changed);
  2842. }
  2843. });
  2844. routerlist_assert_ok(routerlist);
  2845. router_rebuild_store(0, &routerlist->desc_store);
  2846. smartlist_free(routers);
  2847. smartlist_free(changed);
  2848. }
  2849. /** Parse one or more extrainfos from <b>s</b> (ending immediately before
  2850. * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
  2851. * router_load_routers_from_string(). */
  2852. void
  2853. router_load_extrainfo_from_string(const char *s, const char *eos,
  2854. saved_location_t saved_location,
  2855. smartlist_t *requested_fingerprints,
  2856. int descriptor_digests)
  2857. {
  2858. smartlist_t *extrainfo_list = smartlist_create();
  2859. const char *msg;
  2860. int from_cache = (saved_location != SAVED_NOWHERE);
  2861. router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
  2862. NULL);
  2863. log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
  2864. SMARTLIST_FOREACH(extrainfo_list, extrainfo_t *, ei, {
  2865. if (requested_fingerprints) {
  2866. char fp[HEX_DIGEST_LEN+1];
  2867. base16_encode(fp, sizeof(fp), descriptor_digests ?
  2868. ei->cache_info.signed_descriptor_digest :
  2869. ei->cache_info.identity_digest,
  2870. DIGEST_LEN);
  2871. smartlist_string_remove(requested_fingerprints, fp);
  2872. /* XXX020 We silently let people stuff us with extrainfos we
  2873. * didn't ask for. Is this a problem? -RD */
  2874. }
  2875. router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
  2876. });
  2877. routerlist_assert_ok(routerlist);
  2878. router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
  2879. smartlist_free(extrainfo_list);
  2880. }
  2881. /** Return true iff any networkstatus includes a descriptor whose digest
  2882. * is that of <b>desc</b>. */
  2883. static int
  2884. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  2885. {
  2886. routerstatus_t *rs;
  2887. networkstatus_vote_t *consensus = networkstatus_get_latest_consensus();
  2888. int dirserv = dirserver_mode(get_options());
  2889. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  2890. if (consensus) {
  2891. rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
  2892. if (rs && !memcmp(rs->descriptor_digest,
  2893. desc->signed_descriptor_digest, DIGEST_LEN))
  2894. return 1;
  2895. }
  2896. if (dirserv && networkstatus_v2_list) {
  2897. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  2898. {
  2899. if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
  2900. continue;
  2901. if (!memcmp(rs->descriptor_digest,
  2902. desc->signed_descriptor_digest, DIGEST_LEN))
  2903. return 1;
  2904. });
  2905. }
  2906. return 0;
  2907. }
  2908. /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
  2909. * give it all a try again. */
  2910. void
  2911. routerlist_retry_directory_downloads(time_t now)
  2912. {
  2913. router_reset_status_download_failures();
  2914. router_reset_descriptor_download_failures();
  2915. update_networkstatus_downloads(now);
  2916. update_router_descriptor_downloads(now);
  2917. }
  2918. /** Return 1 if all running sufficiently-stable routers will reject
  2919. * addr:port, return 0 if any might accept it. */
  2920. int
  2921. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  2922. int need_uptime)
  2923. {
  2924. addr_policy_result_t r;
  2925. if (!routerlist) return 1;
  2926. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  2927. {
  2928. if (router->is_running &&
  2929. !router_is_unreliable(router, need_uptime, 0, 0)) {
  2930. r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
  2931. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2932. return 0; /* this one could be ok. good enough. */
  2933. }
  2934. });
  2935. return 1; /* all will reject. */
  2936. }
  2937. /** Return true iff <b>router</b> does not permit exit streams.
  2938. */
  2939. int
  2940. router_exit_policy_rejects_all(routerinfo_t *router)
  2941. {
  2942. return compare_addr_to_addr_policy(0, 0, router->exit_policy)
  2943. == ADDR_POLICY_REJECTED;
  2944. }
  2945. /** Add to the list of authorized directory servers one at
  2946. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  2947. * <b>address</b> is NULL, add ourself. */
  2948. void
  2949. add_trusted_dir_server(const char *nickname, const char *address,
  2950. uint16_t dir_port, uint16_t or_port,
  2951. const char *digest, const char *v3_auth_digest,
  2952. authority_type_t type)
  2953. {
  2954. trusted_dir_server_t *ent;
  2955. uint32_t a;
  2956. char *hostname = NULL;
  2957. size_t dlen;
  2958. if (!trusted_dir_servers)
  2959. trusted_dir_servers = smartlist_create();
  2960. if (!address) { /* The address is us; we should guess. */
  2961. if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
  2962. log_warn(LD_CONFIG,
  2963. "Couldn't find a suitable address when adding ourself as a "
  2964. "trusted directory server.");
  2965. return;
  2966. }
  2967. } else {
  2968. if (tor_lookup_hostname(address, &a)) {
  2969. log_warn(LD_CONFIG,
  2970. "Unable to lookup address for directory server at '%s'",
  2971. address);
  2972. return;
  2973. }
  2974. hostname = tor_strdup(address);
  2975. }
  2976. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  2977. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  2978. ent->address = hostname;
  2979. ent->addr = a;
  2980. ent->dir_port = dir_port;
  2981. ent->or_port = or_port;
  2982. ent->is_running = 1;
  2983. ent->type = type;
  2984. memcpy(ent->digest, digest, DIGEST_LEN);
  2985. if (v3_auth_digest && (type & V3_AUTHORITY))
  2986. memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
  2987. dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
  2988. ent->description = tor_malloc(dlen);
  2989. if (nickname)
  2990. tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
  2991. nickname, hostname, (int)dir_port);
  2992. else
  2993. tor_snprintf(ent->description, dlen, "directory server at %s:%d",
  2994. hostname, (int)dir_port);
  2995. ent->fake_status.addr = ent->addr;
  2996. memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  2997. if (nickname)
  2998. strlcpy(ent->fake_status.nickname, nickname,
  2999. sizeof(ent->fake_status.nickname));
  3000. else
  3001. ent->fake_status.nickname[0] = '\0';
  3002. ent->fake_status.dir_port = ent->dir_port;
  3003. ent->fake_status.or_port = ent->or_port;
  3004. if (ent->or_port)
  3005. ent->fake_status.version_supports_begindir = 1;
  3006. smartlist_add(trusted_dir_servers, ent);
  3007. router_dir_info_changed();
  3008. }
  3009. /** Free storage held in <b>ds</b>. */
  3010. static void
  3011. trusted_dir_server_free(trusted_dir_server_t *ds)
  3012. {
  3013. if (ds->v3_certs) {
  3014. SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
  3015. authority_cert_free(cert));
  3016. smartlist_free(ds->v3_certs);
  3017. }
  3018. tor_free(ds->nickname);
  3019. tor_free(ds->description);
  3020. tor_free(ds->address);
  3021. tor_free(ds);
  3022. }
  3023. /** Remove all members from the list of trusted dir servers. */
  3024. void
  3025. clear_trusted_dir_servers(void)
  3026. {
  3027. if (trusted_dir_servers) {
  3028. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  3029. trusted_dir_server_free(ent));
  3030. smartlist_clear(trusted_dir_servers);
  3031. } else {
  3032. trusted_dir_servers = smartlist_create();
  3033. }
  3034. router_dir_info_changed();
  3035. }
  3036. /** Return 1 if any trusted dir server supports v1 directories,
  3037. * else return 0. */
  3038. int
  3039. any_trusted_dir_is_v1_authority(void)
  3040. {
  3041. if (trusted_dir_servers)
  3042. return get_n_authorities(V1_AUTHORITY) > 0;
  3043. return 0;
  3044. }
  3045. /** DOCDOC */
  3046. static void
  3047. list_pending_downloads(digestmap_t *result,
  3048. int purpose, const char *prefix)
  3049. {
  3050. const size_t p_len = strlen(prefix);
  3051. smartlist_t *tmp = smartlist_create();
  3052. smartlist_t *conns = get_connection_array();
  3053. tor_assert(result);
  3054. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3055. {
  3056. if (conn->type == CONN_TYPE_DIR &&
  3057. conn->purpose == purpose &&
  3058. !conn->marked_for_close) {
  3059. const char *resource = TO_DIR_CONN(conn)->requested_resource;
  3060. if (!strcmpstart(resource, prefix))
  3061. dir_split_resource_into_fingerprints(resource + p_len,
  3062. tmp, NULL, 1, 0);
  3063. }
  3064. });
  3065. SMARTLIST_FOREACH(tmp, char *, d,
  3066. {
  3067. digestmap_set(result, d, (void*)1);
  3068. tor_free(d);
  3069. });
  3070. smartlist_free(tmp);
  3071. }
  3072. /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
  3073. * true) we are currently downloading by descriptor digest, set result[d] to
  3074. * (void*)1. */
  3075. static void
  3076. list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
  3077. {
  3078. int purpose =
  3079. extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
  3080. list_pending_downloads(result, purpose, "d/");
  3081. }
  3082. /** Launch downloads for all the descriptors whose digests are listed
  3083. * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
  3084. * If <b>source</b> is given, download from <b>source</b>; otherwise,
  3085. * download from an appropriate random directory server.
  3086. */
  3087. static void
  3088. initiate_descriptor_downloads(routerstatus_t *source,
  3089. int purpose,
  3090. smartlist_t *digests,
  3091. int lo, int hi)
  3092. {
  3093. int i, n = hi-lo;
  3094. char *resource, *cp;
  3095. size_t r_len;
  3096. if (n <= 0)
  3097. return;
  3098. if (lo < 0)
  3099. lo = 0;
  3100. if (hi > smartlist_len(digests))
  3101. hi = smartlist_len(digests);
  3102. r_len = 8 + (HEX_DIGEST_LEN+1)*n;
  3103. cp = resource = tor_malloc(r_len);
  3104. memcpy(cp, "d/", 2);
  3105. cp += 2;
  3106. for (i = lo; i < hi; ++i) {
  3107. base16_encode(cp, r_len-(cp-resource),
  3108. smartlist_get(digests,i), DIGEST_LEN);
  3109. cp += HEX_DIGEST_LEN;
  3110. *cp++ = '+';
  3111. }
  3112. memcpy(cp-1, ".z", 3);
  3113. if (source) {
  3114. /* We know which authority we want. */
  3115. directory_initiate_command_routerstatus(source, purpose,
  3116. ROUTER_PURPOSE_GENERAL,
  3117. 0, /* not private */
  3118. resource, NULL, 0);
  3119. } else {
  3120. directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource, 1);
  3121. }
  3122. tor_free(resource);
  3123. }
  3124. /** Clients don't download any descriptor this recent, since it will probably
  3125. * not have propagated to enough caches. */
  3126. #define ESTIMATED_PROPAGATION_TIME (10*60)
  3127. /** Return 0 if this routerstatus is obsolete, too new, isn't
  3128. * running, or otherwise not a descriptor that we would make any
  3129. * use of even if we had it. Else return 1. */
  3130. static INLINE int
  3131. client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
  3132. {
  3133. if (!rs->is_running && !options->FetchUselessDescriptors) {
  3134. /* If we had this router descriptor, we wouldn't even bother using it.
  3135. * But, if we want to have a complete list, fetch it anyway. */
  3136. return 0;
  3137. }
  3138. if (rs->published_on + ESTIMATED_PROPAGATION_TIME > now) {
  3139. /* Most caches probably don't have this descriptor yet. */
  3140. return 0;
  3141. }
  3142. return 1;
  3143. }
  3144. /** Max amount of hashes to download per request.
  3145. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3146. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3147. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3148. * So use 96 because it's a nice number.
  3149. */
  3150. #define MAX_DL_PER_REQUEST 96
  3151. /** Don't split our requests so finely that we are requesting fewer than
  3152. * this number per server. */
  3153. #define MIN_DL_PER_REQUEST 4
  3154. /** To prevent a single screwy cache from confusing us by selective reply,
  3155. * try to split our requests into at least this this many requests. */
  3156. #define MIN_REQUESTS 3
  3157. /** If we want fewer than this many descriptors, wait until we
  3158. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3159. * passed. */
  3160. #define MAX_DL_TO_DELAY 16
  3161. /** When directory clients have only a few servers to request, they batch
  3162. * them until they have more, or until this amount of time has passed. */
  3163. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3164. /** DOCDOC */
  3165. static void
  3166. launch_router_descriptor_downloads(smartlist_t *downloadable, time_t now)
  3167. {
  3168. int should_delay = 0, n_downloadable;
  3169. or_options_t *options = get_options();
  3170. n_downloadable = smartlist_len(downloadable);
  3171. if (!dirserver_mode(options)) {
  3172. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3173. log_debug(LD_DIR,
  3174. "There are enough downloadable routerdescs to launch requests.");
  3175. should_delay = 0;
  3176. } else {
  3177. should_delay = (last_routerdesc_download_attempted +
  3178. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3179. if (!should_delay) {
  3180. if (last_routerdesc_download_attempted) {
  3181. log_info(LD_DIR,
  3182. "There are not many downloadable routerdescs, but we've "
  3183. "been waiting long enough (%d seconds). Downloading.",
  3184. (int)(now-last_routerdesc_download_attempted));
  3185. } else {
  3186. log_info(LD_DIR,
  3187. "There are not many downloadable routerdescs, but we haven't "
  3188. "tried downloading descriptors recently. Downloading.");
  3189. }
  3190. }
  3191. }
  3192. }
  3193. if (! should_delay) {
  3194. int i, n_per_request;
  3195. const char *req_plural = "", *rtr_plural = "";
  3196. n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
  3197. if (n_per_request > MAX_DL_PER_REQUEST)
  3198. n_per_request = MAX_DL_PER_REQUEST;
  3199. if (n_per_request < MIN_DL_PER_REQUEST)
  3200. n_per_request = MIN_DL_PER_REQUEST;
  3201. if (n_downloadable > n_per_request)
  3202. req_plural = rtr_plural = "s";
  3203. else if (n_downloadable > 1)
  3204. rtr_plural = "s";
  3205. log_info(LD_DIR,
  3206. "Launching %d request%s for %d router%s, %d at a time",
  3207. (n_downloadable+n_per_request-1)/n_per_request,
  3208. req_plural, n_downloadable, rtr_plural, n_per_request);
  3209. smartlist_sort_digests(downloadable);
  3210. for (i=0; i < n_downloadable; i += n_per_request) {
  3211. initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_SERVERDESC,
  3212. downloadable, i, i+n_per_request);
  3213. }
  3214. last_routerdesc_download_attempted = now;
  3215. }
  3216. }
  3217. /** Launch downloads for router status as needed, using the strategy used by
  3218. * authorities and caches: download every descriptor we don't have but would
  3219. * serve, from a random authority that lists it. */
  3220. static void
  3221. update_router_descriptor_cache_downloads(time_t now)
  3222. {
  3223. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  3224. smartlist_t **download_from; /* ... and, what will we dl from it? */
  3225. digestmap_t *map; /* Which descs are in progress, or assigned? */
  3226. int i, j, n;
  3227. int n_download;
  3228. or_options_t *options = get_options();
  3229. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3230. if (! dirserver_mode(options)) {
  3231. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads() "
  3232. "on a non-dir-mirror?");
  3233. }
  3234. if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
  3235. return;
  3236. map = digestmap_new();
  3237. n = smartlist_len(networkstatus_v2_list);
  3238. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3239. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3240. /* Set map[d]=1 for the digest of every descriptor that we are currently
  3241. * downloading. */
  3242. list_pending_descriptor_downloads(map, 0);
  3243. /* For the digest of every descriptor that we don't have, and that we aren't
  3244. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  3245. * about that descriptor, and we haven't already failed to get that
  3246. * descriptor from the corresponding authority.
  3247. */
  3248. n_download = 0;
  3249. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3250. {
  3251. trusted_dir_server_t *ds;
  3252. smartlist_t *dl;
  3253. dl = downloadable[ns_sl_idx] = smartlist_create();
  3254. download_from[ns_sl_idx] = smartlist_create();
  3255. if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
  3256. /* Don't download if the networkstatus is almost ancient. */
  3257. /* Actually, I suspect what's happening here is that we ask
  3258. * for the descriptor when we have a given networkstatus,
  3259. * and then we get a newer networkstatus, and then we receive
  3260. * the descriptor. Having a networkstatus actually expire is
  3261. * probably a rare event, and we'll probably be happiest if
  3262. * we take this clause out. -RD */
  3263. continue;
  3264. }
  3265. /* Don't try dirservers that we think are down -- we might have
  3266. * just tried them and just marked them as down. */
  3267. ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
  3268. if (ds && !ds->is_running)
  3269. continue;
  3270. SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
  3271. {
  3272. if (!rs->need_to_mirror)
  3273. continue;
  3274. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  3275. log_warn(LD_BUG,
  3276. "We have a router descriptor, but need_to_mirror=1.");
  3277. rs->need_to_mirror = 0;
  3278. continue;
  3279. }
  3280. if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
  3281. rs->need_to_mirror = 0;
  3282. continue;
  3283. }
  3284. if (digestmap_get(map, rs->descriptor_digest)) {
  3285. /* We're downloading it already. */
  3286. continue;
  3287. } else {
  3288. /* We could download it from this guy. */
  3289. smartlist_add(dl, rs->descriptor_digest);
  3290. ++n_download;
  3291. }
  3292. });
  3293. });
  3294. /* At random, assign descriptors to authorities such that:
  3295. * - if d is a member of some downloadable[x], d is a member of some
  3296. * download_from[y]. (Everything we want to download, we try to download
  3297. * from somebody.)
  3298. * - If d is a member of download_from[y], d is a member of downloadable[y].
  3299. * (We only try to download descriptors from authorities who claim to have
  3300. * them.)
  3301. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  3302. * (We don't try to download anything from two authorities concurrently.)
  3303. */
  3304. while (n_download) {
  3305. int which_ns = crypto_rand_int(n);
  3306. smartlist_t *dl = downloadable[which_ns];
  3307. int idx;
  3308. char *d;
  3309. if (!smartlist_len(dl))
  3310. continue;
  3311. idx = crypto_rand_int(smartlist_len(dl));
  3312. d = smartlist_get(dl, idx);
  3313. if (! digestmap_get(map, d)) {
  3314. smartlist_add(download_from[which_ns], d);
  3315. digestmap_set(map, d, (void*) 1);
  3316. }
  3317. smartlist_del(dl, idx);
  3318. --n_download;
  3319. }
  3320. /* Now, we can actually launch our requests. */
  3321. for (i=0; i<n; ++i) {
  3322. networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
  3323. trusted_dir_server_t *ds =
  3324. router_get_trusteddirserver_by_digest(ns->identity_digest);
  3325. smartlist_t *dl = download_from[i];
  3326. if (!ds) {
  3327. log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
  3328. continue;
  3329. }
  3330. if (! smartlist_len(dl))
  3331. continue;
  3332. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  3333. smartlist_len(dl), ds->nickname);
  3334. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  3335. initiate_descriptor_downloads(&(ds->fake_status),
  3336. DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
  3337. j+MAX_DL_PER_REQUEST);
  3338. }
  3339. }
  3340. for (i=0; i<n; ++i) {
  3341. smartlist_free(download_from[i]);
  3342. smartlist_free(downloadable[i]);
  3343. }
  3344. tor_free(download_from);
  3345. tor_free(downloadable);
  3346. digestmap_free(map,NULL);
  3347. }
  3348. /** DOCDOC */
  3349. static void
  3350. update_consensus_router_descriptor_downloads(time_t now)
  3351. {
  3352. or_options_t *options = get_options();
  3353. digestmap_t *map = NULL;
  3354. smartlist_t *downloadable = smartlist_create();
  3355. int authdir = authdir_mode(options);
  3356. int dirserver = dirserver_mode(options);
  3357. networkstatus_vote_t *consensus = networkstatus_get_live_consensus(now);
  3358. if (!dirserver) {
  3359. if (rep_hist_circbuilding_dormant(now))
  3360. return;
  3361. }
  3362. if (!consensus)
  3363. return;
  3364. map = digestmap_new();
  3365. list_pending_descriptor_downloads(map, 0);
  3366. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
  3367. {
  3368. if (router_get_by_descriptor_digest(rs->descriptor_digest))
  3369. continue; /* We have it already. */
  3370. if (!download_status_is_ready(&rs->dl_status, now,
  3371. MAX_ROUTERDESC_DOWNLOAD_FAILURES))
  3372. continue;
  3373. if (authdir && dirserv_would_reject_router(rs))
  3374. continue; /* We would throw it out immediately. */
  3375. if (!dirserver && !client_would_use_router(rs, now, options))
  3376. continue; /* We would never use it ourself. */
  3377. if (digestmap_get(map, rs->descriptor_digest))
  3378. continue; /* We have an in-progress download. */
  3379. smartlist_add(downloadable, rs->descriptor_digest);
  3380. });
  3381. launch_router_descriptor_downloads(downloadable, now);
  3382. smartlist_free(downloadable);
  3383. digestmap_free(map, NULL);
  3384. }
  3385. /** Launch downloads for router status as needed. */
  3386. void
  3387. update_router_descriptor_downloads(time_t now)
  3388. {
  3389. or_options_t *options = get_options();
  3390. if (should_delay_dir_fetches(options))
  3391. return;
  3392. if (dirserver_mode(options)) {
  3393. update_router_descriptor_cache_downloads(now);
  3394. }
  3395. update_consensus_router_descriptor_downloads(now);
  3396. }
  3397. /** Return true iff <b>sd</b> is the descriptor for a router descriptor that
  3398. * has an extrainfo that we don't currently have, are not currently
  3399. * downloading, and have not recently tried to download. */
  3400. static INLINE int
  3401. should_download_extrainfo(signed_descriptor_t *sd,
  3402. const routerlist_t *rl,
  3403. const digestmap_t *pending,
  3404. time_t now)
  3405. {
  3406. const char *d = sd->extra_info_digest;
  3407. return (!sd->is_extrainfo &&
  3408. !tor_digest_is_zero(d) &&
  3409. download_status_is_ready(&sd->ei_dl_status, now,
  3410. MAX_ROUTERDESC_DOWNLOAD_FAILURES) &&
  3411. !eimap_get(rl->extra_info_map, d) &&
  3412. !digestmap_get(pending, d));
  3413. }
  3414. /** Launch extrainfo downloads as needed. */
  3415. void
  3416. update_extrainfo_downloads(time_t now)
  3417. {
  3418. or_options_t *options = get_options();
  3419. routerlist_t *rl;
  3420. smartlist_t *wanted;
  3421. digestmap_t *pending;
  3422. int i;
  3423. if (! options->DownloadExtraInfo)
  3424. return;
  3425. if (should_delay_dir_fetches(options))
  3426. return;
  3427. pending = digestmap_new();
  3428. list_pending_descriptor_downloads(pending, 1);
  3429. rl = router_get_routerlist();
  3430. wanted = smartlist_create();
  3431. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  3432. if (should_download_extrainfo(&ri->cache_info, rl, pending, now)) {
  3433. smartlist_add(wanted, ri->cache_info.extra_info_digest);
  3434. }
  3435. });
  3436. if (dirserver_mode(options)) {
  3437. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd, {
  3438. if (should_download_extrainfo(sd, rl, pending, now)) {
  3439. smartlist_add(wanted, sd->extra_info_digest);
  3440. }
  3441. });
  3442. }
  3443. digestmap_free(pending, NULL);
  3444. smartlist_shuffle(wanted);
  3445. for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
  3446. initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
  3447. wanted, i, i + MAX_DL_PER_REQUEST);
  3448. }
  3449. smartlist_free(wanted);
  3450. }
  3451. /** True iff, the last time we checked whether we had enough directory info
  3452. * to build circuits, the answer was "yes". */
  3453. static int have_min_dir_info = 0;
  3454. /** True iff enough has changed since the last time we checked whether we had
  3455. * enough directory info to build circuits that our old answer can no longer
  3456. * be trusted. */
  3457. static int need_to_update_have_min_dir_info = 1;
  3458. /** Return true iff we have enough networkstatus and router information to
  3459. * start building circuits. Right now, this means "more than half the
  3460. * networkstatus documents, and at least 1/4 of expected routers." */
  3461. //XXX should consider whether we have enough exiting nodes here.
  3462. int
  3463. router_have_minimum_dir_info(void)
  3464. {
  3465. if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
  3466. update_router_have_minimum_dir_info();
  3467. need_to_update_have_min_dir_info = 0;
  3468. }
  3469. return have_min_dir_info;
  3470. }
  3471. /** Called when our internal view of the directory has changed. This can be
  3472. * when the authorities change, networkstatuses change, the list of routerdescs
  3473. * changes, or number of running routers changes.
  3474. */
  3475. void
  3476. router_dir_info_changed(void)
  3477. {
  3478. need_to_update_have_min_dir_info = 1;
  3479. }
  3480. /** Change the value of have_min_dir_info, setting it true iff we have enough
  3481. * network and router information to build circuits. Clear the value of
  3482. * need_to_update_have_min_dir_info. */
  3483. static void
  3484. update_router_have_minimum_dir_info(void)
  3485. {
  3486. /*XXX020 call when dirserver_mode() changes. */
  3487. int num_present = 0, num_usable=0;
  3488. time_t now = time(NULL);
  3489. int res;
  3490. or_options_t *options = get_options();
  3491. const networkstatus_vote_t *consensus =
  3492. networkstatus_get_live_consensus(now);
  3493. if (!consensus) {
  3494. res = 0;
  3495. goto done;
  3496. }
  3497. if (should_delay_dir_fetches(get_options())) {
  3498. log_notice(LD_DIR, "no known bridge descriptors running yet; stalling");
  3499. res = 0;
  3500. goto done;
  3501. }
  3502. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
  3503. {
  3504. if (client_would_use_router(rs, now, options)) {
  3505. ++num_usable;
  3506. if (router_get_by_digest(rs->identity_digest)) {
  3507. ++num_present;
  3508. }
  3509. }
  3510. });
  3511. res = num_present >= num_usable/4 && num_usable > 2;
  3512. done:
  3513. if (res && !have_min_dir_info) {
  3514. log(LOG_NOTICE, LD_DIR,
  3515. "We now have enough directory information to build circuits.");
  3516. control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
  3517. }
  3518. if (!res && have_min_dir_info) {
  3519. log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
  3520. "enough to build circuits.%s",
  3521. num_usable > 2 ? "" : " (Not enough servers seem reachable -- "
  3522. "is your network connection down?)");
  3523. control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
  3524. }
  3525. have_min_dir_info = res;
  3526. }
  3527. /** Reset the descriptor download failure count on all routers, so that we
  3528. * can retry any long-failed routers immediately.
  3529. */
  3530. void
  3531. router_reset_descriptor_download_failures(void)
  3532. {
  3533. networkstatus_reset_download_failures();
  3534. last_routerdesc_download_attempted = 0;
  3535. if (!routerlist)
  3536. return;
  3537. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  3538. {
  3539. download_status_reset(&ri->cache_info.ei_dl_status);
  3540. });
  3541. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  3542. {
  3543. download_status_reset(&sd->ei_dl_status);
  3544. });
  3545. }
  3546. /** Any changes in a router descriptor's publication time larger than this are
  3547. * automatically non-cosmetic. */
  3548. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
  3549. /** We allow uptime to vary from how much it ought to be by this much. */
  3550. #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
  3551. /** Return true iff the only differences between r1 and r2 are such that
  3552. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  3553. */
  3554. int
  3555. router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
  3556. {
  3557. time_t r1pub, r2pub;
  3558. int time_difference;
  3559. tor_assert(r1 && r2);
  3560. /* r1 should be the one that was published first. */
  3561. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  3562. routerinfo_t *ri_tmp = r2;
  3563. r2 = r1;
  3564. r1 = ri_tmp;
  3565. }
  3566. /* If any key fields differ, they're different. */
  3567. if (strcasecmp(r1->address, r2->address) ||
  3568. strcasecmp(r1->nickname, r2->nickname) ||
  3569. r1->or_port != r2->or_port ||
  3570. r1->dir_port != r2->dir_port ||
  3571. crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
  3572. crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
  3573. strcasecmp(r1->platform, r2->platform) ||
  3574. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  3575. (!r1->contact_info && r2->contact_info) ||
  3576. (r1->contact_info && r2->contact_info &&
  3577. strcasecmp(r1->contact_info, r2->contact_info)) ||
  3578. r1->is_hibernating != r2->is_hibernating ||
  3579. r1->has_old_dnsworkers != r2->has_old_dnsworkers ||
  3580. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  3581. return 0;
  3582. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  3583. return 0;
  3584. if (r1->declared_family && r2->declared_family) {
  3585. int i, n;
  3586. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  3587. return 0;
  3588. n = smartlist_len(r1->declared_family);
  3589. for (i=0; i < n; ++i) {
  3590. if (strcasecmp(smartlist_get(r1->declared_family, i),
  3591. smartlist_get(r2->declared_family, i)))
  3592. return 0;
  3593. }
  3594. }
  3595. /* Did bandwidth change a lot? */
  3596. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  3597. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  3598. return 0;
  3599. /* Did more than 12 hours pass? */
  3600. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  3601. < r2->cache_info.published_on)
  3602. return 0;
  3603. /* Did uptime fail to increase by approximately the amount we would think,
  3604. * give or take some slop? */
  3605. r1pub = r1->cache_info.published_on;
  3606. r2pub = r2->cache_info.published_on;
  3607. time_difference = abs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
  3608. if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
  3609. time_difference > r1->uptime * .05 &&
  3610. time_difference > r2->uptime * .05)
  3611. return 0;
  3612. /* Otherwise, the difference is cosmetic. */
  3613. return 1;
  3614. }
  3615. /** Check whether <b>ri</b> is a router compatible with the extrainfo document
  3616. * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
  3617. * dropped. Return 0 for "compatible", return 1 for "reject, and inform
  3618. * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
  3619. * <b>msg</b> is present, set *<b>msg</b> to a description of the
  3620. * incompatibility (if any). */
  3621. int
  3622. routerinfo_incompatible_with_extrainfo(routerinfo_t *ri, extrainfo_t *ei,
  3623. const char **msg)
  3624. {
  3625. tor_assert(ri);
  3626. tor_assert(ei);
  3627. if (ei->bad_sig) {
  3628. if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
  3629. return 1;
  3630. }
  3631. /* The nickname must match exactly to have been generated at the same time
  3632. * by the same router. */
  3633. if (strcmp(ri->nickname, ei->nickname) ||
  3634. memcmp(ri->cache_info.identity_digest, ei->cache_info.identity_digest,
  3635. DIGEST_LEN)) {
  3636. if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
  3637. return 1; /* different servers */
  3638. }
  3639. if (ei->pending_sig) {
  3640. char signed_digest[128];
  3641. if (crypto_pk_public_checksig(ri->identity_pkey, signed_digest,
  3642. ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
  3643. memcmp(signed_digest, ei->cache_info.signed_descriptor_digest,
  3644. DIGEST_LEN)) {
  3645. ei->bad_sig = 1;
  3646. tor_free(ei->pending_sig);
  3647. if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
  3648. return 1; /* Bad signature, or no match. */
  3649. }
  3650. tor_free(ei->pending_sig);
  3651. }
  3652. if (ei->cache_info.published_on < ri->cache_info.published_on) {
  3653. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  3654. return 1;
  3655. } else if (ei->cache_info.published_on > ri->cache_info.published_on) {
  3656. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  3657. return -1;
  3658. }
  3659. if (memcmp(ei->cache_info.signed_descriptor_digest,
  3660. ri->cache_info.extra_info_digest, DIGEST_LEN)) {
  3661. if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
  3662. return 1; /* Digest doesn't match declared value. */
  3663. }
  3664. return 0;
  3665. }
  3666. /** Assert that the internal representation of <b>rl</b> is
  3667. * self-consistent. */
  3668. void
  3669. routerlist_assert_ok(routerlist_t *rl)
  3670. {
  3671. digestmap_iter_t *iter; /* XXXX020 use the appropriate iter type. */
  3672. routerinfo_t *r2;
  3673. signed_descriptor_t *sd2;
  3674. if (!rl)
  3675. return;
  3676. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  3677. {
  3678. r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
  3679. tor_assert(r == r2);
  3680. sd2 = sdmap_get(rl->desc_digest_map,
  3681. r->cache_info.signed_descriptor_digest);
  3682. tor_assert(&(r->cache_info) == sd2);
  3683. tor_assert(r->routerlist_index == r_sl_idx);
  3684. #if 0
  3685. /* XXXX020.
  3686. *
  3687. * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
  3688. * commenting this out is just a band-aid.
  3689. *
  3690. * The problem is that, although well-behaved router descriptors
  3691. * should never have the same value for their extra_info_digest, it's
  3692. * possible for ill-behaved routers to claim whatever they like there.
  3693. *
  3694. * The real answer is to trash desc_by_eid_map and instead have
  3695. * something that indicates for a given extra-info digest we want,
  3696. * what its download status is. We'll do that as a part of routerlist
  3697. * refactoring once consensus directories are in. For now,
  3698. * this rep violation is probably harmless: an adversary can make us
  3699. * reset our retry count for an extrainfo, but that's not the end
  3700. * of the world.
  3701. */
  3702. if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
  3703. signed_descriptor_t *sd3 =
  3704. sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
  3705. tor_assert(sd3 == &(r->cache_info));
  3706. }
  3707. #endif
  3708. });
  3709. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  3710. {
  3711. r2 = rimap_get(rl->identity_map, sd->identity_digest);
  3712. tor_assert(sd != &(r2->cache_info));
  3713. sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  3714. tor_assert(sd == sd2);
  3715. #if 0
  3716. /* XXXX020 see above. */
  3717. if (!tor_digest_is_zero(sd->extra_info_digest)) {
  3718. signed_descriptor_t *sd3 =
  3719. sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
  3720. tor_assert(sd3 == sd);
  3721. }
  3722. #endif
  3723. });
  3724. iter = digestmap_iter_init((digestmap_t*)rl->identity_map);
  3725. while (!digestmap_iter_done(iter)) {
  3726. const char *d;
  3727. void *_r;
  3728. routerinfo_t *r;
  3729. digestmap_iter_get(iter, &d, &_r);
  3730. r = _r;
  3731. tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
  3732. iter = digestmap_iter_next((digestmap_t*)rl->identity_map, iter);
  3733. }
  3734. iter = digestmap_iter_init((digestmap_t*)rl->desc_digest_map);
  3735. while (!digestmap_iter_done(iter)) {
  3736. const char *d;
  3737. void *_sd;
  3738. signed_descriptor_t *sd;
  3739. digestmap_iter_get(iter, &d, &_sd);
  3740. sd = _sd;
  3741. tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
  3742. iter = digestmap_iter_next((digestmap_t*)rl->desc_digest_map, iter);
  3743. }
  3744. iter = digestmap_iter_init((digestmap_t*)rl->desc_by_eid_map);
  3745. while (!digestmap_iter_done(iter)) {
  3746. const char *d;
  3747. void *_sd;
  3748. signed_descriptor_t *sd;
  3749. digestmap_iter_get(iter, &d, &_sd);
  3750. sd = _sd;
  3751. tor_assert(!tor_digest_is_zero(d));
  3752. tor_assert(sd);
  3753. tor_assert(!memcmp(sd->extra_info_digest, d, DIGEST_LEN));
  3754. iter = digestmap_iter_next((digestmap_t*)rl->desc_by_eid_map, iter);
  3755. }
  3756. iter = digestmap_iter_init((digestmap_t*)rl->extra_info_map);
  3757. while (!digestmap_iter_done(iter)) {
  3758. const char *d;
  3759. void *_ei;
  3760. extrainfo_t *ei;
  3761. signed_descriptor_t *sd;
  3762. digestmap_iter_get(iter, &d, &_ei);
  3763. ei = _ei;
  3764. tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
  3765. d, DIGEST_LEN));
  3766. sd = sdmap_get(rl->desc_by_eid_map,
  3767. ei->cache_info.signed_descriptor_digest);
  3768. // tor_assert(sd); // XXXX020 see above
  3769. if (sd) {
  3770. tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
  3771. sd->extra_info_digest, DIGEST_LEN));
  3772. }
  3773. iter = digestmap_iter_next((digestmap_t*)rl->extra_info_map, iter);
  3774. }
  3775. }
  3776. /** Allocate and return a new string representing the contact info
  3777. * and platform string for <b>router</b>,
  3778. * surrounded by quotes and using standard C escapes.
  3779. *
  3780. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  3781. * thread. Also, each call invalidates the last-returned value, so don't
  3782. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  3783. *
  3784. * If <b>router</b> is NULL, it just frees its internal memory and returns.
  3785. */
  3786. const char *
  3787. esc_router_info(routerinfo_t *router)
  3788. {
  3789. static char *info=NULL;
  3790. char *esc_contact, *esc_platform;
  3791. size_t len;
  3792. if (info)
  3793. tor_free(info);
  3794. if (!router)
  3795. return NULL; /* we're exiting; just free the memory we use */
  3796. esc_contact = esc_for_log(router->contact_info);
  3797. esc_platform = esc_for_log(router->platform);
  3798. len = strlen(esc_contact)+strlen(esc_platform)+32;
  3799. info = tor_malloc(len);
  3800. tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
  3801. esc_platform);
  3802. tor_free(esc_contact);
  3803. tor_free(esc_platform);
  3804. return info;
  3805. }
  3806. /** Helper for sorting: compare two routerinfos by their identity
  3807. * digest. */
  3808. static int
  3809. _compare_routerinfo_by_id_digest(const void **a, const void **b)
  3810. {
  3811. routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
  3812. return memcmp(first->cache_info.identity_digest,
  3813. second->cache_info.identity_digest,
  3814. DIGEST_LEN);
  3815. }
  3816. /** Sort a list of routerinfo_t in ascending order of identity digest. */
  3817. void
  3818. routers_sort_by_identity(smartlist_t *routers)
  3819. {
  3820. smartlist_sort(routers, _compare_routerinfo_by_id_digest);
  3821. }