dirserv.c 103 KB

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