dirserv.c 109 KB

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