dirserv.c 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  1. /* Copyright 2001-2004 Roger Dingledine.
  2. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char dirserv_c_id[] = "$Id$";
  6. #include "or.h"
  7. /**
  8. * \file dirserv.c
  9. * \brief Directory server core implementation. Manages directory
  10. * contents and generates directories.
  11. **/
  12. /** How far in the future do we allow a router to get? (seconds) */
  13. #define ROUTER_ALLOW_SKEW (60*60*12) /* 12 hours */
  14. /** How many seconds do we wait before regenerating the directory? */
  15. #define DIR_REGEN_SLACK_TIME 30
  16. extern long stats_n_seconds_working;
  17. typedef enum {
  18. FP_NAMED, /**< Listed in fingerprint file. */
  19. FP_VALID, /**< Unlisted but believed valid. */
  20. FP_INVALID, /**< Believed invalid. */
  21. FP_REJECT, /**< We will not publish this router. */
  22. } router_status_t;
  23. /** Do we need to regenerate the directory when someone asks for it? */
  24. static int the_directory_is_dirty = 1;
  25. static int runningrouters_is_dirty = 1;
  26. static int the_v2_networkstatus_is_dirty = 1;
  27. static void directory_remove_invalid(void);
  28. static int dirserv_regenerate_directory(void);
  29. static char *format_versions_list(config_line_t *ln);
  30. /* Should be static; exposed for testing */
  31. int add_fingerprint_to_dir(const char *nickname, const char *fp, smartlist_t *list);
  32. static int router_is_general_exit(routerinfo_t *ri);
  33. static router_status_t dirserv_router_get_status(const routerinfo_t *router,
  34. const char **msg);
  35. static router_status_t
  36. dirserv_get_status_impl(const char *fp, const char *nickname,
  37. const char *address,
  38. uint32_t addr, uint16_t or_port,
  39. const char *platform, const char *contact,
  40. const char **msg, int should_log);
  41. static int dirserv_thinks_router_is_reachable(routerinfo_t *router,
  42. time_t now);
  43. /************** Fingerprint handling code ************/
  44. static addr_policy_t *authdir_reject_policy = NULL;
  45. static addr_policy_t *authdir_invalid_policy = NULL;
  46. /** Parse authdir policy strings from the configuration.
  47. */
  48. void
  49. parse_authdir_policy(void)
  50. {
  51. addr_policy_t *n;
  52. if (authdir_reject_policy) {
  53. addr_policy_free(authdir_reject_policy);
  54. authdir_reject_policy = NULL;
  55. }
  56. config_parse_addr_policy(get_options()->AuthDirReject,
  57. &authdir_reject_policy, ADDR_POLICY_REJECT);
  58. /* ports aren't used. */
  59. for (n=authdir_reject_policy; n; n = n->next) {
  60. n->prt_min = 1;
  61. n->prt_max = 65535;
  62. }
  63. if (authdir_invalid_policy) {
  64. addr_policy_free(authdir_invalid_policy);
  65. authdir_invalid_policy = NULL;
  66. }
  67. config_parse_addr_policy(get_options()->AuthDirInvalid,
  68. &authdir_invalid_policy, ADDR_POLICY_REJECT);
  69. /* ports aren't used. */
  70. for (n=authdir_invalid_policy; n; n = n->next) {
  71. n->prt_min = 1;
  72. n->prt_max = 65535;
  73. }
  74. }
  75. /** A member of fingerprint_list: maps a name to a fingerprint.
  76. **/
  77. typedef struct fingerprint_entry_t {
  78. char *nickname; /**< The name of a router (if this fingerprint is bound to a
  79. * name); the string "!reject" (if this fingerprint should
  80. * always be rejected); or the string "!invalid" (if this
  81. * fingerprint should be accepted but never marked as
  82. * valid. */
  83. char *fingerprint; /**< Stored as HEX_DIGEST_LEN characters, followed by a NUL */
  84. } fingerprint_entry_t;
  85. /** List of nickname-\>identity fingerprint mappings for all the routers
  86. * that we name. Used to prevent router impersonation. */
  87. /* Should be static; exposed for testing */
  88. smartlist_t *fingerprint_list = NULL;
  89. /** Add the fingerprint <b>fp</b> for the nickname <b>nickname</b> to
  90. * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
  91. * new, or 1 if we replaced the old value.
  92. */
  93. int /* Should be static; exposed for testing */
  94. add_fingerprint_to_dir(const char *nickname, const char *fp, smartlist_t *list)
  95. {
  96. int i;
  97. fingerprint_entry_t *ent;
  98. char *fingerprint;
  99. tor_assert(nickname);
  100. tor_assert(fp);
  101. tor_assert(list);
  102. fingerprint = tor_strdup(fp);
  103. tor_strstrip(fingerprint, " ");
  104. if (nickname[0] != '!') {
  105. for (i = 0; i < smartlist_len(list); ++i) {
  106. ent = smartlist_get(list, i);
  107. if (!strcasecmp(ent->nickname,nickname)) {
  108. tor_free(ent->fingerprint);
  109. ent->fingerprint = fingerprint;
  110. return 1;
  111. }
  112. }
  113. }
  114. ent = tor_malloc(sizeof(fingerprint_entry_t));
  115. ent->nickname = tor_strdup(nickname);
  116. ent->fingerprint = fingerprint;
  117. smartlist_add(list, ent);
  118. return 0;
  119. }
  120. /** Add the nickname and fingerprint for this OR to the
  121. * global list of recognized identity key fingerprints. */
  122. int
  123. dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk)
  124. {
  125. char fp[FINGERPRINT_LEN+1];
  126. if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
  127. err(LD_BUG, "Error computing fingerprint");
  128. return -1;
  129. }
  130. if (!fingerprint_list)
  131. fingerprint_list = smartlist_create();
  132. add_fingerprint_to_dir(nickname, fp, fingerprint_list);
  133. return 0;
  134. }
  135. /** Parse the nickname-\>fingerprint mappings stored in the file named
  136. * <b>fname</b>. The file format is line-based, with each non-blank
  137. * holding one nickname, some space, and a fingerprint for that
  138. * nickname. On success, replace the current fingerprint list with
  139. * the contents of <b>fname</b> and return 0. On failure, leave the
  140. * current fingerprint list untouched, and return -1. */
  141. int
  142. dirserv_parse_fingerprint_file(const char *fname)
  143. {
  144. char *cf;
  145. char *nickname, *fingerprint;
  146. smartlist_t *fingerprint_list_new;
  147. int result;
  148. config_line_t *front=NULL, *list;
  149. cf = read_file_to_str(fname, 0);
  150. if (!cf) {
  151. warn(LD_FS, "Cannot open fingerprint file %s", fname);
  152. return -1;
  153. }
  154. result = config_get_lines(cf, &front);
  155. tor_free(cf);
  156. if (result < 0) {
  157. warn(LD_CONFIG, "Error reading from fingerprint file");
  158. return -1;
  159. }
  160. fingerprint_list_new = smartlist_create();
  161. for (list=front; list; list=list->next) {
  162. nickname = list->key; fingerprint = list->value;
  163. if (strlen(nickname) > MAX_NICKNAME_LEN) {
  164. notice(LD_CONFIG,
  165. "Nickname '%s' too long in fingerprint file. Skipping.", nickname);
  166. continue;
  167. }
  168. if (!is_legal_nickname(nickname) &&
  169. strcasecmp(nickname, "!reject") &&
  170. strcasecmp(nickname, "!invalid")) {
  171. notice(LD_CONFIG,
  172. "Invalid nickname '%s' in fingerprint file. Skipping.", nickname);
  173. continue;
  174. }
  175. if (strlen(fingerprint) != FINGERPRINT_LEN ||
  176. !crypto_pk_check_fingerprint_syntax(fingerprint)) {
  177. notice(LD_CONFIG,
  178. "Invalid fingerprint (nickname '%s', fingerprint %s). Skipping.",
  179. nickname, fingerprint);
  180. continue;
  181. }
  182. if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
  183. /* If you approved an OR called "client", then clients who use
  184. * the default nickname could all be rejected. That's no good. */
  185. notice(LD_CONFIG,
  186. "Authorizing a nickname '%s' would break many clients; skipping.",
  187. DEFAULT_CLIENT_NICKNAME);
  188. continue;
  189. }
  190. if (add_fingerprint_to_dir(nickname, fingerprint, fingerprint_list_new) != 0)
  191. notice(LD_CONFIG, "Duplicate nickname '%s'.", nickname);
  192. }
  193. config_free_lines(front);
  194. dirserv_free_fingerprint_list();
  195. fingerprint_list = fingerprint_list_new;
  196. /* Delete any routers whose fingerprints we no longer recognize */
  197. directory_remove_invalid();
  198. return 0;
  199. }
  200. /** Check whether <b>router</b> has a nickname/identity key combination that
  201. * we recognize from the fingerprint list, or an IP we automatically act on
  202. * according to our configuration. Return the appropriate router status.
  203. *
  204. * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
  205. * *<b>msg</b> to an explanation of why. */
  206. static router_status_t
  207. dirserv_router_get_status(const routerinfo_t *router, const char **msg)
  208. {
  209. char fingerprint[FINGERPRINT_LEN+1];
  210. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 0)) {
  211. warn(LD_BUG,"Error computing fingerprint");
  212. return -1;
  213. }
  214. return dirserv_get_status_impl(fingerprint, router->nickname,
  215. router->address,
  216. router->addr, router->or_port,
  217. router->platform, router->contact_info,
  218. msg, 1);
  219. }
  220. /** Return true if there is no point in downloading the router described by
  221. * <b>rs</b> because this directory would reject it. */
  222. int
  223. dirserv_would_reject_router(routerstatus_t *rs)
  224. {
  225. char fp[FINGERPRINT_LEN+1];
  226. router_status_t res;
  227. base16_encode(fp, sizeof(fp), rs->identity_digest, DIGEST_LEN);
  228. res = dirserv_get_status_impl(fp, rs->nickname,
  229. "", /* address is only used in logs */
  230. rs->addr, rs->or_port,
  231. NULL, NULL,
  232. NULL, 0);
  233. return (res == FP_REJECT);
  234. }
  235. /** Helper: As dirserv_get_router_status, but takes the router fingerprint
  236. * (hex, no spaces), nickname, address (used for logging only), IP address, OR
  237. * port, platform (logging only) and contact info (logging only) as arguments.
  238. *
  239. * If should_log is false, do not log messages. (There's not much point in
  240. * logging that we're rejecting servers we'll not download.)
  241. */
  242. static router_status_t
  243. dirserv_get_status_impl(const char *fp, const char *nickname,
  244. const char *address,
  245. uint32_t addr, uint16_t or_port,
  246. const char *platform, const char *contact,
  247. const char **msg, int should_log)
  248. {
  249. fingerprint_entry_t *nn_ent = NULL, *fp_ent = NULL;
  250. if (!fingerprint_list)
  251. fingerprint_list = smartlist_create();
  252. if (should_log)
  253. debug(LD_DIRSERV, "%d fingerprints known.", smartlist_len(fingerprint_list));
  254. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t *, ent,
  255. {
  256. if (!strcasecmp(fp,ent->fingerprint))
  257. fp_ent = ent;
  258. if (!strcasecmp(nickname,ent->nickname))
  259. nn_ent = ent;
  260. });
  261. if (fp_ent) {
  262. if (!strcasecmp(fp_ent->nickname, "!reject")) {
  263. if (msg)
  264. *msg = "Fingerprint is marked rejected";
  265. return FP_REJECT;
  266. } else if (!strcasecmp(fp_ent->nickname, "!invalid")) {
  267. if (msg)
  268. *msg = "Fingerprint is marged invalid";
  269. return FP_INVALID;
  270. }
  271. }
  272. if (!nn_ent) { /* No such server known with that nickname */
  273. addr_policy_result_t rej = router_compare_addr_to_addr_policy(
  274. addr, or_port, authdir_reject_policy);
  275. addr_policy_result_t inv = router_compare_addr_to_addr_policy(
  276. addr, or_port, authdir_invalid_policy);
  277. if (rej == ADDR_POLICY_PROBABLY_REJECTED || rej == ADDR_POLICY_REJECTED) {
  278. if (should_log)
  279. info(LD_DIRSERV, "Rejecting '%s' because of address %s",
  280. nickname, address);
  281. if (msg)
  282. *msg = "Authdir is rejecting routers in this range.";
  283. return FP_REJECT;
  284. }
  285. if (inv == ADDR_POLICY_PROBABLY_REJECTED || inv == ADDR_POLICY_REJECTED) {
  286. if (should_log)
  287. info(LD_DIRSERV, "Not marking '%s' valid because of address %s",
  288. nickname, address);
  289. return FP_INVALID;
  290. }
  291. if (!platform || tor_version_as_new_as(platform,"0.1.0.2-rc"))
  292. return FP_VALID;
  293. else
  294. return FP_INVALID;
  295. if (should_log)
  296. info(LD_DIRSERV,"No fingerprint found for '%s'",nickname);
  297. return 0;
  298. }
  299. if (0==strcasecmp(nn_ent->fingerprint, fp)) {
  300. if (should_log)
  301. debug(LD_DIRSERV,"Good fingerprint for '%s'",nickname);
  302. return FP_NAMED; /* Right fingerprint. */
  303. } else {
  304. if (should_log)
  305. warn(LD_DIRSERV,"Mismatched fingerprint for '%s': expected '%s' got '%s'. ContactInfo '%s', platform '%s'.)",
  306. nickname, nn_ent->fingerprint, fp,
  307. contact ? contact : "",
  308. platform ? platform : "");
  309. if (msg)
  310. *msg = "Rejected: There is already a verified server with this nickname and a different fingerprint.";
  311. return FP_REJECT; /* Wrong fingerprint. */
  312. }
  313. }
  314. /** If we are an authoritative dirserver, and the list of approved
  315. * servers contains one whose identity key digest is <b>digest</b>,
  316. * return that router's nickname. Otherwise return NULL. */
  317. const char *
  318. dirserv_get_nickname_by_digest(const char *digest)
  319. {
  320. char hexdigest[HEX_DIGEST_LEN+1];
  321. if (!fingerprint_list)
  322. return NULL;
  323. tor_assert(digest);
  324. base16_encode(hexdigest, HEX_DIGEST_LEN+1, digest, DIGEST_LEN);
  325. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, ent,
  326. { if (!strcasecmp(hexdigest, ent->fingerprint))
  327. return ent->nickname; } );
  328. return NULL;
  329. }
  330. /** Clear the current fingerprint list. */
  331. void
  332. dirserv_free_fingerprint_list(void)
  333. {
  334. int i;
  335. fingerprint_entry_t *ent;
  336. if (!fingerprint_list)
  337. return;
  338. for (i = 0; i < smartlist_len(fingerprint_list); ++i) {
  339. ent = smartlist_get(fingerprint_list, i);
  340. tor_free(ent->nickname);
  341. tor_free(ent->fingerprint);
  342. tor_free(ent);
  343. }
  344. smartlist_free(fingerprint_list);
  345. fingerprint_list = NULL;
  346. }
  347. /*
  348. * Descriptor list
  349. */
  350. /** Return -1 if <b>ri</b> has a private or otherwise bad address,
  351. * unless we're configured to not care. Return 0 if all ok. */
  352. static int
  353. dirserv_router_has_valid_address(routerinfo_t *ri)
  354. {
  355. struct in_addr iaddr;
  356. if (get_options()->DirAllowPrivateAddresses)
  357. return 0; /* whatever it is, we're fine with it */
  358. if (!tor_inet_aton(ri->address, &iaddr)) {
  359. info(LD_DIRSERV,"Router '%s' published non-IP address '%s'. Refusing.",
  360. ri->nickname, ri->address);
  361. return -1;
  362. }
  363. if (is_internal_IP(ntohl(iaddr.s_addr))) {
  364. info(LD_DIRSERV,
  365. "Router '%s' published internal IP address '%s'. Refusing.",
  366. ri->nickname, ri->address);
  367. return -1; /* it's a private IP, we should reject it */
  368. }
  369. return 0;
  370. }
  371. /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
  372. * return 0, and set its is_valid,named,running fields. Otherwise, return -1.
  373. *
  374. * If the router is rejected, set *<b>msg</b> to an explanation of why.
  375. */
  376. int
  377. authdir_wants_to_reject_router(routerinfo_t *ri,
  378. const char **msg)
  379. {
  380. /* Okay. Now check whether the fingerprint is recognized. */
  381. router_status_t status = dirserv_router_get_status(ri, msg);
  382. time_t now;
  383. tor_assert(msg);
  384. if (status == FP_REJECT)
  385. return -1; /* msg is already set. */
  386. /* Is there too much clock skew? */
  387. now = time(NULL);
  388. if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
  389. notice(LD_DIRSERV, "Publication time for nickname '%s' is too far (%d minutes) in the future; possible clock skew. Not adding (ContactInfo '%s', platform '%s').",
  390. ri->nickname, (int)((ri->cache_info.published_on-now)/60),
  391. ri->contact_info ? ri->contact_info : "",
  392. ri->platform ? ri->platform : "");
  393. *msg = "Rejected: Your clock is set too far in the future, or your timezone is not correct.";
  394. return -1;
  395. }
  396. if (ri->cache_info.published_on < now-ROUTER_MAX_AGE) {
  397. notice(LD_DIRSERV, "Publication time for router with nickname '%s' is too far (%d minutes) in the past. Not adding (ContactInfo '%s', platform '%s').",
  398. ri->nickname, (int)((now-ri->cache_info.published_on)/60),
  399. ri->contact_info ? ri->contact_info : "",
  400. ri->platform ? ri->platform : "");
  401. *msg = "Rejected: Server is expired, or your clock is too far in the past, or your timezone is not correct.";
  402. return -1;
  403. }
  404. if (dirserv_router_has_valid_address(ri) < 0) {
  405. notice(LD_DIRSERV, "Router with nickname '%s' has invalid address '%s'. Not adding (ContactInfo '%s', platform '%s').",
  406. ri->nickname, ri->address,
  407. ri->contact_info ? ri->contact_info : "",
  408. ri->platform ? ri->platform : "");
  409. *msg = "Rejected: Address is not an IP, or IP is a private address.";
  410. return -1;
  411. }
  412. /* Okay, looks like we're willing to accept this one. */
  413. switch (status) {
  414. case FP_NAMED:
  415. ri->is_named = ri->is_verified = 1;
  416. break;
  417. case FP_VALID:
  418. ri->is_named = 0;
  419. ri->is_verified = 1;
  420. break;
  421. case FP_INVALID:
  422. ri->is_named = ri->is_verified = 0;
  423. break;
  424. default:
  425. tor_assert(0);
  426. }
  427. return 0;
  428. }
  429. /** Parse the server descriptor at <b>desc</b> and maybe insert it into
  430. * the list of server descriptors. Set *<b>msg</b> to a message that
  431. * should be passed back to the origin of this descriptor.
  432. *
  433. * Return 2 if descriptor is well-formed and accepted;
  434. * 1 if well-formed and accepted but origin should hear *msg;
  435. * 0 if well-formed but redundant with one we already have;
  436. * -1 if it looks vaguely like a router descriptor but rejected;
  437. * -2 if we can't find a router descriptor in <b>desc</b>.
  438. */
  439. int
  440. dirserv_add_descriptor(const char *desc, const char **msg)
  441. {
  442. int r;
  443. routerinfo_t *ri = NULL, *ri_old = NULL;
  444. tor_assert(msg);
  445. *msg = NULL;
  446. /* Check: is the descriptor syntactically valid? */
  447. ri = router_parse_entry_from_string(desc, NULL);
  448. if (!ri) {
  449. warn(LD_DIRSERV, "Couldn't parse uploaded server descriptor");
  450. *msg = "Rejected: Couldn't parse server descriptor.";
  451. return -2;
  452. }
  453. /* Check whether this descriptor is semantically identical to the last one
  454. * from this server. (We do this here and not in router_add_to_routerlist
  455. * because we want to be able to accept the newest router descriptor that
  456. * another authority has, so we all converge on the same one.) */
  457. ri_old = router_get_by_digest(ri->cache_info.identity_digest);
  458. if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
  459. && router_differences_are_cosmetic(ri_old, ri)) {
  460. info(LD_DIRSERV,
  461. "Not replacing descriptor from '%s'; differences are cosmetic.",
  462. ri->nickname);
  463. *msg = "Not replacing router descriptor; no information has changed since the last one with this identity.";
  464. routerinfo_free(ri);
  465. control_event_or_authdir_new_descriptor("DROPPED", desc, *msg);
  466. return 0;
  467. }
  468. if ((r = router_add_to_routerlist(ri, msg, 0))<0) {
  469. if (r < -1) /* unless the routerinfo was fine, just out-of-date */
  470. control_event_or_authdir_new_descriptor("REJECTED", desc, *msg);
  471. return r == -1 ? 0 : -1;
  472. } else {
  473. smartlist_t *changed;
  474. control_event_or_authdir_new_descriptor("ACCEPTED", desc, *msg);
  475. changed = smartlist_create();
  476. smartlist_add(changed, ri);
  477. control_event_descriptors_changed(changed);
  478. smartlist_free(changed);
  479. if (!*msg) {
  480. *msg = ri->is_verified ? "Verified server descriptor accepted" :
  481. "Unverified server descriptor accepted";
  482. }
  483. return r == 0 ? 2 : 1;
  484. }
  485. }
  486. /** Remove all descriptors whose nicknames or fingerprints no longer
  487. * are allowed by our fingerprint list. (Descriptors that used to be
  488. * good can become bad when we reload the fingerprint list.)
  489. */
  490. static void
  491. directory_remove_invalid(void)
  492. {
  493. int i;
  494. int changed = 0;
  495. routerlist_t *rl = router_get_routerlist();
  496. for (i = 0; i < smartlist_len(rl->routers); ++i) {
  497. const char *msg;
  498. routerinfo_t *ent = smartlist_get(rl->routers, i);
  499. router_status_t r = dirserv_router_get_status(ent, &msg);
  500. switch (r) {
  501. case FP_REJECT:
  502. info(LD_DIRSERV, "Router '%s' is now rejected: %s",
  503. ent->nickname, msg?msg:"");
  504. routerlist_remove(rl, ent, i--, 0);
  505. changed = 1;
  506. break;
  507. case FP_NAMED:
  508. if (!ent->is_verified || !ent->is_named) {
  509. info(LD_DIRSERV,
  510. "Router '%s' is now verified and named.", ent->nickname);
  511. ent->is_verified = ent->is_named = 1;
  512. changed = 1;
  513. }
  514. break;
  515. case FP_VALID:
  516. if (!ent->is_verified || ent->is_named) {
  517. info(LD_DIRSERV, "Router '%s' is now verified.", ent->nickname);
  518. ent->is_verified = 1;
  519. ent->is_named = 0;
  520. changed = 1;
  521. }
  522. break;
  523. case FP_INVALID:
  524. if (ent->is_verified || ent->is_named) {
  525. info(LD_DIRSERV,
  526. "Router '%s' is no longer verified.", ent->nickname);
  527. ent->is_verified = ent->is_named = 0;
  528. changed = 1;
  529. }
  530. break;
  531. }
  532. }
  533. if (changed)
  534. directory_set_dirty();
  535. }
  536. /** Write a list of unregistered descriptors into a newly allocated
  537. * string and return it. Used by dirserv operators to keep track of
  538. * fast nodes that haven't registered.
  539. */
  540. char *
  541. dirserver_getinfo_unregistered(const char *question)
  542. {
  543. router_status_t r;
  544. smartlist_t *answerlist;
  545. char buf[1024];
  546. char *answer;
  547. int min_bw = atoi(question);
  548. routerlist_t *rl = router_get_routerlist();
  549. answerlist = smartlist_create();
  550. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ent, {
  551. r = dirserv_router_get_status(ent, NULL);
  552. if (ent->bandwidthcapacity >= (size_t)min_bw &&
  553. ent->bandwidthrate >= (size_t)min_bw &&
  554. r != FP_NAMED) {
  555. /* then log this one */
  556. tor_snprintf(buf, sizeof(buf),
  557. "%s: BW %d on '%s'.",
  558. ent->nickname, ent->bandwidthcapacity,
  559. ent->platform ? ent->platform : "");
  560. smartlist_add(answerlist, tor_strdup(buf));
  561. }
  562. });
  563. answer = smartlist_join_strings(answerlist, "\r\n", 0, NULL);
  564. SMARTLIST_FOREACH(answerlist, char *, cp, tor_free(cp));
  565. smartlist_free(answerlist);
  566. return answer;
  567. }
  568. /** Mark the directory as <b>dirty</b> -- when we're next asked for a
  569. * directory, we will rebuild it instead of reusing the most recently
  570. * generated one.
  571. */
  572. void
  573. directory_set_dirty(void)
  574. {
  575. time_t now = time(NULL);
  576. if (!the_directory_is_dirty)
  577. the_directory_is_dirty = now;
  578. if (!runningrouters_is_dirty)
  579. runningrouters_is_dirty = now;
  580. if (!the_v2_networkstatus_is_dirty)
  581. the_v2_networkstatus_is_dirty = now;
  582. }
  583. /**
  584. * Allocate and return a description of the status of the server <b>desc</b>,
  585. * for use in a router-status line. The server is listed
  586. * as running iff <b>is_live</b> is true.
  587. */
  588. static char *
  589. list_single_server_status(routerinfo_t *desc, int is_live)
  590. {
  591. char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
  592. char *cp;
  593. tor_assert(desc);
  594. cp = buf;
  595. if (!is_live) {
  596. *cp++ = '!';
  597. }
  598. if (desc->is_verified) {
  599. strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
  600. cp += strlen(cp);
  601. *cp++ = '=';
  602. }
  603. *cp++ = '$';
  604. base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
  605. DIGEST_LEN);
  606. return tor_strdup(buf);
  607. }
  608. #define REACHABLE_TIMEOUT (60*60) /* an hour */
  609. /* Make sure this is 3 times the value of get_dir_fetch_period() */
  610. /** Treat a router as alive if
  611. * - It's me, and I'm not hibernating.
  612. * or - we're connected to it and we've found it reachable recently. */
  613. static int
  614. dirserv_thinks_router_is_reachable(routerinfo_t *router, time_t now)
  615. {
  616. connection_t *conn;
  617. if (router_is_me(router) && !we_are_hibernating())
  618. return 1;
  619. conn = connection_or_get_by_identity_digest(router->cache_info.identity_digest);
  620. if (conn && conn->state == OR_CONN_STATE_OPEN)
  621. return get_options()->AssumeReachable ||
  622. now < router->last_reachable + REACHABLE_TIMEOUT;
  623. return 0;
  624. }
  625. /** Return 1 if we're confident that there's a problem with
  626. * <b>router</b>'s reachability and its operator should be notified.
  627. */
  628. int
  629. dirserv_thinks_router_is_blatantly_unreachable(routerinfo_t *router, time_t now)
  630. {
  631. connection_t *conn;
  632. if (router->is_hibernating)
  633. return 0;
  634. conn = connection_or_get_by_identity_digest(router->cache_info.identity_digest);
  635. if (conn && conn->state == OR_CONN_STATE_OPEN &&
  636. now >= router->last_reachable + 2*REACHABLE_TIMEOUT &&
  637. router->testing_since &&
  638. now >= router->testing_since + 2*REACHABLE_TIMEOUT)
  639. return 1;
  640. return 0;
  641. }
  642. /** Based on the routerinfo_ts in <b>routers</b>, allocate the
  643. * contents of a router-status line, and store it in
  644. * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
  645. */
  646. int
  647. list_server_status(smartlist_t *routers, char **router_status_out)
  648. {
  649. /* List of entries in a router-status style: An optional !, then an optional
  650. * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
  651. smartlist_t *rs_entries;
  652. time_t now = time(NULL);
  653. int authdir_mode = get_options()->AuthoritativeDir;
  654. tor_assert(router_status_out);
  655. rs_entries = smartlist_create();
  656. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  657. {
  658. if (authdir_mode) {
  659. /* Update router status in routerinfo_t. */
  660. ri->is_running = dirserv_thinks_router_is_reachable(ri, now);
  661. }
  662. smartlist_add(rs_entries, list_single_server_status(ri, ri->is_running));
  663. });
  664. *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
  665. SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
  666. smartlist_free(rs_entries);
  667. return 0;
  668. }
  669. /** Helper: Given pointers to two strings describing tor versions, return -1
  670. * if _a precedes _b, 1 if _b preceeds _a, and 0 if they are equivalent.
  671. * Used to sort a list of versions. */
  672. static int
  673. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  674. {
  675. const char *a = *_a, *b = *_b;
  676. int ca, cb;
  677. tor_version_t va, vb;
  678. ca = tor_version_parse(a, &va);
  679. cb = tor_version_parse(b, &vb);
  680. /* If they both parse, compare them. */
  681. if (!ca && !cb)
  682. return tor_version_compare(&va,&vb);
  683. /* If one parses, it comes first. */
  684. if (!ca && cb)
  685. return -1;
  686. if (ca && !cb)
  687. return 1;
  688. /* If neither parses, compare strings. Also, the directory server admin needs
  689. ** to be smacked upside the head. But Tor is tolerant and gentle. */
  690. return strcmp(a,b);
  691. }
  692. /* Given a (possibly empty) list of config_line_t, each line of which contains
  693. * a list of comma-separated version numbers surrounded by optional space,
  694. * allocate and return a new string containing the version numbers, in order,
  695. * separated by commas. Used to generate Recommended(Client|Server)?Versions
  696. */
  697. static char *
  698. format_versions_list(config_line_t *ln)
  699. {
  700. smartlist_t *versions;
  701. char *result;
  702. versions = smartlist_create();
  703. for ( ; ln; ln = ln->next) {
  704. smartlist_split_string(versions, ln->value, ",",
  705. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  706. }
  707. smartlist_sort(versions, _compare_tor_version_str_ptr);
  708. result = smartlist_join_strings(versions,",",0,NULL);
  709. SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
  710. smartlist_free(versions);
  711. return result;
  712. }
  713. /** Generate a new directory and write it into a newly allocated string.
  714. * Point *<b>dir_out</b> to the allocated string. Sign the
  715. * directory with <b>private_key</b>. Return 0 on success, -1 on
  716. * failure.
  717. */
  718. int
  719. dirserv_dump_directory_to_string(char **dir_out,
  720. crypto_pk_env_t *private_key)
  721. {
  722. char *cp;
  723. char *router_status;
  724. char *identity_pkey; /* Identity key, DER64-encoded. */
  725. char *recommended_versions;
  726. char digest[DIGEST_LEN];
  727. char published[ISO_TIME_LEN+1];
  728. time_t published_on;
  729. char *buf = NULL;
  730. size_t buf_len;
  731. size_t identity_pkey_len;
  732. routerlist_t *rl = router_get_routerlist();
  733. tor_assert(dir_out);
  734. *dir_out = NULL;
  735. if (list_server_status(rl->routers, &router_status))
  736. return -1;
  737. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  738. &identity_pkey_len)<0) {
  739. warn(LD_BUG,"write identity_pkey to string failed!");
  740. return -1;
  741. }
  742. recommended_versions = format_versions_list(get_options()->RecommendedVersions);
  743. published_on = time(NULL);
  744. format_iso_time(published, published_on);
  745. buf_len = 2048+strlen(recommended_versions)+
  746. strlen(router_status);
  747. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  748. buf_len += ri->cache_info.signed_descriptor_len+1);
  749. buf = tor_malloc(buf_len);
  750. /* We'll be comparing against buf_len throughout the rest of the
  751. function, though strictly speaking we shouldn't be able to exceed
  752. it. This is C, after all, so we may as well check for buffer
  753. overruns.*/
  754. tor_snprintf(buf, buf_len,
  755. "signed-directory\n"
  756. "published %s\n"
  757. "recommended-software %s\n"
  758. "router-status %s\n"
  759. "dir-signing-key\n%s\n",
  760. published, recommended_versions, router_status,
  761. identity_pkey);
  762. tor_free(recommended_versions);
  763. tor_free(router_status);
  764. tor_free(identity_pkey);
  765. cp = buf + strlen(buf);
  766. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  767. {
  768. size_t len = ri->cache_info.signed_descriptor_len;
  769. if (cp+len+1 >= buf+buf_len)
  770. goto truncated;
  771. memcpy(cp, ri->cache_info.signed_descriptor, len);
  772. cp += len;
  773. *cp++ = '\n'; /* add an extra newline in case somebody was depending on
  774. * it. */
  775. });
  776. *cp = '\0';
  777. /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
  778. signature.
  779. */
  780. if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
  781. goto truncated;
  782. if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
  783. goto truncated;
  784. if (strlcat(buf, "\n", buf_len) >= buf_len)
  785. goto truncated;
  786. if (router_get_dir_hash(buf,digest)) {
  787. warn(LD_BUG,"couldn't compute digest");
  788. tor_free(buf);
  789. return -1;
  790. }
  791. if (router_append_dirobj_signature(buf,buf_len,digest,private_key)<0) {
  792. tor_free(buf);
  793. return -1;
  794. }
  795. *dir_out = buf;
  796. return 0;
  797. truncated:
  798. warn(LD_BUG,"tried to exceed string length.");
  799. tor_free(buf);
  800. return -1;
  801. }
  802. /** Most recently generated encoded signed directory. (auth dirservers only.)*/
  803. static cached_dir_t the_directory = { NULL, NULL, 0, 0, 0 };
  804. /* Used only by non-auth dirservers: The directory and runningrouters we'll
  805. * serve when requested. */
  806. static cached_dir_t cached_directory = { NULL, NULL, 0, 0, 0 };
  807. static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0 };
  808. /* Used for other dirservers' v2 network statuses. Map from hexdigest to
  809. * cached_dir_t. */
  810. static digestmap_t *cached_v2_networkstatus = NULL;
  811. /** Possibly replace the contents of <b>d</b> with the value of
  812. * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
  813. * the last value, or too far in the future.
  814. *
  815. * Does not copy <b>directory</b>; free it if it isn't used.
  816. */
  817. static void
  818. set_cached_dir(cached_dir_t *d, char *directory, time_t when)
  819. {
  820. time_t now = time(NULL);
  821. if (when<=d->published) {
  822. info(LD_DIRSERV, "Ignoring old directory; not caching.");
  823. tor_free(directory);
  824. } else if (when>=now+ROUTER_MAX_AGE) {
  825. info(LD_DIRSERV, "Ignoring future directory; not caching.");
  826. tor_free(directory);
  827. } else {
  828. /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
  829. debug(LD_DIRSERV, "Caching directory.");
  830. tor_free(d->dir);
  831. d->dir = directory;
  832. d->dir_len = strlen(directory);
  833. tor_free(d->dir_z);
  834. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  835. ZLIB_METHOD)) {
  836. warn(LD_BUG,"Error compressing cached directory");
  837. }
  838. d->published = when;
  839. }
  840. }
  841. /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
  842. static void
  843. clear_cached_dir(cached_dir_t *d)
  844. {
  845. tor_free(d->dir);
  846. tor_free(d->dir_z);
  847. memset(d, 0, sizeof(cached_dir_t));
  848. }
  849. /** Free all storage held by the cached_dir_t in <b>d</b>. */
  850. static void
  851. free_cached_dir(void *_d)
  852. {
  853. cached_dir_t *d = (cached_dir_t *)_d;
  854. clear_cached_dir(d);
  855. tor_free(d);
  856. }
  857. /** If we have no cached directory, or it is older than <b>when</b>, then
  858. * replace it with <b>directory</b>, published at <b>when</b>.
  859. */
  860. void
  861. dirserv_set_cached_directory(const char *directory, time_t published,
  862. int is_running_routers)
  863. {
  864. cached_dir_t *d;
  865. d = is_running_routers ? &cached_runningrouters : &cached_directory;
  866. set_cached_dir(d, tor_strdup(directory), published);
  867. }
  868. /** We've just received a v2 network-status for an authoritative directory
  869. * with identity digest <b>identity</b> published at
  870. * <b>published</b>. Store it so we can serve it to others. If
  871. * <b>directory</b> is NULL, remove the entry with the given fingerprint from
  872. * the cache.
  873. */
  874. void
  875. dirserv_set_cached_networkstatus_v2(const char *directory,
  876. const char *identity,
  877. time_t published)
  878. {
  879. cached_dir_t *d;
  880. if (!cached_v2_networkstatus)
  881. cached_v2_networkstatus = digestmap_new();
  882. if (!(d = digestmap_get(cached_v2_networkstatus, identity))) {
  883. if (!directory)
  884. return;
  885. d = tor_malloc_zero(sizeof(cached_dir_t));
  886. digestmap_set(cached_v2_networkstatus, identity, d);
  887. }
  888. tor_assert(d);
  889. if (directory) {
  890. set_cached_dir(d, tor_strdup(directory), published);
  891. } else {
  892. free_cached_dir(d);
  893. digestmap_remove(cached_v2_networkstatus, identity);
  894. }
  895. }
  896. /** Helper: If we're an authority for the right directory version (the
  897. * directory version is determined by <b>is_v1_object</b>), try to regenerate
  898. * auth_src as appropriate and return it, falling back to cache_src on
  899. * failure. If we're a cache, return cach_src.
  900. */
  901. static cached_dir_t *
  902. dirserv_pick_cached_dir_obj(cached_dir_t *cache_src,
  903. cached_dir_t *auth_src,
  904. time_t dirty, int (*regenerate)(void),
  905. const char *name,
  906. int is_v1_object)
  907. {
  908. int authority = get_options()->AuthoritativeDir &&
  909. (!is_v1_object || get_options()->V1AuthoritativeDir);
  910. if (!authority) {
  911. return cache_src;
  912. } else {
  913. /* We're authoritative. */
  914. if (regenerate != NULL) {
  915. if (dirty && dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  916. if (regenerate()) {
  917. err(LD_BUG, "Couldn't generate %s?", name);
  918. exit(1);
  919. }
  920. } else {
  921. info(LD_DIRSERV, "The %s is still clean; reusing.", name);
  922. }
  923. }
  924. return auth_src ? auth_src : cache_src;
  925. }
  926. }
  927. /** Helper: If we're authoritative and <b>auth_src</b> is set, use
  928. * <b>auth_src</b>, otherwise use <b>cache_src</b>. If we're using
  929. * <b>auth_src</b> and it's been <b>dirty</b> for at least
  930. * DIR_REGEN_SLACK_TIME seconds, call <b>regenerate</b>() to make a fresh one.
  931. * Yields the compressed version of the directory object if <b>compress</b> is
  932. * set; otherwise return the uncompressed version. (In either case, sets
  933. * *<b>out</b> and returns the size of the buffer in *<b>out</b>.)
  934. *
  935. * Use <b>is_v1_object</b> to help determine whether we're authoritative for
  936. * this kind of object.
  937. **/
  938. static size_t
  939. dirserv_get_obj(const char **out, int compress,
  940. cached_dir_t *cache_src,
  941. cached_dir_t *auth_src,
  942. time_t dirty, int (*regenerate)(void),
  943. const char *name,
  944. int is_v1_object)
  945. {
  946. cached_dir_t *d = dirserv_pick_cached_dir_obj(
  947. cache_src, auth_src,
  948. dirty, regenerate, name, is_v1_object);
  949. if (!d)
  950. return 0;
  951. *out = compress ? d->dir_z : d->dir;
  952. if (*out) {
  953. return compress ? d->dir_z_len : d->dir_len;
  954. } else {
  955. /* not yet available. */
  956. return 0;
  957. }
  958. }
  959. /** Set *<b>directory</b> to the most recently generated encoded signed
  960. * directory, generating a new one as necessary. If not an authoritative
  961. * directory may return 0 if no directory is yet cached.*/
  962. size_t
  963. dirserv_get_directory(const char **directory, int compress)
  964. {
  965. return dirserv_get_obj(directory, compress,
  966. &cached_directory, &the_directory,
  967. the_directory_is_dirty,
  968. dirserv_regenerate_directory,
  969. "server directory", 1);
  970. }
  971. /**
  972. * Generate a fresh directory (authdirservers only.)
  973. */
  974. static int
  975. dirserv_regenerate_directory(void)
  976. {
  977. char *new_directory=NULL;
  978. if (dirserv_dump_directory_to_string(&new_directory,
  979. get_identity_key())) {
  980. warn(LD_BUG, "Error creating directory.");
  981. tor_free(new_directory);
  982. return -1;
  983. }
  984. set_cached_dir(&the_directory, new_directory, time(NULL));
  985. info(LD_DIRSERV,"New directory (size %d) has been built.",
  986. (int)the_directory.dir_len);
  987. debug(LD_DIRSERV,"New directory (size %d):\n%s",(int)the_directory.dir_len,
  988. the_directory.dir);
  989. the_directory_is_dirty = 0;
  990. /* Save the directory to disk so we re-load it quickly on startup.
  991. */
  992. dirserv_set_cached_directory(the_directory.dir, time(NULL), 0);
  993. return 0;
  994. }
  995. /** For authoritative directories: the current (v1) network status */
  996. static cached_dir_t the_runningrouters = { NULL, NULL, 0, 0, 0 };
  997. /** Replace the current running-routers list with a newly generated one. */
  998. static int
  999. generate_runningrouters(void)
  1000. {
  1001. char *s=NULL;
  1002. char *router_status=NULL;
  1003. char digest[DIGEST_LEN];
  1004. char published[ISO_TIME_LEN+1];
  1005. size_t len;
  1006. crypto_pk_env_t *private_key = get_identity_key();
  1007. char *identity_pkey; /* Identity key, DER64-encoded. */
  1008. size_t identity_pkey_len;
  1009. routerlist_t *rl = router_get_routerlist();
  1010. if (list_server_status(rl->routers, &router_status)) {
  1011. goto err;
  1012. }
  1013. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  1014. &identity_pkey_len)<0) {
  1015. warn(LD_BUG,"write identity_pkey to string failed!");
  1016. goto err;
  1017. }
  1018. format_iso_time(published, time(NULL));
  1019. len = 2048+strlen(router_status);
  1020. s = tor_malloc_zero(len);
  1021. tor_snprintf(s, len,
  1022. "network-status\n"
  1023. "published %s\n"
  1024. "router-status %s\n"
  1025. "dir-signing-key\n%s"
  1026. "directory-signature %s\n",
  1027. published, router_status, identity_pkey, get_options()->Nickname);
  1028. tor_free(router_status);
  1029. tor_free(identity_pkey);
  1030. if (router_get_runningrouters_hash(s,digest)) {
  1031. warn(LD_BUG,"couldn't compute digest");
  1032. goto err;
  1033. }
  1034. if (router_append_dirobj_signature(s, len, digest, private_key)<0)
  1035. goto err;
  1036. set_cached_dir(&the_runningrouters, s, time(NULL));
  1037. runningrouters_is_dirty = 0;
  1038. return 0;
  1039. err:
  1040. tor_free(s);
  1041. tor_free(router_status);
  1042. return -1;
  1043. }
  1044. /** Set *<b>rr</b> to the most recently generated encoded signed
  1045. * running-routers list, generating a new one as necessary. Return the
  1046. * size of the directory on success, and 0 on failure. */
  1047. size_t
  1048. dirserv_get_runningrouters(const char **rr, int compress)
  1049. {
  1050. return dirserv_get_obj(rr, compress,
  1051. &cached_runningrouters, &the_runningrouters,
  1052. runningrouters_is_dirty,
  1053. generate_runningrouters,
  1054. "v1 network status list", 1);
  1055. }
  1056. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  1057. * it allows exit to at least one /8 address space for at least
  1058. * one of ports 80, 443, and 6667. */
  1059. static int
  1060. router_is_general_exit(routerinfo_t *ri)
  1061. {
  1062. static const int ports[] = { 80, 443, 6667 };
  1063. int n_allowed = 0;
  1064. int i;
  1065. for (i = 0; i < 3; ++i) {
  1066. struct addr_policy_t *policy = ri->exit_policy;
  1067. for ( ; policy; policy = policy->next) {
  1068. if (policy->prt_min > ports[i] || policy->prt_max < ports[i])
  1069. continue; /* Doesn't cover our port. */
  1070. if ((policy->msk & 0x00fffffful) != 0)
  1071. continue; /* Narrower than a /8. */
  1072. if ((policy->addr & 0xff000000ul) == 0x7f000000ul)
  1073. continue; /* 127.x */
  1074. /* We have a match that is at least a /8. */
  1075. if (policy->policy_type == ADDR_POLICY_ACCEPT)
  1076. ++n_allowed;
  1077. break;
  1078. }
  1079. }
  1080. return n_allowed > 0;
  1081. }
  1082. /** For authoritative directories: the current (v2) network status */
  1083. static cached_dir_t the_v2_networkstatus = { NULL, NULL, 0, 0, 0 };
  1084. static int
  1085. should_generate_v2_networkstatus(void)
  1086. {
  1087. return get_options()->AuthoritativeDir &&
  1088. the_v2_networkstatus_is_dirty &&
  1089. the_v2_networkstatus_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL);
  1090. }
  1091. /** For authoritative directories only: replace the contents of
  1092. * <b>the_v2_networkstatus</b> with a newly generated network status
  1093. * object. */
  1094. static int
  1095. generate_v2_networkstatus(void)
  1096. {
  1097. #define LONGEST_STATUS_FLAG_NAME_LEN 7
  1098. #define N_STATUS_FLAGS 6
  1099. #define RS_ENTRY_LEN \
  1100. ( /* first line */ \
  1101. MAX_NICKNAME_LEN+BASE64_DIGEST_LEN*2+ISO_TIME_LEN+INET_NTOA_BUF_LEN+ \
  1102. 5*2 /* ports */ + 10 /* punctuation */ + \
  1103. /* second line */ \
  1104. (LONGEST_STATUS_FLAG_NAME_LEN+1)*N_STATUS_FLAGS + 2)
  1105. int r = -1;
  1106. size_t len, identity_pkey_len;
  1107. char *status = NULL, *client_versions = NULL, *server_versions = NULL,
  1108. *identity_pkey = NULL, *hostname = NULL;
  1109. char *outp, *endp;
  1110. or_options_t *options = get_options();
  1111. char fingerprint[FINGERPRINT_LEN+1];
  1112. char ipaddr[INET_NTOA_BUF_LEN+1];
  1113. char published[ISO_TIME_LEN];
  1114. char digest[DIGEST_LEN];
  1115. struct in_addr in;
  1116. uint32_t addr;
  1117. crypto_pk_env_t *private_key = get_identity_key();
  1118. routerlist_t *rl = router_get_routerlist();
  1119. time_t now = time(NULL);
  1120. int naming = options->NamingAuthoritativeDir;
  1121. int versioning = options->VersioningAuthoritativeDir;
  1122. const char *contact;
  1123. if (resolve_my_address(options, &addr, &hostname)<0) {
  1124. warn(LD_NET, "Couldn't resolve my hostname");
  1125. goto done;
  1126. }
  1127. in.s_addr = htonl(addr);
  1128. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1129. format_iso_time(published, time(NULL));
  1130. client_versions = format_versions_list(options->RecommendedClientVersions);
  1131. server_versions = format_versions_list(options->RecommendedServerVersions);
  1132. if (crypto_pk_write_public_key_to_string(private_key, &identity_pkey,
  1133. &identity_pkey_len)<0) {
  1134. warn(LD_BUG,"Writing public key to string failed.");
  1135. goto done;
  1136. }
  1137. if (crypto_pk_get_fingerprint(private_key, fingerprint, 0)<0) {
  1138. err(LD_BUG, "Error computing fingerprint");
  1139. goto done;
  1140. }
  1141. contact = get_options()->ContactInfo;
  1142. if (!contact)
  1143. contact = "(none)";
  1144. len = 2048+strlen(client_versions)+strlen(server_versions)+identity_pkey_len*2;
  1145. len += (RS_ENTRY_LEN)*smartlist_len(rl->routers);
  1146. status = tor_malloc(len);
  1147. tor_snprintf(status, len,
  1148. "network-status-version 2\n"
  1149. "dir-source %s %s %d\n"
  1150. "fingerprint %s\n"
  1151. "contact %s\n"
  1152. "published %s\n"
  1153. "dir-options%s%s\n"
  1154. "client-versions %s\n"
  1155. "server-versions %s\n"
  1156. "dir-signing-key\n%s\n",
  1157. hostname, ipaddr, (int)options->DirPort,
  1158. fingerprint,
  1159. contact,
  1160. published,
  1161. naming ? " Names" : "",
  1162. versioning ? " Versions" : "",
  1163. client_versions,
  1164. server_versions,
  1165. identity_pkey);
  1166. outp = status + strlen(status);
  1167. endp = status + len;
  1168. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1169. int f_exit = router_is_general_exit(ri);
  1170. int f_stable = !router_is_unreliable(ri, 1, 0);
  1171. int f_fast = !router_is_unreliable(ri, 0, 1);
  1172. int f_running;
  1173. int f_authority = router_digest_is_trusted_dir(
  1174. ri->cache_info.identity_digest);
  1175. int f_named = naming && ri->is_named;
  1176. int f_valid = ri->is_verified;
  1177. char identity64[BASE64_DIGEST_LEN+1];
  1178. char digest64[BASE64_DIGEST_LEN+1];
  1179. if (options->AuthoritativeDir) {
  1180. ri->is_running = dirserv_thinks_router_is_reachable(ri, now);
  1181. }
  1182. f_running = ri->is_running;
  1183. format_iso_time(published, ri->cache_info.published_on);
  1184. digest_to_base64(identity64, ri->cache_info.identity_digest);
  1185. digest_to_base64(digest64, ri->cache_info.signed_descriptor_digest);
  1186. in.s_addr = htonl(ri->addr);
  1187. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1188. if (tor_snprintf(outp, endp-outp,
  1189. "r %s %s %s %s %s %d %d\n"
  1190. "s%s%s%s%s%s%s%s\n",
  1191. ri->nickname,
  1192. identity64,
  1193. digest64,
  1194. published,
  1195. ipaddr,
  1196. ri->or_port,
  1197. ri->dir_port,
  1198. f_authority?" Authority":"",
  1199. f_exit?" Exit":"",
  1200. f_fast?" Fast":"",
  1201. f_named?" Named":"",
  1202. f_stable?" Stable":"",
  1203. f_running?" Running":"",
  1204. f_valid?" Valid":"")<0) {
  1205. warn(LD_BUG, "Unable to print router status.");
  1206. goto done;
  1207. }
  1208. outp += strlen(outp);
  1209. });
  1210. if (tor_snprintf(outp, endp-outp, "directory-signature %s\n",
  1211. get_options()->Nickname)<0) {
  1212. warn(LD_BUG, "Unable to write signature line.");
  1213. goto done;
  1214. }
  1215. if (router_get_networkstatus_v2_hash(status, digest)<0) {
  1216. warn(LD_BUG, "Unable to hash network status");
  1217. goto done;
  1218. }
  1219. if (router_append_dirobj_signature(outp,endp-outp,digest,private_key)<0) {
  1220. warn(LD_BUG, "Unable to sign router status.");
  1221. goto done;
  1222. }
  1223. set_cached_dir(&the_v2_networkstatus, status, time(NULL));
  1224. status = NULL; /* So it doesn't get double-freed. */
  1225. the_v2_networkstatus_is_dirty = 0;
  1226. router_set_networkstatus(the_v2_networkstatus.dir, time(NULL), NS_GENERATED,
  1227. NULL);
  1228. r = 0;
  1229. done:
  1230. tor_free(client_versions);
  1231. tor_free(server_versions);
  1232. tor_free(status);
  1233. tor_free(hostname);
  1234. tor_free(identity_pkey);
  1235. return r;
  1236. }
  1237. /** Look for a network status object as specified by <b>key</b>, which should
  1238. * be either "authority" (to find a network status generated by us), a hex
  1239. * identity digest (to find a network status generated by given directory), or
  1240. * "all" (to return all the v2 network status objects we have, concatenated).
  1241. * If <b>compress</b>, find the version compressed with zlib. Return 0 if
  1242. * nothing was found; otherwise set *<b>directory</b> to the matching network
  1243. * status and return its length.
  1244. */
  1245. int
  1246. dirserv_get_networkstatus_v2(smartlist_t *result,
  1247. const char *key)
  1248. {
  1249. tor_assert(result);
  1250. if (!cached_v2_networkstatus)
  1251. cached_v2_networkstatus = digestmap_new();
  1252. if (!(strcmp(key,"authority"))) {
  1253. if (get_options()->AuthoritativeDir) {
  1254. cached_dir_t *d =
  1255. dirserv_pick_cached_dir_obj(NULL,
  1256. &the_v2_networkstatus,
  1257. the_v2_networkstatus_is_dirty,
  1258. generate_v2_networkstatus,
  1259. "network status list", 0);
  1260. if (d)
  1261. smartlist_add(result, d);
  1262. else
  1263. warn(LD_BUG,"Unable to generate an authoritative network status.");
  1264. }
  1265. } else if (!strcmp(key, "all")) {
  1266. digestmap_iter_t *iter;
  1267. if (should_generate_v2_networkstatus())
  1268. generate_v2_networkstatus();
  1269. iter = digestmap_iter_init(cached_v2_networkstatus);
  1270. while (!digestmap_iter_done(iter)) {
  1271. const char *ident;
  1272. void *val;
  1273. digestmap_iter_get(iter, &ident, &val);
  1274. smartlist_add(result, val);
  1275. iter = digestmap_iter_next(cached_v2_networkstatus, iter);
  1276. }
  1277. if (smartlist_len(result) == 0)
  1278. warn(LD_DIRSERV,
  1279. "Client requested 'all' network status objects; we have none.");
  1280. } else if (!strcmpstart(key, "fp/")) {
  1281. smartlist_t *digests = smartlist_create();
  1282. dir_split_resource_into_fingerprints(key+3, digests, NULL, 1);
  1283. SMARTLIST_FOREACH(digests, char *, cp,
  1284. {
  1285. cached_dir_t *cached;
  1286. if (router_digest_is_me(cp) && should_generate_v2_networkstatus())
  1287. generate_v2_networkstatus();
  1288. cached = digestmap_get(cached_v2_networkstatus, cp);
  1289. if (cached) {
  1290. smartlist_add(result, cached);
  1291. } else {
  1292. char hexbuf[HEX_DIGEST_LEN+1];
  1293. base16_encode(hexbuf, sizeof(hexbuf), cp, DIGEST_LEN);
  1294. info(LD_DIRSERV, "Don't know about any network status with fingerprint '%s'", hexbuf);
  1295. }
  1296. tor_free(cp);
  1297. });
  1298. smartlist_free(digests);
  1299. }
  1300. return 0;
  1301. }
  1302. /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
  1303. * <b>key</b>. The key should be either
  1304. * - "/tor/server/authority" for our own routerinfo;
  1305. * - "/tor/server/all" for all the routerinfos we have, concatenated;
  1306. * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
  1307. * hex identity digests; or
  1308. * - "/tor/server/d/D" where D is a plus-separated sequence
  1309. * of server descriptor digests, in hex.
  1310. *
  1311. * Return 0 if we found some matching descriptors, or -1 if we do not
  1312. * have any descriptors, no matching descriptors, or if we did not
  1313. * recognize the key (URL).
  1314. * If -1 is returned *<b>msg</b> will be set to an appropriate error
  1315. * message.
  1316. */
  1317. int
  1318. dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
  1319. const char **msg)
  1320. {
  1321. *msg = NULL;
  1322. if (!strcmp(key, "/tor/server/all")) {
  1323. routerlist_t *rl = router_get_routerlist();
  1324. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1325. smartlist_add(descs_out, &(r->cache_info)));
  1326. } else if (!strcmp(key, "/tor/server/authority")) {
  1327. routerinfo_t *ri = router_get_my_routerinfo();
  1328. if (ri)
  1329. smartlist_add(descs_out, &(ri->cache_info));
  1330. } else if (!strcmpstart(key, "/tor/server/d/")) {
  1331. smartlist_t *digests = smartlist_create();
  1332. key += strlen("/tor/server/d/");
  1333. dir_split_resource_into_fingerprints(key, digests, NULL, 1);
  1334. SMARTLIST_FOREACH(digests, const char *, d,
  1335. {
  1336. signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
  1337. if (sd)
  1338. smartlist_add(descs_out,sd);
  1339. });
  1340. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  1341. smartlist_free(digests);
  1342. } else if (!strcmpstart(key, "/tor/server/fp/")) {
  1343. smartlist_t *digests = smartlist_create();
  1344. key += strlen("/tor/server/fp/");
  1345. dir_split_resource_into_fingerprints(key, digests, NULL, 1);
  1346. SMARTLIST_FOREACH(digests, const char *, d,
  1347. {
  1348. if (router_digest_is_me(d)) {
  1349. smartlist_add(descs_out, &(router_get_my_routerinfo()->cache_info));
  1350. } else {
  1351. routerinfo_t *ri = router_get_by_digest(d);
  1352. if (ri)
  1353. smartlist_add(descs_out, &(ri->cache_info));
  1354. }
  1355. });
  1356. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  1357. smartlist_free(digests);
  1358. } else {
  1359. *msg = "Key not recognized";
  1360. return -1;
  1361. }
  1362. if (!smartlist_len(descs_out)) {
  1363. *msg = "Servers unavailable";
  1364. return -1;
  1365. }
  1366. return 0;
  1367. }
  1368. /** Called when a TLS handshake has completed successfully with a
  1369. * router listening at <b>address</b>:<b>or_port</b>, and has yielded
  1370. * a certificate with digest <b>digest_rcvd</b> and nickname
  1371. * <b>nickname_rcvd</b>. When this happens, it's clear that any other
  1372. * descriptors for that address/port combination must be unusable:
  1373. * delete them if they are not verified.
  1374. *
  1375. * Also, if as_advertised is 1, then inform the reachability checker
  1376. * that we could get to this guy.
  1377. */
  1378. void
  1379. dirserv_orconn_tls_done(const char *address,
  1380. uint16_t or_port,
  1381. const char *digest_rcvd,
  1382. const char *nickname_rcvd,
  1383. int as_advertised)
  1384. {
  1385. int i;
  1386. routerlist_t *rl = router_get_routerlist();
  1387. tor_assert(address);
  1388. tor_assert(digest_rcvd);
  1389. tor_assert(nickname_rcvd);
  1390. // XXXXNM We should really have a better solution here than dropping
  1391. // XXXXNM whole routers; otherwise, they come back way too easily.
  1392. for (i = 0; i < smartlist_len(rl->routers); ++i) {
  1393. routerinfo_t *ri = smartlist_get(rl->routers, i);
  1394. int drop = 0;
  1395. if (strcasecmp(address, ri->address) || or_port != ri->or_port)
  1396. continue;
  1397. if (!ri->is_verified) {
  1398. /* We have a router at the same address! */
  1399. if (strcasecmp(ri->nickname, nickname_rcvd)) {
  1400. notice(LD_DIRSERV, "Dropping descriptor: nickname '%s' does not match nickname '%s' in cert from %s:%d",
  1401. ri->nickname, nickname_rcvd, address, or_port);
  1402. drop = 1;
  1403. } else if (memcmp(ri->cache_info.identity_digest, digest_rcvd,
  1404. DIGEST_LEN)) {
  1405. notice(LD_DIRSERV, "Dropping descriptor: identity key does not match key in cert from %s:%d",
  1406. address, or_port);
  1407. drop = 1;
  1408. }
  1409. }
  1410. if (drop) {
  1411. routerlist_remove(rl, ri, i--, 0);
  1412. directory_set_dirty();
  1413. } else { /* correct nickname and digest. mark this router reachable! */
  1414. info(LD_DIRSERV,"Found router %s to be reachable. Yay.", ri->nickname);
  1415. ri->last_reachable = time(NULL);
  1416. ri->num_unreachable_notifications = 0;
  1417. }
  1418. }
  1419. }
  1420. /** Release all storage used by the directory server. */
  1421. void
  1422. dirserv_free_all(void)
  1423. {
  1424. if (fingerprint_list) {
  1425. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, fp,
  1426. { tor_free(fp->nickname);
  1427. tor_free(fp->fingerprint);
  1428. tor_free(fp); });
  1429. smartlist_free(fingerprint_list);
  1430. fingerprint_list = NULL;
  1431. }
  1432. if (authdir_reject_policy)
  1433. addr_policy_free(authdir_reject_policy);
  1434. if (authdir_invalid_policy)
  1435. addr_policy_free(authdir_invalid_policy);
  1436. clear_cached_dir(&the_directory);
  1437. clear_cached_dir(&the_runningrouters);
  1438. clear_cached_dir(&the_v2_networkstatus);
  1439. clear_cached_dir(&cached_directory);
  1440. clear_cached_dir(&cached_runningrouters);
  1441. if (cached_v2_networkstatus) {
  1442. digestmap_free(cached_v2_networkstatus, free_cached_dir);
  1443. cached_v2_networkstatus = NULL;
  1444. }
  1445. }