dirserv.c 127 KB

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