dirserv.c 126 KB

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