dirserv.c 119 KB

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