routerlist.c 126 KB

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