statefile.c 22 KB

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