dirserv.c 119 KB

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