dirserv.c 100 KB

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