dirserv.c 84 KB

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