dirserv.c 124 KB

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