routerlist.c 69 KB

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