statefile.c 22 KB

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