dirserv.c 50 KB

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