dirserv.c 121 KB

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