dirserv.c 97 KB

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