dirserv.c 83 KB

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