routerlist.c 97 KB

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