statefile.c 22 KB

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