routerlist.c 125 KB

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