routerlist.c 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerlist_c_id[] = "$Id$";
  7. /**
  8. * \file routerlist.c
  9. * \brief Code to
  10. * maintain and access the global list of routerinfos for known
  11. * servers.
  12. **/
  13. #include "or.h"
  14. /****************************************************************************/
  15. /** Global list of a trusted_dir_server_t object for each trusted directory
  16. * server. */
  17. static smartlist_t *trusted_dir_servers = NULL;
  18. /* static function prototypes */
  19. static routerinfo_t *router_pick_directory_server_impl(int requireother,
  20. int fascistfirewall,
  21. int for_v2_directory);
  22. static trusted_dir_server_t *router_pick_trusteddirserver_impl(
  23. int need_v1_support, int requireother, int fascistfirewall);
  24. static void mark_all_trusteddirservers_up(void);
  25. static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  26. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  27. /****************************************************************************/
  28. /****
  29. * Functions to manage and access our list of known routers. (Note:
  30. * dirservers maintain a separate, independent list of known router
  31. * descriptors.)
  32. ****/
  33. /** Global list of all of the routers that we know about. */
  34. static routerlist_t *routerlist = NULL;
  35. extern int has_fetched_directory; /**< from main.c */
  36. /** Global list of all of the current network_status documents that we know
  37. * about. This list is kept sorted by published_on. */
  38. static smartlist_t *networkstatus_list = NULL;
  39. /** True iff networkstatus_list has changed since the last time we called
  40. * routers_update_all_from_networkstatus. Set by router_set_networkstatus;
  41. * cleared by routers_update_all_from_networkstatus.
  42. */
  43. static int networkstatus_list_has_changed = 0;
  44. /** Repopulate our list of network_status_t objects from the list cached on
  45. * disk. Return 0 on success, -1 on failure. */
  46. int
  47. router_reload_networkstatus(void)
  48. {
  49. char filename[512];
  50. struct stat st;
  51. smartlist_t *entries, *bad_names;
  52. char *s;
  53. tor_assert(get_options()->DataDirectory);
  54. if (!networkstatus_list)
  55. networkstatus_list = smartlist_create();
  56. tor_snprintf(filename,sizeof(filename),"%s/cached-status",
  57. get_options()->DataDirectory);
  58. entries = tor_listdir(filename);
  59. bad_names = smartlist_create();
  60. SMARTLIST_FOREACH(entries, const char *, fn, {
  61. char buf[DIGEST_LEN];
  62. if (strlen(fn) != HEX_DIGEST_LEN ||
  63. base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
  64. log_fn(LOG_INFO,
  65. "Skipping cached-status file with unexpected name \"%s\"",fn);
  66. continue;
  67. }
  68. tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
  69. get_options()->DataDirectory, fn);
  70. s = read_file_to_str(filename, 0);
  71. if (s) {
  72. stat(filename, &st);
  73. if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
  74. log_fn(LOG_WARN, "Couldn't load networkstatus from \"%s\"",filename);
  75. }
  76. tor_free(s);
  77. }
  78. });
  79. networkstatus_list_clean(time(NULL));
  80. routers_update_all_from_networkstatus();
  81. return 0;
  82. }
  83. /* Router descriptor storage.
  84. *
  85. * Routerdescs are stored in a big file, named "cached-routers". As new
  86. * routerdescs arrive, we append them to a journal file named
  87. * "cached-routers.new".
  88. *
  89. * From time to time, we replace "cached-routers" with a new file containing
  90. * only the live, non-superseded descriptors, and clear cached-routers.new.
  91. *
  92. * On startup, we read both files.
  93. */
  94. /** The size of the router log, in bytes. */
  95. static size_t router_journal_len = 0;
  96. /** The size of the router store, in bytes. */
  97. static size_t router_store_len = 0;
  98. /** Helper: return 1 iff the router log is so big we want to rebuild the
  99. * store. */
  100. static int
  101. router_should_rebuild_store(void)
  102. {
  103. if (router_store_len > (1<<16))
  104. return router_journal_len > router_store_len / 2;
  105. else
  106. return router_journal_len > (1<<15);
  107. }
  108. /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
  109. * journal. */
  110. static int
  111. router_append_to_journal(const char *s, size_t len)
  112. {
  113. or_options_t *options = get_options();
  114. size_t fname_len = strlen(options->DataDirectory)+32;
  115. char *fname = tor_malloc(len);
  116. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  117. options->DataDirectory);
  118. if (!len)
  119. len = strlen(s);
  120. if (append_bytes_to_file(fname, s, len, 0)) {
  121. log_fn(LOG_WARN, "Unable to store router descriptor");
  122. tor_free(fname);
  123. return -1;
  124. }
  125. tor_free(fname);
  126. router_journal_len += len;
  127. return 0;
  128. }
  129. /** If the journal is too long, or if <b>force</b> is true, then atomically
  130. * replace the router store with the routers currently in our routerlist, and
  131. * clear the journal. Return 0 on success, -1 on failure.
  132. */
  133. static int
  134. router_rebuild_store(int force)
  135. {
  136. size_t len = 0;
  137. or_options_t *options;
  138. size_t fname_len;
  139. smartlist_t *chunk_list = NULL;
  140. char *fname = NULL;
  141. int r = -1;
  142. if (!force && !router_should_rebuild_store())
  143. return 0;
  144. if (!routerlist)
  145. return 0;
  146. /* Don't save deadweight. */
  147. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  148. options = get_options();
  149. fname_len = strlen(options->DataDirectory)+32;
  150. fname = tor_malloc(fname_len);
  151. tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
  152. chunk_list = smartlist_create();
  153. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  154. {
  155. sized_chunk_t *c;
  156. if (!ri->signed_descriptor) {
  157. log_fn(LOG_WARN, "Bug! No descriptor stored for router '%s'.",
  158. ri->nickname);
  159. goto done;
  160. }
  161. c = tor_malloc(sizeof(sized_chunk_t));
  162. c->bytes = ri->signed_descriptor;
  163. c->len = ri->signed_descriptor_len;
  164. smartlist_add(chunk_list, c);
  165. });
  166. if (write_chunks_to_file(fname, chunk_list, 0)<0) {
  167. log_fn(LOG_WARN, "Error writing router store to disk.");
  168. goto done;
  169. }
  170. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  171. options->DataDirectory);
  172. write_str_to_file(fname, "", 0);
  173. r = 0;
  174. router_store_len = len;
  175. router_journal_len = 0;
  176. done:
  177. tor_free(fname);
  178. if (chunk_list) {
  179. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  180. smartlist_free(chunk_list);
  181. }
  182. return r;
  183. }
  184. /* Load all cached router descriptors from the store. Return 0 on success and
  185. * -1 on failure.
  186. */
  187. int
  188. router_reload_router_list(void)
  189. {
  190. or_options_t *options = get_options();
  191. size_t fname_len = strlen(options->DataDirectory)+32;
  192. char *fname = tor_malloc(fname_len);
  193. struct stat st;
  194. int j;
  195. if (!routerlist) {
  196. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  197. routerlist->routers = smartlist_create();
  198. }
  199. router_journal_len = router_store_len = 0;
  200. for (j = 0; j < 2; ++j) {
  201. char *contents;
  202. tor_snprintf(fname, fname_len,
  203. (j==0)?"%s/cached-routers":"%s/cached-routers.new",
  204. options->DataDirectory);
  205. contents = read_file_to_str(fname, 0);
  206. if (contents) {
  207. stat(fname, &st);
  208. if (j==0)
  209. router_store_len = st.st_size;
  210. else
  211. router_journal_len = st.st_size;
  212. router_load_routers_from_string(contents, 1, NULL);
  213. tor_free(contents);
  214. }
  215. }
  216. /* Don't cache expired routers. */
  217. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  218. if (router_journal_len) {
  219. /* Always clear the journal on startup.*/
  220. router_rebuild_store(1);
  221. }
  222. return 0;
  223. }
  224. /** Set *<b>outp</b> to a smartlist containing a list of
  225. * trusted_dir_server_t * for all known trusted dirservers. Callers
  226. * must not modify the list or its contents.
  227. */
  228. void
  229. router_get_trusted_dir_servers(smartlist_t **outp)
  230. {
  231. if (!trusted_dir_servers)
  232. trusted_dir_servers = smartlist_create();
  233. *outp = trusted_dir_servers;
  234. }
  235. /** Try to find a running dirserver. If there are no running dirservers
  236. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  237. * set all the authoritative ones as running again, and pick one;
  238. * if there are then no dirservers at all in our routerlist,
  239. * reload the routerlist and try one last time. If for_runningrouters is
  240. * true, then only pick a dirserver that can answer runningrouters queries
  241. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  242. * Other args are as in router_pick_directory_server_impl().
  243. */
  244. routerinfo_t *
  245. router_pick_directory_server(int requireother,
  246. int fascistfirewall,
  247. int for_v2_directory,
  248. int retry_if_no_servers)
  249. {
  250. routerinfo_t *choice;
  251. if (!routerlist)
  252. return NULL;
  253. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  254. for_v2_directory);
  255. if (choice || !retry_if_no_servers)
  256. return choice;
  257. log_fn(LOG_INFO,"No reachable router entries for dirservers. Trying them all again.");
  258. /* mark all authdirservers as up again */
  259. mark_all_trusteddirservers_up();
  260. /* try again */
  261. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  262. for_v2_directory);
  263. if (choice)
  264. return choice;
  265. log_fn(LOG_INFO,"Still no %s router entries. Reloading and trying again.",
  266. firewall_is_fascist() ? "reachable" : "known");
  267. has_fetched_directory=0; /* reset it */
  268. if (router_reload_router_list()) {
  269. return NULL;
  270. }
  271. /* give it one last try */
  272. choice = router_pick_directory_server_impl(requireother, 0,
  273. for_v2_directory);
  274. return choice;
  275. }
  276. trusted_dir_server_t *
  277. router_get_trusteddirserver_by_digest(const char *digest)
  278. {
  279. if (!trusted_dir_servers)
  280. return NULL;
  281. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  282. {
  283. if (!memcmp(ds->digest, digest, DIGEST_LEN))
  284. return ds;
  285. });
  286. return NULL;
  287. }
  288. /** Try to find a running trusted dirserver. If there are no running
  289. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  290. * set them all as running again, and try again.
  291. * Other args are as in router_pick_trusteddirserver_impl().
  292. */
  293. trusted_dir_server_t *
  294. router_pick_trusteddirserver(int need_v1_support,
  295. int requireother,
  296. int fascistfirewall,
  297. int retry_if_no_servers)
  298. {
  299. trusted_dir_server_t *choice;
  300. choice = router_pick_trusteddirserver_impl(need_v1_support,
  301. requireother, fascistfirewall);
  302. if (choice || !retry_if_no_servers)
  303. return choice;
  304. log_fn(LOG_INFO,"No trusted dirservers are reachable. Trying them all again.");
  305. mark_all_trusteddirservers_up();
  306. return router_pick_trusteddirserver_impl(need_v1_support,
  307. requireother, fascistfirewall);
  308. }
  309. /** Pick a random running verified directory server/mirror from our
  310. * routerlist.
  311. * If <b>fascistfirewall</b> and we're not using a proxy,
  312. * make sure the port we pick is allowed by options-\>firewallports.
  313. * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
  314. * choose a directory server new enough to support the v2 directory
  315. * functionality.
  316. */
  317. static routerinfo_t *
  318. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  319. int for_v2_directory)
  320. {
  321. routerinfo_t *result;
  322. smartlist_t *sl;
  323. if (!routerlist)
  324. return NULL;
  325. if (get_options()->HttpProxy)
  326. fascistfirewall = 0;
  327. /* Find all the running dirservers we know about. */
  328. sl = smartlist_create();
  329. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  330. {
  331. if (!router->is_running || !router->dir_port || !router->is_verified)
  332. continue;
  333. if (requireother && router_is_me(router))
  334. continue;
  335. if (fascistfirewall) {
  336. if (!fascist_firewall_allows_address(router->addr, router->dir_port))
  337. continue;
  338. }
  339. /* Before 0.1.1.6-alpha, only trusted dirservers served status info.
  340. * Before 0.1.1.7-alpha, retrieving nonexistent server IDs could bork
  341. * the directory server.
  342. */
  343. if (for_v2_directory &&
  344. !(tor_version_as_new_as(router->platform,"0.1.1.7-alpha") ||
  345. router_digest_is_trusted_dir(router->identity_digest)))
  346. continue;
  347. smartlist_add(sl, router);
  348. });
  349. result = smartlist_choose(sl);
  350. smartlist_free(sl);
  351. return result;
  352. }
  353. /** Choose randomly from among the trusted dirservers that are up.
  354. * If <b>fascistfirewall</b> and we're not using a proxy,
  355. * make sure the port we pick is allowed by options-\>firewallports.
  356. * If <b>requireother</b>, it cannot be us. If <b>need_v1_support</b>, choose
  357. * a trusted authority for the v1 directory system.
  358. */
  359. static trusted_dir_server_t *
  360. router_pick_trusteddirserver_impl(int need_v1_support,
  361. int requireother, int fascistfirewall)
  362. {
  363. smartlist_t *sl;
  364. routerinfo_t *me;
  365. trusted_dir_server_t *ds;
  366. sl = smartlist_create();
  367. me = router_get_my_routerinfo();
  368. if (!trusted_dir_servers)
  369. return NULL;
  370. if (get_options()->HttpProxy)
  371. fascistfirewall = 0;
  372. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  373. {
  374. if (!d->is_running) continue;
  375. if (need_v1_support && !d->supports_v1_protocol)
  376. continue;
  377. if (requireother && me &&
  378. !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
  379. continue;
  380. if (fascistfirewall) {
  381. if (!fascist_firewall_allows_address(d->addr, d->dir_port))
  382. continue;
  383. }
  384. smartlist_add(sl, d);
  385. });
  386. ds = smartlist_choose(sl);
  387. smartlist_free(sl);
  388. return ds;
  389. }
  390. /** Go through and mark the authoritative dirservers as up. */
  391. static void
  392. mark_all_trusteddirservers_up(void)
  393. {
  394. if (routerlist) {
  395. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  396. if (router_digest_is_trusted_dir(router->identity_digest) &&
  397. router->dir_port > 0) {
  398. router->is_running = 1;
  399. });
  400. }
  401. if (trusted_dir_servers) {
  402. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  403. {
  404. dir->is_running = 1;
  405. dir->n_networkstatus_failures = 0;
  406. });
  407. }
  408. }
  409. /** Return 0 if \\exists an authoritative dirserver that's currently
  410. * thought to be running, else return 1.
  411. */
  412. int
  413. all_trusted_directory_servers_down(void)
  414. {
  415. if (!trusted_dir_servers)
  416. return 1;
  417. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  418. if (dir->is_running) return 0);
  419. return 1;
  420. }
  421. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  422. * This is used to make sure we don't pick siblings in a single path.
  423. */
  424. void
  425. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  426. {
  427. routerinfo_t *r;
  428. config_line_t *cl;
  429. if (!router->declared_family)
  430. return;
  431. /* Add every r such that router declares familyness with r, and r
  432. * declares familyhood with router. */
  433. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  434. {
  435. if (!(r = router_get_by_nickname(n)))
  436. continue;
  437. if (!r->declared_family)
  438. continue;
  439. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  440. {
  441. if (router_nickname_matches(router, n2))
  442. smartlist_add(sl, r);
  443. });
  444. });
  445. /* If the user declared any families locally, honor those too. */
  446. for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
  447. if (router_nickname_is_in_list(router, cl->value)) {
  448. add_nickname_list_to_smartlist(sl, cl->value, 0);
  449. }
  450. }
  451. }
  452. /** List of strings for nicknames we've already warned about and that are
  453. * still unknown / unavailable. */
  454. static smartlist_t *warned_nicknames = NULL;
  455. /** Given a comma-and-whitespace separated list of nicknames, see which
  456. * nicknames in <b>list</b> name routers in our routerlist that are
  457. * currently running. Add the routerinfos for those routers to <b>sl</b>.
  458. */
  459. void
  460. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down)
  461. {
  462. routerinfo_t *router;
  463. smartlist_t *nickname_list;
  464. if (!list)
  465. return; /* nothing to do */
  466. tor_assert(sl);
  467. nickname_list = smartlist_create();
  468. if (!warned_nicknames)
  469. warned_nicknames = smartlist_create();
  470. smartlist_split_string(nickname_list, list, ",",
  471. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  472. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  473. int warned;
  474. if (!is_legal_nickname_or_hexdigest(nick)) {
  475. log_fn(LOG_WARN,"Nickname %s is misformed; skipping", nick);
  476. continue;
  477. }
  478. router = router_get_by_nickname(nick);
  479. warned = smartlist_string_isin(warned_nicknames, nick);
  480. if (router) {
  481. if (router->is_running) {
  482. smartlist_add(sl,router);
  483. if (warned)
  484. smartlist_string_remove(warned_nicknames, nick);
  485. } else {
  486. if (!warned) {
  487. log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG,
  488. "Nickname list includes '%s' which is known but down.",nick);
  489. smartlist_add(warned_nicknames, tor_strdup(nick));
  490. }
  491. }
  492. } else {
  493. if (!warned) {
  494. log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
  495. "Nickname list includes '%s' which isn't a known router.",nick);
  496. smartlist_add(warned_nicknames, tor_strdup(nick));
  497. }
  498. }
  499. });
  500. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  501. smartlist_free(nickname_list);
  502. }
  503. /** Return 1 iff any member of the comma-separated list <b>list</b> is an
  504. * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
  505. */
  506. static int
  507. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  508. {
  509. smartlist_t *nickname_list;
  510. int v = 0;
  511. if (!list)
  512. return 0; /* definitely not */
  513. tor_assert(router);
  514. nickname_list = smartlist_create();
  515. smartlist_split_string(nickname_list, list, ",",
  516. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  517. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  518. if (router_nickname_matches(router, cp)) {v=1;break;});
  519. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  520. smartlist_free(nickname_list);
  521. return v;
  522. }
  523. /** Add every router from our routerlist that is currently running to
  524. * <b>sl</b>.
  525. */
  526. static void
  527. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
  528. int need_uptime, int need_capacity)
  529. {
  530. if (!routerlist)
  531. return;
  532. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  533. {
  534. if (router->is_running &&
  535. (router->is_verified ||
  536. (allow_unverified &&
  537. !router_is_unreliable(router, need_uptime, need_capacity)))) {
  538. /* If it's running, and either it's verified or we're ok picking
  539. * unverified routers and this one is suitable.
  540. */
  541. smartlist_add(sl, router);
  542. }
  543. });
  544. }
  545. /** Look through the routerlist until we find a router that has my key.
  546. Return it. */
  547. routerinfo_t *
  548. routerlist_find_my_routerinfo(void)
  549. {
  550. if (!routerlist)
  551. return NULL;
  552. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  553. {
  554. if (router_is_me(router))
  555. return router;
  556. });
  557. return NULL;
  558. }
  559. /** Find a router that's up, that has this IP address, and
  560. * that allows exit to this address:port, or return NULL if there
  561. * isn't a good one.
  562. */
  563. routerinfo_t *
  564. router_find_exact_exit_enclave(const char *address, uint16_t port)
  565. {
  566. uint32_t addr;
  567. struct in_addr in;
  568. if (!tor_inet_aton(address, &in))
  569. return NULL; /* it's not an IP already */
  570. addr = ntohl(in.s_addr);
  571. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  572. {
  573. log_fn(LOG_DEBUG,"Considering %s: %d, %u==%u, %d.",
  574. router->nickname,
  575. router->is_running,
  576. router->addr, addr,
  577. router_compare_addr_to_addr_policy(addr, port, router->exit_policy));
  578. if (router->is_running &&
  579. router->addr == addr &&
  580. router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
  581. ADDR_POLICY_ACCEPTED)
  582. return router;
  583. });
  584. return NULL;
  585. }
  586. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  587. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  588. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  589. * bandwidth.
  590. */
  591. int
  592. router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
  593. {
  594. if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
  595. return 1;
  596. if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
  597. return 1;
  598. return 0;
  599. }
  600. /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
  601. static void
  602. routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
  603. {
  604. int i;
  605. routerinfo_t *router;
  606. for (i = 0; i < smartlist_len(sl); ++i) {
  607. router = smartlist_get(sl, i);
  608. if (router_is_unreliable(router, 1, 0)) {
  609. // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
  610. // router->nickname);
  611. smartlist_del(sl, i--);
  612. }
  613. }
  614. }
  615. #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
  616. /** Choose a random element of router list <b>sl</b>, weighted by
  617. * the advertised bandwidth of each router.
  618. */
  619. routerinfo_t *
  620. routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
  621. {
  622. int i;
  623. routerinfo_t *router;
  624. smartlist_t *bandwidths;
  625. uint32_t this_bw, tmp, total_bw=0, rand_bw;
  626. uint32_t *p;
  627. /* First count the total bandwidth weight, and make a smartlist
  628. * of each value. */
  629. bandwidths = smartlist_create();
  630. for (i = 0; i < smartlist_len(sl); ++i) {
  631. router = smartlist_get(sl, i);
  632. this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
  633. router->bandwidthcapacity : router->bandwidthrate;
  634. /* if they claim something huge, don't believe it */
  635. if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
  636. this_bw = MAX_BELIEVABLE_BANDWIDTH;
  637. p = tor_malloc(sizeof(uint32_t));
  638. *p = this_bw;
  639. smartlist_add(bandwidths, p);
  640. total_bw += this_bw;
  641. }
  642. if (!total_bw) {
  643. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  644. smartlist_free(bandwidths);
  645. return smartlist_choose(sl);
  646. }
  647. /* Second, choose a random value from the bandwidth weights. */
  648. rand_bw = crypto_pseudo_rand_int(total_bw);
  649. /* Last, count through sl until we get to the element we picked */
  650. tmp = 0;
  651. for (i=0; ; i++) {
  652. tor_assert(i < smartlist_len(sl));
  653. p = smartlist_get(bandwidths, i);
  654. tmp += *p;
  655. if (tmp >= rand_bw)
  656. break;
  657. }
  658. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  659. smartlist_free(bandwidths);
  660. return (routerinfo_t *)smartlist_get(sl, i);
  661. }
  662. /** Return a random running router from the routerlist. If any node
  663. * named in <b>preferred</b> is available, pick one of those. Never
  664. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  665. * <b>excludedsmartlist</b>, even if they are the only nodes
  666. * available. If <b>strict</b> is true, never pick any node besides
  667. * those in <b>preferred</b>.
  668. * If <b>need_uptime</b> is non-zero, don't return a router with less
  669. * than a minimum uptime.
  670. * If <b>need_capacity</b> is non-zero, weight your choice by the
  671. * advertised capacity of each router.
  672. */
  673. routerinfo_t *
  674. router_choose_random_node(const char *preferred,
  675. const char *excluded,
  676. smartlist_t *excludedsmartlist,
  677. int need_uptime, int need_capacity,
  678. int allow_unverified, int strict)
  679. {
  680. smartlist_t *sl, *excludednodes;
  681. routerinfo_t *choice;
  682. excludednodes = smartlist_create();
  683. add_nickname_list_to_smartlist(excludednodes,excluded,0);
  684. /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
  685. * since the user explicitly asked for these nodes. */
  686. sl = smartlist_create();
  687. add_nickname_list_to_smartlist(sl,preferred,1);
  688. smartlist_subtract(sl,excludednodes);
  689. if (excludedsmartlist)
  690. smartlist_subtract(sl,excludedsmartlist);
  691. choice = smartlist_choose(sl);
  692. smartlist_free(sl);
  693. if (!choice && !strict) {
  694. /* Then give up on our preferred choices: any node
  695. * will do that has the required attributes. */
  696. sl = smartlist_create();
  697. router_add_running_routers_to_smartlist(sl, allow_unverified,
  698. need_uptime, need_capacity);
  699. smartlist_subtract(sl,excludednodes);
  700. if (excludedsmartlist)
  701. smartlist_subtract(sl,excludedsmartlist);
  702. if (need_uptime)
  703. routerlist_sl_remove_unreliable_routers(sl);
  704. if (need_capacity)
  705. choice = routerlist_sl_choose_by_bandwidth(sl);
  706. else
  707. choice = smartlist_choose(sl);
  708. smartlist_free(sl);
  709. }
  710. smartlist_free(excludednodes);
  711. if (!choice)
  712. log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
  713. return choice;
  714. }
  715. /** Return true iff the digest of <b>router</b>'s identity key,
  716. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  717. * optionally prefixed with a single dollar sign). Return false if
  718. * <b>hexdigest</b> is malformed, or it doesn't match. */
  719. static INLINE int
  720. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  721. {
  722. char digest[DIGEST_LEN];
  723. tor_assert(hexdigest);
  724. if (hexdigest[0] == '$')
  725. ++hexdigest;
  726. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  727. base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  728. return 0;
  729. return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
  730. }
  731. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  732. * (case-insensitive), or if <b>router's</b> identity key digest
  733. * matches a hexadecimal value stored in <b>nickname</b>. Return
  734. * false otherwise. */
  735. static int
  736. router_nickname_matches(routerinfo_t *router, const char *nickname)
  737. {
  738. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  739. return 1;
  740. return router_hex_digest_matches(router, nickname);
  741. }
  742. /** Return the router in our routerlist whose (case-insensitive)
  743. * nickname or (case-sensitive) hexadecimal key digest is
  744. * <b>nickname</b>. Return NULL if no such router is known.
  745. */
  746. routerinfo_t *
  747. router_get_by_nickname(const char *nickname)
  748. {
  749. int maybedigest;
  750. char digest[DIGEST_LEN];
  751. tor_assert(nickname);
  752. if (!routerlist)
  753. return NULL;
  754. if (nickname[0] == '$')
  755. return router_get_by_hexdigest(nickname);
  756. if (server_mode(get_options()) &&
  757. !strcasecmp(nickname, get_options()->Nickname))
  758. return router_get_my_routerinfo();
  759. maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
  760. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  761. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  762. {
  763. /* XXXX001 NM Should this restrict by Named rouers, or warn on
  764. * non-named routers, or something? */
  765. if (0 == strcasecmp(router->nickname, nickname) ||
  766. (maybedigest && 0 == memcmp(digest, router->identity_digest,
  767. DIGEST_LEN)))
  768. return router;
  769. });
  770. return NULL;
  771. }
  772. /** Return true iff <b>digest</b> is the digest of the identity key of
  773. * a trusted directory. */
  774. int
  775. router_digest_is_trusted_dir(const char *digest)
  776. {
  777. if (!trusted_dir_servers)
  778. return 0;
  779. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  780. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  781. return 0;
  782. }
  783. /** Return the router in our routerlist whose hexadecimal key digest
  784. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  785. routerinfo_t *
  786. router_get_by_hexdigest(const char *hexdigest)
  787. {
  788. char digest[DIGEST_LEN];
  789. tor_assert(hexdigest);
  790. if (!routerlist)
  791. return NULL;
  792. if (hexdigest[0]=='$')
  793. ++hexdigest;
  794. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  795. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  796. return NULL;
  797. return router_get_by_digest(digest);
  798. }
  799. /** Return the router in our routerlist whose 20-byte key digest
  800. * is <b>digest</b>. Return NULL if no such router is known. */
  801. routerinfo_t *
  802. router_get_by_digest(const char *digest)
  803. {
  804. tor_assert(digest);
  805. if (!routerlist) return NULL;
  806. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t*, router,
  807. {
  808. if (0 == memcmp(router->identity_digest, digest, DIGEST_LEN))
  809. return router;
  810. });
  811. return NULL;
  812. }
  813. /** Set *<b>prouterlist</b> to the current list of all known routers. */
  814. void
  815. router_get_routerlist(routerlist_t **prouterlist)
  816. {
  817. *prouterlist = routerlist;
  818. }
  819. #if 0
  820. /** Return the publication time on the current routerlist, or 0 if we have no
  821. * routerlist. */
  822. time_t
  823. routerlist_get_published_time(void)
  824. {
  825. return routerlist ? routerlist->published_on : 0;
  826. }
  827. #endif
  828. /** Free all storage held by <b>router</b>. */
  829. void
  830. routerinfo_free(routerinfo_t *router)
  831. {
  832. if (!router)
  833. return;
  834. tor_free(router->signed_descriptor);
  835. tor_free(router->address);
  836. tor_free(router->nickname);
  837. tor_free(router->platform);
  838. tor_free(router->contact_info);
  839. if (router->onion_pkey)
  840. crypto_free_pk_env(router->onion_pkey);
  841. if (router->identity_pkey)
  842. crypto_free_pk_env(router->identity_pkey);
  843. if (router->declared_family) {
  844. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  845. smartlist_free(router->declared_family);
  846. }
  847. addr_policy_free(router->exit_policy);
  848. tor_free(router);
  849. }
  850. /** Allocate a fresh copy of <b>router</b> */
  851. routerinfo_t *
  852. routerinfo_copy(const routerinfo_t *router)
  853. {
  854. routerinfo_t *r;
  855. addr_policy_t **e, *tmp;
  856. r = tor_malloc(sizeof(routerinfo_t));
  857. memcpy(r, router, sizeof(routerinfo_t));
  858. r->address = tor_strdup(r->address);
  859. r->nickname = tor_strdup(r->nickname);
  860. r->platform = tor_strdup(r->platform);
  861. if (r->signed_descriptor)
  862. r->signed_descriptor = tor_strdup(r->signed_descriptor);
  863. if (r->onion_pkey)
  864. r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
  865. if (r->identity_pkey)
  866. r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
  867. e = &r->exit_policy;
  868. while (*e) {
  869. tmp = tor_malloc(sizeof(addr_policy_t));
  870. memcpy(tmp,*e,sizeof(addr_policy_t));
  871. *e = tmp;
  872. (*e)->string = tor_strdup((*e)->string);
  873. e = & ((*e)->next);
  874. }
  875. if (r->declared_family) {
  876. r->declared_family = smartlist_create();
  877. SMARTLIST_FOREACH(router->declared_family, const char *, s,
  878. smartlist_add(r->declared_family, tor_strdup(s)));
  879. }
  880. return r;
  881. }
  882. /** Free all storage held by a routerlist <b>rl</b> */
  883. void
  884. routerlist_free(routerlist_t *rl)
  885. {
  886. tor_assert(rl);
  887. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  888. routerinfo_free(r));
  889. smartlist_free(rl->routers);
  890. tor_free(rl);
  891. }
  892. /** Free all memory held by the rouerlist module */
  893. void
  894. routerlist_free_all(void)
  895. {
  896. if (routerlist)
  897. routerlist_free(routerlist);
  898. routerlist = NULL;
  899. if (warned_nicknames) {
  900. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  901. smartlist_free(warned_nicknames);
  902. warned_nicknames = NULL;
  903. }
  904. if (trusted_dir_servers) {
  905. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  906. { tor_free(ds->address); tor_free(ds); });
  907. smartlist_free(trusted_dir_servers);
  908. trusted_dir_servers = NULL;
  909. }
  910. if (networkstatus_list) {
  911. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  912. networkstatus_free(ns));
  913. smartlist_free(networkstatus_list);
  914. networkstatus_list = NULL;
  915. }
  916. }
  917. /** Free all storage held by the routerstatus object <b>rs</b>. */
  918. void
  919. routerstatus_free(routerstatus_t *rs)
  920. {
  921. tor_free(rs);
  922. }
  923. /** Free all storage held by the networkstatus object <b>ns</b>. */
  924. void
  925. networkstatus_free(networkstatus_t *ns)
  926. {
  927. tor_free(ns->source_address);
  928. tor_free(ns->contact);
  929. if (ns->signing_key)
  930. crypto_free_pk_env(ns->signing_key);
  931. tor_free(ns->client_versions);
  932. tor_free(ns->server_versions);
  933. if (ns->entries) {
  934. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs, routerstatus_free(rs));
  935. smartlist_free(ns->entries);
  936. }
  937. tor_free(ns);
  938. }
  939. /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
  940. void
  941. router_mark_as_down(const char *digest)
  942. {
  943. routerinfo_t *router;
  944. tor_assert(digest);
  945. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  946. if (!memcmp(d->digest, digest, DIGEST_LEN))
  947. d->is_running = 0);
  948. router = router_get_by_digest(digest);
  949. if (!router) /* we don't seem to know about him in the first place */
  950. return;
  951. log_fn(LOG_DEBUG,"Marking router '%s' as down.",router->nickname);
  952. if (router_is_me(router) && !we_are_hibernating())
  953. log_fn(LOG_WARN, "We just marked ourself as down. Are your external addresses reachable?");
  954. router->is_running = 0;
  955. }
  956. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  957. * older entries (if any) with the same key. Note: Callers should not hold
  958. * their pointers to <b>router</b> if this function fails; <b>router</b>
  959. * will either be inserted into the routerlist or freed.
  960. *
  961. * Returns >= 0 if the router was added; less than 0 if it was not.
  962. *
  963. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  964. * describing the reason for not liking the routerinfo.
  965. *
  966. * If the return value is less than -1, there was a problem with the
  967. * routerinfo. If the return value is equal to -1, then the routerinfo was
  968. * fine, but out-of-date. If the return value is equal to 1, the
  969. * routerinfo was accepted, but we should notify the generator of the
  970. * descriptor using the message *<b>msg</b>.
  971. *
  972. * This function should be called *after*
  973. * routers_update_status_from_networkstatus; subsequenctly, you should call
  974. * router_rebuild_store and control_event_descriptors_changed.
  975. *
  976. * XXXX never replace your own descriptor.
  977. */
  978. int
  979. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  980. int from_cache)
  981. {
  982. int i;
  983. char id_digest[DIGEST_LEN];
  984. int authdir = get_options()->AuthoritativeDir;
  985. int authdir_verified = 0;
  986. tor_assert(msg);
  987. if (!routerlist) {
  988. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  989. routerlist->routers = smartlist_create();
  990. }
  991. crypto_pk_get_digest(router->identity_pkey, id_digest);
  992. if (authdir) {
  993. if (authdir_wants_to_reject_router(router, msg))
  994. return -2;
  995. authdir_verified = router->is_verified;
  996. }
  997. /* If we have a router with this name, and the identity key is the same,
  998. * choose the newer one. If the identity key has changed, drop the router.
  999. */
  1000. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1001. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  1002. if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
  1003. if (router->published_on <= old_router->published_on) {
  1004. /* Same key, but old */
  1005. log_fn(LOG_DEBUG, "Skipping not-new descriptor for router '%s'",
  1006. router->nickname);
  1007. routerinfo_free(router);
  1008. *msg = "Router descriptor was not new.";
  1009. return -1;
  1010. } else {
  1011. /* Same key, new. */
  1012. int unreachable = 0;
  1013. log_fn(LOG_DEBUG, "Replacing entry for router '%s/%s' [%s]",
  1014. router->nickname, old_router->nickname,
  1015. hex_str(id_digest,DIGEST_LEN));
  1016. if (router->addr == old_router->addr &&
  1017. router->or_port == old_router->or_port) {
  1018. /* these carry over when the address and orport are unchanged.*/
  1019. router->last_reachable = old_router->last_reachable;
  1020. router->testing_since = old_router->testing_since;
  1021. router->num_unreachable_notifications =
  1022. old_router->num_unreachable_notifications;
  1023. }
  1024. if (authdir &&
  1025. dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
  1026. if (router->num_unreachable_notifications >= 3) {
  1027. unreachable = 1;
  1028. log_fn(LOG_NOTICE, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
  1029. router->nickname, router->contact_info ? router->contact_info : "",
  1030. router->platform ? router->platform : "");
  1031. } else {
  1032. log_fn(LOG_INFO,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
  1033. router->num_unreachable_notifications++;
  1034. }
  1035. }
  1036. routerinfo_free(old_router);
  1037. smartlist_set(routerlist->routers, i, router);
  1038. if (!from_cache)
  1039. router_append_to_journal(router->signed_descriptor,
  1040. router->signed_descriptor_len);
  1041. directory_set_dirty();
  1042. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  1043. authdir_verified ? "Verified server updated" :
  1044. "Unverified server updated. (Have you sent us your key fingerprint?)";
  1045. return unreachable ? 1 : 0;
  1046. }
  1047. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  1048. /* nicknames match, keys don't. */
  1049. if (router->is_named) {
  1050. /* The new verified router replaces the old one; remove the
  1051. * old one. And carry on to the end of the list, in case
  1052. * there are more old unverified routers with this nickname
  1053. */
  1054. /* mark-for-close connections using the old key, so we can
  1055. * make new ones with the new key.
  1056. */
  1057. connection_t *conn;
  1058. while ((conn = connection_get_by_identity_digest(
  1059. old_router->identity_digest, CONN_TYPE_OR))) {
  1060. log_fn(LOG_INFO,"Closing conn to obsolete router '%s'",
  1061. old_router->nickname);
  1062. connection_mark_for_close(conn);
  1063. }
  1064. routerinfo_free(old_router);
  1065. smartlist_del_keeporder(routerlist->routers, i--);
  1066. } else if (old_router->is_named) {
  1067. /* Can't replace a verified router with an unverified one. */
  1068. log_fn(LOG_DEBUG, "Skipping unverified entry for verified router '%s'",
  1069. router->nickname);
  1070. routerinfo_free(router);
  1071. *msg = "Already have verified router with same nickname and different key.";
  1072. return -2;
  1073. }
  1074. }
  1075. }
  1076. /* We haven't seen a router with this name before. Add it to the end of
  1077. * the list. */
  1078. smartlist_add(routerlist->routers, router);
  1079. if (!from_cache)
  1080. router_append_to_journal(router->signed_descriptor,
  1081. router->signed_descriptor_len);
  1082. directory_set_dirty();
  1083. return 0;
  1084. }
  1085. /** Remove any routers from the routerlist that are more than <b>age</b>
  1086. * seconds old.
  1087. */
  1088. void
  1089. routerlist_remove_old_routers(int age)
  1090. {
  1091. int i;
  1092. time_t cutoff;
  1093. routerinfo_t *router;
  1094. if (!routerlist)
  1095. return;
  1096. cutoff = time(NULL) - age;
  1097. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1098. router = smartlist_get(routerlist->routers, i);
  1099. if (router->published_on <= cutoff) {
  1100. /* Too old. Remove it. */
  1101. log_fn(LOG_INFO,"Forgetting obsolete routerinfo for router '%s'", router->nickname);
  1102. routerinfo_free(router);
  1103. smartlist_del(routerlist->routers, i--);
  1104. }
  1105. }
  1106. }
  1107. /**
  1108. * Code to parse a single router descriptor and insert it into the
  1109. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  1110. * descriptor was well-formed but could not be added; and 1 if the
  1111. * descriptor was added.
  1112. *
  1113. * If we don't add it and <b>msg</b> is not NULL, then assign to
  1114. * *<b>msg</b> a static string describing the reason for refusing the
  1115. * descriptor.
  1116. *
  1117. * This is used only by the controller.
  1118. */
  1119. int
  1120. router_load_single_router(const char *s, const char **msg)
  1121. {
  1122. routerinfo_t *ri;
  1123. tor_assert(msg);
  1124. *msg = NULL;
  1125. if (!(ri = router_parse_entry_from_string(s, NULL))) {
  1126. log_fn(LOG_WARN, "Error parsing router descriptor; dropping.");
  1127. *msg = "Couldn't parse router descriptor.";
  1128. return -1;
  1129. }
  1130. if (router_is_me(ri)) {
  1131. log_fn(LOG_WARN, "Router's identity key matches mine; dropping.");
  1132. *msg = "Router's identity key matches mine.";
  1133. routerinfo_free(ri);
  1134. return 0;
  1135. }
  1136. #if 0
  1137. if (routerlist && routerlist->running_routers) {
  1138. running_routers_t *rr = routerlist->running_routers;
  1139. router_update_status_from_smartlist(ri,
  1140. rr->published_on,
  1141. rr->running_routers);
  1142. }
  1143. #endif
  1144. /* XXXX011 update router status from networkstatus!! */
  1145. if (router_add_to_routerlist(ri, msg, 0)<0) {
  1146. log_fn(LOG_WARN, "Couldn't add router to list: %s Dropping.",
  1147. *msg?*msg:"(No message).");
  1148. /* we've already assigned to *msg now, and ri is already freed */
  1149. return 0;
  1150. } else {
  1151. smartlist_t *changed = smartlist_create();
  1152. smartlist_add(changed, ri);
  1153. control_event_descriptors_changed(changed);
  1154. smartlist_free(changed);
  1155. }
  1156. log_fn(LOG_DEBUG, "Added router to list");
  1157. return 1;
  1158. }
  1159. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  1160. * routers into our directory. If <b>from_cache</b> is false, the routers
  1161. * have come from the network: cache them.
  1162. *
  1163. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1164. * uppercased identity fingerprints. Do not update any router whose
  1165. * fingerprint is not on the list; after updating a router, remove its
  1166. * fingerprint from the list.
  1167. */
  1168. void
  1169. router_load_routers_from_string(const char *s, int from_cache,
  1170. smartlist_t *requested_fingerprints)
  1171. {
  1172. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  1173. char fp[HEX_DIGEST_LEN+1];
  1174. const char *msg;
  1175. router_parse_list_from_string(&s, routers);
  1176. routers_update_status_from_networkstatus(routers);
  1177. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  1178. {
  1179. base16_encode(fp, sizeof(fp), ri->identity_digest, DIGEST_LEN);
  1180. if (requested_fingerprints) {
  1181. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1182. smartlist_string_remove(requested_fingerprints, fp);
  1183. } else {
  1184. char *requested =
  1185. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1186. log_fn(LOG_WARN, "We received a router descriptor with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
  1187. tor_free(requested);
  1188. routerinfo_free(ri);
  1189. continue;
  1190. }
  1191. }
  1192. if (router_add_to_routerlist(ri, &msg, from_cache) >= 0)
  1193. smartlist_add(changed, ri);
  1194. });
  1195. control_event_descriptors_changed(changed);
  1196. router_rebuild_store(0);
  1197. smartlist_free(routers);
  1198. smartlist_free(changed);
  1199. }
  1200. #if 0
  1201. /** Add to the current routerlist each router stored in the
  1202. * signed directory <b>s</b>. If pkey is provided, check the signature
  1203. * against pkey; else check against the pkey of the signing directory
  1204. * server.
  1205. *
  1206. * If <b>dir_is_recent</b> is non-zero, then examine the
  1207. * Recommended-versions line and take appropriate action.
  1208. *
  1209. * If <b>dir_is_cached</b> is non-zero, then we're reading it
  1210. * from the cache so don't bother to re-write it to the cache.
  1211. */
  1212. int
  1213. router_load_routerlist_from_directory(const char *s,
  1214. crypto_pk_env_t *pkey,
  1215. int dir_is_recent,
  1216. int dir_is_cached)
  1217. {
  1218. routerlist_t *new_list = NULL;
  1219. if (router_parse_routerlist_from_directory(s, &new_list, pkey,
  1220. dir_is_recent,
  1221. !dir_is_cached)) {
  1222. log_fn(LOG_WARN, "Couldn't parse directory.");
  1223. return -1;
  1224. }
  1225. if (routerlist) {
  1226. /* Merge the new_list into routerlist, then free new_list. Also
  1227. * keep a list of changed descriptors to inform controllers. */
  1228. smartlist_t *changed = smartlist_create();
  1229. SMARTLIST_FOREACH(new_list->routers, routerinfo_t *, r,
  1230. {
  1231. const char *msg;
  1232. if (router_add_to_routerlist(r,&msg,0)>=0)
  1233. smartlist_add(changed, r);
  1234. });
  1235. smartlist_clear(new_list->routers);
  1236. routerlist->published_on_xx = new_list->published_on_xx;
  1237. routerlist_free(new_list);
  1238. control_event_descriptors_changed(changed);
  1239. smartlist_free(changed);
  1240. } else {
  1241. routerlist = new_list;
  1242. control_event_descriptors_changed(routerlist->routers);
  1243. }
  1244. router_normalize_routerlist(routerlist);
  1245. return 0;
  1246. }
  1247. #endif
  1248. /** Helper: return a newly allocated string containing the name of the filename
  1249. * where we plan to cache <b>ns</b>. */
  1250. static char *
  1251. networkstatus_get_cache_filename(const networkstatus_t *ns)
  1252. {
  1253. const char *datadir = get_options()->DataDirectory;
  1254. size_t len = strlen(datadir)+64;
  1255. char fp[HEX_DIGEST_LEN+1];
  1256. char *fn = tor_malloc(len+1);
  1257. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1258. tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
  1259. return fn;
  1260. }
  1261. /** Helper for smartlist_sort: Compare two networkstatus objects by
  1262. * publication date. */
  1263. static int
  1264. _compare_networkstatus_published_on(const void **_a, const void **_b)
  1265. {
  1266. const networkstatus_t *a = *_a, *b = *_b;
  1267. if (a->published_on < b->published_on)
  1268. return -1;
  1269. else if (a->published_on > b->published_on)
  1270. return 1;
  1271. else
  1272. return 0;
  1273. }
  1274. /** How far in the future do we allow a network-status to get before removing
  1275. * it? (seconds) */
  1276. #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
  1277. /** Given a string <b>s</b> containing a network status that we received at
  1278. * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
  1279. * store it, and put it into our cache is necessary.
  1280. *
  1281. * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
  1282. * own networkstatus_t (if we're a directory server).
  1283. *
  1284. * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
  1285. * cache.
  1286. *
  1287. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1288. * uppercased identity fingerprints. Do not update any networkstatus whose
  1289. * fingerprint is not on the list; after updating a networkstatus, remove its
  1290. * fingerprint from the list.
  1291. *
  1292. o * Return 0 on success, -1 on failure.
  1293. */
  1294. int
  1295. router_set_networkstatus(const char *s, time_t arrived_at,
  1296. networkstatus_source_t source, smartlist_t *requested_fingerprints)
  1297. {
  1298. networkstatus_t *ns;
  1299. int i, found;
  1300. time_t now;
  1301. int skewed = 0;
  1302. trusted_dir_server_t *trusted_dir;
  1303. char fp[HEX_DIGEST_LEN+1];
  1304. char published[ISO_TIME_LEN+1];
  1305. ns = networkstatus_parse_from_string(s);
  1306. if (!ns) {
  1307. log_fn(LOG_WARN, "Couldn't parse network status.");
  1308. return -1;
  1309. }
  1310. if (!(trusted_dir=router_get_trusteddirserver_by_digest(ns->identity_digest))) {
  1311. log_fn(LOG_INFO, "Network status was signed, but not by an authoritative directory we recognize.");
  1312. networkstatus_free(ns);
  1313. return -1;
  1314. }
  1315. now = time(NULL);
  1316. if (arrived_at > now)
  1317. arrived_at = now;
  1318. ns->received_on = arrived_at;
  1319. format_iso_time(published, ns->published_on);
  1320. if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
  1321. log_fn(LOG_WARN, "Network status was published in the future (%s GMT). Somebody is skewed here: check your clock. Not caching.", published);
  1322. skewed = 1;
  1323. }
  1324. if (!networkstatus_list)
  1325. networkstatus_list = smartlist_create();
  1326. if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
  1327. /* Don't replace our own networkstatus when we get it from somebody else. */
  1328. networkstatus_free(ns);
  1329. return 0;
  1330. }
  1331. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1332. if (requested_fingerprints) {
  1333. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1334. smartlist_string_remove(requested_fingerprints, fp);
  1335. } else {
  1336. char *requested = smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1337. log_fn(LOG_WARN, "We received a network status with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
  1338. tor_free(requested);
  1339. return 0;
  1340. }
  1341. }
  1342. if (source != NS_FROM_CACHE)
  1343. trusted_dir->n_networkstatus_failures = 0;
  1344. found = 0;
  1345. for (i=0; i < smartlist_len(networkstatus_list); ++i) {
  1346. networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
  1347. if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
  1348. if (!memcmp(old_ns->networkstatus_digest,
  1349. ns->networkstatus_digest, DIGEST_LEN)) {
  1350. /* Same one we had before. */
  1351. networkstatus_free(ns);
  1352. log_fn(LOG_NOTICE,
  1353. "Dropping network-status from %s:%d (published %s); already have it.",
  1354. trusted_dir->address, trusted_dir->dir_port, published);
  1355. if (old_ns->received_on < arrived_at) {
  1356. if (source != NS_FROM_CACHE) {
  1357. char *fn = networkstatus_get_cache_filename(old_ns);
  1358. /* We use mtime to tell when it arrived, so update that. */
  1359. touch_file(fn);
  1360. tor_free(fn);
  1361. }
  1362. old_ns->received_on = arrived_at;
  1363. }
  1364. return 0;
  1365. } else if (old_ns->published_on >= ns->published_on) {
  1366. char old_published[ISO_TIME_LEN+1];
  1367. format_iso_time(old_published, old_ns->published_on);
  1368. log_fn(LOG_NOTICE,
  1369. "Dropping network-status from %s:%d (published %s);"
  1370. " we have a newer one (published %s) for this authority.",
  1371. trusted_dir->address, trusted_dir->dir_port, published,
  1372. old_published);
  1373. networkstatus_free(ns);
  1374. return 0;
  1375. } else {
  1376. networkstatus_free(old_ns);
  1377. smartlist_set(networkstatus_list, i, ns);
  1378. found = 1;
  1379. break;
  1380. }
  1381. }
  1382. }
  1383. if (!found)
  1384. smartlist_add(networkstatus_list, ns);
  1385. /*XXXX011 downgrade to INFO NM */
  1386. log_fn(LOG_NOTICE, "Setting networkstatus %s %s:%d (published %s)",
  1387. source == NS_FROM_CACHE?"cached from":
  1388. (source==NS_FROM_DIR?"downloaded from":"generated for"),
  1389. trusted_dir->address, trusted_dir->dir_port, published);
  1390. networkstatus_list_has_changed = 1;
  1391. smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
  1392. if (source != NS_FROM_CACHE && !skewed) {
  1393. char *fn = networkstatus_get_cache_filename(ns);
  1394. if (write_str_to_file(fn, s, 0)<0) {
  1395. log_fn(LOG_NOTICE, "Couldn't write cached network status to \"%s\"", fn);
  1396. }
  1397. tor_free(fn);
  1398. }
  1399. if (get_options()->DirPort && !skewed)
  1400. dirserv_set_cached_networkstatus_v2(s, fp, ns->published_on);
  1401. return 0;
  1402. }
  1403. /** How old do we allow a network-status to get before removing it completely? */
  1404. #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
  1405. /** Remove all very-old network_status_t objects from memory and from the
  1406. * disk cache. */
  1407. void
  1408. networkstatus_list_clean(time_t now)
  1409. {
  1410. int i;
  1411. if (!networkstatus_list)
  1412. return;
  1413. for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
  1414. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  1415. char *fname = NULL;;
  1416. if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
  1417. continue;
  1418. /* Okay, this one is too old. Remove it from the list, and delete it
  1419. * from the cache. */
  1420. smartlist_del(networkstatus_list, i--);
  1421. fname = networkstatus_get_cache_filename(ns);
  1422. if (file_status(fname) == FN_FILE) {
  1423. log_fn(LOG_INFO, "Removing too-old networkstatus in %s", fname);
  1424. unlink(fname);
  1425. }
  1426. tor_free(fname);
  1427. if (get_options()->DirPort) {
  1428. char fp[HEX_DIGEST_LEN+1];
  1429. base16_encode(fp, sizeof(fp), ns->identity_digest, DIGEST_LEN);
  1430. dirserv_set_cached_networkstatus_v2(NULL, fp, 0);
  1431. }
  1432. networkstatus_free(ns);
  1433. }
  1434. }
  1435. /** Helper for bsearching a list of routerstatus_t pointers.*/
  1436. static int
  1437. _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
  1438. {
  1439. const char *key = _key;
  1440. const routerstatus_t *rs = *_member;
  1441. return memcmp(key, rs->identity_digest, DIGEST_LEN);
  1442. }
  1443. /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
  1444. * NULL if none was found. */
  1445. static routerstatus_t *
  1446. networkstatus_find_entry(networkstatus_t *ns, const char *digest)
  1447. {
  1448. return smartlist_bsearch(ns->entries, digest,
  1449. _compare_digest_to_routerstatus_entry);
  1450. }
  1451. /* XXXX These should be configurable, perhaps? NM */
  1452. #define AUTHORITY_NS_CACHE_INTERVAL 10*60
  1453. #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
  1454. /** We are a directory server, and so cache network_status documents.
  1455. * Initiate downloads as needed to update them. For authorities, this means
  1456. * asking each trusted directory for its network-status. For caches, this means
  1457. * asking a random authority for all network-statuses.
  1458. */
  1459. void
  1460. update_networkstatus_cache_downloads(time_t now)
  1461. {
  1462. static time_t last_downloaded = 0;
  1463. int authority = authdir_mode(get_options());
  1464. int interval =
  1465. authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
  1466. /*XXXXX NM we should retry on failure. */
  1467. if (last_downloaded + interval >= now)
  1468. return;
  1469. if (!trusted_dir_servers)
  1470. return;
  1471. last_downloaded = now;
  1472. if (authority) {
  1473. /* An authority launches a separate connection for everybody. */
  1474. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1475. {
  1476. char resource[HEX_DIGEST_LEN+6];
  1477. if (router_digest_is_me(ds->digest))
  1478. continue;
  1479. if (connection_get_by_type_addr_port_purpose(
  1480. CONN_TYPE_DIR, ds->addr, ds->dir_port,
  1481. DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
  1482. /* We are already fetching this one. */
  1483. continue;
  1484. }
  1485. strlcpy(resource, "fp/", sizeof(resource));
  1486. base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
  1487. strlcat(resource, ".z", sizeof(resource));
  1488. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,resource,1);
  1489. });
  1490. } else {
  1491. /* A non-authority cache launches one connection to a random authority. */
  1492. /* (Check whether we're currently fetching network-status objects.) */
  1493. if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
  1494. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  1495. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
  1496. }
  1497. }
  1498. /*XXXX Should these be configurable? NM*/
  1499. /** How old (in seconds) can a network-status be before we try replacing it? */
  1500. #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
  1501. /** How long (in seconds) does a client wait after getting a network status
  1502. * before downloading the next in sequence? */
  1503. #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
  1504. /* How many times do we allow a networkstatus download to fail before we
  1505. * assume that the authority isn't publishing? */
  1506. #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
  1507. /** We are not a directory cache or authority. Update our network-status list
  1508. * by launching a new directory fetch for enough network-status documents "as
  1509. * necessary". See function comments for implementation details.
  1510. */
  1511. void
  1512. update_networkstatus_client_downloads(time_t now)
  1513. {
  1514. int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
  1515. int most_recent_idx = -1;
  1516. trusted_dir_server_t *most_recent = NULL;
  1517. time_t most_recent_received = 0;
  1518. char *resource, *cp;
  1519. size_t resource_len;
  1520. if (connection_get_by_type_purpose(CONN_TYPE_DIR,
  1521. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  1522. return;
  1523. /* This is a little tricky. We want to download enough network-status
  1524. * objects so that we have at least half of them under
  1525. * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
  1526. * *one* if the most recent one's publication time is under
  1527. * NETWORKSTATUS_CLIENT_DL_INTERVAL.
  1528. */
  1529. if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
  1530. return;
  1531. n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
  1532. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1533. {
  1534. networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
  1535. if (!ns)
  1536. continue;
  1537. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  1538. --n_running_dirservers;
  1539. continue;
  1540. }
  1541. if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
  1542. ++n_live;
  1543. if (!most_recent || ns->received_on > most_recent_received) {
  1544. most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
  1545. most_recent = ds;
  1546. most_recent_received = ns->received_on;
  1547. }
  1548. });
  1549. /* Download enough so we have at least half live, but no more than all the
  1550. * trusted dirservers we know.
  1551. */
  1552. if (n_live < (n_dirservers/2)+1)
  1553. needed = (n_dirservers/2)+1-n_live;
  1554. if (needed > n_running_dirservers)
  1555. needed = n_running_dirservers;
  1556. if (needed)
  1557. /* XXXX001 Downgrade to info NM */
  1558. log_fn(LOG_NOTICE, "For %d/%d running directory servers, we have %d live"
  1559. " network-status documents. Downloading %d.",
  1560. n_running_dirservers, n_dirservers, n_live, needed);
  1561. /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
  1562. if (n_running_dirservers &&
  1563. most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL && needed < 1) {
  1564. const char *addr = most_recent?most_recent->address:"nobody";
  1565. int port = most_recent?most_recent->dir_port:0;
  1566. log_fn(LOG_NOTICE, "Our most recent network-status document (from %s:%d) "
  1567. "is %d seconds old; downloading another.",
  1568. addr, port, (int)(now-most_recent_received));
  1569. needed = 1;
  1570. }
  1571. if (!needed)
  1572. return;
  1573. /* If no networkstatus was found, choose a dirserver at random as "most
  1574. * recent". */
  1575. if (most_recent_idx<0)
  1576. most_recent_idx = crypto_pseudo_rand_int(n_dirservers);
  1577. /* Build a request string for all the resources we want. */
  1578. resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
  1579. resource = tor_malloc(resource_len);
  1580. memcpy(resource, "fp/", 3);
  1581. cp = resource+3;
  1582. for (i = most_recent_idx+1; needed; ++i) {
  1583. trusted_dir_server_t *ds;
  1584. if (i >= n_dirservers)
  1585. i = 0;
  1586. ds = smartlist_get(trusted_dir_servers, i);
  1587. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
  1588. continue;
  1589. base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
  1590. cp += HEX_DIGEST_LEN;
  1591. --needed;
  1592. if (needed)
  1593. *cp++ = '+';
  1594. }
  1595. memcpy(cp, ".z", 3);
  1596. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
  1597. tor_free(resource);
  1598. }
  1599. /** Decide whether a given addr:port is definitely accepted,
  1600. * definitely rejected, probably accepted, or probably rejected by a
  1601. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  1602. * target address. If <b>port</b> is 0, we don't know the port of the
  1603. * target address.
  1604. *
  1605. * For now, the algorithm is pretty simple: we look for definite and
  1606. * uncertain matches. The first definite match is what we guess; if
  1607. * it was preceded by no uncertain matches of the opposite policy,
  1608. * then the guess is definite; otherwise it is probable. (If we
  1609. * have a known addr and port, all matches are definite; if we have an
  1610. * unknown addr/port, any address/port ranges other than "all" are
  1611. * uncertain.)
  1612. *
  1613. * We could do better by assuming that some ranges never match typical
  1614. * addresses (127.0.0.1, and so on). But we'll try this for now.
  1615. */
  1616. addr_policy_result_t
  1617. router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  1618. addr_policy_t *policy)
  1619. {
  1620. int maybe_reject = 0;
  1621. int maybe_accept = 0;
  1622. int match = 0;
  1623. int maybe = 0;
  1624. addr_policy_t *tmpe;
  1625. for (tmpe=policy; tmpe; tmpe=tmpe->next) {
  1626. maybe = 0;
  1627. if (!addr) {
  1628. /* Address is unknown. */
  1629. if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
  1630. (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
  1631. /* The port definitely matches. */
  1632. if (tmpe->msk == 0) {
  1633. match = 1;
  1634. } else {
  1635. maybe = 1;
  1636. }
  1637. } else if (!port) {
  1638. /* The port maybe matches. */
  1639. maybe = 1;
  1640. }
  1641. } else {
  1642. /* Address is known */
  1643. if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
  1644. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  1645. /* Exact match for the policy */
  1646. match = 1;
  1647. } else if (!port) {
  1648. maybe = 1;
  1649. }
  1650. }
  1651. }
  1652. if (maybe) {
  1653. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1654. maybe_reject = 1;
  1655. else
  1656. maybe_accept = 1;
  1657. }
  1658. if (match) {
  1659. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1660. /* If we already hit a clause that might trigger a 'reject', than we
  1661. * can't be sure of this certain 'accept'.*/
  1662. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1663. } else {
  1664. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
  1665. }
  1666. }
  1667. }
  1668. /* accept all by default. */
  1669. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1670. }
  1671. /** Return 1 if all running sufficiently-stable routers will reject
  1672. * addr:port, return 0 if any might accept it. */
  1673. int
  1674. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  1675. int need_uptime)
  1676. {
  1677. addr_policy_result_t r;
  1678. if (!routerlist) return 1;
  1679. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1680. {
  1681. if (router->is_running &&
  1682. !router_is_unreliable(router, need_uptime, 0)) {
  1683. r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
  1684. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1685. return 0; /* this one could be ok. good enough. */
  1686. }
  1687. });
  1688. return 1; /* all will reject. */
  1689. }
  1690. /**
  1691. * If <b>policy</b> implicitly allows connections to any port in the
  1692. * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
  1693. * part of the policy that allows it, and return 1. Else return 0.
  1694. *
  1695. * A policy allows an IP:Port combination <em>implicitly</em> if
  1696. * it is included in a *: pattern, or in a fallback pattern.
  1697. */
  1698. static int
  1699. policy_includes_addr_mask_implicitly(addr_policy_t *policy,
  1700. uint32_t addr, uint32_t mask,
  1701. addr_policy_t **policy_out)
  1702. {
  1703. uint32_t addr2;
  1704. tor_assert(policy_out);
  1705. addr &= mask;
  1706. addr2 = addr | ~mask;
  1707. for (; policy; policy=policy->next) {
  1708. /* Does this policy cover all of the address range we're looking at? */
  1709. /* Boolean logic time: range X is contained in range Y if, for
  1710. * each bit B, all possible values of B in X are values of B in Y.
  1711. * In "addr", we have every fixed bit set to its value, and every
  1712. * free bit set to 0. In "addr2", we have every fixed bit set to
  1713. * its value, and every free bit set to 1. So if addr and addr2 are
  1714. * both in the policy, the range is covered by the policy.
  1715. */
  1716. uint32_t p_addr = policy->addr & policy->msk;
  1717. if (p_addr == (addr & policy->msk) &&
  1718. p_addr == (addr2 & policy->msk) &&
  1719. (policy->prt_min <= 1 && policy->prt_max == 65535)) {
  1720. return 0;
  1721. }
  1722. /* Does this policy cover some of the address range we're looking at? */
  1723. /* Boolean logic time: range X and range Y intersect if there is
  1724. * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
  1725. * This is FALSE iff there is some bit b where Xmask == yMask == 1
  1726. * and Xaddr != Yaddr. So if X intersects with Y iff at every
  1727. * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
  1728. * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
  1729. */
  1730. if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
  1731. policy->policy_type == ADDR_POLICY_ACCEPT) {
  1732. *policy_out = policy;
  1733. return 1;
  1734. }
  1735. }
  1736. *policy_out = NULL;
  1737. return 1;
  1738. }
  1739. /** If <b>policy</b> implicitly allows connections to any port on
  1740. * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
  1741. * true. Else return false.
  1742. **/
  1743. int
  1744. exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
  1745. int warn)
  1746. {
  1747. addr_policy_t *p;
  1748. int r=0,i;
  1749. static struct {
  1750. uint32_t addr; uint32_t mask; const char *network;
  1751. } private_networks[] = {
  1752. { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
  1753. { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
  1754. { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
  1755. { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
  1756. { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
  1757. { 0,0,NULL},
  1758. };
  1759. for (i=0; private_networks[i].addr; ++i) {
  1760. p = NULL;
  1761. /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
  1762. if (policy_includes_addr_mask_implicitly(
  1763. policy, private_networks[i].addr, private_networks[i].mask, &p)) {
  1764. if (warn)
  1765. log_fn(LOG_WARN, "Exit policy %s implicitly accepts %s",
  1766. p?p->string:"(default)",
  1767. private_networks[i].network);
  1768. r = 1;
  1769. }
  1770. }
  1771. return r;
  1772. }
  1773. /** Return true iff <b>router</b> does not permit exit streams.
  1774. */
  1775. int
  1776. router_exit_policy_rejects_all(routerinfo_t *router)
  1777. {
  1778. return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
  1779. == ADDR_POLICY_REJECTED;
  1780. }
  1781. #if 0
  1782. /** Release all space held in <b>rr</b>. */
  1783. void
  1784. running_routers_free(running_routers_t *rr)
  1785. {
  1786. if (!rr)
  1787. return;
  1788. if (rr->running_routers) {
  1789. SMARTLIST_FOREACH(rr->running_routers, char *, s, tor_free(s));
  1790. smartlist_free(rr->running_routers);
  1791. }
  1792. tor_free(rr);
  1793. }
  1794. /** Update the running/not-running status of every router in <b>list</b>, based
  1795. * on the contents of <b>rr</b>. */
  1796. static void
  1797. routerlist_update_from_runningrouters(routerlist_t *list,
  1798. running_routers_t *rr)
  1799. {
  1800. routerinfo_t *me = router_get_my_routerinfo();
  1801. smartlist_t *all_routers;
  1802. if (!list)
  1803. return;
  1804. if (list->published_on >= rr->published_on)
  1805. return;
  1806. if (list->running_routers_updated_on >= rr->published_on)
  1807. return;
  1808. all_routers = smartlist_create();
  1809. if (me) /* learn if the dirservers think I'm verified */
  1810. smartlist_add(all_routers, me);
  1811. smartlist_add_all(all_routers,list->routers);
  1812. SMARTLIST_FOREACH(rr->running_routers, const char *, cp,
  1813. routers_update_status_from_entry(all_routers, rr->published_on,
  1814. cp));
  1815. smartlist_free(all_routers);
  1816. list->running_routers_updated_on = rr->published_on;
  1817. }
  1818. /** We've just got a running routers list in <b>rr</b>; update the
  1819. * status of the routers in <b>list</b>, and cache <b>rr</b> */
  1820. void
  1821. routerlist_set_runningrouters(routerlist_t *list, running_routers_t *rr)
  1822. {
  1823. routerlist_update_from_runningrouters(list,rr);
  1824. if (list->running_routers != rr) {
  1825. running_routers_free(list->running_routers);
  1826. list->running_routers = rr;
  1827. }
  1828. }
  1829. /** Update the is_running and is_verified fields of the router <b>router</b>,
  1830. * based in its status in the list of strings stored in <b>running_list</b>.
  1831. * All entries in <b>running_list</b> follow one of these formats:
  1832. * <ol><li> <b>nickname</b> -- router is running and verified.
  1833. * (running-routers format)
  1834. * <li> !<b>nickname</b> -- router is not-running and verified.
  1835. * (running-routers format)
  1836. * <li> <b>nickname</b>=$<b>hexdigest</b> -- router is running and
  1837. * verified. (router-status format)
  1838. * (router-status format)
  1839. * <li> !<b>nickname</b>=$<b>hexdigest</b> -- router is running and
  1840. * verified. (router-status format)
  1841. * <li> !<b>nickname</b> -- router is not-running and verified.
  1842. * <li> $<b>hexdigest</b> -- router is running and unverified.
  1843. * <li> !$<b>hexdigest</b> -- router is not-running and unverified.
  1844. * </ol>
  1845. *
  1846. * Return 1 if we found router in running_list, else return 0.
  1847. */
  1848. int
  1849. routers_update_status_from_entry(smartlist_t *routers,
  1850. time_t list_time,
  1851. const char *s)
  1852. {
  1853. int authdir = get_options()->AuthoritativeDir;
  1854. int is_running = 1;
  1855. int is_verified = 0, is_named = 0;
  1856. int hex_digest_set = 0;
  1857. char nickname[MAX_NICKNAME_LEN+1];
  1858. char hexdigest[HEX_DIGEST_LEN+1];
  1859. char digest[DIGEST_LEN];
  1860. const char *cp, *end;
  1861. /* First, parse the entry. */
  1862. cp = s;
  1863. if (*cp == '!') {
  1864. is_running = 0;
  1865. ++cp;
  1866. }
  1867. if (*cp != '$') {
  1868. /* It starts with a non-dollar character; that's a nickname. The nickname
  1869. * entry will either extend to a NUL (old running-routers format) or to an
  1870. * equals sign (new router-status format). */
  1871. is_verified = 1;
  1872. is_named = 1;
  1873. end = strchr(cp, '=');
  1874. if (!end)
  1875. end = strchr(cp,'\0');
  1876. tor_assert(end);
  1877. /* 'end' now points on character beyond the end of the nickname */
  1878. if (end == cp || end-cp > MAX_NICKNAME_LEN) {
  1879. log_fn(LOG_WARN, "Bad nickname length (%d) in router status entry (%s)",
  1880. (int)(end-cp), s);
  1881. return -1;
  1882. }
  1883. memcpy(nickname, cp, end-cp);
  1884. nickname[end-cp]='\0';
  1885. if (!is_legal_nickname(nickname)) {
  1886. log_fn(LOG_WARN, "Bad nickname (%s) in router status entry (%s)",
  1887. nickname, s);
  1888. return -1;
  1889. }
  1890. cp = end;
  1891. if (*cp == '=')
  1892. ++cp;
  1893. }
  1894. /* 'end' now points to the start of a hex digest, or EOS. */
  1895. /* Parse the hexdigest portion of the status. */
  1896. if (*cp == '$') {
  1897. hex_digest_set = 1;
  1898. ++cp;
  1899. if (strlen(cp) != HEX_DIGEST_LEN) {
  1900. log_fn(LOG_WARN, "Bad length (%d) on digest in router status entry (%s)",
  1901. (int)strlen(cp), s);
  1902. return -1;
  1903. }
  1904. strlcpy(hexdigest, cp, sizeof(hexdigest));
  1905. if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0) {
  1906. log_fn(LOG_WARN, "Invalid digest in router status entry (%s)", s);
  1907. return -1;
  1908. }
  1909. }
  1910. /* Make sure that the entry was in the right format. */
  1911. if (!hex_digest_set) {
  1912. log_fn(LOG_WARN, "Invalid syntax for router-status member (%s)", s);
  1913. return -1;
  1914. }
  1915. /* Okay, we're done parsing. For all routers that match, update their status.
  1916. */
  1917. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1918. {
  1919. int nickname_matches = is_verified && !strcasecmp(r->nickname, nickname);
  1920. int digest_matches = !memcmp(digest, r->identity_digest, DIGEST_LEN);
  1921. if (!authdir) {
  1922. /* If we're not an authoritative directory, update verified status.
  1923. */
  1924. if (nickname_matches && digest_matches)
  1925. r->is_verified = r->is_named = 1;
  1926. else if (digest_matches)
  1927. r->is_verified = r->is_named = 0;
  1928. }
  1929. if (digest_matches)
  1930. if (r->status_set_at < list_time) {
  1931. if (!authdir || is_running)
  1932. /* If we're an authoritative directory, only believe that servers
  1933. * are down when we hear it ourselves. Otherwise, believe
  1934. * what we're told.
  1935. */
  1936. r->is_running = is_running;
  1937. r->status_set_at = time(NULL);
  1938. }
  1939. });
  1940. return 0;
  1941. }
  1942. /** As router_update_status_from_entry, but consider all entries in
  1943. * running_list. */
  1944. int
  1945. router_update_status_from_smartlist(routerinfo_t *router,
  1946. time_t list_time,
  1947. smartlist_t *running_list)
  1948. {
  1949. smartlist_t *rl;
  1950. rl = smartlist_create();
  1951. smartlist_add(rl,router);
  1952. SMARTLIST_FOREACH(running_list, const char *, cp,
  1953. routers_update_status_from_entry(rl,list_time,cp));
  1954. smartlist_free(rl);
  1955. return 0;
  1956. }
  1957. #endif
  1958. /** Add to the list of authorized directory servers one at
  1959. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  1960. * <b>address</b> is NULL, add ourself. */
  1961. void
  1962. add_trusted_dir_server(const char *address, uint16_t port, const char *digest,
  1963. int supports_v1)
  1964. {
  1965. trusted_dir_server_t *ent;
  1966. uint32_t a;
  1967. char *hostname = NULL;
  1968. if (!trusted_dir_servers)
  1969. trusted_dir_servers = smartlist_create();
  1970. if (!address) { /* The address is us; we should guess. */
  1971. if (resolve_my_address(get_options(), &a, &hostname) < 0) {
  1972. log_fn(LOG_WARN, "Couldn't find a suitable address. Returning.");
  1973. return;
  1974. }
  1975. } else {
  1976. if (tor_lookup_hostname(address, &a)) {
  1977. log_fn(LOG_WARN, "Unable to lookup address for directory server at %s",
  1978. address);
  1979. return;
  1980. }
  1981. hostname = tor_strdup(address);
  1982. a = ntohl(a);
  1983. }
  1984. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  1985. ent->address = hostname;
  1986. ent->addr = a;
  1987. ent->dir_port = port;
  1988. ent->is_running = 1;
  1989. ent->supports_v1_protocol = supports_v1;
  1990. memcpy(ent->digest, digest, DIGEST_LEN);
  1991. smartlist_add(trusted_dir_servers, ent);
  1992. }
  1993. /** Remove all members from the list of trusted dir servers. */
  1994. void
  1995. clear_trusted_dir_servers(void)
  1996. {
  1997. if (trusted_dir_servers) {
  1998. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1999. { tor_free(ent->address); tor_free(ent); });
  2000. smartlist_clear(trusted_dir_servers);
  2001. } else {
  2002. trusted_dir_servers = smartlist_create();
  2003. }
  2004. }
  2005. /** Return the network status with a given identity digest. */
  2006. networkstatus_t *
  2007. networkstatus_get_by_digest(const char *digest)
  2008. {
  2009. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2010. {
  2011. if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
  2012. return ns;
  2013. });
  2014. return NULL;
  2015. }
  2016. /** If the network-status list has changed since the last time we called this
  2017. * function, update the status of every router from the network-status list.
  2018. */
  2019. void
  2020. routers_update_all_from_networkstatus(void)
  2021. {
  2022. static int have_warned_about_unverified_status = 0;
  2023. routerinfo_t *me;
  2024. if (!routerlist || !networkstatus_list || !networkstatus_list_has_changed)
  2025. return;
  2026. routers_update_status_from_networkstatus(routerlist->routers);
  2027. me = router_get_my_routerinfo();
  2028. if (me) {
  2029. /* We could be more sophisticated about this whole business. How many
  2030. * dirservers list us as named, valid, etc. */
  2031. smartlist_t *lst = smartlist_create();
  2032. smartlist_add(lst, me);
  2033. routers_update_status_from_networkstatus(lst);
  2034. if (me->is_verified == 0) {
  2035. log_fn(LOG_WARN, "Many directory servers list us as unverified. Please consider sending your identity fingerprint to the tor-ops.");
  2036. have_warned_about_unverified_status = 1;
  2037. } else if (me->is_named == 0) {
  2038. log_fn(LOG_WARN, "Many directory servers list us as unnamed. Please consider sending your identity fingerprint to the tor-ops.");
  2039. have_warned_about_unverified_status = 1;
  2040. }
  2041. }
  2042. helper_nodes_set_status_from_directory();
  2043. update_router_descriptor_downloads(time(NULL));
  2044. networkstatus_list_has_changed = 0;
  2045. }
  2046. /** Allow any network-status newer than this to influence our view of who's
  2047. * running. */
  2048. #define DEFAULT_RUNNING_INTERVAL 60*60
  2049. /** If possible, always allow at least this many network-statuses to influence
  2050. * our view of who's running. */
  2051. #define MIN_TO_INFLUENCE_RUNNING 3
  2052. /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
  2053. * is_named, is_verified, and is_running fields according to our current
  2054. * networkstatus_t documents. */
  2055. void
  2056. routers_update_status_from_networkstatus(smartlist_t *routers)
  2057. {
  2058. int n_trusted, n_statuses, n_valid, n_naming, n_named, n_running, n_listing,
  2059. n_recent;
  2060. int i;
  2061. time_t now = time(NULL);
  2062. trusted_dir_server_t *ds;
  2063. or_options_t *options = get_options();
  2064. int authdir = options->AuthoritativeDir;
  2065. if (authdir && options->NamingAuthoritativeDir) {
  2066. /* A completely authoritative directory should never believer someone else
  2067. * about a server's status. */
  2068. return;
  2069. }
  2070. if (!networkstatus_list)
  2071. networkstatus_list = smartlist_create();
  2072. if (!trusted_dir_servers)
  2073. trusted_dir_servers = smartlist_create();
  2074. n_trusted = smartlist_len(trusted_dir_servers);
  2075. n_statuses = smartlist_len(networkstatus_list);
  2076. if (n_statuses < (n_trusted/2)+1) {
  2077. /* Not enough statuses to adjust status. */
  2078. return;
  2079. }
  2080. if (n_statuses < MIN_TO_INFLUENCE_RUNNING) {
  2081. n_recent = n_statuses;
  2082. } else {
  2083. n_recent = 0;
  2084. for (i=smartlist_len(networkstatus_list)-1; i >= 0; --i) {
  2085. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  2086. if (ns->published_on + DEFAULT_RUNNING_INTERVAL < now)
  2087. break;
  2088. ++n_recent;
  2089. }
  2090. if (n_recent < MIN_TO_INFLUENCE_RUNNING) {
  2091. n_recent = MIN_TO_INFLUENCE_RUNNING;
  2092. }
  2093. }
  2094. SMARTLIST_FOREACH(routers, routerinfo_t *, router,
  2095. {
  2096. ds = router_get_trusteddirserver_by_digest(router->identity_digest);
  2097. n_listing = n_valid = n_naming = n_named = n_running = 0;
  2098. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2099. {
  2100. routerstatus_t *rs = networkstatus_find_entry(ns, router->identity_digest);
  2101. if (ns->binds_names)
  2102. ++n_naming;
  2103. if (!rs)
  2104. continue;
  2105. ++n_listing;
  2106. if (rs->is_named && !strcasecmp(rs->nickname, router->nickname))
  2107. ++n_named;
  2108. if (rs->is_valid)
  2109. ++n_valid;
  2110. if (ns_sl_idx >= smartlist_len(networkstatus_list)-n_recent) {
  2111. if (rs->is_running)
  2112. ++n_running;
  2113. }
  2114. });
  2115. log_fn(LOG_DEBUG, "Router '%s' at %s:%d is listed by %d/%d directories, "
  2116. "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
  2117. "think it's running.",
  2118. router->nickname, router->address, router->or_port,
  2119. n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
  2120. n_running, n_recent);
  2121. router->is_named = (n_named > n_naming/2);
  2122. if (authdir) {
  2123. /* We're a non-naming authdir; don't believe others. */
  2124. router->is_verified = (n_valid > n_statuses/2);
  2125. router->is_running = (n_running > n_recent/2);
  2126. if (router->is_running && ds) {
  2127. /* XXXX001 NM Hm. What about authorities? When do they reset
  2128. * n_networkstatus_failures? */
  2129. ds->n_networkstatus_failures = 0;
  2130. }
  2131. }
  2132. });
  2133. }
  2134. /** Return new list of ID fingerprints for superseded routers. A router is
  2135. * superseded if any network-status has a router with a different digest
  2136. * published more recently, or it it is listed in the network-status but not
  2137. * in the router list.
  2138. */
  2139. static smartlist_t *
  2140. router_list_downloadable(void)
  2141. {
  2142. smartlist_t *superseded = smartlist_create();
  2143. strmap_t *most_recent = NULL;
  2144. char fp[HEX_DIGEST_LEN+1];
  2145. routerstatus_t *rs_old;
  2146. strmap_iter_t *iter;
  2147. if (!networkstatus_list)
  2148. return superseded;
  2149. /* Build a map from fingerprint to most recent routerstatus_t. If this
  2150. * becomes inefficient, we can build most_recent lazily when a new
  2151. * networkstatus_t shows up.*/
  2152. most_recent = strmap_new();
  2153. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2154. {
  2155. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  2156. {
  2157. base16_encode(fp, sizeof(fp), rs->identity_digest, DIGEST_LEN);
  2158. rs_old = strmap_get(most_recent, fp);
  2159. if (!rs_old || rs_old->published_on < rs->published_on) {
  2160. strmap_set(most_recent, fp, rs);
  2161. }
  2162. });
  2163. });
  2164. /* Compare each router to the most recent routerstatus. */
  2165. if (routerlist) {
  2166. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  2167. {
  2168. routerstatus_t *rs;
  2169. base16_encode(fp, sizeof(fp), ri->identity_digest, DIGEST_LEN);
  2170. rs = strmap_get(most_recent, fp);
  2171. if (!rs)
  2172. continue;
  2173. if (memcmp(ri->signed_descriptor_digest,rs->descriptor_digest,DIGEST_LEN)
  2174. && rs->published_on > ri->published_on) {
  2175. char *d = tor_malloc(HEX_DIGEST_LEN+1);
  2176. log_fn(LOG_INFO, "A networkstatus implies '%s' is out-of-date.",
  2177. ri->nickname);
  2178. base16_encode(d, HEX_DIGEST_LEN+1, ri->identity_digest, DIGEST_LEN);
  2179. smartlist_add(superseded, d);
  2180. break;
  2181. }
  2182. strmap_remove(most_recent, fp);
  2183. });
  2184. }
  2185. /* Anything left over, we don't even know about yet. */
  2186. for (iter = strmap_iter_init(most_recent); !strmap_iter_done(iter);
  2187. iter = strmap_iter_next(most_recent, iter)) {
  2188. const char *key;
  2189. void *val;
  2190. strmap_iter_get(iter, &key, &val);
  2191. smartlist_add(superseded, tor_strdup(key));
  2192. }
  2193. strmap_free(most_recent, NULL);
  2194. return superseded;
  2195. }
  2196. /** Initiate new router downloads as needed.
  2197. *
  2198. * We only allow one router descriptor download at a time.
  2199. * If we have less than two network-status documents, we ask
  2200. * a directory for "all descriptors."
  2201. * Otherwise, we ask for all descriptors that we think are different
  2202. * from what we have.
  2203. */
  2204. void
  2205. update_router_descriptor_downloads(time_t now)
  2206. {
  2207. char *resource = NULL;
  2208. if (connection_get_by_type_purpose(CONN_TYPE_DIR,
  2209. DIR_PURPOSE_FETCH_SERVERDESC))
  2210. return;
  2211. if (!networkstatus_list || smartlist_len(networkstatus_list)<2) {
  2212. resource = tor_strdup("all.z");
  2213. log_fn(LOG_NOTICE, "Launching request for all routers");
  2214. } else {
  2215. smartlist_t *downloadable = router_list_downloadable();
  2216. if (smartlist_len(downloadable)) {
  2217. char *dl = smartlist_join_strings(downloadable,"+",0,NULL);
  2218. size_t r_len = smartlist_len(downloadable)*(DIGEST_LEN+1)+16;
  2219. /* Damn, that's an ugly way to do this. XXXX011 NM */
  2220. resource = tor_malloc(r_len);
  2221. tor_snprintf(resource, r_len, "fp/%s.z", dl);
  2222. log_fn(LOG_NOTICE, "Launching request for %d routers",
  2223. smartlist_len(downloadable));
  2224. tor_free(dl);
  2225. }
  2226. SMARTLIST_FOREACH(downloadable, char *, c, tor_free(c));
  2227. smartlist_free(downloadable);
  2228. }
  2229. if (!resource) {
  2230. log_fn(LOG_NOTICE, "No routers to download.");
  2231. return;
  2232. }
  2233. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,resource,1);
  2234. tor_free(resource);
  2235. }
  2236. /** Return true iff we have enough networkstatus and router information to
  2237. * start building circuits. Right now, this means "at least 2 networkstatus
  2238. * documents, and at least 1/4 of expected routers." */
  2239. int
  2240. router_have_minimum_dir_info(void)
  2241. {
  2242. int tot = 0, avg;
  2243. if (!networkstatus_list || smartlist_len(networkstatus_list)<2 ||
  2244. !routerlist)
  2245. return 0;
  2246. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2247. tot += smartlist_len(ns->entries));
  2248. avg = tot / smartlist_len(networkstatus_list);
  2249. return smartlist_len(routerlist->routers) > (avg/4);
  2250. }