filesystem.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988
  1. // -------------------------------------------------
  2. // ----------------- FILESYSTEM---------------------
  3. // -------------------------------------------------
  4. // Implementation of a unix filesystem in memory.
  5. "use strict";
  6. var S_IRWXUGO = 0x1FF;
  7. var S_IFMT = 0xF000;
  8. var S_IFSOCK = 0xC000;
  9. var S_IFLNK = 0xA000;
  10. var S_IFREG = 0x8000;
  11. var S_IFBLK = 0x6000;
  12. var S_IFDIR = 0x4000;
  13. var S_IFCHR = 0x2000;
  14. //var S_IFIFO 0010000
  15. //var S_ISUID 0004000
  16. //var S_ISGID 0002000
  17. //var S_ISVTX 0001000
  18. var O_RDONLY = 0x0000; // open for reading only
  19. var O_WRONLY = 0x0001; // open for writing only
  20. var O_RDWR = 0x0002; // open for reading and writing
  21. var O_ACCMODE = 0x0003; // mask for above modes
  22. var STATUS_INVALID = -0x1;
  23. var STATUS_OK = 0x0;
  24. var STATUS_ON_STORAGE = 0x2;
  25. var STATUS_UNLINKED = 0x4;
  26. var STATUS_FORWARDING = 0x5;
  27. /** @const */ var JSONFS_VERSION = 3;
  28. /** @const */ var JSONFS_IDX_NAME = 0;
  29. /** @const */ var JSONFS_IDX_SIZE = 1;
  30. /** @const */ var JSONFS_IDX_MTIME = 2;
  31. /** @const */ var JSONFS_IDX_MODE = 3;
  32. /** @const */ var JSONFS_IDX_UID = 4;
  33. /** @const */ var JSONFS_IDX_GID = 5;
  34. /** @const */ var JSONFS_IDX_TARGET = 6;
  35. /** @const */ var JSONFS_IDX_SHA256 = 6;
  36. /**
  37. * @constructor
  38. * @param {!FileStorageInterface} storage
  39. * @param {{ last_qidnumber: number }=} qidcounter Another fs's qidcounter to synchronise with.
  40. */
  41. function FS(storage, qidcounter) {
  42. /** @type {Array.<!Inode>} */
  43. this.inodes = [];
  44. this.events = [];
  45. this.storage = storage;
  46. this.qidcounter = qidcounter || { last_qidnumber: 0 };
  47. //this.tar = new TAR(this);
  48. this.inodedata = {};
  49. this.total_size = 256 * 1024 * 1024 * 1024;
  50. this.used_size = 0;
  51. /** @type {!Array<!FSMountInfo>} */
  52. this.mounts = [];
  53. //RegisterMessage("LoadFilesystem", this.LoadFilesystem.bind(this) );
  54. //RegisterMessage("MergeFile", this.MergeFile.bind(this) );
  55. //RegisterMessage("tar",
  56. // function(data) {
  57. // SendToMaster("tar", this.tar.Pack(data));
  58. // }.bind(this)
  59. //);
  60. //RegisterMessage("sync",
  61. // function(data) {
  62. // SendToMaster("sync", this.tar.Pack(data));
  63. // }.bind(this)
  64. //);
  65. // root entry
  66. this.CreateDirectory("", -1);
  67. }
  68. FS.prototype.get_state = function()
  69. {
  70. let state = [];
  71. state[0] = this.inodes;
  72. state[1] = this.qidcounter.last_qidnumber;
  73. state[2] = [];
  74. for(let entry of Object.entries(this.inodedata))
  75. {
  76. state[2].push(entry);
  77. }
  78. state[3] = this.total_size;
  79. state[4] = this.used_size;
  80. state = state.concat(this.mounts);
  81. return state;
  82. };
  83. FS.prototype.set_state = function(state)
  84. {
  85. this.inodes = state[0].map(state => { const inode = new Inode(0); inode.set_state(state); return inode; });
  86. this.qidcounter.last_qidnumber = state[1];
  87. this.inodedata = {};
  88. for(let [key, value] of state[2])
  89. {
  90. if(value.buffer.byteLength !== value.byteLength)
  91. {
  92. // make a copy if we didn't get one
  93. value = value.slice();
  94. }
  95. this.inodedata[key] = value;
  96. }
  97. this.total_size = state[3];
  98. this.used_size = state[4];
  99. this.mounts = state.slice(5);
  100. };
  101. // -----------------------------------------------------
  102. FS.prototype.AddEvent = function(id, OnEvent) {
  103. var inode = this.inodes[id];
  104. if (inode.status == STATUS_OK || inode.status == STATUS_ON_STORAGE) {
  105. OnEvent();
  106. }
  107. else if(this.is_forwarder(inode))
  108. {
  109. this.follow_fs(inode).AddEvent(inode.foreign_id, OnEvent);
  110. }
  111. else
  112. {
  113. this.events.push({id: id, OnEvent: OnEvent});
  114. }
  115. };
  116. FS.prototype.HandleEvent = function(id) {
  117. const inode = this.inodes[id];
  118. if(this.is_forwarder(inode))
  119. {
  120. this.follow_fs(inode).HandleEvent(inode.foreign_id);
  121. }
  122. //message.Debug("number of events: " + this.events.length);
  123. var newevents = [];
  124. for(var i=0; i<this.events.length; i++) {
  125. if (this.events[i].id == id) {
  126. this.events[i].OnEvent();
  127. } else {
  128. newevents.push(this.events[i]);
  129. }
  130. }
  131. this.events = newevents;
  132. };
  133. FS.prototype.load_from_json = function(fs, done)
  134. {
  135. dbg_assert(fs, "Invalid fs passed to load_from_json");
  136. if(fs["version"] !== JSONFS_VERSION)
  137. {
  138. throw "The filesystem JSON format has changed. " +
  139. "Please update your fs2json (https://github.com/copy/fs2json) and recreate the filesystem JSON.";
  140. }
  141. var fsroot = fs["fsroot"];
  142. this.used_size = fs["size"];
  143. for(var i = 0; i < fsroot.length; i++) {
  144. this.LoadRecursive(fsroot[i], 0);
  145. }
  146. //if(DEBUG)
  147. //{
  148. // this.Check();
  149. //}
  150. done && done();
  151. };
  152. FS.prototype.LoadRecursive = function(data, parentid)
  153. {
  154. var inode = this.CreateInode();
  155. const name = data[JSONFS_IDX_NAME];
  156. inode.size = data[JSONFS_IDX_SIZE];
  157. inode.mtime = data[JSONFS_IDX_MTIME];
  158. inode.ctime = inode.mtime;
  159. inode.atime = inode.mtime;
  160. inode.mode = data[JSONFS_IDX_MODE];
  161. inode.uid = data[JSONFS_IDX_UID];
  162. inode.gid = data[JSONFS_IDX_GID];
  163. var ifmt = inode.mode & S_IFMT;
  164. if(ifmt === S_IFDIR)
  165. {
  166. inode.updatedir = true;
  167. this.PushInode(inode, parentid, name);
  168. this.LoadDir(this.inodes.length - 1, data[JSONFS_IDX_TARGET]);
  169. }
  170. else if(ifmt === S_IFREG)
  171. {
  172. inode.status = STATUS_ON_STORAGE;
  173. inode.sha256sum = data[JSONFS_IDX_SHA256];
  174. dbg_assert(inode.sha256sum);
  175. this.PushInode(inode, parentid, name);
  176. }
  177. else if(ifmt === S_IFLNK)
  178. {
  179. inode.symlink = data[JSONFS_IDX_TARGET];
  180. this.PushInode(inode, parentid, name);
  181. }
  182. else if(ifmt === S_IFSOCK)
  183. {
  184. // socket: ignore
  185. }
  186. else
  187. {
  188. dbg_log("Unexpected ifmt: " + h(ifmt) + " (" + name + ")");
  189. }
  190. };
  191. FS.prototype.LoadDir = function(parentid, children)
  192. {
  193. for(var i = 0; i < children.length; i++) {
  194. this.LoadRecursive(children[i], parentid);
  195. }
  196. };
  197. // -----------------------------------------------------
  198. /**
  199. * @private
  200. * @param {Inode} inode
  201. * @return {boolean}
  202. */
  203. FS.prototype.should_be_linked = function(inode)
  204. {
  205. // Note: Non-root forwarder inode could still have a non-forwarder parent, so don't use
  206. // parent inode to check.
  207. return !this.is_forwarder(inode) || inode.foreign_id === 0;
  208. };
  209. /**
  210. * @private
  211. * @param {number} parentid
  212. * @param {number} idx
  213. * @param {string} name
  214. */
  215. FS.prototype.link_under_dir = function(parentid, idx, name)
  216. {
  217. const inode = this.inodes[idx];
  218. const parent_inode = this.inodes[parentid];
  219. dbg_assert(!this.is_forwarder(parent_inode),
  220. "Filesystem: Shouldn't link under fowarder parents");
  221. dbg_assert(this.IsDirectory(parentid),
  222. "Filesystem: Can't link under non-directories");
  223. dbg_assert(this.should_be_linked(inode),
  224. "Filesystem: Can't link across filesystems apart from their root");
  225. dbg_assert(inode.nlinks >= 0,
  226. "Filesystem: Found negative nlinks value of " + inode.nlinks);
  227. dbg_assert(!parent_inode.direntries.has(name),
  228. "Filesystem: Name '" + name + "' is already taken");
  229. parent_inode.direntries.set(name, idx);
  230. parent_inode.updatedir = true;
  231. inode.nlinks++;
  232. if(this.IsDirectory(idx))
  233. {
  234. dbg_assert(!inode.direntries.has(".."),
  235. "Filesystem: Cannot link a directory twice");
  236. if(!inode.direntries.has(".")) inode.nlinks++;
  237. inode.direntries.set(".", idx);
  238. inode.direntries.set("..", parentid);
  239. parent_inode.nlinks++;
  240. inode.updatedir = true;
  241. }
  242. };
  243. /**
  244. * @private
  245. * @param {number} parentid
  246. * @param {string} name
  247. */
  248. FS.prototype.unlink_from_dir = function(parentid, name)
  249. {
  250. const idx = this.Search(parentid, name);
  251. const inode = this.inodes[idx];
  252. const parent_inode = this.inodes[parentid];
  253. dbg_assert(!this.is_forwarder(parent_inode), "Filesystem: Can't unlink from fowarders");
  254. dbg_assert(this.IsDirectory(parentid), "Filesystem: Can't unlink from non-directories");
  255. const exists = parent_inode.direntries.delete(name);
  256. if(!exists)
  257. {
  258. dbg_assert(false, "Filesystem: Can't unlink non-existent file: " + name);
  259. return;
  260. }
  261. inode.nlinks--;
  262. parent_inode.updatedir = true;
  263. if(this.IsDirectory(idx))
  264. {
  265. dbg_assert(inode.direntries.get("..") === parentid,
  266. "Filesystem: Found directory with bad parent id");
  267. inode.direntries.delete("..");
  268. parent_inode.nlinks--;
  269. inode.updatedir = true;
  270. }
  271. dbg_assert(inode.nlinks >= 0,
  272. "Filesystem: Found negative nlinks value of " + inode.nlinks);
  273. };
  274. FS.prototype.PushInode = function(inode, parentid, name) {
  275. if (parentid != -1) {
  276. this.inodes.push(inode);
  277. inode.fid = this.inodes.length - 1;
  278. this.link_under_dir(parentid, inode.fid, name);
  279. return;
  280. } else {
  281. if (this.inodes.length == 0) { // if root directory
  282. this.inodes.push(inode);
  283. inode.direntries.set(".", 0);
  284. inode.direntries.set("..", 0);
  285. inode.nlinks = 2;
  286. return;
  287. }
  288. }
  289. message.Debug("Error in Filesystem: Pushed inode with name = "+ name + " has no parent");
  290. message.Abort();
  291. };
  292. /** @constructor */
  293. function Inode(qidnumber)
  294. {
  295. this.updatedir = false; // did the directory listing changed?
  296. this.direntries = new Map(); // maps filename to inode id
  297. this.status = 0;
  298. this.size = 0x0;
  299. this.uid = 0x0;
  300. this.gid = 0x0;
  301. this.fid = 0;
  302. this.ctime = 0;
  303. this.atime = 0;
  304. this.mtime = 0;
  305. this.major = 0x0;
  306. this.minor = 0x0;
  307. this.symlink = "";
  308. this.mode = 0x01ED;
  309. this.qid = {
  310. type: 0,
  311. version: 0,
  312. path: qidnumber,
  313. };
  314. this.caps = undefined;
  315. this.nlinks = 0;
  316. this.dirty = false; // has this file changed?
  317. this.sha256sum = "";
  318. /** @type{!Array<!FSLockRegion>} */
  319. this.locks = []; // lock regions applied to the file, sorted by starting offset.
  320. // For forwarders:
  321. this.mount_id = -1; // which fs in this.mounts does this inode forward to?
  322. this.foreign_id = -1; // which foreign inode id does it represent?
  323. //this.qid_type = 0;
  324. //this.qid_version = 0;
  325. //this.qid_path = qidnumber;
  326. }
  327. Inode.prototype.get_state = function()
  328. {
  329. const state = [];
  330. state[0] = this.updatedir;
  331. state[1] = [...this.direntries];
  332. state[2] = this.locks;
  333. //state[3]
  334. state[4] = this.status;
  335. //state[5]
  336. state[6] = this.size;
  337. state[7] = this.uid;
  338. state[8] = this.gid;
  339. state[9] = this.fid;
  340. state[10] = this.ctime;
  341. state[11] = this.atime;
  342. state[12] = this.mtime;
  343. state[13] = this.major;
  344. state[14] = this.minor;
  345. state[15] = this.symlink;
  346. state[16] = this.mode;
  347. state[17] = this.qid.type;
  348. state[18] = this.qid.version;
  349. state[19] = this.qid.path;
  350. state[20] = this.caps;
  351. state[21] = this.nlinks;
  352. state[22] = this.dirty;
  353. state[23] = this.mount_id;
  354. state[24] = this.foreign_id;
  355. state[25] = this.sha256sum;
  356. return state;
  357. };
  358. Inode.prototype.set_state = function(state)
  359. {
  360. this.updatedir = state[0];
  361. this.direntries = new Map();
  362. for(const [name, entry] of state[1])
  363. {
  364. this.direntries.set(name, entry);
  365. }
  366. this.locks = [];
  367. for(const lock_state of state[2])
  368. {
  369. const lock = new FSLockRegion();
  370. lock.set_state(lock_state);
  371. this.locks.push(lock);
  372. }
  373. //state[3];
  374. this.status = state[4];
  375. //state[5];
  376. this.size = state[6];
  377. this.uid = state[7];
  378. this.gid = state[8];
  379. this.fid = state[9];
  380. this.ctime = state[10];
  381. this.atime = state[11];
  382. this.mtime = state[12];
  383. this.major = state[13];
  384. this.minor = state[14];
  385. this.symlink = state[15];
  386. this.mode = state[16];
  387. this.qid.type = state[17];
  388. this.qid.version = state[18];
  389. this.qid.path = state[19];
  390. this.caps = state[20];
  391. this.nlinks = state[21];
  392. this.dirty = state[22];
  393. this.mount_id = state[23];
  394. this.foreign_id = state[24];
  395. this.sha256sum = state[25];
  396. };
  397. /**
  398. * Clones given inode to new idx, effectively diverting the inode to new idx value.
  399. * Hence, original idx value is now free to use without losing the original information.
  400. * @private
  401. * @param {number} parentid Parent of target to divert.
  402. * @param {string} filename Name of target to divert.
  403. * @return {number} New idx of diversion.
  404. */
  405. FS.prototype.divert = function(parentid, filename)
  406. {
  407. const old_idx = this.Search(parentid, filename);
  408. const old_inode = this.inodes[old_idx];
  409. const new_inode = new Inode(-1);
  410. dbg_assert(old_inode, "Filesystem divert: name (" + filename + ") not found");
  411. dbg_assert(this.IsDirectory(old_idx) || old_inode.nlinks <= 1,
  412. "Filesystem: can't divert hardlinked file '" + filename + "' with nlinks=" +
  413. old_inode.nlinks);
  414. // Shallow copy is alright.
  415. Object.assign(new_inode, old_inode);
  416. const idx = this.inodes.length;
  417. this.inodes.push(new_inode);
  418. new_inode.fid = idx;
  419. // Relink references
  420. if(this.is_forwarder(old_inode))
  421. {
  422. this.mounts[old_inode.mount_id].backtrack.set(old_inode.foreign_id, idx);
  423. }
  424. if(this.should_be_linked(old_inode))
  425. {
  426. this.unlink_from_dir(parentid, filename);
  427. this.link_under_dir(parentid, idx, filename);
  428. }
  429. // Update children
  430. if(this.IsDirectory(old_idx) && !this.is_forwarder(old_inode))
  431. {
  432. for(const [name, child_id] of new_inode.direntries)
  433. {
  434. if(name === "." || name === "..") continue;
  435. if(this.IsDirectory(child_id))
  436. {
  437. this.inodes[child_id].direntries.set("..", idx);
  438. }
  439. }
  440. }
  441. // Relocate local data if any.
  442. this.inodedata[idx] = this.inodedata[old_idx];
  443. delete this.inodedata[old_idx];
  444. // Retire old reference information.
  445. old_inode.direntries = new Map();
  446. old_inode.nlinks = 0;
  447. return idx;
  448. };
  449. /**
  450. * Copy all non-redundant info.
  451. * References left untouched: local idx value and links
  452. * @private
  453. * @param {!Inode} src_inode
  454. * @param {!Inode} dest_inode
  455. */
  456. FS.prototype.copy_inode = function(src_inode, dest_inode)
  457. {
  458. Object.assign(dest_inode, src_inode, {
  459. fid: dest_inode.fid,
  460. direntries: dest_inode.direntries,
  461. nlinks: dest_inode.nlinks,
  462. });
  463. };
  464. FS.prototype.CreateInode = function() {
  465. //console.log("CreateInode", Error().stack);
  466. const now = Math.round(Date.now() / 1000);
  467. const inode = new Inode(++this.qidcounter.last_qidnumber);
  468. inode.atime = inode.ctime = inode.mtime = now;
  469. return inode;
  470. };
  471. // Note: parentid = -1 for initial root directory.
  472. FS.prototype.CreateDirectory = function(name, parentid) {
  473. const parent_inode = this.inodes[parentid];
  474. if(parentid >= 0 && this.is_forwarder(parent_inode))
  475. {
  476. const foreign_parentid = parent_inode.foreign_id;
  477. const foreign_id = this.follow_fs(parent_inode).CreateDirectory(name, foreign_parentid);
  478. return this.create_forwarder(parent_inode.mount_id, foreign_id);
  479. }
  480. var x = this.CreateInode();
  481. x.mode = 0x01FF | S_IFDIR;
  482. x.updatedir = true;
  483. if (parentid >= 0) {
  484. x.uid = this.inodes[parentid].uid;
  485. x.gid = this.inodes[parentid].gid;
  486. x.mode = (this.inodes[parentid].mode & 0x1FF) | S_IFDIR;
  487. }
  488. x.qid.type = S_IFDIR >> 8;
  489. this.PushInode(x, parentid, name);
  490. this.NotifyListeners(this.inodes.length-1, 'newdir');
  491. return this.inodes.length-1;
  492. };
  493. FS.prototype.CreateFile = function(filename, parentid) {
  494. const parent_inode = this.inodes[parentid];
  495. if(this.is_forwarder(parent_inode))
  496. {
  497. const foreign_parentid = parent_inode.foreign_id;
  498. const foreign_id = this.follow_fs(parent_inode).CreateFile(filename, foreign_parentid);
  499. return this.create_forwarder(parent_inode.mount_id, foreign_id);
  500. }
  501. var x = this.CreateInode();
  502. x.dirty = true;
  503. x.uid = this.inodes[parentid].uid;
  504. x.gid = this.inodes[parentid].gid;
  505. x.qid.type = S_IFREG >> 8;
  506. x.mode = (this.inodes[parentid].mode & 0x1B6) | S_IFREG;
  507. this.PushInode(x, parentid, filename);
  508. this.NotifyListeners(this.inodes.length-1, 'newfile');
  509. return this.inodes.length-1;
  510. };
  511. FS.prototype.CreateNode = function(filename, parentid, major, minor) {
  512. const parent_inode = this.inodes[parentid];
  513. if(this.is_forwarder(parent_inode))
  514. {
  515. const foreign_parentid = parent_inode.foreign_id;
  516. const foreign_id =
  517. this.follow_fs(parent_inode).CreateNode(filename, foreign_parentid, major, minor);
  518. return this.create_forwarder(parent_inode.mount_id, foreign_id);
  519. }
  520. var x = this.CreateInode();
  521. x.major = major;
  522. x.minor = minor;
  523. x.uid = this.inodes[parentid].uid;
  524. x.gid = this.inodes[parentid].gid;
  525. x.qid.type = S_IFSOCK >> 8;
  526. x.mode = (this.inodes[parentid].mode & 0x1B6);
  527. this.PushInode(x, parentid, filename);
  528. return this.inodes.length-1;
  529. };
  530. FS.prototype.CreateSymlink = function(filename, parentid, symlink) {
  531. const parent_inode = this.inodes[parentid];
  532. if(this.is_forwarder(parent_inode))
  533. {
  534. const foreign_parentid = parent_inode.foreign_id;
  535. const foreign_id =
  536. this.follow_fs(parent_inode).CreateSymlink(filename, foreign_parentid, symlink);
  537. return this.create_forwarder(parent_inode.mount_id, foreign_id);
  538. }
  539. var x = this.CreateInode();
  540. x.uid = this.inodes[parentid].uid;
  541. x.gid = this.inodes[parentid].gid;
  542. x.qid.type = S_IFLNK >> 8;
  543. x.symlink = symlink;
  544. x.mode = S_IFLNK;
  545. this.PushInode(x, parentid, filename);
  546. return this.inodes.length-1;
  547. };
  548. FS.prototype.CreateTextFile = async function(filename, parentid, str) {
  549. const parent_inode = this.inodes[parentid];
  550. if(this.is_forwarder(parent_inode))
  551. {
  552. const foreign_parentid = parent_inode.foreign_id;
  553. const foreign_id = await
  554. this.follow_fs(parent_inode).CreateTextFile(filename, foreign_parentid, str);
  555. return this.create_forwarder(parent_inode.mount_id, foreign_id);
  556. }
  557. var id = this.CreateFile(filename, parentid);
  558. var x = this.inodes[id];
  559. var data = new Uint8Array(str.length);
  560. x.dirty = true;
  561. x.size = str.length;
  562. for (var j = 0; j < str.length; j++) {
  563. data[j] = str.charCodeAt(j);
  564. }
  565. await this.set_data(id, data);
  566. return id;
  567. };
  568. /**
  569. * @param {Uint8Array} buffer
  570. */
  571. FS.prototype.CreateBinaryFile = async function(filename, parentid, buffer) {
  572. const parent_inode = this.inodes[parentid];
  573. if(this.is_forwarder(parent_inode))
  574. {
  575. const foreign_parentid = parent_inode.foreign_id;
  576. const foreign_id = await
  577. this.follow_fs(parent_inode).CreateBinaryFile(filename, foreign_parentid, buffer);
  578. return this.create_forwarder(parent_inode.mount_id, foreign_id);
  579. }
  580. var id = this.CreateFile(filename, parentid);
  581. var x = this.inodes[id];
  582. var data = new Uint8Array(buffer.length);
  583. x.dirty = true;
  584. data.set(buffer);
  585. await this.set_data(id, data);
  586. x.size = buffer.length;
  587. return id;
  588. };
  589. FS.prototype.OpenInode = function(id, mode) {
  590. var inode = this.inodes[id];
  591. if(this.is_forwarder(inode))
  592. {
  593. return this.follow_fs(inode).OpenInode(inode.foreign_id, mode);
  594. }
  595. if ((inode.mode&S_IFMT) == S_IFDIR) {
  596. this.FillDirectory(id);
  597. }
  598. /*
  599. var type = "";
  600. switch(inode.mode&S_IFMT) {
  601. case S_IFREG: type = "File"; break;
  602. case S_IFBLK: type = "Block Device"; break;
  603. case S_IFDIR: type = "Directory"; break;
  604. case S_IFCHR: type = "Character Device"; break;
  605. }
  606. */
  607. //message.Debug("open:" + this.GetFullPath(id) + " type: " + inode.mode + " status:" + inode.status);
  608. return true;
  609. };
  610. FS.prototype.CloseInode = async function(id) {
  611. //message.Debug("close: " + this.GetFullPath(id));
  612. var inode = this.inodes[id];
  613. if(this.is_forwarder(inode))
  614. {
  615. return await this.follow_fs(inode).CloseInode(inode.foreign_id);
  616. }
  617. if(inode.status === STATUS_ON_STORAGE)
  618. {
  619. this.storage.uncache(inode.sha256sum);
  620. }
  621. if (inode.status == STATUS_UNLINKED) {
  622. //message.Debug("Filesystem: Delete unlinked file");
  623. inode.status = STATUS_INVALID;
  624. await this.DeleteData(id);
  625. }
  626. };
  627. /**
  628. * @return {!Promise<number>} 0 if success, or -errno if failured.
  629. */
  630. FS.prototype.Rename = async function(olddirid, oldname, newdirid, newname) {
  631. // message.Debug("Rename " + oldname + " to " + newname);
  632. if ((olddirid == newdirid) && (oldname == newname)) {
  633. return 0;
  634. }
  635. var oldid = this.Search(olddirid, oldname);
  636. if(oldid === -1)
  637. {
  638. return -ENOENT;
  639. }
  640. // For event notification near end of method.
  641. var oldpath = this.GetFullPath(olddirid) + "/" + oldname;
  642. var newid = this.Search(newdirid, newname);
  643. if (newid != -1) {
  644. const ret = this.Unlink(newdirid, newname);
  645. if(ret < 0) return ret;
  646. }
  647. var idx = oldid; // idx contains the id which we want to rename
  648. var inode = this.inodes[idx];
  649. const olddir = this.inodes[olddirid];
  650. const newdir = this.inodes[newdirid];
  651. if(!this.is_forwarder(olddir) && !this.is_forwarder(newdir))
  652. {
  653. // Move inode within current filesystem.
  654. this.unlink_from_dir(olddirid, oldname);
  655. this.link_under_dir(newdirid, idx, newname);
  656. inode.qid.version++;
  657. }
  658. else if(this.is_forwarder(olddir) && olddir.mount_id === newdir.mount_id)
  659. {
  660. // Move inode within the same child filesystem.
  661. const ret = await
  662. this.follow_fs(olddir).Rename(olddir.foreign_id, oldname, newdir.foreign_id, newname);
  663. if(ret < 0) return ret;
  664. }
  665. else if(this.is_a_root(idx))
  666. {
  667. // The actual inode is a root of some descendant filesystem.
  668. // Moving mountpoint across fs not supported - needs to update all corresponding forwarders.
  669. dbg_log("XXX: Attempted to move mountpoint (" + oldname + ") - skipped", LOG_9P);
  670. return -EPERM;
  671. }
  672. else if(!this.IsDirectory(idx) && this.GetInode(idx).nlinks > 1)
  673. {
  674. // Move hardlinked inode vertically in mount tree.
  675. dbg_log("XXX: Attempted to move hardlinked file (" + oldname + ") " +
  676. "across filesystems - skipped", LOG_9P);
  677. return -EPERM;
  678. }
  679. else
  680. {
  681. // Jump between filesystems.
  682. // Can't work with both old and new inode information without first diverting the old
  683. // information into a new idx value.
  684. const diverted_old_idx = this.divert(olddirid, oldname);
  685. const old_real_inode = this.GetInode(idx);
  686. const data = await this.Read(diverted_old_idx, 0, old_real_inode.size);
  687. if(this.is_forwarder(newdir))
  688. {
  689. // Create new inode.
  690. const foreign_fs = this.follow_fs(newdir);
  691. const foreign_id = this.IsDirectory(diverted_old_idx) ?
  692. foreign_fs.CreateDirectory(newname, newdir.foreign_id) :
  693. foreign_fs.CreateFile(newname, newdir.foreign_id);
  694. const new_real_inode = foreign_fs.GetInode(foreign_id);
  695. this.copy_inode(old_real_inode, new_real_inode);
  696. // Point to this new location.
  697. this.set_forwarder(idx, newdir.mount_id, foreign_id);
  698. }
  699. else
  700. {
  701. // Replace current forwarder with real inode.
  702. this.delete_forwarder(inode);
  703. this.copy_inode(old_real_inode, inode);
  704. // Link into new location in this filesystem.
  705. this.link_under_dir(newdirid, idx, newname);
  706. }
  707. // Rewrite data to newly created destination.
  708. await this.ChangeSize(idx, old_real_inode.size);
  709. if(data && data.length)
  710. {
  711. await this.Write(idx, 0, data.length, data);
  712. }
  713. // Move children to newly created destination.
  714. if(this.IsDirectory(idx))
  715. {
  716. for(const child_filename of this.GetChildren(diverted_old_idx))
  717. {
  718. const ret = await this.Rename(diverted_old_idx, child_filename, idx, child_filename);
  719. if(ret < 0) return ret;
  720. }
  721. }
  722. // Perform destructive changes only after migration succeeded.
  723. await this.DeleteData(diverted_old_idx);
  724. const ret = this.Unlink(olddirid, oldname);
  725. if(ret < 0) return ret;
  726. }
  727. this.NotifyListeners(idx, "rename", {oldpath: oldpath});
  728. return 0;
  729. };
  730. FS.prototype.Write = async function(id, offset, count, buffer) {
  731. this.NotifyListeners(id, 'write');
  732. var inode = this.inodes[id];
  733. if(this.is_forwarder(inode))
  734. {
  735. const foreign_id = inode.foreign_id;
  736. await this.follow_fs(inode).Write(foreign_id, offset, count, buffer);
  737. return;
  738. }
  739. inode.dirty = true;
  740. var data = await this.get_buffer(id);
  741. if (!data || data.length < (offset+count)) {
  742. await this.ChangeSize(id, Math.floor(((offset+count)*3)/2));
  743. inode.size = offset + count;
  744. data = await this.get_buffer(id);
  745. } else
  746. if (inode.size < (offset+count)) {
  747. inode.size = offset + count;
  748. }
  749. if(buffer)
  750. {
  751. data.set(buffer.subarray(0, count), offset);
  752. }
  753. await this.set_data(id, data);
  754. };
  755. FS.prototype.Read = async function(inodeid, offset, count)
  756. {
  757. const inode = this.inodes[inodeid];
  758. if(this.is_forwarder(inode))
  759. {
  760. const foreign_id = inode.foreign_id;
  761. return await this.follow_fs(inode).Read(foreign_id, offset, count);
  762. }
  763. return await this.get_data(inodeid, offset, count);
  764. };
  765. FS.prototype.Search = function(parentid, name) {
  766. const parent_inode = this.inodes[parentid];
  767. if(this.is_forwarder(parent_inode))
  768. {
  769. const foreign_parentid = parent_inode.foreign_id;
  770. const foreign_id = this.follow_fs(parent_inode).Search(foreign_parentid, name);
  771. if(foreign_id === -1) return -1;
  772. return this.get_forwarder(parent_inode.mount_id, foreign_id);
  773. }
  774. const childid = parent_inode.direntries.get(name);
  775. return childid === undefined ? -1 : childid;
  776. };
  777. FS.prototype.CountUsedInodes = function()
  778. {
  779. let count = this.inodes.length;
  780. for(const { fs, backtrack } of this.mounts)
  781. {
  782. count += fs.CountUsedInodes();
  783. // Forwarder inodes don't count.
  784. count -= backtrack.size;
  785. }
  786. return count;
  787. };
  788. FS.prototype.CountFreeInodes = function()
  789. {
  790. let count = 1024 * 1024;
  791. for(const { fs } of this.mounts)
  792. {
  793. count += fs.CountFreeInodes();
  794. }
  795. return count;
  796. };
  797. FS.prototype.GetTotalSize = function() {
  798. let size = this.used_size;
  799. for(const { fs } of this.mounts)
  800. {
  801. size += fs.GetTotalSize();
  802. }
  803. return size;
  804. //var size = 0;
  805. //for(var i=0; i<this.inodes.length; i++) {
  806. // var d = this.inodes[i].data;
  807. // size += d ? d.length : 0;
  808. //}
  809. //return size;
  810. };
  811. FS.prototype.GetSpace = function() {
  812. let size = this.total_size;
  813. for(const { fs } of this.mounts)
  814. {
  815. size += fs.GetSpace();
  816. }
  817. return this.total_size;
  818. };
  819. /**
  820. * XXX: Not ideal.
  821. * @param {number} idx
  822. * @return {string}
  823. */
  824. FS.prototype.GetDirectoryName = function(idx)
  825. {
  826. const parent_inode = this.inodes[this.GetParent(idx)];
  827. if(this.is_forwarder(parent_inode))
  828. {
  829. return this.follow_fs(parent_inode).GetDirectoryName(this.inodes[idx].foreign_id);
  830. }
  831. // Root directory.
  832. if(!parent_inode) return "";
  833. for(const [name, childid] of parent_inode.direntries)
  834. {
  835. if(childid === idx) return name;
  836. }
  837. dbg_assert(false, "Filesystem: Found directory inode whose parent doesn't link to it");
  838. return "";
  839. };
  840. FS.prototype.GetFullPath = function(idx) {
  841. dbg_assert(this.IsDirectory(idx), "Filesystem: Cannot get full path of non-directory inode");
  842. var path = "";
  843. while(idx != 0) {
  844. path = "/" + this.GetDirectoryName(idx) + path;
  845. idx = this.GetParent(idx);
  846. }
  847. return path.substring(1);
  848. };
  849. /**
  850. * @param {number} parentid
  851. * @param {number} targetid
  852. * @param {string} name
  853. * @return {number} 0 if success, or -errno if failured.
  854. */
  855. FS.prototype.Link = function(parentid, targetid, name)
  856. {
  857. if(this.IsDirectory(targetid))
  858. {
  859. return -EPERM;
  860. }
  861. const parent_inode = this.inodes[parentid];
  862. const inode = this.inodes[targetid];
  863. if(this.is_forwarder(parent_inode))
  864. {
  865. if(!this.is_forwarder(inode) || inode.mount_id !== parent_inode.mount_id)
  866. {
  867. dbg_log("XXX: Attempted to hardlink a file into a child filesystem - skipped", LOG_9P);
  868. return -EPERM;
  869. }
  870. return this.follow_fs(parent_inode).Link(parent_inode.foreign_id, inode.foreign_id, name);
  871. }
  872. if(this.is_forwarder(inode))
  873. {
  874. dbg_log("XXX: Attempted to hardlink file across filesystems - skipped", LOG_9P);
  875. return -EPERM;
  876. }
  877. this.link_under_dir(parentid, targetid, name);
  878. return 0;
  879. };
  880. FS.prototype.Unlink = function(parentid, name) {
  881. if(name === "." || name === "..")
  882. {
  883. // Also guarantees that root cannot be deleted.
  884. return -EPERM;
  885. }
  886. const idx = this.Search(parentid, name);
  887. const inode = this.inodes[idx];
  888. const parent_inode = this.inodes[parentid];
  889. //message.Debug("Unlink " + inode.name);
  890. // forward if necessary
  891. if(this.is_forwarder(parent_inode))
  892. {
  893. dbg_assert(this.is_forwarder(inode), "Children of forwarders should be forwarders");
  894. const foreign_parentid = parent_inode.foreign_id;
  895. return this.follow_fs(parent_inode).Unlink(foreign_parentid, name);
  896. // Keep the forwarder dangling - file is still accessible.
  897. }
  898. if(this.IsDirectory(idx) && !this.IsEmpty(idx))
  899. {
  900. return -ENOTEMPTY;
  901. }
  902. this.unlink_from_dir(parentid, name);
  903. if(inode.nlinks === 0)
  904. {
  905. // don't delete the content. The file is still accessible
  906. inode.status = STATUS_UNLINKED;
  907. this.NotifyListeners(idx, 'delete');
  908. }
  909. return 0;
  910. };
  911. FS.prototype.DeleteData = async function(idx)
  912. {
  913. const inode = this.inodes[idx];
  914. if(this.is_forwarder(inode))
  915. {
  916. await this.follow_fs(inode).DeleteData(inode.foreign_id);
  917. return;
  918. }
  919. inode.size = 0;
  920. delete this.inodedata[idx];
  921. };
  922. /**
  923. * @private
  924. * @param {number} idx
  925. * @return {!Promise<Uint8Array>} The buffer that contains the file contents, which may be larger
  926. * than the data itself. To ensure that any modifications done to this buffer is reflected
  927. * to the file, call set_data with the modified buffer.
  928. */
  929. FS.prototype.get_buffer = async function(idx)
  930. {
  931. const inode = this.inodes[idx];
  932. dbg_assert(inode, `Filesystem get_buffer: idx ${idx} does not point to an inode`);
  933. if(this.inodedata[idx])
  934. {
  935. return this.inodedata[idx];
  936. }
  937. else if(inode.status === STATUS_ON_STORAGE)
  938. {
  939. dbg_assert(inode.sha256sum, "Filesystem get_data: found inode on server without sha256sum");
  940. return await this.storage.read(inode.sha256sum, 0, inode.size);
  941. }
  942. else
  943. {
  944. return null;
  945. }
  946. };
  947. /**
  948. * @private
  949. * @param {number} idx
  950. * @param {number} offset
  951. * @param {number} count
  952. * @return {!Promise<Uint8Array>}
  953. */
  954. FS.prototype.get_data = async function(idx, offset, count)
  955. {
  956. const inode = this.inodes[idx];
  957. dbg_assert(inode, `Filesystem get_data: idx ${idx} does not point to an inode`);
  958. if(this.inodedata[idx])
  959. {
  960. return this.inodedata[idx].subarray(offset, offset + count);
  961. }
  962. else if(inode.status === STATUS_ON_STORAGE)
  963. {
  964. dbg_assert(inode.sha256sum, "Filesystem get_data: found inode on server without sha256sum");
  965. return await this.storage.read(inode.sha256sum, offset, count);
  966. }
  967. else
  968. {
  969. return null;
  970. }
  971. };
  972. /**
  973. * @private
  974. * @param {number} idx
  975. * @param {Uint8Array} buffer
  976. */
  977. FS.prototype.set_data = async function(idx, buffer)
  978. {
  979. // Current scheme: Save all modified buffers into local inodedata.
  980. this.inodedata[idx] = buffer;
  981. if(this.inodes[idx].status === STATUS_ON_STORAGE)
  982. {
  983. this.inodes[idx].status = STATUS_OK;
  984. this.storage.uncache(this.inodes[idx].sha256sum);
  985. }
  986. };
  987. /**
  988. * @param {number} idx
  989. * @return {!Inode}
  990. */
  991. FS.prototype.GetInode = function(idx)
  992. {
  993. dbg_assert(!isNaN(idx), "Filesystem GetInode: NaN idx");
  994. dbg_assert(idx >= 0 && idx < this.inodes.length, "Filesystem GetInode: out of range idx:" + idx);
  995. const inode = this.inodes[idx];
  996. if(this.is_forwarder(inode))
  997. {
  998. return this.follow_fs(inode).GetInode(inode.foreign_id);
  999. }
  1000. return inode;
  1001. };
  1002. FS.prototype.ChangeSize = async function(idx, newsize)
  1003. {
  1004. var inode = this.GetInode(idx);
  1005. var temp = await this.get_data(idx, 0, inode.size);
  1006. inode.dirty = true;
  1007. //message.Debug("change size to: " + newsize);
  1008. if (newsize == inode.size) return;
  1009. var data = new Uint8Array(newsize);
  1010. inode.size = newsize;
  1011. if(temp)
  1012. {
  1013. var size = Math.min(temp.length, inode.size);
  1014. data.set(temp.subarray(0, size), 0);
  1015. }
  1016. await this.set_data(idx, data);
  1017. };
  1018. FS.prototype.SearchPath = function(path) {
  1019. //path = path.replace(/\/\//g, "/");
  1020. path = path.replace("//", "/");
  1021. var walk = path.split("/");
  1022. if (walk.length > 0 && walk[walk.length - 1].length === 0) walk.pop();
  1023. if (walk.length > 0 && walk[0].length === 0) walk.shift();
  1024. const n = walk.length;
  1025. var parentid = -1;
  1026. var id = 0;
  1027. let forward_path = null;
  1028. for(var i=0; i<n; i++) {
  1029. parentid = id;
  1030. id = this.Search(parentid, walk[i]);
  1031. if(!forward_path && this.is_forwarder(this.inodes[parentid]))
  1032. {
  1033. forward_path = "/" + walk.slice(i).join("/");
  1034. }
  1035. if (id == -1) {
  1036. if (i < n-1) return {id: -1, parentid: -1, name: walk[i], forward_path }; // one name of the path cannot be found
  1037. return {id: -1, parentid: parentid, name: walk[i], forward_path}; // the last element in the path does not exist, but the parent
  1038. }
  1039. }
  1040. return {id: id, parentid: parentid, name: walk[i], forward_path};
  1041. };
  1042. // -----------------------------------------------------
  1043. /**
  1044. * @param {number} dirid
  1045. * @param {Array<{parentid: number, name: string}>} list
  1046. */
  1047. FS.prototype.GetRecursiveList = function(dirid, list) {
  1048. if(this.is_forwarder(this.inodes[dirid]))
  1049. {
  1050. const foreign_fs = this.follow_fs(this.inodes[dirid]);
  1051. const foreign_dirid = this.inodes[dirid].foreign_id;
  1052. const mount_id = this.inodes[dirid].mount_id;
  1053. const foreign_start = list.length;
  1054. foreign_fs.GetRecursiveList(foreign_dirid, list);
  1055. for(let i = foreign_start; i < list.length; i++)
  1056. {
  1057. list[i].parentid = this.get_forwarder(mount_id, list[i].parentid);
  1058. }
  1059. return;
  1060. }
  1061. for(const [name, id] of this.inodes[dirid].direntries)
  1062. {
  1063. if(name !== "." && name !== "..")
  1064. {
  1065. list.push({ parentid: dirid, name });
  1066. if(this.IsDirectory(id))
  1067. {
  1068. this.GetRecursiveList(id, list);
  1069. }
  1070. }
  1071. }
  1072. };
  1073. FS.prototype.RecursiveDelete = function(path) {
  1074. var toDelete = [];
  1075. var ids = this.SearchPath(path);
  1076. if(ids.id === -1) return;
  1077. this.GetRecursiveList(ids.id, toDelete);
  1078. for(var i=toDelete.length-1; i>=0; i--)
  1079. {
  1080. const ret = this.Unlink(toDelete[i].parentid, toDelete[i].name);
  1081. dbg_assert(ret === 0, "Filesystem RecursiveDelete failed at parent=" + toDelete[i].parentid +
  1082. ", name='" + toDelete[i].name + "' with error code: " + (-ret));
  1083. }
  1084. };
  1085. FS.prototype.DeleteNode = function(path) {
  1086. var ids = this.SearchPath(path);
  1087. if (ids.id == -1) return;
  1088. if ((this.inodes[ids.id].mode&S_IFMT) == S_IFREG){
  1089. const ret = this.Unlink(ids.parentid, ids.name);
  1090. dbg_assert(ret === 0, "Filesystem DeleteNode failed with error code: " + (-ret));
  1091. return;
  1092. }
  1093. if ((this.inodes[ids.id].mode&S_IFMT) == S_IFDIR){
  1094. this.RecursiveDelete(path);
  1095. const ret = this.Unlink(ids.parentid, ids.name);
  1096. dbg_assert(ret === 0, "Filesystem DeleteNode failed with error code: " + (-ret));
  1097. return;
  1098. }
  1099. };
  1100. /** @param {*=} info */
  1101. FS.prototype.NotifyListeners = function(id, action, info) {
  1102. //if(info==undefined)
  1103. // info = {};
  1104. //var path = this.GetFullPath(id);
  1105. //if (this.watchFiles[path] == true && action=='write') {
  1106. // message.Send("WatchFileEvent", path);
  1107. //}
  1108. //for (var directory of this.watchDirectories) {
  1109. // if (this.watchDirectories.hasOwnProperty(directory)) {
  1110. // var indexOf = path.indexOf(directory)
  1111. // if(indexOf == 0 || indexOf == 1)
  1112. // message.Send("WatchDirectoryEvent", {path: path, event: action, info: info});
  1113. // }
  1114. //}
  1115. };
  1116. FS.prototype.Check = function() {
  1117. for(var i=1; i<this.inodes.length; i++)
  1118. {
  1119. if (this.inodes[i].status == STATUS_INVALID) continue;
  1120. var inode = this.GetInode(i);
  1121. if (inode.nlinks < 0) {
  1122. message.Debug("Error in filesystem: negative nlinks=" + inode.nlinks + " at id =" + i);
  1123. }
  1124. if(this.IsDirectory(i))
  1125. {
  1126. const inode = this.GetInode(i);
  1127. if(this.IsDirectory(i) && this.GetParent(i) < 0) {
  1128. message.Debug("Error in filesystem: negative parent id " + i);
  1129. }
  1130. for(const [name, id] of inode.direntries)
  1131. {
  1132. if(name.length === 0) {
  1133. message.Debug("Error in filesystem: inode with no name and id " + id);
  1134. }
  1135. for (const c of name) {
  1136. if (c < 32) {
  1137. message.Debug("Error in filesystem: Unallowed char in filename");
  1138. }
  1139. }
  1140. }
  1141. }
  1142. }
  1143. };
  1144. FS.prototype.FillDirectory = function(dirid) {
  1145. const inode = this.inodes[dirid];
  1146. if(this.is_forwarder(inode))
  1147. {
  1148. // XXX: The ".." of a mountpoint should point back to an inode in this fs.
  1149. // Otherwise, ".." gets the wrong qid and mode.
  1150. this.follow_fs(inode).FillDirectory(inode.foreign_id);
  1151. return;
  1152. }
  1153. if (!inode.updatedir) return;
  1154. inode.updatedir = false;
  1155. let size = 0;
  1156. for(const name of inode.direntries.keys())
  1157. {
  1158. size += 13 + 8 + 1 + 2 + UTF8.UTF8Length(name);
  1159. }
  1160. const data = this.inodedata[dirid] = new Uint8Array(size);
  1161. inode.size = size;
  1162. let offset = 0x0;
  1163. for(const [name, id] of inode.direntries)
  1164. {
  1165. const child = this.GetInode(id);
  1166. offset += marshall.Marshall(
  1167. ["Q", "d", "b", "s"],
  1168. [child.qid,
  1169. offset+13+8+1+2+UTF8.UTF8Length(name),
  1170. child.mode >> 12,
  1171. name],
  1172. data, offset);
  1173. }
  1174. };
  1175. FS.prototype.RoundToDirentry = function(dirid, offset_target)
  1176. {
  1177. const data = this.inodedata[dirid];
  1178. dbg_assert(data, `FS directory data for dirid=${dirid} should be generated`);
  1179. dbg_assert(data.length, "FS directory should have at least an entry");
  1180. if(offset_target >= data.length)
  1181. {
  1182. return data.length;
  1183. }
  1184. let offset = 0;
  1185. while(true)
  1186. {
  1187. const next_offset = marshall.Unmarshall(["Q", "d"], data, { offset })[1];
  1188. if(next_offset > offset_target) break;
  1189. offset = next_offset;
  1190. }
  1191. return offset;
  1192. };
  1193. /**
  1194. * @param {number} idx
  1195. * @return {boolean}
  1196. */
  1197. FS.prototype.IsDirectory = function(idx)
  1198. {
  1199. const inode = this.inodes[idx];
  1200. if(this.is_forwarder(inode))
  1201. {
  1202. return this.follow_fs(inode).IsDirectory(inode.foreign_id);
  1203. }
  1204. return (inode.mode & S_IFMT) === S_IFDIR;
  1205. };
  1206. /**
  1207. * @param {number} idx
  1208. * @return {boolean}
  1209. */
  1210. FS.prototype.IsEmpty = function(idx)
  1211. {
  1212. const inode = this.inodes[idx];
  1213. if(this.is_forwarder(inode))
  1214. {
  1215. return this.follow_fs(inode).IsDirectory(inode.foreign_id);
  1216. }
  1217. for(const name of inode.direntries.keys())
  1218. {
  1219. if(name !== "." && name !== "..") return false;
  1220. }
  1221. return true;
  1222. };
  1223. /**
  1224. * @param {number} idx
  1225. * @return {!Array<string>} List of children names
  1226. */
  1227. FS.prototype.GetChildren = function(idx)
  1228. {
  1229. dbg_assert(this.IsDirectory(idx), "Filesystem: cannot get children of non-directory inode");
  1230. const inode = this.inodes[idx];
  1231. if(this.is_forwarder(inode))
  1232. {
  1233. return this.follow_fs(inode).GetChildren(inode.foreign_id);
  1234. }
  1235. const children = [];
  1236. for(const name of inode.direntries.keys())
  1237. {
  1238. if(name !== "." && name !== "..")
  1239. {
  1240. children.push(name);
  1241. }
  1242. }
  1243. return children;
  1244. };
  1245. /**
  1246. * @param {number} idx
  1247. * @return {number} Local idx of parent
  1248. */
  1249. FS.prototype.GetParent = function(idx)
  1250. {
  1251. dbg_assert(this.IsDirectory(idx), "Filesystem: cannot get parent of non-directory inode");
  1252. const inode = this.inodes[idx];
  1253. if(this.should_be_linked(inode))
  1254. {
  1255. return inode.direntries.get("..");
  1256. }
  1257. else
  1258. {
  1259. const foreign_dirid = this.follow_fs(inode).GetParent(inode.foreign_id);
  1260. dbg_assert(foreign_dirid !== -1, "Filesystem: should not have invalid parent ids");
  1261. return this.get_forwarder(inode.mount_id, foreign_dirid);
  1262. }
  1263. };
  1264. // -----------------------------------------------------
  1265. // only support for security.capabilities
  1266. // should return a "struct vfs_cap_data" defined in
  1267. // linux/capability for format
  1268. // check also:
  1269. // sys/capability.h
  1270. // http://lxr.free-electrons.com/source/security/commoncap.c#L376
  1271. // http://man7.org/linux/man-pages/man7/capabilities.7.html
  1272. // http://man7.org/linux/man-pages/man8/getcap.8.html
  1273. // http://man7.org/linux/man-pages/man3/libcap.3.html
  1274. FS.prototype.PrepareCAPs = function(id) {
  1275. var inode = this.GetInode(id);
  1276. if (inode.caps) return inode.caps.length;
  1277. inode.caps = new Uint8Array(20);
  1278. // format is little endian
  1279. // note: getxattr returns -EINVAL if using revision 1 format.
  1280. // note: getxattr presents revision 3 as revision 2 when revision 3 is not needed.
  1281. // magic_etc (revision=0x02: 20 bytes)
  1282. inode.caps[0] = 0x00;
  1283. inode.caps[1] = 0x00;
  1284. inode.caps[2] = 0x00;
  1285. inode.caps[3] = 0x02;
  1286. // lower
  1287. // permitted (first 32 capabilities)
  1288. inode.caps[4] = 0xFF;
  1289. inode.caps[5] = 0xFF;
  1290. inode.caps[6] = 0xFF;
  1291. inode.caps[7] = 0xFF;
  1292. // inheritable (first 32 capabilities)
  1293. inode.caps[8] = 0xFF;
  1294. inode.caps[9] = 0xFF;
  1295. inode.caps[10] = 0xFF;
  1296. inode.caps[11] = 0xFF;
  1297. // higher
  1298. // permitted (last 6 capabilities)
  1299. inode.caps[12] = 0x3F;
  1300. inode.caps[13] = 0x00;
  1301. inode.caps[14] = 0x00;
  1302. inode.caps[15] = 0x00;
  1303. // inheritable (last 6 capabilities)
  1304. inode.caps[16] = 0x3F;
  1305. inode.caps[17] = 0x00;
  1306. inode.caps[18] = 0x00;
  1307. inode.caps[19] = 0x00;
  1308. return inode.caps.length;
  1309. };
  1310. // -----------------------------------------------------
  1311. /**
  1312. * @constructor
  1313. * @param {FS} filesystem
  1314. */
  1315. function FSMountInfo(filesystem)
  1316. {
  1317. /** @type {FS}*/
  1318. this.fs = filesystem;
  1319. /**
  1320. * Maps foreign inode id back to local inode id.
  1321. * @type {!Map<number,number>}
  1322. */
  1323. this.backtrack = new Map();
  1324. }
  1325. FSMountInfo.prototype.get_state = function()
  1326. {
  1327. const state = [];
  1328. state[0] = this.fs;
  1329. state[1] = [...this.backtrack];
  1330. return state;
  1331. };
  1332. FSMountInfo.prototype.set_state = function(state)
  1333. {
  1334. this.fs = state[0];
  1335. this.backtrack = new Map(state[1]);
  1336. };
  1337. /**
  1338. * @private
  1339. * @param {number} idx Local idx of inode.
  1340. * @param {number} mount_id Mount number of the destination fs.
  1341. * @param {number} foreign_id Foreign idx of destination inode.
  1342. */
  1343. FS.prototype.set_forwarder = function(idx, mount_id, foreign_id)
  1344. {
  1345. const inode = this.inodes[idx];
  1346. dbg_assert(inode.nlinks === 0,
  1347. "Filesystem: attempted to convert an inode into forwarder before unlinking the inode");
  1348. if(this.is_forwarder(inode))
  1349. {
  1350. this.mounts[inode.mount_id].backtrack.delete(inode.foreign_id);
  1351. }
  1352. inode.status = STATUS_FORWARDING;
  1353. inode.mount_id = mount_id;
  1354. inode.foreign_id = foreign_id;
  1355. this.mounts[mount_id].backtrack.set(foreign_id, idx);
  1356. };
  1357. /**
  1358. * @private
  1359. * @param {number} mount_id Mount number of the destination fs.
  1360. * @param {number} foreign_id Foreign idx of destination inode.
  1361. * @return {number} Local idx of newly created forwarder.
  1362. */
  1363. FS.prototype.create_forwarder = function(mount_id, foreign_id)
  1364. {
  1365. const inode = this.CreateInode();
  1366. const idx = this.inodes.length;
  1367. this.inodes.push(inode);
  1368. inode.fid = idx;
  1369. this.set_forwarder(idx, mount_id, foreign_id);
  1370. return idx;
  1371. };
  1372. /**
  1373. * @private
  1374. * @param {Inode} inode
  1375. * @return {boolean}
  1376. */
  1377. FS.prototype.is_forwarder = function(inode)
  1378. {
  1379. return inode.status === STATUS_FORWARDING;
  1380. };
  1381. /**
  1382. * Whether the inode it points to is a root of some filesystem.
  1383. * @private
  1384. * @param {number} idx
  1385. * @return {boolean}
  1386. */
  1387. FS.prototype.is_a_root = function(idx)
  1388. {
  1389. return this.GetInode(idx).fid === 0;
  1390. };
  1391. /**
  1392. * Ensures forwarder exists, and returns such forwarder, for the described foreign inode.
  1393. * @private
  1394. * @param {number} mount_id
  1395. * @param {number} foreign_id
  1396. * @return {number} Local idx of a forwarder to described inode.
  1397. */
  1398. FS.prototype.get_forwarder = function(mount_id, foreign_id)
  1399. {
  1400. const mount = this.mounts[mount_id];
  1401. dbg_assert(foreign_id >= 0, "Filesystem get_forwarder: invalid foreign_id: " + foreign_id);
  1402. dbg_assert(mount, "Filesystem get_forwarder: invalid mount number: " + mount_id);
  1403. const result = mount.backtrack.get(foreign_id);
  1404. if(result === undefined)
  1405. {
  1406. // Create if not already exists.
  1407. return this.create_forwarder(mount_id, foreign_id);
  1408. }
  1409. return result;
  1410. };
  1411. /**
  1412. * @private
  1413. * @param {Inode} inode
  1414. */
  1415. FS.prototype.delete_forwarder = function(inode)
  1416. {
  1417. dbg_assert(this.is_forwarder(inode), "Filesystem delete_forwarder: expected forwarder");
  1418. inode.status = STATUS_INVALID;
  1419. this.mounts[inode.mount_id].backtrack.delete(inode.foreign_id);
  1420. };
  1421. /**
  1422. * @private
  1423. * @param {Inode} inode
  1424. * @return {FS}
  1425. */
  1426. FS.prototype.follow_fs = function(inode)
  1427. {
  1428. const mount = this.mounts[inode.mount_id];
  1429. dbg_assert(this.is_forwarder(inode),
  1430. "Filesystem follow_fs: inode should be a forwarding inode");
  1431. dbg_assert(mount, "Filesystem follow_fs: inode<id=" + inode.fid +
  1432. "> should point to valid mounted FS");
  1433. return mount.fs;
  1434. };
  1435. /**
  1436. * Mount another filesystem to given path.
  1437. * @param {string} path
  1438. * @param {FS} fs
  1439. * @return {number} inode id of mount point if successful, or -errno if mounting failed.
  1440. */
  1441. FS.prototype.Mount = function(path, fs)
  1442. {
  1443. dbg_assert(fs.qidcounter === this.qidcounter,
  1444. "Cannot mount filesystem whose qid numbers aren't synchronised with current filesystem.");
  1445. const path_infos = this.SearchPath(path);
  1446. if(path_infos.parentid === -1)
  1447. {
  1448. dbg_log("Mount failed: parent for path not found: " + path, LOG_9P);
  1449. return -ENOENT;
  1450. }
  1451. if(path_infos.id !== -1)
  1452. {
  1453. dbg_log("Mount failed: file already exists at path: " + path, LOG_9P);
  1454. return -EEXIST;
  1455. }
  1456. if(path_infos.forward_path)
  1457. {
  1458. const parent = this.inodes[path_infos.parentid];
  1459. const ret = this.follow_fs(parent).Mount(path_infos.forward_path, fs);
  1460. if(ret < 0) return ret;
  1461. return this.get_forwarder(parent.mount_id, ret);
  1462. }
  1463. const mount_id = this.mounts.length;
  1464. this.mounts.push(new FSMountInfo(fs));
  1465. const idx = this.create_forwarder(mount_id, 0);
  1466. this.link_under_dir(path_infos.parentid, idx, path_infos.name);
  1467. return idx;
  1468. };
  1469. /**
  1470. * @constructor
  1471. */
  1472. function FSLockRegion()
  1473. {
  1474. this.type = P9_LOCK_TYPE_UNLCK;
  1475. this.start = 0;
  1476. this.length = Infinity;
  1477. this.proc_id = -1;
  1478. this.client_id = "";
  1479. }
  1480. FSLockRegion.prototype.get_state = function()
  1481. {
  1482. const state = [];
  1483. state[0] = this.type;
  1484. state[1] = this.start;
  1485. // Infinity is not JSON.stringify-able
  1486. state[2] = this.length === Infinity ? 0 : this.length;
  1487. state[3] = this.proc_id;
  1488. state[4] = this.client_id;
  1489. return state;
  1490. };
  1491. FSLockRegion.prototype.set_state = function(state)
  1492. {
  1493. this.type = state[0];
  1494. this.start = state[1];
  1495. this.length = state[2] === 0 ? Infinity : state[2];
  1496. this.proc_id = state[3];
  1497. this.client_id = state[4];
  1498. };
  1499. /**
  1500. * @return {FSLockRegion}
  1501. */
  1502. FSLockRegion.prototype.clone = function()
  1503. {
  1504. const new_region = new FSLockRegion();
  1505. new_region.set_state(this.get_state());
  1506. return new_region;
  1507. };
  1508. /**
  1509. * @param {FSLockRegion} region
  1510. * @return {boolean}
  1511. */
  1512. FSLockRegion.prototype.conflicts_with = function(region)
  1513. {
  1514. if(this.proc_id === region.proc_id && this.client_id === region.client_id) return false;
  1515. if(this.type === P9_LOCK_TYPE_UNLCK || region.type === P9_LOCK_TYPE_UNLCK) return false;
  1516. if(this.type !== P9_LOCK_TYPE_WRLCK && region.type !== P9_LOCK_TYPE_WRLCK) return false;
  1517. if(this.start + this.length <= region.start) return false;
  1518. if(region.start + region.length <= this.start) return false;
  1519. return true;
  1520. };
  1521. /**
  1522. * @param {FSLockRegion} region
  1523. * @return {boolean}
  1524. */
  1525. FSLockRegion.prototype.is_alike = function(region)
  1526. {
  1527. return region.proc_id === this.proc_id &&
  1528. region.client_id === this.client_id &&
  1529. region.type === this.type;
  1530. };
  1531. /**
  1532. * @param {FSLockRegion} region
  1533. * @return {boolean}
  1534. */
  1535. FSLockRegion.prototype.may_merge_after = function(region)
  1536. {
  1537. return this.is_alike(region) && region.start + region.length === this.start;
  1538. };
  1539. /**
  1540. * @param {number} type
  1541. * @param {number} start
  1542. * @param {number} length
  1543. * @param {number} proc_id
  1544. * @param {string} client_id
  1545. * @return {!FSLockRegion}
  1546. */
  1547. FS.prototype.DescribeLock = function(type, start, length, proc_id, client_id)
  1548. {
  1549. dbg_assert(type === P9_LOCK_TYPE_RDLCK ||
  1550. type === P9_LOCK_TYPE_WRLCK ||
  1551. type === P9_LOCK_TYPE_UNLCK,
  1552. "Filesystem: Invalid lock type: " + type);
  1553. dbg_assert(start >= 0, "Filesystem: Invalid negative lock starting offset: " + start);
  1554. dbg_assert(length > 0, "Filesystem: Invalid non-positive lock length: " + length);
  1555. const lock = new FSLockRegion();
  1556. lock.type = type;
  1557. lock.start = start;
  1558. lock.length = length;
  1559. lock.proc_id = proc_id;
  1560. lock.client_id = client_id;
  1561. return lock;
  1562. };
  1563. /**
  1564. * @param {number} id
  1565. * @param {FSLockRegion} request
  1566. * @return {FSLockRegion} The first conflicting lock found, or null if requested lock is possible.
  1567. */
  1568. FS.prototype.GetLock = function(id, request)
  1569. {
  1570. const inode = this.inodes[id];
  1571. if(this.is_forwarder(inode))
  1572. {
  1573. const foreign_id = inode.foreign_id;
  1574. return this.follow_fs(inode).GetLock(foreign_id, request);
  1575. }
  1576. for(const region of inode.locks)
  1577. {
  1578. if(request.conflicts_with(region))
  1579. {
  1580. return region.clone();
  1581. }
  1582. }
  1583. return null;
  1584. };
  1585. /**
  1586. * @param {number} id
  1587. * @param {FSLockRegion} request
  1588. * @param {number} flags
  1589. * @return {number} One of P9_LOCK_SUCCESS / P9_LOCK_BLOCKED / P9_LOCK_ERROR / P9_LOCK_GRACE.
  1590. */
  1591. FS.prototype.Lock = function(id, request, flags)
  1592. {
  1593. const inode = this.inodes[id];
  1594. if(this.is_forwarder(inode))
  1595. {
  1596. const foreign_id = inode.foreign_id;
  1597. return this.follow_fs(inode).Lock(foreign_id, request, flags);
  1598. }
  1599. request = request.clone();
  1600. // (1) Check whether lock is possible before any modification.
  1601. if(request.type !== P9_LOCK_TYPE_UNLCK && this.GetLock(id, request))
  1602. {
  1603. return P9_LOCK_BLOCKED;
  1604. }
  1605. // (2) Subtract requested region from locks of the same owner.
  1606. for(let i = 0; i < inode.locks.length; i++)
  1607. {
  1608. const region = inode.locks[i];
  1609. dbg_assert(region.length > 0,
  1610. "Filesystem: Found non-positive lock region length: " + region.length);
  1611. dbg_assert(region.type === P9_LOCK_TYPE_RDLCK || region.type === P9_LOCK_TYPE_WRLCK,
  1612. "Filesystem: Found invalid lock type: " + region.type);
  1613. dbg_assert(!inode.locks[i-1] || inode.locks[i-1].start <= region.start,
  1614. "Filesystem: Locks should be sorted by starting offset");
  1615. // Skip to requested region.
  1616. if(region.start + region.length <= request.start) continue;
  1617. // Check whether we've skipped past the requested region.
  1618. if(request.start + request.length <= region.start) break;
  1619. // Skip over locks of different owners.
  1620. if(region.proc_id !== request.proc_id || region.client_id !== request.client_id)
  1621. {
  1622. dbg_assert(!region.conflicts_with(request),
  1623. "Filesytem: Found conflicting lock region, despite already checked for conflicts");
  1624. continue;
  1625. }
  1626. // Pretend region would be split into parts 1 and 2.
  1627. const start1 = region.start;
  1628. const start2 = request.start + request.length;
  1629. const length1 = request.start - start1;
  1630. const length2 = region.start + region.length - start2;
  1631. if(length1 > 0 && length2 > 0 && region.type === request.type)
  1632. {
  1633. // Requested region is already locked with the required type.
  1634. // Return early - no need to modify anything.
  1635. return P9_LOCK_SUCCESS;
  1636. }
  1637. if(length1 > 0)
  1638. {
  1639. // Shrink from right / first half of the split.
  1640. region.length = length1;
  1641. }
  1642. if(length1 <= 0 && length2 > 0)
  1643. {
  1644. // Shrink from left.
  1645. region.start = start2;
  1646. region.length = length2;
  1647. }
  1648. else if(length2 > 0)
  1649. {
  1650. // Add second half of the split.
  1651. // Fast-forward to correct location.
  1652. while(i < inode.locks.length && inode.locks[i].start < start2) i++;
  1653. inode.locks.splice(i, 0,
  1654. this.DescribeLock(region.type, start2, length2, region.proc_id, region.client_id));
  1655. }
  1656. else if(length1 <= 0)
  1657. {
  1658. // Requested region completely covers this region. Delete.
  1659. inode.locks.splice(i, 1);
  1660. i--;
  1661. }
  1662. }
  1663. // (3) Insert requested lock region as a whole.
  1664. // No point in adding the requested lock region as fragmented bits in the above loop
  1665. // and having to merge them all back into one.
  1666. if(request.type !== P9_LOCK_TYPE_UNLCK)
  1667. {
  1668. let new_region = request;
  1669. let has_merged = false;
  1670. let i = 0;
  1671. // Fast-forward to requested position, and try merging with previous region.
  1672. for(; i < inode.locks.length; i++)
  1673. {
  1674. if(new_region.may_merge_after(inode.locks[i]))
  1675. {
  1676. inode.locks[i].length += request.length;
  1677. new_region = inode.locks[i];
  1678. has_merged = true;
  1679. }
  1680. if(request.start <= inode.locks[i].start) break;
  1681. }
  1682. if(!has_merged)
  1683. {
  1684. inode.locks.splice(i, 0, new_region);
  1685. i++;
  1686. }
  1687. // Try merging with the subsequent alike region.
  1688. for(; i < inode.locks.length; i++)
  1689. {
  1690. if(!inode.locks[i].is_alike(new_region)) continue;
  1691. if(inode.locks[i].may_merge_after(new_region))
  1692. {
  1693. new_region.length += inode.locks[i].length;
  1694. inode.locks.splice(i, 1);
  1695. }
  1696. // No more mergable regions after this.
  1697. break;
  1698. }
  1699. }
  1700. return P9_LOCK_SUCCESS;
  1701. };
  1702. FS.prototype.read_dir = function(path)
  1703. {
  1704. const p = this.SearchPath(path);
  1705. if(p.id === -1)
  1706. {
  1707. return undefined;
  1708. }
  1709. const dir = this.GetInode(p.id);
  1710. return Array.from(dir.direntries.keys()).filter(path => path !== "." && path !== "..");
  1711. };
  1712. FS.prototype.read_file = function(file)
  1713. {
  1714. const p = this.SearchPath(file);
  1715. if(p.id === -1)
  1716. {
  1717. return Promise.resolve(null);
  1718. }
  1719. const inode = this.GetInode(p.id);
  1720. return this.Read(p.id, 0, inode.size);
  1721. };