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