statefile.c 18 KB

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