dirserv.c 136 KB

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