router.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char router_c_id[] =
  7. "$Id$";
  8. #include "or.h"
  9. /**
  10. * \file router.c
  11. * \brief OR functionality, including key maintenance, generating
  12. * and uploading server descriptors, retrying OR connections.
  13. **/
  14. extern long stats_n_seconds_working;
  15. /* Exposed for test.c. */ void get_platform_str(char *platform, size_t len);
  16. /************************************************************/
  17. /*****
  18. * Key management: ORs only.
  19. *****/
  20. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  21. */
  22. static tor_mutex_t *key_lock=NULL;
  23. static time_t onionkey_set_at=0; /* When was onionkey last changed? */
  24. static crypto_pk_env_t *onionkey=NULL;
  25. static crypto_pk_env_t *lastonionkey=NULL;
  26. static crypto_pk_env_t *identitykey=NULL;
  27. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  28. * to update onionkey correctly, call rotate_onion_key().
  29. */
  30. void
  31. set_onion_key(crypto_pk_env_t *k)
  32. {
  33. tor_mutex_acquire(key_lock);
  34. onionkey = k;
  35. onionkey_set_at = time(NULL);
  36. tor_mutex_release(key_lock);
  37. mark_my_descriptor_dirty();
  38. }
  39. /** Return the current onion key. Requires that the onion key has been
  40. * loaded or generated. */
  41. crypto_pk_env_t *
  42. get_onion_key(void)
  43. {
  44. tor_assert(onionkey);
  45. return onionkey;
  46. }
  47. /** Store a copy of the current onion key into *<b>key</b>, and a copy
  48. * of the most recent onion key into *<b>last</b>.
  49. */
  50. void
  51. dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  52. {
  53. tor_assert(key);
  54. tor_assert(last);
  55. tor_mutex_acquire(key_lock);
  56. tor_assert(onionkey);
  57. *key = crypto_pk_dup_key(onionkey);
  58. if (lastonionkey)
  59. *last = crypto_pk_dup_key(lastonionkey);
  60. else
  61. *last = NULL;
  62. tor_mutex_release(key_lock);
  63. }
  64. /** Return the time when the onion key was last set. This is either the time
  65. * when the process launched, or the time of the most recent key rotation since
  66. * the process launched.
  67. */
  68. time_t
  69. get_onion_key_set_at(void)
  70. {
  71. return onionkey_set_at;
  72. }
  73. /** Set the current identity key to k.
  74. */
  75. void
  76. set_identity_key(crypto_pk_env_t *k)
  77. {
  78. if (identitykey)
  79. crypto_free_pk_env(identitykey);
  80. identitykey = k;
  81. }
  82. /** Returns the current identity key; requires that the identity key has been
  83. * set.
  84. */
  85. crypto_pk_env_t *
  86. get_identity_key(void)
  87. {
  88. tor_assert(identitykey);
  89. return identitykey;
  90. }
  91. /** Return true iff the identity key has been set. */
  92. int
  93. identity_key_is_set(void)
  94. {
  95. return identitykey != NULL;
  96. }
  97. /** Replace the previous onion key with the current onion key, and generate
  98. * a new previous onion key. Immediately after calling this function,
  99. * the OR should:
  100. * - schedule all previous cpuworkers to shut down _after_ processing
  101. * pending work. (This will cause fresh cpuworkers to be generated.)
  102. * - generate and upload a fresh routerinfo.
  103. */
  104. void
  105. rotate_onion_key(void)
  106. {
  107. char fname[512];
  108. char fname_prev[512];
  109. crypto_pk_env_t *prkey;
  110. tor_snprintf(fname,sizeof(fname),
  111. "%s/keys/secret_onion_key",get_options()->DataDirectory);
  112. tor_snprintf(fname_prev,sizeof(fname_prev),
  113. "%s/keys/secret_onion_key.old",get_options()->DataDirectory);
  114. if (!(prkey = crypto_new_pk_env())) {
  115. log_err(LD_GENERAL,"Error constructing rotated onion key");
  116. goto error;
  117. }
  118. if (crypto_pk_generate_key(prkey)) {
  119. log_err(LD_BUG,"Error generating onion key");
  120. goto error;
  121. }
  122. if (file_status(fname) == FN_FILE) {
  123. if (replace_file(fname, fname_prev))
  124. goto error;
  125. }
  126. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  127. log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
  128. goto error;
  129. }
  130. log_info(LD_GENERAL, "Rotating onion key");
  131. tor_mutex_acquire(key_lock);
  132. if (lastonionkey)
  133. crypto_free_pk_env(lastonionkey);
  134. lastonionkey = onionkey;
  135. onionkey = prkey;
  136. onionkey_set_at = time(NULL);
  137. tor_mutex_release(key_lock);
  138. mark_my_descriptor_dirty();
  139. return;
  140. error:
  141. log_warn(LD_GENERAL, "Couldn't rotate onion key.");
  142. }
  143. /* Read an RSA secret key key from a file that was once named fname_old,
  144. * but is now named fname_new. Rename the file from old to new as needed.
  145. */
  146. static crypto_pk_env_t *
  147. init_key_from_file_name_changed(const char *fname_old,
  148. const char *fname_new)
  149. {
  150. if (file_status(fname_new) == FN_FILE || file_status(fname_old) != FN_FILE)
  151. /* The new filename is there, or both are, or neither is. */
  152. return init_key_from_file(fname_new);
  153. /* The old filename exists, and the new one doesn't. Rename and load. */
  154. if (rename(fname_old, fname_new) < 0) {
  155. log_warn(LD_FS, "Couldn't rename key file \"%s\" to \"%s\": %s",
  156. fname_old, fname_new, strerror(errno));
  157. return NULL;
  158. }
  159. return init_key_from_file(fname_new);
  160. }
  161. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
  162. * create a new RSA key and save it in <b>fname</b>. Return the read/created
  163. * key, or NULL on error.
  164. */
  165. crypto_pk_env_t *
  166. init_key_from_file(const char *fname)
  167. {
  168. crypto_pk_env_t *prkey = NULL;
  169. FILE *file = NULL;
  170. if (!(prkey = crypto_new_pk_env())) {
  171. log_err(LD_GENERAL,"Error constructing key");
  172. goto error;
  173. }
  174. switch (file_status(fname)) {
  175. case FN_DIR:
  176. case FN_ERROR:
  177. log_err(LD_FS,"Can't read key from \"%s\"", fname);
  178. goto error;
  179. case FN_NOENT:
  180. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  181. fname);
  182. if (crypto_pk_generate_key(prkey)) {
  183. log_err(LD_GENERAL,"Error generating onion key");
  184. goto error;
  185. }
  186. if (crypto_pk_check_key(prkey) <= 0) {
  187. log_err(LD_GENERAL,"Generated key seems invalid");
  188. goto error;
  189. }
  190. log_info(LD_GENERAL, "Generated key seems valid");
  191. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  192. log_err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
  193. goto error;
  194. }
  195. return prkey;
  196. case FN_FILE:
  197. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  198. log_err(LD_GENERAL,"Error loading private key.");
  199. goto error;
  200. }
  201. return prkey;
  202. default:
  203. tor_assert(0);
  204. }
  205. error:
  206. if (prkey)
  207. crypto_free_pk_env(prkey);
  208. if (file)
  209. fclose(file);
  210. return NULL;
  211. }
  212. /** Initialize all OR private keys, and the TLS context, as necessary.
  213. * On OPs, this only initializes the tls context. Return 0 on success,
  214. * or -1 if Tor should die.
  215. */
  216. int
  217. init_keys(void)
  218. {
  219. char keydir[512];
  220. char keydir2[512];
  221. char fingerprint[FINGERPRINT_LEN+1];
  222. /*nickname<space>fp\n\0 */
  223. char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
  224. const char *mydesc, *datadir;
  225. crypto_pk_env_t *prkey;
  226. char digest[20];
  227. or_options_t *options = get_options();
  228. if (!key_lock)
  229. key_lock = tor_mutex_new();
  230. /* OP's don't need persistent keys; just make up an identity and
  231. * initialize the TLS context. */
  232. if (!server_mode(options)) {
  233. if (!(prkey = crypto_new_pk_env()))
  234. return -1;
  235. if (crypto_pk_generate_key(prkey))
  236. return -1;
  237. set_identity_key(prkey);
  238. /* Create a TLS context; default the client nickname to "client". */
  239. if (tor_tls_context_new(get_identity_key(),
  240. options->Nickname ? options->Nickname : "client",
  241. MAX_SSL_KEY_LIFETIME) < 0) {
  242. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  243. return -1;
  244. }
  245. return 0;
  246. }
  247. /* Make sure DataDirectory exists, and is private. */
  248. datadir = options->DataDirectory;
  249. if (check_private_dir(datadir, CPD_CREATE)) {
  250. return -1;
  251. }
  252. /* Check the key directory. */
  253. tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
  254. if (check_private_dir(keydir, CPD_CREATE)) {
  255. return -1;
  256. }
  257. /* 1. Read identity key. Make it if none is found. */
  258. tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
  259. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
  260. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir2);
  261. prkey = init_key_from_file_name_changed(keydir,keydir2);
  262. if (!prkey) return -1;
  263. set_identity_key(prkey);
  264. /* 2. Read onion key. Make it if none is found. */
  265. tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
  266. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
  267. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir2);
  268. prkey = init_key_from_file_name_changed(keydir,keydir2);
  269. if (!prkey) return -1;
  270. set_onion_key(prkey);
  271. tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
  272. if (file_status(keydir) == FN_FILE) {
  273. prkey = init_key_from_file(keydir);
  274. if (prkey)
  275. lastonionkey = prkey;
  276. }
  277. /* 3. Initialize link key and TLS context. */
  278. if (tor_tls_context_new(get_identity_key(), options->Nickname,
  279. MAX_SSL_KEY_LIFETIME) < 0) {
  280. log_err(LD_GENERAL,"Error initializing TLS context");
  281. return -1;
  282. }
  283. /* 4. Build our router descriptor. */
  284. /* Must be called after keys are initialized. */
  285. mydesc = router_get_my_descriptor();
  286. if (authdir_mode(options)) {
  287. const char *m;
  288. /* We need to add our own fingerprint so it gets recognized. */
  289. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  290. log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
  291. return -1;
  292. }
  293. if (!mydesc) {
  294. log_err(LD_GENERAL,"Error initializing descriptor.");
  295. return -1;
  296. }
  297. if (dirserv_add_descriptor(mydesc, &m) < 0) {
  298. log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
  299. m?m:"<unknown error>");
  300. return -1;
  301. }
  302. }
  303. /* 5. Dump fingerprint to 'fingerprint' */
  304. tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
  305. log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  306. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  307. log_err(LD_GENERAL,"Error computing fingerprint");
  308. return -1;
  309. }
  310. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  311. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  312. "%s %s\n",options->Nickname, fingerprint) < 0) {
  313. log_err(LD_GENERAL,"Error writing fingerprint line");
  314. return -1;
  315. }
  316. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  317. log_err(LD_FS, "Error writing fingerprint line to file");
  318. return -1;
  319. }
  320. log(LOG_NOTICE, LD_GENERAL,
  321. "Your Tor server's identity key fingerprint is '%s %s'",
  322. options->Nickname, fingerprint);
  323. if (!authdir_mode(options))
  324. return 0;
  325. /* 6. [authdirserver only] load approved-routers file */
  326. if (dirserv_load_fingerprint_file() < 0) {
  327. log_err(LD_GENERAL,"Error loading fingerprints");
  328. return -1;
  329. }
  330. /* 6b. [authdirserver only] add own key to approved directories. */
  331. crypto_pk_get_digest(get_identity_key(), digest);
  332. if (!router_digest_is_trusted_dir(digest)) {
  333. add_trusted_dir_server(options->Nickname, NULL,
  334. (uint16_t)options->DirPort, digest,
  335. options->V1AuthoritativeDir, /* v1 authority */
  336. 1, /* v2 authority */
  337. options->HSAuthoritativeDir /*hidserv authority*/);
  338. }
  339. return 0; /* success */
  340. }
  341. /* Keep track of whether we should upload our server descriptor,
  342. * and what type of server we are.
  343. */
  344. /** Whether we can reach our ORPort from the outside. */
  345. static int can_reach_or_port = 0;
  346. /** Whether we can reach our DirPort from the outside. */
  347. static int can_reach_dir_port = 0;
  348. /** Return 1 if ORPort is known reachable; else return 0. */
  349. int
  350. check_whether_orport_reachable(void)
  351. {
  352. or_options_t *options = get_options();
  353. return options->AssumeReachable ||
  354. can_reach_or_port;
  355. }
  356. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  357. int
  358. check_whether_dirport_reachable(void)
  359. {
  360. or_options_t *options = get_options();
  361. return !options->DirPort ||
  362. options->AssumeReachable ||
  363. we_are_hibernating() ||
  364. can_reach_dir_port;
  365. }
  366. /** Look at a variety of factors, and return 0 if we don't want to
  367. * advertise the fact that we have a DirPort open. Else return the
  368. * DirPort we want to advertise. */
  369. static int
  370. decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
  371. {
  372. if (!router->dir_port) /* short circuit the rest of the function */
  373. return 0;
  374. if (authdir_mode(options)) /* always publish */
  375. return router->dir_port;
  376. if (we_are_hibernating())
  377. return 0;
  378. if (!check_whether_dirport_reachable())
  379. return 0;
  380. if (router->bandwidthcapacity >= router->bandwidthrate) {
  381. /* check if we might potentially hibernate. */
  382. if (options->AccountingMax != 0)
  383. return 0;
  384. /* also check if we're advertising a small amount, and have
  385. a "boring" DirPort. */
  386. if (router->bandwidthrate < 50000 && router->dir_port > 1024)
  387. return 0;
  388. }
  389. /* Sounds like a great idea. Let's publish it. */
  390. return router->dir_port;
  391. }
  392. /** Some time has passed, or we just got new directory information.
  393. * See if we currently believe our ORPort or DirPort to be
  394. * unreachable. If so, launch a new test for it.
  395. *
  396. * For ORPort, we simply try making a circuit that ends at ourselves.
  397. * Success is noticed in onionskin_answer().
  398. *
  399. * For DirPort, we make a connection via Tor to our DirPort and ask
  400. * for our own server descriptor.
  401. * Success is noticed in connection_dir_client_reached_eof().
  402. */
  403. void
  404. consider_testing_reachability(int test_or, int test_dir)
  405. {
  406. routerinfo_t *me = router_get_my_routerinfo();
  407. int orport_reachable = check_whether_orport_reachable();
  408. if (!me)
  409. return;
  410. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  411. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  412. !orport_reachable ? "reachability" : "bandwidth",
  413. me->address, me->or_port);
  414. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
  415. }
  416. if (test_dir && !check_whether_dirport_reachable() &&
  417. !connection_get_by_type_addr_port_purpose(
  418. CONN_TYPE_DIR, me->addr, me->dir_port,
  419. DIR_PURPOSE_FETCH_SERVERDESC)) {
  420. /* ask myself, via tor, for my server descriptor. */
  421. directory_initiate_command_router(me, DIR_PURPOSE_FETCH_SERVERDESC,
  422. 1, "authority", NULL, 0);
  423. }
  424. }
  425. /** Annotate that we found our ORPort reachable. */
  426. void
  427. router_orport_found_reachable(void)
  428. {
  429. if (!can_reach_or_port) {
  430. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  431. "the outside. Excellent.%s",
  432. get_options()->PublishServerDescriptor ?
  433. " Publishing server descriptor." : "");
  434. can_reach_or_port = 1;
  435. mark_my_descriptor_dirty();
  436. }
  437. }
  438. /** Annotate that we found our DirPort reachable. */
  439. void
  440. router_dirport_found_reachable(void)
  441. {
  442. if (!can_reach_dir_port) {
  443. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  444. "from the outside. Excellent.");
  445. can_reach_dir_port = 1;
  446. mark_my_descriptor_dirty();
  447. }
  448. }
  449. #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
  450. /** Our router has just moved to a new IP. Reset stats. */
  451. void
  452. server_has_changed_ip(void)
  453. {
  454. if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
  455. reset_bandwidth_test();
  456. stats_n_seconds_working = 0;
  457. can_reach_or_port = 0;
  458. can_reach_dir_port = 0;
  459. mark_my_descriptor_dirty();
  460. }
  461. /** We have enough testing circuits open. Send a bunch of "drop"
  462. * cells down each of them, to exercise our bandwidth. */
  463. void
  464. router_perform_bandwidth_test(int num_circs, time_t now)
  465. {
  466. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  467. int max_cells = num_cells < CIRCWINDOW_START ?
  468. num_cells : CIRCWINDOW_START;
  469. int cells_per_circuit = max_cells / num_circs;
  470. origin_circuit_t *circ = NULL;
  471. log_notice(LD_OR,"Performing bandwidth self-test.");
  472. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  473. CIRCUIT_PURPOSE_TESTING))) {
  474. /* dump cells_per_circuit drop cells onto this circ */
  475. int i = cells_per_circuit;
  476. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  477. continue;
  478. circ->_base.timestamp_dirty = now;
  479. while (i-- > 0) {
  480. if (connection_edge_send_command(NULL, TO_CIRCUIT(circ),
  481. RELAY_COMMAND_DROP,
  482. NULL, 0, circ->cpath->prev)<0) {
  483. return; /* stop if error */
  484. }
  485. }
  486. }
  487. }
  488. /** Return true iff we believe ourselves to be an authoritative
  489. * directory server.
  490. */
  491. int
  492. authdir_mode(or_options_t *options)
  493. {
  494. return options->AuthoritativeDir != 0;
  495. }
  496. /** Return true iff we try to stay connected to all ORs at once.
  497. */
  498. int
  499. clique_mode(or_options_t *options)
  500. {
  501. return authdir_mode(options);
  502. }
  503. /** Return true iff we are trying to be a server.
  504. */
  505. int
  506. server_mode(or_options_t *options)
  507. {
  508. if (options->ClientOnly) return 0;
  509. return (options->ORPort != 0 || options->ORListenAddress);
  510. }
  511. /** Remember if we've advertised ourselves to the dirservers. */
  512. static int server_is_advertised=0;
  513. /** Return true iff we have published our descriptor lately.
  514. */
  515. int
  516. advertised_server_mode(void)
  517. {
  518. return server_is_advertised;
  519. }
  520. /**
  521. * Called with a boolean: set whether we have recently published our
  522. * descriptor.
  523. */
  524. static void
  525. set_server_advertised(int s)
  526. {
  527. server_is_advertised = s;
  528. }
  529. /** Return true iff we are trying to be a socks proxy. */
  530. int
  531. proxy_mode(or_options_t *options)
  532. {
  533. return (options->SocksPort != 0 || options->SocksListenAddress);
  534. }
  535. /** Decide if we're a publishable server. We are a publishable server if:
  536. * - We don't have the ClientOnly option set
  537. * and
  538. * - We have the PublishServerDescriptor option set
  539. * and
  540. * - We have ORPort set
  541. * and
  542. * - We believe we are reachable from the outside; or
  543. * - We have the AuthoritativeDirectory option set.
  544. */
  545. static int
  546. decide_if_publishable_server(void)
  547. {
  548. or_options_t *options = get_options();
  549. if (options->ClientOnly)
  550. return 0;
  551. if (!options->PublishServerDescriptor)
  552. return 0;
  553. if (!server_mode(options))
  554. return 0;
  555. if (options->AuthoritativeDir)
  556. return 1;
  557. return check_whether_orport_reachable();
  558. }
  559. /** Initiate server descriptor upload as reasonable (if server is publishable,
  560. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  561. *
  562. * We need to rebuild the descriptor if it's dirty even if we're not
  563. * uploading, because our reachability testing *uses* our descriptor to
  564. * determine what IP address and ports to test.
  565. */
  566. void
  567. consider_publishable_server(int force)
  568. {
  569. int rebuilt;
  570. if (!server_mode(get_options()))
  571. return;
  572. rebuilt = router_rebuild_descriptor(0);
  573. if (decide_if_publishable_server()) {
  574. set_server_advertised(1);
  575. if (rebuilt == 0)
  576. router_upload_dir_desc_to_dirservers(force);
  577. } else {
  578. set_server_advertised(0);
  579. }
  580. }
  581. /*
  582. * Clique maintenance -- to be phased out.
  583. */
  584. /** Return true iff this OR should try to keep connections open to all
  585. * other ORs. */
  586. int
  587. router_is_clique_mode(routerinfo_t *router)
  588. {
  589. if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
  590. return 1;
  591. return 0;
  592. }
  593. /*
  594. * OR descriptor generation.
  595. */
  596. /** My routerinfo. */
  597. static routerinfo_t *desc_routerinfo = NULL;
  598. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  599. * now. */
  600. static time_t desc_clean_since = 0;
  601. /** Boolean: do we need to regenerate the above? */
  602. static int desc_needs_upload = 0;
  603. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  604. * descriptor successfully yet, try to upload our signed descriptor to
  605. * all the directory servers we know about.
  606. */
  607. void
  608. router_upload_dir_desc_to_dirservers(int force)
  609. {
  610. const char *s;
  611. s = router_get_my_descriptor();
  612. if (!s) {
  613. log_info(LD_GENERAL, "No descriptor; skipping upload");
  614. return;
  615. }
  616. if (!get_options()->PublishServerDescriptor)
  617. return;
  618. if (!force && !desc_needs_upload)
  619. return;
  620. desc_needs_upload = 0;
  621. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  622. }
  623. /** OR only: Check whether my exit policy says to allow connection to
  624. * conn. Return 0 if we accept; non-0 if we reject.
  625. */
  626. int
  627. router_compare_to_my_exit_policy(edge_connection_t *conn)
  628. {
  629. tor_assert(desc_routerinfo);
  630. /* make sure it's resolved to something. this way we can't get a
  631. 'maybe' below. */
  632. if (!conn->_base.addr)
  633. return -1;
  634. return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
  635. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  636. }
  637. /** Return true iff I'm a server and <b>digest</b> is equal to
  638. * my identity digest. */
  639. int
  640. router_digest_is_me(const char *digest)
  641. {
  642. routerinfo_t *me = router_get_my_routerinfo();
  643. if (!me || memcmp(me->cache_info.identity_digest, digest, DIGEST_LEN))
  644. return 0;
  645. return 1;
  646. }
  647. /** A wrapper around router_digest_is_me(). */
  648. int
  649. router_is_me(routerinfo_t *router)
  650. {
  651. return router_digest_is_me(router->cache_info.identity_digest);
  652. }
  653. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  654. int
  655. router_fingerprint_is_me(const char *fp)
  656. {
  657. char digest[DIGEST_LEN];
  658. if (strlen(fp) == HEX_DIGEST_LEN &&
  659. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  660. return router_digest_is_me(digest);
  661. return 0;
  662. }
  663. /** Return a routerinfo for this OR, rebuilding a fresh one if
  664. * necessary. Return NULL on error, or if called on an OP. */
  665. routerinfo_t *
  666. router_get_my_routerinfo(void)
  667. {
  668. if (!server_mode(get_options()))
  669. return NULL;
  670. if (router_rebuild_descriptor(0))
  671. return NULL;
  672. return desc_routerinfo;
  673. }
  674. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  675. * one if necessary. Return NULL on error.
  676. */
  677. const char *
  678. router_get_my_descriptor(void)
  679. {
  680. const char *body;
  681. if (!router_get_my_routerinfo())
  682. return NULL;
  683. /* Make sure this is nul-terminated. */
  684. tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
  685. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  686. tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
  687. log_debug(LD_GENERAL,"my desc is '%s'", body);
  688. return body;
  689. }
  690. /*DOCDOC*/
  691. static smartlist_t *warned_nonexistent_family = NULL;
  692. static int router_guess_address_from_dir_headers(uint32_t *guess);
  693. /** Return our current best guess at our address, either because
  694. * it's configured in torrc, or because we've learned it from
  695. * dirserver headers. */
  696. int
  697. router_pick_published_address(or_options_t *options, uint32_t *addr)
  698. {
  699. if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
  700. log_info(LD_CONFIG, "Could not determine our address locally. "
  701. "Checking if directory headers provide any hints.");
  702. if (router_guess_address_from_dir_headers(addr) < 0) {
  703. log_info(LD_CONFIG, "No hints from directory headers either. "
  704. "Will try again later.");
  705. return -1;
  706. }
  707. }
  708. return 0;
  709. }
  710. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
  711. * a fresh routerinfo and signed server descriptor for this OR.
  712. * Return 0 on success, -1 on temporary error.
  713. */
  714. int
  715. router_rebuild_descriptor(int force)
  716. {
  717. routerinfo_t *ri;
  718. uint32_t addr;
  719. char platform[256];
  720. int hibernating = we_are_hibernating();
  721. or_options_t *options = get_options();
  722. if (desc_clean_since && !force)
  723. return 0;
  724. if (router_pick_published_address(options, &addr) < 0) {
  725. /* Stop trying to rebuild our descriptor every second. We'll
  726. * learn that it's time to try again when server_has_changed_ip()
  727. * marks it dirty. */
  728. desc_clean_since = time(NULL);
  729. return -1;
  730. }
  731. ri = tor_malloc_zero(sizeof(routerinfo_t));
  732. ri->routerlist_index = -1;
  733. ri->address = tor_dup_addr(addr);
  734. ri->nickname = tor_strdup(options->Nickname);
  735. ri->addr = addr;
  736. ri->or_port = options->ORPort;
  737. ri->dir_port = options->DirPort;
  738. ri->cache_info.published_on = time(NULL);
  739. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  740. * main thread */
  741. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  742. if (crypto_pk_get_digest(ri->identity_pkey,
  743. ri->cache_info.identity_digest)<0) {
  744. routerinfo_free(ri);
  745. return -1;
  746. }
  747. get_platform_str(platform, sizeof(platform));
  748. ri->platform = tor_strdup(platform);
  749. ri->bandwidthrate = (int)options->BandwidthRate;
  750. ri->bandwidthburst = (int)options->BandwidthBurst;
  751. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  752. if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
  753. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  754. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  755. options->ExitPolicyRejectPrivate);
  756. if (desc_routerinfo) { /* inherit values */
  757. ri->is_valid = desc_routerinfo->is_valid;
  758. ri->is_running = desc_routerinfo->is_running;
  759. ri->is_named = desc_routerinfo->is_named;
  760. }
  761. if (authdir_mode(options))
  762. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  763. if (options->MyFamily) {
  764. smartlist_t *family;
  765. if (!warned_nonexistent_family)
  766. warned_nonexistent_family = smartlist_create();
  767. family = smartlist_create();
  768. ri->declared_family = smartlist_create();
  769. smartlist_split_string(family, options->MyFamily, ",",
  770. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  771. SMARTLIST_FOREACH(family, char *, name,
  772. {
  773. routerinfo_t *member;
  774. if (!strcasecmp(name, options->Nickname))
  775. member = ri;
  776. else
  777. member = router_get_by_nickname(name, 1);
  778. if (!member) {
  779. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  780. !is_legal_hexdigest(name)) {
  781. log_warn(LD_CONFIG,
  782. "I have no descriptor for the router named \"%s\" "
  783. "in my declared family; I'll use the nickname as is, but "
  784. "this may confuse clients.", name);
  785. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  786. }
  787. smartlist_add(ri->declared_family, name);
  788. name = NULL;
  789. } else {
  790. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  791. fp[0] = '$';
  792. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  793. member->cache_info.identity_digest, DIGEST_LEN);
  794. smartlist_add(ri->declared_family, fp);
  795. if (smartlist_string_isin(warned_nonexistent_family, name))
  796. smartlist_string_remove(warned_nonexistent_family, name);
  797. }
  798. tor_free(name);
  799. });
  800. /* remove duplicates from the list */
  801. smartlist_sort_strings(ri->declared_family);
  802. smartlist_uniq_strings(ri->declared_family);
  803. smartlist_free(family);
  804. }
  805. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  806. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  807. ri, get_identity_key())<0) {
  808. log_warn(LD_BUG, "Couldn't allocate string for descriptor.");
  809. return -1;
  810. }
  811. ri->cache_info.signed_descriptor_len =
  812. strlen(ri->cache_info.signed_descriptor_body);
  813. crypto_digest(ri->cache_info.signed_descriptor_digest,
  814. ri->cache_info.signed_descriptor_body,
  815. ri->cache_info.signed_descriptor_len);
  816. if (desc_routerinfo)
  817. routerinfo_free(desc_routerinfo);
  818. desc_routerinfo = ri;
  819. desc_clean_since = time(NULL);
  820. desc_needs_upload = 1;
  821. control_event_my_descriptor_changed();
  822. return 0;
  823. }
  824. /** Mark descriptor out of date if it's older than <b>when</b> */
  825. void
  826. mark_my_descriptor_dirty_if_older_than(time_t when)
  827. {
  828. if (desc_clean_since < when)
  829. mark_my_descriptor_dirty();
  830. }
  831. /** Call when the current descriptor is out of date. */
  832. void
  833. mark_my_descriptor_dirty(void)
  834. {
  835. desc_clean_since = 0;
  836. }
  837. /** How frequently will we republish our descriptor because of large (factor
  838. * of 2) shifts in estimated bandwidth? */
  839. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  840. /** Check whether bandwidth has changed a lot since the last time we announced
  841. * bandwidth. If so, mark our descriptor dirty. */
  842. void
  843. check_descriptor_bandwidth_changed(time_t now)
  844. {
  845. static time_t last_changed = 0;
  846. uint64_t prev, cur;
  847. if (!desc_routerinfo)
  848. return;
  849. prev = desc_routerinfo->bandwidthcapacity;
  850. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  851. if ((prev != cur && (!prev || !cur)) ||
  852. cur > prev*2 ||
  853. cur < prev/2) {
  854. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  855. log_info(LD_GENERAL,
  856. "Measured bandwidth has changed; rebuilding descriptor.");
  857. mark_my_descriptor_dirty();
  858. last_changed = now;
  859. }
  860. }
  861. }
  862. static void
  863. log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
  864. {
  865. char addrbuf_prev[INET_NTOA_BUF_LEN];
  866. char addrbuf_cur[INET_NTOA_BUF_LEN];
  867. struct in_addr in_prev;
  868. struct in_addr in_cur;
  869. in_prev.s_addr = htonl(prev);
  870. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  871. in_cur.s_addr = htonl(cur);
  872. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  873. if (prev)
  874. log_fn(severity, LD_GENERAL,
  875. "Our IP Address has changed from %s to %s; "
  876. "rebuilding descriptor.",
  877. addrbuf_prev, addrbuf_cur);
  878. else
  879. log_notice(LD_GENERAL,
  880. "Guessed our IP address as %s.",
  881. addrbuf_cur);
  882. }
  883. /** Check whether our own address as defined by the Address configuration
  884. * has changed. This is for routers that get their address from a service
  885. * like dyndns. If our address has changed, mark our descriptor dirty. */
  886. void
  887. check_descriptor_ipaddress_changed(time_t now)
  888. {
  889. uint32_t prev, cur;
  890. or_options_t *options = get_options();
  891. (void) now;
  892. if (!desc_routerinfo)
  893. return;
  894. prev = desc_routerinfo->addr;
  895. if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
  896. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  897. return;
  898. }
  899. if (prev != cur) {
  900. log_addr_has_changed(LOG_INFO, prev, cur);
  901. mark_my_descriptor_dirty();
  902. /* the above call is probably redundant, since resolve_my_address()
  903. * probably already noticed and marked it dirty. */
  904. }
  905. }
  906. static uint32_t last_guessed_ip = 0;
  907. /** A directory authority told us our IP address is <b>suggestion</b>.
  908. * If this address is different from the one we think we are now, and
  909. * if our computer doesn't actually know its IP address, then switch. */
  910. void
  911. router_new_address_suggestion(const char *suggestion)
  912. {
  913. uint32_t addr, cur;
  914. struct in_addr in;
  915. or_options_t *options = get_options();
  916. /* first, learn what the IP address actually is */
  917. if (!tor_inet_aton(suggestion, &in)) {
  918. log_debug(LD_DIR, "Malformed X-Your-Address-Is header. Ignoring.");
  919. return;
  920. }
  921. addr = ntohl(in.s_addr);
  922. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  923. if (!server_mode(options) ||
  924. resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
  925. /* We're all set -- we already know our address. Great. */
  926. last_guessed_ip = cur; /* store it in case we need it later */
  927. return;
  928. }
  929. if (last_guessed_ip != addr) {
  930. log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
  931. server_has_changed_ip();
  932. last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
  933. }
  934. }
  935. /** We failed to resolve our address locally, but we'd like to build
  936. * a descriptor and publish / test reachability. If we have a guess
  937. * about our address based on directory headers, answer it and return
  938. * 0; else return -1. */
  939. static int
  940. router_guess_address_from_dir_headers(uint32_t *guess)
  941. {
  942. if (last_guessed_ip) {
  943. *guess = last_guessed_ip;
  944. return 0;
  945. }
  946. return -1;
  947. }
  948. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  949. * string describing the version of Tor and the operating system we're
  950. * currently running on.
  951. */
  952. void
  953. get_platform_str(char *platform, size_t len)
  954. {
  955. tor_snprintf(platform, len, "Tor %s on %s",
  956. VERSION, get_uname());
  957. return;
  958. }
  959. /* XXX need to audit this thing and count fenceposts. maybe
  960. * refactor so we don't have to keep asking if we're
  961. * near the end of maxlen?
  962. */
  963. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  964. /** OR only: Given a routerinfo for this router, and an identity key to sign
  965. * with, encode the routerinfo as a signed server descriptor and write the
  966. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  967. * failure, and the number of bytes used on success.
  968. */
  969. int
  970. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  971. crypto_pk_env_t *ident_key)
  972. {
  973. char *onion_pkey; /* Onion key, PEM-encoded. */
  974. char *identity_pkey; /* Identity key, PEM-encoded. */
  975. char digest[DIGEST_LEN];
  976. char published[ISO_TIME_LEN+1];
  977. char fingerprint[FINGERPRINT_LEN+1];
  978. struct in_addr in;
  979. char addrbuf[INET_NTOA_BUF_LEN];
  980. size_t onion_pkeylen, identity_pkeylen;
  981. size_t written;
  982. int result=0;
  983. addr_policy_t *tmpe;
  984. char *bandwidth_usage;
  985. char *family_line;
  986. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  987. char *s_dup;
  988. const char *cp;
  989. routerinfo_t *ri_tmp;
  990. #endif
  991. or_options_t *options = get_options();
  992. /* Make sure the identity key matches the one in the routerinfo. */
  993. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  994. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  995. "match router's public key!");
  996. return -1;
  997. }
  998. /* record our fingerprint, so we can include it in the descriptor */
  999. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  1000. log_err(LD_BUG,"Error computing fingerprint");
  1001. return -1;
  1002. }
  1003. /* PEM-encode the onion key */
  1004. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  1005. &onion_pkey,&onion_pkeylen)<0) {
  1006. log_warn(LD_BUG,"write onion_pkey to string failed!");
  1007. return -1;
  1008. }
  1009. /* PEM-encode the identity key key */
  1010. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  1011. &identity_pkey,&identity_pkeylen)<0) {
  1012. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1013. tor_free(onion_pkey);
  1014. return -1;
  1015. }
  1016. /* Encode the publication time. */
  1017. format_iso_time(published, router->cache_info.published_on);
  1018. /* How busy have we been? */
  1019. bandwidth_usage = rep_hist_get_bandwidth_lines();
  1020. if (router->declared_family && smartlist_len(router->declared_family)) {
  1021. size_t n;
  1022. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  1023. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  1024. family_line = tor_malloc(n);
  1025. tor_snprintf(family_line, n, "family %s\n", s);
  1026. tor_free(s);
  1027. } else {
  1028. family_line = tor_strdup("");
  1029. }
  1030. /* Generate the easy portion of the router descriptor. */
  1031. result = tor_snprintf(s, maxlen,
  1032. "router %s %s %d 0 %d\n"
  1033. "platform %s\n"
  1034. "published %s\n"
  1035. "opt fingerprint %s\n"
  1036. "uptime %ld\n"
  1037. "bandwidth %d %d %d\n"
  1038. "onion-key\n%s"
  1039. "signing-key\n%s"
  1040. #ifdef USE_EVENTDNS
  1041. "opt eventdns 1\n"
  1042. #else
  1043. "opt eventdns 0\n"
  1044. #endif
  1045. "%s%s%s",
  1046. router->nickname,
  1047. router->address,
  1048. router->or_port,
  1049. decide_to_advertise_dirport(options, router),
  1050. router->platform,
  1051. published,
  1052. fingerprint,
  1053. stats_n_seconds_working,
  1054. (int) router->bandwidthrate,
  1055. (int) router->bandwidthburst,
  1056. (int) router->bandwidthcapacity,
  1057. onion_pkey, identity_pkey,
  1058. family_line, bandwidth_usage,
  1059. we_are_hibernating() ? "opt hibernating 1\n" : "");
  1060. tor_free(family_line);
  1061. tor_free(onion_pkey);
  1062. tor_free(identity_pkey);
  1063. tor_free(bandwidth_usage);
  1064. if (result < 0)
  1065. return -1;
  1066. /* From now on, we use 'written' to remember the current length of 's'. */
  1067. written = result;
  1068. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1069. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  1070. options->ContactInfo);
  1071. if (result<0)
  1072. return -1;
  1073. written += result;
  1074. }
  1075. /* Write the exit policy to the end of 's'. */
  1076. for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  1077. /* Write: "accept 1.2.3.4" */
  1078. in.s_addr = htonl(tmpe->addr);
  1079. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  1080. result = tor_snprintf(s+written, maxlen-written, "%s %s",
  1081. tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
  1082. tmpe->msk == 0 ? "*" : addrbuf);
  1083. if (result < 0)
  1084. return -1;
  1085. written += result;
  1086. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  1087. int n_bits = addr_mask_get_bits(tmpe->msk);
  1088. if (n_bits >= 0) {
  1089. if (tor_snprintf(s+written, maxlen-written, "/%d", n_bits)<0)
  1090. return -1;
  1091. } else {
  1092. /* Write "/255.255.0.0" */
  1093. in.s_addr = htonl(tmpe->msk);
  1094. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  1095. if (tor_snprintf(s+written, maxlen-written, "/%s", addrbuf)<0)
  1096. return -1;
  1097. }
  1098. written += strlen(s+written);
  1099. }
  1100. if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
  1101. /* There is no port set; write ":*" */
  1102. if (written+4 > maxlen)
  1103. return -1;
  1104. strlcat(s+written, ":*\n", maxlen-written);
  1105. written += 3;
  1106. } else if (tmpe->prt_min == tmpe->prt_max) {
  1107. /* There is only one port; write ":80". */
  1108. result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  1109. if (result<0)
  1110. return -1;
  1111. written += result;
  1112. } else {
  1113. /* There is a range of ports; write ":79-80". */
  1114. result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n",
  1115. tmpe->prt_min, tmpe->prt_max);
  1116. if (result<0)
  1117. return -1;
  1118. written += result;
  1119. }
  1120. } /* end for */
  1121. if (written+256 > maxlen) /* Not enough room for signature. */
  1122. return -1;
  1123. /* Sign the directory */
  1124. strlcat(s+written, "router-signature\n", maxlen-written);
  1125. written += strlen(s+written);
  1126. s[written] = '\0';
  1127. if (router_get_router_hash(s, digest) < 0)
  1128. return -1;
  1129. if (router_append_dirobj_signature(s+written,maxlen-written,
  1130. digest,ident_key)<0) {
  1131. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1132. return -1;
  1133. }
  1134. written += strlen(s+written);
  1135. if (written+2 > maxlen)
  1136. return -1;
  1137. /* include a last '\n' */
  1138. s[written] = '\n';
  1139. s[written+1] = 0;
  1140. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1141. cp = s_dup = tor_strdup(s);
  1142. ri_tmp = router_parse_entry_from_string(cp, NULL, 1);
  1143. if (!ri_tmp) {
  1144. log_err(LD_BUG,
  1145. "We just generated a router descriptor we can't parse: <<%s>>",
  1146. s);
  1147. return -1;
  1148. }
  1149. tor_free(s_dup);
  1150. routerinfo_free(ri_tmp);
  1151. #endif
  1152. return written+1;
  1153. }
  1154. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1155. int
  1156. is_legal_nickname(const char *s)
  1157. {
  1158. size_t len;
  1159. tor_assert(s);
  1160. len = strlen(s);
  1161. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1162. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1163. }
  1164. /** Return true iff <b>s</b> is a legally valid server nickname or
  1165. * hex-encoded identity-key digest. */
  1166. int
  1167. is_legal_nickname_or_hexdigest(const char *s)
  1168. {
  1169. if (*s!='$')
  1170. return is_legal_nickname(s);
  1171. else
  1172. return is_legal_hexdigest(s);
  1173. }
  1174. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  1175. * digest. */
  1176. int
  1177. is_legal_hexdigest(const char *s)
  1178. {
  1179. size_t len;
  1180. tor_assert(s);
  1181. if (s[0] == '$') s++;
  1182. len = strlen(s);
  1183. if (len > HEX_DIGEST_LEN) {
  1184. if (s[HEX_DIGEST_LEN] == '=' ||
  1185. s[HEX_DIGEST_LEN] == '~') {
  1186. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  1187. return 0;
  1188. } else {
  1189. return 0;
  1190. }
  1191. }
  1192. return (len >= HEX_DIGEST_LEN &&
  1193. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  1194. }
  1195. /** DOCDOC buf must have MAX_VERBOSE_NICKNAME_LEN+1 bytes. */
  1196. void
  1197. router_get_verbose_nickname(char *buf, routerinfo_t *router)
  1198. {
  1199. buf[0] = '$';
  1200. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  1201. DIGEST_LEN);
  1202. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  1203. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  1204. }
  1205. /** Forget that we have issued any router-related warnings, so that we'll
  1206. * warn again if we see the same errors. */
  1207. void
  1208. router_reset_warnings(void)
  1209. {
  1210. if (warned_nonexistent_family) {
  1211. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1212. smartlist_clear(warned_nonexistent_family);
  1213. }
  1214. }
  1215. /** Release all static resources held in router.c */
  1216. void
  1217. router_free_all(void)
  1218. {
  1219. if (onionkey)
  1220. crypto_free_pk_env(onionkey);
  1221. if (lastonionkey)
  1222. crypto_free_pk_env(lastonionkey);
  1223. if (identitykey)
  1224. crypto_free_pk_env(identitykey);
  1225. if (key_lock)
  1226. tor_mutex_free(key_lock);
  1227. if (desc_routerinfo)
  1228. routerinfo_free(desc_routerinfo);
  1229. if (warned_nonexistent_family) {
  1230. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1231. smartlist_free(warned_nonexistent_family);
  1232. }
  1233. }