dirserv.c 141 KB

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