dirserv.c 136 KB

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