routerlist.c 141 KB

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