dirserv.c 108 KB

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