routerlist.c 121 KB

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