dirserv.c 78 KB

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