dirserv.c 113 KB

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