dirserv.c 102 KB

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