dirserv.c 78 KB

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