dirserv.c 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968
  1. /* Copyright 2001-2004 Roger Dingledine.
  2. * Copyright 2004-2006 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char dirserv_c_id[] =
  6. "$Id$";
  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)
  15. /** How many seconds do we wait before regenerating the directory? */
  16. #define DIR_REGEN_SLACK_TIME 30
  17. /** If we're a cache, keep this many networkstatuses around from non-trusted
  18. * directory authorities. */
  19. #define MAX_UNTRUSTED_NETWORKSTATUSES 16
  20. extern long stats_n_seconds_working;
  21. typedef enum {
  22. FP_NAMED, /**< Listed in fingerprint file. */
  23. FP_VALID, /**< Unlisted but believed valid. */
  24. FP_INVALID, /**< Believed invalid. */
  25. FP_REJECT, /**< We will not publish this router. */
  26. } router_status_t;
  27. /** Do we need to regenerate the directory when someone asks for it? */
  28. static int the_directory_is_dirty = 1;
  29. static int runningrouters_is_dirty = 1;
  30. static int the_v2_networkstatus_is_dirty = 1;
  31. static void directory_remove_invalid(void);
  32. static cached_dir_t *dirserv_regenerate_directory(void);
  33. static char *format_versions_list(config_line_t *ln);
  34. /* Should be static; exposed for testing */
  35. int add_fingerprint_to_dir(const char *nickname, const char *fp,
  36. smartlist_t *list);
  37. static router_status_t dirserv_router_get_status(const routerinfo_t *router,
  38. const char **msg);
  39. static router_status_t
  40. dirserv_get_status_impl(const char *fp, const char *nickname,
  41. const char *address,
  42. uint32_t addr, uint16_t or_port,
  43. const char *platform, const char *contact,
  44. const char **msg, int should_log);
  45. static int dirserv_thinks_router_is_reachable(routerinfo_t *router,
  46. time_t now);
  47. static void clear_cached_dir(cached_dir_t *d);
  48. /************** Fingerprint handling code ************/
  49. /** A member of fingerprint_list: maps a name to a fingerprint.
  50. **/
  51. typedef struct fingerprint_entry_t {
  52. char *nickname; /**< The name of a router (if this fingerprint is bound to a
  53. * name); the string "!reject" (if this fingerprint should
  54. * always be rejected); or the string "!invalid" (if this
  55. * fingerprint should be accepted but never marked as
  56. * valid. */
  57. char *fingerprint; /**< Stored as HEX_DIGEST_LEN characters, followed by a
  58. * NUL */
  59. } fingerprint_entry_t;
  60. /** List of nickname-\>identity fingerprint mappings for all the routers
  61. * that we name. Used to prevent router impersonation. */
  62. /* Should be static; exposed for testing */
  63. smartlist_t *fingerprint_list = NULL;
  64. /** Add the fingerprint <b>fp</b> for the nickname <b>nickname</b> to
  65. * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
  66. * new, or 1 if we replaced the old value.
  67. */
  68. int /* Should be static; exposed for testing */
  69. add_fingerprint_to_dir(const char *nickname, const char *fp, smartlist_t *list)
  70. {
  71. int i;
  72. fingerprint_entry_t *ent;
  73. char *fingerprint;
  74. tor_assert(nickname);
  75. tor_assert(fp);
  76. tor_assert(list);
  77. fingerprint = tor_strdup(fp);
  78. tor_strstrip(fingerprint, " ");
  79. if (nickname[0] != '!') {
  80. for (i = 0; i < smartlist_len(list); ++i) {
  81. ent = smartlist_get(list, i);
  82. if (!strcasecmp(ent->nickname,nickname)) {
  83. tor_free(ent->fingerprint);
  84. ent->fingerprint = fingerprint;
  85. return 1;
  86. }
  87. }
  88. }
  89. ent = tor_malloc(sizeof(fingerprint_entry_t));
  90. ent->nickname = tor_strdup(nickname);
  91. ent->fingerprint = fingerprint;
  92. smartlist_add(list, ent);
  93. return 0;
  94. }
  95. /** Add the nickname and fingerprint for this OR to the
  96. * global list of recognized identity key fingerprints. */
  97. int
  98. dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk)
  99. {
  100. char fp[FINGERPRINT_LEN+1];
  101. if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
  102. log_err(LD_BUG, "Error computing fingerprint");
  103. return -1;
  104. }
  105. if (!fingerprint_list)
  106. fingerprint_list = smartlist_create();
  107. add_fingerprint_to_dir(nickname, fp, fingerprint_list);
  108. return 0;
  109. }
  110. /** Parse the nickname-\>fingerprint mappings stored in the file named
  111. * <b>fname</b>. The file format is line-based, with each non-blank
  112. * holding one nickname, some space, and a fingerprint for that
  113. * nickname. On success, replace the current fingerprint list with
  114. * the contents of <b>fname</b> and return 0. On failure, leave the
  115. * current fingerprint list untouched, and return -1. */
  116. int
  117. dirserv_parse_fingerprint_file(const char *fname)
  118. {
  119. char *cf;
  120. char *nickname, *fingerprint;
  121. smartlist_t *fingerprint_list_new;
  122. int result;
  123. config_line_t *front=NULL, *list;
  124. cf = read_file_to_str(fname, 0);
  125. if (!cf) {
  126. if (get_options()->NamingAuthoritativeDir) {
  127. log_warn(LD_FS, "Cannot open fingerprint file '%s'. Failing.", fname);
  128. return -1;
  129. } else {
  130. log_info(LD_FS, "Cannot open fingerprint file '%s'. Returning.", fname);
  131. return 0;
  132. }
  133. }
  134. result = config_get_lines(cf, &front);
  135. tor_free(cf);
  136. if (result < 0) {
  137. log_warn(LD_CONFIG, "Error reading from fingerprint file");
  138. return -1;
  139. }
  140. fingerprint_list_new = smartlist_create();
  141. for (list=front; list; list=list->next) {
  142. nickname = list->key; fingerprint = list->value;
  143. if (strlen(nickname) > MAX_NICKNAME_LEN) {
  144. log_notice(LD_CONFIG,
  145. "Nickname '%s' too long in fingerprint file. Skipping.",
  146. nickname);
  147. continue;
  148. }
  149. if (!is_legal_nickname(nickname) &&
  150. strcasecmp(nickname, "!reject") &&
  151. strcasecmp(nickname, "!invalid")) {
  152. log_notice(LD_CONFIG,
  153. "Invalid nickname '%s' in fingerprint file. Skipping.",
  154. nickname);
  155. continue;
  156. }
  157. if (strlen(fingerprint) != FINGERPRINT_LEN ||
  158. !crypto_pk_check_fingerprint_syntax(fingerprint)) {
  159. log_notice(LD_CONFIG,
  160. "Invalid fingerprint (nickname '%s', "
  161. "fingerprint %s). Skipping.",
  162. nickname, fingerprint);
  163. continue;
  164. }
  165. if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
  166. /* If you approved an OR called "client", then clients who use
  167. * the default nickname could all be rejected. That's no good. */
  168. log_notice(LD_CONFIG,
  169. "Authorizing a nickname '%s' would break "
  170. "many clients; skipping.",
  171. DEFAULT_CLIENT_NICKNAME);
  172. continue;
  173. }
  174. if (add_fingerprint_to_dir(nickname, fingerprint, fingerprint_list_new)
  175. != 0)
  176. log_notice(LD_CONFIG, "Duplicate nickname '%s'.", nickname);
  177. }
  178. config_free_lines(front);
  179. dirserv_free_fingerprint_list();
  180. fingerprint_list = fingerprint_list_new;
  181. /* Delete any routers whose fingerprints we no longer recognize */
  182. directory_remove_invalid();
  183. return 0;
  184. }
  185. /** Check whether <b>router</b> has a nickname/identity key combination that
  186. * we recognize from the fingerprint list, or an IP we automatically act on
  187. * according to our configuration. Return the appropriate router status.
  188. *
  189. * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
  190. * *<b>msg</b> to an explanation of why. */
  191. static router_status_t
  192. dirserv_router_get_status(const routerinfo_t *router, const char **msg)
  193. {
  194. char fingerprint[FINGERPRINT_LEN+1];
  195. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 0)) {
  196. log_warn(LD_BUG,"Error computing fingerprint");
  197. return -1;
  198. }
  199. return dirserv_get_status_impl(fingerprint, router->nickname,
  200. router->address,
  201. router->addr, router->or_port,
  202. router->platform, router->contact_info,
  203. msg, 1);
  204. }
  205. /** Return true if there is no point in downloading the router described by
  206. * <b>rs</b> because this directory would reject it. */
  207. int
  208. dirserv_would_reject_router(routerstatus_t *rs)
  209. {
  210. char fp[FINGERPRINT_LEN+1];
  211. router_status_t res;
  212. base16_encode(fp, sizeof(fp), rs->identity_digest, DIGEST_LEN);
  213. res = dirserv_get_status_impl(fp, rs->nickname,
  214. "", /* address is only used in logs */
  215. rs->addr, rs->or_port,
  216. NULL, NULL,
  217. NULL, 0);
  218. return (res == FP_REJECT);
  219. }
  220. /** Helper: As dirserv_get_router_status, but takes the router fingerprint
  221. * (hex, no spaces), nickname, address (used for logging only), IP address, OR
  222. * port, platform (logging only) and contact info (logging only) as arguments.
  223. *
  224. * If should_log is false, do not log messages. (There's not much point in
  225. * logging that we're rejecting servers we'll not download.)
  226. */
  227. static router_status_t
  228. dirserv_get_status_impl(const char *fp, const char *nickname,
  229. const char *address,
  230. uint32_t addr, uint16_t or_port,
  231. const char *platform, const char *contact,
  232. const char **msg, int should_log)
  233. {
  234. fingerprint_entry_t *nn_ent = NULL, *fp_ent = NULL;
  235. int reject_unlisted = get_options()->AuthDirRejectUnlisted;
  236. if (!fingerprint_list)
  237. fingerprint_list = smartlist_create();
  238. if (should_log)
  239. log_debug(LD_DIRSERV, "%d fingerprints known.",
  240. smartlist_len(fingerprint_list));
  241. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t *, ent,
  242. {
  243. if (!strcasecmp(fp,ent->fingerprint))
  244. fp_ent = ent;
  245. if (!strcasecmp(nickname,ent->nickname))
  246. nn_ent = ent;
  247. });
  248. if (fp_ent) {
  249. if (!strcasecmp(fp_ent->nickname, "!reject")) {
  250. if (msg)
  251. *msg = "Fingerprint is marked rejected";
  252. return FP_REJECT;
  253. } else if (!strcasecmp(fp_ent->nickname, "!invalid")) {
  254. if (msg)
  255. *msg = "Fingerprint is marked invalid";
  256. return FP_INVALID;
  257. }
  258. }
  259. if (!nn_ent) { /* No such server known with that nickname */
  260. if (!authdir_policy_permits_address(addr, or_port)) {
  261. if (should_log)
  262. log_info(LD_DIRSERV, "Rejecting '%s' because of address '%s'",
  263. nickname, address);
  264. if (msg)
  265. *msg = "Authdir is rejecting routers in this range.";
  266. return FP_REJECT;
  267. }
  268. if (!authdir_policy_valid_address(addr, or_port)) {
  269. if (should_log)
  270. log_info(LD_DIRSERV, "Not marking '%s' valid because of address '%s'",
  271. nickname, address);
  272. return FP_INVALID;
  273. }
  274. if (should_log)
  275. log_debug(LD_DIRSERV,"No fingerprint found for '%s'",nickname);
  276. if (!platform || tor_version_as_new_as(platform,"0.1.0.2-rc"))
  277. return reject_unlisted ? FP_REJECT : FP_VALID;
  278. else
  279. return FP_INVALID;
  280. }
  281. if (0==strcasecmp(nn_ent->fingerprint, fp)) {
  282. if (should_log)
  283. log_debug(LD_DIRSERV,"Good fingerprint for '%s'",nickname);
  284. return FP_NAMED; /* Right fingerprint. */
  285. } else {
  286. if (should_log) {
  287. char *esc_contact = esc_for_log(contact);
  288. log_warn(LD_DIRSERV,
  289. "Mismatched fingerprint for '%s': expected '%s' got '%s'. "
  290. "ContactInfo '%s', platform '%s'.)",
  291. nickname, nn_ent->fingerprint, fp,
  292. esc_contact,
  293. platform ? escaped(platform) : "");
  294. tor_free(esc_contact);
  295. }
  296. if (msg)
  297. *msg = "Rejected: There is already a named server with this nickname "
  298. "and a different fingerprint.";
  299. return FP_REJECT; /* Wrong fingerprint. */
  300. }
  301. }
  302. /** If we are an authoritative dirserver, and the list of approved
  303. * servers contains one whose identity key digest is <b>digest</b>,
  304. * return that router's nickname. Otherwise return NULL. */
  305. const char *
  306. dirserv_get_nickname_by_digest(const char *digest)
  307. {
  308. char hexdigest[HEX_DIGEST_LEN+1];
  309. if (!fingerprint_list)
  310. return NULL;
  311. tor_assert(digest);
  312. base16_encode(hexdigest, HEX_DIGEST_LEN+1, digest, DIGEST_LEN);
  313. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, ent,
  314. { if (!strcasecmp(hexdigest, ent->fingerprint))
  315. return ent->nickname; } );
  316. return NULL;
  317. }
  318. /** Clear the current fingerprint list. */
  319. void
  320. dirserv_free_fingerprint_list(void)
  321. {
  322. int i;
  323. fingerprint_entry_t *ent;
  324. if (!fingerprint_list)
  325. return;
  326. for (i = 0; i < smartlist_len(fingerprint_list); ++i) {
  327. ent = smartlist_get(fingerprint_list, i);
  328. tor_free(ent->nickname);
  329. tor_free(ent->fingerprint);
  330. tor_free(ent);
  331. }
  332. smartlist_free(fingerprint_list);
  333. fingerprint_list = NULL;
  334. }
  335. /*
  336. * Descriptor list
  337. */
  338. /** Return -1 if <b>ri</b> has a private or otherwise bad address,
  339. * unless we're configured to not care. Return 0 if all ok. */
  340. static int
  341. dirserv_router_has_valid_address(routerinfo_t *ri)
  342. {
  343. struct in_addr iaddr;
  344. if (get_options()->DirAllowPrivateAddresses)
  345. return 0; /* whatever it is, we're fine with it */
  346. if (!tor_inet_aton(ri->address, &iaddr)) {
  347. log_info(LD_DIRSERV,"Router '%s' published non-IP address '%s'. Refusing.",
  348. ri->nickname, ri->address);
  349. return -1;
  350. }
  351. if (is_internal_IP(ntohl(iaddr.s_addr), 0)) {
  352. log_info(LD_DIRSERV,
  353. "Router '%s' published internal IP address '%s'. Refusing.",
  354. ri->nickname, ri->address);
  355. return -1; /* it's a private IP, we should reject it */
  356. }
  357. return 0;
  358. }
  359. /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
  360. * set its is_valid,named,running fields and return 0. Otherwise, return -1.
  361. *
  362. * If the router is rejected, set *<b>msg</b> to an explanation of why.
  363. *
  364. * If <b>complain</b> then explain at log-level 'notice' why we refused
  365. * a descriptor; else explain at log-level 'info'.
  366. */
  367. int
  368. authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
  369. int complain)
  370. {
  371. /* Okay. Now check whether the fingerprint is recognized. */
  372. router_status_t status = dirserv_router_get_status(ri, msg);
  373. time_t now;
  374. int severity = complain ? LOG_NOTICE : LOG_INFO;
  375. tor_assert(msg);
  376. if (status == FP_REJECT)
  377. return -1; /* msg is already set. */
  378. /* Is there too much clock skew? */
  379. now = time(NULL);
  380. if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
  381. log_fn(severity, LD_DIRSERV, "Publication time for nickname '%s' is too "
  382. "far (%d minutes) in the future; possible clock skew. Not adding "
  383. "(%s)",
  384. ri->nickname, (int)((ri->cache_info.published_on-now)/60),
  385. esc_router_info(ri));
  386. *msg = "Rejected: Your clock is set too far in the future, or your "
  387. "timezone is not correct.";
  388. return -1;
  389. }
  390. if (ri->cache_info.published_on < now-ROUTER_MAX_AGE_TO_PUBLISH) {
  391. log_fn(severity, LD_DIRSERV,
  392. "Publication time for router with nickname '%s' is too far "
  393. "(%d minutes) in the past. Not adding (%s)",
  394. ri->nickname, (int)((now-ri->cache_info.published_on)/60),
  395. esc_router_info(ri));
  396. *msg = "Rejected: Server is expired, or your clock is too far in the past,"
  397. " or your timezone is not correct.";
  398. return -1;
  399. }
  400. if (dirserv_router_has_valid_address(ri) < 0) {
  401. log_fn(severity, LD_DIRSERV,
  402. "Router with nickname '%s' has invalid address '%s'. "
  403. "Not adding (%s).",
  404. ri->nickname, ri->address,
  405. esc_router_info(ri));
  406. *msg = "Rejected: Address is not an IP, or IP is a private address.";
  407. return -1;
  408. }
  409. /* Okay, looks like we're willing to accept this one. */
  410. switch (status) {
  411. case FP_NAMED:
  412. ri->is_named = ri->is_valid = 1;
  413. break;
  414. case FP_VALID:
  415. ri->is_named = 0;
  416. ri->is_valid = 1;
  417. break;
  418. case FP_INVALID:
  419. ri->is_named = ri->is_valid = 0;
  420. break;
  421. default:
  422. tor_assert(0);
  423. }
  424. return 0;
  425. }
  426. /** Parse the server descriptor at <b>desc</b> and maybe insert it into
  427. * the list of server descriptors. Set *<b>msg</b> to a message that
  428. * should be passed back to the origin of this descriptor.
  429. *
  430. * Return 2 if descriptor is well-formed and accepted;
  431. * 1 if well-formed and accepted but origin should hear *msg;
  432. * 0 if well-formed but redundant with one we already have;
  433. * -1 if it looks vaguely like a router descriptor but rejected;
  434. * -2 if we can't find a router descriptor in <b>desc</b>.
  435. */
  436. int
  437. dirserv_add_descriptor(const char *desc, const char **msg)
  438. {
  439. int r;
  440. routerinfo_t *ri = NULL, *ri_old = NULL;
  441. tor_assert(msg);
  442. *msg = NULL;
  443. /* Check: is the descriptor syntactically valid? */
  444. ri = router_parse_entry_from_string(desc, NULL);
  445. if (!ri) {
  446. log_warn(LD_DIRSERV, "Couldn't parse uploaded server descriptor");
  447. *msg = "Rejected: Couldn't parse server descriptor.";
  448. return -2;
  449. }
  450. /* Check whether this descriptor is semantically identical to the last one
  451. * from this server. (We do this here and not in router_add_to_routerlist
  452. * because we want to be able to accept the newest router descriptor that
  453. * another authority has, so we all converge on the same one.) */
  454. ri_old = router_get_by_digest(ri->cache_info.identity_digest);
  455. if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
  456. && router_differences_are_cosmetic(ri_old, ri)
  457. && !router_is_me(ri)) {
  458. log_info(LD_DIRSERV,
  459. "Not replacing descriptor from '%s'; differences are cosmetic.",
  460. ri->nickname);
  461. *msg = "Not replacing router descriptor; no information has changed since "
  462. "the last one with this identity.";
  463. routerinfo_free(ri);
  464. control_event_or_authdir_new_descriptor("DROPPED", desc, *msg);
  465. return 0;
  466. }
  467. if ((r = router_add_to_routerlist(ri, msg, 0, 0))<0) {
  468. if (r < -1) /* unless the routerinfo was fine, just out-of-date */
  469. control_event_or_authdir_new_descriptor("REJECTED", desc, *msg);
  470. return r == -1 ? 0 : -1;
  471. } else {
  472. smartlist_t *changed;
  473. control_event_or_authdir_new_descriptor("ACCEPTED", desc, *msg);
  474. changed = smartlist_create();
  475. smartlist_add(changed, ri);
  476. control_event_descriptors_changed(changed);
  477. smartlist_free(changed);
  478. if (!*msg) {
  479. *msg = ri->is_valid ? "Descriptor for valid server accepted" :
  480. "Descriptor for invalid server accepted";
  481. }
  482. return r == 0 ? 2 : 1;
  483. }
  484. }
  485. /** Remove all descriptors whose nicknames or fingerprints no longer
  486. * are allowed by our fingerprint list. (Descriptors that used to be
  487. * good can become bad when we reload the fingerprint list.)
  488. */
  489. static void
  490. directory_remove_invalid(void)
  491. {
  492. int i;
  493. int changed = 0;
  494. routerlist_t *rl = router_get_routerlist();
  495. for (i = 0; i < smartlist_len(rl->routers); ++i) {
  496. const char *msg;
  497. routerinfo_t *ent = smartlist_get(rl->routers, i);
  498. router_status_t r = dirserv_router_get_status(ent, &msg);
  499. switch (r) {
  500. case FP_REJECT:
  501. log_info(LD_DIRSERV, "Router '%s' is now rejected: %s",
  502. ent->nickname, msg?msg:"");
  503. routerlist_remove(rl, ent, i--, 0);
  504. changed = 1;
  505. break;
  506. case FP_NAMED:
  507. if (!ent->is_valid || !ent->is_named) {
  508. log_info(LD_DIRSERV,
  509. "Router '%s' is now valid and named.", ent->nickname);
  510. ent->is_valid = ent->is_named = 1;
  511. changed = 1;
  512. }
  513. break;
  514. case FP_VALID:
  515. if (!ent->is_valid || ent->is_named) {
  516. log_info(LD_DIRSERV, "Router '%s' is now valid.", ent->nickname);
  517. ent->is_valid = 1;
  518. ent->is_named = 0;
  519. changed = 1;
  520. }
  521. break;
  522. case FP_INVALID:
  523. if (ent->is_valid || ent->is_named) {
  524. log_info(LD_DIRSERV,
  525. "Router '%s' is no longer valid.", ent->nickname);
  526. ent->is_valid = ent->is_named = 0;
  527. changed = 1;
  528. }
  529. break;
  530. }
  531. }
  532. if (changed)
  533. directory_set_dirty();
  534. }
  535. /** Write a list of unregistered descriptors into a newly allocated
  536. * string and return it. Used by dirserv operators to keep track of
  537. * fast nodes that haven't registered.
  538. */
  539. char *
  540. dirserver_getinfo_unregistered(const char *question)
  541. {
  542. router_status_t r;
  543. smartlist_t *answerlist;
  544. char buf[1024];
  545. char *answer;
  546. int min_bw = atoi(question);
  547. routerlist_t *rl = router_get_routerlist();
  548. answerlist = smartlist_create();
  549. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ent, {
  550. r = dirserv_router_get_status(ent, NULL);
  551. if (router_get_advertised_bandwidth(ent) >= (size_t)min_bw &&
  552. r != FP_NAMED) {
  553. /* then log this one */
  554. tor_snprintf(buf, sizeof(buf),
  555. "%s: BW %d on '%s'.",
  556. ent->nickname, router_get_advertised_bandwidth(ent),
  557. ent->platform ? ent->platform : "");
  558. smartlist_add(answerlist, tor_strdup(buf));
  559. }
  560. });
  561. answer = smartlist_join_strings(answerlist, "\r\n", 0, NULL);
  562. SMARTLIST_FOREACH(answerlist, char *, cp, tor_free(cp));
  563. smartlist_free(answerlist);
  564. return answer;
  565. }
  566. /** Mark the directory as <b>dirty</b> -- when we're next asked for a
  567. * directory, we will rebuild it instead of reusing the most recently
  568. * generated one.
  569. */
  570. void
  571. directory_set_dirty(void)
  572. {
  573. time_t now = time(NULL);
  574. if (!the_directory_is_dirty)
  575. the_directory_is_dirty = now;
  576. if (!runningrouters_is_dirty)
  577. runningrouters_is_dirty = now;
  578. if (!the_v2_networkstatus_is_dirty)
  579. the_v2_networkstatus_is_dirty = now;
  580. }
  581. /**
  582. * Allocate and return a description of the status of the server <b>desc</b>,
  583. * for use in a router-status line. The server is listed
  584. * as running iff <b>is_live</b> is true.
  585. */
  586. static char *
  587. list_single_server_status(routerinfo_t *desc, int is_live)
  588. {
  589. char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
  590. char *cp;
  591. tor_assert(desc);
  592. cp = buf;
  593. if (!is_live) {
  594. *cp++ = '!';
  595. }
  596. if (desc->is_valid) {
  597. strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
  598. cp += strlen(cp);
  599. *cp++ = '=';
  600. }
  601. *cp++ = '$';
  602. base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
  603. DIGEST_LEN);
  604. return tor_strdup(buf);
  605. }
  606. /** Each server needs to have passed a reachability test no more
  607. * than this number of seconds ago, or he is listed as down in
  608. * the directory. */
  609. #define REACHABLE_TIMEOUT (45*60)
  610. /** Treat a router as alive if
  611. * - It's me, and I'm not hibernating.
  612. * or - We've found it reachable recently. */
  613. static int
  614. dirserv_thinks_router_is_reachable(routerinfo_t *router, time_t now)
  615. {
  616. if (router_is_me(router) && !we_are_hibernating())
  617. return 1;
  618. return get_options()->AssumeReachable ||
  619. now < router->last_reachable + REACHABLE_TIMEOUT;
  620. }
  621. /** Return 1 if we're confident that there's a problem with
  622. * <b>router</b>'s reachability and its operator should be notified.
  623. */
  624. int
  625. dirserv_thinks_router_is_blatantly_unreachable(routerinfo_t *router,
  626. time_t now)
  627. {
  628. if (router->is_hibernating)
  629. return 0;
  630. if (now >= router->last_reachable + 4*REACHABLE_TIMEOUT &&
  631. router->testing_since &&
  632. now >= router->testing_since + 4*REACHABLE_TIMEOUT)
  633. return 1;
  634. return 0;
  635. }
  636. /** Based on the routerinfo_ts in <b>routers</b>, allocate the
  637. * contents of a router-status line, and store it in
  638. * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
  639. */
  640. int
  641. list_server_status(smartlist_t *routers, char **router_status_out)
  642. {
  643. /* List of entries in a router-status style: An optional !, then an optional
  644. * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
  645. smartlist_t *rs_entries;
  646. time_t now = time(NULL);
  647. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  648. int authdir_mode = get_options()->AuthoritativeDir;
  649. tor_assert(router_status_out);
  650. rs_entries = smartlist_create();
  651. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  652. {
  653. if (authdir_mode) {
  654. /* Update router status in routerinfo_t. */
  655. ri->is_running = dirserv_thinks_router_is_reachable(ri, now);
  656. }
  657. if (ri->cache_info.published_on >= cutoff)
  658. smartlist_add(rs_entries, list_single_server_status(ri, ri->is_running));
  659. });
  660. *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
  661. SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
  662. smartlist_free(rs_entries);
  663. return 0;
  664. }
  665. /* Given a (possibly empty) list of config_line_t, each line of which contains
  666. * a list of comma-separated version numbers surrounded by optional space,
  667. * allocate and return a new string containing the version numbers, in order,
  668. * separated by commas. Used to generate Recommended(Client|Server)?Versions
  669. */
  670. static char *
  671. format_versions_list(config_line_t *ln)
  672. {
  673. smartlist_t *versions;
  674. char *result;
  675. versions = smartlist_create();
  676. for ( ; ln; ln = ln->next) {
  677. smartlist_split_string(versions, ln->value, ",",
  678. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  679. }
  680. sort_version_list(versions, 1);
  681. result = smartlist_join_strings(versions,",",0,NULL);
  682. SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
  683. smartlist_free(versions);
  684. return result;
  685. }
  686. /** Return 1 if <b>ri</b>'s descriptor is worth including in the v1
  687. * directory, else return 0.
  688. */
  689. static int
  690. live_enough_for_v1_dir(routerinfo_t *ri, time_t now)
  691. {
  692. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  693. if (ri->cache_info.published_on < cutoff)
  694. return 0;
  695. if (!ri->is_running || !ri->is_valid)
  696. return 0;
  697. return 1;
  698. }
  699. /** Generate a new v1 directory and write it into a newly allocated string.
  700. * Point *<b>dir_out</b> to the allocated string. Sign the
  701. * directory with <b>private_key</b>. Return 0 on success, -1 on
  702. * failure. If <b>complete</b> is set, give us all the descriptors;
  703. * otherwise leave out non-running and non-valid ones.
  704. */
  705. int
  706. dirserv_dump_directory_to_string(char **dir_out,
  707. crypto_pk_env_t *private_key, int complete)
  708. {
  709. char *cp;
  710. char *router_status;
  711. char *identity_pkey; /* Identity key, DER64-encoded. */
  712. char *recommended_versions;
  713. char digest[DIGEST_LEN];
  714. char published[ISO_TIME_LEN+1];
  715. char *buf = NULL;
  716. size_t buf_len;
  717. size_t identity_pkey_len;
  718. routerlist_t *rl = router_get_routerlist();
  719. time_t now = time(NULL);
  720. tor_assert(dir_out);
  721. *dir_out = NULL;
  722. if (list_server_status(rl->routers, &router_status))
  723. return -1;
  724. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  725. &identity_pkey_len)<0) {
  726. log_warn(LD_BUG,"write identity_pkey to string failed!");
  727. return -1;
  728. }
  729. recommended_versions =
  730. format_versions_list(get_options()->RecommendedVersions);
  731. format_iso_time(published, now);
  732. buf_len = 2048+strlen(recommended_versions)+
  733. strlen(router_status);
  734. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  735. if (complete || live_enough_for_v1_dir(ri, now))
  736. buf_len += ri->cache_info.signed_descriptor_len+1);
  737. buf = tor_malloc(buf_len);
  738. /* We'll be comparing against buf_len throughout the rest of the
  739. function, though strictly speaking we shouldn't be able to exceed
  740. it. This is C, after all, so we may as well check for buffer
  741. overruns.*/
  742. tor_snprintf(buf, buf_len,
  743. "signed-directory\n"
  744. "published %s\n"
  745. "recommended-software %s\n"
  746. "router-status %s\n"
  747. "dir-signing-key\n%s\n",
  748. published, recommended_versions, router_status,
  749. identity_pkey);
  750. tor_free(recommended_versions);
  751. tor_free(router_status);
  752. tor_free(identity_pkey);
  753. cp = buf + strlen(buf);
  754. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  755. {
  756. size_t len = ri->cache_info.signed_descriptor_len;
  757. const char *body;
  758. if (!complete && !live_enough_for_v1_dir(ri, now))
  759. continue;
  760. if (cp+len+1 >= buf+buf_len)
  761. goto truncated;
  762. body = signed_descriptor_get_body(&ri->cache_info);
  763. memcpy(cp, body, len);
  764. cp += len;
  765. *cp++ = '\n'; /* add an extra newline in case somebody was depending on
  766. * it. */
  767. });
  768. *cp = '\0';
  769. /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
  770. signature. */
  771. if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
  772. goto truncated;
  773. if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
  774. goto truncated;
  775. if (strlcat(buf, "\n", buf_len) >= buf_len)
  776. goto truncated;
  777. if (router_get_dir_hash(buf,digest)) {
  778. log_warn(LD_BUG,"couldn't compute digest");
  779. tor_free(buf);
  780. return -1;
  781. }
  782. if (router_append_dirobj_signature(buf,buf_len,digest,private_key)<0) {
  783. tor_free(buf);
  784. return -1;
  785. }
  786. *dir_out = buf;
  787. return 0;
  788. truncated:
  789. log_warn(LD_BUG,"tried to exceed string length.");
  790. tor_free(buf);
  791. return -1;
  792. }
  793. /** Most recently generated encoded signed directory. (auth dirservers only.)*/
  794. static cached_dir_t *the_directory = NULL;
  795. /* Used only by non-auth dirservers: The directory and runningrouters we'll
  796. * serve when requested. */
  797. static cached_dir_t *cached_directory = NULL;
  798. static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0, -1 };
  799. /* Used for other dirservers' v2 network statuses. Map from hexdigest to
  800. * cached_dir_t. */
  801. static digestmap_t *cached_v2_networkstatus = NULL;
  802. /** Possibly replace the contents of <b>d</b> with the value of
  803. * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
  804. * the last value, or too far in the future.
  805. *
  806. * Does not copy <b>directory</b>; free it if it isn't used.
  807. */
  808. static void
  809. set_cached_dir(cached_dir_t *d, char *directory, time_t when)
  810. {
  811. time_t now = time(NULL);
  812. if (when<=d->published) {
  813. log_info(LD_DIRSERV, "Ignoring old directory; not caching.");
  814. tor_free(directory);
  815. } else if (when>=now+ROUTER_MAX_AGE_TO_PUBLISH) {
  816. log_info(LD_DIRSERV, "Ignoring future directory; not caching.");
  817. tor_free(directory);
  818. } else {
  819. /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
  820. log_debug(LD_DIRSERV, "Caching directory.");
  821. tor_free(d->dir);
  822. d->dir = directory;
  823. d->dir_len = strlen(directory);
  824. tor_free(d->dir_z);
  825. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  826. ZLIB_METHOD)) {
  827. log_warn(LD_BUG,"Error compressing cached directory");
  828. }
  829. d->published = when;
  830. }
  831. }
  832. /** DOCDOC */
  833. void
  834. cached_dir_decref(cached_dir_t *d)
  835. {
  836. if (!d || --d->refcnt > 0)
  837. return;
  838. clear_cached_dir(d);
  839. tor_free(d);
  840. }
  841. /** DOCDOC */
  842. static cached_dir_t *
  843. new_cached_dir(char *s, time_t published)
  844. {
  845. cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
  846. d->refcnt = 1;
  847. d->dir = s;
  848. d->dir_len = strlen(s);
  849. d->published = published;
  850. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  851. ZLIB_METHOD)) {
  852. log_warn(LD_BUG, "Error compressing directory");
  853. }
  854. return d;
  855. }
  856. /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
  857. static void
  858. clear_cached_dir(cached_dir_t *d)
  859. {
  860. tor_free(d->dir);
  861. tor_free(d->dir_z);
  862. memset(d, 0, sizeof(cached_dir_t));
  863. }
  864. /** Free all storage held by the cached_dir_t in <b>d</b>. */
  865. static void
  866. _free_cached_dir(void *_d)
  867. {
  868. cached_dir_t *d = (cached_dir_t *)_d;
  869. cached_dir_decref(d);
  870. }
  871. /** If we have no cached directory, or it is older than <b>when</b>, then
  872. * replace it with <b>directory</b>, published at <b>when</b>.
  873. */
  874. void
  875. dirserv_set_cached_directory(const char *directory, time_t published,
  876. int is_running_routers)
  877. {
  878. if (is_running_routers) {
  879. set_cached_dir(&cached_runningrouters, tor_strdup(directory), published);
  880. } else {
  881. cached_dir_decref(cached_directory);
  882. cached_directory = new_cached_dir(tor_strdup(directory), published);
  883. }
  884. }
  885. /** We've just received a v2 network-status for an authoritative directory
  886. * with identity digest <b>identity</b> published at
  887. * <b>published</b>. Store it so we can serve it to others. If
  888. * <b>directory</b> is NULL, remove the entry with the given fingerprint from
  889. * the cache.
  890. */
  891. void
  892. dirserv_set_cached_networkstatus_v2(const char *networkstatus,
  893. const char *identity,
  894. time_t published)
  895. {
  896. cached_dir_t *d, *old_d;
  897. smartlist_t *trusted_dirs;
  898. if (!cached_v2_networkstatus)
  899. cached_v2_networkstatus = digestmap_new();
  900. old_d = digestmap_get(cached_v2_networkstatus, identity);
  901. if (!old_d && !networkstatus)
  902. return;
  903. if (networkstatus) {
  904. if (!old_d || published > old_d->published) {
  905. d = new_cached_dir(tor_strdup(networkstatus), published);
  906. digestmap_set(cached_v2_networkstatus, identity, d);
  907. if (old_d)
  908. cached_dir_decref(old_d);
  909. }
  910. } else {
  911. if (old_d) {
  912. digestmap_remove(cached_v2_networkstatus, identity);
  913. cached_dir_decref(old_d);
  914. }
  915. }
  916. /* Now purge old entries. */
  917. trusted_dirs = router_get_trusted_dir_servers();
  918. if (digestmap_size(cached_v2_networkstatus) >
  919. smartlist_len(trusted_dirs) + MAX_UNTRUSTED_NETWORKSTATUSES) {
  920. /* We need to remove the oldest untrusted networkstatus. */
  921. const char *oldest = NULL;
  922. time_t oldest_published = TIME_MAX;
  923. digestmap_iter_t *iter;
  924. for (iter = digestmap_iter_init(cached_v2_networkstatus);
  925. !digestmap_iter_done(iter);
  926. iter = digestmap_iter_next(cached_v2_networkstatus, iter)) {
  927. const char *ident;
  928. void *val;
  929. digestmap_iter_get(iter, &ident, &val);
  930. d = val;
  931. if (d->published < oldest_published &&
  932. !router_get_trusteddirserver_by_digest(ident)) {
  933. oldest = ident;
  934. oldest_published = d->published;
  935. }
  936. }
  937. tor_assert(oldest);
  938. d = digestmap_remove(cached_v2_networkstatus, oldest);
  939. if (d)
  940. cached_dir_decref(d);
  941. }
  942. }
  943. /** Helper: If we're an authority for the right directory version (the
  944. * directory version is determined by <b>is_v1_object</b>), try to regenerate
  945. * auth_src as appropriate and return it, falling back to cache_src on
  946. * failure. If we're a cache, return cach_src.
  947. */
  948. static cached_dir_t *
  949. dirserv_pick_cached_dir_obj(cached_dir_t *cache_src,
  950. cached_dir_t *auth_src,
  951. time_t dirty, cached_dir_t *(*regenerate)(void),
  952. const char *name,
  953. int is_v1_object)
  954. {
  955. int authority = get_options()->AuthoritativeDir &&
  956. (!is_v1_object || get_options()->V1AuthoritativeDir);
  957. if (!authority) {
  958. return cache_src;
  959. } else {
  960. /* We're authoritative. */
  961. if (regenerate != NULL) {
  962. if (dirty && dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  963. if (!(auth_src = regenerate())) {
  964. log_err(LD_BUG, "Couldn't generate %s?", name);
  965. exit(1);
  966. }
  967. } else {
  968. log_info(LD_DIRSERV, "The %s is still clean; reusing.", name);
  969. }
  970. }
  971. return auth_src ? auth_src : cache_src;
  972. }
  973. }
  974. /** Helper: If we're authoritative and <b>auth_src</b> is set, use
  975. * <b>auth_src</b>, otherwise use <b>cache_src</b>. If we're using
  976. * <b>auth_src</b> and it's been <b>dirty</b> for at least
  977. * DIR_REGEN_SLACK_TIME seconds, call <b>regenerate</b>() to make a fresh one.
  978. * Yields the compressed version of the directory object if <b>compress</b> is
  979. * set; otherwise return the uncompressed version. (In either case, sets
  980. * *<b>out</b> and returns the size of the buffer in *<b>out</b>.)
  981. *
  982. * Use <b>is_v1_object</b> to help determine whether we're authoritative for
  983. * this kind of object.
  984. **/
  985. static size_t
  986. dirserv_get_obj(const char **out,
  987. int compress,
  988. cached_dir_t *cache_src,
  989. cached_dir_t *auth_src,
  990. time_t dirty, cached_dir_t *(*regenerate)(void),
  991. const char *name,
  992. int is_v1_object)
  993. {
  994. cached_dir_t *d = dirserv_pick_cached_dir_obj(
  995. cache_src, auth_src,
  996. dirty, regenerate, name, is_v1_object);
  997. if (!d)
  998. return 0;
  999. *out = compress ? d->dir_z : d->dir;
  1000. if (*out) {
  1001. return compress ? d->dir_z_len : d->dir_len;
  1002. } else {
  1003. /* not yet available. */
  1004. return 0;
  1005. }
  1006. }
  1007. /** Return the most recently generated encoded signed directory, generating a
  1008. * new one as necessary. If not an authoritative directory may return NULL if
  1009. * no directory is yet cached.*/
  1010. cached_dir_t *
  1011. dirserv_get_directory(void)
  1012. {
  1013. return dirserv_pick_cached_dir_obj(cached_directory, the_directory,
  1014. the_directory_is_dirty,
  1015. dirserv_regenerate_directory,
  1016. "server directory", 1);
  1017. }
  1018. /**
  1019. * Generate a fresh v1 directory (authdirservers only); set the_directory
  1020. * and return a pointer to the new value.
  1021. */
  1022. static cached_dir_t *
  1023. dirserv_regenerate_directory(void)
  1024. {
  1025. char *new_directory=NULL;
  1026. if (dirserv_dump_directory_to_string(&new_directory,
  1027. get_identity_key(), 0)) {
  1028. log_warn(LD_BUG, "Error creating directory.");
  1029. tor_free(new_directory);
  1030. return NULL;
  1031. }
  1032. cached_dir_decref(the_directory);
  1033. the_directory = new_cached_dir(new_directory, time(NULL));
  1034. log_info(LD_DIRSERV,"New directory (size %d) has been built.",
  1035. (int)the_directory->dir_len);
  1036. log_debug(LD_DIRSERV,"New directory (size %d):\n%s",
  1037. (int)the_directory->dir_len, the_directory->dir);
  1038. the_directory_is_dirty = 0;
  1039. /* Save the directory to disk so we re-load it quickly on startup.
  1040. */
  1041. dirserv_set_cached_directory(the_directory->dir, time(NULL), 0);
  1042. return the_directory;
  1043. }
  1044. /** For authoritative directories: the current (v1) network status */
  1045. static cached_dir_t the_runningrouters = { NULL, NULL, 0, 0, 0, -1 };
  1046. /** Replace the current running-routers list with a newly generated one. */
  1047. static cached_dir_t *
  1048. generate_runningrouters(void)
  1049. {
  1050. char *s=NULL;
  1051. char *router_status=NULL;
  1052. char digest[DIGEST_LEN];
  1053. char published[ISO_TIME_LEN+1];
  1054. size_t len;
  1055. crypto_pk_env_t *private_key = get_identity_key();
  1056. char *identity_pkey; /* Identity key, DER64-encoded. */
  1057. size_t identity_pkey_len;
  1058. routerlist_t *rl = router_get_routerlist();
  1059. if (list_server_status(rl->routers, &router_status)) {
  1060. goto err;
  1061. }
  1062. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  1063. &identity_pkey_len)<0) {
  1064. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1065. goto err;
  1066. }
  1067. format_iso_time(published, time(NULL));
  1068. len = 2048+strlen(router_status);
  1069. s = tor_malloc_zero(len);
  1070. tor_snprintf(s, len,
  1071. "network-status\n"
  1072. "published %s\n"
  1073. "router-status %s\n"
  1074. "dir-signing-key\n%s"
  1075. "directory-signature %s\n",
  1076. published, router_status, identity_pkey,
  1077. get_options()->Nickname);
  1078. tor_free(router_status);
  1079. tor_free(identity_pkey);
  1080. if (router_get_runningrouters_hash(s,digest)) {
  1081. log_warn(LD_BUG,"couldn't compute digest");
  1082. goto err;
  1083. }
  1084. if (router_append_dirobj_signature(s, len, digest, private_key)<0)
  1085. goto err;
  1086. set_cached_dir(&the_runningrouters, s, time(NULL));
  1087. runningrouters_is_dirty = 0;
  1088. return &the_runningrouters;
  1089. err:
  1090. tor_free(s);
  1091. tor_free(router_status);
  1092. return NULL;
  1093. }
  1094. /** Set *<b>rr</b> to the most recently generated encoded signed
  1095. * running-routers list, generating a new one as necessary. Return the
  1096. * size of the directory on success, and 0 on failure. */
  1097. size_t
  1098. dirserv_get_runningrouters(const char **rr, int compress)
  1099. {
  1100. return dirserv_get_obj(rr, compress,
  1101. &cached_runningrouters, &the_runningrouters,
  1102. runningrouters_is_dirty,
  1103. generate_runningrouters,
  1104. "v1 network status list", 1);
  1105. }
  1106. /** For authoritative directories: the current (v2) network status */
  1107. static cached_dir_t *the_v2_networkstatus = NULL;
  1108. static int
  1109. should_generate_v2_networkstatus(void)
  1110. {
  1111. return get_options()->AuthoritativeDir &&
  1112. the_v2_networkstatus_is_dirty &&
  1113. the_v2_networkstatus_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL);
  1114. }
  1115. static uint32_t stable_uptime = 0; /* start at a safe value */
  1116. static uint32_t fast_bandwidth = 0;
  1117. static uint32_t guard_bandwidth = 0;
  1118. static INLINE int
  1119. real_uptime(routerinfo_t *router, time_t now)
  1120. {
  1121. return router->uptime + (now - router->cache_info.published_on);
  1122. }
  1123. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  1124. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  1125. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  1126. * bandwidth.
  1127. */
  1128. static int
  1129. dirserv_thinks_router_is_unreliable(time_t now,
  1130. routerinfo_t *router,
  1131. int need_uptime, int need_capacity)
  1132. {
  1133. if (need_uptime &&
  1134. (unsigned)real_uptime(router, now) < stable_uptime)
  1135. return 1;
  1136. if (need_capacity &&
  1137. router_get_advertised_bandwidth(router) < fast_bandwidth)
  1138. return 1;
  1139. return 0;
  1140. }
  1141. static int
  1142. _compare_uint32(const void **a, const void **b)
  1143. {
  1144. uint32_t first = **(uint32_t **)a, second = **(uint32_t **)b;
  1145. if (first < second) return -1;
  1146. if (first > second) return 1;
  1147. return 0;
  1148. }
  1149. /** Look through the routerlist, and assign the median uptime
  1150. * of running valid servers to stable_uptime, and the relative bandwidth
  1151. * capacities to fast_bandwidth and guard_bandwidth. */
  1152. static void
  1153. dirserv_compute_performance_thresholds(routerlist_t *rl)
  1154. {
  1155. smartlist_t *uptimes, *bandwidths;
  1156. time_t now = time(NULL);
  1157. uptimes = smartlist_create();
  1158. bandwidths = smartlist_create();
  1159. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1160. if (ri->is_running && ri->is_valid) {
  1161. uint32_t *up = tor_malloc(sizeof(uint32_t));
  1162. uint32_t *bw = tor_malloc(sizeof(uint32_t));
  1163. *up = (uint32_t) real_uptime(ri, now);
  1164. smartlist_add(uptimes, up);
  1165. *bw = router_get_advertised_bandwidth(ri);
  1166. smartlist_add(bandwidths, bw);
  1167. }
  1168. });
  1169. smartlist_sort(uptimes, _compare_uint32);
  1170. smartlist_sort(bandwidths, _compare_uint32);
  1171. if (smartlist_len(uptimes))
  1172. stable_uptime = *(uint32_t*)smartlist_get(uptimes,
  1173. smartlist_len(uptimes)/2);
  1174. if (smartlist_len(bandwidths)) {
  1175. fast_bandwidth = *(uint32_t*)smartlist_get(bandwidths,
  1176. smartlist_len(bandwidths)/8);
  1177. if (fast_bandwidth < ROUTER_REQUIRED_MIN_BANDWIDTH)
  1178. fast_bandwidth = *(uint32_t*)smartlist_get(bandwidths,
  1179. smartlist_len(bandwidths)/4);
  1180. guard_bandwidth = *(uint32_t*)smartlist_get(bandwidths,
  1181. smartlist_len(bandwidths)/2);
  1182. }
  1183. log_info(LD_DIRSERV, "Uptime cutoff is %lu seconds.",
  1184. (unsigned long)stable_uptime);
  1185. log_info(LD_DIRSERV, "Bandwidth cutoff is %lu bytes.",
  1186. (unsigned long)fast_bandwidth);
  1187. SMARTLIST_FOREACH(uptimes, uint32_t *, up, tor_free(up));
  1188. SMARTLIST_FOREACH(bandwidths, uint32_t *, bw, tor_free(bw));
  1189. smartlist_free(uptimes);
  1190. smartlist_free(bandwidths);
  1191. }
  1192. /** For authoritative directories only: replace the contents of
  1193. * <b>the_v2_networkstatus</b> with a newly generated network status
  1194. * object. */
  1195. static cached_dir_t *
  1196. generate_v2_networkstatus(void)
  1197. {
  1198. #define LONGEST_STATUS_FLAG_NAME_LEN 7
  1199. #define N_STATUS_FLAGS 6
  1200. #define RS_ENTRY_LEN \
  1201. ( /* first line */ \
  1202. MAX_NICKNAME_LEN+BASE64_DIGEST_LEN*2+ISO_TIME_LEN+INET_NTOA_BUF_LEN+ \
  1203. 5*2 /* ports */ + 10 /* punctuation */ + \
  1204. /* second line */ \
  1205. (LONGEST_STATUS_FLAG_NAME_LEN+1)*N_STATUS_FLAGS + 2)
  1206. cached_dir_t *r = NULL;
  1207. size_t len, identity_pkey_len;
  1208. char *status = NULL, *client_versions = NULL, *server_versions = NULL,
  1209. *identity_pkey = NULL, *hostname = NULL;
  1210. char *outp, *endp;
  1211. or_options_t *options = get_options();
  1212. char fingerprint[FINGERPRINT_LEN+1];
  1213. char ipaddr[INET_NTOA_BUF_LEN];
  1214. char published[ISO_TIME_LEN+1];
  1215. char digest[DIGEST_LEN];
  1216. struct in_addr in;
  1217. uint32_t addr;
  1218. crypto_pk_env_t *private_key = get_identity_key();
  1219. routerlist_t *rl = router_get_routerlist();
  1220. time_t now = time(NULL);
  1221. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  1222. int naming = options->NamingAuthoritativeDir;
  1223. int versioning = options->VersioningAuthoritativeDir;
  1224. const char *contact;
  1225. if (resolve_my_address(options, &addr, &hostname)<0) {
  1226. log_warn(LD_NET, "Couldn't resolve my hostname");
  1227. goto done;
  1228. }
  1229. in.s_addr = htonl(addr);
  1230. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1231. format_iso_time(published, time(NULL));
  1232. client_versions = format_versions_list(options->RecommendedClientVersions);
  1233. server_versions = format_versions_list(options->RecommendedServerVersions);
  1234. if (crypto_pk_write_public_key_to_string(private_key, &identity_pkey,
  1235. &identity_pkey_len)<0) {
  1236. log_warn(LD_BUG,"Writing public key to string failed.");
  1237. goto done;
  1238. }
  1239. if (crypto_pk_get_fingerprint(private_key, fingerprint, 0)<0) {
  1240. log_err(LD_BUG, "Error computing fingerprint");
  1241. goto done;
  1242. }
  1243. contact = get_options()->ContactInfo;
  1244. if (!contact)
  1245. contact = "(none)";
  1246. len = 2048+strlen(client_versions)+strlen(server_versions);
  1247. len += identity_pkey_len*2;
  1248. len += (RS_ENTRY_LEN)*smartlist_len(rl->routers);
  1249. status = tor_malloc(len);
  1250. tor_snprintf(status, len,
  1251. "network-status-version 2\n"
  1252. "dir-source %s %s %d\n"
  1253. "fingerprint %s\n"
  1254. "contact %s\n"
  1255. "published %s\n"
  1256. "dir-options%s%s\n"
  1257. "%s%s" /* client versions %s */
  1258. "%s%s%s" /* \nserver versions %s \n */
  1259. "dir-signing-key\n%s\n",
  1260. hostname, ipaddr, (int)options->DirPort,
  1261. fingerprint,
  1262. contact,
  1263. published,
  1264. naming ? " Names" : "",
  1265. versioning ? " Versions" : "",
  1266. versioning ? "client-versions " : "",
  1267. client_versions,
  1268. versioning ? "\nserver-versions " : "",
  1269. server_versions,
  1270. versioning ? "\n" : "",
  1271. identity_pkey);
  1272. outp = status + strlen(status);
  1273. endp = status + len;
  1274. /* precompute this part, since we need it to decide what "stable"
  1275. * means. */
  1276. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1277. ri->is_running = dirserv_thinks_router_is_reachable(ri, now);
  1278. });
  1279. dirserv_compute_performance_thresholds(rl);
  1280. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1281. if (ri->cache_info.published_on >= cutoff) {
  1282. int f_exit = exit_policy_is_general_exit(ri->exit_policy);
  1283. /* These versions dump connections with idle live circuits
  1284. sometimes. D'oh!*/
  1285. int unstable_version =
  1286. tor_version_as_new_as(ri->platform,"0.1.1.10-alpha") &&
  1287. !tor_version_as_new_as(ri->platform,"0.1.1.16-rc-cvs");
  1288. int f_stable = ri->is_stable =
  1289. !dirserv_thinks_router_is_unreliable(now, ri, 1, 0) &&
  1290. !unstable_version;
  1291. int f_fast = ri->is_fast =
  1292. !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
  1293. int f_running = ri->is_running; /* computed above */
  1294. int f_authority = router_digest_is_trusted_dir(
  1295. ri->cache_info.identity_digest);
  1296. int f_named = naming && ri->is_named;
  1297. int f_valid = ri->is_valid;
  1298. int f_guard = f_fast && f_stable &&
  1299. router_get_advertised_bandwidth(ri) > guard_bandwidth;
  1300. /* 0.1.1.9-alpha is the first version to support fetch by descriptor
  1301. * hash. */
  1302. int f_v2_dir = ri->dir_port &&
  1303. tor_version_as_new_as(ri->platform,"0.1.1.9-alpha");
  1304. char identity64[BASE64_DIGEST_LEN+1];
  1305. char digest64[BASE64_DIGEST_LEN+1];
  1306. format_iso_time(published, ri->cache_info.published_on);
  1307. digest_to_base64(identity64, ri->cache_info.identity_digest);
  1308. digest_to_base64(digest64, ri->cache_info.signed_descriptor_digest);
  1309. in.s_addr = htonl(ri->addr);
  1310. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1311. if (tor_snprintf(outp, endp-outp,
  1312. "r %s %s %s %s %s %d %d\n"
  1313. "s%s%s%s%s%s%s%s%s%s\n",
  1314. ri->nickname,
  1315. identity64,
  1316. digest64,
  1317. published,
  1318. ipaddr,
  1319. ri->or_port,
  1320. ri->dir_port,
  1321. f_authority?" Authority":"",
  1322. f_exit?" Exit":"",
  1323. f_fast?" Fast":"",
  1324. f_guard?" Guard":"",
  1325. f_named?" Named":"",
  1326. f_stable?" Stable":"",
  1327. f_running?" Running":"",
  1328. f_valid?" Valid":"",
  1329. f_v2_dir?" V2Dir":"")<0) {
  1330. log_warn(LD_BUG, "Unable to print router status.");
  1331. goto done;
  1332. }
  1333. outp += strlen(outp);
  1334. }
  1335. });
  1336. if (tor_snprintf(outp, endp-outp, "directory-signature %s\n",
  1337. get_options()->Nickname)<0) {
  1338. log_warn(LD_BUG, "Unable to write signature line.");
  1339. goto done;
  1340. }
  1341. if (router_get_networkstatus_v2_hash(status, digest)<0) {
  1342. log_warn(LD_BUG, "Unable to hash network status");
  1343. goto done;
  1344. }
  1345. if (router_append_dirobj_signature(outp,endp-outp,digest,private_key)<0) {
  1346. log_warn(LD_BUG, "Unable to sign router status.");
  1347. goto done;
  1348. }
  1349. if (the_v2_networkstatus)
  1350. cached_dir_decref(the_v2_networkstatus);
  1351. the_v2_networkstatus = new_cached_dir(status, time(NULL));
  1352. status = NULL; /* So it doesn't get double-freed. */
  1353. the_v2_networkstatus_is_dirty = 0;
  1354. router_set_networkstatus(the_v2_networkstatus->dir,
  1355. time(NULL), NS_GENERATED, NULL);
  1356. r = the_v2_networkstatus;
  1357. done:
  1358. tor_free(client_versions);
  1359. tor_free(server_versions);
  1360. tor_free(status);
  1361. tor_free(hostname);
  1362. tor_free(identity_pkey);
  1363. return r;
  1364. }
  1365. /* DOCDOC */
  1366. void
  1367. dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
  1368. const char *key)
  1369. {
  1370. tor_assert(result);
  1371. if (!cached_v2_networkstatus)
  1372. cached_v2_networkstatus = digestmap_new();
  1373. if (should_generate_v2_networkstatus())
  1374. generate_v2_networkstatus();
  1375. if (!strcmp(key,"authority")) {
  1376. if (get_options()->AuthoritativeDir) {
  1377. routerinfo_t *me = router_get_my_routerinfo();
  1378. if (me)
  1379. smartlist_add(result,
  1380. tor_memdup(me->cache_info.identity_digest, DIGEST_LEN));
  1381. }
  1382. } else if (!strcmp(key, "all")) {
  1383. digestmap_iter_t *iter;
  1384. iter = digestmap_iter_init(cached_v2_networkstatus);
  1385. while (!digestmap_iter_done(iter)) {
  1386. const char *ident;
  1387. void *val;
  1388. digestmap_iter_get(iter, &ident, &val);
  1389. smartlist_add(result, tor_memdup(ident, DIGEST_LEN));
  1390. iter = digestmap_iter_next(cached_v2_networkstatus, iter);
  1391. }
  1392. if (smartlist_len(result) == 0)
  1393. log_warn(LD_DIRSERV,
  1394. "Client requested 'all' network status objects; we have none.");
  1395. } else if (!strcmpstart(key, "fp/")) {
  1396. dir_split_resource_into_fingerprints(key+3, result, NULL, 1);
  1397. }
  1398. }
  1399. /** Look for a network status object as specified by <b>key</b>, which should
  1400. * be either "authority" (to find a network status generated by us), a hex
  1401. * identity digest (to find a network status generated by given directory), or
  1402. * "all" (to return all the v2 network status objects we have).
  1403. */
  1404. void
  1405. dirserv_get_networkstatus_v2(smartlist_t *result,
  1406. const char *key)
  1407. {
  1408. tor_assert(result);
  1409. if (!cached_v2_networkstatus)
  1410. cached_v2_networkstatus = digestmap_new();
  1411. if (!strcmp(key,"authority")) {
  1412. if (get_options()->AuthoritativeDir) {
  1413. cached_dir_t *d =
  1414. dirserv_pick_cached_dir_obj(NULL,
  1415. the_v2_networkstatus,
  1416. the_v2_networkstatus_is_dirty,
  1417. generate_v2_networkstatus,
  1418. "network status list", 0);
  1419. if (d)
  1420. smartlist_add(result, d);
  1421. else
  1422. log_warn(LD_BUG,
  1423. "Unable to generate an authoritative network status.");
  1424. }
  1425. } else if (!strcmp(key, "all")) {
  1426. digestmap_iter_t *iter;
  1427. if (should_generate_v2_networkstatus())
  1428. generate_v2_networkstatus();
  1429. iter = digestmap_iter_init(cached_v2_networkstatus);
  1430. while (!digestmap_iter_done(iter)) {
  1431. const char *ident;
  1432. void *val;
  1433. digestmap_iter_get(iter, &ident, &val);
  1434. smartlist_add(result, val);
  1435. iter = digestmap_iter_next(cached_v2_networkstatus, iter);
  1436. }
  1437. if (smartlist_len(result) == 0)
  1438. log_warn(LD_DIRSERV,
  1439. "Client requested 'all' network status objects; we have none.");
  1440. } else if (!strcmpstart(key, "fp/")) {
  1441. smartlist_t *digests = smartlist_create();
  1442. dir_split_resource_into_fingerprints(key+3, digests, NULL, 1);
  1443. SMARTLIST_FOREACH(digests, char *, cp,
  1444. {
  1445. cached_dir_t *cached;
  1446. if (router_digest_is_me(cp) && should_generate_v2_networkstatus())
  1447. generate_v2_networkstatus();
  1448. cached = digestmap_get(cached_v2_networkstatus, cp);
  1449. if (cached) {
  1450. smartlist_add(result, cached);
  1451. } else {
  1452. char hexbuf[HEX_DIGEST_LEN+1];
  1453. base16_encode(hexbuf, sizeof(hexbuf), cp, DIGEST_LEN);
  1454. log_info(LD_DIRSERV, "Don't know about any network status with "
  1455. "fingerprint '%s'", hexbuf);
  1456. }
  1457. tor_free(cp);
  1458. });
  1459. smartlist_free(digests);
  1460. }
  1461. }
  1462. /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
  1463. * pointers, adds copies of digests to fps_out. For a /tor/server/d/ request,
  1464. * adds descriptor digests; for other requests, adds identity digests.
  1465. */
  1466. int
  1467. dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
  1468. const char **msg)
  1469. {
  1470. *msg = NULL;
  1471. if (!strcmp(key, "/tor/server/all")) {
  1472. routerlist_t *rl = router_get_routerlist();
  1473. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1474. smartlist_add(fps_out,
  1475. tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
  1476. } else if (!strcmp(key, "/tor/server/authority")) {
  1477. routerinfo_t *ri = router_get_my_routerinfo();
  1478. if (ri)
  1479. smartlist_add(fps_out,
  1480. tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
  1481. } else if (!strcmpstart(key, "/tor/server/d/")) {
  1482. key += strlen("/tor/server/d/");
  1483. dir_split_resource_into_fingerprints(key, fps_out, NULL, 1);
  1484. } else if (!strcmpstart(key, "/tor/server/fp/")) {
  1485. key += strlen("/tor/server/fp/");
  1486. dir_split_resource_into_fingerprints(key, fps_out, NULL, 1);
  1487. } else {
  1488. *msg = "Key not recognized";
  1489. return -1;
  1490. }
  1491. if (!smartlist_len(fps_out)) {
  1492. *msg = "Servers unavailable";
  1493. return -1;
  1494. }
  1495. return 0;
  1496. }
  1497. /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
  1498. * <b>key</b>. The key should be either
  1499. * - "/tor/server/authority" for our own routerinfo;
  1500. * - "/tor/server/all" for all the routerinfos we have, concatenated;
  1501. * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
  1502. * hex identity digests; or
  1503. * - "/tor/server/d/D" where D is a plus-separated sequence
  1504. * of server descriptor digests, in hex.
  1505. *
  1506. * Return 0 if we found some matching descriptors, or -1 if we do not
  1507. * have any descriptors, no matching descriptors, or if we did not
  1508. * recognize the key (URL).
  1509. * If -1 is returned *<b>msg</b> will be set to an appropriate error
  1510. * message.
  1511. *
  1512. * (Despite its name, this function is also called from the controller, which
  1513. * exposes a similar means to fetch descriptors.)
  1514. */
  1515. int
  1516. dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
  1517. const char **msg)
  1518. {
  1519. *msg = NULL;
  1520. if (!strcmp(key, "/tor/server/all")) {
  1521. routerlist_t *rl = router_get_routerlist();
  1522. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1523. smartlist_add(descs_out, &(r->cache_info)));
  1524. } else if (!strcmp(key, "/tor/server/authority")) {
  1525. routerinfo_t *ri = router_get_my_routerinfo();
  1526. if (ri)
  1527. smartlist_add(descs_out, &(ri->cache_info));
  1528. } else if (!strcmpstart(key, "/tor/server/d/")) {
  1529. smartlist_t *digests = smartlist_create();
  1530. key += strlen("/tor/server/d/");
  1531. dir_split_resource_into_fingerprints(key, digests, NULL, 1);
  1532. SMARTLIST_FOREACH(digests, const char *, d,
  1533. {
  1534. signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
  1535. if (sd)
  1536. smartlist_add(descs_out,sd);
  1537. });
  1538. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  1539. smartlist_free(digests);
  1540. } else if (!strcmpstart(key, "/tor/server/fp/")) {
  1541. smartlist_t *digests = smartlist_create();
  1542. time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
  1543. key += strlen("/tor/server/fp/");
  1544. dir_split_resource_into_fingerprints(key, digests, NULL, 1);
  1545. SMARTLIST_FOREACH(digests, const char *, d,
  1546. {
  1547. if (router_digest_is_me(d)) {
  1548. smartlist_add(descs_out, &(router_get_my_routerinfo()->cache_info));
  1549. } else {
  1550. routerinfo_t *ri = router_get_by_digest(d);
  1551. /* Don't actually serve a descriptor that everyone will think is
  1552. * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
  1553. * Tors from downloading descriptors that they will throw away.
  1554. */
  1555. if (ri && ri->cache_info.published_on > cutoff)
  1556. smartlist_add(descs_out, &(ri->cache_info));
  1557. }
  1558. });
  1559. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  1560. smartlist_free(digests);
  1561. } else {
  1562. *msg = "Key not recognized";
  1563. return -1;
  1564. }
  1565. if (!smartlist_len(descs_out)) {
  1566. *msg = "Servers unavailable";
  1567. return -1;
  1568. }
  1569. return 0;
  1570. }
  1571. /** Called when a TLS handshake has completed successfully with a
  1572. * router listening at <b>address</b>:<b>or_port</b>, and has yielded
  1573. * a certificate with digest <b>digest_rcvd</b> and nickname
  1574. * <b>nickname_rcvd</b>. When this happens, it's clear that any other
  1575. * descriptors for that address/port combination must be unusable:
  1576. * delete them if they are not valid.
  1577. *
  1578. * Also, if as_advertised is 1, then inform the reachability checker
  1579. * that we could get to this guy.
  1580. */
  1581. void
  1582. dirserv_orconn_tls_done(const char *address,
  1583. uint16_t or_port,
  1584. const char *digest_rcvd,
  1585. const char *nickname_rcvd,
  1586. int as_advertised)
  1587. {
  1588. int i;
  1589. routerlist_t *rl = router_get_routerlist();
  1590. tor_assert(address);
  1591. tor_assert(digest_rcvd);
  1592. tor_assert(nickname_rcvd);
  1593. (void) as_advertised; // XXXX This should really be implemented. -NM
  1594. // XXXXNM We should really have a better solution here than dropping
  1595. // XXXXNM whole routers; otherwise, they come back way too easily.
  1596. for (i = 0; i < smartlist_len(rl->routers); ++i) {
  1597. routerinfo_t *ri = smartlist_get(rl->routers, i);
  1598. int drop = 0;
  1599. if (strcasecmp(address, ri->address) || or_port != ri->or_port)
  1600. continue;
  1601. /* XXX For 0.1.2.x, we should do something smarter here than !is_valid. */
  1602. if (!ri->is_valid) {
  1603. /* We have a router at the same address! */
  1604. if (strcasecmp(ri->nickname, nickname_rcvd)) {
  1605. log_notice(LD_DIRSERV,
  1606. "Dropping old invalid descriptor: nickname '%s' does "
  1607. "not match nickname '%s' in new cert from %s:%d",
  1608. ri->nickname, nickname_rcvd, address, or_port);
  1609. drop = 1;
  1610. } else if (memcmp(ri->cache_info.identity_digest, digest_rcvd,
  1611. DIGEST_LEN)) {
  1612. log_notice(LD_DIRSERV,
  1613. "Dropping old invalid descriptor for nickname '%s': "
  1614. "identity key does not match key in new cert from %s:%d",
  1615. ri->nickname, address, or_port);
  1616. drop = 1;
  1617. }
  1618. }
  1619. if (drop) {
  1620. routerlist_remove(rl, ri, i--, 0);
  1621. directory_set_dirty();
  1622. } else { /* correct nickname and digest. mark this router reachable! */
  1623. log_info(LD_DIRSERV, "Found router %s to be reachable. Yay.",
  1624. ri->nickname);
  1625. ri->last_reachable = time(NULL);
  1626. ri->num_unreachable_notifications = 0;
  1627. }
  1628. }
  1629. }
  1630. /** When we're spooling data onto our outbuf, add more whenever we dip
  1631. * below this threshold. */
  1632. #define DIRSERV_BUFFER_MIN 16384
  1633. static int
  1634. connection_dirserv_finish_spooling(connection_t *conn)
  1635. {
  1636. if (conn->zlib_state) {
  1637. connection_write_to_buf_zlib(conn, conn->zlib_state, "", 0, 1);
  1638. tor_zlib_free(conn->zlib_state);
  1639. conn->zlib_state = NULL;
  1640. }
  1641. conn->dir_spool_src = DIR_SPOOL_NONE;
  1642. return 0;
  1643. }
  1644. /** DOCDOC */
  1645. static int
  1646. connection_dirserv_add_servers_to_outbuf(connection_t *conn)
  1647. {
  1648. int by_fp = conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP;
  1649. while (smartlist_len(conn->fingerprint_stack) &&
  1650. buf_datalen(conn->outbuf) < DIRSERV_BUFFER_MIN) {
  1651. char *fp = smartlist_pop_last(conn->fingerprint_stack);
  1652. signed_descriptor_t *sd = NULL;
  1653. if (by_fp) {
  1654. if (router_digest_is_me(fp)) {
  1655. sd = &(router_get_my_routerinfo()->cache_info);
  1656. } else {
  1657. routerinfo_t *ri = router_get_by_digest(fp);
  1658. if (ri &&
  1659. ri->cache_info.published_on > time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH)
  1660. sd = &ri->cache_info;
  1661. }
  1662. } else
  1663. sd = router_get_by_descriptor_digest(fp);
  1664. tor_free(fp);
  1665. if (!sd)
  1666. continue;
  1667. if (conn->zlib_state) {
  1668. connection_write_to_buf_zlib(
  1669. conn, conn->zlib_state,
  1670. sd->signed_descriptor_body, sd->signed_descriptor_len,
  1671. 0);
  1672. } else {
  1673. connection_write_to_buf(sd->signed_descriptor_body,
  1674. sd->signed_descriptor_len,
  1675. conn);
  1676. }
  1677. }
  1678. if (!smartlist_len(conn->fingerprint_stack)) {
  1679. /* We just wrote the last one; finish up. */
  1680. connection_dirserv_finish_spooling(conn);
  1681. smartlist_free(conn->fingerprint_stack);
  1682. conn->fingerprint_stack = NULL;
  1683. }
  1684. return 0;
  1685. }
  1686. /** DOCDOC */
  1687. static int
  1688. connection_dirserv_add_dir_bytes_to_outbuf(connection_t *conn)
  1689. {
  1690. int bytes, remaining;
  1691. bytes = DIRSERV_BUFFER_MIN - buf_datalen(conn->outbuf);
  1692. tor_assert(bytes > 0);
  1693. tor_assert(conn->cached_dir);
  1694. if (bytes < 8192)
  1695. bytes = 8192;
  1696. remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
  1697. if (bytes > remaining)
  1698. bytes = remaining;
  1699. if (conn->zlib_state) {
  1700. connection_write_to_buf_zlib(conn, conn->zlib_state,
  1701. conn->cached_dir->dir_z + conn->cached_dir_offset,
  1702. bytes, bytes == remaining);
  1703. } else {
  1704. connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
  1705. bytes, conn);
  1706. }
  1707. conn->cached_dir_offset += bytes;
  1708. if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
  1709. /* We just wrote the last one; finish up. */
  1710. connection_dirserv_finish_spooling(conn);
  1711. cached_dir_decref(conn->cached_dir);
  1712. conn->cached_dir = NULL;
  1713. }
  1714. return 0;
  1715. }
  1716. /* DOCDOC */
  1717. static int
  1718. connection_dirserv_add_networkstatus_bytes_to_outbuf(connection_t *conn)
  1719. {
  1720. while (buf_datalen(conn->outbuf) < DIRSERV_BUFFER_MIN) {
  1721. if (conn->cached_dir) {
  1722. int uncompressing = (conn->zlib_state != NULL);
  1723. int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
  1724. /* This bit is tricky. If we were uncompressing the last networkstatus,
  1725. * we may need to make a new zlib object to uncompress the next one. */
  1726. if (uncompressing && ! conn->zlib_state &&
  1727. conn->fingerprint_stack && smartlist_len(conn->fingerprint_stack))
  1728. conn->zlib_state = conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  1729. if (r) return r;
  1730. } else if (conn->fingerprint_stack &&
  1731. smartlist_len(conn->fingerprint_stack)) {
  1732. /* Add another networkstatus; start serving it. */
  1733. char *fp = smartlist_pop_last(conn->fingerprint_stack);
  1734. cached_dir_t *d;
  1735. if (router_digest_is_me(fp))
  1736. d = the_v2_networkstatus;
  1737. else
  1738. d = digestmap_get(cached_v2_networkstatus, fp);
  1739. tor_free(fp);
  1740. if (d) {
  1741. ++d->refcnt;
  1742. conn->cached_dir = d;
  1743. conn->cached_dir_offset = 0;
  1744. }
  1745. } else {
  1746. connection_dirserv_finish_spooling(conn);
  1747. if (conn->fingerprint_stack)
  1748. smartlist_free(conn->fingerprint_stack);
  1749. conn->fingerprint_stack = NULL;
  1750. return 0;
  1751. }
  1752. }
  1753. return 0;
  1754. }
  1755. /** Called whenever we have flushed some directory data in state
  1756. * SERVER_WRITING. */
  1757. int
  1758. connection_dirserv_flushed_some(connection_t *conn)
  1759. {
  1760. tor_assert(conn->type == CONN_TYPE_DIR);
  1761. tor_assert(conn->state == DIR_CONN_STATE_SERVER_WRITING);
  1762. if (conn->dir_spool_src == DIR_SPOOL_NONE
  1763. || buf_datalen(conn->outbuf) >= DIRSERV_BUFFER_MIN)
  1764. return 0;
  1765. switch (conn->dir_spool_src) {
  1766. case DIR_SPOOL_SERVER_BY_DIGEST:
  1767. case DIR_SPOOL_SERVER_BY_FP:
  1768. return connection_dirserv_add_servers_to_outbuf(conn);
  1769. case DIR_SPOOL_CACHED_DIR:
  1770. return connection_dirserv_add_dir_bytes_to_outbuf(conn);
  1771. case DIR_SPOOL_NETWORKSTATUS:
  1772. return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
  1773. default:
  1774. return 0;
  1775. }
  1776. }
  1777. /** Release all storage used by the directory server. */
  1778. void
  1779. dirserv_free_all(void)
  1780. {
  1781. if (fingerprint_list) {
  1782. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, fp,
  1783. { tor_free(fp->nickname);
  1784. tor_free(fp->fingerprint);
  1785. tor_free(fp); });
  1786. smartlist_free(fingerprint_list);
  1787. fingerprint_list = NULL;
  1788. }
  1789. cached_dir_decref(the_directory);
  1790. clear_cached_dir(&the_runningrouters);
  1791. cached_dir_decref(the_v2_networkstatus);
  1792. cached_dir_decref(cached_directory);
  1793. clear_cached_dir(&cached_runningrouters);
  1794. if (cached_v2_networkstatus) {
  1795. digestmap_free(cached_v2_networkstatus, _free_cached_dir);
  1796. cached_v2_networkstatus = NULL;
  1797. }
  1798. }