statefile.c 18 KB

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