_SessionFile.jsm 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  3. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. this.EXPORTED_SYMBOLS = ["_SessionFile"];
  6. /**
  7. * Implementation of all the disk I/O required by the session store.
  8. * This is a private API, meant to be used only by the session store.
  9. * It will change. Do not use it for any other purpose.
  10. *
  11. * Note that this module implicitly depends on one of two things:
  12. * 1. either the asynchronous file I/O system enqueues its requests
  13. * and never attempts to simultaneously execute two I/O requests on
  14. * the files used by this module from two distinct threads; or
  15. * 2. the clients of this API are well-behaved and do not place
  16. * concurrent requests to the files used by this module.
  17. *
  18. * Otherwise, we could encounter bugs, especially under Windows,
  19. * e.g. if a request attempts to write sessionstore.js while
  20. * another attempts to copy that file.
  21. *
  22. * This implementation uses OS.File, which guarantees property 1.
  23. */
  24. const Cu = Components.utils;
  25. const Cc = Components.classes;
  26. const Ci = Components.interfaces;
  27. Cu.import("resource://gre/modules/Services.jsm");
  28. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  29. Cu.import("resource://gre/modules/osfile.jsm");
  30. Cu.import("resource://gre/modules/Promise.jsm");
  31. XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
  32. "resource://gre/modules/NetUtil.jsm");
  33. XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
  34. "resource://gre/modules/FileUtils.jsm");
  35. XPCOMUtils.defineLazyModuleGetter(this, "Task",
  36. "resource://gre/modules/Task.jsm");
  37. XPCOMUtils.defineLazyModuleGetter(this, "console",
  38. "resource://gre/modules/Console.jsm");
  39. // An encoder to UTF-8.
  40. XPCOMUtils.defineLazyGetter(this, "gEncoder", function() {
  41. return new TextEncoder();
  42. });
  43. // A decoder.
  44. XPCOMUtils.defineLazyGetter(this, "gDecoder", function() {
  45. return new TextDecoder();
  46. });
  47. this._SessionFile = {
  48. /**
  49. * A promise fulfilled once initialization (either synchronous or
  50. * asynchronous) is complete.
  51. */
  52. promiseInitialized: function() {
  53. return SessionFileInternal.promiseInitialized;
  54. },
  55. /**
  56. * Read the contents of the session file, asynchronously.
  57. */
  58. read: function() {
  59. return SessionFileInternal.read();
  60. },
  61. /**
  62. * Read the contents of the session file, synchronously.
  63. */
  64. syncRead: function() {
  65. return SessionFileInternal.syncRead();
  66. },
  67. /**
  68. * Write the contents of the session file, asynchronously.
  69. */
  70. write: function(aData) {
  71. return SessionFileInternal.write(aData);
  72. },
  73. /**
  74. * Create a backup copy, asynchronously.
  75. */
  76. createBackupCopy: function() {
  77. return SessionFileInternal.createBackupCopy();
  78. },
  79. /**
  80. * Wipe the contents of the session file, asynchronously.
  81. */
  82. wipe: function() {
  83. return SessionFileInternal.wipe();
  84. }
  85. };
  86. Object.freeze(_SessionFile);
  87. /**
  88. * Utilities for dealing with promises and Task.jsm
  89. */
  90. const TaskUtils = {
  91. /**
  92. * Add logging to a promise.
  93. *
  94. * @param {Promise} promise
  95. * @return {Promise} A promise behaving as |promise|, but with additional
  96. * logging in case of uncaught error.
  97. */
  98. captureErrors: function(promise) {
  99. return promise.then(
  100. null,
  101. function onError(reason) {
  102. console.error("Uncaught asynchronous error:", reason);
  103. throw reason;
  104. }
  105. );
  106. },
  107. /**
  108. * Spawn a new Task from a generator.
  109. *
  110. * This function behaves as |Task.spawn|, with the exception that it
  111. * adds logging in case of uncaught error. For more information, see
  112. * the documentation of |Task.jsm|.
  113. *
  114. * @param {generator} gen Some generator.
  115. * @return {Promise} A promise built from |gen|, with the same semantics
  116. * as |Task.spawn(gen)|.
  117. */
  118. spawn: function spawn(gen) {
  119. return this.captureErrors(Task.spawn(gen));
  120. }
  121. };
  122. var SessionFileInternal = {
  123. /**
  124. * A promise fulfilled once initialization is complete
  125. */
  126. promiseInitialized: Promise.defer(),
  127. /**
  128. * The path to sessionstore.js
  129. */
  130. path: OS.Path.join(OS.Constants.Path.profileDir, "sessionstore.js"),
  131. /**
  132. * The path to sessionstore.bak
  133. */
  134. backupPath: OS.Path.join(OS.Constants.Path.profileDir, "sessionstore.bak"),
  135. /**
  136. * Utility function to safely read a file synchronously.
  137. * @param aPath
  138. * A path to read the file from.
  139. * @returns string if successful, undefined otherwise.
  140. */
  141. readAuxSync: function(aPath) {
  142. let text;
  143. try {
  144. let file = new FileUtils.File(aPath);
  145. let chan = NetUtil.newChannel({
  146. uri: NetUtil.newURI(file),
  147. loadUsingSystemPrincipal: true
  148. });
  149. let stream = chan.open();
  150. text = NetUtil.readInputStreamToString(stream, stream.available(),
  151. {charset: "utf-8"});
  152. } catch (e if e.result == Components.results.NS_ERROR_FILE_NOT_FOUND) {
  153. // Ignore exceptions about non-existent files.
  154. } catch (ex) {
  155. // Any other error.
  156. console.error("Uncaught error:", ex);
  157. } finally {
  158. return text;
  159. }
  160. },
  161. /**
  162. * Read the sessionstore file synchronously.
  163. *
  164. * This function is meant to serve as a fallback in case of race
  165. * between a synchronous usage of the API and asynchronous
  166. * initialization.
  167. *
  168. * In case if sessionstore.js file does not exist or is corrupted (something
  169. * happened between backup and write), attempt to read the sessionstore.bak
  170. * instead.
  171. */
  172. syncRead: function() {
  173. // First read the sessionstore.js.
  174. let text = this.readAuxSync(this.path);
  175. if (typeof text === "undefined") {
  176. // If sessionstore.js does not exist or is corrupted, read sessionstore.bak.
  177. text = this.readAuxSync(this.backupPath);
  178. }
  179. return text || "";
  180. },
  181. /**
  182. * Utility function to safely read a file asynchronously.
  183. * @param aPath
  184. * A path to read the file from.
  185. * @param aReadOptions
  186. * Read operation options.
  187. * |outExecutionDuration| option will be reused and can be
  188. * incrementally updated by the worker process.
  189. * @returns string if successful, undefined otherwise.
  190. */
  191. readAux: function(aPath, aReadOptions) {
  192. let self = this;
  193. return TaskUtils.spawn(function() {
  194. let text;
  195. try {
  196. let bytes = yield OS.File.read(aPath, undefined, aReadOptions);
  197. text = gDecoder.decode(bytes);
  198. } catch (ex if self._isNoSuchFile(ex)) {
  199. // Ignore exceptions about non-existent files.
  200. } catch (ex) {
  201. // Any other error.
  202. console.error("Uncaught error - with the file: " + self.path, ex);
  203. }
  204. throw new Task.Result(text);
  205. });
  206. },
  207. /**
  208. * Read the sessionstore file asynchronously.
  209. *
  210. * In case sessionstore.js file does not exist or is corrupted (something
  211. * happened between backup and write), attempt to read the sessionstore.bak
  212. * instead.
  213. */
  214. read: function() {
  215. let self = this;
  216. return TaskUtils.spawn(function task() {
  217. // Specify |outExecutionDuration| option to hold the combined duration of
  218. // the asynchronous reads off the main thread (of both sessionstore.js and
  219. // sessionstore.bak, if necessary). If sessionstore.js does not exist or
  220. // is corrupted, |outExecutionDuration| will register the time it took to
  221. // attempt to read the file. It will then be subsequently incremented by
  222. // the read time of sessionsore.bak.
  223. let readOptions = {
  224. outExecutionDuration: null
  225. };
  226. // First read the sessionstore.js.
  227. let text = yield self.readAux(self.path, readOptions);
  228. if (typeof text === "undefined") {
  229. // If sessionstore.js does not exist or is corrupted, read the
  230. // sessionstore.bak.
  231. text = yield self.readAux(self.backupPath, readOptions);
  232. }
  233. // Return either the content of the sessionstore.bak if it was read
  234. // successfully or an empty string otherwise.
  235. throw new Task.Result(text || "");
  236. });
  237. },
  238. write: function(aData) {
  239. let refObj = {};
  240. let self = this;
  241. return TaskUtils.spawn(function task() {
  242. let bytes = gEncoder.encode(aData);
  243. try {
  244. let promise = OS.File.writeAtomic(self.path, bytes, {tmpPath: self.path + ".tmp"});
  245. yield promise;
  246. } catch (ex) {
  247. console.error("Could not write session state file: " + self.path, ex);
  248. }
  249. });
  250. },
  251. createBackupCopy: function() {
  252. let backupCopyOptions = {
  253. outExecutionDuration: null
  254. };
  255. let self = this;
  256. return TaskUtils.spawn(function task() {
  257. try {
  258. yield OS.File.move(self.path, self.backupPath, backupCopyOptions);
  259. } catch (ex if self._isNoSuchFile(ex)) {
  260. // Ignore exceptions about non-existent files.
  261. } catch (ex) {
  262. console.error("Could not backup session state file: " + self.path, ex);
  263. throw ex;
  264. }
  265. });
  266. },
  267. wipe: function() {
  268. let self = this;
  269. return TaskUtils.spawn(function task() {
  270. try {
  271. yield OS.File.remove(self.path);
  272. } catch (ex if self._isNoSuchFile(ex)) {
  273. // Ignore exceptions about non-existent files.
  274. } catch (ex) {
  275. console.error("Could not remove session state file: " + self.path, ex);
  276. throw ex;
  277. }
  278. try {
  279. yield OS.File.remove(self.backupPath);
  280. } catch (ex if self._isNoSuchFile(ex)) {
  281. // Ignore exceptions about non-existent files.
  282. } catch (ex) {
  283. console.error("Could not remove session state backup file: " + self.path, ex);
  284. throw ex;
  285. }
  286. });
  287. },
  288. _isNoSuchFile: function(aReason) {
  289. return aReason instanceof OS.File.Error && aReason.becauseNoSuchFile;
  290. }
  291. };