router.c 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. #define ROUTER_PRIVATE
  7. #include "or.h"
  8. #include "circuitbuild.h"
  9. #include "circuitlist.h"
  10. #include "circuituse.h"
  11. #include "config.h"
  12. #include "connection.h"
  13. #include "control.h"
  14. #include "directory.h"
  15. #include "dirserv.h"
  16. #include "dns.h"
  17. #include "geoip.h"
  18. #include "hibernate.h"
  19. #include "main.h"
  20. #include "networkstatus.h"
  21. #include "nodelist.h"
  22. #include "policies.h"
  23. #include "relay.h"
  24. #include "rephist.h"
  25. #include "router.h"
  26. #include "routerlist.h"
  27. #include "routerparse.h"
  28. /**
  29. * \file router.c
  30. * \brief OR functionality, including key maintenance, generating
  31. * and uploading server descriptors, retrying OR connections.
  32. **/
  33. extern long stats_n_seconds_working;
  34. /************************************************************/
  35. /*****
  36. * Key management: ORs only.
  37. *****/
  38. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  39. */
  40. static tor_mutex_t *key_lock=NULL;
  41. static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
  42. /** Current private onionskin decryption key: used to decode CREATE cells. */
  43. static crypto_pk_t *onionkey=NULL;
  44. /** Previous private onionskin decryption key: used to decode CREATE cells
  45. * generated by clients that have an older version of our descriptor. */
  46. static crypto_pk_t *lastonionkey=NULL;
  47. /** Private server "identity key": used to sign directory info and TLS
  48. * certificates. Never changes. */
  49. static crypto_pk_t *server_identitykey=NULL;
  50. /** Digest of server_identitykey. */
  51. static char server_identitykey_digest[DIGEST_LEN];
  52. /** Private client "identity key": used to sign bridges' and clients'
  53. * outbound TLS certificates. Regenerated on startup and on IP address
  54. * change. */
  55. static crypto_pk_t *client_identitykey=NULL;
  56. /** Signing key used for v3 directory material; only set for authorities. */
  57. static crypto_pk_t *authority_signing_key = NULL;
  58. /** Key certificate to authenticate v3 directory material; only set for
  59. * authorities. */
  60. static authority_cert_t *authority_key_certificate = NULL;
  61. /** For emergency V3 authority key migration: An extra signing key that we use
  62. * with our old (obsolete) identity key for a while. */
  63. static crypto_pk_t *legacy_signing_key = NULL;
  64. /** For emergency V3 authority key migration: An extra certificate to
  65. * authenticate legacy_signing_key with our obsolete identity key.*/
  66. static authority_cert_t *legacy_key_certificate = NULL;
  67. /* (Note that v3 authorities also have a separate "authority identity key",
  68. * but this key is never actually loaded by the Tor process. Instead, it's
  69. * used by tor-gencert to sign new signing keys and make new key
  70. * certificates. */
  71. /** Replace the current onion key with <b>k</b>. Does not affect
  72. * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
  73. */
  74. static void
  75. set_onion_key(crypto_pk_t *k)
  76. {
  77. if (onionkey && !crypto_pk_cmp_keys(onionkey, k)) {
  78. /* k is already our onion key; free it and return */
  79. crypto_pk_free(k);
  80. return;
  81. }
  82. tor_mutex_acquire(key_lock);
  83. crypto_pk_free(onionkey);
  84. onionkey = k;
  85. tor_mutex_release(key_lock);
  86. mark_my_descriptor_dirty("set onion key");
  87. }
  88. /** Return the current onion key. Requires that the onion key has been
  89. * loaded or generated. */
  90. crypto_pk_t *
  91. get_onion_key(void)
  92. {
  93. tor_assert(onionkey);
  94. return onionkey;
  95. }
  96. /** Store a full copy of the current onion key into *<b>key</b>, and a full
  97. * copy of the most recent onion key into *<b>last</b>.
  98. */
  99. void
  100. dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
  101. {
  102. tor_assert(key);
  103. tor_assert(last);
  104. tor_mutex_acquire(key_lock);
  105. tor_assert(onionkey);
  106. *key = crypto_pk_copy_full(onionkey);
  107. if (lastonionkey)
  108. *last = crypto_pk_copy_full(lastonionkey);
  109. else
  110. *last = NULL;
  111. tor_mutex_release(key_lock);
  112. }
  113. /** Return the time when the onion key was last set. This is either the time
  114. * when the process launched, or the time of the most recent key rotation since
  115. * the process launched.
  116. */
  117. time_t
  118. get_onion_key_set_at(void)
  119. {
  120. return onionkey_set_at;
  121. }
  122. /** Set the current server identity key to <b>k</b>.
  123. */
  124. void
  125. set_server_identity_key(crypto_pk_t *k)
  126. {
  127. crypto_pk_free(server_identitykey);
  128. server_identitykey = k;
  129. crypto_pk_get_digest(server_identitykey, server_identitykey_digest);
  130. }
  131. /** Make sure that we have set up our identity keys to match or not match as
  132. * appropriate, and die with an assertion if we have not. */
  133. static void
  134. assert_identity_keys_ok(void)
  135. {
  136. tor_assert(client_identitykey);
  137. if (public_server_mode(get_options())) {
  138. /* assert that we have set the client and server keys to be equal */
  139. tor_assert(server_identitykey);
  140. tor_assert(0==crypto_pk_cmp_keys(client_identitykey, server_identitykey));
  141. } else {
  142. /* assert that we have set the client and server keys to be unequal */
  143. if (server_identitykey)
  144. tor_assert(0!=crypto_pk_cmp_keys(client_identitykey,
  145. server_identitykey));
  146. }
  147. }
  148. /** Returns the current server identity key; requires that the key has
  149. * been set, and that we are running as a Tor server.
  150. */
  151. crypto_pk_t *
  152. get_server_identity_key(void)
  153. {
  154. tor_assert(server_identitykey);
  155. tor_assert(server_mode(get_options()));
  156. assert_identity_keys_ok();
  157. return server_identitykey;
  158. }
  159. /** Return true iff the server identity key has been set. */
  160. int
  161. server_identity_key_is_set(void)
  162. {
  163. return server_identitykey != NULL;
  164. }
  165. /** Set the current client identity key to <b>k</b>.
  166. */
  167. void
  168. set_client_identity_key(crypto_pk_t *k)
  169. {
  170. crypto_pk_free(client_identitykey);
  171. client_identitykey = k;
  172. }
  173. /** Returns the current client identity key for use on outgoing TLS
  174. * connections; requires that the key has been set.
  175. */
  176. crypto_pk_t *
  177. get_tlsclient_identity_key(void)
  178. {
  179. tor_assert(client_identitykey);
  180. assert_identity_keys_ok();
  181. return client_identitykey;
  182. }
  183. /** Return true iff the client identity key has been set. */
  184. int
  185. client_identity_key_is_set(void)
  186. {
  187. return client_identitykey != NULL;
  188. }
  189. /** Return the key certificate for this v3 (voting) authority, or NULL
  190. * if we have no such certificate. */
  191. authority_cert_t *
  192. get_my_v3_authority_cert(void)
  193. {
  194. return authority_key_certificate;
  195. }
  196. /** Return the v3 signing key for this v3 (voting) authority, or NULL
  197. * if we have no such key. */
  198. crypto_pk_t *
  199. get_my_v3_authority_signing_key(void)
  200. {
  201. return authority_signing_key;
  202. }
  203. /** If we're an authority, and we're using a legacy authority identity key for
  204. * emergency migration purposes, return the certificate associated with that
  205. * key. */
  206. authority_cert_t *
  207. get_my_v3_legacy_cert(void)
  208. {
  209. return legacy_key_certificate;
  210. }
  211. /** If we're an authority, and we're using a legacy authority identity key for
  212. * emergency migration purposes, return that key. */
  213. crypto_pk_t *
  214. get_my_v3_legacy_signing_key(void)
  215. {
  216. return legacy_signing_key;
  217. }
  218. /** Replace the previous onion key with the current onion key, and generate
  219. * a new previous onion key. Immediately after calling this function,
  220. * the OR should:
  221. * - schedule all previous cpuworkers to shut down _after_ processing
  222. * pending work. (This will cause fresh cpuworkers to be generated.)
  223. * - generate and upload a fresh routerinfo.
  224. */
  225. void
  226. rotate_onion_key(void)
  227. {
  228. char *fname, *fname_prev;
  229. crypto_pk_t *prkey;
  230. or_state_t *state = get_or_state();
  231. time_t now;
  232. fname = get_datadir_fname2("keys", "secret_onion_key");
  233. fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
  234. if (!(prkey = crypto_pk_new())) {
  235. log_err(LD_GENERAL,"Error constructing rotated onion key");
  236. goto error;
  237. }
  238. if (crypto_pk_generate_key(prkey)) {
  239. log_err(LD_BUG,"Error generating onion key");
  240. goto error;
  241. }
  242. if (file_status(fname) == FN_FILE) {
  243. if (replace_file(fname, fname_prev))
  244. goto error;
  245. }
  246. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  247. log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
  248. goto error;
  249. }
  250. log_info(LD_GENERAL, "Rotating onion key");
  251. tor_mutex_acquire(key_lock);
  252. crypto_pk_free(lastonionkey);
  253. lastonionkey = onionkey;
  254. onionkey = prkey;
  255. now = time(NULL);
  256. state->LastRotatedOnionKey = onionkey_set_at = now;
  257. tor_mutex_release(key_lock);
  258. mark_my_descriptor_dirty("rotated onion key");
  259. or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
  260. goto done;
  261. error:
  262. log_warn(LD_GENERAL, "Couldn't rotate onion key.");
  263. if (prkey)
  264. crypto_pk_free(prkey);
  265. done:
  266. tor_free(fname);
  267. tor_free(fname_prev);
  268. }
  269. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
  270. * and <b>generate</b> is true, create a new RSA key and save it in
  271. * <b>fname</b>. Return the read/created key, or NULL on error. Log all
  272. * errors at level <b>severity</b>.
  273. */
  274. crypto_pk_t *
  275. init_key_from_file(const char *fname, int generate, int severity)
  276. {
  277. crypto_pk_t *prkey = NULL;
  278. if (!(prkey = crypto_pk_new())) {
  279. log(severity, LD_GENERAL,"Error constructing key");
  280. goto error;
  281. }
  282. switch (file_status(fname)) {
  283. case FN_DIR:
  284. case FN_ERROR:
  285. log(severity, LD_FS,"Can't read key from \"%s\"", fname);
  286. goto error;
  287. case FN_NOENT:
  288. if (generate) {
  289. if (!have_lockfile()) {
  290. if (try_locking(get_options(), 0)<0) {
  291. /* Make sure that --list-fingerprint only creates new keys
  292. * if there is no possibility for a deadlock. */
  293. log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
  294. "writing any new keys.", fname);
  295. /*XXXX The 'other process' might make a key in a second or two;
  296. * maybe we should wait for it. */
  297. goto error;
  298. }
  299. }
  300. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  301. fname);
  302. if (crypto_pk_generate_key(prkey)) {
  303. log(severity, LD_GENERAL,"Error generating onion key");
  304. goto error;
  305. }
  306. if (crypto_pk_check_key(prkey) <= 0) {
  307. log(severity, LD_GENERAL,"Generated key seems invalid");
  308. goto error;
  309. }
  310. log_info(LD_GENERAL, "Generated key seems valid");
  311. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  312. log(severity, LD_FS,
  313. "Couldn't write generated key to \"%s\".", fname);
  314. goto error;
  315. }
  316. } else {
  317. log_info(LD_GENERAL, "No key found in \"%s\"", fname);
  318. }
  319. return prkey;
  320. case FN_FILE:
  321. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  322. log(severity, LD_GENERAL,"Error loading private key.");
  323. goto error;
  324. }
  325. return prkey;
  326. default:
  327. tor_assert(0);
  328. }
  329. error:
  330. if (prkey)
  331. crypto_pk_free(prkey);
  332. return NULL;
  333. }
  334. /** Try to load the vote-signing private key and certificate for being a v3
  335. * directory authority, and make sure they match. If <b>legacy</b>, load a
  336. * legacy key/cert set for emergency key migration; otherwise load the regular
  337. * key/cert set. On success, store them into *<b>key_out</b> and
  338. * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
  339. static int
  340. load_authority_keyset(int legacy, crypto_pk_t **key_out,
  341. authority_cert_t **cert_out)
  342. {
  343. int r = -1;
  344. char *fname = NULL, *cert = NULL;
  345. const char *eos = NULL;
  346. crypto_pk_t *signing_key = NULL;
  347. authority_cert_t *parsed = NULL;
  348. fname = get_datadir_fname2("keys",
  349. legacy ? "legacy_signing_key" : "authority_signing_key");
  350. signing_key = init_key_from_file(fname, 0, LOG_INFO);
  351. if (!signing_key) {
  352. log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
  353. goto done;
  354. }
  355. tor_free(fname);
  356. fname = get_datadir_fname2("keys",
  357. legacy ? "legacy_certificate" : "authority_certificate");
  358. cert = read_file_to_str(fname, 0, NULL);
  359. if (!cert) {
  360. log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
  361. fname);
  362. goto done;
  363. }
  364. parsed = authority_cert_parse_from_string(cert, &eos);
  365. if (!parsed) {
  366. log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
  367. goto done;
  368. }
  369. if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
  370. log_warn(LD_DIR, "Stored signing key does not match signing key in "
  371. "certificate");
  372. goto done;
  373. }
  374. crypto_pk_free(*key_out);
  375. authority_cert_free(*cert_out);
  376. *key_out = signing_key;
  377. *cert_out = parsed;
  378. r = 0;
  379. signing_key = NULL;
  380. parsed = NULL;
  381. done:
  382. tor_free(fname);
  383. tor_free(cert);
  384. crypto_pk_free(signing_key);
  385. authority_cert_free(parsed);
  386. return r;
  387. }
  388. /** Load the v3 (voting) authority signing key and certificate, if they are
  389. * present. Return -1 if anything is missing, mismatched, or unloadable;
  390. * return 0 on success. */
  391. static int
  392. init_v3_authority_keys(void)
  393. {
  394. if (load_authority_keyset(0, &authority_signing_key,
  395. &authority_key_certificate)<0)
  396. return -1;
  397. if (get_options()->V3AuthUseLegacyKey &&
  398. load_authority_keyset(1, &legacy_signing_key,
  399. &legacy_key_certificate)<0)
  400. return -1;
  401. return 0;
  402. }
  403. /** If we're a v3 authority, check whether we have a certificate that's
  404. * likely to expire soon. Warn if we do, but not too often. */
  405. void
  406. v3_authority_check_key_expiry(void)
  407. {
  408. time_t now, expires;
  409. static time_t last_warned = 0;
  410. int badness, time_left, warn_interval;
  411. if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
  412. return;
  413. now = time(NULL);
  414. expires = authority_key_certificate->expires;
  415. time_left = (int)( expires - now );
  416. if (time_left <= 0) {
  417. badness = LOG_ERR;
  418. warn_interval = 60*60;
  419. } else if (time_left <= 24*60*60) {
  420. badness = LOG_WARN;
  421. warn_interval = 60*60;
  422. } else if (time_left <= 24*60*60*7) {
  423. badness = LOG_WARN;
  424. warn_interval = 24*60*60;
  425. } else if (time_left <= 24*60*60*30) {
  426. badness = LOG_WARN;
  427. warn_interval = 24*60*60*5;
  428. } else {
  429. return;
  430. }
  431. if (last_warned + warn_interval > now)
  432. return;
  433. if (time_left <= 0) {
  434. log(badness, LD_DIR, "Your v3 authority certificate has expired."
  435. " Generate a new one NOW.");
  436. } else if (time_left <= 24*60*60) {
  437. log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
  438. " Generate a new one NOW.", time_left/(60*60));
  439. } else {
  440. log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
  441. " Generate a new one soon.", time_left/(24*60*60));
  442. }
  443. last_warned = now;
  444. }
  445. /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
  446. * on success, and -1 on failure. */
  447. int
  448. router_initialize_tls_context(void)
  449. {
  450. return tor_tls_context_init(public_server_mode(get_options()),
  451. get_tlsclient_identity_key(),
  452. server_mode(get_options()) ?
  453. get_server_identity_key() : NULL,
  454. MAX_SSL_KEY_LIFETIME_ADVERTISED);
  455. }
  456. /** Initialize all OR private keys, and the TLS context, as necessary.
  457. * On OPs, this only initializes the tls context. Return 0 on success,
  458. * or -1 if Tor should die.
  459. */
  460. int
  461. init_keys(void)
  462. {
  463. char *keydir;
  464. char fingerprint[FINGERPRINT_LEN+1];
  465. /*nickname<space>fp\n\0 */
  466. char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
  467. const char *mydesc;
  468. crypto_pk_t *prkey;
  469. char digest[DIGEST_LEN];
  470. char v3_digest[DIGEST_LEN];
  471. char *cp;
  472. const or_options_t *options = get_options();
  473. dirinfo_type_t type;
  474. time_t now = time(NULL);
  475. trusted_dir_server_t *ds;
  476. int v3_digest_set = 0;
  477. authority_cert_t *cert = NULL;
  478. if (!key_lock)
  479. key_lock = tor_mutex_new();
  480. /* There are a couple of paths that put us here before we've asked
  481. * openssl to initialize itself. */
  482. if (crypto_global_init(get_options()->HardwareAccel,
  483. get_options()->AccelName,
  484. get_options()->AccelDir)) {
  485. log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
  486. return -1;
  487. }
  488. /* OP's don't need persistent keys; just make up an identity and
  489. * initialize the TLS context. */
  490. if (!server_mode(options)) {
  491. if (!(prkey = crypto_pk_new()))
  492. return -1;
  493. if (crypto_pk_generate_key(prkey)) {
  494. crypto_pk_free(prkey);
  495. return -1;
  496. }
  497. set_client_identity_key(prkey);
  498. /* Create a TLS context. */
  499. if (router_initialize_tls_context() < 0) {
  500. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  501. return -1;
  502. }
  503. return 0;
  504. }
  505. /* Make sure DataDirectory exists, and is private. */
  506. if (check_private_dir(options->DataDirectory, CPD_CREATE, options->User)) {
  507. return -1;
  508. }
  509. /* Check the key directory. */
  510. keydir = get_datadir_fname("keys");
  511. if (check_private_dir(keydir, CPD_CREATE, options->User)) {
  512. tor_free(keydir);
  513. return -1;
  514. }
  515. tor_free(keydir);
  516. /* 1a. Read v3 directory authority key/cert information. */
  517. memset(v3_digest, 0, sizeof(v3_digest));
  518. if (authdir_mode_v3(options)) {
  519. if (init_v3_authority_keys()<0) {
  520. log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
  521. "were unable to load our v3 authority keys and certificate! "
  522. "Use tor-gencert to generate them. Dying.");
  523. return -1;
  524. }
  525. cert = get_my_v3_authority_cert();
  526. if (cert) {
  527. crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
  528. v3_digest);
  529. v3_digest_set = 1;
  530. }
  531. }
  532. /* 1b. Read identity key. Make it if none is found. */
  533. keydir = get_datadir_fname2("keys", "secret_id_key");
  534. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  535. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  536. tor_free(keydir);
  537. if (!prkey) return -1;
  538. set_server_identity_key(prkey);
  539. /* 1c. If we are configured as a bridge, generate a client key;
  540. * otherwise, set the server identity key as our client identity
  541. * key. */
  542. if (public_server_mode(options)) {
  543. set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
  544. } else {
  545. if (!(prkey = crypto_pk_new()))
  546. return -1;
  547. if (crypto_pk_generate_key(prkey)) {
  548. crypto_pk_free(prkey);
  549. return -1;
  550. }
  551. set_client_identity_key(prkey);
  552. }
  553. /* 2. Read onion key. Make it if none is found. */
  554. keydir = get_datadir_fname2("keys", "secret_onion_key");
  555. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  556. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  557. tor_free(keydir);
  558. if (!prkey) return -1;
  559. set_onion_key(prkey);
  560. if (options->command == CMD_RUN_TOR) {
  561. /* only mess with the state file if we're actually running Tor */
  562. or_state_t *state = get_or_state();
  563. if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
  564. /* We allow for some parsing slop, but we don't want to risk accepting
  565. * values in the distant future. If we did, we might never rotate the
  566. * onion key. */
  567. onionkey_set_at = state->LastRotatedOnionKey;
  568. } else {
  569. /* We have no LastRotatedOnionKey set; either we just created the key
  570. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  571. * start the clock ticking now so that we will eventually rotate it even
  572. * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
  573. state->LastRotatedOnionKey = onionkey_set_at = now;
  574. or_state_mark_dirty(state, options->AvoidDiskWrites ?
  575. time(NULL)+3600 : 0);
  576. }
  577. }
  578. keydir = get_datadir_fname2("keys", "secret_onion_key.old");
  579. if (!lastonionkey && file_status(keydir) == FN_FILE) {
  580. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  581. if (prkey)
  582. lastonionkey = prkey;
  583. }
  584. tor_free(keydir);
  585. /* 3. Initialize link key and TLS context. */
  586. if (router_initialize_tls_context() < 0) {
  587. log_err(LD_GENERAL,"Error initializing TLS context");
  588. return -1;
  589. }
  590. /* 4. Build our router descriptor. */
  591. /* Must be called after keys are initialized. */
  592. mydesc = router_get_my_descriptor();
  593. if (authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)) {
  594. const char *m = NULL;
  595. routerinfo_t *ri;
  596. /* We need to add our own fingerprint so it gets recognized. */
  597. if (dirserv_add_own_fingerprint(options->Nickname,
  598. get_server_identity_key())) {
  599. log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
  600. return -1;
  601. }
  602. if (mydesc) {
  603. was_router_added_t added;
  604. ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
  605. if (!ri) {
  606. log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
  607. return -1;
  608. }
  609. added = dirserv_add_descriptor(ri, &m, "self");
  610. if (!WRA_WAS_ADDED(added)) {
  611. if (!WRA_WAS_OUTDATED(added)) {
  612. log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
  613. m?m:"<unknown error>");
  614. return -1;
  615. } else {
  616. /* If the descriptor was outdated, that's ok. This can happen
  617. * when some config options are toggled that affect workers, but
  618. * we don't really need new keys yet so the descriptor doesn't
  619. * change and the old one is still fresh. */
  620. log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
  621. "after key init: %s. This is usually not a problem.",
  622. m?m:"<unknown error>");
  623. }
  624. }
  625. }
  626. }
  627. /* 5. Dump fingerprint to 'fingerprint' */
  628. keydir = get_datadir_fname("fingerprint");
  629. log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  630. if (crypto_pk_get_fingerprint(get_server_identity_key(),
  631. fingerprint, 0) < 0) {
  632. log_err(LD_GENERAL,"Error computing fingerprint");
  633. tor_free(keydir);
  634. return -1;
  635. }
  636. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  637. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  638. "%s %s\n",options->Nickname, fingerprint) < 0) {
  639. log_err(LD_GENERAL,"Error writing fingerprint line");
  640. tor_free(keydir);
  641. return -1;
  642. }
  643. /* Check whether we need to write the fingerprint file. */
  644. cp = NULL;
  645. if (file_status(keydir) == FN_FILE)
  646. cp = read_file_to_str(keydir, 0, NULL);
  647. if (!cp || strcmp(cp, fingerprint_line)) {
  648. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  649. log_err(LD_FS, "Error writing fingerprint line to file");
  650. tor_free(keydir);
  651. tor_free(cp);
  652. return -1;
  653. }
  654. }
  655. tor_free(cp);
  656. tor_free(keydir);
  657. log(LOG_NOTICE, LD_GENERAL,
  658. "Your Tor server's identity key fingerprint is '%s %s'",
  659. options->Nickname, fingerprint);
  660. if (!authdir_mode(options))
  661. return 0;
  662. /* 6. [authdirserver only] load approved-routers file */
  663. if (dirserv_load_fingerprint_file() < 0) {
  664. log_err(LD_GENERAL,"Error loading fingerprints");
  665. return -1;
  666. }
  667. /* 6b. [authdirserver only] add own key to approved directories. */
  668. crypto_pk_get_digest(get_server_identity_key(), digest);
  669. type = ((options->V1AuthoritativeDir ? V1_DIRINFO : NO_DIRINFO) |
  670. (options->V2AuthoritativeDir ? V2_DIRINFO : NO_DIRINFO) |
  671. (options->V3AuthoritativeDir ?
  672. (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
  673. (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO) |
  674. (options->HSAuthoritativeDir ? HIDSERV_DIRINFO : NO_DIRINFO));
  675. ds = router_get_trusteddirserver_by_digest(digest);
  676. if (!ds) {
  677. ds = add_trusted_dir_server(options->Nickname, NULL,
  678. router_get_advertised_dir_port(options, 0),
  679. router_get_advertised_or_port(options),
  680. digest,
  681. v3_digest,
  682. type);
  683. if (!ds) {
  684. log_err(LD_GENERAL,"We want to be a directory authority, but we "
  685. "couldn't add ourselves to the authority list. Failing.");
  686. return -1;
  687. }
  688. }
  689. if (ds->type != type) {
  690. log_warn(LD_DIR, "Configured authority type does not match authority "
  691. "type in DirServer list. Adjusting. (%d v %d)",
  692. type, ds->type);
  693. ds->type = type;
  694. }
  695. if (v3_digest_set && (ds->type & V3_DIRINFO) &&
  696. tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
  697. log_warn(LD_DIR, "V3 identity key does not match identity declared in "
  698. "DirServer line. Adjusting.");
  699. memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
  700. }
  701. if (cert) { /* add my own cert to the list of known certs */
  702. log_info(LD_DIR, "adding my own v3 cert");
  703. if (trusted_dirs_load_certs_from_string(
  704. cert->cache_info.signed_descriptor_body, 0, 0)<0) {
  705. log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
  706. return -1;
  707. }
  708. }
  709. return 0; /* success */
  710. }
  711. /* Keep track of whether we should upload our server descriptor,
  712. * and what type of server we are.
  713. */
  714. /** Whether we can reach our ORPort from the outside. */
  715. static int can_reach_or_port = 0;
  716. /** Whether we can reach our DirPort from the outside. */
  717. static int can_reach_dir_port = 0;
  718. /** Forget what we have learned about our reachability status. */
  719. void
  720. router_reset_reachability(void)
  721. {
  722. can_reach_or_port = can_reach_dir_port = 0;
  723. }
  724. /** Return 1 if ORPort is known reachable; else return 0. */
  725. int
  726. check_whether_orport_reachable(void)
  727. {
  728. const or_options_t *options = get_options();
  729. return options->AssumeReachable ||
  730. can_reach_or_port;
  731. }
  732. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  733. int
  734. check_whether_dirport_reachable(void)
  735. {
  736. const or_options_t *options = get_options();
  737. return !options->DirPort ||
  738. options->AssumeReachable ||
  739. net_is_disabled() ||
  740. can_reach_dir_port;
  741. }
  742. /** Look at a variety of factors, and return 0 if we don't want to
  743. * advertise the fact that we have a DirPort open. Else return the
  744. * DirPort we want to advertise.
  745. *
  746. * Log a helpful message if we change our mind about whether to publish
  747. * a DirPort.
  748. */
  749. static int
  750. decide_to_advertise_dirport(const or_options_t *options, uint16_t dir_port)
  751. {
  752. static int advertising=1; /* start out assuming we will advertise */
  753. int new_choice=1;
  754. const char *reason = NULL;
  755. /* Section one: reasons to publish or not publish that aren't
  756. * worth mentioning to the user, either because they're obvious
  757. * or because they're normal behavior. */
  758. if (!dir_port) /* short circuit the rest of the function */
  759. return 0;
  760. if (authdir_mode(options)) /* always publish */
  761. return dir_port;
  762. if (net_is_disabled())
  763. return 0;
  764. if (!check_whether_dirport_reachable())
  765. return 0;
  766. if (!router_get_advertised_dir_port(options, dir_port))
  767. return 0;
  768. /* Section two: reasons to publish or not publish that the user
  769. * might find surprising. These are generally config options that
  770. * make us choose not to publish. */
  771. if (accounting_is_enabled(options)) {
  772. /* Don't spend bytes for directory traffic if we could end up hibernating,
  773. * but allow DirPort otherwise. Some people set AccountingMax because
  774. * they're confused or to get statistics. */
  775. int interval_length = accounting_get_interval_length();
  776. uint32_t effective_bw = get_effective_bwrate(options);
  777. if (!interval_length) {
  778. log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
  779. "seconds long. Raising to 1.");
  780. interval_length = 1;
  781. }
  782. log_info(LD_GENERAL, "Calculating whether to disable dirport: effective "
  783. "bwrate: %u, AccountingMax: "U64_FORMAT", "
  784. "accounting interval length %d", effective_bw,
  785. U64_PRINTF_ARG(options->AccountingMax),
  786. interval_length);
  787. if (effective_bw >=
  788. options->AccountingMax / interval_length) {
  789. new_choice = 0;
  790. reason = "AccountingMax enabled";
  791. }
  792. #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
  793. } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
  794. (options->RelayBandwidthRate > 0 &&
  795. options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
  796. /* if we're advertising a small amount */
  797. new_choice = 0;
  798. reason = "BandwidthRate under 50KB";
  799. }
  800. if (advertising != new_choice) {
  801. if (new_choice == 1) {
  802. log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
  803. } else {
  804. tor_assert(reason);
  805. log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
  806. }
  807. advertising = new_choice;
  808. }
  809. return advertising ? dir_port : 0;
  810. }
  811. /** Some time has passed, or we just got new directory information.
  812. * See if we currently believe our ORPort or DirPort to be
  813. * unreachable. If so, launch a new test for it.
  814. *
  815. * For ORPort, we simply try making a circuit that ends at ourselves.
  816. * Success is noticed in onionskin_answer().
  817. *
  818. * For DirPort, we make a connection via Tor to our DirPort and ask
  819. * for our own server descriptor.
  820. * Success is noticed in connection_dir_client_reached_eof().
  821. */
  822. void
  823. consider_testing_reachability(int test_or, int test_dir)
  824. {
  825. const routerinfo_t *me = router_get_my_routerinfo();
  826. int orport_reachable = check_whether_orport_reachable();
  827. tor_addr_t addr;
  828. const or_options_t *options = get_options();
  829. if (!me)
  830. return;
  831. if (routerset_contains_router(options->ExcludeNodes, me, -1) &&
  832. options->StrictNodes) {
  833. /* If we've excluded ourself, and StrictNodes is set, we can't test
  834. * ourself. */
  835. if (test_or || test_dir) {
  836. #define SELF_EXCLUDED_WARN_INTERVAL 3600
  837. static ratelim_t warning_limit=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL);
  838. char *msg;
  839. if ((msg = rate_limit_log(&warning_limit, approx_time()))) {
  840. log_warn(LD_CIRC, "Can't peform self-tests for this relay: we have "
  841. "listed ourself in ExcludeNodes, and StrictNodes is set. "
  842. "We cannot learn whether we are usable, and will not "
  843. "be able to advertise ourself.%s", msg);
  844. tor_free(msg);
  845. }
  846. }
  847. return;
  848. }
  849. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  850. extend_info_t *ei;
  851. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  852. !orport_reachable ? "reachability" : "bandwidth",
  853. me->address, me->or_port);
  854. /* XXX IPv6 self testing IPv6 orports will need pref_addr */
  855. ei = extend_info_from_router(me, 0);
  856. circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING, ei,
  857. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  858. extend_info_free(ei);
  859. }
  860. tor_addr_from_ipv4h(&addr, me->addr);
  861. if (test_dir && !check_whether_dirport_reachable() &&
  862. !connection_get_by_type_addr_port_purpose(
  863. CONN_TYPE_DIR, &addr, me->dir_port,
  864. DIR_PURPOSE_FETCH_SERVERDESC)) {
  865. /* ask myself, via tor, for my server descriptor. */
  866. directory_initiate_command(me->address, &addr,
  867. me->or_port, me->dir_port,
  868. 0, /* does not matter */
  869. 0, me->cache_info.identity_digest,
  870. DIR_PURPOSE_FETCH_SERVERDESC,
  871. ROUTER_PURPOSE_GENERAL,
  872. 1, "authority.z", NULL, 0, 0);
  873. }
  874. }
  875. /** Annotate that we found our ORPort reachable. */
  876. void
  877. router_orport_found_reachable(void)
  878. {
  879. const routerinfo_t *me = router_get_my_routerinfo();
  880. if (!can_reach_or_port && me) {
  881. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  882. "the outside. Excellent.%s",
  883. get_options()->_PublishServerDescriptor != NO_DIRINFO ?
  884. " Publishing server descriptor." : "");
  885. can_reach_or_port = 1;
  886. mark_my_descriptor_dirty("ORPort found reachable");
  887. control_event_server_status(LOG_NOTICE,
  888. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  889. me->address, me->or_port);
  890. }
  891. }
  892. /** Annotate that we found our DirPort reachable. */
  893. void
  894. router_dirport_found_reachable(void)
  895. {
  896. const routerinfo_t *me = router_get_my_routerinfo();
  897. if (!can_reach_dir_port && me) {
  898. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  899. "from the outside. Excellent.");
  900. can_reach_dir_port = 1;
  901. if (decide_to_advertise_dirport(get_options(), me->dir_port))
  902. mark_my_descriptor_dirty("DirPort found reachable");
  903. control_event_server_status(LOG_NOTICE,
  904. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  905. me->address, me->dir_port);
  906. }
  907. }
  908. /** We have enough testing circuits open. Send a bunch of "drop"
  909. * cells down each of them, to exercise our bandwidth. */
  910. void
  911. router_perform_bandwidth_test(int num_circs, time_t now)
  912. {
  913. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  914. int max_cells = num_cells < CIRCWINDOW_START ?
  915. num_cells : CIRCWINDOW_START;
  916. int cells_per_circuit = max_cells / num_circs;
  917. origin_circuit_t *circ = NULL;
  918. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  919. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  920. CIRCUIT_PURPOSE_TESTING))) {
  921. /* dump cells_per_circuit drop cells onto this circ */
  922. int i = cells_per_circuit;
  923. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  924. continue;
  925. circ->_base.timestamp_dirty = now;
  926. while (i-- > 0) {
  927. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  928. RELAY_COMMAND_DROP,
  929. NULL, 0, circ->cpath->prev)<0) {
  930. return; /* stop if error */
  931. }
  932. }
  933. }
  934. }
  935. /** Return true iff our network is in some sense disabled: either we're
  936. * hibernating, entering hibernation, or */
  937. int
  938. net_is_disabled(void)
  939. {
  940. return get_options()->DisableNetwork || we_are_hibernating();
  941. }
  942. /** Return true iff we believe ourselves to be an authoritative
  943. * directory server.
  944. */
  945. int
  946. authdir_mode(const or_options_t *options)
  947. {
  948. return options->AuthoritativeDir != 0;
  949. }
  950. /** Return true iff we believe ourselves to be a v1 authoritative
  951. * directory server.
  952. */
  953. int
  954. authdir_mode_v1(const or_options_t *options)
  955. {
  956. return authdir_mode(options) && options->V1AuthoritativeDir != 0;
  957. }
  958. /** Return true iff we believe ourselves to be a v2 authoritative
  959. * directory server.
  960. */
  961. int
  962. authdir_mode_v2(const or_options_t *options)
  963. {
  964. return authdir_mode(options) && options->V2AuthoritativeDir != 0;
  965. }
  966. /** Return true iff we believe ourselves to be a v3 authoritative
  967. * directory server.
  968. */
  969. int
  970. authdir_mode_v3(const or_options_t *options)
  971. {
  972. return authdir_mode(options) && options->V3AuthoritativeDir != 0;
  973. }
  974. /** Return true iff we are a v1, v2, or v3 directory authority. */
  975. int
  976. authdir_mode_any_main(const or_options_t *options)
  977. {
  978. return options->V1AuthoritativeDir ||
  979. options->V2AuthoritativeDir ||
  980. options->V3AuthoritativeDir;
  981. }
  982. /** Return true if we believe ourselves to be any kind of
  983. * authoritative directory beyond just a hidserv authority. */
  984. int
  985. authdir_mode_any_nonhidserv(const or_options_t *options)
  986. {
  987. return options->BridgeAuthoritativeDir ||
  988. authdir_mode_any_main(options);
  989. }
  990. /** Return true iff we are an authoritative directory server that is
  991. * authoritative about receiving and serving descriptors of type
  992. * <b>purpose</b> on its dirport. Use -1 for "any purpose". */
  993. int
  994. authdir_mode_handles_descs(const or_options_t *options, int purpose)
  995. {
  996. if (purpose < 0)
  997. return authdir_mode_any_nonhidserv(options);
  998. else if (purpose == ROUTER_PURPOSE_GENERAL)
  999. return authdir_mode_any_main(options);
  1000. else if (purpose == ROUTER_PURPOSE_BRIDGE)
  1001. return (options->BridgeAuthoritativeDir);
  1002. else
  1003. return 0;
  1004. }
  1005. /** Return true iff we are an authoritative directory server that
  1006. * publishes its own network statuses.
  1007. */
  1008. int
  1009. authdir_mode_publishes_statuses(const or_options_t *options)
  1010. {
  1011. if (authdir_mode_bridge(options))
  1012. return 0;
  1013. return authdir_mode_any_nonhidserv(options);
  1014. }
  1015. /** Return true iff we are an authoritative directory server that
  1016. * tests reachability of the descriptors it learns about.
  1017. */
  1018. int
  1019. authdir_mode_tests_reachability(const or_options_t *options)
  1020. {
  1021. return authdir_mode_handles_descs(options, -1);
  1022. }
  1023. /** Return true iff we believe ourselves to be a bridge authoritative
  1024. * directory server.
  1025. */
  1026. int
  1027. authdir_mode_bridge(const or_options_t *options)
  1028. {
  1029. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  1030. }
  1031. /** Return true iff we are trying to be a server.
  1032. */
  1033. int
  1034. server_mode(const or_options_t *options)
  1035. {
  1036. if (options->ClientOnly) return 0;
  1037. return (options->ORPort || options->ORListenAddress);
  1038. }
  1039. /** Return true iff we are trying to be a non-bridge server.
  1040. */
  1041. int
  1042. public_server_mode(const or_options_t *options)
  1043. {
  1044. if (!server_mode(options)) return 0;
  1045. return (!options->BridgeRelay);
  1046. }
  1047. /** Return true iff the combination of options in <b>options</b> and parameters
  1048. * in the consensus mean that we don't want to allow exits from circuits
  1049. * we got from addresses not known to be servers. */
  1050. int
  1051. should_refuse_unknown_exits(const or_options_t *options)
  1052. {
  1053. if (options->RefuseUnknownExits != -1) {
  1054. return options->RefuseUnknownExits;
  1055. } else {
  1056. return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
  1057. }
  1058. }
  1059. /** Remember if we've advertised ourselves to the dirservers. */
  1060. static int server_is_advertised=0;
  1061. /** Return true iff we have published our descriptor lately.
  1062. */
  1063. int
  1064. advertised_server_mode(void)
  1065. {
  1066. return server_is_advertised;
  1067. }
  1068. /**
  1069. * Called with a boolean: set whether we have recently published our
  1070. * descriptor.
  1071. */
  1072. static void
  1073. set_server_advertised(int s)
  1074. {
  1075. server_is_advertised = s;
  1076. }
  1077. /** Return true iff we are trying to proxy client connections. */
  1078. int
  1079. proxy_mode(const or_options_t *options)
  1080. {
  1081. (void)options;
  1082. SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
  1083. if (p->type == CONN_TYPE_AP_LISTENER ||
  1084. p->type == CONN_TYPE_AP_TRANS_LISTENER ||
  1085. p->type == CONN_TYPE_AP_DNS_LISTENER ||
  1086. p->type == CONN_TYPE_AP_NATD_LISTENER)
  1087. return 1;
  1088. } SMARTLIST_FOREACH_END(p);
  1089. return 0;
  1090. }
  1091. /** Decide if we're a publishable server. We are a publishable server if:
  1092. * - We don't have the ClientOnly option set
  1093. * and
  1094. * - We have the PublishServerDescriptor option set to non-empty
  1095. * and
  1096. * - We have ORPort set
  1097. * and
  1098. * - We believe we are reachable from the outside; or
  1099. * - We are an authoritative directory server.
  1100. */
  1101. static int
  1102. decide_if_publishable_server(void)
  1103. {
  1104. const or_options_t *options = get_options();
  1105. if (options->ClientOnly)
  1106. return 0;
  1107. if (options->_PublishServerDescriptor == NO_DIRINFO)
  1108. return 0;
  1109. if (!server_mode(options))
  1110. return 0;
  1111. if (authdir_mode(options))
  1112. return 1;
  1113. if (!router_get_advertised_or_port(options))
  1114. return 0;
  1115. return check_whether_orport_reachable();
  1116. }
  1117. /** Initiate server descriptor upload as reasonable (if server is publishable,
  1118. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  1119. *
  1120. * We need to rebuild the descriptor if it's dirty even if we're not
  1121. * uploading, because our reachability testing *uses* our descriptor to
  1122. * determine what IP address and ports to test.
  1123. */
  1124. void
  1125. consider_publishable_server(int force)
  1126. {
  1127. int rebuilt;
  1128. if (!server_mode(get_options()))
  1129. return;
  1130. rebuilt = router_rebuild_descriptor(0);
  1131. if (decide_if_publishable_server()) {
  1132. set_server_advertised(1);
  1133. if (rebuilt == 0)
  1134. router_upload_dir_desc_to_dirservers(force);
  1135. } else {
  1136. set_server_advertised(0);
  1137. }
  1138. }
  1139. /** Return the port of the first active listener of type
  1140. * <b>listener_type</b>. */
  1141. /** XXX not a very good interface. it's not reliable when there are
  1142. multiple listeners. */
  1143. uint16_t
  1144. router_get_active_listener_port_by_type(int listener_type)
  1145. {
  1146. /* Iterate all connections, find one of the right kind and return
  1147. the port. Not very sophisticated or fast, but effective. */
  1148. const connection_t *c = connection_get_by_type(listener_type);
  1149. if (c)
  1150. return c->port;
  1151. return 0;
  1152. }
  1153. /** Return the port that we should advertise as our ORPort; this is either
  1154. * the one configured in the ORPort option, or the one we actually bound to
  1155. * if ORPort is "auto".
  1156. */
  1157. uint16_t
  1158. router_get_advertised_or_port(const or_options_t *options)
  1159. {
  1160. int port = get_primary_or_port();
  1161. (void)options;
  1162. /* If the port is in 'auto' mode, we have to use
  1163. router_get_listener_port_by_type(). */
  1164. if (port == CFG_AUTO_PORT)
  1165. return router_get_active_listener_port_by_type(CONN_TYPE_OR_LISTENER);
  1166. return port;
  1167. }
  1168. /** Return the port that we should advertise as our DirPort;
  1169. * this is one of three possibilities:
  1170. * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
  1171. * the one configured in the DirPort option,
  1172. * or the one we actually bound to if DirPort is "auto". */
  1173. uint16_t
  1174. router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
  1175. {
  1176. int dirport_configured = get_primary_dir_port();
  1177. (void)options;
  1178. if (!dirport_configured)
  1179. return dirport;
  1180. if (dirport_configured == CFG_AUTO_PORT)
  1181. return router_get_active_listener_port_by_type(CONN_TYPE_DIR_LISTENER);
  1182. return dirport_configured;
  1183. }
  1184. /*
  1185. * OR descriptor generation.
  1186. */
  1187. /** My routerinfo. */
  1188. static routerinfo_t *desc_routerinfo = NULL;
  1189. /** My extrainfo */
  1190. static extrainfo_t *desc_extrainfo = NULL;
  1191. /** Why did we most recently decide to regenerate our descriptor? Used to
  1192. * tell the authorities why we're sending it to them. */
  1193. static const char *desc_gen_reason = NULL;
  1194. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  1195. * now. */
  1196. static time_t desc_clean_since = 0;
  1197. /** Why did we mark the descriptor dirty? */
  1198. static const char *desc_dirty_reason = NULL;
  1199. /** Boolean: do we need to regenerate the above? */
  1200. static int desc_needs_upload = 0;
  1201. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  1202. * descriptor successfully yet, try to upload our signed descriptor to
  1203. * all the directory servers we know about.
  1204. */
  1205. void
  1206. router_upload_dir_desc_to_dirservers(int force)
  1207. {
  1208. const routerinfo_t *ri;
  1209. extrainfo_t *ei;
  1210. char *msg;
  1211. size_t desc_len, extra_len = 0, total_len;
  1212. dirinfo_type_t auth = get_options()->_PublishServerDescriptor;
  1213. ri = router_get_my_routerinfo();
  1214. if (!ri) {
  1215. log_info(LD_GENERAL, "No descriptor; skipping upload");
  1216. return;
  1217. }
  1218. ei = router_get_my_extrainfo();
  1219. if (auth == NO_DIRINFO)
  1220. return;
  1221. if (!force && !desc_needs_upload)
  1222. return;
  1223. log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
  1224. force ? " (forced)" : "");
  1225. desc_needs_upload = 0;
  1226. desc_len = ri->cache_info.signed_descriptor_len;
  1227. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  1228. total_len = desc_len + extra_len + 1;
  1229. msg = tor_malloc(total_len);
  1230. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  1231. if (ei) {
  1232. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  1233. }
  1234. msg[desc_len+extra_len] = 0;
  1235. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  1236. (auth & BRIDGE_DIRINFO) ?
  1237. ROUTER_PURPOSE_BRIDGE :
  1238. ROUTER_PURPOSE_GENERAL,
  1239. auth, msg, desc_len, extra_len);
  1240. tor_free(msg);
  1241. }
  1242. /** OR only: Check whether my exit policy says to allow connection to
  1243. * conn. Return 0 if we accept; non-0 if we reject.
  1244. */
  1245. int
  1246. router_compare_to_my_exit_policy(edge_connection_t *conn)
  1247. {
  1248. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  1249. return -1;
  1250. /* make sure it's resolved to something. this way we can't get a
  1251. 'maybe' below. */
  1252. if (tor_addr_is_null(&conn->_base.addr))
  1253. return -1;
  1254. /* XXXX IPv6 */
  1255. if (tor_addr_family(&conn->_base.addr) != AF_INET)
  1256. return -1;
  1257. return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
  1258. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  1259. }
  1260. /** Return true iff my exit policy is reject *:*. Return -1 if we don't
  1261. * have a descriptor */
  1262. int
  1263. router_my_exit_policy_is_reject_star(void)
  1264. {
  1265. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  1266. return -1;
  1267. return desc_routerinfo->policy_is_reject_star;
  1268. }
  1269. /** Return true iff I'm a server and <b>digest</b> is equal to
  1270. * my server identity key digest. */
  1271. int
  1272. router_digest_is_me(const char *digest)
  1273. {
  1274. return (server_identitykey &&
  1275. tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
  1276. }
  1277. /** Return true iff I'm a server and <b>digest</b> is equal to
  1278. * my identity digest. */
  1279. int
  1280. router_extrainfo_digest_is_me(const char *digest)
  1281. {
  1282. extrainfo_t *ei = router_get_my_extrainfo();
  1283. if (!ei)
  1284. return 0;
  1285. return tor_memeq(digest,
  1286. ei->cache_info.signed_descriptor_digest,
  1287. DIGEST_LEN);
  1288. }
  1289. /** A wrapper around router_digest_is_me(). */
  1290. int
  1291. router_is_me(const routerinfo_t *router)
  1292. {
  1293. return router_digest_is_me(router->cache_info.identity_digest);
  1294. }
  1295. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  1296. int
  1297. router_fingerprint_is_me(const char *fp)
  1298. {
  1299. char digest[DIGEST_LEN];
  1300. if (strlen(fp) == HEX_DIGEST_LEN &&
  1301. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  1302. return router_digest_is_me(digest);
  1303. return 0;
  1304. }
  1305. /** Return a routerinfo for this OR, rebuilding a fresh one if
  1306. * necessary. Return NULL on error, or if called on an OP. */
  1307. const routerinfo_t *
  1308. router_get_my_routerinfo(void)
  1309. {
  1310. if (!server_mode(get_options()))
  1311. return NULL;
  1312. if (router_rebuild_descriptor(0))
  1313. return NULL;
  1314. return desc_routerinfo;
  1315. }
  1316. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  1317. * one if necessary. Return NULL on error.
  1318. */
  1319. const char *
  1320. router_get_my_descriptor(void)
  1321. {
  1322. const char *body;
  1323. if (!router_get_my_routerinfo())
  1324. return NULL;
  1325. /* Make sure this is nul-terminated. */
  1326. tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
  1327. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  1328. tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
  1329. log_debug(LD_GENERAL,"my desc is '%s'", body);
  1330. return body;
  1331. }
  1332. /** Return the extrainfo document for this OR, or NULL if we have none.
  1333. * Rebuilt it (and the server descriptor) if necessary. */
  1334. extrainfo_t *
  1335. router_get_my_extrainfo(void)
  1336. {
  1337. if (!server_mode(get_options()))
  1338. return NULL;
  1339. if (router_rebuild_descriptor(0))
  1340. return NULL;
  1341. return desc_extrainfo;
  1342. }
  1343. /** Return a human-readable string describing what triggered us to generate
  1344. * our current descriptor, or NULL if we don't know. */
  1345. const char *
  1346. router_get_descriptor_gen_reason(void)
  1347. {
  1348. return desc_gen_reason;
  1349. }
  1350. /** A list of nicknames that we've warned about including in our family
  1351. * declaration verbatim rather than as digests. */
  1352. static smartlist_t *warned_nonexistent_family = NULL;
  1353. static int router_guess_address_from_dir_headers(uint32_t *guess);
  1354. /** Make a current best guess at our address, either because
  1355. * it's configured in torrc, or because we've learned it from
  1356. * dirserver headers. Place the answer in *<b>addr</b> and return
  1357. * 0 on success, else return -1 if we have no guess. */
  1358. int
  1359. router_pick_published_address(const or_options_t *options, uint32_t *addr)
  1360. {
  1361. if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
  1362. log_info(LD_CONFIG, "Could not determine our address locally. "
  1363. "Checking if directory headers provide any hints.");
  1364. if (router_guess_address_from_dir_headers(addr) < 0) {
  1365. log_info(LD_CONFIG, "No hints from directory headers either. "
  1366. "Will try again later.");
  1367. return -1;
  1368. }
  1369. }
  1370. log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
  1371. return 0;
  1372. }
  1373. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
  1374. * routerinfo, signed server descriptor, and extra-info document for this OR.
  1375. * Return 0 on success, -1 on temporary error.
  1376. */
  1377. int
  1378. router_rebuild_descriptor(int force)
  1379. {
  1380. routerinfo_t *ri;
  1381. extrainfo_t *ei;
  1382. uint32_t addr;
  1383. char platform[256];
  1384. int hibernating = we_are_hibernating();
  1385. const or_options_t *options = get_options();
  1386. if (desc_clean_since && !force)
  1387. return 0;
  1388. if (router_pick_published_address(options, &addr) < 0 ||
  1389. router_get_advertised_or_port(options) == 0) {
  1390. /* Stop trying to rebuild our descriptor every second. We'll
  1391. * learn that it's time to try again when ip_address_changed()
  1392. * marks it dirty. */
  1393. desc_clean_since = time(NULL);
  1394. return -1;
  1395. }
  1396. log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
  1397. ri = tor_malloc_zero(sizeof(routerinfo_t));
  1398. ri->cache_info.routerlist_index = -1;
  1399. ri->address = tor_dup_ip(addr);
  1400. ri->nickname = tor_strdup(options->Nickname);
  1401. ri->addr = addr;
  1402. ri->or_port = router_get_advertised_or_port(options);
  1403. ri->dir_port = router_get_advertised_dir_port(options, 0);
  1404. ri->cache_info.published_on = time(NULL);
  1405. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  1406. * main thread */
  1407. if (options->BridgeRelay) {
  1408. /* For now, only bridges advertise an ipv6 or-address. And only one. */
  1409. const port_cfg_t *ipv6_orport = NULL;
  1410. SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
  1411. if (p->type == CONN_TYPE_OR_LISTENER &&
  1412. ! p->no_advertise &&
  1413. ! p->ipv4_only &&
  1414. tor_addr_family(&p->addr) == AF_INET6) {
  1415. if (! tor_addr_is_internal(&p->addr, 0)) {
  1416. ipv6_orport = p;
  1417. break;
  1418. } else {
  1419. char addrbuf[TOR_ADDR_BUF_LEN];
  1420. log_warn(LD_CONFIG,
  1421. "Unable to use configured IPv6 address \"%s\" in a "
  1422. "descriptor. Skipping it. "
  1423. "Try specifying a globally reachable address explicitly. ",
  1424. tor_addr_to_str(addrbuf, &p->addr, sizeof(addrbuf), 1));
  1425. }
  1426. }
  1427. } SMARTLIST_FOREACH_END(p);
  1428. if (ipv6_orport) {
  1429. tor_addr_copy(&ri->ipv6_addr, &ipv6_orport->addr);
  1430. ri->ipv6_orport = ipv6_orport->port;
  1431. }
  1432. }
  1433. ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
  1434. if (crypto_pk_get_digest(ri->identity_pkey,
  1435. ri->cache_info.identity_digest)<0) {
  1436. routerinfo_free(ri);
  1437. return -1;
  1438. }
  1439. get_platform_str(platform, sizeof(platform));
  1440. ri->platform = tor_strdup(platform);
  1441. /* compute ri->bandwidthrate as the min of various options */
  1442. ri->bandwidthrate = get_effective_bwrate(options);
  1443. /* and compute ri->bandwidthburst similarly */
  1444. ri->bandwidthburst = get_effective_bwburst(options);
  1445. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  1446. if (dns_seems_to_be_broken() || has_dns_init_failed()) {
  1447. /* DNS is screwed up; don't claim to be an exit. */
  1448. policies_exit_policy_append_reject_star(&ri->exit_policy);
  1449. } else {
  1450. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  1451. options->ExitPolicyRejectPrivate,
  1452. ri->address, !options->BridgeRelay);
  1453. }
  1454. ri->policy_is_reject_star =
  1455. policy_is_reject_star(ri->exit_policy);
  1456. #if 0
  1457. /* XXXX NM NM I belive this is safe to remove */
  1458. if (authdir_mode(options))
  1459. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  1460. #endif
  1461. if (options->MyFamily) {
  1462. smartlist_t *family;
  1463. if (!warned_nonexistent_family)
  1464. warned_nonexistent_family = smartlist_new();
  1465. family = smartlist_new();
  1466. ri->declared_family = smartlist_new();
  1467. smartlist_split_string(family, options->MyFamily, ",",
  1468. SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1469. SMARTLIST_FOREACH_BEGIN(family, char *, name) {
  1470. const node_t *member;
  1471. if (!strcasecmp(name, options->Nickname))
  1472. goto skip; /* Don't list ourself, that's redundant */
  1473. else
  1474. member = node_get_by_nickname(name, 1);
  1475. if (!member) {
  1476. int is_legal = is_legal_nickname_or_hexdigest(name);
  1477. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  1478. !is_legal_hexdigest(name)) {
  1479. if (is_legal)
  1480. log_warn(LD_CONFIG,
  1481. "I have no descriptor for the router named \"%s\" in my "
  1482. "declared family; I'll use the nickname as is, but "
  1483. "this may confuse clients.", name);
  1484. else
  1485. log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
  1486. "declared family, but that isn't a legal nickname. "
  1487. "Skipping it.", escaped(name));
  1488. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  1489. }
  1490. if (is_legal) {
  1491. smartlist_add(ri->declared_family, name);
  1492. name = NULL;
  1493. }
  1494. } else if (router_digest_is_me(member->identity)) {
  1495. /* Don't list ourself in our own family; that's redundant */
  1496. /* XXX shouldn't be possible */
  1497. } else {
  1498. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  1499. fp[0] = '$';
  1500. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  1501. member->identity, DIGEST_LEN);
  1502. smartlist_add(ri->declared_family, fp);
  1503. if (smartlist_string_isin(warned_nonexistent_family, name))
  1504. smartlist_string_remove(warned_nonexistent_family, name);
  1505. }
  1506. skip:
  1507. tor_free(name);
  1508. } SMARTLIST_FOREACH_END(name);
  1509. /* remove duplicates from the list */
  1510. smartlist_sort_strings(ri->declared_family);
  1511. smartlist_uniq_strings(ri->declared_family);
  1512. smartlist_free(family);
  1513. }
  1514. /* Now generate the extrainfo. */
  1515. ei = tor_malloc_zero(sizeof(extrainfo_t));
  1516. ei->cache_info.is_extrainfo = 1;
  1517. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  1518. ei->cache_info.published_on = ri->cache_info.published_on;
  1519. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  1520. DIGEST_LEN);
  1521. if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
  1522. ei, get_server_identity_key()) < 0) {
  1523. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  1524. extrainfo_free(ei);
  1525. ei = NULL;
  1526. } else {
  1527. ei->cache_info.signed_descriptor_len =
  1528. strlen(ei->cache_info.signed_descriptor_body);
  1529. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  1530. ei->cache_info.signed_descriptor_len,
  1531. ei->cache_info.signed_descriptor_digest);
  1532. }
  1533. /* Now finish the router descriptor. */
  1534. if (ei) {
  1535. memcpy(ri->cache_info.extra_info_digest,
  1536. ei->cache_info.signed_descriptor_digest,
  1537. DIGEST_LEN);
  1538. } else {
  1539. /* ri was allocated with tor_malloc_zero, so there is no need to
  1540. * zero ri->cache_info.extra_info_digest here. */
  1541. }
  1542. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  1543. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  1544. ri, get_server_identity_key()) < 0) {
  1545. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  1546. routerinfo_free(ri);
  1547. extrainfo_free(ei);
  1548. return -1;
  1549. }
  1550. ri->cache_info.signed_descriptor_len =
  1551. strlen(ri->cache_info.signed_descriptor_body);
  1552. ri->purpose =
  1553. options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  1554. if (options->BridgeRelay) {
  1555. /* Bridges shouldn't be able to send their descriptors unencrypted,
  1556. anyway, since they don't have a DirPort, and always connect to the
  1557. bridge authority anonymously. But just in case they somehow think of
  1558. sending them on an unencrypted connection, don't allow them to try. */
  1559. ri->cache_info.send_unencrypted = ei->cache_info.send_unencrypted = 0;
  1560. } else {
  1561. ri->cache_info.send_unencrypted = ei->cache_info.send_unencrypted = 1;
  1562. }
  1563. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  1564. strlen(ri->cache_info.signed_descriptor_body),
  1565. ri->cache_info.signed_descriptor_digest);
  1566. if (ei) {
  1567. tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
  1568. }
  1569. routerinfo_free(desc_routerinfo);
  1570. desc_routerinfo = ri;
  1571. extrainfo_free(desc_extrainfo);
  1572. desc_extrainfo = ei;
  1573. desc_clean_since = time(NULL);
  1574. desc_needs_upload = 1;
  1575. desc_gen_reason = desc_dirty_reason;
  1576. desc_dirty_reason = NULL;
  1577. control_event_my_descriptor_changed();
  1578. return 0;
  1579. }
  1580. /** If our router descriptor ever goes this long without being regenerated
  1581. * because something changed, we force an immediate regenerate-and-upload. */
  1582. #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
  1583. /** If our router descriptor seems to be missing or unacceptable according
  1584. * to the authorities, regenerate and reupload it _this_ often. */
  1585. #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
  1586. /** Mark descriptor out of date if it's been "too long" since we last tried
  1587. * to upload one. */
  1588. void
  1589. mark_my_descriptor_dirty_if_too_old(time_t now)
  1590. {
  1591. networkstatus_t *ns;
  1592. const routerstatus_t *rs;
  1593. const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
  1594. const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
  1595. const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
  1596. /* If it's already dirty, don't mark it. */
  1597. if (! desc_clean_since)
  1598. return;
  1599. /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
  1600. * time to rebuild it. */
  1601. if (desc_clean_since < slow_cutoff) {
  1602. mark_my_descriptor_dirty("time for new descriptor");
  1603. return;
  1604. }
  1605. /* Now we see whether we want to be retrying frequently or no. The
  1606. * rule here is that we'll retry frequently if we aren't listed in the
  1607. * live consensus we have, or if the publication time of the
  1608. * descriptor listed for us in the consensus is very old. */
  1609. ns = networkstatus_get_live_consensus(now);
  1610. if (ns) {
  1611. rs = networkstatus_vote_find_entry(ns, server_identitykey_digest);
  1612. if (rs == NULL)
  1613. retry_fast_reason = "not listed in consensus";
  1614. else if (rs->published_on < slow_cutoff)
  1615. retry_fast_reason = "version listed in consensus is quite old";
  1616. }
  1617. if (retry_fast_reason && desc_clean_since < fast_cutoff)
  1618. mark_my_descriptor_dirty(retry_fast_reason);
  1619. }
  1620. /** Call when the current descriptor is out of date. */
  1621. void
  1622. mark_my_descriptor_dirty(const char *reason)
  1623. {
  1624. const or_options_t *options = get_options();
  1625. if (server_mode(options) && options->_PublishServerDescriptor)
  1626. log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
  1627. desc_clean_since = 0;
  1628. if (!desc_dirty_reason)
  1629. desc_dirty_reason = reason;
  1630. }
  1631. /** How frequently will we republish our descriptor because of large (factor
  1632. * of 2) shifts in estimated bandwidth? */
  1633. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  1634. /** Check whether bandwidth has changed a lot since the last time we announced
  1635. * bandwidth. If so, mark our descriptor dirty. */
  1636. void
  1637. check_descriptor_bandwidth_changed(time_t now)
  1638. {
  1639. static time_t last_changed = 0;
  1640. uint64_t prev, cur;
  1641. if (!desc_routerinfo)
  1642. return;
  1643. prev = desc_routerinfo->bandwidthcapacity;
  1644. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  1645. if ((prev != cur && (!prev || !cur)) ||
  1646. cur > prev*2 ||
  1647. cur < prev/2) {
  1648. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  1649. log_info(LD_GENERAL,
  1650. "Measured bandwidth has changed; rebuilding descriptor.");
  1651. mark_my_descriptor_dirty("bandwidth has changed");
  1652. last_changed = now;
  1653. }
  1654. }
  1655. }
  1656. /** Note at log level severity that our best guess of address has changed from
  1657. * <b>prev</b> to <b>cur</b>. */
  1658. static void
  1659. log_addr_has_changed(int severity,
  1660. const tor_addr_t *prev,
  1661. const tor_addr_t *cur,
  1662. const char *source)
  1663. {
  1664. char addrbuf_prev[TOR_ADDR_BUF_LEN];
  1665. char addrbuf_cur[TOR_ADDR_BUF_LEN];
  1666. if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
  1667. strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
  1668. if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
  1669. strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
  1670. if (!tor_addr_is_null(prev))
  1671. log_fn(severity, LD_GENERAL,
  1672. "Our IP Address has changed from %s to %s; "
  1673. "rebuilding descriptor (source: %s).",
  1674. addrbuf_prev, addrbuf_cur, source);
  1675. else
  1676. log_notice(LD_GENERAL,
  1677. "Guessed our IP address as %s (source: %s).",
  1678. addrbuf_cur, source);
  1679. }
  1680. /** Check whether our own address as defined by the Address configuration
  1681. * has changed. This is for routers that get their address from a service
  1682. * like dyndns. If our address has changed, mark our descriptor dirty. */
  1683. void
  1684. check_descriptor_ipaddress_changed(time_t now)
  1685. {
  1686. uint32_t prev, cur;
  1687. const or_options_t *options = get_options();
  1688. (void) now;
  1689. if (!desc_routerinfo)
  1690. return;
  1691. /* XXXX ipv6 */
  1692. prev = desc_routerinfo->addr;
  1693. if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
  1694. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  1695. return;
  1696. }
  1697. if (prev != cur) {
  1698. tor_addr_t tmp_prev, tmp_cur;
  1699. tor_addr_from_ipv4h(&tmp_prev, prev);
  1700. tor_addr_from_ipv4h(&tmp_cur, cur);
  1701. log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, "resolve");
  1702. ip_address_changed(0);
  1703. }
  1704. }
  1705. /** The most recently guessed value of our IP address, based on directory
  1706. * headers. */
  1707. static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
  1708. /** A directory server <b>d_conn</b> told us our IP address is
  1709. * <b>suggestion</b>.
  1710. * If this address is different from the one we think we are now, and
  1711. * if our computer doesn't actually know its IP address, then switch. */
  1712. void
  1713. router_new_address_suggestion(const char *suggestion,
  1714. const dir_connection_t *d_conn)
  1715. {
  1716. tor_addr_t addr;
  1717. uint32_t cur = 0; /* Current IPv4 address. */
  1718. const or_options_t *options = get_options();
  1719. /* first, learn what the IP address actually is */
  1720. if (tor_addr_parse(&addr, suggestion) == -1) {
  1721. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  1722. escaped(suggestion));
  1723. return;
  1724. }
  1725. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  1726. if (!server_mode(options)) {
  1727. tor_addr_copy(&last_guessed_ip, &addr);
  1728. return;
  1729. }
  1730. /* XXXX ipv6 */
  1731. if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
  1732. /* We're all set -- we already know our address. Great. */
  1733. tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
  1734. need it later */
  1735. return;
  1736. }
  1737. if (tor_addr_is_internal(&addr, 0)) {
  1738. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  1739. return;
  1740. }
  1741. if (tor_addr_eq(&d_conn->_base.addr, &addr)) {
  1742. /* Don't believe anybody who says our IP is their IP. */
  1743. log_debug(LD_DIR, "A directory server told us our IP address is %s, "
  1744. "but he's just reporting his own IP address. Ignoring.",
  1745. suggestion);
  1746. return;
  1747. }
  1748. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  1749. * us an answer different from what we had the last time we managed to
  1750. * resolve it. */
  1751. if (!tor_addr_eq(&last_guessed_ip, &addr)) {
  1752. control_event_server_status(LOG_NOTICE,
  1753. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  1754. suggestion);
  1755. log_addr_has_changed(LOG_NOTICE, &last_guessed_ip, &addr,
  1756. d_conn->_base.address);
  1757. ip_address_changed(0);
  1758. tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
  1759. will fetch it */
  1760. }
  1761. }
  1762. /** We failed to resolve our address locally, but we'd like to build
  1763. * a descriptor and publish / test reachability. If we have a guess
  1764. * about our address based on directory headers, answer it and return
  1765. * 0; else return -1. */
  1766. static int
  1767. router_guess_address_from_dir_headers(uint32_t *guess)
  1768. {
  1769. if (!tor_addr_is_null(&last_guessed_ip)) {
  1770. *guess = tor_addr_to_ipv4h(&last_guessed_ip);
  1771. return 0;
  1772. }
  1773. return -1;
  1774. }
  1775. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  1776. * string describing the version of Tor and the operating system we're
  1777. * currently running on.
  1778. */
  1779. void
  1780. get_platform_str(char *platform, size_t len)
  1781. {
  1782. tor_snprintf(platform, len, "Tor %s on %s", get_short_version(), get_uname());
  1783. }
  1784. /* XXX need to audit this thing and count fenceposts. maybe
  1785. * refactor so we don't have to keep asking if we're
  1786. * near the end of maxlen?
  1787. */
  1788. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1789. /** OR only: Given a routerinfo for this router, and an identity key to sign
  1790. * with, encode the routerinfo as a signed server descriptor and write the
  1791. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  1792. * failure, and the number of bytes used on success.
  1793. */
  1794. int
  1795. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  1796. crypto_pk_t *ident_key)
  1797. {
  1798. char *onion_pkey; /* Onion key, PEM-encoded. */
  1799. char *identity_pkey; /* Identity key, PEM-encoded. */
  1800. char digest[DIGEST_LEN];
  1801. char published[ISO_TIME_LEN+1];
  1802. char fingerprint[FINGERPRINT_LEN+1];
  1803. int has_extra_info_digest;
  1804. char extra_info_digest[HEX_DIGEST_LEN+1];
  1805. size_t onion_pkeylen, identity_pkeylen;
  1806. size_t written;
  1807. int result=0;
  1808. addr_policy_t *tmpe;
  1809. char *family_line;
  1810. char *extra_or_address = NULL;
  1811. const or_options_t *options = get_options();
  1812. /* Make sure the identity key matches the one in the routerinfo. */
  1813. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  1814. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  1815. "match router's public key!");
  1816. return -1;
  1817. }
  1818. /* record our fingerprint, so we can include it in the descriptor */
  1819. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  1820. log_err(LD_BUG,"Error computing fingerprint");
  1821. return -1;
  1822. }
  1823. /* PEM-encode the onion key */
  1824. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  1825. &onion_pkey,&onion_pkeylen)<0) {
  1826. log_warn(LD_BUG,"write onion_pkey to string failed!");
  1827. return -1;
  1828. }
  1829. /* PEM-encode the identity key */
  1830. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  1831. &identity_pkey,&identity_pkeylen)<0) {
  1832. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1833. tor_free(onion_pkey);
  1834. return -1;
  1835. }
  1836. /* Encode the publication time. */
  1837. format_iso_time(published, router->cache_info.published_on);
  1838. if (router->declared_family && smartlist_len(router->declared_family)) {
  1839. char *family = smartlist_join_strings(router->declared_family,
  1840. " ", 0, NULL);
  1841. tor_asprintf(&family_line, "family %s\n", family);
  1842. tor_free(family);
  1843. } else {
  1844. family_line = tor_strdup("");
  1845. }
  1846. has_extra_info_digest =
  1847. ! tor_digest_is_zero(router->cache_info.extra_info_digest);
  1848. if (has_extra_info_digest) {
  1849. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  1850. router->cache_info.extra_info_digest, DIGEST_LEN);
  1851. }
  1852. if (router->ipv6_orport &&
  1853. tor_addr_family(&router->ipv6_addr) == AF_INET6) {
  1854. char addr[TOR_ADDR_BUF_LEN];
  1855. const char *a;
  1856. a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
  1857. if (a) {
  1858. tor_asprintf(&extra_or_address,
  1859. "or-address %s:%d\n", a, router->ipv6_orport);
  1860. log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
  1861. }
  1862. }
  1863. /* Generate the easy portion of the router descriptor. */
  1864. result = tor_snprintf(s, maxlen,
  1865. "router %s %s %d 0 %d\n"
  1866. "%s"
  1867. "platform %s\n"
  1868. "opt protocols Link 1 2 Circuit 1\n"
  1869. "published %s\n"
  1870. "opt fingerprint %s\n"
  1871. "uptime %ld\n"
  1872. "bandwidth %d %d %d\n"
  1873. "%s%s%s%s"
  1874. "onion-key\n%s"
  1875. "signing-key\n%s"
  1876. "%s%s%s%s",
  1877. router->nickname,
  1878. router->address,
  1879. router->or_port,
  1880. decide_to_advertise_dirport(options, router->dir_port),
  1881. extra_or_address ? extra_or_address : "",
  1882. router->platform,
  1883. published,
  1884. fingerprint,
  1885. stats_n_seconds_working,
  1886. (int) router->bandwidthrate,
  1887. (int) router->bandwidthburst,
  1888. (int) router->bandwidthcapacity,
  1889. has_extra_info_digest ? "opt extra-info-digest " : "",
  1890. has_extra_info_digest ? extra_info_digest : "",
  1891. has_extra_info_digest ? "\n" : "",
  1892. options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
  1893. onion_pkey, identity_pkey,
  1894. family_line,
  1895. we_are_hibernating() ? "opt hibernating 1\n" : "",
  1896. options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
  1897. options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
  1898. tor_free(family_line);
  1899. tor_free(onion_pkey);
  1900. tor_free(identity_pkey);
  1901. tor_free(extra_or_address);
  1902. if (result < 0) {
  1903. log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
  1904. return -1;
  1905. }
  1906. /* From now on, we use 'written' to remember the current length of 's'. */
  1907. written = result;
  1908. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1909. const char *ci = options->ContactInfo;
  1910. if (strchr(ci, '\n') || strchr(ci, '\r'))
  1911. ci = escaped(ci);
  1912. result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
  1913. if (result<0) {
  1914. log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
  1915. return -1;
  1916. }
  1917. written += result;
  1918. }
  1919. /* Write the exit policy to the end of 's'. */
  1920. if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
  1921. strlcat(s+written, "reject *:*\n", maxlen-written);
  1922. written += strlen("reject *:*\n");
  1923. tmpe = NULL;
  1924. } else if (router->exit_policy) {
  1925. int i;
  1926. for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
  1927. tmpe = smartlist_get(router->exit_policy, i);
  1928. result = policy_write_item(s+written, maxlen-written, tmpe, 1);
  1929. if (result < 0) {
  1930. log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
  1931. return -1;
  1932. }
  1933. tor_assert(result == (int)strlen(s+written));
  1934. written += result;
  1935. if (written+2 > maxlen) {
  1936. log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
  1937. return -1;
  1938. }
  1939. s[written++] = '\n';
  1940. }
  1941. }
  1942. if (written + DIROBJ_MAX_SIG_LEN > maxlen) {
  1943. /* Not enough room for signature. */
  1944. log_warn(LD_BUG,"not enough room left in descriptor for signature!");
  1945. return -1;
  1946. }
  1947. /* Sign the descriptor */
  1948. strlcpy(s+written, "router-signature\n", maxlen-written);
  1949. written += strlen(s+written);
  1950. s[written] = '\0';
  1951. if (router_get_router_hash(s, strlen(s), digest) < 0) {
  1952. return -1;
  1953. }
  1954. note_crypto_pk_op(SIGN_RTR);
  1955. if (router_append_dirobj_signature(s+written,maxlen-written,
  1956. digest,DIGEST_LEN,ident_key)<0) {
  1957. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1958. return -1;
  1959. }
  1960. written += strlen(s+written);
  1961. if (written+2 > maxlen) {
  1962. log_warn(LD_BUG,"Not enough room to finish descriptor.");
  1963. return -1;
  1964. }
  1965. /* include a last '\n' */
  1966. s[written] = '\n';
  1967. s[written+1] = 0;
  1968. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1969. {
  1970. char *s_dup;
  1971. const char *cp;
  1972. routerinfo_t *ri_tmp;
  1973. cp = s_dup = tor_strdup(s);
  1974. ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
  1975. if (!ri_tmp) {
  1976. log_err(LD_BUG,
  1977. "We just generated a router descriptor we can't parse.");
  1978. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1979. return -1;
  1980. }
  1981. tor_free(s_dup);
  1982. routerinfo_free(ri_tmp);
  1983. }
  1984. #endif
  1985. return (int)written+1;
  1986. }
  1987. /** Copy the primary (IPv4) OR port (IP address and TCP port) for
  1988. * <b>router</b> into *<b>ap_out</b>. */
  1989. void
  1990. router_get_prim_orport(const routerinfo_t *router, tor_addr_port_t *ap_out)
  1991. {
  1992. tor_assert(ap_out != NULL);
  1993. tor_addr_from_ipv4h(&ap_out->addr, router->addr);
  1994. ap_out->port = router->or_port;
  1995. }
  1996. /** Return 1 if we prefer the IPv6 address and OR TCP port of
  1997. * <b>router</b>, else 0.
  1998. *
  1999. * We prefer the IPv6 address if the router has one and
  2000. * i) the routerinfo_t says so
  2001. * or
  2002. * ii) the router has no IPv4 address. */
  2003. int
  2004. router_ipv6_preferred(const routerinfo_t *router)
  2005. {
  2006. return (!tor_addr_is_null(&router->ipv6_addr)
  2007. && (router->ipv6_preferred || router->addr == 0));
  2008. }
  2009. /** Copy the preferred OR port (IP address and TCP port) for
  2010. * <b>router</b> into *<b>addr_out</b>. */
  2011. void
  2012. router_get_pref_orport(const routerinfo_t *router, tor_addr_port_t *ap_out)
  2013. {
  2014. if (router_ipv6_preferred(router))
  2015. router_get_pref_ipv6_orport(router, ap_out);
  2016. else
  2017. router_get_prim_orport(router, ap_out);
  2018. }
  2019. /** Copy the preferred IPv6 OR port (IP address and TCP port) for
  2020. * <b>router</b> into *<b>ap_out</b>. */
  2021. void
  2022. router_get_pref_ipv6_orport(const routerinfo_t *router,
  2023. tor_addr_port_t *ap_out)
  2024. {
  2025. tor_assert(ap_out != NULL);
  2026. tor_addr_copy(&ap_out->addr, &router->ipv6_addr);
  2027. ap_out->port = router->ipv6_orport;
  2028. }
  2029. /** Load the contents of <b>filename</b>, find the last line starting with
  2030. * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
  2031. * the past or more than 1 hour in the future with respect to <b>now</b>,
  2032. * and write the file contents starting with that line to *<b>out</b>.
  2033. * Return 1 for success, 0 if the file does not exist, or -1 if the file
  2034. * does not contain a line matching these criteria or other failure. */
  2035. static int
  2036. load_stats_file(const char *filename, const char *end_line, time_t now,
  2037. char **out)
  2038. {
  2039. int r = -1;
  2040. char *fname = get_datadir_fname(filename);
  2041. char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
  2042. time_t written;
  2043. switch (file_status(fname)) {
  2044. case FN_FILE:
  2045. /* X022 Find an alternative to reading the whole file to memory. */
  2046. if ((contents = read_file_to_str(fname, 0, NULL))) {
  2047. tmp = strstr(contents, end_line);
  2048. /* Find last block starting with end_line */
  2049. while (tmp) {
  2050. start = tmp;
  2051. tmp = strstr(tmp + 1, end_line);
  2052. }
  2053. if (!start)
  2054. goto notfound;
  2055. if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
  2056. goto notfound;
  2057. strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
  2058. if (parse_iso_time(timestr, &written) < 0)
  2059. goto notfound;
  2060. if (written < now - (25*60*60) || written > now + (1*60*60))
  2061. goto notfound;
  2062. *out = tor_strdup(start);
  2063. r = 1;
  2064. }
  2065. notfound:
  2066. tor_free(contents);
  2067. break;
  2068. case FN_NOENT:
  2069. r = 0;
  2070. break;
  2071. case FN_ERROR:
  2072. case FN_DIR:
  2073. default:
  2074. break;
  2075. }
  2076. tor_free(fname);
  2077. return r;
  2078. }
  2079. /** Write the contents of <b>extrainfo</b> and aggregated statistics to
  2080. * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
  2081. * success, negative on failure. */
  2082. int
  2083. extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
  2084. crypto_pk_t *ident_key)
  2085. {
  2086. const or_options_t *options = get_options();
  2087. char identity[HEX_DIGEST_LEN+1];
  2088. char published[ISO_TIME_LEN+1];
  2089. char digest[DIGEST_LEN];
  2090. char *bandwidth_usage;
  2091. int result;
  2092. static int write_stats_to_extrainfo = 1;
  2093. char sig[DIROBJ_MAX_SIG_LEN+1];
  2094. char *s, *pre, *contents, *cp, *s_dup = NULL;
  2095. time_t now = time(NULL);
  2096. smartlist_t *chunks = smartlist_new();
  2097. extrainfo_t *ei_tmp = NULL;
  2098. base16_encode(identity, sizeof(identity),
  2099. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  2100. format_iso_time(published, extrainfo->cache_info.published_on);
  2101. bandwidth_usage = rep_hist_get_bandwidth_lines();
  2102. tor_asprintf(&pre, "extra-info %s %s\npublished %s\n%s",
  2103. extrainfo->nickname, identity,
  2104. published, bandwidth_usage);
  2105. tor_free(bandwidth_usage);
  2106. smartlist_add(chunks, pre);
  2107. if (geoip_is_loaded()) {
  2108. smartlist_add_asprintf(chunks, "geoip-db-digest %s\n", geoip_db_digest());
  2109. }
  2110. if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
  2111. log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
  2112. if (options->DirReqStatistics &&
  2113. load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
  2114. "dirreq-stats-end", now, &contents) > 0) {
  2115. smartlist_add(chunks, contents);
  2116. }
  2117. if (options->EntryStatistics &&
  2118. load_stats_file("stats"PATH_SEPARATOR"entry-stats",
  2119. "entry-stats-end", now, &contents) > 0) {
  2120. smartlist_add(chunks, contents);
  2121. }
  2122. if (options->CellStatistics &&
  2123. load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
  2124. "cell-stats-end", now, &contents) > 0) {
  2125. smartlist_add(chunks, contents);
  2126. }
  2127. if (options->ExitPortStatistics &&
  2128. load_stats_file("stats"PATH_SEPARATOR"exit-stats",
  2129. "exit-stats-end", now, &contents) > 0) {
  2130. smartlist_add(chunks, contents);
  2131. }
  2132. if (options->ConnDirectionStatistics &&
  2133. load_stats_file("stats"PATH_SEPARATOR"conn-stats",
  2134. "conn-bi-direct", now, &contents) > 0) {
  2135. smartlist_add(chunks, contents);
  2136. }
  2137. }
  2138. if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
  2139. const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
  2140. if (bridge_stats) {
  2141. smartlist_add(chunks, tor_strdup(bridge_stats));
  2142. }
  2143. }
  2144. smartlist_add(chunks, tor_strdup("router-signature\n"));
  2145. s = smartlist_join_strings(chunks, "", 0, NULL);
  2146. while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
  2147. /* So long as there are at least two chunks (one for the initial
  2148. * extra-info line and one for the router-signature), we can keep removing
  2149. * things. */
  2150. if (smartlist_len(chunks) > 2) {
  2151. /* We remove the next-to-last element (remember, len-1 is the last
  2152. element), since we need to keep the router-signature element. */
  2153. int idx = smartlist_len(chunks) - 2;
  2154. char *e = smartlist_get(chunks, idx);
  2155. smartlist_del_keeporder(chunks, idx);
  2156. log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
  2157. "with statistics that exceeds the 50 KB "
  2158. "upload limit. Removing last added "
  2159. "statistics.");
  2160. tor_free(e);
  2161. tor_free(s);
  2162. s = smartlist_join_strings(chunks, "", 0, NULL);
  2163. } else {
  2164. log_warn(LD_BUG, "We just generated an extra-info descriptors that "
  2165. "exceeds the 50 KB upload limit.");
  2166. goto err;
  2167. }
  2168. }
  2169. memset(sig, 0, sizeof(sig));
  2170. if (router_get_extrainfo_hash(s, strlen(s), digest) < 0 ||
  2171. router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
  2172. ident_key) < 0) {
  2173. log_warn(LD_BUG, "Could not append signature to extra-info "
  2174. "descriptor.");
  2175. goto err;
  2176. }
  2177. smartlist_add(chunks, tor_strdup(sig));
  2178. tor_free(s);
  2179. s = smartlist_join_strings(chunks, "", 0, NULL);
  2180. cp = s_dup = tor_strdup(s);
  2181. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  2182. if (!ei_tmp) {
  2183. if (write_stats_to_extrainfo) {
  2184. log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
  2185. "with statistics that we can't parse. Not "
  2186. "adding statistics to this or any future "
  2187. "extra-info descriptors.");
  2188. write_stats_to_extrainfo = 0;
  2189. result = extrainfo_dump_to_string(s_out, extrainfo, ident_key);
  2190. goto done;
  2191. } else {
  2192. log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
  2193. "can't parse.");
  2194. goto err;
  2195. }
  2196. }
  2197. *s_out = s;
  2198. s = NULL; /* prevent free */
  2199. result = 0;
  2200. goto done;
  2201. err:
  2202. result = -1;
  2203. done:
  2204. tor_free(s);
  2205. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  2206. smartlist_free(chunks);
  2207. tor_free(s_dup);
  2208. extrainfo_free(ei_tmp);
  2209. return result;
  2210. }
  2211. /** Return true iff <b>s</b> is a legally valid server nickname. */
  2212. int
  2213. is_legal_nickname(const char *s)
  2214. {
  2215. size_t len;
  2216. tor_assert(s);
  2217. len = strlen(s);
  2218. return len > 0 && len <= MAX_NICKNAME_LEN &&
  2219. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  2220. }
  2221. /** Return true iff <b>s</b> is a legally valid server nickname or
  2222. * hex-encoded identity-key digest. */
  2223. int
  2224. is_legal_nickname_or_hexdigest(const char *s)
  2225. {
  2226. if (*s!='$')
  2227. return is_legal_nickname(s);
  2228. else
  2229. return is_legal_hexdigest(s);
  2230. }
  2231. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  2232. * digest. */
  2233. int
  2234. is_legal_hexdigest(const char *s)
  2235. {
  2236. size_t len;
  2237. tor_assert(s);
  2238. if (s[0] == '$') s++;
  2239. len = strlen(s);
  2240. if (len > HEX_DIGEST_LEN) {
  2241. if (s[HEX_DIGEST_LEN] == '=' ||
  2242. s[HEX_DIGEST_LEN] == '~') {
  2243. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  2244. return 0;
  2245. } else {
  2246. return 0;
  2247. }
  2248. }
  2249. return (len >= HEX_DIGEST_LEN &&
  2250. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  2251. }
  2252. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2253. * hold a human-readable description of a node with identity digest
  2254. * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
  2255. * and address <b>addr</b> or <b>addr32h</b>.
  2256. *
  2257. * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
  2258. * NULL. The <b>addr32h</b> field is optional and may be set to 0.
  2259. *
  2260. * Return a pointer to the front of <b>buf</b>.
  2261. */
  2262. const char *
  2263. format_node_description(char *buf,
  2264. const char *id_digest,
  2265. int is_named,
  2266. const char *nickname,
  2267. const tor_addr_t *addr,
  2268. uint32_t addr32h)
  2269. {
  2270. char *cp;
  2271. if (!buf)
  2272. return "<NULL BUFFER>";
  2273. buf[0] = '$';
  2274. base16_encode(buf+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
  2275. cp = buf+1+HEX_DIGEST_LEN;
  2276. if (nickname) {
  2277. buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
  2278. strlcpy(buf+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
  2279. cp += strlen(cp);
  2280. }
  2281. if (addr32h || addr) {
  2282. memcpy(cp, " at ", 4);
  2283. cp += 4;
  2284. if (addr) {
  2285. tor_addr_to_str(cp, addr, TOR_ADDR_BUF_LEN, 0);
  2286. } else {
  2287. struct in_addr in;
  2288. in.s_addr = htonl(addr32h);
  2289. tor_inet_ntoa(&in, cp, INET_NTOA_BUF_LEN);
  2290. }
  2291. }
  2292. return buf;
  2293. }
  2294. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2295. * hold a human-readable description of <b>ri</b>.
  2296. *
  2297. *
  2298. * Return a pointer to the front of <b>buf</b>.
  2299. */
  2300. const char *
  2301. router_get_description(char *buf, const routerinfo_t *ri)
  2302. {
  2303. if (!ri)
  2304. return "<null>";
  2305. return format_node_description(buf,
  2306. ri->cache_info.identity_digest,
  2307. router_is_named(ri),
  2308. ri->nickname,
  2309. NULL,
  2310. ri->addr);
  2311. }
  2312. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2313. * hold a human-readable description of <b>node</b>.
  2314. *
  2315. * Return a pointer to the front of <b>buf</b>.
  2316. */
  2317. const char *
  2318. node_get_description(char *buf, const node_t *node)
  2319. {
  2320. const char *nickname = NULL;
  2321. uint32_t addr32h = 0;
  2322. int is_named = 0;
  2323. if (!node)
  2324. return "<null>";
  2325. if (node->rs) {
  2326. nickname = node->rs->nickname;
  2327. is_named = node->rs->is_named;
  2328. addr32h = node->rs->addr;
  2329. } else if (node->ri) {
  2330. nickname = node->ri->nickname;
  2331. addr32h = node->ri->addr;
  2332. }
  2333. return format_node_description(buf,
  2334. node->identity,
  2335. is_named,
  2336. nickname,
  2337. NULL,
  2338. addr32h);
  2339. }
  2340. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2341. * hold a human-readable description of <b>rs</b>.
  2342. *
  2343. * Return a pointer to the front of <b>buf</b>.
  2344. */
  2345. const char *
  2346. routerstatus_get_description(char *buf, const routerstatus_t *rs)
  2347. {
  2348. if (!rs)
  2349. return "<null>";
  2350. return format_node_description(buf,
  2351. rs->identity_digest,
  2352. rs->is_named,
  2353. rs->nickname,
  2354. NULL,
  2355. rs->addr);
  2356. }
  2357. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2358. * hold a human-readable description of <b>ei</b>.
  2359. *
  2360. * Return a pointer to the front of <b>buf</b>.
  2361. */
  2362. const char *
  2363. extend_info_get_description(char *buf, const extend_info_t *ei)
  2364. {
  2365. if (!ei)
  2366. return "<null>";
  2367. return format_node_description(buf,
  2368. ei->identity_digest,
  2369. 0,
  2370. ei->nickname,
  2371. &ei->addr,
  2372. 0);
  2373. }
  2374. /** Return a human-readable description of the routerinfo_t <b>ri</b>.
  2375. *
  2376. * This function is not thread-safe. Each call to this function invalidates
  2377. * previous values returned by this function.
  2378. */
  2379. const char *
  2380. router_describe(const routerinfo_t *ri)
  2381. {
  2382. static char buf[NODE_DESC_BUF_LEN];
  2383. return router_get_description(buf, ri);
  2384. }
  2385. /** Return a human-readable description of the node_t <b>node</b>.
  2386. *
  2387. * This function is not thread-safe. Each call to this function invalidates
  2388. * previous values returned by this function.
  2389. */
  2390. const char *
  2391. node_describe(const node_t *node)
  2392. {
  2393. static char buf[NODE_DESC_BUF_LEN];
  2394. return node_get_description(buf, node);
  2395. }
  2396. /** Return a human-readable description of the routerstatus_t <b>rs</b>.
  2397. *
  2398. * This function is not thread-safe. Each call to this function invalidates
  2399. * previous values returned by this function.
  2400. */
  2401. const char *
  2402. routerstatus_describe(const routerstatus_t *rs)
  2403. {
  2404. static char buf[NODE_DESC_BUF_LEN];
  2405. return routerstatus_get_description(buf, rs);
  2406. }
  2407. /** Return a human-readable description of the extend_info_t <b>ri</b>.
  2408. *
  2409. * This function is not thread-safe. Each call to this function invalidates
  2410. * previous values returned by this function.
  2411. */
  2412. const char *
  2413. extend_info_describe(const extend_info_t *ei)
  2414. {
  2415. static char buf[NODE_DESC_BUF_LEN];
  2416. return extend_info_get_description(buf, ei);
  2417. }
  2418. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  2419. * verbose representation of the identity of <b>router</b>. The format is:
  2420. * A dollar sign.
  2421. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  2422. * A "=" if the router is named; a "~" if it is not.
  2423. * The router's nickname.
  2424. **/
  2425. void
  2426. router_get_verbose_nickname(char *buf, const routerinfo_t *router)
  2427. {
  2428. const char *good_digest = networkstatus_get_router_digest_by_nickname(
  2429. router->nickname);
  2430. int is_named = good_digest && tor_memeq(good_digest,
  2431. router->cache_info.identity_digest,
  2432. DIGEST_LEN);
  2433. buf[0] = '$';
  2434. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  2435. DIGEST_LEN);
  2436. buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
  2437. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  2438. }
  2439. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  2440. * verbose representation of the identity of <b>router</b>. The format is:
  2441. * A dollar sign.
  2442. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  2443. * A "=" if the router is named; a "~" if it is not.
  2444. * The router's nickname.
  2445. **/
  2446. void
  2447. routerstatus_get_verbose_nickname(char *buf, const routerstatus_t *router)
  2448. {
  2449. buf[0] = '$';
  2450. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->identity_digest,
  2451. DIGEST_LEN);
  2452. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  2453. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  2454. }
  2455. /** Forget that we have issued any router-related warnings, so that we'll
  2456. * warn again if we see the same errors. */
  2457. void
  2458. router_reset_warnings(void)
  2459. {
  2460. if (warned_nonexistent_family) {
  2461. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  2462. smartlist_clear(warned_nonexistent_family);
  2463. }
  2464. }
  2465. /** Given a router purpose, convert it to a string. Don't call this on
  2466. * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
  2467. * know its string representation. */
  2468. const char *
  2469. router_purpose_to_string(uint8_t p)
  2470. {
  2471. switch (p)
  2472. {
  2473. case ROUTER_PURPOSE_GENERAL: return "general";
  2474. case ROUTER_PURPOSE_BRIDGE: return "bridge";
  2475. case ROUTER_PURPOSE_CONTROLLER: return "controller";
  2476. default:
  2477. tor_assert(0);
  2478. }
  2479. return NULL;
  2480. }
  2481. /** Given a string, convert it to a router purpose. */
  2482. uint8_t
  2483. router_purpose_from_string(const char *s)
  2484. {
  2485. if (!strcmp(s, "general"))
  2486. return ROUTER_PURPOSE_GENERAL;
  2487. else if (!strcmp(s, "bridge"))
  2488. return ROUTER_PURPOSE_BRIDGE;
  2489. else if (!strcmp(s, "controller"))
  2490. return ROUTER_PURPOSE_CONTROLLER;
  2491. else
  2492. return ROUTER_PURPOSE_UNKNOWN;
  2493. }
  2494. /** Release all static resources held in router.c */
  2495. void
  2496. router_free_all(void)
  2497. {
  2498. crypto_pk_free(onionkey);
  2499. crypto_pk_free(lastonionkey);
  2500. crypto_pk_free(server_identitykey);
  2501. crypto_pk_free(client_identitykey);
  2502. tor_mutex_free(key_lock);
  2503. routerinfo_free(desc_routerinfo);
  2504. extrainfo_free(desc_extrainfo);
  2505. crypto_pk_free(authority_signing_key);
  2506. authority_cert_free(authority_key_certificate);
  2507. crypto_pk_free(legacy_signing_key);
  2508. authority_cert_free(legacy_key_certificate);
  2509. if (warned_nonexistent_family) {
  2510. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  2511. smartlist_free(warned_nonexistent_family);
  2512. }
  2513. }