dirserv.c 101 KB

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