statefile.c 22 KB

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