statefile.c 21 KB

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