dirserv.c 93 KB

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