dirserv.c 123 KB

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