dirserv.c 126 KB

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