statefile.c 23 KB

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