statefile.c 21 KB

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