statefile.c 22 KB

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