routerlist.c 130 KB

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