statefile.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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-2013, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. #define STATEFILE_PRIVATE
  7. #include "or.h"
  8. #include "circuitstats.h"
  9. #include "config.h"
  10. #include "confparse.h"
  11. #include "entrynodes.h"
  12. #include "hibernate.h"
  13. #include "rephist.h"
  14. #include "router.h"
  15. #include "statefile.h"
  16. /** A list of state-file "abbreviations," for compatibility. */
  17. static config_abbrev_t state_abbrevs_[] = {
  18. { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
  19. { "HelperNode", "EntryGuard", 0, 0 },
  20. { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
  21. { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
  22. { "EntryNode", "EntryGuard", 0, 0 },
  23. { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
  24. { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
  25. { NULL, NULL, 0, 0},
  26. };
  27. /*XXXX these next two are duplicates or near-duplicates from config.c */
  28. #define VAR(name,conftype,member,initvalue) \
  29. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
  30. initvalue }
  31. /** As VAR, but the option name and member name are the same. */
  32. #define V(member,conftype,initvalue) \
  33. VAR(#member, conftype, member, initvalue)
  34. /** Array of "state" variables saved to the ~/.tor/state file. */
  35. static config_var_t state_vars_[] = {
  36. /* Remember to document these in state-contents.txt ! */
  37. V(AccountingBytesReadInInterval, MEMUNIT, NULL),
  38. V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
  39. V(AccountingExpectedUsage, MEMUNIT, NULL),
  40. V(AccountingIntervalStart, ISOTIME, NULL),
  41. V(AccountingSecondsActive, INTERVAL, NULL),
  42. V(AccountingSecondsToReachSoftLimit,INTERVAL, NULL),
  43. V(AccountingSoftLimitHitAt, ISOTIME, NULL),
  44. V(AccountingBytesAtSoftLimit, MEMUNIT, NULL),
  45. VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
  46. VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
  47. VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
  48. VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
  49. VAR("EntryGuardPathBias", LINELIST_S, EntryGuards, NULL),
  50. VAR("EntryGuardPathUseBias", LINELIST_S, EntryGuards, NULL),
  51. V(EntryGuards, LINELIST_V, NULL),
  52. VAR("TransportProxy", LINELIST_S, TransportProxies, NULL),
  53. V(TransportProxies, LINELIST_V, NULL),
  54. V(BWHistoryReadEnds, ISOTIME, NULL),
  55. V(BWHistoryReadInterval, UINT, "900"),
  56. V(BWHistoryReadValues, CSV, ""),
  57. V(BWHistoryReadMaxima, CSV, ""),
  58. V(BWHistoryWriteEnds, ISOTIME, NULL),
  59. V(BWHistoryWriteInterval, UINT, "900"),
  60. V(BWHistoryWriteValues, CSV, ""),
  61. V(BWHistoryWriteMaxima, CSV, ""),
  62. V(BWHistoryDirReadEnds, ISOTIME, NULL),
  63. V(BWHistoryDirReadInterval, UINT, "900"),
  64. V(BWHistoryDirReadValues, CSV, ""),
  65. V(BWHistoryDirReadMaxima, CSV, ""),
  66. V(BWHistoryDirWriteEnds, ISOTIME, NULL),
  67. V(BWHistoryDirWriteInterval, UINT, "900"),
  68. V(BWHistoryDirWriteValues, CSV, ""),
  69. V(BWHistoryDirWriteMaxima, CSV, ""),
  70. V(TorVersion, STRING, NULL),
  71. V(LastRotatedOnionKey, ISOTIME, NULL),
  72. V(LastWritten, ISOTIME, NULL),
  73. V(TotalBuildTimes, UINT, NULL),
  74. V(CircuitBuildAbandonedCount, UINT, "0"),
  75. VAR("CircuitBuildTimeBin", LINELIST_S, BuildtimeHistogram, NULL),
  76. VAR("BuildtimeHistogram", LINELIST_V, BuildtimeHistogram, NULL),
  77. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  78. };
  79. #undef VAR
  80. #undef V
  81. static int or_state_validate(or_state_t *state, char **msg);
  82. static int or_state_validate_cb(void *old_options, void *options,
  83. void *default_options,
  84. int from_setconf, char **msg);
  85. /** Magic value for or_state_t. */
  86. #define OR_STATE_MAGIC 0x57A73f57
  87. /** "Extra" variable in the state that receives lines we can't parse. This
  88. * lets us preserve options from versions of Tor newer than us. */
  89. static config_var_t state_extra_var = {
  90. "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
  91. };
  92. /** Configuration format for or_state_t. */
  93. static const config_format_t state_format = {
  94. sizeof(or_state_t),
  95. OR_STATE_MAGIC,
  96. STRUCT_OFFSET(or_state_t, magic_),
  97. state_abbrevs_,
  98. state_vars_,
  99. or_state_validate_cb,
  100. &state_extra_var,
  101. };
  102. /** Persistent serialized state. */
  103. static or_state_t *global_state = NULL;
  104. /** Return the persistent state struct for this Tor. */
  105. MOCK_IMPL(or_state_t *,
  106. get_or_state, (void))
  107. {
  108. tor_assert(global_state);
  109. return global_state;
  110. }
  111. /** Return true iff we have loaded the global state for this Tor */
  112. int
  113. or_state_loaded(void)
  114. {
  115. return global_state != NULL;
  116. }
  117. /** Return true if <b>line</b> is a valid state TransportProxy line.
  118. * Return false otherwise. */
  119. static int
  120. state_transport_line_is_valid(const char *line)
  121. {
  122. smartlist_t *items = NULL;
  123. char *addrport=NULL;
  124. tor_addr_t addr;
  125. uint16_t port = 0;
  126. int r;
  127. items = smartlist_new();
  128. smartlist_split_string(items, line, NULL,
  129. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  130. if (smartlist_len(items) != 2) {
  131. log_warn(LD_CONFIG, "state: Not enough arguments in TransportProxy line.");
  132. goto err;
  133. }
  134. addrport = smartlist_get(items, 1);
  135. if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
  136. log_warn(LD_CONFIG, "state: Could not parse addrport.");
  137. goto err;
  138. }
  139. if (!port) {
  140. log_warn(LD_CONFIG, "state: Transport line did not contain port.");
  141. goto err;
  142. }
  143. r = 1;
  144. goto done;
  145. err:
  146. r = 0;
  147. done:
  148. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  149. smartlist_free(items);
  150. return r;
  151. }
  152. /** Return 0 if all TransportProxy lines in <b>state</b> are well
  153. * formed. Otherwise, return -1. */
  154. static int
  155. validate_transports_in_state(or_state_t *state)
  156. {
  157. int broken = 0;
  158. config_line_t *line;
  159. for (line = state->TransportProxies ; line ; line = line->next) {
  160. tor_assert(!strcmp(line->key, "TransportProxy"));
  161. if (!state_transport_line_is_valid(line->value))
  162. broken = 1;
  163. }
  164. if (broken)
  165. log_warn(LD_CONFIG, "state: State file seems to be broken.");
  166. return 0;
  167. }
  168. static int
  169. or_state_validate_cb(void *old_state, void *state, void *default_state,
  170. int from_setconf, char **msg)
  171. {
  172. /* We don't use these; only options do. Still, we need to match that
  173. * signature. */
  174. (void) from_setconf;
  175. (void) default_state;
  176. (void) old_state;
  177. return or_state_validate(state, msg);
  178. }
  179. /** Return 0 if every setting in <b>state</b> is reasonable, and a
  180. * permissible transition from <b>old_state</b>. Else warn and return -1.
  181. * Should have no side effects, except for normalizing the contents of
  182. * <b>state</b>.
  183. */
  184. static int
  185. or_state_validate(or_state_t *state, char **msg)
  186. {
  187. if (entry_guards_parse_state(state, 0, msg)<0)
  188. return -1;
  189. if (validate_transports_in_state(state)<0)
  190. return -1;
  191. return 0;
  192. }
  193. /** Replace the current persistent state with <b>new_state</b> */
  194. static int
  195. or_state_set(or_state_t *new_state)
  196. {
  197. char *err = NULL;
  198. int ret = 0;
  199. tor_assert(new_state);
  200. config_free(&state_format, global_state);
  201. global_state = new_state;
  202. if (entry_guards_parse_state(global_state, 1, &err)<0) {
  203. log_warn(LD_GENERAL,"%s",err);
  204. tor_free(err);
  205. ret = -1;
  206. }
  207. if (rep_hist_load_state(global_state, &err)<0) {
  208. log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
  209. tor_free(err);
  210. ret = -1;
  211. }
  212. if (circuit_build_times_parse_state(
  213. get_circuit_build_times_mutable(),global_state) < 0) {
  214. ret = -1;
  215. }
  216. return ret;
  217. }
  218. /**
  219. * Save a broken state file to a backup location.
  220. */
  221. static void
  222. or_state_save_broken(char *fname)
  223. {
  224. int i;
  225. file_status_t status;
  226. char *fname2 = NULL;
  227. for (i = 0; i < 100; ++i) {
  228. tor_asprintf(&fname2, "%s.%d", fname, i);
  229. status = file_status(fname2);
  230. if (status == FN_NOENT)
  231. break;
  232. tor_free(fname2);
  233. }
  234. if (i == 100) {
  235. log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
  236. "state files to move aside. Discarding the old state file.",
  237. fname);
  238. unlink(fname);
  239. } else {
  240. log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
  241. "to \"%s\". This could be a bug in Tor; please tell "
  242. "the developers.", fname, fname2);
  243. if (rename(fname, fname2) < 0) {
  244. log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
  245. "OS gave an error of %s", strerror(errno));
  246. }
  247. }
  248. tor_free(fname2);
  249. }
  250. /** Reload the persistent state from disk, generating a new state as needed.
  251. * Return 0 on success, less than 0 on failure.
  252. */
  253. int
  254. or_state_load(void)
  255. {
  256. or_state_t *new_state = NULL;
  257. char *contents = NULL, *fname;
  258. char *errmsg = NULL;
  259. int r = -1, badstate = 0;
  260. fname = get_datadir_fname("state");
  261. switch (file_status(fname)) {
  262. case FN_FILE:
  263. if (!(contents = read_file_to_str(fname, 0, NULL))) {
  264. log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
  265. goto done;
  266. }
  267. break;
  268. case FN_NOENT:
  269. break;
  270. case FN_ERROR:
  271. case FN_DIR:
  272. default:
  273. log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
  274. goto done;
  275. }
  276. new_state = tor_malloc_zero(sizeof(or_state_t));
  277. new_state->magic_ = OR_STATE_MAGIC;
  278. config_init(&state_format, new_state);
  279. if (contents) {
  280. config_line_t *lines=NULL;
  281. int assign_retval;
  282. if (config_get_lines(contents, &lines, 0)<0)
  283. goto done;
  284. assign_retval = config_assign(&state_format, new_state,
  285. lines, 0, 0, &errmsg);
  286. config_free_lines(lines);
  287. if (assign_retval<0)
  288. badstate = 1;
  289. if (errmsg) {
  290. log_warn(LD_GENERAL, "%s", errmsg);
  291. tor_free(errmsg);
  292. }
  293. }
  294. if (!badstate && or_state_validate(new_state, &errmsg) < 0)
  295. badstate = 1;
  296. if (errmsg) {
  297. log_warn(LD_GENERAL, "%s", errmsg);
  298. tor_free(errmsg);
  299. }
  300. if (badstate && !contents) {
  301. log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
  302. " This is a bug in Tor.");
  303. goto done;
  304. } else if (badstate && contents) {
  305. or_state_save_broken(fname);
  306. tor_free(contents);
  307. config_free(&state_format, new_state);
  308. new_state = tor_malloc_zero(sizeof(or_state_t));
  309. new_state->magic_ = OR_STATE_MAGIC;
  310. config_init(&state_format, new_state);
  311. } else if (contents) {
  312. log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
  313. } else {
  314. log_info(LD_GENERAL, "Initialized state");
  315. }
  316. if (or_state_set(new_state) == -1) {
  317. or_state_save_broken(fname);
  318. }
  319. new_state = NULL;
  320. if (!contents) {
  321. global_state->next_write = 0;
  322. or_state_save(time(NULL));
  323. }
  324. r = 0;
  325. done:
  326. tor_free(fname);
  327. tor_free(contents);
  328. if (new_state)
  329. config_free(&state_format, new_state);
  330. return r;
  331. }
  332. /** Did the last time we tried to write the state file fail? If so, we
  333. * should consider disabling such features as preemptive circuit generation
  334. * to compute circuit-build-time. */
  335. static int last_state_file_write_failed = 0;
  336. /** Return whether the state file failed to write last time we tried. */
  337. int
  338. did_last_state_file_write_fail(void)
  339. {
  340. return last_state_file_write_failed;
  341. }
  342. /** If writing the state to disk fails, try again after this many seconds. */
  343. #define STATE_WRITE_RETRY_INTERVAL 3600
  344. /** If we're a relay, how often should we checkpoint our state file even
  345. * if nothing else dirties it? This will checkpoint ongoing stats like
  346. * bandwidth used, per-country user stats, etc. */
  347. #define STATE_RELAY_CHECKPOINT_INTERVAL (12*60*60)
  348. /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
  349. int
  350. or_state_save(time_t now)
  351. {
  352. char *state, *contents;
  353. char tbuf[ISO_TIME_LEN+1];
  354. char *fname;
  355. tor_assert(global_state);
  356. if (global_state->next_write > now)
  357. return 0;
  358. /* Call everything else that might dirty the state even more, in order
  359. * to avoid redundant writes. */
  360. entry_guards_update_state(global_state);
  361. rep_hist_update_state(global_state);
  362. circuit_build_times_update_state(get_circuit_build_times(), global_state);
  363. if (accounting_is_enabled(get_options()))
  364. accounting_run_housekeeping(now);
  365. global_state->LastWritten = now;
  366. tor_free(global_state->TorVersion);
  367. tor_asprintf(&global_state->TorVersion, "Tor %s", get_version());
  368. state = config_dump(&state_format, NULL, global_state, 1, 0);
  369. format_local_iso_time(tbuf, now);
  370. tor_asprintf(&contents,
  371. "# Tor state file last generated on %s local time\n"
  372. "# Other times below are in UTC\n"
  373. "# You *do not* need to edit this file.\n\n%s",
  374. tbuf, state);
  375. tor_free(state);
  376. fname = get_datadir_fname("state");
  377. if (write_str_to_file(fname, contents, 0)<0) {
  378. log_warn(LD_FS, "Unable to write state to file \"%s\"; "
  379. "will try again later", fname);
  380. last_state_file_write_failed = 1;
  381. tor_free(fname);
  382. tor_free(contents);
  383. /* Try again after STATE_WRITE_RETRY_INTERVAL (or sooner, if the state
  384. * changes sooner). */
  385. global_state->next_write = now + STATE_WRITE_RETRY_INTERVAL;
  386. return -1;
  387. }
  388. last_state_file_write_failed = 0;
  389. log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
  390. tor_free(fname);
  391. tor_free(contents);
  392. if (server_mode(get_options()))
  393. global_state->next_write = now + STATE_RELAY_CHECKPOINT_INTERVAL;
  394. else
  395. global_state->next_write = TIME_MAX;
  396. return 0;
  397. }
  398. /** Return the config line for transport <b>transport</b> in the current state.
  399. * Return NULL if there is no config line for <b>transport</b>. */
  400. STATIC config_line_t *
  401. get_transport_in_state_by_name(const char *transport)
  402. {
  403. or_state_t *or_state = get_or_state();
  404. config_line_t *line;
  405. config_line_t *ret = NULL;
  406. smartlist_t *items = NULL;
  407. for (line = or_state->TransportProxies ; line ; line = line->next) {
  408. tor_assert(!strcmp(line->key, "TransportProxy"));
  409. items = smartlist_new();
  410. smartlist_split_string(items, line->value, NULL,
  411. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  412. if (smartlist_len(items) != 2) /* broken state */
  413. goto done;
  414. if (!strcmp(smartlist_get(items, 0), transport)) {
  415. ret = line;
  416. goto done;
  417. }
  418. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  419. smartlist_free(items);
  420. items = NULL;
  421. }
  422. done:
  423. if (items) {
  424. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  425. smartlist_free(items);
  426. }
  427. return ret;
  428. }
  429. /** Return string containing the address:port part of the
  430. * TransportProxy <b>line</b> for transport <b>transport</b>.
  431. * If the line is corrupted, return NULL. */
  432. static const char *
  433. get_transport_bindaddr(const char *line, const char *transport)
  434. {
  435. char *line_tmp = NULL;
  436. if (strlen(line) < strlen(transport) + 2) {
  437. goto broken_state;
  438. } else {
  439. /* line should start with the name of the transport and a space.
  440. (for example, "obfs2 127.0.0.1:47245") */
  441. tor_asprintf(&line_tmp, "%s ", transport);
  442. if (strcmpstart(line, line_tmp))
  443. goto broken_state;
  444. tor_free(line_tmp);
  445. return (line+strlen(transport)+1);
  446. }
  447. broken_state:
  448. tor_free(line_tmp);
  449. return NULL;
  450. }
  451. /** Return a string containing the address:port that a proxy transport
  452. * should bind on. The string is stored on the heap and must be freed
  453. * by the caller of this function. */
  454. char *
  455. get_stored_bindaddr_for_server_transport(const char *transport)
  456. {
  457. char *default_addrport = NULL;
  458. const char *stored_bindaddr = NULL;
  459. config_line_t *line = NULL;
  460. {
  461. /* See if the user explicitly asked for a specific listening
  462. address for this transport. */
  463. char *conf_bindaddr = get_transport_bindaddr_from_config(transport);
  464. if (conf_bindaddr)
  465. return conf_bindaddr;
  466. }
  467. line = get_transport_in_state_by_name(transport);
  468. if (!line) /* Found no references in state for this transport. */
  469. goto no_bindaddr_found;
  470. stored_bindaddr = get_transport_bindaddr(line->value, transport);
  471. if (stored_bindaddr) /* found stored bindaddr in state file. */
  472. return tor_strdup(stored_bindaddr);
  473. no_bindaddr_found:
  474. /** If we didn't find references for this pluggable transport in the
  475. state file, we should instruct the pluggable transport proxy to
  476. listen on INADDR_ANY on a random ephemeral port. */
  477. tor_asprintf(&default_addrport, "%s:%s", fmt_addr32(INADDR_ANY), "0");
  478. return default_addrport;
  479. }
  480. /** Save <b>transport</b> listening on <b>addr</b>:<b>port</b> to
  481. state */
  482. void
  483. save_transport_to_state(const char *transport,
  484. const tor_addr_t *addr, uint16_t port)
  485. {
  486. or_state_t *state = get_or_state();
  487. char *transport_addrport=NULL;
  488. /** find where to write on the state */
  489. config_line_t **next, *line;
  490. /* see if this transport is already stored in state */
  491. config_line_t *transport_line =
  492. get_transport_in_state_by_name(transport);
  493. if (transport_line) { /* if transport already exists in state... */
  494. const char *prev_bindaddr = /* get its addrport... */
  495. get_transport_bindaddr(transport_line->value, transport);
  496. transport_addrport = tor_strdup(fmt_addrport(addr, port));
  497. /* if transport in state has the same address as this one, life is good */
  498. if (!strcmp(prev_bindaddr, transport_addrport)) {
  499. log_info(LD_CONFIG, "Transport seems to have spawned on its usual "
  500. "address:port.");
  501. goto done;
  502. } else { /* if addrport in state is different than the one we got */
  503. log_info(LD_CONFIG, "Transport seems to have spawned on different "
  504. "address:port. Let's update the state file with the new "
  505. "address:port");
  506. tor_free(transport_line->value); /* free the old line */
  507. /* replace old addrport line with new line */
  508. tor_asprintf(&transport_line->value, "%s %s", transport,
  509. fmt_addrport(addr, port));
  510. }
  511. } else { /* never seen this one before; save it in state for next time */
  512. log_info(LD_CONFIG, "It's the first time we see this transport. "
  513. "Let's save its address:port");
  514. next = &state->TransportProxies;
  515. /* find the last TransportProxy line in the state and point 'next'
  516. right after it */
  517. line = state->TransportProxies;
  518. while (line) {
  519. next = &(line->next);
  520. line = line->next;
  521. }
  522. /* allocate space for the new line and fill it in */
  523. *next = line = tor_malloc_zero(sizeof(config_line_t));
  524. line->key = tor_strdup("TransportProxy");
  525. tor_asprintf(&line->value, "%s %s", transport, fmt_addrport(addr, port));
  526. next = &(line->next);
  527. }
  528. if (!get_options()->AvoidDiskWrites)
  529. or_state_mark_dirty(state, 0);
  530. done:
  531. tor_free(transport_addrport);
  532. }
  533. void
  534. or_state_free_all(void)
  535. {
  536. config_free(&state_format, global_state);
  537. global_state = NULL;
  538. }