dirserv.c 132 KB

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