statefile.c 23 KB

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