dirserv.c 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2009, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #define DIRSERV_PRIVATE
  6. #include "or.h"
  7. /**
  8. * \file dirserv.c
  9. * \brief Directory server core implementation. Manages directory
  10. * contents and generates directories.
  11. */
  12. /** How far in the future do we allow a router to get? (seconds) */
  13. #define ROUTER_ALLOW_SKEW (60*60*12)
  14. /** How many seconds do we wait before regenerating the directory? */
  15. #define DIR_REGEN_SLACK_TIME 30
  16. /** If we're a cache, keep this many networkstatuses around from non-trusted
  17. * directory authorities. */
  18. #define MAX_UNTRUSTED_NETWORKSTATUSES 16
  19. /** If a v1 directory is older than this, discard it. */
  20. #define MAX_V1_DIRECTORY_AGE (30*24*60*60)
  21. /** If a v1 running-routers is older than this, discard it. */
  22. #define MAX_V1_RR_AGE (7*24*60*60)
  23. extern time_t time_of_process_start; /* from main.c */
  24. /** Do we need to regenerate the v1 directory when someone asks for it? */
  25. static time_t the_directory_is_dirty = 1;
  26. /** Do we need to regenerate the v1 runningrouters document when somebody
  27. * asks for it? */
  28. static time_t runningrouters_is_dirty = 1;
  29. /** Do we need to regenerate our v2 networkstatus document when somebody asks
  30. * for it? */
  31. static time_t the_v2_networkstatus_is_dirty = 1;
  32. /** Most recently generated encoded signed v1 directory. (v1 auth dirservers
  33. * only.) */
  34. static cached_dir_t *the_directory = NULL;
  35. /** For authoritative directories: the current (v1) network status. */
  36. static cached_dir_t the_runningrouters = { NULL, NULL, 0, 0, 0, -1 };
  37. static void directory_remove_invalid(void);
  38. static cached_dir_t *dirserv_regenerate_directory(void);
  39. static char *format_versions_list(config_line_t *ln);
  40. struct authdir_config_t;
  41. static int add_fingerprint_to_dir(const char *nickname, const char *fp,
  42. struct authdir_config_t *list);
  43. static uint32_t dirserv_router_get_status(const routerinfo_t *router,
  44. const char **msg);
  45. static uint32_t
  46. dirserv_get_status_impl(const char *fp, const char *nickname,
  47. const char *address,
  48. uint32_t addr, uint16_t or_port,
  49. const char *platform, const char *contact,
  50. const char **msg, int should_log);
  51. static void clear_cached_dir(cached_dir_t *d);
  52. static signed_descriptor_t *get_signed_descriptor_by_fp(const char *fp,
  53. int extrainfo,
  54. time_t publish_cutoff);
  55. static int dirserv_add_extrainfo(extrainfo_t *ei, const char **msg);
  56. /************** Fingerprint handling code ************/
  57. #define FP_NAMED 1 /**< Listed in fingerprint file. */
  58. #define FP_INVALID 2 /**< Believed invalid. */
  59. #define FP_REJECT 4 /**< We will not publish this router. */
  60. #define FP_BADDIR 8 /**< We'll tell clients to avoid using this as a dir. */
  61. #define FP_BADEXIT 16 /**< We'll tell clients not to use this as an exit. */
  62. #define FP_UNNAMED 32 /**< Another router has this name in fingerprint file. */
  63. /** Encapsulate a nickname and an FP_* status; target of status_by_digest
  64. * map. */
  65. typedef struct router_status_t {
  66. char nickname[MAX_NICKNAME_LEN+1];
  67. uint32_t status;
  68. } router_status_t;
  69. /** List of nickname-\>identity fingerprint mappings for all the routers
  70. * that we name. Used to prevent router impersonation. */
  71. typedef struct authdir_config_t {
  72. strmap_t *fp_by_name; /**< Map from lc nickname to fingerprint. */
  73. digestmap_t *status_by_digest; /**< Map from digest to router_status_t. */
  74. } authdir_config_t;
  75. /** Should be static; exposed for testing. */
  76. static authdir_config_t *fingerprint_list = NULL;
  77. /** Allocate and return a new, empty, authdir_config_t. */
  78. static authdir_config_t *
  79. authdir_config_new(void)
  80. {
  81. authdir_config_t *list = tor_malloc_zero(sizeof(authdir_config_t));
  82. list->fp_by_name = strmap_new();
  83. list->status_by_digest = digestmap_new();
  84. return list;
  85. }
  86. /** Add the fingerprint <b>fp</b> for the nickname <b>nickname</b> to
  87. * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
  88. * new, or 1 if we replaced the old value.
  89. */
  90. /* static */ int
  91. add_fingerprint_to_dir(const char *nickname, const char *fp,
  92. authdir_config_t *list)
  93. {
  94. char *fingerprint;
  95. char d[DIGEST_LEN];
  96. router_status_t *status;
  97. tor_assert(nickname);
  98. tor_assert(fp);
  99. tor_assert(list);
  100. fingerprint = tor_strdup(fp);
  101. tor_strstrip(fingerprint, " ");
  102. if (base16_decode(d, DIGEST_LEN, fingerprint, strlen(fingerprint))) {
  103. log_warn(LD_DIRSERV, "Couldn't decode fingerprint \"%s\"",
  104. escaped(fp));
  105. tor_free(fingerprint);
  106. return 0;
  107. }
  108. if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) {
  109. log_warn(LD_DIRSERV, "Tried to add a mapping for reserved nickname %s",
  110. UNNAMED_ROUTER_NICKNAME);
  111. tor_free(fingerprint);
  112. return 0;
  113. }
  114. status = digestmap_get(list->status_by_digest, d);
  115. if (!status) {
  116. status = tor_malloc_zero(sizeof(router_status_t));
  117. digestmap_set(list->status_by_digest, d, status);
  118. }
  119. if (nickname[0] != '!') {
  120. char *old_fp = strmap_get_lc(list->fp_by_name, nickname);
  121. if (old_fp && !strcasecmp(fingerprint, old_fp)) {
  122. tor_free(fingerprint);
  123. } else {
  124. tor_free(old_fp);
  125. strmap_set_lc(list->fp_by_name, nickname, fingerprint);
  126. }
  127. status->status |= FP_NAMED;
  128. strlcpy(status->nickname, nickname, sizeof(status->nickname));
  129. } else {
  130. tor_free(fingerprint);
  131. if (!strcasecmp(nickname, "!reject")) {
  132. status->status |= FP_REJECT;
  133. } else if (!strcasecmp(nickname, "!invalid")) {
  134. status->status |= FP_INVALID;
  135. } else if (!strcasecmp(nickname, "!baddir")) {
  136. status->status |= FP_BADDIR;
  137. } else if (!strcasecmp(nickname, "!badexit")) {
  138. status->status |= FP_BADEXIT;
  139. }
  140. }
  141. return 0;
  142. }
  143. /** Add the nickname and fingerprint for this OR to the
  144. * global list of recognized identity key fingerprints. */
  145. int
  146. dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk)
  147. {
  148. char fp[FINGERPRINT_LEN+1];
  149. if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
  150. log_err(LD_BUG, "Error computing fingerprint");
  151. return -1;
  152. }
  153. if (!fingerprint_list)
  154. fingerprint_list = authdir_config_new();
  155. add_fingerprint_to_dir(nickname, fp, fingerprint_list);
  156. return 0;
  157. }
  158. /** Load the nickname-\>fingerprint mappings stored in the approved-routers
  159. * file. The file format is line-based, with each non-blank holding one
  160. * nickname, some space, and a fingerprint for that nickname. On success,
  161. * replace the current fingerprint list with the new list and return 0. On
  162. * failure, leave the current fingerprint list untouched, and
  163. * return -1. */
  164. int
  165. dirserv_load_fingerprint_file(void)
  166. {
  167. char *fname;
  168. char *cf;
  169. char *nickname, *fingerprint;
  170. authdir_config_t *fingerprint_list_new;
  171. int result;
  172. config_line_t *front=NULL, *list;
  173. or_options_t *options = get_options();
  174. fname = get_datadir_fname("approved-routers");
  175. log_info(LD_GENERAL,
  176. "Reloading approved fingerprints from \"%s\"...", fname);
  177. cf = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
  178. if (!cf) {
  179. if (options->NamingAuthoritativeDir) {
  180. log_warn(LD_FS, "Cannot open fingerprint file '%s'. Failing.", fname);
  181. tor_free(fname);
  182. return -1;
  183. } else {
  184. log_info(LD_FS, "Cannot open fingerprint file '%s'. That's ok.", fname);
  185. tor_free(fname);
  186. return 0;
  187. }
  188. }
  189. tor_free(fname);
  190. result = config_get_lines(cf, &front);
  191. tor_free(cf);
  192. if (result < 0) {
  193. log_warn(LD_CONFIG, "Error reading from fingerprint file");
  194. return -1;
  195. }
  196. fingerprint_list_new = authdir_config_new();
  197. for (list=front; list; list=list->next) {
  198. char digest_tmp[DIGEST_LEN];
  199. nickname = list->key; fingerprint = list->value;
  200. if (strlen(nickname) > MAX_NICKNAME_LEN) {
  201. log_notice(LD_CONFIG,
  202. "Nickname '%s' too long in fingerprint file. Skipping.",
  203. nickname);
  204. continue;
  205. }
  206. if (!is_legal_nickname(nickname) &&
  207. strcasecmp(nickname, "!reject") &&
  208. strcasecmp(nickname, "!invalid") &&
  209. strcasecmp(nickname, "!badexit")) {
  210. log_notice(LD_CONFIG,
  211. "Invalid nickname '%s' in fingerprint file. Skipping.",
  212. nickname);
  213. continue;
  214. }
  215. tor_strstrip(fingerprint, " "); /* remove spaces */
  216. if (strlen(fingerprint) != HEX_DIGEST_LEN ||
  217. base16_decode(digest_tmp, sizeof(digest_tmp),
  218. fingerprint, HEX_DIGEST_LEN) < 0) {
  219. log_notice(LD_CONFIG,
  220. "Invalid fingerprint (nickname '%s', "
  221. "fingerprint %s). Skipping.",
  222. nickname, fingerprint);
  223. continue;
  224. }
  225. if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
  226. /* If you approved an OR called "client", then clients who use
  227. * the default nickname could all be rejected. That's no good. */
  228. log_notice(LD_CONFIG,
  229. "Authorizing nickname '%s' would break "
  230. "many clients; skipping.",
  231. DEFAULT_CLIENT_NICKNAME);
  232. continue;
  233. }
  234. if (0==strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) {
  235. /* If you approved an OR called "unnamed", then clients will be
  236. * confused. */
  237. log_notice(LD_CONFIG,
  238. "Authorizing nickname '%s' is not allowed; skipping.",
  239. UNNAMED_ROUTER_NICKNAME);
  240. continue;
  241. }
  242. if (add_fingerprint_to_dir(nickname, fingerprint, fingerprint_list_new)
  243. != 0)
  244. log_notice(LD_CONFIG, "Duplicate nickname '%s'.", nickname);
  245. }
  246. config_free_lines(front);
  247. dirserv_free_fingerprint_list();
  248. fingerprint_list = fingerprint_list_new;
  249. /* Delete any routers whose fingerprints we no longer recognize */
  250. directory_remove_invalid();
  251. return 0;
  252. }
  253. /** Check whether <b>router</b> has a nickname/identity key combination that
  254. * we recognize from the fingerprint list, or an IP we automatically act on
  255. * according to our configuration. Return the appropriate router status.
  256. *
  257. * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
  258. * *<b>msg</b> to an explanation of why. */
  259. static uint32_t
  260. dirserv_router_get_status(const routerinfo_t *router, const char **msg)
  261. {
  262. char d[DIGEST_LEN];
  263. if (crypto_pk_get_digest(router->identity_pkey, d)) {
  264. log_warn(LD_BUG,"Error computing fingerprint");
  265. if (msg)
  266. *msg = "Bug: Error computing fingerprint";
  267. return FP_REJECT;
  268. }
  269. return dirserv_get_status_impl(d, router->nickname,
  270. router->address,
  271. router->addr, router->or_port,
  272. router->platform, router->contact_info,
  273. msg, 1);
  274. }
  275. /** Return true if there is no point in downloading the router described by
  276. * <b>rs</b> because this directory would reject it. */
  277. int
  278. dirserv_would_reject_router(routerstatus_t *rs)
  279. {
  280. uint32_t res;
  281. res = dirserv_get_status_impl(rs->identity_digest, rs->nickname,
  282. "", /* address is only used in logs */
  283. rs->addr, rs->or_port,
  284. NULL, NULL,
  285. NULL, 0);
  286. return (res & FP_REJECT) != 0;
  287. }
  288. /** Helper: Based only on the ID/Nickname combination,
  289. * return FP_UNNAMED (unnamed), FP_NAMED (named), or 0 (neither).
  290. */
  291. static uint32_t
  292. dirserv_get_name_status(const char *id_digest, const char *nickname)
  293. {
  294. char fp[HEX_DIGEST_LEN+1];
  295. char *fp_by_name;
  296. base16_encode(fp, sizeof(fp), id_digest, DIGEST_LEN);
  297. if ((fp_by_name =
  298. strmap_get_lc(fingerprint_list->fp_by_name, nickname))) {
  299. if (!strcasecmp(fp, fp_by_name)) {
  300. return FP_NAMED;
  301. } else {
  302. return FP_UNNAMED; /* Wrong fingerprint. */
  303. }
  304. }
  305. return 0;
  306. }
  307. /** Helper: As dirserv_get_router_status, but takes the router fingerprint
  308. * (hex, no spaces), nickname, address (used for logging only), IP address, OR
  309. * port, platform (logging only) and contact info (logging only) as arguments.
  310. *
  311. * If should_log is false, do not log messages. (There's not much point in
  312. * logging that we're rejecting servers we'll not download.)
  313. */
  314. static uint32_t
  315. dirserv_get_status_impl(const char *id_digest, const char *nickname,
  316. const char *address,
  317. uint32_t addr, uint16_t or_port,
  318. const char *platform, const char *contact,
  319. const char **msg, int should_log)
  320. {
  321. int reject_unlisted = get_options()->AuthDirRejectUnlisted;
  322. uint32_t result = 0;
  323. router_status_t *status_by_digest;
  324. if (!fingerprint_list)
  325. fingerprint_list = authdir_config_new();
  326. if (should_log)
  327. log_debug(LD_DIRSERV, "%d fingerprints, %d digests known.",
  328. strmap_size(fingerprint_list->fp_by_name),
  329. digestmap_size(fingerprint_list->status_by_digest));
  330. /* 0.1.1.17-rc was the first version that claimed to be stable, doesn't
  331. * crash and drop circuits all the time, and is even vaguely compatible with
  332. * the current network */
  333. if (platform && !tor_version_as_new_as(platform,"0.1.1.17-rc")) {
  334. if (msg)
  335. *msg = "Tor version is far too old to work.";
  336. return FP_REJECT;
  337. }
  338. result = dirserv_get_name_status(id_digest, nickname);
  339. if (result & FP_NAMED) {
  340. if (should_log)
  341. log_debug(LD_DIRSERV,"Good fingerprint for '%s'",nickname);
  342. }
  343. if (result & FP_UNNAMED) {
  344. if (should_log) {
  345. char *esc_contact = esc_for_log(contact);
  346. log_info(LD_DIRSERV,
  347. "Mismatched fingerprint for '%s'. "
  348. "ContactInfo '%s', platform '%s'.)",
  349. nickname,
  350. esc_contact,
  351. platform ? escaped(platform) : "");
  352. tor_free(esc_contact);
  353. }
  354. if (msg)
  355. *msg = "Rejected: There is already a named server with this nickname "
  356. "and a different fingerprint.";
  357. }
  358. status_by_digest = digestmap_get(fingerprint_list->status_by_digest,
  359. id_digest);
  360. if (status_by_digest)
  361. result |= (status_by_digest->status & ~FP_NAMED);
  362. if (result & FP_REJECT) {
  363. if (msg)
  364. *msg = "Fingerprint is marked rejected";
  365. return FP_REJECT;
  366. } else if (result & FP_INVALID) {
  367. if (msg)
  368. *msg = "Fingerprint is marked invalid";
  369. }
  370. if (authdir_policy_baddir_address(addr, or_port)) {
  371. if (should_log)
  372. log_info(LD_DIRSERV,
  373. "Marking '%s' as bad directory because of address '%s'",
  374. nickname, address);
  375. result |= FP_BADDIR;
  376. }
  377. if (authdir_policy_badexit_address(addr, or_port)) {
  378. if (should_log)
  379. log_info(LD_DIRSERV, "Marking '%s' as bad exit because of address '%s'",
  380. nickname, address);
  381. result |= FP_BADEXIT;
  382. }
  383. if (!(result & FP_NAMED)) {
  384. if (!authdir_policy_permits_address(addr, or_port)) {
  385. if (should_log)
  386. log_info(LD_DIRSERV, "Rejecting '%s' because of address '%s'",
  387. nickname, address);
  388. if (msg)
  389. *msg = "Authdir is rejecting routers in this range.";
  390. return FP_REJECT;
  391. }
  392. if (!authdir_policy_valid_address(addr, or_port)) {
  393. if (should_log)
  394. log_info(LD_DIRSERV, "Not marking '%s' valid because of address '%s'",
  395. nickname, address);
  396. result |= FP_INVALID;
  397. }
  398. if (reject_unlisted) {
  399. if (msg)
  400. *msg = "Authdir rejects unknown routers.";
  401. return FP_REJECT;
  402. }
  403. }
  404. return result;
  405. }
  406. /** If we are an authoritative dirserver, and the list of approved
  407. * servers contains one whose identity key digest is <b>digest</b>,
  408. * return that router's nickname. Otherwise return NULL. */
  409. const char *
  410. dirserv_get_nickname_by_digest(const char *digest)
  411. {
  412. router_status_t *status;
  413. if (!fingerprint_list)
  414. return NULL;
  415. tor_assert(digest);
  416. status = digestmap_get(fingerprint_list->status_by_digest, digest);
  417. return status ? status->nickname : NULL;
  418. }
  419. /** Clear the current fingerprint list. */
  420. void
  421. dirserv_free_fingerprint_list(void)
  422. {
  423. if (!fingerprint_list)
  424. return;
  425. strmap_free(fingerprint_list->fp_by_name, _tor_free);
  426. digestmap_free(fingerprint_list->status_by_digest, _tor_free);
  427. tor_free(fingerprint_list);
  428. }
  429. /*
  430. * Descriptor list
  431. */
  432. /** Return -1 if <b>ri</b> has a private or otherwise bad address,
  433. * unless we're configured to not care. Return 0 if all ok. */
  434. static int
  435. dirserv_router_has_valid_address(routerinfo_t *ri)
  436. {
  437. struct in_addr iaddr;
  438. if (get_options()->DirAllowPrivateAddresses)
  439. return 0; /* whatever it is, we're fine with it */
  440. if (!tor_inet_aton(ri->address, &iaddr)) {
  441. log_info(LD_DIRSERV,"Router '%s' published non-IP address '%s'. Refusing.",
  442. ri->nickname, ri->address);
  443. return -1;
  444. }
  445. if (is_internal_IP(ntohl(iaddr.s_addr), 0)) {
  446. log_info(LD_DIRSERV,
  447. "Router '%s' published internal IP address '%s'. Refusing.",
  448. ri->nickname, ri->address);
  449. return -1; /* it's a private IP, we should reject it */
  450. }
  451. return 0;
  452. }
  453. /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
  454. * set its is_valid,named,running fields and return 0. Otherwise, return -1.
  455. *
  456. * If the router is rejected, set *<b>msg</b> to an explanation of why.
  457. *
  458. * If <b>complain</b> then explain at log-level 'notice' why we refused
  459. * a descriptor; else explain at log-level 'info'.
  460. */
  461. int
  462. authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
  463. int complain)
  464. {
  465. /* Okay. Now check whether the fingerprint is recognized. */
  466. uint32_t status = dirserv_router_get_status(ri, msg);
  467. time_t now;
  468. int severity = complain ? LOG_NOTICE : LOG_INFO;
  469. tor_assert(msg);
  470. if (status & FP_REJECT)
  471. return -1; /* msg is already set. */
  472. /* Is there too much clock skew? */
  473. now = time(NULL);
  474. if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
  475. log_fn(severity, LD_DIRSERV, "Publication time for nickname '%s' is too "
  476. "far (%d minutes) in the future; possible clock skew. Not adding "
  477. "(%s)",
  478. ri->nickname, (int)((ri->cache_info.published_on-now)/60),
  479. esc_router_info(ri));
  480. *msg = "Rejected: Your clock is set too far in the future, or your "
  481. "timezone is not correct.";
  482. return -1;
  483. }
  484. if (ri->cache_info.published_on < now-ROUTER_MAX_AGE_TO_PUBLISH) {
  485. log_fn(severity, LD_DIRSERV,
  486. "Publication time for router with nickname '%s' is too far "
  487. "(%d minutes) in the past. Not adding (%s)",
  488. ri->nickname, (int)((now-ri->cache_info.published_on)/60),
  489. esc_router_info(ri));
  490. *msg = "Rejected: Server is expired, or your clock is too far in the past,"
  491. " or your timezone is not correct.";
  492. return -1;
  493. }
  494. if (dirserv_router_has_valid_address(ri) < 0) {
  495. log_fn(severity, LD_DIRSERV,
  496. "Router with nickname '%s' has invalid address '%s'. "
  497. "Not adding (%s).",
  498. ri->nickname, ri->address,
  499. esc_router_info(ri));
  500. *msg = "Rejected: Address is not an IP, or IP is a private address.";
  501. return -1;
  502. }
  503. /* Okay, looks like we're willing to accept this one. */
  504. ri->is_named = (status & FP_NAMED) ? 1 : 0;
  505. ri->is_valid = (status & FP_INVALID) ? 0 : 1;
  506. ri->is_bad_directory = (status & FP_BADDIR) ? 1 : 0;
  507. ri->is_bad_exit = (status & FP_BADEXIT) ? 1 : 0;
  508. return 0;
  509. }
  510. /** True iff <b>a</b> is more severe than <b>b</b>. */
  511. static int
  512. WRA_MORE_SEVERE(was_router_added_t a, was_router_added_t b)
  513. {
  514. return a < b;
  515. }
  516. /** As for dirserv_add_descriptor(), but accepts multiple documents, and
  517. * returns the most severe error that occurred for any one of them. */
  518. was_router_added_t
  519. dirserv_add_multiple_descriptors(const char *desc, uint8_t purpose,
  520. const char *source,
  521. const char **msg)
  522. {
  523. was_router_added_t r, r_tmp;
  524. const char *msg_out;
  525. smartlist_t *list;
  526. const char *s;
  527. int n_parsed = 0;
  528. time_t now = time(NULL);
  529. char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
  530. char time_buf[ISO_TIME_LEN+1];
  531. int general = purpose == ROUTER_PURPOSE_GENERAL;
  532. tor_assert(msg);
  533. r=ROUTER_ADDED_SUCCESSFULLY; /*Least severe return value. */
  534. format_iso_time(time_buf, now);
  535. if (tor_snprintf(annotation_buf, sizeof(annotation_buf),
  536. "@uploaded-at %s\n"
  537. "@source %s\n"
  538. "%s%s%s", time_buf, escaped(source),
  539. !general ? "@purpose " : "",
  540. !general ? router_purpose_to_string(purpose) : "",
  541. !general ? "\n" : "")<0) {
  542. *msg = "Couldn't format annotations";
  543. return -1;
  544. }
  545. s = desc;
  546. list = smartlist_create();
  547. if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 0, 0,
  548. annotation_buf)) {
  549. SMARTLIST_FOREACH(list, routerinfo_t *, ri, {
  550. msg_out = NULL;
  551. tor_assert(ri->purpose == purpose);
  552. r_tmp = dirserv_add_descriptor(ri, &msg_out, source);
  553. if (WRA_MORE_SEVERE(r_tmp, r)) {
  554. r = r_tmp;
  555. *msg = msg_out;
  556. }
  557. });
  558. }
  559. n_parsed += smartlist_len(list);
  560. smartlist_clear(list);
  561. s = desc;
  562. if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 1, 0,
  563. NULL)) {
  564. SMARTLIST_FOREACH(list, extrainfo_t *, ei, {
  565. msg_out = NULL;
  566. r_tmp = dirserv_add_extrainfo(ei, &msg_out);
  567. if (WRA_MORE_SEVERE(r_tmp, r)) {
  568. r = r_tmp;
  569. *msg = msg_out;
  570. }
  571. });
  572. }
  573. n_parsed += smartlist_len(list);
  574. smartlist_free(list);
  575. if (! *msg) {
  576. if (!n_parsed) {
  577. *msg = "No descriptors found in your POST.";
  578. if (WRA_WAS_ADDED(r))
  579. r = ROUTER_WAS_NOT_NEW;
  580. } else {
  581. *msg = "(no message)";
  582. }
  583. }
  584. return r;
  585. }
  586. /** Examine the parsed server descriptor in <b>ri</b> and maybe insert it into
  587. * the list of server descriptors. Set *<b>msg</b> to a message that should be
  588. * passed back to the origin of this descriptor. Use <b>source</b> to produce
  589. * better log messages.
  590. *
  591. * Return the status of the operation
  592. *
  593. * This function is only called when fresh descriptors are posted, not when
  594. * we re-load the cache.
  595. */
  596. was_router_added_t
  597. dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
  598. {
  599. was_router_added_t r;
  600. routerinfo_t *ri_old;
  601. char *desc, *nickname;
  602. size_t desclen = 0;
  603. /* If it's too big, refuse it now. Otherwise we'll cache it all over the
  604. * network and it'll clog everything up. */
  605. if (ri->cache_info.signed_descriptor_len > MAX_DESCRIPTOR_UPLOAD_SIZE) {
  606. log_notice(LD_DIR, "Somebody attempted to publish a router descriptor '%s'"
  607. " (source: %s) with size %d. Either this is an attack, or the "
  608. "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
  609. ri->nickname, source, (int)ri->cache_info.signed_descriptor_len,
  610. MAX_DESCRIPTOR_UPLOAD_SIZE);
  611. *msg = "Router descriptor was too large";
  612. control_event_or_authdir_new_descriptor("REJECTED",
  613. ri->cache_info.signed_descriptor_body,
  614. ri->cache_info.signed_descriptor_len, *msg);
  615. routerinfo_free(ri);
  616. return ROUTER_AUTHDIR_REJECTS;
  617. }
  618. /* Check whether this descriptor is semantically identical to the last one
  619. * from this server. (We do this here and not in router_add_to_routerlist
  620. * because we want to be able to accept the newest router descriptor that
  621. * another authority has, so we all converge on the same one.) */
  622. ri_old = router_get_by_digest(ri->cache_info.identity_digest);
  623. if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
  624. && router_differences_are_cosmetic(ri_old, ri)
  625. && !router_is_me(ri)) {
  626. log_info(LD_DIRSERV,
  627. "Not replacing descriptor from '%s' (source: %s); "
  628. "differences are cosmetic.",
  629. ri->nickname, source);
  630. *msg = "Not replacing router descriptor; no information has changed since "
  631. "the last one with this identity.";
  632. control_event_or_authdir_new_descriptor("DROPPED",
  633. ri->cache_info.signed_descriptor_body,
  634. ri->cache_info.signed_descriptor_len, *msg);
  635. routerinfo_free(ri);
  636. return ROUTER_WAS_NOT_NEW;
  637. }
  638. /* Make a copy of desc, since router_add_to_routerlist might free
  639. * ri and its associated signed_descriptor_t. */
  640. desclen = ri->cache_info.signed_descriptor_len;
  641. desc = tor_strndup(ri->cache_info.signed_descriptor_body, desclen);
  642. nickname = tor_strdup(ri->nickname);
  643. r = router_add_to_routerlist(ri, msg, 0, 0);
  644. if (!WRA_WAS_ADDED(r)) {
  645. /* unless the routerinfo was fine, just out-of-date */
  646. if (WRA_WAS_REJECTED(r))
  647. control_event_or_authdir_new_descriptor("REJECTED", desc, desclen, *msg);
  648. log_info(LD_DIRSERV,
  649. "Did not add descriptor from '%s' (source: %s): %s.",
  650. nickname, source, *msg);
  651. } else {
  652. smartlist_t *changed;
  653. control_event_or_authdir_new_descriptor("ACCEPTED", desc, desclen, *msg);
  654. changed = smartlist_create();
  655. smartlist_add(changed, ri);
  656. control_event_descriptors_changed(changed);
  657. smartlist_free(changed);
  658. if (!*msg) {
  659. *msg = ri->is_valid ? "Descriptor for valid server accepted" :
  660. "Descriptor for invalid server accepted";
  661. }
  662. log_info(LD_DIRSERV,
  663. "Added descriptor from '%s' (source: %s): %s.",
  664. nickname, source, *msg);
  665. }
  666. tor_free(desc);
  667. tor_free(nickname);
  668. return r;
  669. }
  670. /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
  671. static was_router_added_t
  672. dirserv_add_extrainfo(extrainfo_t *ei, const char **msg)
  673. {
  674. routerinfo_t *ri;
  675. int r;
  676. tor_assert(msg);
  677. *msg = NULL;
  678. ri = router_get_by_digest(ei->cache_info.identity_digest);
  679. if (!ri) {
  680. *msg = "No corresponding router descriptor for extra-info descriptor";
  681. extrainfo_free(ei);
  682. return ROUTER_BAD_EI;
  683. }
  684. /* If it's too big, refuse it now. Otherwise we'll cache it all over the
  685. * network and it'll clog everything up. */
  686. if (ei->cache_info.signed_descriptor_len > MAX_EXTRAINFO_UPLOAD_SIZE) {
  687. log_notice(LD_DIR, "Somebody attempted to publish an extrainfo "
  688. "with size %d. Either this is an attack, or the "
  689. "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
  690. (int)ei->cache_info.signed_descriptor_len,
  691. MAX_EXTRAINFO_UPLOAD_SIZE);
  692. *msg = "Extrainfo document was too large";
  693. extrainfo_free(ei);
  694. return ROUTER_BAD_EI;
  695. }
  696. if ((r = routerinfo_incompatible_with_extrainfo(ri, ei, NULL, msg))) {
  697. extrainfo_free(ei);
  698. return r < 0 ? ROUTER_WAS_NOT_NEW : ROUTER_BAD_EI;
  699. }
  700. router_add_extrainfo_to_routerlist(ei, msg, 0, 0);
  701. return ROUTER_ADDED_SUCCESSFULLY;
  702. }
  703. /** Remove all descriptors whose nicknames or fingerprints no longer
  704. * are allowed by our fingerprint list. (Descriptors that used to be
  705. * good can become bad when we reload the fingerprint list.)
  706. */
  707. static void
  708. directory_remove_invalid(void)
  709. {
  710. int i;
  711. int changed = 0;
  712. routerlist_t *rl = router_get_routerlist();
  713. routerlist_assert_ok(rl);
  714. for (i = 0; i < smartlist_len(rl->routers); ++i) {
  715. const char *msg;
  716. routerinfo_t *ent = smartlist_get(rl->routers, i);
  717. uint32_t r = dirserv_router_get_status(ent, &msg);
  718. if (r & FP_REJECT) {
  719. log_info(LD_DIRSERV, "Router '%s' is now rejected: %s",
  720. ent->nickname, msg?msg:"");
  721. routerlist_remove(rl, ent, 0);
  722. i--;
  723. changed = 1;
  724. continue;
  725. }
  726. if (bool_neq((r & FP_NAMED), ent->is_named)) {
  727. log_info(LD_DIRSERV,
  728. "Router '%s' is now %snamed.", ent->nickname,
  729. (r&FP_NAMED)?"":"un");
  730. ent->is_named = (r&FP_NAMED)?1:0;
  731. changed = 1;
  732. }
  733. if (bool_neq((r & FP_INVALID), !ent->is_valid)) {
  734. log_info(LD_DIRSERV, "Router '%s' is now %svalid.", ent->nickname,
  735. (r&FP_INVALID) ? "in" : "");
  736. ent->is_valid = (r&FP_INVALID)?0:1;
  737. changed = 1;
  738. }
  739. if (bool_neq((r & FP_BADDIR), ent->is_bad_directory)) {
  740. log_info(LD_DIRSERV, "Router '%s' is now a %s directory", ent->nickname,
  741. (r & FP_BADDIR) ? "bad" : "good");
  742. ent->is_bad_directory = (r&FP_BADDIR) ? 1: 0;
  743. changed = 1;
  744. }
  745. if (bool_neq((r & FP_BADEXIT), ent->is_bad_exit)) {
  746. log_info(LD_DIRSERV, "Router '%s' is now a %s exit", ent->nickname,
  747. (r & FP_BADEXIT) ? "bad" : "good");
  748. ent->is_bad_exit = (r&FP_BADEXIT) ? 1: 0;
  749. changed = 1;
  750. }
  751. }
  752. if (changed)
  753. directory_set_dirty();
  754. routerlist_assert_ok(rl);
  755. }
  756. /** Write a list of unregistered descriptors into a newly allocated
  757. * string and return it. Used by dirserv operators to keep track of
  758. * fast nodes that haven't registered.
  759. */
  760. int
  761. getinfo_helper_dirserv_unregistered(control_connection_t *control_conn,
  762. const char *question, char **answer_out)
  763. {
  764. smartlist_t *answerlist;
  765. char buf[1024];
  766. char *answer;
  767. int min_bw = atoi(question);
  768. routerlist_t *rl = router_get_routerlist();
  769. (void) control_conn;
  770. if (strcmpstart(question, "unregistered-servers-"))
  771. return 0;
  772. question += strlen("unregistered-servers-");
  773. answerlist = smartlist_create();
  774. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ent, {
  775. uint32_t r = dirserv_router_get_status(ent, NULL);
  776. if (router_get_advertised_bandwidth(ent) >= (size_t)min_bw &&
  777. !(r & FP_NAMED)) {
  778. /* then log this one */
  779. tor_snprintf(buf, sizeof(buf),
  780. "%s: BW %d on '%s'.",
  781. ent->nickname, router_get_advertised_bandwidth(ent),
  782. ent->platform ? ent->platform : "");
  783. smartlist_add(answerlist, tor_strdup(buf));
  784. }
  785. });
  786. answer = smartlist_join_strings(answerlist, "\r\n", 0, NULL);
  787. SMARTLIST_FOREACH(answerlist, char *, cp, tor_free(cp));
  788. smartlist_free(answerlist);
  789. *answer_out = answer;
  790. return 0;
  791. }
  792. /** Mark the directory as <b>dirty</b> -- when we're next asked for a
  793. * directory, we will rebuild it instead of reusing the most recently
  794. * generated one.
  795. */
  796. void
  797. directory_set_dirty(void)
  798. {
  799. time_t now = time(NULL);
  800. int set_v1_dirty=0;
  801. /* Regenerate stubs only every 8 hours.
  802. * XXXX It would be nice to generate less often, but these are just
  803. * stubs: it doesn't matter. */
  804. #define STUB_REGENERATE_INTERVAL (8*60*60)
  805. if (!the_directory || !the_runningrouters.dir)
  806. set_v1_dirty = 1;
  807. else if (the_directory->published < now - STUB_REGENERATE_INTERVAL ||
  808. the_runningrouters.published < now - STUB_REGENERATE_INTERVAL)
  809. set_v1_dirty = 1;
  810. if (set_v1_dirty) {
  811. if (!the_directory_is_dirty)
  812. the_directory_is_dirty = now;
  813. if (!runningrouters_is_dirty)
  814. runningrouters_is_dirty = now;
  815. }
  816. if (!the_v2_networkstatus_is_dirty)
  817. the_v2_networkstatus_is_dirty = now;
  818. }
  819. /**
  820. * Allocate and return a description of the status of the server <b>desc</b>,
  821. * for use in a v1-style router-status line. The server is listed
  822. * as running iff <b>is_live</b> is true.
  823. */
  824. static char *
  825. list_single_server_status(routerinfo_t *desc, int is_live)
  826. {
  827. char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
  828. char *cp;
  829. tor_assert(desc);
  830. cp = buf;
  831. if (!is_live) {
  832. *cp++ = '!';
  833. }
  834. if (desc->is_valid) {
  835. strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
  836. cp += strlen(cp);
  837. *cp++ = '=';
  838. }
  839. *cp++ = '$';
  840. base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
  841. DIGEST_LEN);
  842. return tor_strdup(buf);
  843. }
  844. /** Each server needs to have passed a reachability test no more
  845. * than this number of seconds ago, or he is listed as down in
  846. * the directory. */
  847. #define REACHABLE_TIMEOUT (45*60)
  848. /** Treat a router as alive if
  849. * - It's me, and I'm not hibernating.
  850. * or - We've found it reachable recently. */
  851. void
  852. dirserv_set_router_is_running(routerinfo_t *router, time_t now)
  853. {
  854. int answer;
  855. if (router_is_me(router) && !we_are_hibernating())
  856. answer = 1;
  857. else
  858. answer = get_options()->AssumeReachable ||
  859. now < router->last_reachable + REACHABLE_TIMEOUT;
  860. if (router->is_running && !answer) {
  861. /* it was running but now it's not. tell rephist. */
  862. rep_hist_note_router_unreachable(router->cache_info.identity_digest, now);
  863. }
  864. router->is_running = answer;
  865. }
  866. /** Based on the routerinfo_ts in <b>routers</b>, allocate the
  867. * contents of a v1-style router-status line, and store it in
  868. * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
  869. *
  870. * If for_controller is true, include the routers with very old descriptors.
  871. * If for_controller is &gt;1, use the verbose nickname format.
  872. */
  873. int
  874. list_server_status_v1(smartlist_t *routers, char **router_status_out,
  875. int for_controller)
  876. {
  877. /* List of entries in a router-status style: An optional !, then an optional
  878. * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
  879. smartlist_t *rs_entries;
  880. time_t now = time(NULL);
  881. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  882. or_options_t *options = get_options();
  883. /* We include v2 dir auths here too, because they need to answer
  884. * controllers. Eventually we'll deprecate this whole function;
  885. * see also networkstatus_getinfo_by_purpose(). */
  886. int authdir = authdir_mode_publishes_statuses(options);
  887. tor_assert(router_status_out);
  888. rs_entries = smartlist_create();
  889. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  890. {
  891. if (authdir) {
  892. /* Update router status in routerinfo_t. */
  893. dirserv_set_router_is_running(ri, now);
  894. }
  895. if (for_controller == 1 || ri->cache_info.published_on >= cutoff)
  896. smartlist_add(rs_entries, list_single_server_status(ri, ri->is_running));
  897. else if (for_controller > 2) {
  898. char name_buf[MAX_VERBOSE_NICKNAME_LEN+2];
  899. char *cp = name_buf;
  900. if (!ri->is_running)
  901. *cp++ = '!';
  902. router_get_verbose_nickname(cp, ri);
  903. smartlist_add(rs_entries, tor_strdup(name_buf));
  904. }
  905. });
  906. *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
  907. SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
  908. smartlist_free(rs_entries);
  909. return 0;
  910. }
  911. /** Given a (possibly empty) list of config_line_t, each line of which contains
  912. * a list of comma-separated version numbers surrounded by optional space,
  913. * allocate and return a new string containing the version numbers, in order,
  914. * separated by commas. Used to generate Recommended(Client|Server)?Versions
  915. */
  916. static char *
  917. format_versions_list(config_line_t *ln)
  918. {
  919. smartlist_t *versions;
  920. char *result;
  921. versions = smartlist_create();
  922. for ( ; ln; ln = ln->next) {
  923. smartlist_split_string(versions, ln->value, ",",
  924. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  925. }
  926. sort_version_list(versions, 1);
  927. result = smartlist_join_strings(versions,",",0,NULL);
  928. SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
  929. smartlist_free(versions);
  930. return result;
  931. }
  932. /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
  933. * not hibernating, and not too old. Else return 0.
  934. */
  935. static int
  936. router_is_active(routerinfo_t *ri, time_t now)
  937. {
  938. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  939. if (ri->cache_info.published_on < cutoff)
  940. return 0;
  941. if (!ri->is_running || !ri->is_valid || ri->is_hibernating)
  942. return 0;
  943. return 1;
  944. }
  945. /** Generate a new v1 directory and write it into a newly allocated string.
  946. * Point *<b>dir_out</b> to the allocated string. Sign the
  947. * directory with <b>private_key</b>. Return 0 on success, -1 on
  948. * failure. If <b>complete</b> is set, give us all the descriptors;
  949. * otherwise leave out non-running and non-valid ones.
  950. */
  951. int
  952. dirserv_dump_directory_to_string(char **dir_out,
  953. crypto_pk_env_t *private_key)
  954. {
  955. char *cp;
  956. char *identity_pkey; /* Identity key, DER64-encoded. */
  957. char *recommended_versions;
  958. char digest[DIGEST_LEN];
  959. char published[ISO_TIME_LEN+1];
  960. char *buf = NULL;
  961. size_t buf_len;
  962. size_t identity_pkey_len;
  963. time_t now = time(NULL);
  964. tor_assert(dir_out);
  965. *dir_out = NULL;
  966. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  967. &identity_pkey_len)<0) {
  968. log_warn(LD_BUG,"write identity_pkey to string failed!");
  969. return -1;
  970. }
  971. recommended_versions =
  972. format_versions_list(get_options()->RecommendedVersions);
  973. format_iso_time(published, now);
  974. buf_len = 2048+strlen(recommended_versions);
  975. buf = tor_malloc(buf_len);
  976. /* We'll be comparing against buf_len throughout the rest of the
  977. function, though strictly speaking we shouldn't be able to exceed
  978. it. This is C, after all, so we may as well check for buffer
  979. overruns.*/
  980. tor_snprintf(buf, buf_len,
  981. "signed-directory\n"
  982. "published %s\n"
  983. "recommended-software %s\n"
  984. "router-status %s\n"
  985. "dir-signing-key\n%s\n",
  986. published, recommended_versions, "",
  987. identity_pkey);
  988. tor_free(recommended_versions);
  989. tor_free(identity_pkey);
  990. cp = buf + strlen(buf);
  991. *cp = '\0';
  992. /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
  993. signature. */
  994. if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
  995. goto truncated;
  996. if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
  997. goto truncated;
  998. if (strlcat(buf, "\n", buf_len) >= buf_len)
  999. goto truncated;
  1000. if (router_get_dir_hash(buf,digest)) {
  1001. log_warn(LD_BUG,"couldn't compute digest");
  1002. tor_free(buf);
  1003. return -1;
  1004. }
  1005. note_crypto_pk_op(SIGN_DIR);
  1006. if (router_append_dirobj_signature(buf,buf_len,digest,private_key)<0) {
  1007. tor_free(buf);
  1008. return -1;
  1009. }
  1010. *dir_out = buf;
  1011. return 0;
  1012. truncated:
  1013. log_warn(LD_BUG,"tried to exceed string length.");
  1014. tor_free(buf);
  1015. return -1;
  1016. }
  1017. /********************************************************************/
  1018. /* A set of functions to answer questions about how we'd like to behave
  1019. * as a directory mirror/client. */
  1020. /** Return 1 if we fetch our directory material directly from the
  1021. * authorities, rather than from a mirror. */
  1022. int
  1023. directory_fetches_from_authorities(or_options_t *options)
  1024. {
  1025. routerinfo_t *me;
  1026. uint32_t addr;
  1027. if (options->FetchDirInfoEarly)
  1028. return 1;
  1029. if (options->BridgeRelay == 1)
  1030. return 0;
  1031. if (server_mode(options) && router_pick_published_address(options, &addr)<0)
  1032. return 1; /* we don't know our IP address; ask an authority. */
  1033. if (options->DirPort == 0)
  1034. return 0;
  1035. if (!server_mode(options) || !advertised_server_mode())
  1036. return 0;
  1037. me = router_get_my_routerinfo();
  1038. if (!me || !me->dir_port)
  1039. return 0; /* if dirport not advertised, return 0 too */
  1040. return 1;
  1041. }
  1042. /** Return 1 if we should fetch new networkstatuses, descriptors, etc
  1043. * on the "mirror" schedule rather than the "client" schedule.
  1044. */
  1045. int
  1046. directory_fetches_dir_info_early(or_options_t *options)
  1047. {
  1048. return directory_fetches_from_authorities(options);
  1049. }
  1050. /** Return 1 if we should fetch new networkstatuses, descriptors, etc
  1051. * on a very passive schedule -- waiting long enough for ordinary clients
  1052. * to probably have the info we want. These would include bridge users,
  1053. * and maybe others in the future e.g. if a Tor client uses another Tor
  1054. * client as a directory guard.
  1055. */
  1056. int
  1057. directory_fetches_dir_info_later(or_options_t *options)
  1058. {
  1059. return options->UseBridges != 0;
  1060. }
  1061. /** Return 1 if we want to cache v2 dir info (each status file).
  1062. */
  1063. int
  1064. directory_caches_v2_dir_info(or_options_t *options)
  1065. {
  1066. return options->DirPort != 0;
  1067. }
  1068. /** Return 1 if we want to keep descriptors, networkstatuses, etc around
  1069. * and we're willing to serve them to others. Else return 0.
  1070. */
  1071. int
  1072. directory_caches_dir_info(or_options_t *options)
  1073. {
  1074. return options->BridgeRelay != 0 || options->DirPort != 0;
  1075. }
  1076. /** Return 1 if we want to allow remote people to ask us directory
  1077. * requests via the "begin_dir" interface, which doesn't require
  1078. * having any separate port open. */
  1079. int
  1080. directory_permits_begindir_requests(or_options_t *options)
  1081. {
  1082. return options->BridgeRelay != 0 || options->DirPort != 0;
  1083. }
  1084. /** Return 1 if we want to allow controllers to ask us directory
  1085. * requests via the controller interface, which doesn't require
  1086. * having any separate port open. */
  1087. int
  1088. directory_permits_controller_requests(or_options_t *options)
  1089. {
  1090. return options->DirPort != 0;
  1091. }
  1092. /** Return 1 if we have no need to fetch new descriptors. This generally
  1093. * happens when we're not a dir cache and we haven't built any circuits
  1094. * lately.
  1095. */
  1096. int
  1097. directory_too_idle_to_fetch_descriptors(or_options_t *options, time_t now)
  1098. {
  1099. return !directory_caches_dir_info(options) &&
  1100. !options->FetchUselessDescriptors &&
  1101. rep_hist_circbuilding_dormant(now);
  1102. }
  1103. /********************************************************************/
  1104. /* Used only by non-v1-auth dirservers: The v1 directory and
  1105. * runningrouters we'll serve when requested. */
  1106. /** The v1 directory we'll serve (as a cache or as an authority) if
  1107. * requested. */
  1108. static cached_dir_t *cached_directory = NULL;
  1109. /** The v1 runningrouters document we'll serve (as a cache or as an authority)
  1110. * if requested. */
  1111. static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0, -1 };
  1112. /** Used for other dirservers' v2 network statuses. Map from hexdigest to
  1113. * cached_dir_t. */
  1114. static digestmap_t *cached_v2_networkstatus = NULL;
  1115. /** The v3 consensus network status that we're currently serving. */
  1116. static cached_dir_t *cached_v3_networkstatus = NULL;
  1117. /** Possibly replace the contents of <b>d</b> with the value of
  1118. * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
  1119. * the last value, or too far in the future.
  1120. *
  1121. * Does not copy <b>directory</b>; frees it if it isn't used.
  1122. */
  1123. static void
  1124. set_cached_dir(cached_dir_t *d, char *directory, time_t when)
  1125. {
  1126. time_t now = time(NULL);
  1127. if (when<=d->published) {
  1128. log_info(LD_DIRSERV, "Ignoring old directory; not caching.");
  1129. tor_free(directory);
  1130. } else if (when>=now+ROUTER_MAX_AGE_TO_PUBLISH) {
  1131. log_info(LD_DIRSERV, "Ignoring future directory; not caching.");
  1132. tor_free(directory);
  1133. } else {
  1134. /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
  1135. log_debug(LD_DIRSERV, "Caching directory.");
  1136. tor_free(d->dir);
  1137. d->dir = directory;
  1138. d->dir_len = strlen(directory);
  1139. tor_free(d->dir_z);
  1140. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  1141. ZLIB_METHOD)) {
  1142. log_warn(LD_BUG,"Error compressing cached directory");
  1143. }
  1144. d->published = when;
  1145. }
  1146. }
  1147. /** Decrement the reference count on <b>d</b>, and free it if it no longer has
  1148. * any references. */
  1149. void
  1150. cached_dir_decref(cached_dir_t *d)
  1151. {
  1152. if (!d || --d->refcnt > 0)
  1153. return;
  1154. clear_cached_dir(d);
  1155. tor_free(d);
  1156. }
  1157. /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
  1158. * published at <b>published</b>. */
  1159. cached_dir_t *
  1160. new_cached_dir(char *s, time_t published)
  1161. {
  1162. cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
  1163. d->refcnt = 1;
  1164. d->dir = s;
  1165. d->dir_len = strlen(s);
  1166. d->published = published;
  1167. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  1168. ZLIB_METHOD)) {
  1169. log_warn(LD_BUG, "Error compressing directory");
  1170. }
  1171. return d;
  1172. }
  1173. /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
  1174. static void
  1175. clear_cached_dir(cached_dir_t *d)
  1176. {
  1177. tor_free(d->dir);
  1178. tor_free(d->dir_z);
  1179. memset(d, 0, sizeof(cached_dir_t));
  1180. }
  1181. /** Free all storage held by the cached_dir_t in <b>d</b>. */
  1182. static void
  1183. _free_cached_dir(void *_d)
  1184. {
  1185. cached_dir_t *d = (cached_dir_t *)_d;
  1186. cached_dir_decref(d);
  1187. }
  1188. /** If we have no cached v1 directory, or it is older than <b>published</b>,
  1189. * then replace it with <b>directory</b>, published at <b>published</b>.
  1190. *
  1191. * If <b>published</b> is too old, do nothing.
  1192. *
  1193. * If <b>is_running_routers</b>, this is really a v1 running_routers
  1194. * document rather than a v1 directory.
  1195. */
  1196. void
  1197. dirserv_set_cached_directory(const char *directory, time_t published,
  1198. int is_running_routers)
  1199. {
  1200. time_t now = time(NULL);
  1201. if (is_running_routers) {
  1202. if (published >= now - MAX_V1_RR_AGE)
  1203. set_cached_dir(&cached_runningrouters, tor_strdup(directory), published);
  1204. } else {
  1205. if (published >= now - MAX_V1_DIRECTORY_AGE) {
  1206. cached_dir_decref(cached_directory);
  1207. cached_directory = new_cached_dir(tor_strdup(directory), published);
  1208. }
  1209. }
  1210. }
  1211. /** If <b>networkstatus</b> is non-NULL, we've just received a v2
  1212. * network-status for an authoritative directory with identity digest
  1213. * <b>identity</b> published at <b>published</b> -- store it so we can
  1214. * serve it to others.
  1215. *
  1216. * If <b>networkstatus</b> is NULL, remove the entry with the given
  1217. * identity fingerprint from the v2 cache.
  1218. */
  1219. void
  1220. dirserv_set_cached_networkstatus_v2(const char *networkstatus,
  1221. const char *identity,
  1222. time_t published)
  1223. {
  1224. cached_dir_t *d, *old_d;
  1225. smartlist_t *trusted_dirs;
  1226. if (!cached_v2_networkstatus)
  1227. cached_v2_networkstatus = digestmap_new();
  1228. old_d = digestmap_get(cached_v2_networkstatus, identity);
  1229. if (!old_d && !networkstatus)
  1230. return;
  1231. if (networkstatus) {
  1232. if (!old_d || published > old_d->published) {
  1233. d = new_cached_dir(tor_strdup(networkstatus), published);
  1234. digestmap_set(cached_v2_networkstatus, identity, d);
  1235. if (old_d)
  1236. cached_dir_decref(old_d);
  1237. }
  1238. } else {
  1239. if (old_d) {
  1240. digestmap_remove(cached_v2_networkstatus, identity);
  1241. cached_dir_decref(old_d);
  1242. }
  1243. }
  1244. /* Now purge old entries. */
  1245. trusted_dirs = router_get_trusted_dir_servers();
  1246. if (digestmap_size(cached_v2_networkstatus) >
  1247. smartlist_len(trusted_dirs) + MAX_UNTRUSTED_NETWORKSTATUSES) {
  1248. /* We need to remove the oldest untrusted networkstatus. */
  1249. const char *oldest = NULL;
  1250. time_t oldest_published = TIME_MAX;
  1251. digestmap_iter_t *iter;
  1252. for (iter = digestmap_iter_init(cached_v2_networkstatus);
  1253. !digestmap_iter_done(iter);
  1254. iter = digestmap_iter_next(cached_v2_networkstatus, iter)) {
  1255. const char *ident;
  1256. void *val;
  1257. digestmap_iter_get(iter, &ident, &val);
  1258. d = val;
  1259. if (d->published < oldest_published &&
  1260. !router_digest_is_trusted_dir(ident)) {
  1261. oldest = ident;
  1262. oldest_published = d->published;
  1263. }
  1264. }
  1265. tor_assert(oldest);
  1266. d = digestmap_remove(cached_v2_networkstatus, oldest);
  1267. if (d)
  1268. cached_dir_decref(d);
  1269. }
  1270. }
  1271. /** Replace the v3 consensus networkstatus that we're serving with
  1272. * <b>networkstatus</b>, published at <b>published</b>. No validation is
  1273. * performed. */
  1274. void
  1275. dirserv_set_cached_networkstatus_v3(const char *networkstatus,
  1276. time_t published)
  1277. {
  1278. if (cached_v3_networkstatus)
  1279. cached_dir_decref(cached_v3_networkstatus);
  1280. cached_v3_networkstatus = new_cached_dir(
  1281. tor_strdup(networkstatus), published);
  1282. }
  1283. /** Remove any v2 networkstatus from the directory cache that was published
  1284. * before <b>cutoff</b>. */
  1285. void
  1286. dirserv_clear_old_networkstatuses(time_t cutoff)
  1287. {
  1288. if (!cached_v2_networkstatus)
  1289. return;
  1290. DIGESTMAP_FOREACH_MODIFY(cached_v2_networkstatus, id, cached_dir_t *, dir) {
  1291. if (dir->published < cutoff) {
  1292. char *fname;
  1293. fname = networkstatus_get_cache_filename(id);
  1294. if (file_status(fname) == FN_FILE) {
  1295. log_info(LD_DIR, "Removing too-old untrusted networkstatus in %s",
  1296. fname);
  1297. unlink(fname);
  1298. }
  1299. tor_free(fname);
  1300. cached_dir_decref(dir);
  1301. MAP_DEL_CURRENT(id);
  1302. }
  1303. } DIGESTMAP_FOREACH_END
  1304. }
  1305. /** Remove any v1 info from the directory cache that was published
  1306. * too long ago. */
  1307. void
  1308. dirserv_clear_old_v1_info(time_t now)
  1309. {
  1310. if (cached_directory &&
  1311. cached_directory->published < (now - MAX_V1_DIRECTORY_AGE)) {
  1312. cached_dir_decref(cached_directory);
  1313. cached_directory = NULL;
  1314. }
  1315. if (cached_runningrouters.published < (now - MAX_V1_RR_AGE)) {
  1316. clear_cached_dir(&cached_runningrouters);
  1317. }
  1318. }
  1319. /** Helper: If we're an authority for the right directory version (v1 or v2)
  1320. * (based on <b>auth_type</b>), try to regenerate
  1321. * auth_src as appropriate and return it, falling back to cache_src on
  1322. * failure. If we're a cache, simply return cache_src.
  1323. */
  1324. static cached_dir_t *
  1325. dirserv_pick_cached_dir_obj(cached_dir_t *cache_src,
  1326. cached_dir_t *auth_src,
  1327. time_t dirty, cached_dir_t *(*regenerate)(void),
  1328. const char *name,
  1329. authority_type_t auth_type)
  1330. {
  1331. or_options_t *options = get_options();
  1332. int authority = (auth_type == V1_AUTHORITY && authdir_mode_v1(options)) ||
  1333. (auth_type == V2_AUTHORITY && authdir_mode_v2(options));
  1334. if (!authority || authdir_mode_bridge(options)) {
  1335. return cache_src;
  1336. } else {
  1337. /* We're authoritative. */
  1338. if (regenerate != NULL) {
  1339. if (dirty && dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  1340. if (!(auth_src = regenerate())) {
  1341. log_err(LD_BUG, "Couldn't generate %s?", name);
  1342. exit(1);
  1343. }
  1344. } else {
  1345. log_info(LD_DIRSERV, "The %s is still clean; reusing.", name);
  1346. }
  1347. }
  1348. return auth_src ? auth_src : cache_src;
  1349. }
  1350. }
  1351. /** Return the most recently generated encoded signed v1 directory,
  1352. * generating a new one as necessary. If not a v1 authoritative directory
  1353. * may return NULL if no directory is yet cached. */
  1354. cached_dir_t *
  1355. dirserv_get_directory(void)
  1356. {
  1357. return dirserv_pick_cached_dir_obj(cached_directory, the_directory,
  1358. the_directory_is_dirty,
  1359. dirserv_regenerate_directory,
  1360. "v1 server directory", V1_AUTHORITY);
  1361. }
  1362. /** Only called by v1 auth dirservers.
  1363. * Generate a fresh v1 directory; set the_directory and return a pointer
  1364. * to the new value.
  1365. */
  1366. static cached_dir_t *
  1367. dirserv_regenerate_directory(void)
  1368. {
  1369. char *new_directory=NULL;
  1370. if (dirserv_dump_directory_to_string(&new_directory, get_identity_key())) {
  1371. log_warn(LD_BUG, "Error creating directory.");
  1372. tor_free(new_directory);
  1373. return NULL;
  1374. }
  1375. cached_dir_decref(the_directory);
  1376. the_directory = new_cached_dir(new_directory, time(NULL));
  1377. log_info(LD_DIRSERV,"New directory (size %d) has been built.",
  1378. (int)the_directory->dir_len);
  1379. log_debug(LD_DIRSERV,"New directory (size %d):\n%s",
  1380. (int)the_directory->dir_len, the_directory->dir);
  1381. the_directory_is_dirty = 0;
  1382. /* Save the directory to disk so we re-load it quickly on startup.
  1383. */
  1384. dirserv_set_cached_directory(the_directory->dir, time(NULL), 0);
  1385. return the_directory;
  1386. }
  1387. /** Only called by v1 auth dirservers.
  1388. * Replace the current running-routers list with a newly generated one. */
  1389. static cached_dir_t *
  1390. generate_runningrouters(void)
  1391. {
  1392. char *s=NULL;
  1393. char digest[DIGEST_LEN];
  1394. char published[ISO_TIME_LEN+1];
  1395. size_t len;
  1396. crypto_pk_env_t *private_key = get_identity_key();
  1397. char *identity_pkey; /* Identity key, DER64-encoded. */
  1398. size_t identity_pkey_len;
  1399. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  1400. &identity_pkey_len)<0) {
  1401. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1402. goto err;
  1403. }
  1404. format_iso_time(published, time(NULL));
  1405. len = 2048;
  1406. s = tor_malloc_zero(len);
  1407. tor_snprintf(s, len,
  1408. "network-status\n"
  1409. "published %s\n"
  1410. "router-status %s\n"
  1411. "dir-signing-key\n%s"
  1412. "directory-signature %s\n",
  1413. published, "", identity_pkey,
  1414. get_options()->Nickname);
  1415. tor_free(identity_pkey);
  1416. if (router_get_runningrouters_hash(s,digest)) {
  1417. log_warn(LD_BUG,"couldn't compute digest");
  1418. goto err;
  1419. }
  1420. note_crypto_pk_op(SIGN_DIR);
  1421. if (router_append_dirobj_signature(s, len, digest, private_key)<0)
  1422. goto err;
  1423. set_cached_dir(&the_runningrouters, s, time(NULL));
  1424. runningrouters_is_dirty = 0;
  1425. return &the_runningrouters;
  1426. err:
  1427. tor_free(s);
  1428. return NULL;
  1429. }
  1430. /** Set *<b>rr</b> to the most recently generated encoded signed
  1431. * running-routers list, generating a new one as necessary. Return the
  1432. * size of the directory on success, and 0 on failure. */
  1433. cached_dir_t *
  1434. dirserv_get_runningrouters(void)
  1435. {
  1436. return dirserv_pick_cached_dir_obj(
  1437. &cached_runningrouters, &the_runningrouters,
  1438. runningrouters_is_dirty,
  1439. generate_runningrouters,
  1440. "v1 network status list", V1_AUTHORITY);
  1441. }
  1442. /** Return the latest downloaded consensus networkstatus in encoded, signed,
  1443. * optionally compressed format, suitable for sending to clients. */
  1444. cached_dir_t *
  1445. dirserv_get_consensus(void)
  1446. {
  1447. return cached_v3_networkstatus;
  1448. }
  1449. /** For authoritative directories: the current (v2) network status. */
  1450. static cached_dir_t *the_v2_networkstatus = NULL;
  1451. /** Return true iff our opinion of the routers has been stale for long
  1452. * enough that we should generate a new v2 network status doc. */
  1453. static int
  1454. should_generate_v2_networkstatus(void)
  1455. {
  1456. return authdir_mode_v2(get_options()) &&
  1457. the_v2_networkstatus_is_dirty &&
  1458. the_v2_networkstatus_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL);
  1459. }
  1460. /** If a router's uptime is at least this value, then it is always
  1461. * considered stable, regardless of the rest of the network. This
  1462. * way we resist attacks where an attacker doubles the size of the
  1463. * network using allegedly high-uptime nodes, displacing all the
  1464. * current guards. */
  1465. #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
  1466. /** If a router's MTBF is at least this value, then it is always stable.
  1467. * See above. (Corresponds to about 7 days for current decay rates.) */
  1468. #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
  1469. /** Similarly, we protect sufficiently fast nodes from being pushed
  1470. * out of the set of Fast nodes. */
  1471. #define BANDWIDTH_TO_GUARANTEE_FAST ROUTER_REQUIRED_MIN_BANDWIDTH
  1472. /** Similarly, every node with sufficient bandwidth can be considered
  1473. * for Guard status. */
  1474. #define BANDWIDTH_TO_GUARANTEE_GUARD (250*1024)
  1475. /** Similarly, every node with at least this much weighted time known can be
  1476. * considered familiar enough to be a guard. Corresponds to about 20 days for
  1477. * current decay rates.
  1478. */
  1479. #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
  1480. /** Similarly, every node with sufficient WFU is around enough to be a guard.
  1481. */
  1482. #define WFU_TO_GUARANTEE_GUARD (0.995)
  1483. /* Thresholds for server performance: set by
  1484. * dirserv_compute_performance_thresholds, and used by
  1485. * generate_v2_networkstatus */
  1486. /** Any router with an uptime of at least this value is stable. */
  1487. static uint32_t stable_uptime = 0; /* start at a safe value */
  1488. /** Any router with an mtbf of at least this value is stable. */
  1489. static double stable_mtbf = 0.0;
  1490. /** If true, we have measured enough mtbf info to look at stable_mtbf rather
  1491. * than stable_uptime. */
  1492. static int enough_mtbf_info = 0;
  1493. /** Any router with a weighted fractional uptime of at least this much might
  1494. * be good as a guard. */
  1495. static double guard_wfu = 0.0;
  1496. /** Don't call a router a guard unless we've known about it for at least this
  1497. * many seconds. */
  1498. static long guard_tk = 0;
  1499. /** Any router with a bandwidth at least this high is "Fast" */
  1500. static uint32_t fast_bandwidth = 0;
  1501. /** If exits can be guards, then all guards must have a bandwidth this
  1502. * high. */
  1503. static uint32_t guard_bandwidth_including_exits = 0;
  1504. /** If exits can't be guards, then all guards must have a bandwidth this
  1505. * high. */
  1506. static uint32_t guard_bandwidth_excluding_exits = 0;
  1507. /** Total bandwidth of all the routers we're considering. */
  1508. static uint64_t total_bandwidth = 0;
  1509. /** Total bandwidth of all the exit routers we're considering. */
  1510. static uint64_t total_exit_bandwidth = 0;
  1511. /** Helper: estimate the uptime of a router given its stated uptime and the
  1512. * amount of time since it last stated its stated uptime. */
  1513. static INLINE long
  1514. real_uptime(routerinfo_t *router, time_t now)
  1515. {
  1516. if (now < router->cache_info.published_on)
  1517. return router->uptime;
  1518. else
  1519. return router->uptime + (now - router->cache_info.published_on);
  1520. }
  1521. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  1522. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  1523. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  1524. * bandwidth.
  1525. */
  1526. static int
  1527. dirserv_thinks_router_is_unreliable(time_t now,
  1528. routerinfo_t *router,
  1529. int need_uptime, int need_capacity)
  1530. {
  1531. if (need_uptime) {
  1532. if (!enough_mtbf_info) {
  1533. /* XXX022 Once most authorities are on v3, we should change the rule from
  1534. * "use uptime if we don't have mtbf data" to "don't advertise Stable on
  1535. * v3 if we don't have enough mtbf data." */
  1536. long uptime = real_uptime(router, now);
  1537. if ((unsigned)uptime < stable_uptime &&
  1538. (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
  1539. return 1;
  1540. } else {
  1541. double mtbf =
  1542. rep_hist_get_stability(router->cache_info.identity_digest, now);
  1543. if (mtbf < stable_mtbf &&
  1544. mtbf < MTBF_TO_GUARANTEE_STABLE)
  1545. return 1;
  1546. }
  1547. }
  1548. if (need_capacity) {
  1549. uint32_t bw = router_get_advertised_bandwidth(router);
  1550. if (bw < fast_bandwidth)
  1551. return 1;
  1552. }
  1553. return 0;
  1554. }
  1555. /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
  1556. * Right now this means it advertises support for it, it has a high
  1557. * uptime, and it's currently considered Running.
  1558. *
  1559. * This function needs to be called after router-\>is_running has
  1560. * been set.
  1561. */
  1562. static int
  1563. dirserv_thinks_router_is_hs_dir(routerinfo_t *router, time_t now)
  1564. {
  1565. long uptime = real_uptime(router, now);
  1566. return (router->wants_to_be_hs_dir &&
  1567. uptime > get_options()->MinUptimeHidServDirectoryV2 &&
  1568. router->is_running);
  1569. }
  1570. /** Look through the routerlist, the Mean Time Between Failure history, and
  1571. * the Weighted Fractional Uptime history, and use them to set thresholds for
  1572. * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
  1573. * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
  1574. * guard_bandwidh_including_exits, guard_bandwidth_excluding_exits,
  1575. * total_bandwidth, and total_exit_bandwidth.
  1576. *
  1577. * Also, set the is_exit flag of each router appropriately. */
  1578. static void
  1579. dirserv_compute_performance_thresholds(routerlist_t *rl)
  1580. {
  1581. int n_active, n_active_nonexit, n_familiar;
  1582. uint32_t *uptimes, *bandwidths, *bandwidths_excluding_exits;
  1583. long *tks;
  1584. double *mtbfs, *wfus;
  1585. time_t now = time(NULL);
  1586. /* initialize these all here, in case there are no routers */
  1587. stable_uptime = 0;
  1588. stable_mtbf = 0;
  1589. fast_bandwidth = 0;
  1590. guard_bandwidth_including_exits = 0;
  1591. guard_bandwidth_excluding_exits = 0;
  1592. guard_tk = 0;
  1593. guard_wfu = 0;
  1594. total_bandwidth = 0;
  1595. total_exit_bandwidth = 0;
  1596. /* Initialize arrays that will hold values for each router. We'll
  1597. * sort them and use that to compute thresholds. */
  1598. n_active = n_active_nonexit = 0;
  1599. /* Uptime for every active router. */
  1600. uptimes = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
  1601. /* Bandwidth for every active router. */
  1602. bandwidths = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
  1603. /* Bandwidth for every active non-exit router. */
  1604. bandwidths_excluding_exits =
  1605. tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
  1606. /* Weighted mean time between failure for each active router. */
  1607. mtbfs = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
  1608. /* Time-known for each active router. */
  1609. tks = tor_malloc(sizeof(long)*smartlist_len(rl->routers));
  1610. /* Weighted fractional uptime for each active router. */
  1611. wfus = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
  1612. /* Now, fill in the arrays. */
  1613. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1614. if (router_is_active(ri, now)) {
  1615. const char *id = ri->cache_info.identity_digest;
  1616. uint32_t bw;
  1617. ri->is_exit = exit_policy_is_general_exit(ri->exit_policy);
  1618. uptimes[n_active] = (uint32_t)real_uptime(ri, now);
  1619. mtbfs[n_active] = rep_hist_get_stability(id, now);
  1620. tks [n_active] = rep_hist_get_weighted_time_known(id, now);
  1621. bandwidths[n_active] = bw = router_get_advertised_bandwidth(ri);
  1622. total_bandwidth += bw;
  1623. if (ri->is_exit && !ri->is_bad_exit) {
  1624. total_exit_bandwidth += bw;
  1625. } else {
  1626. bandwidths_excluding_exits[n_active_nonexit] = bw;
  1627. ++n_active_nonexit;
  1628. }
  1629. ++n_active;
  1630. }
  1631. });
  1632. /* Now, compute thresholds. */
  1633. if (n_active) {
  1634. /* The median uptime is stable. */
  1635. stable_uptime = median_uint32(uptimes, n_active);
  1636. /* The median mtbf is stable, if we have enough mtbf info */
  1637. stable_mtbf = median_double(mtbfs, n_active);
  1638. /* The 12.5th percentile bandwidth is fast. */
  1639. fast_bandwidth = find_nth_uint32(bandwidths, n_active, n_active/8);
  1640. /* (Now bandwidths is sorted.) */
  1641. if (fast_bandwidth < ROUTER_REQUIRED_MIN_BANDWIDTH/2)
  1642. fast_bandwidth = bandwidths[n_active/4];
  1643. guard_bandwidth_including_exits = bandwidths[(n_active-1)/2];
  1644. guard_tk = find_nth_long(tks, n_active, n_active/8);
  1645. }
  1646. if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
  1647. guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
  1648. if (fast_bandwidth > BANDWIDTH_TO_GUARANTEE_FAST)
  1649. fast_bandwidth = BANDWIDTH_TO_GUARANTEE_FAST;
  1650. /* Now that we have a time-known that 7/8 routers are known longer than,
  1651. * fill wfus with the wfu of every such "familiar" router. */
  1652. n_familiar = 0;
  1653. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1654. if (router_is_active(ri, now)) {
  1655. const char *id = ri->cache_info.identity_digest;
  1656. long tk = rep_hist_get_weighted_time_known(id, now);
  1657. if (tk < guard_tk)
  1658. continue;
  1659. wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
  1660. }
  1661. });
  1662. if (n_familiar)
  1663. guard_wfu = median_double(wfus, n_familiar);
  1664. if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
  1665. guard_wfu = WFU_TO_GUARANTEE_GUARD;
  1666. enough_mtbf_info = rep_hist_have_measured_enough_stability();
  1667. if (n_active_nonexit) {
  1668. guard_bandwidth_excluding_exits =
  1669. median_uint32(bandwidths_excluding_exits, n_active_nonexit);
  1670. }
  1671. log(LOG_INFO, LD_DIRSERV,
  1672. "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
  1673. "For Fast: %lu bytes/sec. "
  1674. "For Guard: WFU %.03lf%%, time-known %lu sec, "
  1675. "and bandwidth %lu or %lu bytes/sec. We%s have enough stability data.",
  1676. (unsigned long)stable_uptime,
  1677. (unsigned long)stable_mtbf,
  1678. (unsigned long)fast_bandwidth,
  1679. guard_wfu*100,
  1680. (unsigned long)guard_tk,
  1681. (unsigned long)guard_bandwidth_including_exits,
  1682. (unsigned long)guard_bandwidth_excluding_exits,
  1683. enough_mtbf_info ? "" : " don't ");
  1684. tor_free(uptimes);
  1685. tor_free(mtbfs);
  1686. tor_free(bandwidths);
  1687. tor_free(bandwidths_excluding_exits);
  1688. tor_free(tks);
  1689. tor_free(wfus);
  1690. }
  1691. /** Given a platform string as in a routerinfo_t (possibly null), return a
  1692. * newly allocated version string for a networkstatus document, or NULL if the
  1693. * platform doesn't give a Tor version. */
  1694. static char *
  1695. version_from_platform(const char *platform)
  1696. {
  1697. if (platform && !strcmpstart(platform, "Tor ")) {
  1698. const char *eos = find_whitespace(platform+4);
  1699. if (eos && !strcmpstart(eos, " (r")) {
  1700. /* XXXX Unify this logic with the other version extraction
  1701. * logic in routerparse.c. */
  1702. eos = find_whitespace(eos+1);
  1703. }
  1704. if (eos) {
  1705. return tor_strndup(platform, eos-platform);
  1706. }
  1707. }
  1708. return NULL;
  1709. }
  1710. /** Helper: write the router-status information in <b>rs</b> into <b>buf</b>,
  1711. * which has at least <b>buf_len</b> free characters. Do NUL-termination.
  1712. * Use the same format as in network-status documents. If <b>version</b> is
  1713. * non-NULL, add a "v" line for the platform. Return 0 on success, -1 on
  1714. * failure. If <b>first_line_only</b> is true, don't include any flags
  1715. * or version line.
  1716. */
  1717. int
  1718. routerstatus_format_entry(char *buf, size_t buf_len,
  1719. routerstatus_t *rs, const char *version,
  1720. int first_line_only, int v2_format)
  1721. /* XXX: first_line_only and v2_format should probably be be both
  1722. * replaced by a single purpose parameter.
  1723. */
  1724. {
  1725. int r;
  1726. struct in_addr in;
  1727. char *cp;
  1728. char *summary;
  1729. char published[ISO_TIME_LEN+1];
  1730. char ipaddr[INET_NTOA_BUF_LEN];
  1731. char identity64[BASE64_DIGEST_LEN+1];
  1732. char digest64[BASE64_DIGEST_LEN+1];
  1733. format_iso_time(published, rs->published_on);
  1734. digest_to_base64(identity64, rs->identity_digest);
  1735. digest_to_base64(digest64, rs->descriptor_digest);
  1736. in.s_addr = htonl(rs->addr);
  1737. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1738. r = tor_snprintf(buf, buf_len,
  1739. "r %s %s %s %s %s %d %d\n",
  1740. rs->nickname,
  1741. identity64,
  1742. digest64,
  1743. published,
  1744. ipaddr,
  1745. (int)rs->or_port,
  1746. (int)rs->dir_port);
  1747. if (r<0) {
  1748. log_warn(LD_BUG, "Not enough space in buffer.");
  1749. return -1;
  1750. }
  1751. if (first_line_only)
  1752. return 0;
  1753. cp = buf + strlen(buf);
  1754. /* NOTE: Whenever this list expands, be sure to increase MAX_FLAG_LINE_LEN*/
  1755. r = tor_snprintf(cp, buf_len - (cp-buf),
  1756. "s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
  1757. /* These must stay in alphabetical order. */
  1758. rs->is_authority?" Authority":"",
  1759. rs->is_bad_directory?" BadDirectory":"",
  1760. rs->is_bad_exit?" BadExit":"",
  1761. rs->is_exit?" Exit":"",
  1762. rs->is_fast?" Fast":"",
  1763. rs->is_possible_guard?" Guard":"",
  1764. rs->is_hs_dir?" HSDir":"",
  1765. rs->is_named?" Named":"",
  1766. rs->is_running?" Running":"",
  1767. rs->is_stable?" Stable":"",
  1768. rs->is_unnamed?" Unnamed":"",
  1769. rs->is_v2_dir?" V2Dir":"",
  1770. rs->is_valid?" Valid":"");
  1771. if (r<0) {
  1772. log_warn(LD_BUG, "Not enough space in buffer.");
  1773. return -1;
  1774. }
  1775. cp += strlen(cp);
  1776. /* length of "opt v \n" */
  1777. #define V_LINE_OVERHEAD 7
  1778. if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
  1779. if (tor_snprintf(cp, buf_len - (cp-buf), "opt v %s\n", version)<0) {
  1780. log_warn(LD_BUG, "Unable to print router version.");
  1781. return -1;
  1782. }
  1783. cp += strlen(cp);
  1784. }
  1785. if (!v2_format) {
  1786. routerinfo_t* desc = router_get_by_digest(rs->identity_digest);
  1787. /* Blow up more or less nicely if we didn't get anything or not the
  1788. * thing we expected.
  1789. */
  1790. if (!desc) {
  1791. char id[HEX_DIGEST_LEN+1];
  1792. char dd[HEX_DIGEST_LEN+1];
  1793. base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
  1794. base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
  1795. log_warn(LD_BUG, "Cannot get any descriptor for %s "
  1796. "(wanted descriptor %s).",
  1797. id, dd);
  1798. return -1;
  1799. };
  1800. if (memcmp(desc->cache_info.signed_descriptor_digest,
  1801. rs->descriptor_digest,
  1802. DIGEST_LEN)) {
  1803. char rl_d[HEX_DIGEST_LEN+1];
  1804. char rs_d[HEX_DIGEST_LEN+1];
  1805. char id[HEX_DIGEST_LEN+1];
  1806. base16_encode(rl_d, sizeof(rl_d),
  1807. desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
  1808. base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
  1809. base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
  1810. log_err(LD_BUG, "descriptor digest in routerlist does not match "
  1811. "the one in routerstatus: %s vs %s "
  1812. "(router %s)\n",
  1813. rl_d, rs_d, id);
  1814. tor_assert(!memcmp(desc->cache_info.signed_descriptor_digest,
  1815. rs->descriptor_digest,
  1816. DIGEST_LEN));
  1817. };
  1818. r = tor_snprintf(cp, buf_len - (cp-buf),
  1819. "w Bandwidth=%d\n",
  1820. router_get_advertised_bandwidth_capped(desc) / 1024);
  1821. if (r<0) {
  1822. log_warn(LD_BUG, "Not enough space in buffer.");
  1823. return -1;
  1824. }
  1825. cp += strlen(cp);
  1826. summary = policy_summarize(desc->exit_policy);
  1827. r = tor_snprintf(cp, buf_len - (cp-buf), "p %s\n", summary);
  1828. if (r<0) {
  1829. log_warn(LD_BUG, "Not enough space in buffer.");
  1830. tor_free(summary);
  1831. return -1;
  1832. }
  1833. cp += strlen(cp);
  1834. tor_free(summary);
  1835. }
  1836. return 0;
  1837. }
  1838. /** Helper for sorting: compares two routerinfos first by address, and then by
  1839. * descending order of "usefulness". (An authority is more useful than a
  1840. * non-authority; a running router is more useful than a non-running router;
  1841. * and a router with more bandwidth is more useful than one with less.)
  1842. **/
  1843. static int
  1844. _compare_routerinfo_by_ip_and_bw(const void **a, const void **b)
  1845. {
  1846. routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
  1847. int first_is_auth, second_is_auth;
  1848. uint32_t bw_first, bw_second;
  1849. /* we return -1 if first should appear before second... that is,
  1850. * if first is a better router. */
  1851. if (first->addr < second->addr)
  1852. return -1;
  1853. else if (first->addr > second->addr)
  1854. return 1;
  1855. /* Potentially, this next bit could cause k n lg n memcmp calls. But in
  1856. * reality, we will almost never get here, since addresses will usually be
  1857. * different. */
  1858. first_is_auth =
  1859. router_digest_is_trusted_dir(first->cache_info.identity_digest);
  1860. second_is_auth =
  1861. router_digest_is_trusted_dir(second->cache_info.identity_digest);
  1862. if (first_is_auth && !second_is_auth)
  1863. return -1;
  1864. else if (!first_is_auth && second_is_auth)
  1865. return 1;
  1866. else if (first->is_running && !second->is_running)
  1867. return -1;
  1868. else if (!first->is_running && second->is_running)
  1869. return 1;
  1870. bw_first = router_get_advertised_bandwidth(first);
  1871. bw_second = router_get_advertised_bandwidth(second);
  1872. if (bw_first > bw_second)
  1873. return -1;
  1874. else if (bw_first < bw_second)
  1875. return 1;
  1876. /* They're equal! Compare by identity digest, so there's a
  1877. * deterministic order and we avoid flapping. */
  1878. return memcmp(first->cache_info.identity_digest,
  1879. second->cache_info.identity_digest,
  1880. DIGEST_LEN);
  1881. }
  1882. /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
  1883. * whose keys are the identity digests of those routers that we're going to
  1884. * exclude for Sybil-like appearance. */
  1885. static digestmap_t *
  1886. get_possible_sybil_list(const smartlist_t *routers)
  1887. {
  1888. or_options_t *options = get_options();
  1889. digestmap_t *omit_as_sybil;
  1890. smartlist_t *routers_by_ip = smartlist_create();
  1891. uint32_t last_addr;
  1892. int addr_count;
  1893. /* Allow at most this number of Tor servers on a single IP address, ... */
  1894. int max_with_same_addr = options->AuthDirMaxServersPerAddr;
  1895. /* ... unless it's a directory authority, in which case allow more. */
  1896. int max_with_same_addr_on_authority = options->AuthDirMaxServersPerAuthAddr;
  1897. if (max_with_same_addr <= 0)
  1898. max_with_same_addr = INT_MAX;
  1899. if (max_with_same_addr_on_authority <= 0)
  1900. max_with_same_addr_on_authority = INT_MAX;
  1901. smartlist_add_all(routers_by_ip, routers);
  1902. smartlist_sort(routers_by_ip, _compare_routerinfo_by_ip_and_bw);
  1903. omit_as_sybil = digestmap_new();
  1904. last_addr = 0;
  1905. addr_count = 0;
  1906. SMARTLIST_FOREACH(routers_by_ip, routerinfo_t *, ri,
  1907. {
  1908. if (last_addr != ri->addr) {
  1909. last_addr = ri->addr;
  1910. addr_count = 1;
  1911. } else if (++addr_count > max_with_same_addr) {
  1912. if (!router_addr_is_trusted_dir(ri->addr) ||
  1913. addr_count > max_with_same_addr_on_authority)
  1914. digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
  1915. }
  1916. });
  1917. smartlist_free(routers_by_ip);
  1918. return omit_as_sybil;
  1919. }
  1920. /** Extract status information from <b>ri</b> and from other authority
  1921. * functions and store it in <b>rs</b>>. If <b>naming</b>, consider setting
  1922. * the named flag in <b>rs</b>. If not <b>exits_can_be_guards</b>, never mark
  1923. * an exit as a guard. If <b>listbadexits</b>, consider setting the badexit
  1924. * flag.
  1925. *
  1926. * We assume that ri-\>is_running has already been set, e.g. by
  1927. * dirserv_set_router_is_running(ri, now);
  1928. */
  1929. void
  1930. set_routerstatus_from_routerinfo(routerstatus_t *rs,
  1931. routerinfo_t *ri, time_t now,
  1932. int naming, int exits_can_be_guards,
  1933. int listbadexits, int listbaddirs)
  1934. {
  1935. int unstable_version =
  1936. !tor_version_as_new_as(ri->platform,"0.1.1.16-rc-cvs");
  1937. memset(rs, 0, sizeof(routerstatus_t));
  1938. rs->is_authority =
  1939. router_digest_is_trusted_dir(ri->cache_info.identity_digest);
  1940. /* Already set by compute_performance_thresholds. */
  1941. rs->is_exit = ri->is_exit;
  1942. rs->is_stable = ri->is_stable =
  1943. router_is_active(ri, now) &&
  1944. !dirserv_thinks_router_is_unreliable(now, ri, 1, 0) &&
  1945. !unstable_version;
  1946. rs->is_fast = ri->is_fast =
  1947. router_is_active(ri, now) &&
  1948. !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
  1949. rs->is_running = ri->is_running; /* computed above */
  1950. if (naming) {
  1951. uint32_t name_status = dirserv_get_name_status(
  1952. ri->cache_info.identity_digest, ri->nickname);
  1953. rs->is_named = (naming && (name_status & FP_NAMED)) ? 1 : 0;
  1954. rs->is_unnamed = (naming && (name_status & FP_UNNAMED)) ? 1 : 0;
  1955. }
  1956. rs->is_valid = ri->is_valid;
  1957. if (rs->is_fast &&
  1958. (!rs->is_exit || exits_can_be_guards) &&
  1959. (router_get_advertised_bandwidth(ri) >= BANDWIDTH_TO_GUARANTEE_GUARD ||
  1960. router_get_advertised_bandwidth(ri) >=
  1961. (exits_can_be_guards ? guard_bandwidth_including_exits :
  1962. guard_bandwidth_excluding_exits))) {
  1963. long tk = rep_hist_get_weighted_time_known(
  1964. ri->cache_info.identity_digest, now);
  1965. double wfu = rep_hist_get_weighted_fractional_uptime(
  1966. ri->cache_info.identity_digest, now);
  1967. rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
  1968. } else {
  1969. rs->is_possible_guard = 0;
  1970. }
  1971. rs->is_bad_directory = listbaddirs && ri->is_bad_directory;
  1972. rs->is_bad_exit = listbadexits && ri->is_bad_exit;
  1973. ri->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, now);
  1974. rs->is_hs_dir = ri->is_hs_dir;
  1975. rs->is_v2_dir = ri->dir_port != 0;
  1976. if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME))
  1977. rs->is_named = rs->is_unnamed = 0;
  1978. rs->published_on = ri->cache_info.published_on;
  1979. memcpy(rs->identity_digest, ri->cache_info.identity_digest, DIGEST_LEN);
  1980. memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
  1981. DIGEST_LEN);
  1982. rs->addr = ri->addr;
  1983. strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
  1984. rs->or_port = ri->or_port;
  1985. rs->dir_port = ri->dir_port;
  1986. }
  1987. /** Routerstatus <b>rs</b> is part of a group of routers that are on
  1988. * too narrow an IP-space. Clear out its flags: we don't want people
  1989. * using it.
  1990. */
  1991. static void
  1992. clear_status_flags_on_sybil(routerstatus_t *rs)
  1993. {
  1994. rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
  1995. rs->is_running = rs->is_named = rs->is_valid = rs->is_v2_dir =
  1996. rs->is_hs_dir = rs->is_possible_guard = rs->is_bad_exit =
  1997. rs->is_bad_directory = 0;
  1998. /* FFFF we might want some mechanism to check later on if we
  1999. * missed zeroing any flags: it's easy to add a new flag but
  2000. * forget to add it to this clause. */
  2001. }
  2002. /** Clear all the status flags in routerinfo <b>router</b>. We put this
  2003. * function here because it's eerily similar to
  2004. * clear_status_flags_on_sybil() above. One day we should merge them. */
  2005. void
  2006. router_clear_status_flags(routerinfo_t *router)
  2007. {
  2008. router->is_valid = router->is_running = router->is_hs_dir =
  2009. router->is_fast = router->is_stable =
  2010. router->is_possible_guard = router->is_exit =
  2011. router->is_bad_exit = router->is_bad_directory = 0;
  2012. }
  2013. /** Return a new networkstatus_t* containing our current opinion. (For v3
  2014. * authorities) */
  2015. networkstatus_t *
  2016. dirserv_generate_networkstatus_vote_obj(crypto_pk_env_t *private_key,
  2017. authority_cert_t *cert)
  2018. {
  2019. or_options_t *options = get_options();
  2020. networkstatus_t *v3_out = NULL;
  2021. uint32_t addr;
  2022. char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
  2023. const char *contact;
  2024. smartlist_t *routers, *routerstatuses;
  2025. char identity_digest[DIGEST_LEN];
  2026. char signing_key_digest[DIGEST_LEN];
  2027. int naming = options->NamingAuthoritativeDir;
  2028. int listbadexits = options->AuthDirListBadExits;
  2029. int listbaddirs = options->AuthDirListBadDirs;
  2030. int exits_can_be_guards;
  2031. routerlist_t *rl = router_get_routerlist();
  2032. time_t now = time(NULL);
  2033. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  2034. networkstatus_voter_info_t *voter = NULL;
  2035. vote_timing_t timing;
  2036. digestmap_t *omit_as_sybil = NULL;
  2037. int vote_on_reachability = 1;
  2038. tor_assert(private_key);
  2039. tor_assert(cert);
  2040. if (now - time_of_process_start <
  2041. options->TestingAuthDirTimeToLearnReachability)
  2042. vote_on_reachability = 0;
  2043. if (resolve_my_address(LOG_WARN, options, &addr, &hostname)<0) {
  2044. log_warn(LD_NET, "Couldn't resolve my hostname");
  2045. return NULL;
  2046. }
  2047. if (!strchr(hostname, '.')) {
  2048. tor_free(hostname);
  2049. hostname = tor_dup_ip(addr);
  2050. }
  2051. if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
  2052. log_err(LD_BUG, "Error computing signing key digest");
  2053. return NULL;
  2054. }
  2055. if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
  2056. log_err(LD_BUG, "Error computing identity key digest");
  2057. return NULL;
  2058. }
  2059. if (options->VersioningAuthoritativeDir) {
  2060. client_versions = format_versions_list(options->RecommendedClientVersions);
  2061. server_versions = format_versions_list(options->RecommendedServerVersions);
  2062. }
  2063. contact = get_options()->ContactInfo;
  2064. if (!contact)
  2065. contact = "(none)";
  2066. /* precompute this part, since we need it to decide what "stable"
  2067. * means. */
  2068. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  2069. dirserv_set_router_is_running(ri, now);
  2070. });
  2071. dirserv_compute_performance_thresholds(rl);
  2072. /* XXXX We should take steps to keep this from oscillating if
  2073. * total_exit_bandwidth is close to total_bandwidth/3. */
  2074. exits_can_be_guards = total_exit_bandwidth >= (total_bandwidth / 3);
  2075. routers = smartlist_create();
  2076. smartlist_add_all(routers, rl->routers);
  2077. routers_sort_by_identity(routers);
  2078. omit_as_sybil = get_possible_sybil_list(routers);
  2079. routerstatuses = smartlist_create();
  2080. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  2081. if (ri->cache_info.published_on >= cutoff) {
  2082. routerstatus_t *rs;
  2083. vote_routerstatus_t *vrs;
  2084. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2085. rs = &vrs->status;
  2086. set_routerstatus_from_routerinfo(rs, ri, now,
  2087. naming, exits_can_be_guards,
  2088. listbadexits, listbaddirs);
  2089. if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
  2090. clear_status_flags_on_sybil(rs);
  2091. if (!vote_on_reachability)
  2092. rs->is_running = 0;
  2093. vrs->version = version_from_platform(ri->platform);
  2094. smartlist_add(routerstatuses, vrs);
  2095. }
  2096. });
  2097. smartlist_free(routers);
  2098. digestmap_free(omit_as_sybil, NULL);
  2099. v3_out = tor_malloc_zero(sizeof(networkstatus_t));
  2100. v3_out->type = NS_TYPE_VOTE;
  2101. dirvote_get_preferred_voting_intervals(&timing);
  2102. v3_out->published = now;
  2103. {
  2104. char tbuf[ISO_TIME_LEN+1];
  2105. networkstatus_t *current_consensus =
  2106. networkstatus_get_live_consensus(now);
  2107. long last_consensus_interval; /* only used to pick a valid_after */
  2108. if (current_consensus)
  2109. last_consensus_interval = current_consensus->fresh_until -
  2110. current_consensus->valid_after;
  2111. else
  2112. last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
  2113. v3_out->valid_after =
  2114. dirvote_get_start_of_next_interval(now, (int)last_consensus_interval);
  2115. format_iso_time(tbuf, v3_out->valid_after);
  2116. log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
  2117. "consensus_set=%d, last_interval=%d",
  2118. tbuf, current_consensus?1:0, (int)last_consensus_interval);
  2119. }
  2120. v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
  2121. v3_out->valid_until = v3_out->valid_after +
  2122. (timing.vote_interval * timing.n_intervals_valid);
  2123. v3_out->vote_seconds = timing.vote_delay;
  2124. v3_out->dist_seconds = timing.dist_delay;
  2125. tor_assert(v3_out->vote_seconds > 0);
  2126. tor_assert(v3_out->dist_seconds > 0);
  2127. tor_assert(timing.n_intervals_valid > 0);
  2128. v3_out->client_versions = client_versions;
  2129. v3_out->server_versions = server_versions;
  2130. v3_out->known_flags = smartlist_create();
  2131. smartlist_split_string(v3_out->known_flags,
  2132. "Authority Exit Fast Guard HSDir Stable V2Dir Valid",
  2133. 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2134. if (vote_on_reachability)
  2135. smartlist_add(v3_out->known_flags, tor_strdup("Running"));
  2136. if (listbaddirs)
  2137. smartlist_add(v3_out->known_flags, tor_strdup("BadDirectory"));
  2138. if (listbadexits)
  2139. smartlist_add(v3_out->known_flags, tor_strdup("BadExit"));
  2140. if (naming) {
  2141. smartlist_add(v3_out->known_flags, tor_strdup("Named"));
  2142. smartlist_add(v3_out->known_flags, tor_strdup("Unnamed"));
  2143. }
  2144. smartlist_sort_strings(v3_out->known_flags);
  2145. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2146. voter->nickname = tor_strdup(options->Nickname);
  2147. memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
  2148. voter->address = hostname;
  2149. voter->addr = addr;
  2150. voter->dir_port = options->DirPort;
  2151. voter->or_port = options->ORPort;
  2152. voter->contact = tor_strdup(contact);
  2153. memcpy(voter->signing_key_digest, signing_key_digest, DIGEST_LEN);
  2154. if (options->V3AuthUseLegacyKey) {
  2155. authority_cert_t *c = get_my_v3_legacy_cert();
  2156. if (c) {
  2157. crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest);
  2158. }
  2159. }
  2160. v3_out->voters = smartlist_create();
  2161. smartlist_add(v3_out->voters, voter);
  2162. v3_out->cert = authority_cert_dup(cert);
  2163. v3_out->routerstatus_list = routerstatuses;
  2164. /* Note: networkstatus_digest is unset; it won't get set until we actually
  2165. * format the vote. */
  2166. return v3_out;
  2167. }
  2168. /** For v2 authoritative directories only: Replace the contents of
  2169. * <b>the_v2_networkstatus</b> with a newly generated network status
  2170. * object. */
  2171. static cached_dir_t *
  2172. generate_v2_networkstatus_opinion(void)
  2173. {
  2174. cached_dir_t *r = NULL;
  2175. size_t len, identity_pkey_len;
  2176. char *status = NULL, *client_versions = NULL, *server_versions = NULL,
  2177. *identity_pkey = NULL, *hostname = NULL;
  2178. char *outp, *endp;
  2179. or_options_t *options = get_options();
  2180. char fingerprint[FINGERPRINT_LEN+1];
  2181. char ipaddr[INET_NTOA_BUF_LEN];
  2182. char published[ISO_TIME_LEN+1];
  2183. char digest[DIGEST_LEN];
  2184. struct in_addr in;
  2185. uint32_t addr;
  2186. crypto_pk_env_t *private_key;
  2187. routerlist_t *rl = router_get_routerlist();
  2188. time_t now = time(NULL);
  2189. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  2190. int naming = options->NamingAuthoritativeDir;
  2191. int versioning = options->VersioningAuthoritativeDir;
  2192. int listbaddirs = options->AuthDirListBadDirs;
  2193. int listbadexits = options->AuthDirListBadExits;
  2194. int exits_can_be_guards;
  2195. const char *contact;
  2196. char *version_lines = NULL;
  2197. smartlist_t *routers = NULL;
  2198. digestmap_t *omit_as_sybil = NULL;
  2199. private_key = get_identity_key();
  2200. if (resolve_my_address(LOG_WARN, options, &addr, &hostname)<0) {
  2201. log_warn(LD_NET, "Couldn't resolve my hostname");
  2202. goto done;
  2203. }
  2204. in.s_addr = htonl(addr);
  2205. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  2206. format_iso_time(published, now);
  2207. client_versions = format_versions_list(options->RecommendedClientVersions);
  2208. server_versions = format_versions_list(options->RecommendedServerVersions);
  2209. if (crypto_pk_write_public_key_to_string(private_key, &identity_pkey,
  2210. &identity_pkey_len)<0) {
  2211. log_warn(LD_BUG,"Writing public key to string failed.");
  2212. goto done;
  2213. }
  2214. if (crypto_pk_get_fingerprint(private_key, fingerprint, 0)<0) {
  2215. log_err(LD_BUG, "Error computing fingerprint");
  2216. goto done;
  2217. }
  2218. contact = get_options()->ContactInfo;
  2219. if (!contact)
  2220. contact = "(none)";
  2221. if (versioning) {
  2222. size_t v_len = 64+strlen(client_versions)+strlen(server_versions);
  2223. version_lines = tor_malloc(v_len);
  2224. tor_snprintf(version_lines, v_len,
  2225. "client-versions %s\nserver-versions %s\n",
  2226. client_versions, server_versions);
  2227. } else {
  2228. version_lines = tor_strdup("");
  2229. }
  2230. len = 4096+strlen(client_versions)+strlen(server_versions);
  2231. len += identity_pkey_len*2;
  2232. len += (RS_ENTRY_LEN)*smartlist_len(rl->routers);
  2233. status = tor_malloc(len);
  2234. tor_snprintf(status, len,
  2235. "network-status-version 2\n"
  2236. "dir-source %s %s %d\n"
  2237. "fingerprint %s\n"
  2238. "contact %s\n"
  2239. "published %s\n"
  2240. "dir-options%s%s%s%s\n"
  2241. "%s" /* client version line, server version line. */
  2242. "dir-signing-key\n%s",
  2243. hostname, ipaddr, (int)options->DirPort,
  2244. fingerprint,
  2245. contact,
  2246. published,
  2247. naming ? " Names" : "",
  2248. listbaddirs ? " BadDirectories" : "",
  2249. listbadexits ? " BadExits" : "",
  2250. versioning ? " Versions" : "",
  2251. version_lines,
  2252. identity_pkey);
  2253. outp = status + strlen(status);
  2254. endp = status + len;
  2255. /* precompute this part, since we need it to decide what "stable"
  2256. * means. */
  2257. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  2258. dirserv_set_router_is_running(ri, now);
  2259. });
  2260. dirserv_compute_performance_thresholds(rl);
  2261. /* XXXX We should take steps to keep this from oscillating if
  2262. * total_exit_bandwidth is close to total_bandwidth/3. */
  2263. exits_can_be_guards = total_exit_bandwidth >= (total_bandwidth / 3);
  2264. routers = smartlist_create();
  2265. smartlist_add_all(routers, rl->routers);
  2266. routers_sort_by_identity(routers);
  2267. omit_as_sybil = get_possible_sybil_list(routers);
  2268. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  2269. if (ri->cache_info.published_on >= cutoff) {
  2270. routerstatus_t rs;
  2271. char *version = version_from_platform(ri->platform);
  2272. set_routerstatus_from_routerinfo(&rs, ri, now,
  2273. naming, exits_can_be_guards,
  2274. listbadexits, listbaddirs);
  2275. if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
  2276. clear_status_flags_on_sybil(&rs);
  2277. if (routerstatus_format_entry(outp, endp-outp, &rs, version, 0, 1)) {
  2278. log_warn(LD_BUG, "Unable to print router status.");
  2279. tor_free(version);
  2280. goto done;
  2281. }
  2282. tor_free(version);
  2283. outp += strlen(outp);
  2284. }
  2285. });
  2286. if (tor_snprintf(outp, endp-outp, "directory-signature %s\n",
  2287. get_options()->Nickname)<0) {
  2288. log_warn(LD_BUG, "Unable to write signature line.");
  2289. goto done;
  2290. }
  2291. if (router_get_networkstatus_v2_hash(status, digest)<0) {
  2292. log_warn(LD_BUG, "Unable to hash network status");
  2293. goto done;
  2294. }
  2295. outp += strlen(outp);
  2296. note_crypto_pk_op(SIGN_DIR);
  2297. if (router_append_dirobj_signature(outp,endp-outp,digest,private_key)<0) {
  2298. log_warn(LD_BUG, "Unable to sign router status.");
  2299. goto done;
  2300. }
  2301. {
  2302. networkstatus_v2_t *ns;
  2303. if (!(ns = networkstatus_v2_parse_from_string(status))) {
  2304. log_err(LD_BUG,"Generated a networkstatus we couldn't parse.");
  2305. goto done;
  2306. }
  2307. networkstatus_v2_free(ns);
  2308. }
  2309. {
  2310. cached_dir_t **ns_ptr = &the_v2_networkstatus;
  2311. if (*ns_ptr)
  2312. cached_dir_decref(*ns_ptr);
  2313. *ns_ptr = new_cached_dir(status, now);
  2314. status = NULL; /* So it doesn't get double-freed. */
  2315. the_v2_networkstatus_is_dirty = 0;
  2316. router_set_networkstatus_v2((*ns_ptr)->dir, now, NS_GENERATED, NULL);
  2317. r = *ns_ptr;
  2318. }
  2319. done:
  2320. tor_free(client_versions);
  2321. tor_free(server_versions);
  2322. tor_free(version_lines);
  2323. tor_free(status);
  2324. tor_free(hostname);
  2325. tor_free(identity_pkey);
  2326. if (routers)
  2327. smartlist_free(routers);
  2328. if (omit_as_sybil)
  2329. digestmap_free(omit_as_sybil, NULL);
  2330. return r;
  2331. }
  2332. /** Given the portion of a networkstatus request URL after "tor/status/" in
  2333. * <b>key</b>, append to <b>result</b> the digests of the identity keys of the
  2334. * networkstatus objects that the client has requested. */
  2335. void
  2336. dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
  2337. const char *key)
  2338. {
  2339. tor_assert(result);
  2340. if (!cached_v2_networkstatus)
  2341. cached_v2_networkstatus = digestmap_new();
  2342. if (should_generate_v2_networkstatus())
  2343. generate_v2_networkstatus_opinion();
  2344. if (!strcmp(key,"authority")) {
  2345. if (authdir_mode_v2(get_options())) {
  2346. routerinfo_t *me = router_get_my_routerinfo();
  2347. if (me)
  2348. smartlist_add(result,
  2349. tor_memdup(me->cache_info.identity_digest, DIGEST_LEN));
  2350. }
  2351. } else if (!strcmp(key, "all")) {
  2352. if (digestmap_size(cached_v2_networkstatus)) {
  2353. digestmap_iter_t *iter;
  2354. iter = digestmap_iter_init(cached_v2_networkstatus);
  2355. while (!digestmap_iter_done(iter)) {
  2356. const char *ident;
  2357. void *val;
  2358. digestmap_iter_get(iter, &ident, &val);
  2359. smartlist_add(result, tor_memdup(ident, DIGEST_LEN));
  2360. iter = digestmap_iter_next(cached_v2_networkstatus, iter);
  2361. }
  2362. } else {
  2363. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  2364. trusted_dir_server_t *, ds,
  2365. if (ds->type & V2_AUTHORITY)
  2366. smartlist_add(result, tor_memdup(ds->digest, DIGEST_LEN)));
  2367. }
  2368. smartlist_sort_digests(result);
  2369. if (smartlist_len(result) == 0)
  2370. log_info(LD_DIRSERV,
  2371. "Client requested 'all' network status objects; we have none.");
  2372. } else if (!strcmpstart(key, "fp/")) {
  2373. dir_split_resource_into_fingerprints(key+3, result, NULL, 1, 1);
  2374. }
  2375. }
  2376. /** Look for a network status object as specified by <b>key</b>, which should
  2377. * be either "authority" (to find a network status generated by us), a hex
  2378. * identity digest (to find a network status generated by given directory), or
  2379. * "all" (to return all the v2 network status objects we have).
  2380. */
  2381. void
  2382. dirserv_get_networkstatus_v2(smartlist_t *result,
  2383. const char *key)
  2384. {
  2385. cached_dir_t *cached;
  2386. smartlist_t *fingerprints = smartlist_create();
  2387. tor_assert(result);
  2388. if (!cached_v2_networkstatus)
  2389. cached_v2_networkstatus = digestmap_new();
  2390. dirserv_get_networkstatus_v2_fingerprints(fingerprints, key);
  2391. SMARTLIST_FOREACH(fingerprints, const char *, fp,
  2392. {
  2393. if (router_digest_is_me(fp) && should_generate_v2_networkstatus())
  2394. generate_v2_networkstatus_opinion();
  2395. cached = digestmap_get(cached_v2_networkstatus, fp);
  2396. if (cached) {
  2397. smartlist_add(result, cached);
  2398. } else {
  2399. char hexbuf[HEX_DIGEST_LEN+1];
  2400. base16_encode(hexbuf, sizeof(hexbuf), fp, DIGEST_LEN);
  2401. log_info(LD_DIRSERV, "Don't know about any network status with "
  2402. "fingerprint '%s'", hexbuf);
  2403. }
  2404. });
  2405. SMARTLIST_FOREACH(fingerprints, char *, cp, tor_free(cp));
  2406. smartlist_free(fingerprints);
  2407. }
  2408. /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
  2409. * pointers, adds copies of digests to fps_out, and doesn't use the
  2410. * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
  2411. * requests, adds identity digests.
  2412. */
  2413. int
  2414. dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
  2415. const char **msg, int for_unencrypted_conn,
  2416. int is_extrainfo)
  2417. {
  2418. int by_id = 1;
  2419. *msg = NULL;
  2420. if (!strcmp(key, "all")) {
  2421. routerlist_t *rl = router_get_routerlist();
  2422. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  2423. smartlist_add(fps_out,
  2424. tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
  2425. } else if (!strcmp(key, "authority")) {
  2426. routerinfo_t *ri = router_get_my_routerinfo();
  2427. if (ri)
  2428. smartlist_add(fps_out,
  2429. tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
  2430. } else if (!strcmpstart(key, "d/")) {
  2431. by_id = 0;
  2432. key += strlen("d/");
  2433. dir_split_resource_into_fingerprints(key, fps_out, NULL, 1, 1);
  2434. } else if (!strcmpstart(key, "fp/")) {
  2435. key += strlen("fp/");
  2436. dir_split_resource_into_fingerprints(key, fps_out, NULL, 1, 1);
  2437. } else {
  2438. *msg = "Key not recognized";
  2439. return -1;
  2440. }
  2441. if (for_unencrypted_conn) {
  2442. /* Remove anything that insists it not be sent unencrypted. */
  2443. SMARTLIST_FOREACH(fps_out, char *, cp, {
  2444. signed_descriptor_t *sd;
  2445. if (by_id)
  2446. sd = get_signed_descriptor_by_fp(cp,is_extrainfo,0);
  2447. else if (is_extrainfo)
  2448. sd = extrainfo_get_by_descriptor_digest(cp);
  2449. else
  2450. sd = router_get_by_descriptor_digest(cp);
  2451. if (sd && !sd->send_unencrypted) {
  2452. tor_free(cp);
  2453. SMARTLIST_DEL_CURRENT(fps_out, cp);
  2454. }
  2455. });
  2456. }
  2457. if (!smartlist_len(fps_out)) {
  2458. *msg = "Servers unavailable";
  2459. return -1;
  2460. }
  2461. return 0;
  2462. }
  2463. /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
  2464. * <b>key</b>. The key should be either
  2465. * - "/tor/server/authority" for our own routerinfo;
  2466. * - "/tor/server/all" for all the routerinfos we have, concatenated;
  2467. * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
  2468. * hex identity digests; or
  2469. * - "/tor/server/d/D" where D is a plus-separated sequence
  2470. * of server descriptor digests, in hex.
  2471. *
  2472. * Return 0 if we found some matching descriptors, or -1 if we do not
  2473. * have any descriptors, no matching descriptors, or if we did not
  2474. * recognize the key (URL).
  2475. * If -1 is returned *<b>msg</b> will be set to an appropriate error
  2476. * message.
  2477. *
  2478. * XXXX rename this function. It's only called from the controller.
  2479. * XXXX in fact, refactor this function, mergeing as much as possible.
  2480. */
  2481. int
  2482. dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
  2483. const char **msg)
  2484. {
  2485. *msg = NULL;
  2486. if (!strcmp(key, "/tor/server/all")) {
  2487. routerlist_t *rl = router_get_routerlist();
  2488. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  2489. smartlist_add(descs_out, &(r->cache_info)));
  2490. } else if (!strcmp(key, "/tor/server/authority")) {
  2491. routerinfo_t *ri = router_get_my_routerinfo();
  2492. if (ri)
  2493. smartlist_add(descs_out, &(ri->cache_info));
  2494. } else if (!strcmpstart(key, "/tor/server/d/")) {
  2495. smartlist_t *digests = smartlist_create();
  2496. key += strlen("/tor/server/d/");
  2497. dir_split_resource_into_fingerprints(key, digests, NULL, 1, 1);
  2498. SMARTLIST_FOREACH(digests, const char *, d,
  2499. {
  2500. signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
  2501. if (sd)
  2502. smartlist_add(descs_out,sd);
  2503. });
  2504. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  2505. smartlist_free(digests);
  2506. } else if (!strcmpstart(key, "/tor/server/fp/")) {
  2507. smartlist_t *digests = smartlist_create();
  2508. time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
  2509. key += strlen("/tor/server/fp/");
  2510. dir_split_resource_into_fingerprints(key, digests, NULL, 1, 1);
  2511. SMARTLIST_FOREACH(digests, const char *, d,
  2512. {
  2513. if (router_digest_is_me(d)) {
  2514. /* make sure desc_routerinfo exists */
  2515. routerinfo_t *ri = router_get_my_routerinfo();
  2516. if (ri)
  2517. smartlist_add(descs_out, &(ri->cache_info));
  2518. } else {
  2519. routerinfo_t *ri = router_get_by_digest(d);
  2520. /* Don't actually serve a descriptor that everyone will think is
  2521. * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
  2522. * Tors from downloading descriptors that they will throw away.
  2523. */
  2524. if (ri && ri->cache_info.published_on > cutoff)
  2525. smartlist_add(descs_out, &(ri->cache_info));
  2526. }
  2527. });
  2528. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  2529. smartlist_free(digests);
  2530. } else {
  2531. *msg = "Key not recognized";
  2532. return -1;
  2533. }
  2534. if (!smartlist_len(descs_out)) {
  2535. *msg = "Servers unavailable";
  2536. return -1;
  2537. }
  2538. return 0;
  2539. }
  2540. /** Called when a TLS handshake has completed successfully with a
  2541. * router listening at <b>address</b>:<b>or_port</b>, and has yielded
  2542. * a certificate with digest <b>digest_rcvd</b>.
  2543. *
  2544. * Also, if as_advertised is 1, then inform the reachability checker
  2545. * that we could get to this guy.
  2546. */
  2547. void
  2548. dirserv_orconn_tls_done(const char *address,
  2549. uint16_t or_port,
  2550. const char *digest_rcvd,
  2551. int as_advertised)
  2552. {
  2553. routerlist_t *rl = router_get_routerlist();
  2554. time_t now = time(NULL);
  2555. int bridge_auth = authdir_mode_bridge(get_options());
  2556. tor_assert(address);
  2557. tor_assert(digest_rcvd);
  2558. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  2559. if (!strcasecmp(address, ri->address) && or_port == ri->or_port &&
  2560. as_advertised &&
  2561. !memcmp(ri->cache_info.identity_digest, digest_rcvd, DIGEST_LEN)) {
  2562. /* correct digest. mark this router reachable! */
  2563. if (!bridge_auth || ri->purpose == ROUTER_PURPOSE_BRIDGE) {
  2564. log_info(LD_DIRSERV, "Found router %s to be reachable. Yay.",
  2565. ri->nickname);
  2566. rep_hist_note_router_reachable(digest_rcvd, now);
  2567. ri->last_reachable = now;
  2568. }
  2569. }
  2570. });
  2571. /* FFFF Maybe we should reinstate the code that dumps routers with the same
  2572. * addr/port but with nonmatching keys, but instead of dumping, we should
  2573. * skip testing. */
  2574. }
  2575. /** Auth dir server only: if <b>try_all</b> is 1, launch connections to
  2576. * all known routers; else we want to load balance such that we only
  2577. * try a few connections per call.
  2578. *
  2579. * The load balancing is such that if we get called once every ten
  2580. * seconds, we will cycle through all the tests in 1280 seconds (a
  2581. * bit over 20 minutes).
  2582. */
  2583. void
  2584. dirserv_test_reachability(time_t now, int try_all)
  2585. {
  2586. /* XXX decide what to do here; see or-talk thread "purging old router
  2587. * information, revocation." -NM
  2588. * We can't afford to mess with this in 0.1.2.x. The reason is that
  2589. * if we stop doing reachability tests on some of routerlist, then
  2590. * we'll for-sure think they're down, which may have unexpected
  2591. * effects in other parts of the code. It doesn't hurt much to do
  2592. * the testing, and directory authorities are easy to upgrade. Let's
  2593. * wait til 0.2.0. -RD */
  2594. // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  2595. routerlist_t *rl = router_get_routerlist();
  2596. static char ctr = 0;
  2597. int bridge_auth = authdir_mode_bridge(get_options());
  2598. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
  2599. const char *id_digest = router->cache_info.identity_digest;
  2600. tor_addr_t router_addr;
  2601. if (router_is_me(router))
  2602. continue;
  2603. if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
  2604. continue; /* bridge authorities only test reachability on bridges */
  2605. // if (router->cache_info.published_on > cutoff)
  2606. // continue;
  2607. if (try_all || (((uint8_t)id_digest[0]) % 128) == ctr) {
  2608. log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
  2609. router->nickname, router->address, router->or_port);
  2610. /* Remember when we started trying to determine reachability */
  2611. if (!router->testing_since)
  2612. router->testing_since = now;
  2613. tor_addr_from_ipv4h(&router_addr, router->addr);
  2614. connection_or_connect(&router_addr, router->or_port, id_digest);
  2615. }
  2616. } SMARTLIST_FOREACH_END(router);
  2617. if (!try_all) /* increment ctr */
  2618. ctr = (ctr + 1) % 128;
  2619. }
  2620. /** Given a fingerprint <b>fp</b> which is either set if we're looking
  2621. * for a v2 status, or zeroes if we're looking for a v3 status, return
  2622. * a pointer to the appropriate cached dir object, or NULL if there isn't
  2623. * one available. */
  2624. static cached_dir_t *
  2625. lookup_cached_dir_by_fp(const char *fp)
  2626. {
  2627. cached_dir_t *d = NULL;
  2628. if (tor_digest_is_zero(fp) && cached_v3_networkstatus)
  2629. d = cached_v3_networkstatus;
  2630. else if (router_digest_is_me(fp) && the_v2_networkstatus)
  2631. d = the_v2_networkstatus;
  2632. else if (cached_v2_networkstatus)
  2633. d = digestmap_get(cached_v2_networkstatus, fp);
  2634. return d;
  2635. }
  2636. /** Remove from <b>fps</b> every networkstatus key where both
  2637. * a) we have a networkstatus document and
  2638. * b) it is not newer than <b>cutoff</b>.
  2639. *
  2640. * Return 1 if any items were present at all; else return 0.
  2641. */
  2642. int
  2643. dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff)
  2644. {
  2645. int found_any = 0;
  2646. SMARTLIST_FOREACH(fps, char *, digest,
  2647. {
  2648. cached_dir_t *d = lookup_cached_dir_by_fp(digest);
  2649. if (!d)
  2650. continue;
  2651. found_any = 1;
  2652. if (d->published <= cutoff) {
  2653. tor_free(digest);
  2654. SMARTLIST_DEL_CURRENT(fps, digest);
  2655. }
  2656. });
  2657. return found_any;
  2658. }
  2659. /** Return the cache-info for identity fingerprint <b>fp</b>, or
  2660. * its extra-info document if <b>extrainfo</b> is true. Return
  2661. * NULL if not found or if the descriptor is older than
  2662. * <b>publish_cutoff</b>. */
  2663. static signed_descriptor_t *
  2664. get_signed_descriptor_by_fp(const char *fp, int extrainfo,
  2665. time_t publish_cutoff)
  2666. {
  2667. if (router_digest_is_me(fp)) {
  2668. if (extrainfo)
  2669. return &(router_get_my_extrainfo()->cache_info);
  2670. else
  2671. return &(router_get_my_routerinfo()->cache_info);
  2672. } else {
  2673. routerinfo_t *ri = router_get_by_digest(fp);
  2674. if (ri &&
  2675. ri->cache_info.published_on > publish_cutoff) {
  2676. if (extrainfo)
  2677. return extrainfo_get_by_descriptor_digest(
  2678. ri->cache_info.extra_info_digest);
  2679. else
  2680. return &ri->cache_info;
  2681. }
  2682. }
  2683. return NULL;
  2684. }
  2685. /** Return true iff we have any of the docments (extrainfo or routerdesc)
  2686. * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
  2687. * decide whether to send a 404. */
  2688. int
  2689. dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src)
  2690. {
  2691. time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
  2692. SMARTLIST_FOREACH(fps, const char *, fp, {
  2693. switch (spool_src)
  2694. {
  2695. case DIR_SPOOL_EXTRA_BY_DIGEST:
  2696. if (extrainfo_get_by_descriptor_digest(fp)) return 1;
  2697. break;
  2698. case DIR_SPOOL_SERVER_BY_DIGEST:
  2699. if (router_get_by_descriptor_digest(fp)) return 1;
  2700. break;
  2701. case DIR_SPOOL_EXTRA_BY_FP:
  2702. case DIR_SPOOL_SERVER_BY_FP:
  2703. if (get_signed_descriptor_by_fp(fp,
  2704. spool_src == DIR_SPOOL_EXTRA_BY_FP, publish_cutoff))
  2705. return 1;
  2706. break;
  2707. }
  2708. });
  2709. return 0;
  2710. }
  2711. /** Return an approximate estimate of the number of bytes that will
  2712. * be needed to transmit the server descriptors (if is_serverdescs --
  2713. * they can be either d/ or fp/ queries) or networkstatus objects (if
  2714. * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
  2715. * we guess how large the data will be after compression.
  2716. *
  2717. * The return value is an estimate; it might be larger or smaller.
  2718. **/
  2719. size_t
  2720. dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
  2721. int compressed)
  2722. {
  2723. size_t result;
  2724. tor_assert(fps);
  2725. if (is_serverdescs) {
  2726. int n = smartlist_len(fps);
  2727. routerinfo_t *me = router_get_my_routerinfo();
  2728. result = (me?me->cache_info.signed_descriptor_len:2048) * n;
  2729. if (compressed)
  2730. result /= 2; /* observed compressability is between 35 and 55%. */
  2731. } else {
  2732. result = 0;
  2733. SMARTLIST_FOREACH(fps, const char *, digest, {
  2734. cached_dir_t *dir = lookup_cached_dir_by_fp(digest);
  2735. if (dir)
  2736. result += compressed ? dir->dir_z_len : dir->dir_len;
  2737. });
  2738. }
  2739. return result;
  2740. }
  2741. /** When we're spooling data onto our outbuf, add more whenever we dip
  2742. * below this threshold. */
  2743. #define DIRSERV_BUFFER_MIN 16384
  2744. /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
  2745. * Flushes any remaining data to be (un)compressed, and changes the spool
  2746. * source to NONE. Returns 0 on success, negative on failure. */
  2747. static int
  2748. connection_dirserv_finish_spooling(dir_connection_t *conn)
  2749. {
  2750. if (conn->zlib_state) {
  2751. connection_write_to_buf_zlib("", 0, conn, 1);
  2752. tor_zlib_free(conn->zlib_state);
  2753. conn->zlib_state = NULL;
  2754. }
  2755. conn->dir_spool_src = DIR_SPOOL_NONE;
  2756. return 0;
  2757. }
  2758. /** Spooling helper: called when we're sending a bunch of server descriptors,
  2759. * and the outbuf has become too empty. Pulls some entries from
  2760. * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
  2761. * run out of entries, flushes the zlib state and sets the spool source to
  2762. * NONE. Returns 0 on success, negative on failure.
  2763. */
  2764. static int
  2765. connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
  2766. {
  2767. #ifdef TRACK_SERVED_TIME
  2768. time_t now = time(NULL);
  2769. #endif
  2770. int by_fp = (conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP ||
  2771. conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP);
  2772. int extra = (conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP ||
  2773. conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_DIGEST);
  2774. time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
  2775. while (smartlist_len(conn->fingerprint_stack) &&
  2776. buf_datalen(conn->_base.outbuf) < DIRSERV_BUFFER_MIN) {
  2777. const char *body;
  2778. char *fp = smartlist_pop_last(conn->fingerprint_stack);
  2779. signed_descriptor_t *sd = NULL;
  2780. if (by_fp) {
  2781. sd = get_signed_descriptor_by_fp(fp, extra, publish_cutoff);
  2782. } else {
  2783. sd = extra ? extrainfo_get_by_descriptor_digest(fp)
  2784. : router_get_by_descriptor_digest(fp);
  2785. }
  2786. tor_free(fp);
  2787. if (!sd)
  2788. continue;
  2789. if (!connection_dir_is_encrypted(conn) && !sd->send_unencrypted) {
  2790. /* we did this check once before (so we could have an accurate size
  2791. * estimate and maybe send a 404 if somebody asked for only bridges on a
  2792. * connection), but we need to do it again in case a previously
  2793. * unknown bridge descriptor has shown up between then and now. */
  2794. continue;
  2795. }
  2796. #ifdef TRACK_SERVED_TIME
  2797. sd->last_served_at = now;
  2798. #endif
  2799. body = signed_descriptor_get_body(sd);
  2800. if (conn->zlib_state) {
  2801. int last = ! smartlist_len(conn->fingerprint_stack);
  2802. connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
  2803. last);
  2804. if (last) {
  2805. tor_zlib_free(conn->zlib_state);
  2806. conn->zlib_state = NULL;
  2807. }
  2808. } else {
  2809. connection_write_to_buf(body,
  2810. sd->signed_descriptor_len,
  2811. TO_CONN(conn));
  2812. }
  2813. }
  2814. if (!smartlist_len(conn->fingerprint_stack)) {
  2815. /* We just wrote the last one; finish up. */
  2816. conn->dir_spool_src = DIR_SPOOL_NONE;
  2817. smartlist_free(conn->fingerprint_stack);
  2818. conn->fingerprint_stack = NULL;
  2819. }
  2820. return 0;
  2821. }
  2822. /** Spooling helper: Called when we're sending a directory or networkstatus,
  2823. * and the outbuf has become too empty. Pulls some bytes from
  2824. * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
  2825. * puts them on the outbuf. If we run out of entries, flushes the zlib state
  2826. * and sets the spool source to NONE. Returns 0 on success, negative on
  2827. * failure. */
  2828. static int
  2829. connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
  2830. {
  2831. ssize_t bytes;
  2832. int64_t remaining;
  2833. bytes = DIRSERV_BUFFER_MIN - buf_datalen(conn->_base.outbuf);
  2834. tor_assert(bytes > 0);
  2835. tor_assert(conn->cached_dir);
  2836. if (bytes < 8192)
  2837. bytes = 8192;
  2838. remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
  2839. if (bytes > remaining)
  2840. bytes = (ssize_t) remaining;
  2841. if (conn->zlib_state) {
  2842. connection_write_to_buf_zlib(
  2843. conn->cached_dir->dir_z + conn->cached_dir_offset,
  2844. bytes, conn, bytes == remaining);
  2845. } else {
  2846. connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
  2847. bytes, TO_CONN(conn));
  2848. }
  2849. conn->cached_dir_offset += bytes;
  2850. if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
  2851. /* We just wrote the last one; finish up. */
  2852. connection_dirserv_finish_spooling(conn);
  2853. cached_dir_decref(conn->cached_dir);
  2854. conn->cached_dir = NULL;
  2855. }
  2856. return 0;
  2857. }
  2858. /** Spooling helper: Called when we're spooling networkstatus objects on
  2859. * <b>conn</b>, and the outbuf has become too empty. If the current
  2860. * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
  2861. * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
  2862. * and start spooling the next networkstatus. (A digest of all 0 bytes is
  2863. * treated as a request for the current consensus.) If we run out of entries,
  2864. * flushes the zlib state and sets the spool source to NONE. Returns 0 on
  2865. * success, negative on failure. */
  2866. static int
  2867. connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
  2868. {
  2869. while (buf_datalen(conn->_base.outbuf) < DIRSERV_BUFFER_MIN) {
  2870. if (conn->cached_dir) {
  2871. int uncompressing = (conn->zlib_state != NULL);
  2872. int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
  2873. if (conn->dir_spool_src == DIR_SPOOL_NONE) {
  2874. /* add_dir_bytes thinks we're done with the cached_dir. But we
  2875. * may have more cached_dirs! */
  2876. conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
  2877. /* This bit is tricky. If we were uncompressing the last
  2878. * networkstatus, we may need to make a new zlib object to
  2879. * uncompress the next one. */
  2880. if (uncompressing && ! conn->zlib_state &&
  2881. conn->fingerprint_stack &&
  2882. smartlist_len(conn->fingerprint_stack)) {
  2883. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  2884. }
  2885. }
  2886. if (r) return r;
  2887. } else if (conn->fingerprint_stack &&
  2888. smartlist_len(conn->fingerprint_stack)) {
  2889. /* Add another networkstatus; start serving it. */
  2890. char *fp = smartlist_pop_last(conn->fingerprint_stack);
  2891. cached_dir_t *d = lookup_cached_dir_by_fp(fp);
  2892. tor_free(fp);
  2893. if (d) {
  2894. ++d->refcnt;
  2895. conn->cached_dir = d;
  2896. conn->cached_dir_offset = 0;
  2897. }
  2898. } else {
  2899. connection_dirserv_finish_spooling(conn);
  2900. if (conn->fingerprint_stack)
  2901. smartlist_free(conn->fingerprint_stack);
  2902. conn->fingerprint_stack = NULL;
  2903. return 0;
  2904. }
  2905. }
  2906. return 0;
  2907. }
  2908. /** Called whenever we have flushed some directory data in state
  2909. * SERVER_WRITING. */
  2910. int
  2911. connection_dirserv_flushed_some(dir_connection_t *conn)
  2912. {
  2913. tor_assert(conn->_base.state == DIR_CONN_STATE_SERVER_WRITING);
  2914. if (buf_datalen(conn->_base.outbuf) >= DIRSERV_BUFFER_MIN)
  2915. return 0;
  2916. switch (conn->dir_spool_src) {
  2917. case DIR_SPOOL_EXTRA_BY_DIGEST:
  2918. case DIR_SPOOL_EXTRA_BY_FP:
  2919. case DIR_SPOOL_SERVER_BY_DIGEST:
  2920. case DIR_SPOOL_SERVER_BY_FP:
  2921. return connection_dirserv_add_servers_to_outbuf(conn);
  2922. case DIR_SPOOL_CACHED_DIR:
  2923. return connection_dirserv_add_dir_bytes_to_outbuf(conn);
  2924. case DIR_SPOOL_NETWORKSTATUS:
  2925. return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
  2926. case DIR_SPOOL_NONE:
  2927. default:
  2928. return 0;
  2929. }
  2930. }
  2931. /** Release all storage used by the directory server. */
  2932. void
  2933. dirserv_free_all(void)
  2934. {
  2935. dirserv_free_fingerprint_list();
  2936. cached_dir_decref(the_directory);
  2937. clear_cached_dir(&the_runningrouters);
  2938. cached_dir_decref(the_v2_networkstatus);
  2939. cached_dir_decref(cached_directory);
  2940. clear_cached_dir(&cached_runningrouters);
  2941. if (cached_v2_networkstatus) {
  2942. digestmap_free(cached_v2_networkstatus, _free_cached_dir);
  2943. cached_v2_networkstatus = NULL;
  2944. }
  2945. cached_dir_decref(cached_v3_networkstatus);
  2946. }