routerlist.c 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, 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. /****************************************************************************/
  16. /* static function prototypes */
  17. static routerstatus_t *router_pick_directory_server_impl(int requireother,
  18. int fascistfirewall,
  19. int for_v2_directory);
  20. static routerstatus_t *router_pick_trusteddirserver_impl(
  21. int need_v1_authority, int requireother, int fascistfirewall);
  22. static void mark_all_trusteddirservers_up(void);
  23. static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  24. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  25. static void routerstatus_list_update_from_networkstatus(time_t now);
  26. static void local_routerstatus_free(local_routerstatus_t *rs);
  27. static void trusted_dir_server_free(trusted_dir_server_t *ds);
  28. static void update_networkstatus_cache_downloads(time_t now);
  29. static void update_networkstatus_client_downloads(time_t now);
  30. static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
  31. static void routerlist_assert_ok(routerlist_t *rl);
  32. static int have_tried_downloading_all_statuses(int n_failures);
  33. static routerstatus_t *networkstatus_find_entry(networkstatus_t *ns,
  34. const char *digest);
  35. /****************************************************************************/
  36. /** Global list of a trusted_dir_server_t object for each trusted directory
  37. * server. */
  38. static smartlist_t *trusted_dir_servers = NULL;
  39. /** Global list of all of the routers that we know about. */
  40. static routerlist_t *routerlist = NULL;
  41. /** Global list of all of the current network_status documents that we know
  42. * about. This list is kept sorted by published_on. */
  43. static smartlist_t *networkstatus_list = NULL;
  44. /** Global list of local_routerstatus_t for each router, known or unknown. */
  45. static smartlist_t *routerstatus_list = NULL;
  46. /** True iff any member of networkstatus_list has changed since the last time
  47. * we called routerstatus_list_update_from_networkstatus(). */
  48. static int networkstatus_list_has_changed = 0;
  49. /** True iff any element of routerstatus_list has changed since the last
  50. * time we called routers_update_all_from_networkstatus().*/
  51. static int routerstatus_list_has_changed = 0;
  52. /** List of strings for nicknames we've already warned about and that are
  53. * still unknown / unavailable. */
  54. static smartlist_t *warned_nicknames = NULL;
  55. /** List of strings for nicknames or fingerprints we've already warned about
  56. * and that are still conflicted. */
  57. static smartlist_t *warned_conflicts = NULL;
  58. /** The last time we tried to download any routerdesc, or 0 for "never". We
  59. * use this to rate-limit download attempts when the number of routerdescs to
  60. * download is low. */
  61. static time_t last_routerdesc_download_attempted = 0;
  62. /** The last time we tried to download a networkstatus, or 0 for "never". We
  63. * use this to rate-limit download attempts for directory caches (including
  64. * mirrors). Clients don't use this now. */
  65. static time_t last_networkstatus_download_attempted = 0;
  66. /** True iff we have logged a warning about this OR not being valid or
  67. * not being named. */
  68. static int have_warned_about_invalid_status = 0;
  69. /** True iff we have logged a warning about this OR's version being older than
  70. * listed by the authorities */
  71. static int have_warned_about_old_version = 0;
  72. /** True iff we have logged a warning about this OR's version being newer than
  73. * listed by the authorities */
  74. static int have_warned_about_new_version = 0;
  75. /** Repopulate our list of network_status_t objects from the list cached on
  76. * disk. Return 0 on success, -1 on failure. */
  77. int
  78. router_reload_networkstatus(void)
  79. {
  80. char filename[512];
  81. struct stat st;
  82. smartlist_t *entries;
  83. char *s;
  84. tor_assert(get_options()->DataDirectory);
  85. if (!networkstatus_list)
  86. networkstatus_list = smartlist_create();
  87. tor_snprintf(filename,sizeof(filename),"%s/cached-status",
  88. get_options()->DataDirectory);
  89. entries = tor_listdir(filename);
  90. SMARTLIST_FOREACH(entries, const char *, fn, {
  91. char buf[DIGEST_LEN];
  92. if (strlen(fn) != HEX_DIGEST_LEN ||
  93. base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
  94. log_info(LD_DIR,
  95. "Skipping cached-status file with unexpected name \"%s\"",fn);
  96. continue;
  97. }
  98. tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
  99. get_options()->DataDirectory, fn);
  100. s = read_file_to_str(filename, 0);
  101. if (s) {
  102. stat(filename, &st);
  103. if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
  104. log_warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
  105. }
  106. tor_free(s);
  107. }
  108. });
  109. SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
  110. smartlist_free(entries);
  111. networkstatus_list_clean(time(NULL));
  112. routers_update_all_from_networkstatus();
  113. return 0;
  114. }
  115. /* Router descriptor storage.
  116. *
  117. * Routerdescs are stored in a big file, named "cached-routers". As new
  118. * routerdescs arrive, we append them to a journal file named
  119. * "cached-routers.new".
  120. *
  121. * From time to time, we replace "cached-routers" with a new file containing
  122. * only the live, non-superseded descriptors, and clear cached-routers.new.
  123. *
  124. * On startup, we read both files.
  125. */
  126. /** The size of the router log, in bytes. */
  127. static size_t router_journal_len = 0;
  128. /** The size of the router store, in bytes. */
  129. static size_t router_store_len = 0;
  130. /** Total bytes dropped since last rebuild. */
  131. static size_t router_bytes_dropped = 0;
  132. /** Helper: return 1 iff the router log is so big we want to rebuild the
  133. * store. */
  134. static int
  135. router_should_rebuild_store(void)
  136. {
  137. if (router_store_len > (1<<16))
  138. return (router_journal_len > router_store_len / 2 ||
  139. router_bytes_dropped > router_store_len / 2);
  140. else
  141. return router_journal_len > (1<<15);
  142. }
  143. /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
  144. * journal. */
  145. static int
  146. router_append_to_journal(signed_descriptor_t *desc)
  147. {
  148. or_options_t *options = get_options();
  149. size_t fname_len = strlen(options->DataDirectory)+32;
  150. char *fname = tor_malloc(fname_len);
  151. const char *body = signed_descriptor_get_body(desc);
  152. size_t len = desc->signed_descriptor_len;
  153. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  154. options->DataDirectory);
  155. tor_assert(len == strlen(body));
  156. if (append_bytes_to_file(fname, body, len, 0)) {
  157. log_warn(LD_FS, "Unable to store router descriptor");
  158. tor_free(fname);
  159. return -1;
  160. }
  161. tor_free(fname);
  162. router_journal_len += len;
  163. return 0;
  164. }
  165. /** If the journal is too long, or if <b>force</b> is true, then atomically
  166. * replace the router store with the routers currently in our routerlist, and
  167. * clear the journal. Return 0 on success, -1 on failure.
  168. */
  169. static int
  170. router_rebuild_store(int force)
  171. {
  172. size_t len = 0;
  173. or_options_t *options;
  174. size_t fname_len;
  175. smartlist_t *chunk_list = NULL;
  176. char *fname = NULL;
  177. int r = -1, i;
  178. if (!force && !router_should_rebuild_store())
  179. return 0;
  180. if (!routerlist)
  181. return 0;
  182. /* Don't save deadweight. */
  183. routerlist_remove_old_routers();
  184. options = get_options();
  185. fname_len = strlen(options->DataDirectory)+32;
  186. fname = tor_malloc(fname_len);
  187. tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
  188. chunk_list = smartlist_create();
  189. for (i = 0; i < 2; ++i) {
  190. smartlist_t *lst = (i == 0) ? routerlist->old_routers :
  191. routerlist->routers;
  192. SMARTLIST_FOREACH(lst, void *, ptr,
  193. {
  194. signed_descriptor_t *sd = (i==0) ?
  195. ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
  196. sized_chunk_t *c;
  197. const char *body = signed_descriptor_get_body(sd);
  198. if (!body) {
  199. log_warn(LD_BUG, "Bug! No descriptor available for router.");
  200. goto done;
  201. }
  202. c = tor_malloc(sizeof(sized_chunk_t));
  203. c->bytes = body;
  204. c->len = sd->signed_descriptor_len;
  205. smartlist_add(chunk_list, c);
  206. });
  207. }
  208. if (write_chunks_to_file(fname, chunk_list, 0)<0) {
  209. log_warn(LD_FS, "Error writing router store to disk.");
  210. goto done;
  211. }
  212. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  213. options->DataDirectory);
  214. write_str_to_file(fname, "", 0);
  215. r = 0;
  216. router_store_len = len;
  217. router_journal_len = 0;
  218. router_bytes_dropped = 0;
  219. done:
  220. tor_free(fname);
  221. if (chunk_list) {
  222. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  223. smartlist_free(chunk_list);
  224. }
  225. return r;
  226. }
  227. /* Load all cached router descriptors from the store. Return 0 on success and
  228. * -1 on failure.
  229. */
  230. int
  231. router_reload_router_list(void)
  232. {
  233. or_options_t *options = get_options();
  234. size_t fname_len = strlen(options->DataDirectory)+32;
  235. char *fname = tor_malloc(fname_len);
  236. struct stat st;
  237. int j;
  238. if (!routerlist)
  239. router_get_routerlist(); /* mallocs and inits it in place */
  240. router_journal_len = router_store_len = 0;
  241. for (j = 0; j < 2; ++j) {
  242. char *contents;
  243. tor_snprintf(fname, fname_len,
  244. (j==0)?"%s/cached-routers":"%s/cached-routers.new",
  245. options->DataDirectory);
  246. contents = read_file_to_str(fname, 0);
  247. if (contents) {
  248. stat(fname, &st);
  249. if (j==0)
  250. router_store_len = st.st_size;
  251. else
  252. router_journal_len = st.st_size;
  253. router_load_routers_from_string(contents, 1, NULL);
  254. tor_free(contents);
  255. }
  256. }
  257. tor_free(fname);
  258. if (router_journal_len) {
  259. /* Always clear the journal on startup.*/
  260. router_rebuild_store(1);
  261. } else {
  262. /* Don't cache expired routers. (This is in an else because
  263. * router_rebuild_store() also calls remove_old_routers().) */
  264. routerlist_remove_old_routers();
  265. }
  266. return 0;
  267. }
  268. /** Return a smartlist containing a list of trusted_dir_server_t * for all
  269. * known trusted dirservers. Callers must not modify the list or its
  270. * contents.
  271. */
  272. smartlist_t *
  273. router_get_trusted_dir_servers(void)
  274. {
  275. if (!trusted_dir_servers)
  276. trusted_dir_servers = smartlist_create();
  277. return trusted_dir_servers;
  278. }
  279. /** Try to find a running dirserver. If there are no running dirservers
  280. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  281. * set all the authoritative ones as running again, and pick one;
  282. * if there are then no dirservers at all in our routerlist,
  283. * reload the routerlist and try one last time. If for_runningrouters is
  284. * true, then only pick a dirserver that can answer runningrouters queries
  285. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  286. * Don't pick an authority if any non-authority is viable.
  287. * Other args are as in router_pick_directory_server_impl().
  288. */
  289. routerstatus_t *
  290. router_pick_directory_server(int requireother,
  291. int fascistfirewall,
  292. int for_v2_directory,
  293. int retry_if_no_servers)
  294. {
  295. routerstatus_t *choice;
  296. if (!routerlist)
  297. return NULL;
  298. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  299. for_v2_directory);
  300. if (choice || !retry_if_no_servers)
  301. return choice;
  302. log_info(LD_DIR,
  303. "No reachable router entries for dirservers. "
  304. "Trying them all again.");
  305. /* mark all authdirservers as up again */
  306. mark_all_trusteddirservers_up();
  307. /* try again */
  308. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  309. for_v2_directory);
  310. if (choice)
  311. return choice;
  312. log_info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
  313. fascistfirewall ? "reachable" : "known");
  314. if (router_reload_router_list()) {
  315. return NULL;
  316. }
  317. /* give it one last try */
  318. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  319. for_v2_directory);
  320. return choice;
  321. }
  322. /** Return the trusted_dir_server_t for the directory authority whose identity
  323. * key hashes to <b>digest</b>, or NULL if no such authority is known.
  324. */
  325. trusted_dir_server_t *
  326. router_get_trusteddirserver_by_digest(const char *digest)
  327. {
  328. if (!trusted_dir_servers)
  329. return NULL;
  330. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  331. {
  332. if (!memcmp(ds->digest, digest, DIGEST_LEN))
  333. return ds;
  334. });
  335. return NULL;
  336. }
  337. /** Try to find a running trusted dirserver. If there are no running
  338. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  339. * set them all as running again, and try again.
  340. * If <b>need_v1_authority</b> is set, return only trusted servers
  341. * that are authorities for the V1 directory protocol.
  342. * Other args are as in router_pick_trusteddirserver_impl().
  343. */
  344. routerstatus_t *
  345. router_pick_trusteddirserver(int need_v1_authority,
  346. int requireother,
  347. int fascistfirewall,
  348. int retry_if_no_servers)
  349. {
  350. routerstatus_t *choice;
  351. choice = router_pick_trusteddirserver_impl(need_v1_authority,
  352. requireother, fascistfirewall);
  353. if (choice || !retry_if_no_servers)
  354. return choice;
  355. log_info(LD_DIR,
  356. "No trusted dirservers are reachable. Trying them all again.");
  357. mark_all_trusteddirservers_up();
  358. return router_pick_trusteddirserver_impl(need_v1_authority,
  359. requireother, fascistfirewall);
  360. }
  361. /** Pick a random running valid directory server/mirror from our
  362. * routerlist. Don't pick an authority if any non-authorities are viable.
  363. * If <b>fascistfirewall</b>,
  364. * make sure the router we pick is allowed by our firewall options.
  365. * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
  366. * choose a directory server new enough to support the v2 directory
  367. * functionality.
  368. */
  369. static routerstatus_t *
  370. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  371. int for_v2_directory)
  372. {
  373. routerstatus_t *result;
  374. smartlist_t *sl;
  375. smartlist_t *trusted;
  376. if (!routerstatus_list)
  377. return NULL;
  378. /* Find all the running dirservers we know about. */
  379. sl = smartlist_create();
  380. trusted = smartlist_create();
  381. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, _local_status,
  382. {
  383. routerstatus_t *status = &(_local_status->status);
  384. int is_trusted;
  385. if (!status->is_running || !status->dir_port || !status->is_valid)
  386. continue;
  387. if (requireother && router_digest_is_me(status->identity_digest))
  388. continue;
  389. if (fascistfirewall) {
  390. if (!fascist_firewall_allows_address_dir(status->addr, status->dir_port))
  391. continue;
  392. }
  393. is_trusted = router_digest_is_trusted_dir(status->identity_digest);
  394. if (for_v2_directory && !(status->is_v2_dir || is_trusted))
  395. continue;
  396. smartlist_add(is_trusted ? trusted : sl, status);
  397. });
  398. if (smartlist_len(sl))
  399. result = smartlist_choose(sl);
  400. else
  401. result = smartlist_choose(trusted);
  402. smartlist_free(sl);
  403. smartlist_free(trusted);
  404. return result;
  405. }
  406. /** Choose randomly from among the trusted dirservers that are up. If
  407. * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
  408. * firewall options. If <b>requireother</b>, it cannot be us. If
  409. * <b>need_v1_authority</b>, choose a trusted authority for the v1 directory
  410. * system.
  411. */
  412. static routerstatus_t *
  413. router_pick_trusteddirserver_impl(int need_v1_authority,
  414. int requireother, int fascistfirewall)
  415. {
  416. smartlist_t *sl;
  417. routerinfo_t *me;
  418. routerstatus_t *rs;
  419. sl = smartlist_create();
  420. me = router_get_my_routerinfo();
  421. if (!trusted_dir_servers)
  422. return NULL;
  423. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  424. {
  425. if (!d->is_running) continue;
  426. if (need_v1_authority && !d->is_v1_authority)
  427. continue;
  428. if (requireother && me && router_digest_is_me(d->digest))
  429. continue;
  430. if (fascistfirewall) {
  431. if (!fascist_firewall_allows_address_dir(d->addr, d->dir_port))
  432. continue;
  433. }
  434. smartlist_add(sl, &d->fake_status);
  435. });
  436. rs = smartlist_choose(sl);
  437. smartlist_free(sl);
  438. return rs;
  439. }
  440. /** Go through and mark the authoritative dirservers as up. */
  441. static void
  442. mark_all_trusteddirservers_up(void)
  443. {
  444. if (routerlist) {
  445. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  446. if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
  447. router->dir_port > 0) {
  448. router->is_running = 1;
  449. });
  450. }
  451. if (trusted_dir_servers) {
  452. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  453. {
  454. local_routerstatus_t *rs;
  455. dir->is_running = 1;
  456. dir->n_networkstatus_failures = 0;
  457. rs = router_get_combined_status_by_digest(dir->digest);
  458. if (rs)
  459. rs->status.is_running = 1;
  460. });
  461. }
  462. last_networkstatus_download_attempted = 0;
  463. }
  464. /** Reset all internal variables used to count failed downloads of network
  465. * status objects. */
  466. void
  467. router_reset_status_download_failures(void)
  468. {
  469. mark_all_trusteddirservers_up();
  470. }
  471. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  472. * This is used to make sure we don't pick siblings in a single path.
  473. */
  474. void
  475. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  476. {
  477. routerinfo_t *r;
  478. config_line_t *cl;
  479. if (!router->declared_family)
  480. return;
  481. /* Add every r such that router declares familyness with r, and r
  482. * declares familyhood with router. */
  483. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  484. {
  485. if (!(r = router_get_by_nickname(n, 0)))
  486. continue;
  487. if (!r->declared_family)
  488. continue;
  489. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  490. {
  491. if (router_nickname_matches(router, n2))
  492. smartlist_add(sl, r);
  493. });
  494. });
  495. /* If the user declared any families locally, honor those too. */
  496. for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
  497. if (router_nickname_is_in_list(router, cl->value)) {
  498. add_nickname_list_to_smartlist(sl, cl->value, 0, 1, 1);
  499. }
  500. }
  501. }
  502. /** Given a comma-and-whitespace separated list of nicknames, see which
  503. * nicknames in <b>list</b> name routers in our routerlist that are
  504. * currently running. Add the routerinfos for those routers to <b>sl</b>.
  505. */
  506. void
  507. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
  508. int must_be_running,
  509. int warn_if_down, int warn_if_unnamed)
  510. {
  511. routerinfo_t *router;
  512. smartlist_t *nickname_list;
  513. int have_dir_info = router_have_minimum_dir_info();
  514. if (!list)
  515. return; /* nothing to do */
  516. tor_assert(sl);
  517. nickname_list = smartlist_create();
  518. if (!warned_nicknames)
  519. warned_nicknames = smartlist_create();
  520. smartlist_split_string(nickname_list, list, ",",
  521. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  522. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  523. int warned;
  524. if (!is_legal_nickname_or_hexdigest(nick)) {
  525. log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
  526. continue;
  527. }
  528. router = router_get_by_nickname(nick, warn_if_unnamed);
  529. warned = smartlist_string_isin(warned_nicknames, nick);
  530. if (router) {
  531. if (!must_be_running || router->is_running) {
  532. smartlist_add(sl,router);
  533. if (warned)
  534. smartlist_string_remove(warned_nicknames, nick);
  535. } else {
  536. if (!warned) {
  537. log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG, LD_CONFIG,
  538. "Nickname list includes '%s' which is known but down.",nick);
  539. smartlist_add(warned_nicknames, tor_strdup(nick));
  540. }
  541. }
  542. } else {
  543. if (!warned) {
  544. log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
  545. "Nickname list includes '%s' which isn't a known router.",nick);
  546. smartlist_add(warned_nicknames, tor_strdup(nick));
  547. }
  548. }
  549. });
  550. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  551. smartlist_free(nickname_list);
  552. }
  553. /** Return 1 iff any member of the comma-separated list <b>list</b> is an
  554. * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
  555. */
  556. static int
  557. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  558. {
  559. smartlist_t *nickname_list;
  560. int v = 0;
  561. if (!list)
  562. return 0; /* definitely not */
  563. tor_assert(router);
  564. nickname_list = smartlist_create();
  565. smartlist_split_string(nickname_list, list, ",",
  566. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  567. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  568. if (router_nickname_matches(router, cp)) {v=1;break;});
  569. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  570. smartlist_free(nickname_list);
  571. return v;
  572. }
  573. /** Add every router from our routerlist that is currently running to
  574. * <b>sl</b>, so that we can pick a node for a circuit.
  575. */
  576. static void
  577. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_invalid,
  578. int need_uptime, int need_capacity,
  579. int need_guard)
  580. {
  581. if (!routerlist)
  582. return;
  583. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  584. {
  585. if (router->is_running &&
  586. router->purpose == ROUTER_PURPOSE_GENERAL &&
  587. (router->is_valid ||
  588. /* XXX this next part is wrong and should be fixed one day -RD */
  589. (allow_invalid &&
  590. !router_is_unreliable(router, need_uptime,
  591. need_capacity, need_guard)))) {
  592. /* If it's running, and either it's valid or we're ok picking
  593. * invalid routers and this one is suitable.
  594. */
  595. smartlist_add(sl, router);
  596. }
  597. });
  598. }
  599. /** Look through the routerlist until we find a router that has my key.
  600. Return it. */
  601. routerinfo_t *
  602. routerlist_find_my_routerinfo(void)
  603. {
  604. if (!routerlist)
  605. return NULL;
  606. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  607. {
  608. if (router_is_me(router))
  609. return router;
  610. });
  611. return NULL;
  612. }
  613. /** Find a router that's up, that has this IP address, and
  614. * that allows exit to this address:port, or return NULL if there
  615. * isn't a good one.
  616. */
  617. routerinfo_t *
  618. router_find_exact_exit_enclave(const char *address, uint16_t port)
  619. {
  620. uint32_t addr;
  621. struct in_addr in;
  622. if (!tor_inet_aton(address, &in))
  623. return NULL; /* it's not an IP already */
  624. addr = ntohl(in.s_addr);
  625. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  626. {
  627. if (router->is_running &&
  628. router->addr == addr &&
  629. compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
  630. ADDR_POLICY_ACCEPTED)
  631. return router;
  632. });
  633. return NULL;
  634. }
  635. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  636. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  637. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  638. * bandwidth.
  639. */
  640. int
  641. router_is_unreliable(routerinfo_t *router, int need_uptime,
  642. int need_capacity, int need_guard)
  643. {
  644. if (need_uptime && !router->is_stable)
  645. return 1;
  646. if (need_capacity && !router->is_fast)
  647. return 1;
  648. if (need_guard && !router->is_possible_guard)
  649. return 1;
  650. return 0;
  651. }
  652. /** Remove from routerlist <b>sl</b> all routers that are not
  653. * sufficiently stable. */
  654. static void
  655. routerlist_sl_remove_unreliable_routers(smartlist_t *sl, int need_uptime,
  656. int need_capacity, int need_guard)
  657. {
  658. int i;
  659. routerinfo_t *router;
  660. for (i = 0; i < smartlist_len(sl); ++i) {
  661. router = smartlist_get(sl, i);
  662. if (router_is_unreliable(router, need_uptime,
  663. need_capacity, need_guard)) {
  664. // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
  665. // router->nickname);
  666. smartlist_del(sl, i--);
  667. }
  668. }
  669. }
  670. /** Return the smaller of the router's configured BandwidthRate
  671. * and its advertised capacity. */
  672. uint32_t
  673. router_get_advertised_bandwidth(routerinfo_t *router)
  674. {
  675. if (router->bandwidthcapacity < router->bandwidthrate)
  676. return router->bandwidthcapacity;
  677. return router->bandwidthrate;
  678. }
  679. #define MAX_BELIEVABLE_BANDWIDTH 1500000 /* 1.5 MB/sec */
  680. /** Choose a random element of router list <b>sl</b>, weighted by
  681. * the advertised bandwidth of each router.
  682. */
  683. routerinfo_t *
  684. routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
  685. {
  686. int i;
  687. routerinfo_t *router;
  688. smartlist_t *bandwidths;
  689. uint32_t this_bw, tmp, total_bw=0, rand_bw;
  690. uint32_t *p;
  691. /* First count the total bandwidth weight, and make a smartlist
  692. * of each value. */
  693. bandwidths = smartlist_create();
  694. for (i = 0; i < smartlist_len(sl); ++i) {
  695. router = smartlist_get(sl, i);
  696. this_bw = router_get_advertised_bandwidth(router);
  697. /* if they claim something huge, don't believe it */
  698. if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
  699. this_bw = MAX_BELIEVABLE_BANDWIDTH;
  700. p = tor_malloc(sizeof(uint32_t));
  701. *p = this_bw;
  702. smartlist_add(bandwidths, p);
  703. total_bw += this_bw;
  704. }
  705. if (!total_bw) {
  706. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  707. smartlist_free(bandwidths);
  708. return smartlist_choose(sl);
  709. }
  710. /* Second, choose a random value from the bandwidth weights. */
  711. rand_bw = crypto_rand_int(total_bw);
  712. /* Last, count through sl until we get to the element we picked */
  713. tmp = 0;
  714. for (i=0; ; i++) {
  715. tor_assert(i < smartlist_len(sl));
  716. p = smartlist_get(bandwidths, i);
  717. tmp += *p;
  718. if (tmp >= rand_bw)
  719. break;
  720. }
  721. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  722. smartlist_free(bandwidths);
  723. return (routerinfo_t *)smartlist_get(sl, i);
  724. }
  725. /** Return a random running router from the routerlist. If any node
  726. * named in <b>preferred</b> is available, pick one of those. Never
  727. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  728. * <b>excludedsmartlist</b>, even if they are the only nodes
  729. * available. If <b>strict</b> is true, never pick any node besides
  730. * those in <b>preferred</b>.
  731. * If <b>need_uptime</b> is non-zero and any router has more than
  732. * a minimum uptime, return one of those.
  733. * If <b>need_capacity</b> is non-zero, weight your choice by the
  734. * advertised capacity of each router.
  735. */
  736. routerinfo_t *
  737. router_choose_random_node(const char *preferred,
  738. const char *excluded,
  739. smartlist_t *excludedsmartlist,
  740. int need_uptime, int need_capacity,
  741. int need_guard,
  742. int allow_invalid, int strict)
  743. {
  744. smartlist_t *sl, *excludednodes;
  745. routerinfo_t *choice = NULL;
  746. excludednodes = smartlist_create();
  747. add_nickname_list_to_smartlist(excludednodes,excluded,0,0,1);
  748. /* Try the preferred nodes first. Ignore need_uptime and need_capacity
  749. * and need_guard, since the user explicitly asked for these nodes. */
  750. if (preferred) {
  751. sl = smartlist_create();
  752. add_nickname_list_to_smartlist(sl,preferred,1,1,1);
  753. smartlist_subtract(sl,excludednodes);
  754. if (excludedsmartlist)
  755. smartlist_subtract(sl,excludedsmartlist);
  756. choice = smartlist_choose(sl);
  757. smartlist_free(sl);
  758. }
  759. if (!choice && !strict) {
  760. /* Then give up on our preferred choices: any node
  761. * will do that has the required attributes. */
  762. sl = smartlist_create();
  763. router_add_running_routers_to_smartlist(sl, allow_invalid,
  764. need_uptime, need_capacity,
  765. need_guard);
  766. smartlist_subtract(sl,excludednodes);
  767. if (excludedsmartlist)
  768. smartlist_subtract(sl,excludedsmartlist);
  769. routerlist_sl_remove_unreliable_routers(sl, need_uptime,
  770. need_capacity, need_guard);
  771. if (need_capacity)
  772. choice = routerlist_sl_choose_by_bandwidth(sl);
  773. else
  774. choice = smartlist_choose(sl);
  775. smartlist_free(sl);
  776. if (!choice && (need_uptime || need_capacity || need_guard)) {
  777. /* try once more -- recurse but with fewer restrictions. */
  778. log_info(LD_CIRC,
  779. "We couldn't find any live%s%s%s routers; falling back "
  780. "to list of all routers.",
  781. need_capacity?", fast":"",
  782. need_uptime?", stable":"",
  783. need_guard?", guard":"");
  784. choice = router_choose_random_node(
  785. NULL, excluded, excludedsmartlist, 0, 0, 0, allow_invalid, 0);
  786. }
  787. }
  788. smartlist_free(excludednodes);
  789. if (!choice)
  790. log_warn(LD_CIRC,
  791. "No available nodes when trying to choose node. Failing.");
  792. return choice;
  793. }
  794. /** Return true iff the digest of <b>router</b>'s identity key,
  795. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  796. * optionally prefixed with a single dollar sign). Return false if
  797. * <b>hexdigest</b> is malformed, or it doesn't match. */
  798. static INLINE int
  799. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  800. {
  801. char digest[DIGEST_LEN];
  802. tor_assert(hexdigest);
  803. if (hexdigest[0] == '$')
  804. ++hexdigest;
  805. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  806. base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  807. return 0;
  808. return (!memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
  809. }
  810. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  811. * (case-insensitive), or if <b>router's</b> identity key digest
  812. * matches a hexadecimal value stored in <b>nickname</b>. Return
  813. * false otherwise. */
  814. static int
  815. router_nickname_matches(routerinfo_t *router, const char *nickname)
  816. {
  817. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  818. return 1;
  819. return router_hex_digest_matches(router, nickname);
  820. }
  821. /** Return the router in our routerlist whose (case-insensitive)
  822. * nickname or (case-sensitive) hexadecimal key digest is
  823. * <b>nickname</b>. Return NULL if no such router is known.
  824. */
  825. routerinfo_t *
  826. router_get_by_nickname(const char *nickname, int warn_if_unnamed)
  827. {
  828. int maybedigest;
  829. char digest[DIGEST_LEN];
  830. routerinfo_t *best_match=NULL;
  831. int n_matches = 0;
  832. tor_assert(nickname);
  833. if (!routerlist)
  834. return NULL;
  835. if (nickname[0] == '$')
  836. return router_get_by_hexdigest(nickname);
  837. if (server_mode(get_options()) &&
  838. !strcasecmp(nickname, get_options()->Nickname))
  839. return router_get_my_routerinfo();
  840. maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
  841. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  842. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  843. {
  844. if (!strcasecmp(router->nickname, nickname)) {
  845. if (router->is_named)
  846. return router;
  847. else {
  848. ++n_matches;
  849. if (n_matches <= 1 || router->is_running)
  850. best_match = router;
  851. }
  852. } else if (maybedigest &&
  853. !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
  854. ) {
  855. return router;
  856. }
  857. });
  858. if (best_match) {
  859. if (warn_if_unnamed && n_matches > 1) {
  860. smartlist_t *fps = smartlist_create();
  861. int any_unwarned = 0;
  862. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  863. {
  864. local_routerstatus_t *rs;
  865. char *desc;
  866. size_t dlen;
  867. char fp[HEX_DIGEST_LEN+1];
  868. if (strcasecmp(router->nickname, nickname))
  869. continue;
  870. rs = router_get_combined_status_by_digest(
  871. router->cache_info.identity_digest);
  872. if (rs && !rs->name_lookup_warned) {
  873. rs->name_lookup_warned = 1;
  874. any_unwarned = 1;
  875. }
  876. base16_encode(fp, sizeof(fp),
  877. router->cache_info.identity_digest, DIGEST_LEN);
  878. dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
  879. desc = tor_malloc(dlen);
  880. tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
  881. fp, router->address, router->or_port);
  882. smartlist_add(fps, desc);
  883. });
  884. if (any_unwarned) {
  885. char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
  886. log_warn(LD_CONFIG,
  887. "There are multiple matches for the nickname \"%s\","
  888. " but none is listed as named by the directory authories. "
  889. "Choosing one arbitrarily. If you meant one in particular, "
  890. "you should say %s.", nickname, alternatives);
  891. tor_free(alternatives);
  892. }
  893. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  894. smartlist_free(fps);
  895. } else if (warn_if_unnamed) {
  896. local_routerstatus_t *rs = router_get_combined_status_by_digest(
  897. best_match->cache_info.identity_digest);
  898. if (rs && !rs->name_lookup_warned) {
  899. char fp[HEX_DIGEST_LEN+1];
  900. base16_encode(fp, sizeof(fp),
  901. best_match->cache_info.identity_digest, DIGEST_LEN);
  902. log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but the "
  903. "directory authorities do not have a listing for this name. "
  904. "To make sure you get the same server in the future, refer to "
  905. "it by key, as \"$%s\".", nickname, fp);
  906. rs->name_lookup_warned = 1;
  907. }
  908. }
  909. return best_match;
  910. }
  911. return NULL;
  912. }
  913. /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
  914. * return 1. If we do, ask tor_version_as_new_as() for the answer.
  915. */
  916. int
  917. router_digest_version_as_new_as(const char *digest, const char *cutoff)
  918. {
  919. routerinfo_t *router = router_get_by_digest(digest);
  920. if (!router)
  921. return 1;
  922. return tor_version_as_new_as(router->platform, cutoff);
  923. }
  924. /** Return true iff <b>digest</b> is the digest of the identity key of
  925. * a trusted directory. */
  926. int
  927. router_digest_is_trusted_dir(const char *digest)
  928. {
  929. if (!trusted_dir_servers)
  930. return 0;
  931. if (get_options()->AuthoritativeDir &&
  932. router_digest_is_me(digest))
  933. return 1;
  934. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  935. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  936. return 0;
  937. }
  938. /** Return the router in our routerlist whose hexadecimal key digest
  939. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  940. routerinfo_t *
  941. router_get_by_hexdigest(const char *hexdigest)
  942. {
  943. char digest[DIGEST_LEN];
  944. tor_assert(hexdigest);
  945. if (!routerlist)
  946. return NULL;
  947. if (hexdigest[0]=='$')
  948. ++hexdigest;
  949. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  950. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  951. return NULL;
  952. return router_get_by_digest(digest);
  953. }
  954. /** Return the router in our routerlist whose 20-byte key digest
  955. * is <b>digest</b>. Return NULL if no such router is known. */
  956. routerinfo_t *
  957. router_get_by_digest(const char *digest)
  958. {
  959. tor_assert(digest);
  960. if (!routerlist) return NULL;
  961. // routerlist_assert_ok(routerlist);
  962. return digestmap_get(routerlist->identity_map, digest);
  963. }
  964. /** Return the router in our routerlist whose 20-byte descriptor
  965. * is <b>digest</b>. Return NULL if no such router is known. */
  966. signed_descriptor_t *
  967. router_get_by_descriptor_digest(const char *digest)
  968. {
  969. tor_assert(digest);
  970. if (!routerlist) return NULL;
  971. return digestmap_get(routerlist->desc_digest_map, digest);
  972. }
  973. const char *
  974. signed_descriptor_get_body(signed_descriptor_t *desc)
  975. {
  976. return desc->signed_descriptor_body;
  977. }
  978. /** Return the current list of all known routers. */
  979. routerlist_t *
  980. router_get_routerlist(void)
  981. {
  982. if (!routerlist) {
  983. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  984. routerlist->routers = smartlist_create();
  985. routerlist->old_routers = smartlist_create();
  986. routerlist->identity_map = digestmap_new();
  987. routerlist->desc_digest_map = digestmap_new();
  988. }
  989. return routerlist;
  990. }
  991. /** Free all storage held by <b>router</b>. */
  992. void
  993. routerinfo_free(routerinfo_t *router)
  994. {
  995. if (!router)
  996. return;
  997. tor_free(router->cache_info.signed_descriptor_body);
  998. tor_free(router->address);
  999. tor_free(router->nickname);
  1000. tor_free(router->platform);
  1001. tor_free(router->contact_info);
  1002. if (router->onion_pkey)
  1003. crypto_free_pk_env(router->onion_pkey);
  1004. if (router->identity_pkey)
  1005. crypto_free_pk_env(router->identity_pkey);
  1006. if (router->declared_family) {
  1007. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  1008. smartlist_free(router->declared_family);
  1009. }
  1010. addr_policy_free(router->exit_policy);
  1011. tor_free(router);
  1012. }
  1013. /** Release storage held by <b>sd</b>. */
  1014. static void
  1015. signed_descriptor_free(signed_descriptor_t *sd)
  1016. {
  1017. tor_free(sd->signed_descriptor_body);
  1018. tor_free(sd);
  1019. }
  1020. /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
  1021. */
  1022. static signed_descriptor_t *
  1023. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  1024. {
  1025. signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  1026. memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
  1027. ri->cache_info.signed_descriptor_body = NULL;
  1028. routerinfo_free(ri);
  1029. return sd;
  1030. }
  1031. /** Free all storage held by a routerlist <b>rl</b> */
  1032. void
  1033. routerlist_free(routerlist_t *rl)
  1034. {
  1035. tor_assert(rl);
  1036. digestmap_free(rl->identity_map, NULL);
  1037. digestmap_free(rl->desc_digest_map, NULL);
  1038. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1039. routerinfo_free(r));
  1040. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  1041. signed_descriptor_free(sd));
  1042. smartlist_free(rl->routers);
  1043. smartlist_free(rl->old_routers);
  1044. tor_free(rl);
  1045. }
  1046. void
  1047. dump_routerlist_mem_usage(int severity)
  1048. {
  1049. uint64_t livedescs = 0;
  1050. uint64_t olddescs = 0;
  1051. if (!routerlist)
  1052. return;
  1053. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  1054. livedescs += r->cache_info.signed_descriptor_len);
  1055. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  1056. olddescs += sd->signed_descriptor_len);
  1057. log(severity, LD_GENERAL,
  1058. "In %d live descriptors: "U64_FORMAT" bytes. "
  1059. "In %d old descriptors: "U64_FORMAT" bytes.",
  1060. smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
  1061. smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
  1062. }
  1063. /** Return the greatest number of routerdescs we'll hold for any given router.
  1064. */
  1065. static int
  1066. max_descriptors_per_router(void)
  1067. {
  1068. int n_authorities = 0;
  1069. if (trusted_dir_servers)
  1070. n_authorities = smartlist_len(trusted_dir_servers);
  1071. return (n_authorities < 5) ? 5 : n_authorities;
  1072. }
  1073. /** Return non-zero if we have a lot of extra descriptors in our
  1074. * routerlist, and should get rid of some of them. Else return 0.
  1075. *
  1076. * We should be careful to not return true too eagerly, since we
  1077. * could churn. By using "+1" below, we make sure this function
  1078. * only returns true at most every smartlist_len(rl-\>routers)
  1079. * new descriptors.
  1080. */
  1081. static INLINE int
  1082. routerlist_is_overfull(routerlist_t *rl)
  1083. {
  1084. return smartlist_len(rl->old_routers) >
  1085. smartlist_len(rl->routers)*(max_descriptors_per_router()+1);
  1086. }
  1087. static INLINE int
  1088. _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
  1089. {
  1090. if (idx < 0 || smartlist_get(sl, idx) != ri) {
  1091. idx = -1;
  1092. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  1093. if (r == ri) {
  1094. idx = r_sl_idx;
  1095. break;
  1096. });
  1097. }
  1098. return idx;
  1099. }
  1100. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  1101. * as needed. */
  1102. static void
  1103. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  1104. {
  1105. digestmap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  1106. digestmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
  1107. &(ri->cache_info));
  1108. smartlist_add(rl->routers, ri);
  1109. // routerlist_assert_ok(rl);
  1110. }
  1111. static void
  1112. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  1113. {
  1114. if (get_options()->DirPort &&
  1115. !digestmap_get(rl->desc_digest_map,
  1116. ri->cache_info.signed_descriptor_digest)) {
  1117. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  1118. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1119. smartlist_add(rl->old_routers, sd);
  1120. } else {
  1121. routerinfo_free(ri);
  1122. }
  1123. // routerlist_assert_ok(rl);
  1124. }
  1125. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  1126. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  1127. * idx) == ri, we don't need to do a linear search over the list to decide
  1128. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  1129. * the list, if any exists. <b>ri</b> is freed. */
  1130. void
  1131. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
  1132. {
  1133. routerinfo_t *ri_tmp;
  1134. idx = _routerlist_find_elt(rl->routers, ri, idx);
  1135. if (idx < 0)
  1136. return;
  1137. smartlist_del(rl->routers, idx);
  1138. ri_tmp = digestmap_remove(rl->identity_map, ri->cache_info.identity_digest);
  1139. tor_assert(ri_tmp == ri);
  1140. if (make_old && get_options()->DirPort) {
  1141. signed_descriptor_t *sd;
  1142. sd = signed_descriptor_from_routerinfo(ri);
  1143. smartlist_add(rl->old_routers, sd);
  1144. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1145. } else {
  1146. ri_tmp = digestmap_remove(rl->desc_digest_map,
  1147. ri->cache_info.signed_descriptor_digest);
  1148. tor_assert(ri_tmp == ri);
  1149. router_bytes_dropped += ri->cache_info.signed_descriptor_len;
  1150. routerinfo_free(ri);
  1151. }
  1152. // routerlist_assert_ok(rl);
  1153. }
  1154. static void
  1155. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  1156. {
  1157. signed_descriptor_t *sd_tmp;
  1158. idx = _routerlist_find_elt(rl->old_routers, sd, idx);
  1159. if (idx < 0)
  1160. return;
  1161. smartlist_del(rl->old_routers, idx);
  1162. sd_tmp = digestmap_remove(rl->desc_digest_map,
  1163. sd->signed_descriptor_digest);
  1164. tor_assert(sd_tmp == sd);
  1165. router_bytes_dropped += sd->signed_descriptor_len;
  1166. signed_descriptor_free(sd);
  1167. // routerlist_assert_ok(rl);
  1168. }
  1169. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  1170. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  1171. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  1172. * search over the list to decide which to remove. We put ri_new in the same
  1173. * index as ri_old, if possible. ri is freed as appropriate. */
  1174. static void
  1175. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  1176. routerinfo_t *ri_new, int idx, int make_old)
  1177. {
  1178. tor_assert(ri_old != ri_new);
  1179. idx = _routerlist_find_elt(rl->routers, ri_old, idx);
  1180. if (idx >= 0) {
  1181. smartlist_set(rl->routers, idx, ri_new);
  1182. } else {
  1183. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  1184. routerlist_insert(rl, ri_new);
  1185. return;
  1186. }
  1187. if (memcmp(ri_old->cache_info.identity_digest,
  1188. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  1189. /* digests don't match; digestmap_set won't replace */
  1190. digestmap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  1191. }
  1192. digestmap_set(rl->identity_map, ri_new->cache_info.identity_digest, ri_new);
  1193. digestmap_set(rl->desc_digest_map,
  1194. ri_new->cache_info.signed_descriptor_digest, &(ri_new->cache_info));
  1195. if (make_old && get_options()->DirPort) {
  1196. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  1197. smartlist_add(rl->old_routers, sd);
  1198. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1199. } else {
  1200. if (memcmp(ri_old->cache_info.signed_descriptor_digest,
  1201. ri_new->cache_info.signed_descriptor_digest,
  1202. DIGEST_LEN)) {
  1203. /* digests don't match; digestmap_set didn't replace */
  1204. digestmap_remove(rl->desc_digest_map,
  1205. ri_old->cache_info.signed_descriptor_digest);
  1206. }
  1207. routerinfo_free(ri_old);
  1208. }
  1209. // routerlist_assert_ok(rl);
  1210. }
  1211. /** Free all memory held by the routerlist module. */
  1212. void
  1213. routerlist_free_all(void)
  1214. {
  1215. if (routerlist)
  1216. routerlist_free(routerlist);
  1217. routerlist = NULL;
  1218. if (warned_nicknames) {
  1219. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1220. smartlist_free(warned_nicknames);
  1221. warned_nicknames = NULL;
  1222. }
  1223. if (warned_conflicts) {
  1224. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1225. smartlist_free(warned_conflicts);
  1226. warned_conflicts = NULL;
  1227. }
  1228. if (trusted_dir_servers) {
  1229. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1230. trusted_dir_server_free(ds));
  1231. smartlist_free(trusted_dir_servers);
  1232. trusted_dir_servers = NULL;
  1233. }
  1234. if (networkstatus_list) {
  1235. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1236. networkstatus_free(ns));
  1237. smartlist_free(networkstatus_list);
  1238. networkstatus_list = NULL;
  1239. }
  1240. if (routerstatus_list) {
  1241. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1242. local_routerstatus_free(rs));
  1243. smartlist_free(routerstatus_list);
  1244. routerstatus_list = NULL;
  1245. }
  1246. }
  1247. /** Free all storage held by the routerstatus object <b>rs</b>. */
  1248. void
  1249. routerstatus_free(routerstatus_t *rs)
  1250. {
  1251. tor_free(rs);
  1252. }
  1253. /** Free all storage held by the local_routerstatus object <b>rs</b>. */
  1254. static void
  1255. local_routerstatus_free(local_routerstatus_t *rs)
  1256. {
  1257. tor_free(rs);
  1258. }
  1259. /** Free all storage held by the networkstatus object <b>ns</b>. */
  1260. void
  1261. networkstatus_free(networkstatus_t *ns)
  1262. {
  1263. tor_free(ns->source_address);
  1264. tor_free(ns->contact);
  1265. if (ns->signing_key)
  1266. crypto_free_pk_env(ns->signing_key);
  1267. tor_free(ns->client_versions);
  1268. tor_free(ns->server_versions);
  1269. if (ns->entries) {
  1270. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1271. routerstatus_free(rs));
  1272. smartlist_free(ns->entries);
  1273. }
  1274. tor_free(ns);
  1275. }
  1276. /** Forget that we have issued any router-related warnings, so that we'll
  1277. * warn again if we see the same errors. */
  1278. void
  1279. routerlist_reset_warnings(void)
  1280. {
  1281. if (!warned_nicknames)
  1282. warned_nicknames = smartlist_create();
  1283. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1284. smartlist_clear(warned_nicknames); /* now the list is empty. */
  1285. if (!warned_conflicts)
  1286. warned_conflicts = smartlist_create();
  1287. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1288. smartlist_clear(warned_conflicts); /* now the list is empty. */
  1289. if (!routerstatus_list)
  1290. routerstatus_list = smartlist_create();
  1291. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1292. rs->name_lookup_warned = 0);
  1293. have_warned_about_invalid_status = 0;
  1294. have_warned_about_old_version = 0;
  1295. have_warned_about_new_version = 0;
  1296. }
  1297. /** Mark the router with ID <b>digest</b> as running or non-running
  1298. * in our routerlist. */
  1299. void
  1300. router_set_status(const char *digest, int up)
  1301. {
  1302. routerinfo_t *router;
  1303. local_routerstatus_t *status;
  1304. tor_assert(digest);
  1305. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  1306. if (!memcmp(d->digest, digest, DIGEST_LEN))
  1307. d->is_running = up);
  1308. router = router_get_by_digest(digest);
  1309. if (router) {
  1310. log_debug(LD_DIR,"Marking router '%s' as %s.",
  1311. router->nickname, up ? "up" : "down");
  1312. if (!up && router_is_me(router) && !we_are_hibernating())
  1313. log_warn(LD_NET, "We just marked ourself as down. Are your external "
  1314. "addresses reachable?");
  1315. router->is_running = up;
  1316. }
  1317. status = router_get_combined_status_by_digest(digest);
  1318. if (status) {
  1319. status->status.is_running = up;
  1320. }
  1321. }
  1322. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  1323. * older entries (if any) with the same key. Note: Callers should not hold
  1324. * their pointers to <b>router</b> if this function fails; <b>router</b>
  1325. * will either be inserted into the routerlist or freed.
  1326. *
  1327. * Returns >= 0 if the router was added; less than 0 if it was not.
  1328. *
  1329. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  1330. * describing the reason for not liking the routerinfo.
  1331. *
  1332. * If the return value is less than -1, there was a problem with the
  1333. * routerinfo. If the return value is equal to -1, then the routerinfo was
  1334. * fine, but out-of-date. If the return value is equal to 1, the
  1335. * routerinfo was accepted, but we should notify the generator of the
  1336. * descriptor using the message *<b>msg</b>.
  1337. *
  1338. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  1339. * <b>from_fetch</b>, we received it in response to a request we made.
  1340. * (If both are false, that means it was uploaded to us as an auth dir
  1341. * server or via the controller.)
  1342. *
  1343. * This function should be called *after*
  1344. * routers_update_status_from_networkstatus; subsequently, you should call
  1345. * router_rebuild_store and control_event_descriptors_changed.
  1346. */
  1347. int
  1348. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  1349. int from_cache, int from_fetch)
  1350. {
  1351. int i;
  1352. const char *id_digest;
  1353. int authdir = get_options()->AuthoritativeDir;
  1354. int authdir_believes_valid = 0;
  1355. tor_assert(msg);
  1356. if (!routerlist)
  1357. router_get_routerlist();
  1358. if (!networkstatus_list)
  1359. networkstatus_list = smartlist_create();
  1360. id_digest = router->cache_info.identity_digest;
  1361. /* Make sure that we haven't already got this exact descriptor. */
  1362. if (digestmap_get(routerlist->desc_digest_map,
  1363. router->cache_info.signed_descriptor_digest)) {
  1364. log_info(LD_DIR,
  1365. "Dropping descriptor that we already have for router '%s'",
  1366. router->nickname);
  1367. *msg = "Router descriptor was not new.";
  1368. routerinfo_free(router);
  1369. return -1;
  1370. }
  1371. if (routerlist_is_overfull(routerlist))
  1372. routerlist_remove_old_routers();
  1373. if (authdir) {
  1374. if (authdir_wants_to_reject_router(router, msg,
  1375. !from_cache && !from_fetch)) {
  1376. tor_assert(*msg);
  1377. routerinfo_free(router);
  1378. return -2;
  1379. }
  1380. authdir_believes_valid = router->is_valid;
  1381. } else if (from_fetch) {
  1382. /* Only check the descriptor digest against the network statuses when
  1383. * we are receiving in response to a fetch. */
  1384. if (!signed_desc_digest_is_recognized(&router->cache_info)) {
  1385. log_warn(LD_DIR, "Dropping unrecognized descriptor for router '%s'",
  1386. router->nickname);
  1387. *msg = "Router descriptor is not referenced by any network-status.";
  1388. routerinfo_free(router);
  1389. return -1;
  1390. }
  1391. }
  1392. /* We no longer need a router with this descriptor digest. */
  1393. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1394. {
  1395. routerstatus_t *rs =
  1396. networkstatus_find_entry(ns, router->cache_info.identity_digest);
  1397. if (rs && !memcmp(rs->descriptor_digest,
  1398. router->cache_info.signed_descriptor_digest,
  1399. DIGEST_LEN))
  1400. rs->need_to_mirror = 0;
  1401. });
  1402. /* Probably, there's no way to actually pass this function our own
  1403. * descriptor, but in case there is, don't replace our own descriptor. */
  1404. if (router_is_me(router)) {
  1405. routerinfo_free(router);
  1406. return 0;
  1407. }
  1408. /* If we have a router with this name, and the identity key is the same,
  1409. * choose the newer one. If the identity key has changed, and one of the
  1410. * routers is named, drop the unnamed ones. (If more than one are named,
  1411. * drop the old ones.)
  1412. */
  1413. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1414. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  1415. if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
  1416. if (router->cache_info.published_on <=
  1417. old_router->cache_info.published_on) {
  1418. /* Same key, but old */
  1419. log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
  1420. router->nickname);
  1421. /* Only journal this desc if we'll be serving it. */
  1422. if (!from_cache && get_options()->DirPort)
  1423. router_append_to_journal(&router->cache_info);
  1424. routerlist_insert_old(routerlist, router);
  1425. *msg = "Router descriptor was not new.";
  1426. return -1;
  1427. } else {
  1428. /* Same key, new. */
  1429. int unreachable = 0;
  1430. log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
  1431. router->nickname, old_router->nickname,
  1432. hex_str(id_digest,DIGEST_LEN));
  1433. if (router->addr == old_router->addr &&
  1434. router->or_port == old_router->or_port) {
  1435. /* these carry over when the address and orport are unchanged.*/
  1436. router->last_reachable = old_router->last_reachable;
  1437. router->testing_since = old_router->testing_since;
  1438. router->num_unreachable_notifications =
  1439. old_router->num_unreachable_notifications;
  1440. }
  1441. if (authdir && !from_cache && !from_fetch &&
  1442. router_have_minimum_dir_info() &&
  1443. dirserv_thinks_router_is_blatantly_unreachable(router,
  1444. time(NULL))) {
  1445. if (router->num_unreachable_notifications >= 3) {
  1446. unreachable = 1;
  1447. log_notice(LD_DIR, "Notifying server '%s' that it's unreachable. "
  1448. "(ContactInfo '%s', platform '%s').",
  1449. router->nickname,
  1450. router->contact_info ? router->contact_info : "",
  1451. router->platform ? router->platform : "");
  1452. } else {
  1453. log_info(LD_DIR,"'%s' may be unreachable -- the %d previous "
  1454. "descriptors were thought to be unreachable.",
  1455. router->nickname, router->num_unreachable_notifications);
  1456. router->num_unreachable_notifications++;
  1457. }
  1458. }
  1459. routerlist_replace(routerlist, old_router, router, i, 1);
  1460. if (!from_cache) {
  1461. router_append_to_journal(&router->cache_info);
  1462. }
  1463. directory_set_dirty();
  1464. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  1465. authdir_believes_valid ? "Valid server updated" :
  1466. ("Invalid server updated. (This dirserver is marking your "
  1467. "server as unapproved.)");
  1468. return unreachable ? 1 : 0;
  1469. }
  1470. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  1471. /* nicknames match, keys don't. */
  1472. if (router->is_named) {
  1473. /* The new named router replaces the old one; remove the
  1474. * old one. And carry on to the end of the list, in case
  1475. * there are more old unnamed routers with this nickname.
  1476. */
  1477. /* mark-for-close connections using the old key, so we can
  1478. * make new ones with the new key.
  1479. */
  1480. connection_t *conn;
  1481. while ((conn = connection_or_get_by_identity_digest(
  1482. old_router->cache_info.identity_digest))) {
  1483. log_info(LD_DIR,"Closing conn to router '%s'; there is now a named "
  1484. "router with that name.",
  1485. old_router->nickname);
  1486. connection_mark_for_close(conn);
  1487. }
  1488. routerlist_remove(routerlist, old_router, i--, 0);
  1489. } else if (old_router->is_named) {
  1490. /* Can't replace a named router with an unnamed one. */
  1491. log_debug(LD_DIR, "Skipping unnamed entry for named router '%s'",
  1492. router->nickname);
  1493. routerinfo_free(router);
  1494. *msg =
  1495. "Already have named router with same nickname and different key.";
  1496. return -2;
  1497. }
  1498. }
  1499. }
  1500. /* We haven't seen a router with this name before. Add it to the end of
  1501. * the list. */
  1502. routerlist_insert(routerlist, router);
  1503. if (!from_cache)
  1504. router_append_to_journal(&router->cache_info);
  1505. directory_set_dirty();
  1506. return 0;
  1507. }
  1508. static int
  1509. _compare_old_routers_by_identity(const void **_a, const void **_b)
  1510. {
  1511. int i;
  1512. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  1513. if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  1514. return i;
  1515. return r1->published_on - r2->published_on;
  1516. }
  1517. struct duration_idx_t {
  1518. int duration;
  1519. int idx;
  1520. int old;
  1521. };
  1522. static int
  1523. _compare_duration_idx(const void *_d1, const void *_d2)
  1524. {
  1525. const struct duration_idx_t *d1 = _d1;
  1526. const struct duration_idx_t *d2 = _d2;
  1527. return d1->duration - d2->duration;
  1528. }
  1529. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  1530. * must contain routerinfo_t with the same identity and with publication time
  1531. * in ascending order. Remove members from this range until there are no more
  1532. * than max_descriptors_per_router() remaining. Start by removing the oldest
  1533. * members from before <b>cutoff</b>, then remove members which were current
  1534. * for the lowest amount of time. The order of members of old_routers at
  1535. * indices <b>lo</b> or higher may be changed.
  1536. */
  1537. static void
  1538. routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi,
  1539. digestmap_t *retain)
  1540. {
  1541. int i, n = hi-lo+1, n_extra;
  1542. int n_rmv = 0;
  1543. struct duration_idx_t *lifespans;
  1544. uint8_t *rmv, *must_keep;
  1545. smartlist_t *lst = routerlist->old_routers;
  1546. #if 1
  1547. const char *ident;
  1548. tor_assert(hi < smartlist_len(lst));
  1549. tor_assert(lo <= hi);
  1550. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  1551. for (i = lo+1; i <= hi; ++i) {
  1552. signed_descriptor_t *r = smartlist_get(lst, i);
  1553. tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
  1554. }
  1555. #endif
  1556. /* Check whether we need to do anything at all. */
  1557. n_extra = n - max_descriptors_per_router();
  1558. if (n_extra <= 0)
  1559. return;
  1560. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  1561. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  1562. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  1563. /* Set lifespans to contain the lifespan and index of each server. */
  1564. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  1565. for (i = lo; i <= hi; ++i) {
  1566. signed_descriptor_t *r = smartlist_get(lst, i);
  1567. signed_descriptor_t *r_next;
  1568. lifespans[i-lo].idx = i;
  1569. if (retain && digestmap_get(retain, r->signed_descriptor_digest)) {
  1570. must_keep[i-lo] = 1;
  1571. }
  1572. if (i < hi) {
  1573. r_next = smartlist_get(lst, i+1);
  1574. tor_assert(r->published_on <= r_next->published_on);
  1575. lifespans[i-lo].duration = (r_next->published_on - r->published_on);
  1576. } else {
  1577. r_next = NULL;
  1578. lifespans[i-lo].duration = INT_MAX;
  1579. }
  1580. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  1581. ++n_rmv;
  1582. lifespans[i-lo].old = 1;
  1583. rmv[i-lo] = 1;
  1584. }
  1585. }
  1586. if (n_rmv < n_extra) {
  1587. /**
  1588. * We aren't removing enough servers for being old. Sort lifespans by
  1589. * the duration of liveness, and remove the ones we're not already going to
  1590. * remove based on how long they were alive.
  1591. **/
  1592. qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
  1593. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  1594. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  1595. rmv[lifespans[i].idx-lo] = 1;
  1596. ++n_rmv;
  1597. }
  1598. }
  1599. }
  1600. for (i = hi; i >= lo; --i) {
  1601. if (rmv[i-lo])
  1602. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  1603. }
  1604. tor_free(must_keep);
  1605. tor_free(rmv);
  1606. tor_free(lifespans);
  1607. }
  1608. /** Deactivate any routers from the routerlist that are more than
  1609. * ROUTER_MAX_AGE seconds old; remove old routers from the list of
  1610. * cached routers if we have too many.
  1611. */
  1612. void
  1613. routerlist_remove_old_routers(void)
  1614. {
  1615. int i, hi=-1;
  1616. const char *cur_id = NULL;
  1617. time_t now = time(NULL);
  1618. time_t cutoff;
  1619. routerinfo_t *router;
  1620. signed_descriptor_t *sd;
  1621. digestmap_t *retain;
  1622. or_options_t *options = get_options();
  1623. if (!routerlist || !networkstatus_list)
  1624. return;
  1625. retain = digestmap_new();
  1626. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1627. if (server_mode(options) && options->DirPort) {
  1628. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1629. {
  1630. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1631. if (rs->published_on >= cutoff)
  1632. digestmap_set(retain, rs->descriptor_digest, (void*)1));
  1633. });
  1634. }
  1635. cutoff = now - ROUTER_MAX_AGE;
  1636. /* Remove too-old members of routerlist->routers. */
  1637. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1638. router = smartlist_get(routerlist->routers, i);
  1639. if (router->cache_info.published_on <= cutoff &&
  1640. !digestmap_get(retain, router->cache_info.signed_descriptor_digest)) {
  1641. /* Too old. Remove it. */
  1642. log_info(LD_DIR,
  1643. "Forgetting obsolete (too old) routerinfo for router '%s'",
  1644. router->nickname);
  1645. routerlist_remove(routerlist, router, i--, 1);
  1646. }
  1647. }
  1648. /* Remove far-too-old members of routerlist->old_routers. */
  1649. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1650. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  1651. sd = smartlist_get(routerlist->old_routers, i);
  1652. if (sd->published_on <= cutoff &&
  1653. !digestmap_get(retain, sd->signed_descriptor_digest)) {
  1654. /* Too old. Remove it. */
  1655. routerlist_remove_old(routerlist, sd, i--);
  1656. }
  1657. }
  1658. /* Now we're looking at routerlist->old_routers for extraneous
  1659. * members. (We'd keep all the members if we could, but we'd like to save
  1660. * space.) First, check whether we have too many router descriptors, total.
  1661. * We're okay with having too many for some given router, so long as the
  1662. * total number doesn't approach max_descriptors_per_router()*len(router).
  1663. */
  1664. if (smartlist_len(routerlist->old_routers) <
  1665. smartlist_len(routerlist->routers) * (max_descriptors_per_router() - 1))
  1666. goto done;
  1667. smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
  1668. /* Iterate through the list from back to front, so when we remove descriptors
  1669. * we don't mess up groups we haven't gotten to. */
  1670. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  1671. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  1672. if (!cur_id) {
  1673. cur_id = r->identity_digest;
  1674. hi = i;
  1675. }
  1676. if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
  1677. routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi, retain);
  1678. cur_id = r->identity_digest;
  1679. hi = i;
  1680. }
  1681. }
  1682. if (hi>=0)
  1683. routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi, retain);
  1684. routerlist_assert_ok(routerlist);
  1685. done:
  1686. digestmap_free(retain, NULL);
  1687. }
  1688. /**
  1689. * Code to parse a single router descriptor and insert it into the
  1690. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  1691. * descriptor was well-formed but could not be added; and 1 if the
  1692. * descriptor was added.
  1693. *
  1694. * If we don't add it and <b>msg</b> is not NULL, then assign to
  1695. * *<b>msg</b> a static string describing the reason for refusing the
  1696. * descriptor.
  1697. *
  1698. * This is used only by the controller.
  1699. */
  1700. int
  1701. router_load_single_router(const char *s, uint8_t purpose, const char **msg)
  1702. {
  1703. routerinfo_t *ri;
  1704. int r;
  1705. smartlist_t *lst;
  1706. tor_assert(msg);
  1707. *msg = NULL;
  1708. if (!(ri = router_parse_entry_from_string(s, NULL))) {
  1709. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  1710. *msg = "Couldn't parse router descriptor.";
  1711. return -1;
  1712. }
  1713. ri->purpose = purpose;
  1714. if (router_is_me(ri)) {
  1715. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  1716. *msg = "Router's identity key matches mine.";
  1717. routerinfo_free(ri);
  1718. return 0;
  1719. }
  1720. lst = smartlist_create();
  1721. smartlist_add(lst, ri);
  1722. routers_update_status_from_networkstatus(lst, 0);
  1723. if ((r=router_add_to_routerlist(ri, msg, 0, 0))<0) {
  1724. /* we've already assigned to *msg now, and ri is already freed */
  1725. tor_assert(*msg);
  1726. if (r < -1)
  1727. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  1728. smartlist_free(lst);
  1729. return 0;
  1730. } else {
  1731. control_event_descriptors_changed(lst);
  1732. smartlist_free(lst);
  1733. log_debug(LD_DIR, "Added router to list");
  1734. return 1;
  1735. }
  1736. }
  1737. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  1738. * routers into our directory. If <b>from_cache</b> is false, the routers
  1739. * are in response to a query to the network: cache them.
  1740. *
  1741. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1742. * uppercased identity fingerprints. Do not update any router whose
  1743. * fingerprint is not on the list; after updating a router, remove its
  1744. * fingerprint from the list.
  1745. */
  1746. void
  1747. router_load_routers_from_string(const char *s, int from_cache,
  1748. smartlist_t *requested_fingerprints)
  1749. {
  1750. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  1751. char fp[HEX_DIGEST_LEN+1];
  1752. const char *msg;
  1753. router_parse_list_from_string(&s, routers);
  1754. routers_update_status_from_networkstatus(routers, !from_cache);
  1755. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  1756. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  1757. {
  1758. base16_encode(fp, sizeof(fp), ri->cache_info.signed_descriptor_digest,
  1759. DIGEST_LEN);
  1760. if (requested_fingerprints) {
  1761. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1762. smartlist_string_remove(requested_fingerprints, fp);
  1763. } else {
  1764. char *requested =
  1765. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1766. log_warn(LD_DIR,
  1767. "We received a router descriptor with a fingerprint (%s) "
  1768. "that we never requested. (We asked for: %s.) Dropping.",
  1769. fp, requested);
  1770. tor_free(requested);
  1771. routerinfo_free(ri);
  1772. continue;
  1773. }
  1774. }
  1775. if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0)
  1776. smartlist_add(changed, ri);
  1777. });
  1778. if (smartlist_len(changed))
  1779. control_event_descriptors_changed(changed);
  1780. routerlist_assert_ok(routerlist);
  1781. router_rebuild_store(0);
  1782. smartlist_free(routers);
  1783. smartlist_free(changed);
  1784. }
  1785. /** Helper: return a newly allocated string containing the name of the filename
  1786. * where we plan to cache <b>ns</b>. */
  1787. static char *
  1788. networkstatus_get_cache_filename(const networkstatus_t *ns)
  1789. {
  1790. const char *datadir = get_options()->DataDirectory;
  1791. size_t len = strlen(datadir)+64;
  1792. char fp[HEX_DIGEST_LEN+1];
  1793. char *fn = tor_malloc(len+1);
  1794. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1795. tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
  1796. return fn;
  1797. }
  1798. /** Helper for smartlist_sort: Compare two networkstatus objects by
  1799. * publication date. */
  1800. static int
  1801. _compare_networkstatus_published_on(const void **_a, const void **_b)
  1802. {
  1803. const networkstatus_t *a = *_a, *b = *_b;
  1804. if (a->published_on < b->published_on)
  1805. return -1;
  1806. else if (a->published_on > b->published_on)
  1807. return 1;
  1808. else
  1809. return 0;
  1810. }
  1811. /** Add the parsed neworkstatus in <b>ns</b> (with original document in
  1812. * <b>s</b> to the disk cache (and the in-memory directory server cache) as
  1813. * appropriate. */
  1814. static int
  1815. add_networkstatus_to_cache(const char *s,
  1816. networkstatus_source_t source,
  1817. networkstatus_t *ns)
  1818. {
  1819. if (source != NS_FROM_CACHE) {
  1820. char *fn = networkstatus_get_cache_filename(ns);
  1821. if (write_str_to_file(fn, s, 0)<0) {
  1822. log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
  1823. }
  1824. tor_free(fn);
  1825. }
  1826. if (get_options()->DirPort)
  1827. dirserv_set_cached_networkstatus_v2(s,
  1828. ns->identity_digest,
  1829. ns->published_on);
  1830. return 0;
  1831. }
  1832. /** How far in the future do we allow a network-status to get before removing
  1833. * it? (seconds) */
  1834. #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
  1835. /** Given a string <b>s</b> containing a network status that we received at
  1836. * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
  1837. * store it, and put it into our cache as necessary.
  1838. *
  1839. * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
  1840. * own networkstatus_t (if we're a directory server).
  1841. *
  1842. * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
  1843. * cache.
  1844. *
  1845. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1846. * uppercased identity fingerprints. Do not update any networkstatus whose
  1847. * fingerprint is not on the list; after updating a networkstatus, remove its
  1848. * fingerprint from the list.
  1849. *
  1850. * Return 0 on success, -1 on failure.
  1851. *
  1852. * Callers should make sure that routers_update_all_from_networkstatus() is
  1853. * invoked after this function succeeds.
  1854. */
  1855. int
  1856. router_set_networkstatus(const char *s, time_t arrived_at,
  1857. networkstatus_source_t source, smartlist_t *requested_fingerprints)
  1858. {
  1859. networkstatus_t *ns;
  1860. int i, found;
  1861. time_t now;
  1862. int skewed = 0;
  1863. trusted_dir_server_t *trusted_dir = NULL;
  1864. const char *source_desc = NULL;
  1865. char fp[HEX_DIGEST_LEN+1];
  1866. char published[ISO_TIME_LEN+1];
  1867. ns = networkstatus_parse_from_string(s);
  1868. if (!ns) {
  1869. log_warn(LD_DIR, "Couldn't parse network status.");
  1870. return -1;
  1871. }
  1872. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1873. if (!(trusted_dir =
  1874. router_get_trusteddirserver_by_digest(ns->identity_digest))) {
  1875. log_info(LD_DIR, "Network status was signed, but not by an authoritative "
  1876. "directory we recognize.");
  1877. if (!get_options()->DirPort) {
  1878. networkstatus_free(ns);
  1879. return 0;
  1880. }
  1881. source_desc = fp;
  1882. } else {
  1883. source_desc = trusted_dir->description;
  1884. }
  1885. now = time(NULL);
  1886. if (arrived_at > now)
  1887. arrived_at = now;
  1888. ns->received_on = arrived_at;
  1889. format_iso_time(published, ns->published_on);
  1890. if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
  1891. log_warn(LD_GENERAL, "Network status from %s was published in the future "
  1892. "(%s GMT). Somebody is skewed here: check your clock. "
  1893. "Not caching.",
  1894. source_desc, published);
  1895. skewed = 1;
  1896. }
  1897. if (!networkstatus_list)
  1898. networkstatus_list = smartlist_create();
  1899. if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
  1900. /* Don't replace our own networkstatus when we get it from somebody else.*/
  1901. networkstatus_free(ns);
  1902. return 0;
  1903. }
  1904. if (requested_fingerprints) {
  1905. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1906. smartlist_string_remove(requested_fingerprints, fp);
  1907. } else {
  1908. char *requested =
  1909. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1910. log_warn(LD_DIR,
  1911. "We received a network status with a fingerprint (%s) that we "
  1912. "never requested. (We asked for: %s.) Dropping.",
  1913. fp, requested);
  1914. tor_free(requested);
  1915. return 0;
  1916. }
  1917. }
  1918. if (!trusted_dir) {
  1919. if (!skewed && get_options()->DirPort) {
  1920. /* We got a non-trusted networkstatus, and we're a directory cache.
  1921. * This means that we asked an authority, and it told us about another
  1922. * authority we didn't recognize. */
  1923. add_networkstatus_to_cache(s, source, ns);
  1924. networkstatus_free(ns);
  1925. }
  1926. return 0;
  1927. }
  1928. if (source != NS_FROM_CACHE && trusted_dir)
  1929. trusted_dir->n_networkstatus_failures = 0;
  1930. found = 0;
  1931. for (i=0; i < smartlist_len(networkstatus_list); ++i) {
  1932. networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
  1933. if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
  1934. if (!memcmp(old_ns->networkstatus_digest,
  1935. ns->networkstatus_digest, DIGEST_LEN)) {
  1936. /* Same one we had before. */
  1937. networkstatus_free(ns);
  1938. log_info(LD_DIR,
  1939. "Not replacing network-status from %s (published %s); "
  1940. "we already have it.",
  1941. trusted_dir->description, published);
  1942. if (old_ns->received_on < arrived_at) {
  1943. if (source != NS_FROM_CACHE) {
  1944. char *fn = networkstatus_get_cache_filename(old_ns);
  1945. /* We use mtime to tell when it arrived, so update that. */
  1946. touch_file(fn);
  1947. tor_free(fn);
  1948. }
  1949. old_ns->received_on = arrived_at;
  1950. }
  1951. return 0;
  1952. } else if (old_ns->published_on >= ns->published_on) {
  1953. char old_published[ISO_TIME_LEN+1];
  1954. format_iso_time(old_published, old_ns->published_on);
  1955. log_info(LD_DIR,
  1956. "Not replacing network-status from %s (published %s);"
  1957. " we have a newer one (published %s) for this authority.",
  1958. trusted_dir->description, published,
  1959. old_published);
  1960. networkstatus_free(ns);
  1961. return 0;
  1962. } else {
  1963. networkstatus_free(old_ns);
  1964. smartlist_set(networkstatus_list, i, ns);
  1965. found = 1;
  1966. break;
  1967. }
  1968. }
  1969. }
  1970. if (!found)
  1971. smartlist_add(networkstatus_list, ns);
  1972. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1973. {
  1974. if (!router_get_by_descriptor_digest(rs->descriptor_digest))
  1975. rs->need_to_mirror = 1;
  1976. });
  1977. log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
  1978. source == NS_FROM_CACHE?"cached from":
  1979. (source==NS_FROM_DIR?"downloaded from":"generated for"),
  1980. trusted_dir->description, published);
  1981. networkstatus_list_has_changed = 1;
  1982. smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
  1983. if (!skewed)
  1984. add_networkstatus_to_cache(s, source, ns);
  1985. networkstatus_list_update_recent(now);
  1986. return 0;
  1987. }
  1988. /** How old do we allow a network-status to get before removing it
  1989. * completely? */
  1990. #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
  1991. /** Remove all very-old network_status_t objects from memory and from the
  1992. * disk cache. */
  1993. void
  1994. networkstatus_list_clean(time_t now)
  1995. {
  1996. int i;
  1997. if (!networkstatus_list)
  1998. return;
  1999. for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
  2000. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  2001. char *fname = NULL;;
  2002. if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
  2003. continue;
  2004. /* Okay, this one is too old. Remove it from the list, and delete it
  2005. * from the cache. */
  2006. smartlist_del(networkstatus_list, i--);
  2007. fname = networkstatus_get_cache_filename(ns);
  2008. if (file_status(fname) == FN_FILE) {
  2009. log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
  2010. unlink(fname);
  2011. }
  2012. tor_free(fname);
  2013. if (get_options()->DirPort) {
  2014. dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
  2015. }
  2016. networkstatus_free(ns);
  2017. }
  2018. }
  2019. /** Helper for bsearching a list of routerstatus_t pointers.*/
  2020. static int
  2021. _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
  2022. {
  2023. const char *key = _key;
  2024. const routerstatus_t *rs = *_member;
  2025. return memcmp(key, rs->identity_digest, DIGEST_LEN);
  2026. }
  2027. /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
  2028. * NULL if none was found. */
  2029. static routerstatus_t *
  2030. networkstatus_find_entry(networkstatus_t *ns, const char *digest)
  2031. {
  2032. return smartlist_bsearch(ns->entries, digest,
  2033. _compare_digest_to_routerstatus_entry);
  2034. }
  2035. /** Return the consensus view of the status of the router whose digest is
  2036. * <b>digest</b>, or NULL if we don't know about any such router. */
  2037. local_routerstatus_t *
  2038. router_get_combined_status_by_digest(const char *digest)
  2039. {
  2040. if (!routerstatus_list)
  2041. return NULL;
  2042. return smartlist_bsearch(routerstatus_list, digest,
  2043. _compare_digest_to_routerstatus_entry);
  2044. }
  2045. /** Return true iff any networkstatus includes a descriptor whose digest
  2046. * is that of <b>desc</b>. */
  2047. static int
  2048. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  2049. {
  2050. routerstatus_t *rs;
  2051. if (!networkstatus_list)
  2052. return 0;
  2053. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2054. {
  2055. if (!(rs = networkstatus_find_entry(ns, desc->identity_digest)))
  2056. continue;
  2057. if (!memcmp(rs->descriptor_digest,
  2058. desc->signed_descriptor_digest, DIGEST_LEN))
  2059. return 1;
  2060. });
  2061. return 0;
  2062. }
  2063. /** How frequently do directory authorities re-download fresh networkstatus
  2064. * documents? */
  2065. #define AUTHORITY_NS_CACHE_INTERVAL (5*60)
  2066. /** How frequently do non-authority directory caches re-download fresh
  2067. * networkstatus documents? */
  2068. #define NONAUTHORITY_NS_CACHE_INTERVAL (15*60)
  2069. /** We are a directory server, and so cache network_status documents.
  2070. * Initiate downloads as needed to update them. For authorities, this means
  2071. * asking each trusted directory for its network-status. For caches, this
  2072. * means asking a random authority for all network-statuses.
  2073. */
  2074. static void
  2075. update_networkstatus_cache_downloads(time_t now)
  2076. {
  2077. int authority = authdir_mode(get_options());
  2078. int interval =
  2079. authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
  2080. if (last_networkstatus_download_attempted + interval >= now)
  2081. return;
  2082. if (!trusted_dir_servers)
  2083. return;
  2084. last_networkstatus_download_attempted = now;
  2085. if (authority) {
  2086. /* An authority launches a separate connection for everybody. */
  2087. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2088. {
  2089. char resource[HEX_DIGEST_LEN+6]; /* fp/hexdigit.z\0 */
  2090. if (router_digest_is_me(ds->digest))
  2091. continue;
  2092. if (connection_get_by_type_addr_port_purpose(
  2093. CONN_TYPE_DIR, ds->addr, ds->dir_port,
  2094. DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
  2095. /* We are already fetching this one. */
  2096. continue;
  2097. }
  2098. strlcpy(resource, "fp/", sizeof(resource));
  2099. base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
  2100. strlcat(resource, ".z", sizeof(resource));
  2101. directory_initiate_command_routerstatus(
  2102. &ds->fake_status, DIR_PURPOSE_FETCH_NETWORKSTATUS,
  2103. 0, /* Not private */
  2104. resource,
  2105. NULL, 0 /* No payload. */);
  2106. });
  2107. } else {
  2108. /* A non-authority cache launches one connection to a random authority. */
  2109. /* (Check whether we're currently fetching network-status objects.) */
  2110. if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
  2111. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  2112. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
  2113. }
  2114. }
  2115. /** How long (in seconds) does a client wait after getting a network status
  2116. * before downloading the next in sequence? */
  2117. #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
  2118. /* How many times do we allow a networkstatus download to fail before we
  2119. * assume that the authority isn't publishing? */
  2120. #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
  2121. /** We are not a directory cache or authority. Update our network-status list
  2122. * by launching a new directory fetch for enough network-status documents "as
  2123. * necessary". See function comments for implementation details.
  2124. */
  2125. static void
  2126. update_networkstatus_client_downloads(time_t now)
  2127. {
  2128. int n_live = 0, n_dirservers, n_running_dirservers, needed = 0;
  2129. int fetch_latest = 0;
  2130. int most_recent_idx = -1;
  2131. trusted_dir_server_t *most_recent = NULL;
  2132. time_t most_recent_received = 0;
  2133. char *resource, *cp;
  2134. size_t resource_len;
  2135. smartlist_t *missing;
  2136. if (connection_get_by_type_purpose(CONN_TYPE_DIR,
  2137. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  2138. return;
  2139. /* This is a little tricky. We want to download enough network-status
  2140. * objects so that we have all of them under
  2141. * NETWORKSTATUS_MAX_AGE publication time. We want to download a new
  2142. * *one* if the most recent one's publication time is under
  2143. * NETWORKSTATUS_CLIENT_DL_INTERVAL.
  2144. */
  2145. if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
  2146. return;
  2147. n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
  2148. missing = smartlist_create();
  2149. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2150. {
  2151. networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
  2152. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  2153. --n_running_dirservers;
  2154. continue;
  2155. }
  2156. if (ns && ns->published_on > now-NETWORKSTATUS_MAX_AGE)
  2157. ++n_live;
  2158. else
  2159. smartlist_add(missing, ds->digest);
  2160. if (ns && (!most_recent || ns->received_on > most_recent_received)) {
  2161. most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
  2162. most_recent = ds;
  2163. most_recent_received = ns->received_on;
  2164. }
  2165. });
  2166. /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
  2167. if (!smartlist_len(missing) &&
  2168. most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL) {
  2169. log_info(LD_DIR, "Our most recent network-status document (from %s) "
  2170. "is %d seconds old; downloading another.",
  2171. most_recent?most_recent->description:"nobody",
  2172. (int)(now-most_recent_received));
  2173. fetch_latest = 1;
  2174. needed = 1;
  2175. } else if (smartlist_len(missing)) {
  2176. log_info(LD_DIR, "For %d/%d running directory servers, we have %d live"
  2177. " network-status documents. Downloading %d.",
  2178. n_running_dirservers, n_dirservers, n_live,
  2179. smartlist_len(missing));
  2180. needed = smartlist_len(missing);
  2181. } else {
  2182. smartlist_free(missing);
  2183. return;
  2184. }
  2185. /* If no networkstatus was found, choose a dirserver at random as "most
  2186. * recent". */
  2187. if (most_recent_idx<0)
  2188. most_recent_idx = crypto_rand_int(n_dirservers);
  2189. if (fetch_latest) {
  2190. int i;
  2191. int n_failed = 0;
  2192. for (i = most_recent_idx + 1; 1; ++i) {
  2193. trusted_dir_server_t *ds;
  2194. if (i >= n_dirservers)
  2195. i = 0;
  2196. ds = smartlist_get(trusted_dir_servers, i);
  2197. if (n_failed < n_dirservers &&
  2198. ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  2199. ++n_failed;
  2200. continue;
  2201. }
  2202. smartlist_add(missing, ds->digest);
  2203. break;
  2204. }
  2205. }
  2206. /* Build a request string for all the resources we want. */
  2207. resource_len = smartlist_len(missing) * (HEX_DIGEST_LEN+1) + 6;
  2208. resource = tor_malloc(resource_len);
  2209. memcpy(resource, "fp/", 3);
  2210. cp = resource+3;
  2211. needed = smartlist_len(missing);
  2212. SMARTLIST_FOREACH(missing, const char *, d,
  2213. {
  2214. base16_encode(cp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
  2215. cp += HEX_DIGEST_LEN;
  2216. --needed;
  2217. if (needed)
  2218. *cp++ = '+';
  2219. });
  2220. memcpy(cp, ".z", 3);
  2221. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
  2222. tor_free(resource);
  2223. smartlist_free(missing);
  2224. }
  2225. /** Launch requests for networkstatus documents as appropriate. */
  2226. void
  2227. update_networkstatus_downloads(time_t now)
  2228. {
  2229. or_options_t *options = get_options();
  2230. if (server_mode(options) && options->DirPort)
  2231. update_networkstatus_cache_downloads(time(NULL));
  2232. else
  2233. update_networkstatus_client_downloads(time(NULL));
  2234. }
  2235. /** Return 1 if all running sufficiently-stable routers will reject
  2236. * addr:port, return 0 if any might accept it. */
  2237. int
  2238. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  2239. int need_uptime)
  2240. {
  2241. addr_policy_result_t r;
  2242. if (!routerlist) return 1;
  2243. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  2244. {
  2245. if (router->is_running &&
  2246. !router_is_unreliable(router, need_uptime, 0, 0)) {
  2247. r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
  2248. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2249. return 0; /* this one could be ok. good enough. */
  2250. }
  2251. });
  2252. return 1; /* all will reject. */
  2253. }
  2254. /** Return true iff <b>router</b> does not permit exit streams.
  2255. */
  2256. int
  2257. router_exit_policy_rejects_all(routerinfo_t *router)
  2258. {
  2259. return compare_addr_to_addr_policy(0, 0, router->exit_policy)
  2260. == ADDR_POLICY_REJECTED;
  2261. }
  2262. /** Add to the list of authorized directory servers one at
  2263. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  2264. * <b>address</b> is NULL, add ourself. */
  2265. void
  2266. add_trusted_dir_server(const char *nickname, const char *address,
  2267. uint16_t port, const char *digest, int supports_v1)
  2268. {
  2269. trusted_dir_server_t *ent;
  2270. uint32_t a;
  2271. char *hostname = NULL;
  2272. size_t dlen;
  2273. if (!trusted_dir_servers)
  2274. trusted_dir_servers = smartlist_create();
  2275. if (!address) { /* The address is us; we should guess. */
  2276. if (resolve_my_address(get_options(), &a, &hostname) < 0) {
  2277. log_warn(LD_CONFIG,
  2278. "Couldn't find a suitable address when adding ourself as a "
  2279. "trusted directory server.");
  2280. return;
  2281. }
  2282. } else {
  2283. if (tor_lookup_hostname(address, &a)) {
  2284. log_warn(LD_CONFIG,
  2285. "Unable to lookup address for directory server at '%s'",
  2286. address);
  2287. return;
  2288. }
  2289. hostname = tor_strdup(address);
  2290. a = ntohl(a);
  2291. }
  2292. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  2293. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  2294. ent->address = hostname;
  2295. ent->addr = a;
  2296. ent->dir_port = port;
  2297. ent->is_running = 1;
  2298. ent->is_v1_authority = supports_v1;
  2299. memcpy(ent->digest, digest, DIGEST_LEN);
  2300. dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
  2301. ent->description = tor_malloc(dlen);
  2302. if (nickname)
  2303. tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
  2304. nickname, hostname, (int)port);
  2305. else
  2306. tor_snprintf(ent->description, dlen, "directory server at %s:%d",
  2307. hostname, (int)port);
  2308. ent->fake_status.addr = ent->addr;
  2309. memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  2310. if (nickname)
  2311. strlcpy(ent->fake_status.nickname, nickname,
  2312. sizeof(ent->fake_status.nickname));
  2313. else
  2314. ent->fake_status.nickname[0] = '\0';
  2315. ent->fake_status.dir_port = ent->dir_port;
  2316. smartlist_add(trusted_dir_servers, ent);
  2317. }
  2318. /** Free storage held in <b>ds</b> */
  2319. void
  2320. trusted_dir_server_free(trusted_dir_server_t *ds)
  2321. {
  2322. tor_free(ds->nickname);
  2323. tor_free(ds->description);
  2324. tor_free(ds->address);
  2325. tor_free(ds);
  2326. }
  2327. /** Remove all members from the list of trusted dir servers. */
  2328. void
  2329. clear_trusted_dir_servers(void)
  2330. {
  2331. if (trusted_dir_servers) {
  2332. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2333. trusted_dir_server_free(ent));
  2334. smartlist_clear(trusted_dir_servers);
  2335. } else {
  2336. trusted_dir_servers = smartlist_create();
  2337. }
  2338. }
  2339. /** Return 1 if any trusted dir server supports v1 directories,
  2340. * else return 0. */
  2341. int
  2342. any_trusted_dir_supports_v1(void)
  2343. {
  2344. if (trusted_dir_servers)
  2345. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2346. if (ent->is_v1_authority) return 1);
  2347. return 0;
  2348. }
  2349. /** Return the network status with a given identity digest. */
  2350. networkstatus_t *
  2351. networkstatus_get_by_digest(const char *digest)
  2352. {
  2353. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2354. {
  2355. if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
  2356. return ns;
  2357. });
  2358. return NULL;
  2359. }
  2360. /** We believe networkstatuses more recent than this when they tell us that
  2361. * our server is broken, invalid, obsolete, etc. */
  2362. #define SELF_OPINION_INTERVAL (90*60)
  2363. /** Return a string naming the versions of Tor recommended by
  2364. * at least n_needed versioning networkstatuses */
  2365. static char *
  2366. compute_recommended_versions(time_t now, int client)
  2367. {
  2368. int n_seen;
  2369. char *current;
  2370. smartlist_t *combined, *recommended;
  2371. int n_recent;
  2372. char *result;
  2373. if (!networkstatus_list)
  2374. return tor_strdup("<none>");
  2375. combined = smartlist_create();
  2376. n_recent = 0;
  2377. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2378. {
  2379. const char *vers;
  2380. smartlist_t *versions;
  2381. if (! ns->recommends_versions)
  2382. continue;
  2383. if (ns->received_on + SELF_OPINION_INTERVAL < now)
  2384. continue;
  2385. n_recent++;
  2386. vers = client ? ns->client_versions : ns->server_versions;
  2387. if (!vers)
  2388. continue;
  2389. versions = smartlist_create();
  2390. smartlist_split_string(versions, vers, ",",
  2391. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2392. sort_version_list(versions, 1);
  2393. smartlist_add_all(combined, versions);
  2394. smartlist_free(versions);
  2395. });
  2396. sort_version_list(combined, 0);
  2397. current = NULL;
  2398. n_seen = 0;
  2399. recommended = smartlist_create();
  2400. SMARTLIST_FOREACH(combined, char *, cp,
  2401. {
  2402. if (current && !strcmp(cp, current)) {
  2403. ++n_seen;
  2404. } else {
  2405. if (n_seen > n_recent/2 && current)
  2406. smartlist_add(recommended, current);
  2407. n_seen = 0;
  2408. current = cp;
  2409. }
  2410. });
  2411. if (n_seen > n_recent/2 && current)
  2412. smartlist_add(recommended, current);
  2413. result = smartlist_join_strings(recommended, ", ", 0, NULL);
  2414. SMARTLIST_FOREACH(combined, char *, cp, tor_free(cp));
  2415. smartlist_free(combined);
  2416. smartlist_free(recommended);
  2417. return result;
  2418. }
  2419. /** If the network-status list has changed since the last time we called this
  2420. * function, update the status of every routerinfo from the network-status
  2421. * list.
  2422. */
  2423. void
  2424. routers_update_all_from_networkstatus(void)
  2425. {
  2426. routerinfo_t *me;
  2427. time_t now;
  2428. if (!routerlist || !networkstatus_list ||
  2429. (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
  2430. return;
  2431. now = time(NULL);
  2432. if (networkstatus_list_has_changed)
  2433. routerstatus_list_update_from_networkstatus(now);
  2434. routers_update_status_from_networkstatus(routerlist->routers, 0);
  2435. me = router_get_my_routerinfo();
  2436. if (me && !have_warned_about_invalid_status &&
  2437. have_tried_downloading_all_statuses(4)) {
  2438. int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0, n_naming = 0;
  2439. routerstatus_t *rs;
  2440. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2441. {
  2442. if (ns->received_on + SELF_OPINION_INTERVAL < now)
  2443. continue;
  2444. ++n_recent;
  2445. if (ns->binds_names)
  2446. ++n_naming;
  2447. if (!(rs = networkstatus_find_entry(ns, me->cache_info.identity_digest)))
  2448. continue;
  2449. ++n_listing;
  2450. if (rs->is_valid)
  2451. ++n_valid;
  2452. if (rs->is_named)
  2453. ++n_named;
  2454. });
  2455. if (n_recent && n_listing) {
  2456. if (n_valid <= n_recent/2) {
  2457. log_warn(LD_GENERAL,
  2458. "%d/%d recent statements from directory authorities list us "
  2459. "as unapproved. Are you misconfigured?",
  2460. n_recent-n_valid, n_recent);
  2461. have_warned_about_invalid_status = 1;
  2462. } else if (n_naming && !n_named) {
  2463. log_warn(LD_GENERAL, "0/%d name-binding directory authorities "
  2464. "recognize your nickname. Please consider sending your "
  2465. "nickname and identity fingerprint to the tor-ops.",
  2466. n_naming);
  2467. have_warned_about_invalid_status = 1;
  2468. }
  2469. }
  2470. }
  2471. entry_guards_set_status_from_directory();
  2472. if (!have_warned_about_old_version &&
  2473. have_tried_downloading_all_statuses(4)) {
  2474. int n_recent = 0;
  2475. int n_recommended = 0;
  2476. int is_server = server_mode(get_options());
  2477. version_status_t consensus = VS_RECOMMENDED;
  2478. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2479. {
  2480. version_status_t vs;
  2481. if (!ns->recommends_versions ||
  2482. ns->received_on + SELF_OPINION_INTERVAL < now )
  2483. continue;
  2484. vs = tor_version_is_obsolete(
  2485. VERSION, is_server ? ns->server_versions : ns->client_versions);
  2486. if (vs == VS_RECOMMENDED)
  2487. ++n_recommended;
  2488. if (n_recent++ == 0) {
  2489. consensus = vs;
  2490. } else if (consensus != vs) {
  2491. consensus = version_status_join(consensus, vs);
  2492. }
  2493. });
  2494. if (n_recent && n_recommended <= n_recent/2) {
  2495. if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
  2496. if (!have_warned_about_new_version) {
  2497. char *rec = compute_recommended_versions(now, !is_server);
  2498. log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
  2499. "recommended version%s, according to %d/%d recent network "
  2500. "statuses. Versions recommended by more than %d recent "
  2501. "authorit%s are: %s",
  2502. VERSION,
  2503. consensus == VS_NEW_IN_SERIES ? " in its series" : "",
  2504. n_recent-n_recommended, n_recent, n_recent/2,
  2505. n_recent/2 > 1 ? "ies" : "y", rec);
  2506. have_warned_about_new_version = 1;
  2507. tor_free(rec);
  2508. }
  2509. } else {
  2510. char *rec = compute_recommended_versions(now, !is_server);
  2511. log_warn(LD_GENERAL, "Please upgrade! "
  2512. "This version of Tor (%s) is %s, according to "
  2513. "%d/%d recent network statuses. Versions recommended by "
  2514. "at least %d recent authorit%s are: %s",
  2515. VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
  2516. n_recent-n_recommended, n_recent, n_recent/2,
  2517. n_recent/2 > 1 ? "ies" : "y", rec);
  2518. have_warned_about_old_version = 1;
  2519. tor_free(rec);
  2520. }
  2521. } else {
  2522. log_info(LD_GENERAL, "%d/%d recently downloaded statements from "
  2523. "directory authorities say my version is ok.",
  2524. n_recommended, n_recent);
  2525. }
  2526. }
  2527. routerstatus_list_has_changed = 0;
  2528. }
  2529. /** Allow any network-status newer than this to influence our view of who's
  2530. * running. */
  2531. #define DEFAULT_RUNNING_INTERVAL (60*60)
  2532. /** If possible, always allow at least this many network-statuses to influence
  2533. * our view of who's running. */
  2534. #define MIN_TO_INFLUENCE_RUNNING 3
  2535. /** Change the is_recent field of each member of networkstatus_list so that
  2536. * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
  2537. * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
  2538. * others are recent. Set networkstatus_list_has_changed if anything happened.
  2539. */
  2540. void
  2541. networkstatus_list_update_recent(time_t now)
  2542. {
  2543. int n_statuses, n_recent, changed, i;
  2544. char published[ISO_TIME_LEN+1];
  2545. if (!networkstatus_list)
  2546. return;
  2547. n_statuses = smartlist_len(networkstatus_list);
  2548. n_recent = 0;
  2549. changed = 0;
  2550. for (i=n_statuses-1; i >= 0; --i) {
  2551. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  2552. trusted_dir_server_t *ds =
  2553. router_get_trusteddirserver_by_digest(ns->identity_digest);
  2554. const char *src = ds?ds->description:ns->source_address;
  2555. if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
  2556. ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
  2557. if (!ns->is_recent) {
  2558. format_iso_time(published, ns->published_on);
  2559. log_info(LD_DIR,
  2560. "Networkstatus from %s (published %s) is now \"recent\"",
  2561. src, published);
  2562. changed = 1;
  2563. }
  2564. ns->is_recent = 1;
  2565. ++n_recent;
  2566. } else {
  2567. if (ns->is_recent) {
  2568. format_iso_time(published, ns->published_on);
  2569. log_info(LD_DIR,
  2570. "Networkstatus from %s (published %s) is "
  2571. "no longer \"recent\"",
  2572. src, published);
  2573. changed = 1;
  2574. ns->is_recent = 0;
  2575. }
  2576. }
  2577. }
  2578. if (changed)
  2579. networkstatus_list_has_changed = 1;
  2580. }
  2581. /** Helper for routerstatus_list_update_from_networkstatus: remember how many
  2582. * authorities recommend a given descriptor digest. */
  2583. typedef struct {
  2584. routerstatus_t *rs;
  2585. int count;
  2586. } desc_digest_count_t;
  2587. /** Update our view of router status (as stored in routerstatus_list) from the
  2588. * current set of network status documents (as stored in networkstatus_list).
  2589. * Do nothing unless the network status list has changed since the last time
  2590. * this function was called.
  2591. */
  2592. static void
  2593. routerstatus_list_update_from_networkstatus(time_t now)
  2594. {
  2595. or_options_t *options = get_options();
  2596. int n_trusted, n_statuses, n_recent = 0, n_naming = 0;
  2597. int i, j, warned;
  2598. int *index, *size;
  2599. networkstatus_t **networkstatus;
  2600. smartlist_t *result;
  2601. strmap_t *name_map;
  2602. char conflict[DIGEST_LEN]; /* Sentinel value */
  2603. desc_digest_count_t *digest_counts = NULL;
  2604. /* compute which network statuses will have a vote now */
  2605. networkstatus_list_update_recent(now);
  2606. if (!networkstatus_list_has_changed)
  2607. return;
  2608. if (!networkstatus_list)
  2609. networkstatus_list = smartlist_create();
  2610. if (!routerstatus_list)
  2611. routerstatus_list = smartlist_create();
  2612. if (!trusted_dir_servers)
  2613. trusted_dir_servers = smartlist_create();
  2614. if (!warned_conflicts)
  2615. warned_conflicts = smartlist_create();
  2616. n_trusted = smartlist_len(trusted_dir_servers);
  2617. n_statuses = smartlist_len(networkstatus_list);
  2618. if (n_statuses <= n_trusted/2) {
  2619. /* Not enough statuses to adjust status. */
  2620. log_info(LD_DIR,
  2621. "Not enough statuses to update router status list. (%d/%d)",
  2622. n_statuses, n_trusted);
  2623. return;
  2624. }
  2625. log_info(LD_DIR, "Rebuilding router status list.");
  2626. index = tor_malloc(sizeof(int)*n_statuses);
  2627. size = tor_malloc(sizeof(int)*n_statuses);
  2628. networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
  2629. for (i = 0; i < n_statuses; ++i) {
  2630. index[i] = 0;
  2631. networkstatus[i] = smartlist_get(networkstatus_list, i);
  2632. size[i] = smartlist_len(networkstatus[i]->entries);
  2633. if (networkstatus[i]->binds_names)
  2634. ++n_naming;
  2635. if (networkstatus[i]->is_recent)
  2636. ++n_recent;
  2637. }
  2638. /** Iterate over all entries in all networkstatuses, and build
  2639. * name_map as a map from lc nickname to identity digest. If there
  2640. * is a conflict on that nickname, map the lc nickname to conflict.
  2641. */
  2642. name_map = strmap_new();
  2643. memset(conflict, 0xff, sizeof(conflict));
  2644. for (i = 0; i < n_statuses; ++i) {
  2645. if (!networkstatus[i]->binds_names)
  2646. continue;
  2647. SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
  2648. {
  2649. const char *other_digest;
  2650. if (!rs->is_named)
  2651. continue;
  2652. other_digest = strmap_get_lc(name_map, rs->nickname);
  2653. warned = smartlist_string_isin(warned_conflicts, rs->nickname);
  2654. if (!other_digest) {
  2655. strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
  2656. if (warned)
  2657. smartlist_string_remove(warned_conflicts, rs->nickname);
  2658. } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
  2659. other_digest != conflict) {
  2660. if (!warned) {
  2661. int should_warn = options->DirPort && options->AuthoritativeDir;
  2662. char fp1[HEX_DIGEST_LEN+1];
  2663. char fp2[HEX_DIGEST_LEN+1];
  2664. base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
  2665. base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
  2666. log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
  2667. "Naming authorities disagree about which key goes with %s. "
  2668. "($%s vs $%s)",
  2669. rs->nickname, fp1, fp2);
  2670. strmap_set_lc(name_map, rs->nickname, conflict);
  2671. smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
  2672. }
  2673. } else {
  2674. if (warned)
  2675. smartlist_string_remove(warned_conflicts, rs->nickname);
  2676. }
  2677. });
  2678. }
  2679. result = smartlist_create();
  2680. digest_counts = tor_malloc_zero(sizeof(desc_digest_count_t)*n_statuses);
  2681. /* Iterate through all of the sorted routerstatus lists in lockstep.
  2682. * Invariants:
  2683. * - For 0 <= i < n_statuses: index[i] is an index into
  2684. * networkstatus[i]->entries, which has size[i] elements.
  2685. * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
  2686. * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
  2687. * networkstatus[i2]->entries[index[i2]]->identity_digest.
  2688. *
  2689. * (That is, the indices are always advanced past lower digest before
  2690. * higher.)
  2691. */
  2692. while (1) {
  2693. int n_running=0, n_named=0, n_valid=0, n_listing=0;
  2694. int n_v2_dir=0, n_fast=0, n_stable=0, n_exit=0, n_guard=0;
  2695. int n_desc_digests=0, highest_count=0;
  2696. const char *the_name = NULL;
  2697. local_routerstatus_t *rs_out, *rs_old;
  2698. routerstatus_t *rs, *most_recent;
  2699. networkstatus_t *ns;
  2700. const char *lowest = NULL;
  2701. /* Find out which of the digests appears first. */
  2702. for (i = 0; i < n_statuses; ++i) {
  2703. if (index[i] < size[i]) {
  2704. rs = smartlist_get(networkstatus[i]->entries, index[i]);
  2705. if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
  2706. lowest = rs->identity_digest;
  2707. }
  2708. }
  2709. if (!lowest) {
  2710. /* We're out of routers. Great! */
  2711. break;
  2712. }
  2713. /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
  2714. * match "lowest" are next in order. Iterate over them, incrementing those
  2715. * index[i] as we go. */
  2716. for (i = 0; i < n_statuses; ++i) {
  2717. if (index[i] >= size[i])
  2718. continue;
  2719. ns = networkstatus[i];
  2720. rs = smartlist_get(ns->entries, index[i]);
  2721. if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
  2722. continue;
  2723. /* At this point, we know that we're looking at a routersatus with
  2724. * identity "lowest".
  2725. */
  2726. ++index[i];
  2727. ++n_listing;
  2728. /* Should we name this router? Only if all the names from naming
  2729. * authorities match. */
  2730. if (rs->is_named && ns->binds_names) {
  2731. if (!the_name)
  2732. the_name = rs->nickname;
  2733. if (!strcasecmp(rs->nickname, the_name)) {
  2734. ++n_named;
  2735. } else if (strcmp(the_name,"**mismatch**")) {
  2736. char hd[HEX_DIGEST_LEN+1];
  2737. base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
  2738. if (! smartlist_string_isin(warned_conflicts, hd)) {
  2739. log_warn(LD_DIR,
  2740. "Naming authorities disagree about nicknames for $%s "
  2741. "(\"%s\" vs \"%s\")",
  2742. hd, the_name, rs->nickname);
  2743. smartlist_add(warned_conflicts, tor_strdup(hd));
  2744. }
  2745. the_name = "**mismatch**";
  2746. }
  2747. }
  2748. /* Keep a running count of how often which descriptor digests
  2749. * appear. */
  2750. for (j = 0; j < n_desc_digests; ++j) {
  2751. if (!memcmp(rs->descriptor_digest,
  2752. digest_counts[j].rs->descriptor_digest, DIGEST_LEN)) {
  2753. if (++digest_counts[j].count > highest_count)
  2754. highest_count = digest_counts[j].count;
  2755. goto found;
  2756. }
  2757. }
  2758. digest_counts[n_desc_digests].rs = rs;
  2759. digest_counts[n_desc_digests].count = 1;
  2760. if (!highest_count)
  2761. highest_count = 1;
  2762. ++n_desc_digests;
  2763. found:
  2764. /* Now tally up the easily-tallied flags. */
  2765. if (rs->is_valid)
  2766. ++n_valid;
  2767. if (rs->is_running && ns->is_recent)
  2768. ++n_running;
  2769. if (rs->is_exit)
  2770. ++n_exit;
  2771. if (rs->is_fast)
  2772. ++n_fast;
  2773. if (rs->is_possible_guard)
  2774. ++n_guard;
  2775. if (rs->is_stable)
  2776. ++n_stable;
  2777. if (rs->is_v2_dir)
  2778. ++n_v2_dir;
  2779. }
  2780. /* Go over the descriptor digests and figure out which descriptor we
  2781. * want. */
  2782. most_recent = NULL;
  2783. for (i = 0; i < n_desc_digests; ++i) {
  2784. /* If any digest appears twice or more, ignore those that don't.*/
  2785. if (highest_count >= 2 && digest_counts[i].count < 2)
  2786. continue;
  2787. if (!most_recent ||
  2788. digest_counts[i].rs->published_on > most_recent->published_on)
  2789. most_recent = digest_counts[i].rs;
  2790. }
  2791. rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
  2792. memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
  2793. /* Copy status info about this router, if we had any before. */
  2794. if ((rs_old = router_get_combined_status_by_digest(lowest))) {
  2795. if (!memcmp(rs_out->status.descriptor_digest,
  2796. most_recent->descriptor_digest, DIGEST_LEN)) {
  2797. rs_out->n_download_failures = rs_old->n_download_failures;
  2798. rs_out->next_attempt_at = rs_old->next_attempt_at;
  2799. }
  2800. rs_out->name_lookup_warned = rs_old->name_lookup_warned;
  2801. }
  2802. smartlist_add(result, rs_out);
  2803. log_debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
  2804. "named by %d/%d, validated by %d/%d, and %d/%d recent "
  2805. "directories think it's running.",
  2806. rs_out->status.nickname,
  2807. n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
  2808. n_running, n_recent);
  2809. rs_out->status.is_named = 0;
  2810. if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
  2811. const char *d = strmap_get_lc(name_map, the_name);
  2812. if (d && d != conflict)
  2813. rs_out->status.is_named = 1;
  2814. if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
  2815. smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
  2816. }
  2817. if (rs_out->status.is_named)
  2818. strlcpy(rs_out->status.nickname, the_name,
  2819. sizeof(rs_out->status.nickname));
  2820. rs_out->status.is_valid = n_valid > n_statuses/2;
  2821. rs_out->status.is_running = n_running > n_recent/2;
  2822. rs_out->status.is_exit = n_exit > n_statuses/2;
  2823. rs_out->status.is_fast = n_fast > n_statuses/2;
  2824. rs_out->status.is_possible_guard = n_guard > n_statuses/2;
  2825. rs_out->status.is_stable = n_stable > n_statuses/2;
  2826. rs_out->status.is_v2_dir = n_v2_dir > n_statuses/2;
  2827. }
  2828. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2829. local_routerstatus_free(rs));
  2830. smartlist_free(routerstatus_list);
  2831. routerstatus_list = result;
  2832. tor_free(networkstatus);
  2833. tor_free(index);
  2834. tor_free(size);
  2835. tor_free(digest_counts);
  2836. strmap_free(name_map, NULL);
  2837. networkstatus_list_has_changed = 0;
  2838. routerstatus_list_has_changed = 1;
  2839. }
  2840. /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
  2841. * is_named, is_valid, and is_running fields according to our current
  2842. * networkstatus_t documents. */
  2843. void
  2844. routers_update_status_from_networkstatus(smartlist_t *routers,
  2845. int reset_failures)
  2846. {
  2847. trusted_dir_server_t *ds;
  2848. local_routerstatus_t *rs;
  2849. or_options_t *options = get_options();
  2850. int authdir = options->AuthoritativeDir;
  2851. int namingdir = options->AuthoritativeDir &&
  2852. options->NamingAuthoritativeDir;
  2853. if (!routerstatus_list)
  2854. return;
  2855. SMARTLIST_FOREACH(routers, routerinfo_t *, router,
  2856. {
  2857. const char *digest = router->cache_info.identity_digest;
  2858. rs = router_get_combined_status_by_digest(digest);
  2859. ds = router_get_trusteddirserver_by_digest(digest);
  2860. if (!rs)
  2861. continue;
  2862. if (!namingdir)
  2863. router->is_named = rs->status.is_named;
  2864. if (!authdir) {
  2865. /* If we're not an authdir, believe others. */
  2866. router->is_valid = rs->status.is_valid;
  2867. router->is_running = rs->status.is_running;
  2868. router->is_fast = rs->status.is_fast;
  2869. router->is_stable = rs->status.is_stable;
  2870. router->is_possible_guard = rs->status.is_possible_guard;
  2871. }
  2872. if (router->is_running && ds) {
  2873. ds->n_networkstatus_failures = 0;
  2874. }
  2875. if (reset_failures) {
  2876. rs->n_download_failures = 0;
  2877. rs->next_attempt_at = 0;
  2878. }
  2879. });
  2880. }
  2881. /** For every router descriptor we are currently downloading by descriptor
  2882. * digest, set result[d] to 1. */
  2883. static void
  2884. list_pending_descriptor_downloads(digestmap_t *result)
  2885. {
  2886. const char *prefix = "d/";
  2887. size_t p_len = strlen(prefix);
  2888. int i, n_conns;
  2889. connection_t **carray;
  2890. smartlist_t *tmp = smartlist_create();
  2891. tor_assert(result);
  2892. get_connection_array(&carray, &n_conns);
  2893. for (i = 0; i < n_conns; ++i) {
  2894. connection_t *conn = carray[i];
  2895. if (conn->type == CONN_TYPE_DIR &&
  2896. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  2897. !conn->marked_for_close) {
  2898. if (!strcmpstart(conn->requested_resource, prefix))
  2899. dir_split_resource_into_fingerprints(conn->requested_resource+p_len,
  2900. tmp, NULL, 1);
  2901. }
  2902. }
  2903. SMARTLIST_FOREACH(tmp, char *, d,
  2904. {
  2905. digestmap_set(result, d, (void*)1);
  2906. tor_free(d);
  2907. });
  2908. smartlist_free(tmp);
  2909. }
  2910. /** Launch downloads for all the descriptors whose digests are listed
  2911. * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
  2912. * If <b>source</b> is given, download from <b>source</b>; otherwise,
  2913. * download from an appropriate random directory server.
  2914. */
  2915. static void
  2916. initiate_descriptor_downloads(routerstatus_t *source,
  2917. smartlist_t *digests,
  2918. int lo, int hi)
  2919. {
  2920. int i, n = hi-lo;
  2921. char *resource, *cp;
  2922. size_t r_len;
  2923. if (n <= 0)
  2924. return;
  2925. if (lo < 0)
  2926. lo = 0;
  2927. if (hi > smartlist_len(digests))
  2928. hi = smartlist_len(digests);
  2929. r_len = 8 + (HEX_DIGEST_LEN+1)*n;
  2930. cp = resource = tor_malloc(r_len);
  2931. memcpy(cp, "d/", 2);
  2932. cp += 2;
  2933. for (i = lo; i < hi; ++i) {
  2934. base16_encode(cp, r_len-(cp-resource),
  2935. smartlist_get(digests,i), DIGEST_LEN);
  2936. cp += HEX_DIGEST_LEN;
  2937. *cp++ = '+';
  2938. }
  2939. memcpy(cp-1, ".z", 3);
  2940. if (source) {
  2941. /* We know which authority we want. */
  2942. directory_initiate_command_routerstatus(source,
  2943. DIR_PURPOSE_FETCH_SERVERDESC,
  2944. 0, /* not private */
  2945. resource, NULL, 0);
  2946. } else {
  2947. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  2948. resource,
  2949. 1);
  2950. }
  2951. tor_free(resource);
  2952. }
  2953. /** Clients don't download any descriptor this recent, since it will probably
  2954. * not have propageted to enough caches. */
  2955. #define ESTIMATED_PROPAGATION_TIME (10*60)
  2956. /** Return 0 if this routerstatus is obsolete, too new, isn't
  2957. * running, or otherwise not a descriptor that we would make any
  2958. * use of even if we had it. Else return 1. */
  2959. static int
  2960. client_would_use_router(routerstatus_t *rs, time_t now)
  2961. {
  2962. if (rs->published_on + ROUTER_MAX_AGE < now) {
  2963. /* This one is too old to consider. */
  2964. return 0;
  2965. }
  2966. if (!rs->is_running && !get_options()->FetchUselessDescriptors) {
  2967. /* If we had this router descriptor, we wouldn't even bother using it.
  2968. * But, if we want to have a complete list, fetch it anyway. */
  2969. return 0;
  2970. }
  2971. if (rs->published_on + ESTIMATED_PROPAGATION_TIME > now) {
  2972. /* Most caches probably don't have this descriptor yet. */
  2973. return 0;
  2974. }
  2975. return 1;
  2976. }
  2977. /** Return new list of ID fingerprints for routers that we (as a client) would
  2978. * like to download.
  2979. */
  2980. static smartlist_t *
  2981. router_list_client_downloadable(void)
  2982. {
  2983. int n_downloadable = 0;
  2984. smartlist_t *downloadable = smartlist_create();
  2985. digestmap_t *downloading;
  2986. time_t now = time(NULL);
  2987. /* these are just used for logging */
  2988. int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_wouldnt_use = 0;
  2989. if (!routerstatus_list)
  2990. return downloadable;
  2991. downloading = digestmap_new();
  2992. list_pending_descriptor_downloads(downloading);
  2993. routerstatus_list_update_from_networkstatus(now);
  2994. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2995. {
  2996. routerinfo_t *ri;
  2997. if (!client_would_use_router(&rs->status, now)) {
  2998. /* We wouldn't want this descriptor even if we got it. */
  2999. ++n_wouldnt_use;
  3000. } else if (digestmap_get(downloading, rs->status.descriptor_digest)) {
  3001. /* We're downloading this one now. */
  3002. ++n_in_progress;
  3003. } else if (router_get_by_descriptor_digest(rs->status.descriptor_digest)) {
  3004. /* We have the 'best' descriptor for this router. */
  3005. ++n_uptodate;
  3006. } else if ((ri = router_get_by_digest(rs->status.identity_digest)) &&
  3007. ri->cache_info.published_on > rs->status.published_on) {
  3008. /* Oddly, we have a descriptor more recent than the 'best' one, but it
  3009. was once best. So that's okay. */
  3010. ++n_uptodate;
  3011. } else if (rs->next_attempt_at > now) {
  3012. /* We failed too recently to try again. */
  3013. ++n_not_ready;
  3014. } else {
  3015. /* Okay, time to try it. */
  3016. smartlist_add(downloadable, rs->status.descriptor_digest);
  3017. ++n_downloadable;
  3018. }
  3019. });
  3020. #if 0
  3021. log_info(LD_DIR,
  3022. "%d router descriptors are downloadable. "
  3023. "%d are in progress. %d are up-to-date. "
  3024. "%d are non-useful. %d failed too recently to retry.",
  3025. n_downloadable, n_in_progress, n_uptodate,
  3026. n_wouldnt_use, n_not_ready);
  3027. #endif
  3028. digestmap_free(downloading, NULL);
  3029. return downloadable;
  3030. }
  3031. /** Initiate new router downloads as needed, using the strategy for
  3032. * non-directory-servers.
  3033. *
  3034. * We only allow one router descriptor download at a time.
  3035. * If we have less than two network-status documents, we ask
  3036. * a directory for "all descriptors."
  3037. * Otherwise, we ask for all descriptors that we think are different
  3038. * from what we have.
  3039. */
  3040. static void
  3041. update_router_descriptor_client_downloads(time_t now)
  3042. {
  3043. /* Max amount of hashes to download per request.
  3044. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3045. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3046. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3047. * So use 96 because it's a nice number.
  3048. */
  3049. #define MAX_DL_PER_REQUEST 96
  3050. /** Don't split our requests so finely that we are requesting fewer than
  3051. * this number per server. */
  3052. #define MIN_DL_PER_REQUEST 4
  3053. /** To prevent a single screwy cache from confusing us by selective reply,
  3054. * try to split our requests into at least this this many requests. */
  3055. #define MIN_REQUESTS 3
  3056. /** If we want fewer than this many descriptors, wait until we
  3057. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3058. * passed. */
  3059. #define MAX_DL_TO_DELAY 16
  3060. /** When directory clients have only a few servers to request, they batch
  3061. * them until they have more, or until this amount of time has passed. */
  3062. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3063. smartlist_t *downloadable = NULL;
  3064. int should_delay, n_downloadable;
  3065. or_options_t *options = get_options();
  3066. if (server_mode(options) && options->DirPort) {
  3067. log_warn(LD_BUG,
  3068. "Called router_descriptor_client_downloads() on a mirror?");
  3069. }
  3070. /* XXX here's another magic 2 that probably should be replaced
  3071. * by <= smartlist_len(trusted_dir_servers)/2
  3072. * or by a function returning same. -- weasel */
  3073. if (networkstatus_list && smartlist_len(networkstatus_list) < 2) {
  3074. log_info(LD_DIR,
  3075. "Not enough networkstatus documents to launch requests.");
  3076. }
  3077. downloadable = router_list_client_downloadable();
  3078. n_downloadable = smartlist_len(downloadable);
  3079. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3080. log_debug(LD_DIR,
  3081. "There are enough downloadable routerdescs to launch requests.");
  3082. should_delay = 0;
  3083. } else if (n_downloadable == 0) {
  3084. // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
  3085. should_delay = 1;
  3086. } else {
  3087. should_delay = (last_routerdesc_download_attempted +
  3088. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3089. if (!should_delay) {
  3090. if (last_routerdesc_download_attempted) {
  3091. log_info(LD_DIR,
  3092. "There are not many downloadable routerdescs, but we've "
  3093. "been waiting long enough (%d seconds). Downloading.",
  3094. (int)(now-last_routerdesc_download_attempted));
  3095. } else {
  3096. log_info(LD_DIR,
  3097. "There are not many downloadable routerdescs, but we've "
  3098. "never downloaded descriptors before. Downloading.");
  3099. }
  3100. }
  3101. }
  3102. if (! should_delay) {
  3103. int i, n_per_request;
  3104. n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
  3105. if (n_per_request > MAX_DL_PER_REQUEST)
  3106. n_per_request = MAX_DL_PER_REQUEST;
  3107. if (n_per_request < MIN_DL_PER_REQUEST)
  3108. n_per_request = MIN_DL_PER_REQUEST;
  3109. log_info(LD_DIR,
  3110. "Launching %d request%s for %d router%s, %d at a time",
  3111. (n_downloadable+n_per_request-1)/n_per_request,
  3112. n_downloadable>n_per_request?"s":"",
  3113. n_downloadable, n_downloadable>1?"s":"", n_per_request);
  3114. for (i=0; i < n_downloadable; i += n_per_request) {
  3115. initiate_descriptor_downloads(NULL, downloadable, i, i+n_per_request);
  3116. }
  3117. last_routerdesc_download_attempted = now;
  3118. }
  3119. smartlist_free(downloadable);
  3120. }
  3121. /** Launch downloads for router status as needed, using the strategy used by
  3122. * authorities and caches: download every descriptor we don't have but would
  3123. * serve from a random authoritiy that lists it. */
  3124. static void
  3125. update_router_descriptor_cache_downloads(time_t now)
  3126. {
  3127. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  3128. smartlist_t **download_from; /* ... and, what will we dl from it? */
  3129. digestmap_t *map; /* Which descs are in progress, or assigned? */
  3130. int i, j, n;
  3131. int n_download;
  3132. or_options_t *options = get_options();
  3133. if (!(server_mode(options) && options->DirPort)) {
  3134. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads() "
  3135. "on a non-mirror?");
  3136. }
  3137. if (!networkstatus_list || !smartlist_len(networkstatus_list))
  3138. return;
  3139. map = digestmap_new();
  3140. n = smartlist_len(networkstatus_list);
  3141. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3142. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3143. /* Set map[d]=1 for the digest of every descriptor that we are currently
  3144. * downloading. */
  3145. list_pending_descriptor_downloads(map);
  3146. /* For the digest of every descriptor that we don't have, and that we aren't
  3147. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  3148. * about that descriptor, and we haven't already failed to get that
  3149. * descriptor from the corresponding authority.
  3150. */
  3151. n_download = 0;
  3152. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3153. {
  3154. smartlist_t *dl = smartlist_create();
  3155. downloadable[ns_sl_idx] = dl;
  3156. download_from[ns_sl_idx] = smartlist_create();
  3157. SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
  3158. {
  3159. if (!rs->need_to_mirror)
  3160. continue;
  3161. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  3162. log_warn(LD_BUG,
  3163. "Bug: We have a router descriptor, but need_to_mirror=1.");
  3164. rs->need_to_mirror = 0;
  3165. continue;
  3166. }
  3167. if (options->AuthoritativeDir && dirserv_would_reject_router(rs)) {
  3168. rs->need_to_mirror = 0;
  3169. continue;
  3170. }
  3171. if (digestmap_get(map, rs->descriptor_digest)) {
  3172. /* We're downloading it already. */
  3173. continue;
  3174. } else {
  3175. /* We could download it from this guy. */
  3176. smartlist_add(dl, rs->descriptor_digest);
  3177. ++n_download;
  3178. }
  3179. });
  3180. });
  3181. /* At random, assign descriptors to authorities such that:
  3182. * - if d is a member of some downloadable[x], d is a member of some
  3183. * download_from[y]. (Everything we want to download, we try to download
  3184. * from somebody.)
  3185. * - If d is a member of download_from[y], d is a member of downloadable[y].
  3186. * (We only try to download descriptors from authorities who claim to have
  3187. * them.)
  3188. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  3189. * (We don't try to download anything from two authorities concurrently.)
  3190. */
  3191. while (n_download) {
  3192. int which_ns = crypto_rand_int(n);
  3193. smartlist_t *dl = downloadable[which_ns];
  3194. int idx;
  3195. char *d;
  3196. tor_assert(dl);
  3197. if (!smartlist_len(dl))
  3198. continue;
  3199. idx = crypto_rand_int(smartlist_len(dl));
  3200. d = smartlist_get(dl, idx);
  3201. if (! digestmap_get(map, d)) {
  3202. smartlist_add(download_from[which_ns], d);
  3203. digestmap_set(map, d, (void*) 1);
  3204. }
  3205. smartlist_del(dl, idx);
  3206. --n_download;
  3207. }
  3208. /* Now, we can actually launch our requests. */
  3209. for (i=0; i<n; ++i) {
  3210. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  3211. trusted_dir_server_t *ds =
  3212. router_get_trusteddirserver_by_digest(ns->identity_digest);
  3213. smartlist_t *dl = download_from[i];
  3214. if (!ds) {
  3215. log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
  3216. continue;
  3217. }
  3218. if (! smartlist_len(dl))
  3219. continue;
  3220. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  3221. smartlist_len(dl), ds->nickname);
  3222. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  3223. initiate_descriptor_downloads(&(ds->fake_status), dl, j,
  3224. j+MAX_DL_PER_REQUEST);
  3225. }
  3226. }
  3227. for (i=0; i<n; ++i) {
  3228. smartlist_free(download_from[i]);
  3229. smartlist_free(downloadable[i]);
  3230. }
  3231. tor_free(download_from);
  3232. tor_free(downloadable);
  3233. digestmap_free(map,NULL);
  3234. }
  3235. /** Launch downloads for router status as needed. */
  3236. void
  3237. update_router_descriptor_downloads(time_t now)
  3238. {
  3239. or_options_t *options = get_options();
  3240. if (server_mode(options) && options->DirPort) {
  3241. update_router_descriptor_cache_downloads(now);
  3242. } else {
  3243. update_router_descriptor_client_downloads(now);
  3244. }
  3245. }
  3246. static int
  3247. routerstatus_count_usable_entries(smartlist_t *entries)
  3248. {
  3249. int count = 0;
  3250. time_t now = time(NULL);
  3251. SMARTLIST_FOREACH(entries, routerstatus_t *, rs,
  3252. if (client_would_use_router(rs, now)) count++);
  3253. return count;
  3254. }
  3255. /** Return true iff we have enough networkstatus and router information to
  3256. * start building circuits. Right now, this means "more than half the
  3257. * networkstatus documents, and at least 1/4 of expected routers." */
  3258. //XXX should consider whether we have enough exiting nodes here.
  3259. int
  3260. router_have_minimum_dir_info(void)
  3261. {
  3262. int tot = 0, num_running = 0;
  3263. int n_ns, n_authorities, res, avg;
  3264. static int have_enough = 0;
  3265. if (!networkstatus_list || !routerlist) {
  3266. res = 0;
  3267. goto done;
  3268. }
  3269. n_authorities = smartlist_len(trusted_dir_servers);
  3270. n_ns = smartlist_len(networkstatus_list);
  3271. if (n_ns<=n_authorities/2) {
  3272. log_info(LD_DIR,
  3273. "We have %d of %d network statuses, and we want "
  3274. "more than %d.", n_ns, n_authorities, n_authorities/2);
  3275. res = 0;
  3276. goto done;
  3277. }
  3278. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3279. tot += routerstatus_count_usable_entries(ns->entries));
  3280. avg = tot / n_ns;
  3281. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3282. {
  3283. if (rs->status.is_running)
  3284. num_running++;
  3285. });
  3286. res = smartlist_len(routerlist->routers) >= (avg/4) && num_running > 2;
  3287. done:
  3288. if (res && !have_enough) {
  3289. log(LOG_NOTICE, LD_DIR,
  3290. "We now have enough directory information to build circuits.");
  3291. }
  3292. if (!res && have_enough) {
  3293. log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
  3294. "enough to build circuits.%s",
  3295. num_running > 2 ? "" : " (Not enough servers seem reachable -- "
  3296. "is your network connection down?)");
  3297. }
  3298. have_enough = res;
  3299. return res;
  3300. }
  3301. /** Return true iff we have downloaded, or attempted to download at least
  3302. * n_failures times, a network status for each authority. */
  3303. static int
  3304. have_tried_downloading_all_statuses(int n_failures)
  3305. {
  3306. if (!trusted_dir_servers)
  3307. return 0;
  3308. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  3309. {
  3310. /* If we don't have the status, and we haven't failed to get the status,
  3311. * we haven't tried to get the status. */
  3312. if (!networkstatus_get_by_digest(ds->digest) &&
  3313. ds->n_networkstatus_failures <= n_failures)
  3314. return 0;
  3315. });
  3316. return 1;
  3317. }
  3318. /** Reset the descriptor download failure count on all routers, so that we
  3319. * can retry any long-failed routers immediately.
  3320. */
  3321. void
  3322. router_reset_descriptor_download_failures(void)
  3323. {
  3324. if (!routerstatus_list)
  3325. return;
  3326. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3327. {
  3328. rs->n_download_failures = 0;
  3329. rs->next_attempt_at = 0;
  3330. });
  3331. tor_assert(networkstatus_list);
  3332. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3333. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  3334. {
  3335. if (!router_get_by_descriptor_digest(rs->descriptor_digest))
  3336. rs->need_to_mirror = 1;
  3337. }));
  3338. last_routerdesc_download_attempted = 0;
  3339. }
  3340. /** Any changes in a router descriptor's publication time larger than this are
  3341. * automatically non-cosmetic. */
  3342. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
  3343. /** Return true iff the only differences between r1 and r2 are such that
  3344. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  3345. */
  3346. int
  3347. router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
  3348. {
  3349. time_t r1pub, r2pub;
  3350. tor_assert(r1 && r2);
  3351. /* r1 should be the one that was published first. */
  3352. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  3353. routerinfo_t *ri_tmp = r2;
  3354. r2 = r1;
  3355. r1 = ri_tmp;
  3356. }
  3357. /* If any key fields differ, they're different. */
  3358. if (strcasecmp(r1->address, r2->address) ||
  3359. strcasecmp(r1->nickname, r2->nickname) ||
  3360. r1->or_port != r2->or_port ||
  3361. r1->dir_port != r2->dir_port ||
  3362. crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
  3363. crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
  3364. strcasecmp(r1->platform, r2->platform) ||
  3365. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  3366. (!r1->contact_info && r2->contact_info) ||
  3367. (r1->contact_info && r2->contact_info &&
  3368. strcasecmp(r1->contact_info, r2->contact_info)) ||
  3369. r1->is_hibernating != r2->is_hibernating ||
  3370. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  3371. return 0;
  3372. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  3373. return 0;
  3374. if (r1->declared_family && r2->declared_family) {
  3375. int i, n;
  3376. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  3377. return 0;
  3378. n = smartlist_len(r1->declared_family);
  3379. for (i=0; i < n; ++i) {
  3380. if (strcasecmp(smartlist_get(r1->declared_family, i),
  3381. smartlist_get(r2->declared_family, i)))
  3382. return 0;
  3383. }
  3384. }
  3385. /* Did bandwidth change a lot? */
  3386. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  3387. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  3388. return 0;
  3389. /* Did more than 12 hours pass? */
  3390. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  3391. < r2->cache_info.published_on)
  3392. return 0;
  3393. /* Did uptime fail to increase by approximately the amount we would think,
  3394. * give or take 30 minutes? */
  3395. r1pub = r1->cache_info.published_on;
  3396. r2pub = r2->cache_info.published_on;
  3397. if (abs(r2->uptime - (r1->uptime + (r2pub - r1pub))))
  3398. return 0;
  3399. /* Otherwise, the difference is cosmetic. */
  3400. return 1;
  3401. }
  3402. static void
  3403. routerlist_assert_ok(routerlist_t *rl)
  3404. {
  3405. digestmap_iter_t *iter;
  3406. routerinfo_t *r2;
  3407. signed_descriptor_t *sd2;
  3408. if (!routerlist)
  3409. return;
  3410. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  3411. {
  3412. r2 = digestmap_get(rl->identity_map, r->cache_info.identity_digest);
  3413. tor_assert(r == r2);
  3414. sd2 = digestmap_get(rl->desc_digest_map,
  3415. r->cache_info.signed_descriptor_digest);
  3416. tor_assert(&(r->cache_info) == sd2);
  3417. });
  3418. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  3419. {
  3420. r2 = digestmap_get(rl->identity_map, sd->identity_digest);
  3421. tor_assert(sd != &(r2->cache_info));
  3422. sd2 = digestmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  3423. tor_assert(sd == sd2);
  3424. });
  3425. iter = digestmap_iter_init(rl->identity_map);
  3426. while (!digestmap_iter_done(iter)) {
  3427. const char *d;
  3428. void *_r;
  3429. routerinfo_t *r;
  3430. digestmap_iter_get(iter, &d, &_r);
  3431. r = _r;
  3432. tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
  3433. iter = digestmap_iter_next(rl->identity_map, iter);
  3434. }
  3435. iter = digestmap_iter_init(rl->desc_digest_map);
  3436. while (!digestmap_iter_done(iter)) {
  3437. const char *d;
  3438. void *_sd;
  3439. signed_descriptor_t *sd;
  3440. digestmap_iter_get(iter, &d, &_sd);
  3441. sd = _sd;
  3442. tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
  3443. iter = digestmap_iter_next(rl->desc_digest_map, iter);
  3444. }
  3445. }
  3446. /** Allocate and return a new string representing the contact info
  3447. * and platform string for <b>router</b>,
  3448. * surrounded by quotes and using standard C escapes.
  3449. *
  3450. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  3451. * thread. Also, each call invalidates the last-returned value, so don't
  3452. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  3453. */
  3454. const char *
  3455. esc_router_info(routerinfo_t *router)
  3456. {
  3457. static char *info;
  3458. char *esc_contact, *esc_platform;
  3459. size_t len;
  3460. if (info)
  3461. tor_free(info);
  3462. esc_contact = esc_for_log(router->contact_info);
  3463. esc_platform = esc_for_log(router->platform);
  3464. len = strlen(esc_contact)+strlen(esc_platform)+32;
  3465. info = tor_malloc(len);
  3466. tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
  3467. esc_platform);
  3468. tor_free(esc_contact);
  3469. tor_free(esc_platform);
  3470. return info;
  3471. }