dirserv.c 120 KB

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