dirserv.c 133 KB

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