dirserv.c 45 KB

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