cheerpOS.js 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139
  1. // Copyright 2017-2021 Leaning Technologies Ltd. All Rights Reserved.
  2. // An array of {path:"/path",handler:handlerObj} ordered by the most specific to the least
  3. var cheerpjFSMounts = [];
  4. // An array of resources loaded from the runtime
  5. var cheerpjRuntimeResources = [];
  6. // Resource ranges loaded from the runtime
  7. var cosRuntimeResourcesRanges = {};
  8. var cosFileWatchPrefixes = {};
  9. function cheerpjFSInit(appUrlPrefix, jarJsOverridePath, loaderPath, useIframe)
  10. {
  11. // Keep these ordered from the most specific to the least
  12. cheerpjFSMounts.push(new CheerpJWebFolder("/app/", appUrlPrefix ? appUrlPrefix : "", jarJsOverridePath, false, DirectDownloader));
  13. cheerpjFSMounts.push(new CheerpJIndexedDBFolder("/files/"));
  14. cheerpjFSMounts.push(new CheerpJWebFolder("/lt/", loaderPath, null, true, useIframe ? IFrameProxyDownloader : DirectDownloader));
  15. cheerpjFSMounts.push(new CheerpJDataFolder("/str/"));
  16. cheerpjFSMounts.push(new CheerpJDevFolder("/dev/"));
  17. cheerpjFSMounts.push(new CheerpJDataFolder("/proc/"));
  18. cheerpjFSMounts.push(new CheerpJRootFolder("/"));
  19. cheerpOSAddStringFile("/proc/mounts", "none / ext4 rw,relatime 0 0\n");
  20. if(useIframe)
  21. ipfCreateIFrame(loaderPath);
  22. }
  23. function cheerpOSCreateWebFolder(appUrlPrefix)
  24. {
  25. return new CheerpJWebFolder("/app/", appUrlPrefix ? appUrlPrefix : "", null, false, DirectDownloader);
  26. }
  27. function cheerpOSNetInit(path_, tailscaleLoginUrlCb, tailscaleAuthKey, tailscaleControlUrl, tailscaleDnsIp, ipMap, tailscaleNetmapUpdateCb, cb)
  28. {
  29. self.cjEnableTailscale = true;
  30. import(path_).then((net) => {
  31. var state = net.State;
  32. var stateUpdate = (s) => {
  33. if (s == state.Running)
  34. {
  35. // Resolve promise
  36. return cb();
  37. }
  38. };
  39. var loginCb = tailscaleLoginUrlCb;
  40. if(loginCb == null)
  41. {
  42. // Use an empty callback by default
  43. loginCb = () => {};
  44. }
  45. var controlUrl = tailscaleControlUrl;
  46. if(controlUrl == null)
  47. {
  48. // Reset to undefined, it will be interpreted as the default Tailscale control plane
  49. controlUrl = undefined;
  50. }
  51. if (!ipMap)
  52. {
  53. // Reset to an empty object since when not used.
  54. ipMap = {}
  55. }
  56. net.autoConf({loginUrlCb: loginCb, stateUpdateCb: stateUpdate, netmapUpdateCb: tailscaleNetmapUpdateCb, authKey: tailscaleAuthKey, controlUrl: controlUrl, dnsIp: tailscaleDnsIp, ipMap: ipMap})
  57. .then((netExports) => {
  58. self.cjTailscaleSocket=netExports.tcpSocket;
  59. self.cjTailscaleUdpSocket=netExports.udpSocket;
  60. self.cjTailscaleParseIp=netExports.parseIP;
  61. self.cjTailscaleDumpIp=netExports.dumpIP;
  62. // NOTE: Not exporting resolve, which was used in CJ2
  63. netExports.up();
  64. });
  65. })
  66. }
  67. function cheerpOSNetDisable()
  68. {
  69. // explicit API call to the set the global state to false
  70. self.cjEnableTailscale = false;
  71. }
  72. function CheerpJFileData(parent, path, len, inodeId, permType, lastModified, uid, gid)
  73. {
  74. this.refCount = 0;
  75. this.cacheRefCount = 0;
  76. this.length = len | 0;
  77. this.dirty = 0;
  78. this.parent = parent;
  79. // path is local to the mount point
  80. this.path = path;
  81. this.inodeId = inodeId | 0;
  82. // data is linear not chunked data
  83. this.data = null;
  84. // chunks is for chunked data
  85. this.chunks = null;
  86. // mount contains the ops structure
  87. this.mount = null;
  88. // permissions and file type following 'stat' conventions
  89. this.permType = permType | 0;
  90. this.uid = uid;
  91. this.gid = gid;
  92. // last modification time, seconds from epoch
  93. this.lastModified = lastModified | 0;
  94. this.flags = 0;
  95. }
  96. CheerpJFileData.S_IFCHR = 0x2000;
  97. CheerpJFileData.S_IFDIR = 0x4000;
  98. CheerpJFileData.S_IFREG = 0x8000;
  99. CheerpJFileData.S_IFSOCK = 0xc000;
  100. CheerpJFileData.S_IFMT = 0xf000;
  101. CheerpJFileData.O_NONBLOCK = 0x800;
  102. function CheerpJFolder(mp)
  103. {
  104. this.mountPoint = mp;
  105. this.isSplit = false;
  106. // { statAsync, listAsync, makeFileData, createDirAsync, renameAsync, unlinkAsync }
  107. this.mountOps = null;
  108. // { readAsync, writeAsync, close };
  109. this.inodeOps = null;
  110. this.devId = CheerpJFolder.lastDevId;
  111. // Contains inodes
  112. this.fileCache = {};
  113. this.cacheThreads = {};
  114. // Contains CheerpJFileData entries
  115. this.inodeCache = [];
  116. CheerpJFolder.lastDevId = CheerpJFolder.lastDevId + 1|0
  117. }
  118. function folderDecRefCached(fileName, fileData)
  119. {
  120. fileData.cacheRefCount = fileData.cacheRefCount-1|0;
  121. if(fileData.cacheRefCount==0)
  122. {
  123. assert(this.inodeCache[fileData.inodeId]);
  124. delete this.inodeCache[fileData.inodeId];
  125. }
  126. }
  127. function folderGetCached(fileName)
  128. {
  129. var c = this.fileCache;
  130. if(!c.hasOwnProperty(fileName))
  131. return null;
  132. var inodeId = c[fileName];
  133. var ret = this.inodeCache[inodeId];
  134. assert(ret);
  135. return ret;
  136. }
  137. function folderSetCached(fileName, fileData)
  138. {
  139. var c = this.fileCache;
  140. fileData.cacheRefCount = fileData.cacheRefCount+1|0;
  141. if(c.hasOwnProperty(fileName))
  142. this.decRefCached(fileName, c[fileName]);
  143. var inodeId = fileData.inodeId;
  144. c[fileName] = inodeId;
  145. this.inodeCache[inodeId] = fileData;
  146. }
  147. function folderClearCached(fileName)
  148. {
  149. var c = this.fileCache;
  150. if(c.hasOwnProperty(fileName))
  151. {
  152. var inodeId = c[fileName];
  153. var data = this.inodeCache[inodeId];
  154. assert(data);
  155. this.decRefCached(fileName, data);
  156. delete c[fileName];
  157. }
  158. }
  159. CheerpJFolder.lastDevId = 1;
  160. CheerpJFolder.prototype.getCached = folderGetCached;
  161. CheerpJFolder.prototype.setCached = folderSetCached;
  162. CheerpJFolder.prototype.decRefCached = folderDecRefCached;
  163. CheerpJFolder.prototype.clearCached = folderClearCached;
  164. function CheerpJRootFolder(mp)
  165. {
  166. CheerpJFolder.call(this, mp);
  167. this.mountOps = RootOps;
  168. this.inodeOps = RootInodeOps;
  169. }
  170. CheerpJRootFolder.prototype = Object.create(CheerpJFolder.prototype);
  171. function rootStatAsync(mp, path, fileRef, cb)
  172. {
  173. if(path == "/")
  174. {
  175. fileRef.permType = CheerpJFileData.S_IFDIR | 0555;
  176. // Use the dev id as the inode id
  177. fileRef.inodeId = 0;
  178. return cb();
  179. }
  180. // Iterate over the mount points
  181. for(var i=0;i<cheerpjFSMounts.length;i++)
  182. {
  183. var f = cheerpjFSMounts[i];
  184. if(f.mountPoint == path + "/")
  185. {
  186. fileRef.permType = CheerpJFileData.S_IFDIR | 0555;
  187. // Use the dev id as the inode id
  188. fileRef.inodeId = f.devId;
  189. return cb();
  190. }
  191. }
  192. fileRef.permType = 0;
  193. return cb();
  194. }
  195. function rootListAsync(mp, path, fileRef, cb)
  196. {
  197. // Only the root itself can be listed
  198. if(path != "/"){
  199. return cb();
  200. }
  201. for(var i=0;i<cheerpjFSMounts.length-1;i++)
  202. {
  203. var f = cheerpjFSMounts[i];
  204. fileRef.push(f.mountPoint.substr(1, f.mountPoint.length - 2));
  205. }
  206. return cb();
  207. }
  208. function rootMakeFileData(mp, path, mode, uid, gid, cb)
  209. {
  210. // Only the root itself can be opened
  211. if(path != "/"){
  212. return cb(null);
  213. }
  214. var ret = new CheerpJFileData(mp, path, 0, 0, CheerpJFileData.S_IFDIR | 0777, /*lastModified*/0, /*uid*/0, /*gid*/0);
  215. ret.mount = mp.inodeOps;
  216. return cb(ret);
  217. }
  218. var RootOps = { statAsync: rootStatAsync, listAsync: rootListAsync, makeFileData: rootMakeFileData, createDirAsync: null, renameAsync: null, linkAsync: null, unlinkAsync: null };
  219. var RootInodeOps = { readAsync: null, writeAsync: null, close: null };
  220. function CheerpJWebFolder(mp, basePath, jarJSOverride, resTrace, downloader)
  221. {
  222. CheerpJFolder.call(this, mp);
  223. this.mountOps = WebOps;
  224. this.inodeOps = WebInodeOps;
  225. this.basePath = basePath;
  226. this.jarJSOverride = jarJSOverride;
  227. // Make this a member as it needs to be overridden for jnlp support
  228. this.mapPath = webMapPath;
  229. // We need to assign unique ids to each file, and they must persist over the lifetime of the application
  230. this.inodeMap = {}
  231. this.lastInode = 1;
  232. // True if we should keep track of required resource ranges
  233. this.resTrace = resTrace;
  234. this.downloader = downloader;
  235. this.chunkSize = 128 * 1024;
  236. }
  237. CheerpJWebFolder.prototype = Object.create(CheerpJFolder.prototype);
  238. function webGetInode(mp, path)
  239. {
  240. var ret = mp.inodeMap[path];
  241. if(ret !== undefined){
  242. return ret;
  243. }
  244. ret = {inodeId:mp.lastInode, permType:0, fileLength:0};
  245. mp.lastInode = mp.lastInode + 1|0;
  246. mp.inodeMap[path] = ret;
  247. return ret;
  248. }
  249. function DirectDownloader(url, metaDataOnly, chunkSize, rangeHeader)
  250. {
  251. this.url = url;
  252. this.metaDataOnly = metaDataOnly;
  253. this.responseURL = null;
  254. this.response = null;
  255. this.fileLength = -1;
  256. // The effective length of the downloaded data
  257. this.downloadLength = 0;
  258. this.failCount = 0;
  259. this.chunkSize = chunkSize;
  260. this.chunk = null;
  261. this.chunkOffset = 0;
  262. this.chunkCount = 0;
  263. this.rangeHeader = rangeHeader;
  264. }
  265. function cheerpOSSafeContentLength(contentRangeStr)
  266. {
  267. if(contentRangeStr == null)
  268. return -1;
  269. // Partial content with a Content-Range header
  270. if(!contentRangeStr.startsWith("bytes "))
  271. return -1;
  272. var segments = contentRangeStr.substr(6).split("/");
  273. if(segments.length != 2)
  274. return -1;
  275. return parseInt(segments[1]);
  276. }
  277. function ddlOnLoad(resp, downloader)
  278. {
  279. if(resp.status == 206)
  280. {
  281. downloader.responseURL = resp.url;
  282. downloader.lastModified = resp.headers.get("Last-Modified");
  283. if(downloader.responseURL.endsWith("/"))
  284. {
  285. downloader.fileLength = 0;
  286. downloader.onEnd(null);
  287. }
  288. else if(resp.headers.get("Content-Encoding") !== null)
  289. {
  290. // Be defensive against broken servers that mix up compression and partial content,
  291. // that is forbidden since it's ambiguous if the partial content is over the compressed
  292. // or uncompressed data
  293. ddlOnError(downloader, "HTTP server returned compressed partial data. That should not happen. CheerpJ cannot run.", /*fatal*/true);
  294. }
  295. else
  296. {
  297. var safeContentLength = cheerpOSSafeContentLength(resp.headers.get("Content-Range"));
  298. if(safeContentLength < 0)
  299. {
  300. // Partial content without Content-Range. The server is broken.
  301. ddlOnError(downloader, "HTTP server does not support the 'Content-Range' header. CheerpJ cannot run.", /*fatal*/true);
  302. }
  303. downloader.fileLength = safeContentLength;
  304. downloader.chunk = new Uint8Array(downloader.chunkSize);
  305. ddlOnData(downloader, resp.body.getReader());
  306. }
  307. return;
  308. }
  309. else if(resp.status == 200)
  310. {
  311. // It's only ever supposed to happen for directory redirects and index.list
  312. downloader.responseURL = resp.url;
  313. if(downloader.responseURL.endsWith("/"))
  314. {
  315. downloader.fileLength = 0;
  316. downloader.onEnd(null);
  317. }
  318. else
  319. {
  320. if(downloader.chunkSize > 0)
  321. {
  322. // Corner case, when the file is empty even reasonable servers (e.g. nginx) reply with 200
  323. if(resp.headers.get("Content-Length") != "0")
  324. {
  325. // We expected a chunk, we got a full response. The server is broken.
  326. ddlOnError(downloader, "HTTP server does not support the 'Range' header. CheerpJ cannot run.", /*fatal*/true);
  327. return;
  328. }
  329. }
  330. // Accumulate the data
  331. downloader.chunk = [];
  332. ddlOnData(downloader, resp.body.getReader());
  333. }
  334. downloader.lastModified = resp.headers.get("Last-Modified");
  335. return;
  336. }
  337. else if(resp.status == 416)
  338. {
  339. // Existing, but empty
  340. downloader.responseURL = resp.url;
  341. downloader.fileLength = 0;
  342. downloader.lastModified = resp.headers.get("Last-Modified");
  343. downloader.onEnd(null);
  344. return;
  345. }
  346. else if(resp.status == 204 || resp.status == 231 || resp.status == 403 || resp.status == 404)
  347. {
  348. downloader.responseURL = resp.url;
  349. if(resp.status == 231)
  350. downloader.responseURL += "/";
  351. downloader.onEnd(null);
  352. return;
  353. }
  354. else if(resp.status >= 500 && resp.status < 600)
  355. {
  356. ddlOnError(downloader, "Internal server error: " + resp.status, /*fatal*/false);
  357. return;
  358. }
  359. else
  360. {
  361. debugger;
  362. }
  363. }
  364. function ddlOnData(downloader, reader)
  365. {
  366. reader.read()
  367. .then(function(result){
  368. if(!result.done)
  369. {
  370. var data = result.value;
  371. if(downloader.chunkSize == 0)
  372. {
  373. downloader.chunk.push(data);
  374. downloader.downloadLength += data.length;
  375. }
  376. else
  377. {
  378. // Copy data in chunks
  379. var dataLen = data.length;
  380. var dataOff = 0;
  381. var chunkAvail = downloader.chunkSize - downloader.chunkOffset;
  382. while(dataLen > 0)
  383. {
  384. if(chunkAvail > dataLen)
  385. chunkAvail = dataLen;
  386. downloader.chunk.set(data.subarray(dataOff, dataOff + chunkAvail), downloader.chunkOffset);
  387. downloader.chunkOffset += chunkAvail;
  388. downloader.downloadLength += chunkAvail;
  389. dataOff += chunkAvail;
  390. dataLen -= chunkAvail;
  391. if(downloader.chunkOffset == downloader.chunkSize)
  392. {
  393. downloader.onData(new Uint8Array(downloader.chunk));
  394. downloader.chunkOffset = 0;
  395. chunkAvail = downloader.chunkSize;
  396. }
  397. }
  398. }
  399. ddlOnData(downloader, reader);
  400. }
  401. else
  402. {
  403. if(downloader.fileLength == -1)
  404. {
  405. downloader.fileLength = downloader.downloadLength;
  406. }
  407. if(downloader.chunkSize == 0)
  408. {
  409. downloader.onEnd(downloader.chunk);
  410. }
  411. else
  412. {
  413. if(downloader.chunkOffset != 0)
  414. downloader.onData(new Uint8Array(downloader.chunk.subarray(0, downloader.chunkOffset)));
  415. downloader.onEnd(null);
  416. }
  417. }
  418. });
  419. }
  420. function ddlOnError(downloader, err, fatal)
  421. {
  422. downloader.failCount++;
  423. if(downloader.failCount > 5 || fatal)
  424. {
  425. console.error("Network error for " + downloader.responseURL + ": " + err);
  426. downloader.onEnd(null);
  427. return;
  428. }
  429. // Try again
  430. downloader.send();
  431. }
  432. function ddlSend()
  433. {
  434. var downloader = this;
  435. var headers = {};
  436. var method = "GET";
  437. if(downloader.rangeHeader)
  438. headers["Range"] = downloader.rangeHeader;
  439. else if(downloader.metaDataOnly)
  440. headers["Range"] = "bytes=0-0";
  441. fetch(downloader.url, {"method": method, "mode": "cors", "headers" : headers})
  442. .then(function(response){
  443. ddlOnLoad(response, downloader);
  444. })
  445. .catch(function(err){
  446. ddlOnError(downloader, err);
  447. });
  448. }
  449. DirectDownloader.prototype.send = ddlSend;
  450. DirectDownloader.prototype.onData = function(value){};
  451. DirectDownloader.prototype.onEnd = function(allChunks){};
  452. function IFrameProxyDownloader(url, metaDataOnly, chunkSize, rangeHeader)
  453. {
  454. this.url = url;
  455. this.metaDataOnly = metaDataOnly;
  456. this.responseURL = null;
  457. this.response = null;
  458. this.fileLength = -1;
  459. this.chunkSize = chunkSize;
  460. this.chunk = null;
  461. this.chunkOffset = 0;
  462. this.rangeHeader = rangeHeader;
  463. assert(IFrameProxyDownloader.iframe);
  464. }
  465. function ipfMessage(e)
  466. {
  467. var d = e.data;
  468. var dl = IFrameProxyDownloader.pending[d.idx];
  469. dl.responseURL = d.responseURL;
  470. dl.fileLength = d.fileLength;
  471. if(d.from === "onData")
  472. {
  473. dl.onData(d.resp);
  474. }
  475. else if(d.from === "onEnd")
  476. {
  477. IFrameProxyDownloader.pending[d.idx] = null;
  478. dl.onEnd(d.resp);
  479. }
  480. return;
  481. }
  482. function ipfCreateIFrame(loaderPath)
  483. {
  484. var ret = document.createElement("iframe");
  485. ret.onload = function(e)
  486. {
  487. clearInterval(IFrameProxyDownloader.intervalId);
  488. var i = e.target;
  489. var c = new MessageChannel();
  490. var q = IFrameProxyDownloader.portOrQueue;
  491. c.port1.onmessage = ipfMessage;
  492. IFrameProxyDownloader.portOrQueue = c.port1;
  493. i.contentWindow.postMessage({t:"port",port:c.port2}, loaderPath, [c.port2]);
  494. // Dispatch pending loads
  495. for(var i=0;i<q.length;i=i+1|0)
  496. q[i].send();
  497. };
  498. ret.src = loaderPath + "/c.html";
  499. ret.width = "0px";
  500. ret.height = "0px";
  501. ret.style.border = "0px";
  502. ret.style.position = "fixed";
  503. ret.style.visibility = "hidden";
  504. IFrameProxyDownloader.iframe = ret;
  505. if(document.body)
  506. document.body.appendChild(ret);
  507. else
  508. document.addEventListener("DOMContentLoaded", function(e) { document.body.appendChild(IFrameProxyDownloader.iframe); })
  509. IFrameProxyDownloader.intervalId = setInterval(function(){
  510. IFrameProxyDownloader.iframe.src = loaderPath + "/c.html";
  511. }, 10000);
  512. }
  513. function ipfSend()
  514. {
  515. if(Array.isArray(IFrameProxyDownloader.portOrQueue))
  516. {
  517. // Not ready, add to queue
  518. IFrameProxyDownloader.portOrQueue.push(this);
  519. return;
  520. }
  521. var dict = {t: "load", url: this.url, metaDataOnly: this.metaDataOnly, chunkSize: this.chunkSize, rangeHeader: this.rangeHeader};
  522. for(var i = 0; i < IFrameProxyDownloader.pending.length; ++i)
  523. {
  524. if(IFrameProxyDownloader.pending[i] === null)
  525. {
  526. IFrameProxyDownloader.pending[i] = this;
  527. dict.idx = i;
  528. IFrameProxyDownloader.portOrQueue.postMessage(dict);
  529. return;
  530. }
  531. }
  532. IFrameProxyDownloader.pending.push(this);
  533. dict.idx = IFrameProxyDownloader.pending.length - 1;
  534. IFrameProxyDownloader.portOrQueue.postMessage(dict);
  535. }
  536. // Global data
  537. IFrameProxyDownloader.iframe = null;
  538. IFrameProxyDownloader.portOrQueue = [];
  539. IFrameProxyDownloader.pending = [];
  540. IFrameProxyDownloader.intervalId = 0;
  541. IFrameProxyDownloader.prototype.send = ipfSend;
  542. IFrameProxyDownloader.prototype.onData = function(value){};
  543. IFrameProxyDownloader.prototype.onEnd = function(allChunks){};
  544. function webStatAsyncImpl(mp, path, fileRef, onData, cb)
  545. {
  546. var ci = mp.inodeMap[path];
  547. if(ci !== undefined)
  548. {
  549. fileRef.fileLength = ci.fileLength | 0;
  550. fileRef.inodeId = ci.inodeId | 0;
  551. fileRef.permType = ci.permType | 0;
  552. return cb();
  553. }
  554. if(path == "")
  555. {
  556. var ci = webGetInode(mp, path);
  557. fileRef.inodeId = ci.inodeId;
  558. fileRef.permType = ci.permType = CheerpJFileData.S_IFDIR | 0555;
  559. return cb();
  560. }
  561. var url = mp.mapPath(mp, path);
  562. var rangeHeader = null;
  563. if(onData)
  564. {
  565. // The caller can also store data, download the first chunk
  566. // For small files we can avoid further requests by doing this
  567. rangeHeader = "bytes=0-"+(mp.chunkSize-1);
  568. }
  569. var dl = new mp.downloader(url, /*metaDataOnly*/true, mp.chunkSize, /*rangeHeader*/rangeHeader);
  570. if(onData)
  571. dl.onData = onData;
  572. dl.onEnd = function(allChunks) {
  573. var inodeId = 0;
  574. var permType = 0;
  575. if(this.responseURL && this.responseURL.endsWith("/"))
  576. {
  577. var ci = webGetInode(mp, path);
  578. inodeId = ci.inodeId;
  579. permType = ci.permType = CheerpJFileData.S_IFDIR | 0555;
  580. }
  581. else if(this.fileLength >= 0)
  582. {
  583. var ci = webGetInode(mp, path);
  584. inodeId = ci.inodeId;
  585. permType = ci.permType = CheerpJFileData.S_IFREG | 0444;
  586. fileRef.fileLength = ci.fileLength = this.fileLength;
  587. }
  588. fileRef.permType = permType | 0;
  589. fileRef.inodeId = inodeId | 0;
  590. if(this.lastModified)
  591. fileRef.lastModified = (Date.parse(this.lastModified) / 1000) | 0;
  592. else
  593. fileRef.lastModified = 0;
  594. return cb();
  595. };
  596. dl.send();
  597. }
  598. function webStatAsync(mp, path, fileRef, cb)
  599. {
  600. webStatAsyncImpl(mp, path, fileRef, null, cb);
  601. }
  602. function webMapPath(mp, path)
  603. {
  604. if(mp.resTrace)
  605. {
  606. var res = mp.mountPoint + path.substr(1);
  607. if(cosRuntimeResourcesRanges[res] === undefined)
  608. {
  609. cheerpjRuntimeResources.push(res);
  610. cosRuntimeResourcesRanges[res] = [];
  611. }
  612. }
  613. if(path.endsWith(".jar.js") && mp.jarJSOverride){
  614. return mp.jarJSOverride + path;
  615. }else{
  616. return mp.basePath + path;
  617. }
  618. }
  619. function webMakeFileData(mp, path, mode, uid, gid, cb)
  620. {
  621. if(mode != "r")
  622. return cb(null);
  623. var fileRef={}
  624. var chunks = [];
  625. function onData(value)
  626. {
  627. chunks.push(value);
  628. }
  629. webStatAsyncImpl(mp, path, fileRef, onData, function(){
  630. if(fileRef.permType === 0)
  631. return cb(null);
  632. var fileData = new CheerpJFileData(mp, path, fileRef.fileLength|0, fileRef.inodeId|0, fileRef.permType|0, fileRef.lastModified, /*uid*/0, /*gid*/0);
  633. fileData.mount = mp.inodeOps;
  634. fileData.chunks = chunks;
  635. if((fileRef.permType & CheerpJFileData.S_IFMT) != CheerpJFileData.S_IFREG){
  636. return cb(fileData);
  637. }
  638. // Prepare chunks
  639. var numChunks = ((fileRef.fileLength + (mp.chunkSize-1)) / mp.chunkSize) | 0;
  640. // NOTE: The first chunk might be already populated
  641. for(var i=chunks.length;i<numChunks;i++)
  642. chunks[i] = null;
  643. return cb(fileData);
  644. });
  645. }
  646. function webReadAsync(fileData, fileOffset, buf, off, len, flags, cb)
  647. {
  648. assert(fileOffset <= fileData.length);
  649. if(fileOffset + len > fileData.length) len = fileData.length - fileOffset;
  650. // EOF
  651. if(len == 0){
  652. return cb(0);
  653. }
  654. var mp = fileData.parent;
  655. var chunkSize = mp.chunkSize;
  656. var startChunk = fileOffset / chunkSize | 0;
  657. var endChunk = (fileOffset + len - 1) / chunkSize | 0;
  658. var fileRef = {pendingLoads: 0};
  659. if(mp.resTrace){
  660. var startOffset = startChunk * chunkSize;
  661. var endOffset = (endChunk + 1) * chunkSize
  662. var res = mp.mountPoint + fileData.path.substr(1);
  663. // Keep the array ordered and remove duplicates, ranges are exclusive
  664. var ranges = cosRuntimeResourcesRanges[res];
  665. var i = 0;
  666. for(;i<ranges.length;i+=2)
  667. {
  668. if(ranges[i] < startOffset)
  669. continue;
  670. break;
  671. }
  672. if(i > 0 && ranges[i-1] >= startOffset)
  673. {
  674. // Merge on the left
  675. if(ranges[i-1] < endOffset)
  676. {
  677. ranges[i-1] = endOffset;
  678. // Check if we also need to merge on the right and remove an entry
  679. if(ranges[i] <= endOffset)
  680. {
  681. if(ranges[i+1] > endOffset)
  682. {
  683. ranges[i-1] = ranges[i+1];
  684. }
  685. ranges.splice(i, 2);
  686. }
  687. }
  688. }
  689. else if(i != ranges.length && ranges[i] <= endOffset)
  690. {
  691. // Merge on the right
  692. ranges[i] = startOffset;
  693. }
  694. else
  695. {
  696. // Add an entry
  697. ranges.splice(i, 0, startOffset, endOffset);
  698. }
  699. // Sanity checks
  700. for(var i=1;i<ranges.length;i++)
  701. {
  702. assert(ranges[i] > ranges[i-1]);
  703. }
  704. }
  705. return webReadAsyncLoop(fileData, fileOffset, buf, off, len, fileRef, startChunk, endChunk, cb);
  706. }
  707. function webBuildRange(fileData, chunkStart, chunkEnd)
  708. {
  709. var startByte = chunkStart * fileData.parent.chunkSize;
  710. var endByte = ((chunkEnd + 1) * fileData.parent.chunkSize) - 1;
  711. if(endByte >= fileData.length)
  712. endByte = fileData.length - 1;
  713. return "bytes="+startByte+"-"+endByte;
  714. }
  715. function webDownloadRange(fileData, fileOffset, buf, off, len, startChunk, endChunk, fileRef, cb)
  716. {
  717. var url = fileData.path;
  718. var rangeHeader = webBuildRange(fileData, startChunk, endChunk);
  719. url = webMapPath(fileData.parent, url);
  720. var dl = new fileData.parent.downloader(url, /*metaDataOnly*/false, fileData.parent.chunkSize, rangeHeader);
  721. dl.curChunk = startChunk;
  722. dl.onData = function(value)
  723. {
  724. var tmp = fileData.chunks[this.curChunk];
  725. fileData.chunks[this.curChunk] = value;
  726. this.curChunk++;
  727. for(var k = 0; k < tmp.length; k++)
  728. {
  729. tmp[k]();
  730. }
  731. // NOTE: pendingLoads can go negative due to read-ahead
  732. fileRef.pendingLoads--;
  733. if(fileRef.pendingLoads !== 0)
  734. return;
  735. webReadAsyncEnd(fileData, fileOffset, buf, off, len, cb);
  736. };
  737. dl.send();
  738. }
  739. function webReadAsyncLoop(fileData, fileOffset, buf, off, len, fileRef, startChunk, endChunk, cb)
  740. {
  741. var pendingStartChunk = startChunk;
  742. for(var curChunk=startChunk;curChunk<=endChunk;curChunk++){
  743. var curData = fileData.chunks[curChunk];
  744. if(curData)
  745. {
  746. if(pendingStartChunk < curChunk)
  747. {
  748. // Download a range up to this chunk, which we already have
  749. webDownloadRange(fileData, fileOffset, buf, off, len, pendingStartChunk, curChunk - 1, fileRef, cb)
  750. }
  751. pendingStartChunk = curChunk + 1;
  752. if(curData instanceof Uint8Array)
  753. {
  754. continue;
  755. }
  756. else
  757. {
  758. // The double increment here is required to avoid waking up threads too early
  759. // due to the read-ahead block arriving sooner
  760. fileRef.pendingLoads+=2;
  761. curData.push(function()
  762. {
  763. // If the read-ahead has already completed we will reach -1
  764. fileRef.pendingLoads-=2;
  765. if(fileRef.pendingLoads > 0)
  766. return;
  767. webReadAsyncEnd(fileData, fileOffset, buf, off, len, cb);
  768. });
  769. }
  770. }
  771. else
  772. {
  773. // Nothing to do, accumulate the range
  774. fileRef.pendingLoads++;
  775. fileData.chunks[curChunk] = [];
  776. }
  777. }
  778. // Do read-ahead, but do not wait for the results
  779. var fwdAhead = endChunk + 1;
  780. var bwdAhead = startChunk - 1;
  781. var bwdDownloader = null;
  782. if(fwdAhead < fileData.chunks.length && fileData.chunks[fwdAhead] == null)
  783. {
  784. // Extend the range, but don't increment pendingLoads
  785. endChunk = fwdAhead;
  786. fileData.chunks[fwdAhead] = [];
  787. }
  788. else if(bwdAhead >= 0 && fileData.chunks[bwdAhead] == null)
  789. {
  790. var url = fileData.path;
  791. var rangeHeader = webBuildRange(fileData, bwdAhead, bwdAhead);
  792. url = webMapPath(fileData.parent, url);
  793. bwdDownloader = new fileData.parent.downloader(url, /*metaDataOnly*/false, fileData.parent.chunkSize, rangeHeader);
  794. fileData.chunks[bwdAhead] = [];
  795. bwdDownloader.curChunk = bwdAhead;
  796. bwdDownloader.onData = function(value)
  797. {
  798. var tmp = fileData.chunks[this.curChunk];
  799. fileData.chunks[this.curChunk] = value;
  800. for(var k = 0; k < tmp.length; k++)
  801. {
  802. tmp[k]();
  803. }
  804. };
  805. }
  806. if(pendingStartChunk <= endChunk)
  807. {
  808. webDownloadRange(fileData, fileOffset, buf, off, len, pendingStartChunk, endChunk, fileRef, cb)
  809. }
  810. if(bwdDownloader)
  811. {
  812. bwdDownloader.send();
  813. }
  814. if(fileRef.pendingLoads !== 0){
  815. return;
  816. }
  817. return webReadAsyncEnd(fileData, fileOffset, buf, off, len, cb);
  818. }
  819. function webReadAsyncEnd(fileData, fileOffset, buf, off, len, cb)
  820. {
  821. // All chunks are now loaded
  822. var chunkSize = fileData.parent.chunkSize;
  823. var curChunk = fileOffset / chunkSize | 0;
  824. var curOffset = fileOffset - (curChunk*chunkSize) | 0;
  825. var i=0;
  826. while(i<len)
  827. {
  828. var c = fileData.chunks[curChunk];
  829. if((len-i) < (chunkSize-curOffset))
  830. chunkSize = curOffset+(len-i);
  831. for(var j=curOffset;j<chunkSize;j++)
  832. {
  833. buf[off+i>>>0]=c[j];
  834. i++;
  835. }
  836. curChunk++;
  837. curOffset=0;
  838. }
  839. assert(i===len);
  840. return cb(len);
  841. }
  842. function webListAsync(mp, path, fileRef, cb)
  843. {
  844. var url = mp.mapPath(mp, path+"/index.list");
  845. var dl = new mp.downloader(url, /*metaDataOnly*/false, /*chunkSize*/0, /*rangeHeader*/null);
  846. dl.fileRef = fileRef;
  847. dl.onEnd = function(allChunks)
  848. {
  849. if(allChunks != null)
  850. {
  851. var res = "";
  852. for(var i=0;i<allChunks.length;i++)
  853. {
  854. var chunk = allChunks[i];
  855. var chunkLen = chunk.length;
  856. for(var j=0;j<chunkLen;j++)
  857. res += String.fromCharCode(chunk[j]);
  858. }
  859. var files = res.split("\n");
  860. var filesLen = files.length;
  861. for(var i=0;i<filesLen;i++)
  862. {
  863. if(files[i].length)
  864. fileRef.push(files[i]);
  865. }
  866. }
  867. cb();
  868. };
  869. dl.send();
  870. }
  871. var WebOps = { statAsync: webStatAsync, listAsync: webListAsync, makeFileData: webMakeFileData, createDirAsync: null, renameAsync: null, linkAsync: null, unlinkAsync: null };
  872. var WebInodeOps = { readAsync: webReadAsync, writeAsync: null, close: null };
  873. function CheerpJIndexedDBFolder(mp)
  874. {
  875. CheerpJFolder.call(this, mp);
  876. this.mountOps = IdbOps;
  877. this.inodeOps = IdbInodeOps;
  878. this.isSplit = true;
  879. this.dbConnection = null;
  880. this.dEntries = {};
  881. }
  882. CheerpJIndexedDBFolder.prototype = Object.create(CheerpJFolder.prototype);
  883. function idbTrap(e)
  884. {
  885. debugger
  886. }
  887. function idbStatAsync(mp, path, fileRef, cb)
  888. {
  889. idbEnsureDBConnection(mp, function()
  890. {
  891. // We get here after dbConnection is valid
  892. assert(path[path.length-1]!='/');
  893. var tx = mp.dbConnection.transaction("files", "readonly");
  894. var store = tx.objectStore("files");
  895. // Find the directory
  896. var req = store.get(path);
  897. assert(req.readyState != "done");
  898. req.fileRef = fileRef;
  899. req.onerror = idbTrap;
  900. function gotRes(fileRef, res)
  901. {
  902. if(!res)
  903. {
  904. fileRef.permType = 0;
  905. }
  906. else
  907. {
  908. fileRef.inodeId = res.inodeId;
  909. fileRef.uid = res.uid;
  910. fileRef.gid = res.gid;
  911. if(res.hasOwnProperty("permType"))
  912. fileRef.permType = res.permType;
  913. else if(res.type == "dir")
  914. fileRef.permType = CheerpJFileData.S_IFDIR | 0777;
  915. else if(res.type == "s")
  916. fileRef.permType = CheerpJFileData.S_IFSOCK | 0666;
  917. else
  918. {
  919. assert(res.type == "file");
  920. fileRef.permType = CheerpJFileData.S_IFREG | 0666;
  921. }
  922. if(res.type == "file")
  923. fileRef.fileLength = res.contents == null ? 0 : res.contents.length;
  924. else if(res.type == "special")
  925. fileRef.contents = res.contents;
  926. fileRef.lastModified = res.lastModified|0;
  927. }
  928. return cb();
  929. }
  930. req.onsuccess = function(e)
  931. {
  932. this.onerror = null;
  933. this.onsuccess = null;
  934. var res = this.result;
  935. if(typeof(res) == "number")
  936. {
  937. assert(store != null);
  938. var req = store.get(res);
  939. assert(req.readyState != "done");
  940. req.fileRef = this.fileRef;
  941. req.onerror = idbTrap;
  942. req.onsuccess = function(e)
  943. {
  944. this.onerror = null;
  945. this.onsuccess = null;
  946. var res = this.result;
  947. return gotRes(this.fileRef, res);
  948. };
  949. return;
  950. }
  951. return gotRes(this.fileRef, res);
  952. }
  953. });
  954. }
  955. function idbListAsync(mp,path, fileRef, cb)
  956. {
  957. idbEnsureDBConnection(mp, function()
  958. {
  959. // We get here after dbConnection is valid
  960. assert(path[path.length-1]!='/');
  961. var tx = mp.dbConnection.transaction("files", "readonly");
  962. var store = tx.objectStore("files");
  963. // Find the directory
  964. var req = store.get(path);
  965. assert(req.readyState != "done");
  966. req.fileRef = fileRef;
  967. req.onerror = idbTrap;
  968. req.onsuccess = function(e)
  969. {
  970. this.onerror = null;
  971. this.onsuccess = null;
  972. var res = this.result;
  973. if(res && res.type == "dir")
  974. {
  975. var c = res.contents;
  976. for(var i=0;i<c.length;i++)
  977. fileRef.push(c[i].substr(1));
  978. }
  979. // If there is no event, this is an sync handling
  980. if(e){
  981. return cb();
  982. }
  983. }
  984. if(req.readyState == "done"){
  985. req.onsuccess(null);
  986. return cb();
  987. }else{
  988. return;
  989. }
  990. });
  991. }
  992. function idbCreateDirAsync(mp, path, fileRef, mode, uid, gid, cb)
  993. {
  994. idbEnsureDBConnection(mp, function(){
  995. // We get here after dbConnection is valid
  996. assert(path[path.length-1]!='/');
  997. // Find where the parent directory ends
  998. var parentEnd = path.lastIndexOf('/');
  999. assert(parentEnd >= 0);
  1000. var parentPath = path.substring(0, parentEnd);
  1001. var tx = mp.dbConnection.transaction("files", "readwrite");
  1002. var store = tx.objectStore("files");
  1003. function gotParent(res, asyncThread)
  1004. {
  1005. if(!res)
  1006. fileRef.exists = 0;
  1007. else
  1008. fileRef.exists = (res.type == "dir" ? 5 : 3);
  1009. if(fileRef.exists !== 5)
  1010. {
  1011. // Parent directory does not exist or it's not a directory
  1012. if(asyncThread)
  1013. {
  1014. fileRef.exists = 0;
  1015. return asyncThread();
  1016. }
  1017. return;
  1018. }
  1019. res = idbAddDEntry(mp, parentPath, res);
  1020. // Add this new object to the parent Path
  1021. var childPath = path.substring(parentPath.length);
  1022. assert(childPath[0]=='/');
  1023. for(var i=0;i<res.contents.length;i++)
  1024. {
  1025. if(res.contents[i] == childPath)
  1026. {
  1027. if(asyncThread)
  1028. {
  1029. fileRef.exists = 5;
  1030. return asyncThread();
  1031. }
  1032. return;
  1033. }
  1034. }
  1035. res.contents.push(childPath);
  1036. store.put(res, parentPath);
  1037. var cachedDE = idbCheckDEntry(mp, "");
  1038. var curInodeId = cachedDE.nextInode++;
  1039. store.put(cachedDE, "");
  1040. store.put({ type: "dir", contents:[], inodeId: curInodeId, permType: CheerpJFileData.S_IFDIR | (mode & 01777), uid: uid, gid: gid, lastModified: (Date.now() / 1000)|0}, path);
  1041. if(asyncThread)
  1042. {
  1043. fileRef.exists = 5;
  1044. return asyncThread();
  1045. }
  1046. }
  1047. var cachedDE = idbCheckDEntry(mp, parentPath);
  1048. if(cachedDE)
  1049. {
  1050. gotParent(cachedDE, null);
  1051. return cb();
  1052. }
  1053. else
  1054. {
  1055. // Find the parent
  1056. var req = store.get(parentPath);
  1057. if(req.readyState == "done")
  1058. {
  1059. gotParent(req.result, null);
  1060. return cb();
  1061. }
  1062. else
  1063. {
  1064. req.onerror = idbTrap;
  1065. req.onsuccess = function(e) { this.onerror = null; this.onsuccess = null; gotParent(this.result, cb); }
  1066. return;
  1067. }
  1068. }
  1069. });
  1070. }
  1071. function idbCheckDEntry(mp, path)
  1072. {
  1073. // Does it exists already?
  1074. var ret = mp.dEntries[path];
  1075. if(!ret){
  1076. return null;
  1077. }
  1078. // Yep, mark it for LRU
  1079. ret.ts = Date.now();
  1080. return ret.res;
  1081. }
  1082. function idbAddDEntry(mp, path, res)
  1083. {
  1084. var ret = idbCheckDEntry(mp, path);
  1085. if(ret){
  1086. return ret;
  1087. }
  1088. mp.dEntries[path] = { res: res, ts: Date.now() };
  1089. return res;
  1090. }
  1091. function idbDelDEntry(mp, path)
  1092. {
  1093. delete mp.dEntries[path];
  1094. }
  1095. function idbDecRefIndirect(store, fileRef)
  1096. {
  1097. fileRef.refCount = fileRef.refCount-1|0;
  1098. if(fileRef.refCount == 0)
  1099. store.delete(fileRef.inodeId);
  1100. else
  1101. store.put(fileRef, fileRef.inodeId);
  1102. }
  1103. function idbResolve(mp, path, fileRef, cb)
  1104. {
  1105. var parentPath = null;
  1106. // We get here after dbConnection is valid
  1107. if(path.length == 0)
  1108. {
  1109. // Getting the root directory, special case this
  1110. parentPath = path;
  1111. }
  1112. else
  1113. {
  1114. assert(path[path.length-1]!='/');
  1115. // Find where the parent directory ends
  1116. var parentEnd = path.lastIndexOf('/');
  1117. assert(parentEnd >= 0);
  1118. parentPath = path.substring(0, parentEnd);
  1119. }
  1120. function gotFile(parentRes, res, asyncThread, store)
  1121. {
  1122. if(typeof(res) == "number")
  1123. {
  1124. assert(store != null);
  1125. assert(asyncThread != null);
  1126. var req = store.get(res);
  1127. assert(req.readyState != "done");
  1128. req.onerror = idbTrap;
  1129. req.onsuccess = function(e)
  1130. {
  1131. this.onerror = null;
  1132. this.onsuccess = null;
  1133. var res = this.result;
  1134. gotFile(parentRes, res, asyncThread, store);
  1135. }
  1136. return;
  1137. }
  1138. fileRef.parentPath = parentPath;
  1139. fileRef.parentRes = parentRes;
  1140. fileRef.res = res;
  1141. if(asyncThread)
  1142. {
  1143. return asyncThread();
  1144. }
  1145. }
  1146. function gotParent(res, asyncThread, store)
  1147. {
  1148. if(!res || res.type != "dir")
  1149. {
  1150. // Parent directory does not exist or it's not a directory
  1151. fileRef.fileData = null;
  1152. if(asyncThread)
  1153. {
  1154. return asyncThread();
  1155. }
  1156. return false;
  1157. }
  1158. var parentRes = idbAddDEntry(mp, parentPath, res);
  1159. // The file may already exists
  1160. var filePath = path.substr(parentPath.length);
  1161. var fileIndex = res.contents.indexOf(filePath);
  1162. if(filePath == "")
  1163. {
  1164. gotFile(parentRes, parentRes, asyncThread, store);
  1165. return false;
  1166. }
  1167. else if(fileIndex < 0)
  1168. {
  1169. gotFile(parentRes, null, asyncThread, store);
  1170. return false;
  1171. }
  1172. else
  1173. {
  1174. if(store == null)
  1175. {
  1176. var tx = mp.dbConnection.transaction("files", "readonly");
  1177. var store = tx.objectStore("files");
  1178. }
  1179. var req = store.get(path);
  1180. assert(req.readyState != "done");
  1181. req.onerror = idbTrap;
  1182. req.onsuccess = function(e)
  1183. {
  1184. this.onerror = null;
  1185. this.onsuccess = null;
  1186. var res = this.result;
  1187. gotFile(parentRes, res, asyncThread ? asyncThread : cb, store);
  1188. }
  1189. return true;
  1190. }
  1191. }
  1192. var cachedDE = idbCheckDEntry(mp, parentPath);
  1193. var doAsync = false;
  1194. if(cachedDE)
  1195. {
  1196. doAsync = gotParent(cachedDE, null, null);
  1197. }
  1198. else
  1199. {
  1200. // Find the parent
  1201. var tx = mp.dbConnection.transaction("files", "readonly");
  1202. var store = tx.objectStore("files");
  1203. var req = store.get(parentPath);
  1204. assert(req.readyState != "done");
  1205. if(req.readyState == "done")
  1206. doAsync = gotParent(null, null, store);
  1207. else
  1208. {
  1209. req.onerror = idbTrap;
  1210. req.onsuccess = function(e) { this.onerror = null; this.onsuccess = null; gotParent(this.result, cb, this.source); }
  1211. doAsync = true;
  1212. assert(req.readyState != "done");
  1213. }
  1214. }
  1215. if(doAsync)
  1216. {
  1217. return;
  1218. }
  1219. return cb();
  1220. }
  1221. function idbMakeFileData(mp, path, mode, uid, gid, cb)
  1222. {
  1223. assert(mp.isSplit);
  1224. var fileRef={fileData:null, parentPath: null, parentRes:null, res:null};
  1225. idbEnsureDBConnection(mp, function(){
  1226. idbResolve(mp, path, fileRef, function(){
  1227. var tx = mp.dbConnection.transaction("files", "readwrite");
  1228. var store = tx.objectStore("files");
  1229. if(fileRef.parentRes == null)
  1230. {
  1231. // Parent directory does not exists
  1232. return cb(null);
  1233. }
  1234. else
  1235. {
  1236. var parentPath = fileRef.parentPath;
  1237. var parentRes = fileRef.parentRes;
  1238. var res = fileRef.res;
  1239. var fileExists = res && (res.type == "file" || res.type == "dir");
  1240. var fileIsIndirect = res && res.hasOwnProperty("refCount");
  1241. if(mode == "r" || ((mode == "r+" || mode == "w") && fileExists))
  1242. {
  1243. if(fileExists)
  1244. {
  1245. if(res.type == "file")
  1246. {
  1247. var data = res.contents;
  1248. var chunks = [];
  1249. if(mode == "w")
  1250. data = null;
  1251. else if(data)
  1252. {
  1253. var cur = 0;
  1254. var len = data.length;
  1255. var chunkSize = 1024*1024;
  1256. while(cur < len)
  1257. {
  1258. var thisChunkSize = (len - cur) < chunkSize ? len - cur : chunkSize;
  1259. var c = new Uint8Array(chunkSize);
  1260. c.set(data.subarray(cur, cur+thisChunkSize));
  1261. chunks.push(c);
  1262. cur += thisChunkSize;
  1263. }
  1264. assert(cur == len);
  1265. }
  1266. var permType = res.permType ? res.permType : CheerpJFileData.S_IFREG | 0666;
  1267. if(mp.inodeCache[res.inodeId])
  1268. {
  1269. fileRef.fileData = mp.inodeCache[res.inodeId];
  1270. fileRef.path = null;
  1271. }
  1272. else
  1273. {
  1274. fileRef.fileData = new CheerpJFileData(mp, fileIsIndirect ? null : path, data?data.length:0, res.inodeId, permType, res.lastModified|0, res.uid, res.gid);
  1275. fileRef.fileData.mount = mp.inodeOps;
  1276. fileRef.fileData.chunks = chunks;
  1277. }
  1278. if(mode == "w")
  1279. fileRef.fileData.dirty = 1;
  1280. }
  1281. else if(res.type == "dir")
  1282. {
  1283. // It is legal to get an fd to a directory
  1284. var permType = res.permType ? res.permType : CheerpJFileData.S_IFDIR | 0777;
  1285. // It not legal to have multiple names for the same directory
  1286. assert(!mp.inodeCache[res.inodeId]);
  1287. fileRef.fileData = new CheerpJFileData(mp, path, 0, res.inodeId, permType, res.lastModified|0, res.uid, res.gid);
  1288. fileRef.fileData.mount = mp.inodeOps;
  1289. }
  1290. }
  1291. else
  1292. fileRef.fileData = null;
  1293. }
  1294. else if(mode == "r+" || mode == "w")
  1295. {
  1296. // w is truncate, so we always update the file
  1297. assert(!fileExists);
  1298. {
  1299. // Add this new object to the parent Path
  1300. var childPath = path.substring(parentPath.length);
  1301. assert(childPath[0]=='/');
  1302. assert(parentRes.contents);
  1303. parentRes.contents.push(childPath);
  1304. store.put(parentRes, parentPath);
  1305. }
  1306. // TODO: Check if the file is actually a dir
  1307. var cachedDE = idbCheckDEntry(mp, "");
  1308. var curInodeId = cachedDE.nextInode++;
  1309. store.put(cachedDE, "");
  1310. var lastModified = (Date.now() / 1000)|0;
  1311. store.put({ type: "file", contents:null, inodeId: curInodeId, uid: uid, gid: gid, lastModified: lastModified }, path);
  1312. fileRef.fileData = new CheerpJFileData(mp, path, 0, curInodeId, CheerpJFileData.S_IFREG | 0666, lastModified, uid, gid);
  1313. fileRef.fileData.dirty = 1;
  1314. fileRef.fileData.mount = mp.inodeOps;
  1315. fileRef.fileData.chunks = [];
  1316. }
  1317. else if(mode == "s")
  1318. {
  1319. if(fileExists)
  1320. fileRef.fileData = null;
  1321. else
  1322. {
  1323. // Add this new object to the parent Path
  1324. var childPath = path.substring(parentPath.length);
  1325. assert(childPath[0]=='/');
  1326. assert(parentRes.contents);
  1327. parentRes.contents.push(childPath);
  1328. store.put(parentRes, parentPath);
  1329. var cachedDE = idbCheckDEntry(mp, "");
  1330. var curInodeId = cachedDE.nextInode++;
  1331. store.put(cachedDE, "");
  1332. var lastModified = (Date.now() / 1000)|0;
  1333. store.put({ type: "special", contents:null, inodeId: curInodeId, uid: uid, gid: gid, lastModified: lastModified }, path);
  1334. fileRef.fileData = new CheerpJFileData(mp, path, 0, curInodeId, CheerpJFileData.S_IFSOCK | 0666, lastModified, uid, gid);
  1335. fileRef.fileData.dirty = 1;
  1336. fileRef.fileData.mount = mp.inodeOps;
  1337. }
  1338. }
  1339. else
  1340. debugger
  1341. }
  1342. // The returned value may be null if the file can't be created
  1343. return cb(fileRef.fileData);
  1344. });
  1345. });
  1346. }
  1347. function idbRenameAsync(mp, srcPath, dstPath, cb)
  1348. {
  1349. idbEnsureDBConnection(mp, function(){
  1350. // The whole operation should be atomic, using a single transaction should do it
  1351. // TODO: What about the file cache atomicity? That is handled in the caller.
  1352. var srcFileRef={fileData:null, parentPath: null, parentRes:null, res:null};
  1353. idbResolve(mp, srcPath, srcFileRef, function(){
  1354. if(srcFileRef.res == null){
  1355. // File does not exists
  1356. return cb(0);
  1357. }
  1358. var dstFileRef={fileData:null, parentPath: null, parentRes:null, res:null};
  1359. idbResolve(mp, dstPath, dstFileRef, function()
  1360. {
  1361. assert(dstFileRef.res == null || !dstFileRef.res.hasOwnProperty("refCount"));
  1362. if(dstFileRef.parentRes == null){
  1363. // Parent directory does not exists
  1364. return cb(0);
  1365. }
  1366. // TODO: Support renaming directories
  1367. if(srcFileRef.res.type == "dir"){
  1368. return cb(0);
  1369. }
  1370. var tx = mp.dbConnection.transaction("files", "readwrite");
  1371. var store = tx.objectStore("files");
  1372. // 1) Remove src file from parent directory
  1373. var srcChildPath = srcPath.substr(srcFileRef.parentPath.length);
  1374. var srcParentIndex = srcFileRef.parentRes.contents.indexOf(srcChildPath);
  1375. assert(srcParentIndex >= 0);
  1376. srcFileRef.parentRes.contents.splice(srcParentIndex, 1);
  1377. store.put(srcFileRef.parentRes, srcFileRef.parentPath);
  1378. // 2) Remove src from the DB
  1379. store.delete(srcPath);
  1380. // 3) Add the file to the dst directory
  1381. var dstChildPath = dstPath.substr(dstFileRef.parentPath.length);
  1382. var dstParentIndex = dstFileRef.parentRes.contents.indexOf(dstChildPath);
  1383. if(dstParentIndex < 0){
  1384. dstFileRef.parentRes.contents.push(dstChildPath);
  1385. store.put(dstFileRef.parentRes, dstFileRef.parentPath);
  1386. }
  1387. // 4) Store the contents to the dst path
  1388. store.put(srcFileRef.res, dstPath);
  1389. tx.oncomplete = function(e){
  1390. return cb(1);
  1391. }
  1392. });
  1393. });
  1394. });
  1395. }
  1396. function idbLinkAsync(mp, srcPath, dstPath, cb)
  1397. {
  1398. idbEnsureDBConnection(mp, function(){
  1399. // The whole operation should be atomic, using a single transaction should do it
  1400. var srcFileRef={fileData:null, parentPath: null, parentRes:null, res:null};
  1401. idbResolve(mp, srcPath, srcFileRef, function(){
  1402. if(srcFileRef.res == null){
  1403. // File does not exists
  1404. return cb(0);
  1405. }
  1406. var dstFileRef={fileData:null, parentPath: null, parentRes:null, res:null};
  1407. idbResolve(mp, dstPath, dstFileRef, function()
  1408. {
  1409. if(dstFileRef.res != null){
  1410. // Dest file already exists
  1411. return cb(0);
  1412. }
  1413. if(dstFileRef.parentRes == null){
  1414. // Parent directory does not exists
  1415. return cb(0);
  1416. }
  1417. // Hard-linking directories is not supported
  1418. if(srcFileRef.res.type == "dir"){
  1419. return cb(0);
  1420. }
  1421. var tx = mp.dbConnection.transaction("files", "readwrite");
  1422. var store = tx.objectStore("files");
  1423. // 1) Check if srcFileRef needs to become indirect
  1424. if(!srcFileRef.res.hasOwnProperty("refCount")){
  1425. var res = srcFileRef.res;
  1426. var inodeId = res.inodeId;
  1427. assert(inodeId);
  1428. store.put(inodeId, srcPath);
  1429. res.refCount = 1;
  1430. var cachedFileData = mp.inodeCache[inodeId];
  1431. if(cachedFileData){
  1432. assert(cachedFileData.path);
  1433. cachedFileData.path = null;
  1434. }
  1435. }
  1436. // 2) Add the file to the dst directory
  1437. var dstChildPath = dstPath.substr(dstFileRef.parentPath.length);
  1438. var dstParentIndex = dstFileRef.parentRes.contents.indexOf(dstChildPath);
  1439. assert(dstParentIndex < 0);
  1440. dstFileRef.parentRes.contents.push(dstChildPath);
  1441. store.put(dstFileRef.parentRes, dstFileRef.parentPath);
  1442. // 3) Store the contents to the dst path, as indirect
  1443. srcFileRef.res.refCount = srcFileRef.res.refCount+1|0;
  1444. store.put(srcFileRef.res, srcFileRef.res.inodeId);
  1445. store.put(srcFileRef.res.inodeId, dstPath);
  1446. tx.oncomplete = function(e){
  1447. return cb(1);
  1448. }
  1449. });
  1450. });
  1451. });
  1452. }
  1453. function idbReadAsync(fileData, fileOffset, buf, off, len, flags, cb)
  1454. {
  1455. var chunkSize = 1024*1024;
  1456. var curChunk = fileOffset / chunkSize | 0;
  1457. if(fileOffset + len > fileData.length)
  1458. len = fileData.length - fileOffset;
  1459. if(len<=0){
  1460. return cb(0);
  1461. }
  1462. var endChunk = (fileOffset + len - 1) / chunkSize | 0;
  1463. var fileRef={cheerpjDownload:null};
  1464. while(len && curChunk <= endChunk){
  1465. assert(fileData.chunks[curChunk]);
  1466. var curChunk = curChunk+1|0;
  1467. }
  1468. // All chunks are now loaded
  1469. var curChunk = fileOffset / chunkSize | 0;
  1470. var curOffset = fileOffset - (curChunk*chunkSize) | 0;
  1471. var i=0;
  1472. while(i<len)
  1473. {
  1474. var c = fileData.chunks[curChunk];
  1475. if((len-i) < (chunkSize-curOffset))
  1476. chunkSize = curOffset+(len-i);
  1477. for(var j=curOffset;j<chunkSize;j++)
  1478. {
  1479. buf[off+i>>>0]=c[j];
  1480. i++;
  1481. }
  1482. curChunk++;
  1483. curOffset=0;
  1484. }
  1485. assert(i==len);
  1486. return cb(len);
  1487. }
  1488. function idbWriteAsync(fileData, fileOffset, buf, off, len, cb)
  1489. {
  1490. var chunkSize = 1024*1024;
  1491. var curChunk = 0;
  1492. var endChunk = (fileOffset + len) / chunkSize | 0;
  1493. // Create all chunks first
  1494. while(curChunk <= endChunk)
  1495. {
  1496. if(fileData.chunks[curChunk])
  1497. {
  1498. var curChunk = curChunk+1|0;
  1499. continue;
  1500. }
  1501. fileData.chunks[curChunk]=new Uint8Array(chunkSize);
  1502. curChunk = curChunk+1|0;
  1503. }
  1504. var curChunk = fileOffset / chunkSize | 0;
  1505. var curOffset = fileOffset - (curChunk*chunkSize) | 0;
  1506. var i=0;
  1507. while(i<len)
  1508. {
  1509. var c = fileData.chunks[curChunk];
  1510. if((len-i) < (chunkSize-curOffset))
  1511. chunkSize = curOffset+(len-i);
  1512. for(var j=curOffset;j<chunkSize;j++)
  1513. {
  1514. c[j]=buf[off+i>>>0];
  1515. i++;
  1516. }
  1517. curChunk++;
  1518. curOffset=0;
  1519. }
  1520. assert(i==len);
  1521. if((fileOffset+len|0) > fileData.length)
  1522. {
  1523. fileData.length = fileOffset + len | 0;
  1524. }
  1525. return cb(len);
  1526. }
  1527. function idbCommitFileData(fileData, cb)
  1528. {
  1529. if (!fileData.dirty)
  1530. return cb();
  1531. var mp = fileData.parent;
  1532. assert(mp.isSplit);
  1533. assert(mp.dbConnection);
  1534. var fileRef = null;
  1535. var filePath = fileData.path;
  1536. if(filePath == null){
  1537. assert(fileData.inodeId > 0);
  1538. filePath = fileData.inodeId;
  1539. }
  1540. // For non-files we only update permType
  1541. if((fileData.permType & CheerpJFileData.S_IFMT) != CheerpJFileData.S_IFREG){
  1542. fileRef={};
  1543. idbResolve(mp, filePath, fileRef, function()
  1544. {
  1545. assert(fileRef.res);
  1546. fileRef = fileRef.res;
  1547. fileRef.permType = fileData.permType;
  1548. if((fileData.permType & CheerpJFileData.S_IFMT) != CheerpJFileData.S_IFDIR){
  1549. fileRef.contents = fileData.chunks;
  1550. }
  1551. var tx = mp.dbConnection.transaction("files", "readwrite");
  1552. var store = tx.objectStore("files");
  1553. tx.oncomplete = function()
  1554. {
  1555. cb();
  1556. };
  1557. fileData.dirty = 0;
  1558. store.put(fileRef, filePath);
  1559. });
  1560. }else{
  1561. var contents = new Uint8Array(fileData.length);
  1562. var chunkSize = 1024*1024;
  1563. var curChunk = 0;
  1564. for(var i=0;i<fileData.length;)
  1565. {
  1566. var c = fileData.chunks[curChunk];
  1567. if(fileData.length - i < chunkSize)
  1568. c = c.subarray(0, fileData.length-i)
  1569. contents.set(c, i);
  1570. curChunk++;
  1571. i += c.length;
  1572. }
  1573. fileRef = { type: "file", contents:contents, inodeId: fileData.inodeId, permType: fileData.permType, uid: fileData.uid, gid: fileData.gid, lastModified: (Date.now() / 1000)|0 };
  1574. var tx = mp.dbConnection.transaction("files", "readwrite");
  1575. var store = tx.objectStore("files");
  1576. tx.oncomplete = function()
  1577. {
  1578. cb();
  1579. };
  1580. fileData.dirty = 0;
  1581. store.put(fileRef, filePath);
  1582. }
  1583. }
  1584. function idbUnlinkAsync(mp, path, cb)
  1585. {
  1586. assert(mp.isSplit);
  1587. var fileRef={fileData:null, parentPath: null, parentRes:null, res:null};
  1588. idbEnsureDBConnection(mp, function(){
  1589. idbResolve(mp, path, fileRef, function(){
  1590. if(fileRef.res == null)
  1591. {
  1592. // File does not exists
  1593. return cb(false);
  1594. }
  1595. else
  1596. {
  1597. var parentPath = fileRef.parentPath;
  1598. var parentRes = fileRef.parentRes;
  1599. var res = fileRef.res;
  1600. if(res.type == "dir")
  1601. {
  1602. // We can only delete empty directories
  1603. if(res.contents.length > 0)
  1604. return cb(false);
  1605. // Remove the cached entry
  1606. idbDelDEntry(mp, path);
  1607. }
  1608. var filePath = path.substr(parentPath.length);
  1609. var fileIndex = parentRes.contents.indexOf(filePath);
  1610. assert(filePath.length > 0);
  1611. assert(fileIndex >= 0);
  1612. parentRes.contents.splice(fileIndex, 1);
  1613. var tx = mp.dbConnection.transaction("files", "readwrite");
  1614. var store = tx.objectStore("files");
  1615. tx.onerror = idbTrap;
  1616. tx.onabort = idbTrap;
  1617. tx.oncomplete = function()
  1618. {
  1619. this.onerror = null;
  1620. this.onabort = null;
  1621. this.oncomplete = null;
  1622. // If we get here the deletion was successfull
  1623. return cb(true);
  1624. };
  1625. store.put(parentRes, parentPath);
  1626. store.delete(path);
  1627. if(fileRef.res.hasOwnProperty("refCount"))
  1628. idbDecRefIndirect(store, fileRef.res);
  1629. }
  1630. });
  1631. });
  1632. }
  1633. function idbEnsureDBConnection(mp, cb)
  1634. {
  1635. if(mp.dbConnection == null){
  1636. // Async connection to the DB
  1637. var openResult = indexedDB.open("cjFS_"+mp.mountPoint);
  1638. assert(openResult.readyState != "done");
  1639. openResult.folder = mp;
  1640. openResult.onerror = idbTrap;
  1641. openResult.onsuccess = function(e)
  1642. {
  1643. this.onerror = null;
  1644. this.onsuccess = null;
  1645. this.onupgradeneeded = null;
  1646. this.folder.dbConnection = this.result;
  1647. var tx = this.folder.dbConnection.transaction("files", "readonly");
  1648. // Retrieve the first unallocated inode
  1649. var store = tx.objectStore("files");
  1650. var inodeReq = store.get("");
  1651. assert(inodeReq.readyState != "done");
  1652. inodeReq.folder = this.folder;
  1653. inodeReq.onerror = idbTrap;
  1654. inodeReq.onsuccess = function()
  1655. {
  1656. idbAddDEntry(this.folder, "", this.result);
  1657. this.folder.inodeId = this.result.nextInode;
  1658. return cb();
  1659. };
  1660. }
  1661. openResult.onupgradeneeded = function(e)
  1662. {
  1663. this.onerror = null;
  1664. this.onsuccess = null;
  1665. this.onupgradeneeded = null;
  1666. var db = this.result;
  1667. db.onerror = idbTrap;
  1668. db.onabort = idbTrap;
  1669. db.onclose = idbTrap;
  1670. db.onversionchange = idbTrap;
  1671. var store=db.createObjectStore("files");
  1672. // Initialize the root dir
  1673. var req = store.add({ type: "dir", contents:[], uid: 0, gid: 0, lastModified: (Date.now() / 1000)|0, inodeId: 1, nextInode:2 }, "");
  1674. assert(req.readyState != "done");
  1675. // TODO: What if this fails?
  1676. req.onabort = idbTrap;
  1677. this.transaction.oncomplete = function()
  1678. {
  1679. this.oncomplete = null;
  1680. openResult.folder.dbConnection = this.db;
  1681. return cb();
  1682. }
  1683. }
  1684. }else{
  1685. return cb();
  1686. }
  1687. }
  1688. var IdbOps = { statAsync: idbStatAsync, listAsync: idbListAsync, makeFileData: idbMakeFileData, createDirAsync: idbCreateDirAsync, renameAsync: idbRenameAsync, linkAsync: idbLinkAsync, unlinkAsync: idbUnlinkAsync };
  1689. var IdbInodeOps = { readAsync: idbReadAsync, writeAsync: idbWriteAsync, close: idbCommitFileData };
  1690. function CheerpJDataFolder(mp)
  1691. {
  1692. CheerpJFolder.call(this, mp);
  1693. this.mountOps = StrOps;
  1694. this.inodeOps = StrInodeOps;
  1695. this.files = {};
  1696. this.lastInode = 2;
  1697. }
  1698. CheerpJDataFolder.prototype = Object.create(CheerpJFolder.prototype);
  1699. function strStatAsync(mp, path, fileRef, cb)
  1700. {
  1701. if(path == "")
  1702. {
  1703. fileRef.permType = CheerpJFileData.S_IFDIR | 0555;
  1704. // Use the dev id as the inode id
  1705. fileRef.inodeId = 1;
  1706. return cb();
  1707. }
  1708. if(mp.files.hasOwnProperty(path))
  1709. {
  1710. var file = mp.files[path];
  1711. fileRef.fileLength = file.data.length;
  1712. fileRef.permType = CheerpJFileData.S_IFREG | 0444;
  1713. fileRef.inodeId = file.inodeId;
  1714. }
  1715. else
  1716. {
  1717. fileRef.permType = 0;
  1718. }
  1719. return cb();
  1720. }
  1721. function strListAsync(mp, path, fileRef, cb)
  1722. {
  1723. // Only the root itself can be listed
  1724. if(path != ""){
  1725. return cb();
  1726. }
  1727. for(var p in mp.files)
  1728. {
  1729. fileRef.push(p.substring(1));
  1730. }
  1731. return cb();
  1732. }
  1733. function strMakeFileData(mp, path, mode, uid, gid, cb)
  1734. {
  1735. if(path == "")
  1736. {
  1737. var ret = new CheerpJFileData(mp, path, 0, 0, CheerpJFileData.S_IFDIR | 0777, /*lastModified*/0, /*uid*/0, /*gid*/0);
  1738. ret.mount = mp.inodeOps;
  1739. return cb(ret);
  1740. }
  1741. if(!mp.files.hasOwnProperty(path))
  1742. {
  1743. return cb(null);
  1744. }
  1745. var ret = mp.files[path].data;
  1746. assert(ret instanceof Uint8Array);
  1747. var inodeId = mp.files[path].inodeId
  1748. var fileData = new CheerpJFileData(mp, path, ret.length|0, inodeId|0, CheerpJFileData.S_IFREG | 0444, /*lastModified*/0, /*uid*/0, /*gid*/0);
  1749. fileData.mount = mp.inodeOps;
  1750. fileData.data = ret;
  1751. return cb(fileData);
  1752. }
  1753. function strReadAsync(fileData, fileOffset, buf, off, len, flags, cb)
  1754. {
  1755. if(len > fileData.data.length - fileOffset)
  1756. len = fileData.data.length - fileOffset;
  1757. // EOF
  1758. if(len == 0){
  1759. return cb(0);
  1760. }
  1761. for(var i=0;i<len;i++)
  1762. buf[off+i>>>0] = fileData.data[fileOffset+i|0];
  1763. return cb(len);
  1764. }
  1765. var StrOps = { statAsync: strStatAsync, listAsync: strListAsync, makeFileData: strMakeFileData, createDirAsync: null, renameAsync: null, linkAsync: null, unlinkAsync: null };
  1766. var StrInodeOps = { readAsync: strReadAsync, writeAsync: null, close: null };
  1767. function CheerpJDevFolder(mp, basePath)
  1768. {
  1769. CheerpJFolder.call(this, mp);
  1770. this.mountOps = DevOps;
  1771. this.inodeOps = null;
  1772. this.isSplit = true;
  1773. this.devMap = {};
  1774. // Reserve a few ides for random/urandom/nul;
  1775. this.nextInode = 4;
  1776. }
  1777. CheerpJDevFolder.prototype = Object.create(CheerpJFolder.prototype);
  1778. function devStatAsync(mp, path, fileRef, cb)
  1779. {
  1780. if(path == "/random" || path == "/urandom" || path == "/null")
  1781. {
  1782. fileRef.permType = CheerpJFileData.S_IFCHR | 0666;
  1783. }
  1784. else
  1785. {
  1786. fileRef.permType = 0;
  1787. }
  1788. return cb();
  1789. }
  1790. function devMakeFileData(mp, path, mode, uid, gid, cb)
  1791. {
  1792. var fileData = null;
  1793. if(path == "/random")
  1794. {
  1795. fileData = new CheerpJFileData(mp, path, 0xffffffff, 1, CheerpJFileData.S_IFCHR | 0666, /*lastModified*/0, /*uid*/0, /*gid*/0);
  1796. fileData.mount = DevRandomInodeOps;
  1797. }
  1798. else if(path == "/urandom")
  1799. {
  1800. fileData = new CheerpJFileData(mp, path, 0xffffffff, 2, CheerpJFileData.S_IFCHR | 0666, /*lastModified*/0, /*uid*/0, /*gid*/0);
  1801. fileData.mount = DevRandomInodeOps;
  1802. }
  1803. else if(path == "/null")
  1804. {
  1805. fileData = new CheerpJFileData(mp, path, 0xffffffff, 3, CheerpJFileData.S_IFCHR | 0666, /*lastModified*/0, /*uid*/0, /*gid*/0);
  1806. fileData.mount = DevNullInodeOps;
  1807. }
  1808. else if(mp.devMap.hasOwnProperty(path))
  1809. {
  1810. fileData = new CheerpJFileData(mp, path, 0xffffffff, mp.devMap[path].inodeId, CheerpJFileData.S_IFCHR | 0666, /*lastModified*/0, /*uid*/0, /*gid*/0);
  1811. fileData.mount = mp.devMap[path];
  1812. }
  1813. return cb(fileData);
  1814. }
  1815. function devRandomRead(fileData, fileOffset, buf, off, len, flags, cb)
  1816. {
  1817. var data = buf.subarray(off, off+len);
  1818. crypto.getRandomValues(data);
  1819. return cb(len);
  1820. }
  1821. function devRandomWrite(fileData, fileOffset, buf, off, len, cb)
  1822. {
  1823. return cb(len);
  1824. }
  1825. var DevRandomInodeOps = { readAsync: devRandomRead, writeAsync: devRandomWrite, close: null };
  1826. function devNullRead(fileData, fileOffset, buf, off, len, flags, cb)
  1827. {
  1828. return cb(0);
  1829. }
  1830. function devNullWrite(fileData, fileOffset, buf, off, len, cb)
  1831. {
  1832. return cb(len);
  1833. }
  1834. var DevNullInodeOps = { readAsync: devNullRead, writeAsync: devNullWrite, close: null };
  1835. var DevOps = { statAsync: devStatAsync, listAsync: null, makeFileData: devMakeFileData, createDirAsync: null, renameAsync: null, linkAsync: null, unlinkAsync: null };
  1836. function conReadAsync(fileData, fileOffset, buf, off, len, flags, cb)
  1837. {
  1838. if(!fileData.inCallback)
  1839. return;
  1840. fileData.inCallback(fileData.param, fileOffset, buf, off, len, cb);
  1841. }
  1842. function conWriteAsync(fileData, fileOffset, buf, off, len, cb)
  1843. {
  1844. fileData.outCallback(fileData.param, fileOffset, buf, off, len, cb);
  1845. }
  1846. var ConInodeOps = { readAsync: conReadAsync, writeAsync: conWriteAsync, close: null };
  1847. function cheerpjCreateConsole(param, inCallback, outCallback)
  1848. {
  1849. var fileData = new CheerpJFileData(null, null, 0, 0, CheerpJFileData.S_IFCHR | 0666, /*lastModified*/0, /*uid*/0, /*gid*/0);
  1850. fileData.mount = ConInodeOps;
  1851. // Add custom fields
  1852. fileData.inCallback = inCallback;
  1853. fileData.outCallback = outCallback;
  1854. fileData.param = param;
  1855. return fileData;
  1856. }
  1857. function cheerpjDefaultConsoleWrite(param, fileOffset, buf, off, len, cb)
  1858. {
  1859. // Console output, either to debug console or DOM console
  1860. var strBytes = ""
  1861. for(var i=0;i<len;i++)
  1862. {
  1863. var b = buf[i+off]&0xff;
  1864. var h = b.toString(16);
  1865. if(b < 16)
  1866. h = "0" + h;
  1867. strBytes += "%" + h;
  1868. }
  1869. strBytes = decodeURIComponent(strBytes);
  1870. var c = self.document ? document.getElementById("console") : null;
  1871. if(c)
  1872. c.textContent += strBytes;
  1873. else
  1874. console.log(strBytes);
  1875. return cb(len);
  1876. }
  1877. function cheerpOSAddStringFile(name, str)
  1878. {
  1879. var mount = cheerpjGetFSMountForPath(name);
  1880. var fileName = name.substr(mount.mountPoint.length-1);
  1881. if(fileName.lastIndexOf("/") != 0)
  1882. console.error(`CheerpOS: Directories are not supported ${name}`);
  1883. else
  1884. cheerpOSAddStringFileMain(mount, fileName, str);
  1885. }
  1886. function cheerpOSAddStringFileMain(mount, fileName, str)
  1887. {
  1888. assert(mount instanceof CheerpJDataFolder);
  1889. if(!(str instanceof Uint8Array))
  1890. {
  1891. var enc = new TextEncoder();
  1892. str = enc.encode(str.toString());
  1893. }
  1894. mount.files[fileName] = {inodeId:mount.lastInode, data:str};
  1895. mount.lastInode = mount.lastInode + 1|0;
  1896. mount.clearCached(fileName);
  1897. }
  1898. function cheerpOSRemoveStringFile(name)
  1899. {
  1900. var mount = cheerpjGetFSMountForPath(name);
  1901. assert(mount instanceof CheerpJDataFolder);
  1902. var fileName = name.substr(mount.mountPoint.length-1);
  1903. delete mount.files[fileName];
  1904. mount.clearCached(fileName);
  1905. }
  1906. function cheerpjAddStringFile(name, str)
  1907. {
  1908. console.warn("Deprecated: Use cheerpOSAddStringFile");
  1909. return cheerpOSAddStringFile(name, str);
  1910. }
  1911. function cheerpjRemoveStringFile(name)
  1912. {
  1913. console.warn("Deprecated: Use cheerpjRemoveStringFile");
  1914. return cheerpOSRemoveStringFile(name);
  1915. }
  1916. function cheerpjGetFSMountForPath(path)
  1917. {
  1918. for(var i=0;i<cheerpjFSMounts.length;i++)
  1919. {
  1920. var mount = cheerpjFSMounts[i];
  1921. if(path.startsWith(mount.mountPoint)){
  1922. return mount;
  1923. }
  1924. }
  1925. debugger
  1926. return null;
  1927. }
  1928. function cheerpjNormalizePath(path)
  1929. {
  1930. var parts = path.split('/');
  1931. var newParts = []
  1932. var partsUnderflow = 0;
  1933. for(var i=0;i<parts.length;i++)
  1934. {
  1935. if(parts[i] == '.' || parts[i] == "")
  1936. continue;
  1937. else if(parts[i] == '..')
  1938. {
  1939. if(newParts.length)
  1940. newParts.pop();
  1941. else
  1942. partsUnderflow++;
  1943. }
  1944. else
  1945. newParts.push(parts[i]);
  1946. }
  1947. if(!path.startsWith('/') && partsUnderflow == 0)
  1948. {
  1949. // TODO: Support cwd
  1950. newParts.unshift("files");
  1951. }
  1952. return "/" + newParts.join("/");
  1953. }
  1954. function cheerpOSStat(path_, fileRef, cb)
  1955. {
  1956. var path = cheerpjNormalizePath(path_)
  1957. var mount = cheerpjGetFSMountForPath(path + "/");
  1958. cheerpOSStatMain(mount, path.substr(mount.mountPoint.length-1), fileRef, cb);
  1959. }
  1960. function cheerpOSStatMain(mount, fileName, fileRef, cb)
  1961. {
  1962. fileRef.parent = mount;
  1963. mount.mountOps.statAsync(mount, fileName, fileRef, cb);
  1964. }
  1965. function cheerpOSListFiles(path_, fileRef, cb)
  1966. {
  1967. var path = cheerpjNormalizePath(path_)
  1968. var mount = cheerpjGetFSMountForPath(path + "/");
  1969. cheerpOSListFilesMain(mount, path.substr(mount.mountPoint.length-1), fileRef, cb);
  1970. }
  1971. function cheerpOSListFilesMain(mount, path_, fileRef, cb)
  1972. {
  1973. // Some backends (like Web) do not implement list
  1974. if(!mount.mountOps.listAsync){
  1975. return;
  1976. }
  1977. mount.mountOps.listAsync(mount, path_, fileRef, cb);
  1978. }
  1979. function cheerpOSCreateDir(path_, fileRef, mode, cb)
  1980. {
  1981. var path = cheerpjNormalizePath(path_)
  1982. var mount = cheerpjGetFSMountForPath(path);
  1983. cheerpOSCreateDirMain(mount, path.substr(mount.mountPoint.length-1), fileRef, mode, /*uid*/0, /*gid*/0, cb);
  1984. }
  1985. function cheerpOSCreateDirMain(mount, path_, fileRef, mode, uid, gid, cb)
  1986. {
  1987. if(!mount.mountOps.createDirAsync){
  1988. return cb(-1);
  1989. }
  1990. mount.mountOps.createDirAsync(mount, path_, fileRef, mode, uid, gid, cb);
  1991. }
  1992. function cheerpOSInitFds(fds)
  1993. {
  1994. var conFileData = cheerpjCreateConsole(null, null, cheerpjDefaultConsoleWrite);
  1995. var conFD = { fileData: conFileData, offset: 0, flags: 0 };
  1996. fds[0] = conFD;
  1997. fds[1] = conFD;
  1998. fds[2] = conFD;
  1999. conFileData.refCount+=3;
  2000. }
  2001. function cheerpOSCopyFds(dstFds, srcFds)
  2002. {
  2003. for(var i=0;i<srcFds.length;i++)
  2004. {
  2005. var fdObj = srcFds[i];
  2006. var fileData = fdObj.fileData;
  2007. dstFds[i] = {fileData: fileData, offset: fdObj.offset, flags: fdObj.flags};
  2008. fileData.refCount=fileData.refCount+1|0;
  2009. }
  2010. }
  2011. function cheerpOSAllocateFd(fds, fileData)
  2012. {
  2013. var newFD = {fileData: fileData, offset: 0, flags: 0};
  2014. for(var i=0;i<fds.length;i++)
  2015. {
  2016. if(fds[i]===null)
  2017. {
  2018. fds[i] = newFD;
  2019. return i;
  2020. }
  2021. }
  2022. fds.push(newFD);
  2023. return fds.length-1|0;
  2024. }
  2025. function cheerpOSDupFd(fds, oldFd, newFd, cb)
  2026. {
  2027. cheerpOSClose(fds, newFd, function()
  2028. {
  2029. var fdObj = fds[oldFd];
  2030. var fileData = fdObj.fileData;
  2031. fds[newFd] = {fileData: fileData, offset: fdObj.offset, flags: fdObj.flags};
  2032. fileData.refCount=fileData.refCount+1|0;
  2033. cb(newFd);
  2034. });
  2035. }
  2036. function cheerpjWakeOpenThreads (fileName, mount)
  2037. {
  2038. var tmp = mount.cacheThreads[fileName];
  2039. delete mount.cacheThreads[fileName];
  2040. for(var i = 0; i < tmp.length; i++)
  2041. {
  2042. tmp[i]();
  2043. }
  2044. }
  2045. function cheerpOSOpen(fds, path_, mode, cb)
  2046. {
  2047. var path = cheerpjNormalizePath(path_)
  2048. var mount = cheerpjGetFSMountForPath(path + "/");
  2049. var fileName = path.substr(mount.mountPoint.length-1);
  2050. if(mount.cacheThreads[fileName]){
  2051. mount.cacheThreads[fileName].push(function()
  2052. {
  2053. cheerpOSOpen(fds, path_, mode, cb);
  2054. });
  2055. return;
  2056. }
  2057. return cheerpOSOpenMain(fileName, mount, fds, mode, /*uid*/0, /*gid*/0, cb);
  2058. }
  2059. function cheerpOSOpenMain(fileName, mount, fds, mode, uid, gid, cb)
  2060. {
  2061. var fileData = mount.getCached(fileName);
  2062. if(fileData === null)
  2063. {
  2064. mount.cacheThreads[fileName] = [];
  2065. var fileRef = {};
  2066. assert(mount.mountOps.makeFileData);
  2067. mount.mountOps.makeFileData(mount, fileName, mode, uid, gid, function(fileData){
  2068. if(fileData == null){
  2069. cheerpjWakeOpenThreads(fileName, mount);
  2070. return cb(-1);
  2071. }
  2072. mount.setCached(fileName, fileData);
  2073. cheerpjWakeOpenThreads(fileName, mount);
  2074. fileData.refCount=fileData.refCount+1|0;
  2075. return cb(cheerpOSAllocateFd(fds, fileData));
  2076. });
  2077. return;
  2078. }else if(mode != "r" && !fileData.parent.isSplit){
  2079. // Make sure we don't allow opening for write a cached file that does not support it
  2080. return cb(-1);
  2081. }else if(mode == "w"){
  2082. // Truncation of a cached file
  2083. fileData.dirty = 1;
  2084. fileData.chunks = [];
  2085. fileData.length = 0;
  2086. }
  2087. fileData.refCount=fileData.refCount+1|0;
  2088. return cb(cheerpOSAllocateFd(fds, fileData));
  2089. }
  2090. function cheerpOSRead(fds, fd, buf, off, len, cb)
  2091. {
  2092. if(fd < 0){
  2093. return cb(-1);
  2094. }
  2095. var fdObj = fds[fd];
  2096. assert(fdObj);
  2097. assert(fdObj.fileData.mount);
  2098. assert(off + len <= buf.length);
  2099. fdObj.fileData.mount.readAsync(fdObj.fileData, fdObj.offset, buf, off, len, fdObj.flags, function(ret){
  2100. if(ret<=0){
  2101. return cb(ret);
  2102. }
  2103. fdObj.offset = fdObj.offset + ret|0;
  2104. return cb(ret);
  2105. });
  2106. }
  2107. function cheerpOSWrite(fds, fd, buf, off, len, cb)
  2108. {
  2109. if(fd < 0){
  2110. return cb(-1);
  2111. }
  2112. var fdObj = fds[fd];
  2113. assert(fdObj);
  2114. assert(fdObj.fileData.mount);
  2115. assert(off + len <= buf.length);
  2116. fdObj.fileData.dirty = 1;
  2117. fdObj.fileData.mount.writeAsync(fdObj.fileData, fdObj.offset, buf, off, len, function(ret){
  2118. if(ret<=0){
  2119. return cb(ret);
  2120. }
  2121. fdObj.offset = fdObj.offset + ret|0;
  2122. return cb(ret);
  2123. });
  2124. }
  2125. function cheerpOSRename(srcPath_, dstPath_, cb)
  2126. {
  2127. var srcPath = cheerpjNormalizePath(srcPath_);
  2128. var dstPath = cheerpjNormalizePath(dstPath_);
  2129. var srcMount = cheerpjGetFSMountForPath(srcPath + "/");
  2130. var dstMount = cheerpjGetFSMountForPath(dstPath + "/");
  2131. // Only allowed on the same mount point
  2132. if(srcMount !== dstMount){
  2133. return cb(0);
  2134. }
  2135. var prefixLen = srcMount.mountPoint.length-1;
  2136. var srcFileName = srcPath.substr(prefixLen);
  2137. var dstFileName = dstPath.substr(prefixLen);
  2138. return cheerpOSRenameMain(srcMount, srcFileName, dstFileName, cb);
  2139. }
  2140. function cheerpOSRenameMain(mount, srcPath_, dstPath_, cb)
  2141. {
  2142. if(!mount.mountOps.renameAsync){
  2143. return cb(0);
  2144. }
  2145. mount.mountOps.renameAsync(mount, srcPath_, dstPath_, function(ret){
  2146. if(ret == 0){
  2147. return cb(0);
  2148. }
  2149. mount.clearCached(srcPath_);
  2150. mount.clearCached(dstPath_);
  2151. return cb(1);
  2152. });
  2153. }
  2154. function cheerpOSLink(srcPath_, dstPath_, cb)
  2155. {
  2156. var srcPath = cheerpjNormalizePath(srcPath_);
  2157. var dstPath = cheerpjNormalizePath(dstPath_);
  2158. var srcMount = cheerpjGetFSMountForPath(srcPath + "/");
  2159. var dstMount = cheerpjGetFSMountForPath(dstPath + "/");
  2160. // Only allowed on the same mount point
  2161. if(srcMount !== dstMount){
  2162. return cb(0);
  2163. }
  2164. var prefixLen = srcMount.mountPoint.length-1;
  2165. return cheerpOSLinkMain(srcMount, srcPath.substr(prefixLen), dstPath.substr(prefixLen), cb);
  2166. }
  2167. function cheerpOSLinkMain(mount, srcPath_, dstPath_, cb)
  2168. {
  2169. if(!mount.mountOps.linkAsync){
  2170. return cb(0);
  2171. }
  2172. mount.mountOps.linkAsync(mount, srcPath_, dstPath_, cb);
  2173. }
  2174. function cheerpOSUnlink(path_, cb)
  2175. {
  2176. var path = cheerpjNormalizePath(path_, false);
  2177. var mount = cheerpjGetFSMountForPath(path);
  2178. var fileName = path.substr(mount.mountPoint.length-1);
  2179. return cheerpOSUnlinkMain(mount, fileName, cb);
  2180. }
  2181. function cheerpOSUnlinkMain(mount, path_, cb)
  2182. {
  2183. mount.clearCached(path_);
  2184. if(!mount.mountOps.unlinkAsync)
  2185. return cb(-1);
  2186. mount.mountOps.unlinkAsync(mount, path_, cb);
  2187. }
  2188. var cjGraceTimeQueue = []
  2189. function cjGraceTimeExpire()
  2190. {
  2191. // Only get the first item on the queue
  2192. assert(cjGraceTimeQueue.length);
  2193. var fileData = cjGraceTimeQueue.shift();
  2194. if(fileData == null)
  2195. {
  2196. // The file lifetime has been bumped
  2197. return;
  2198. }
  2199. if(fileData.refCount > 0)
  2200. {
  2201. // The file has been resurrected
  2202. return;
  2203. }
  2204. // File dead, free the memory
  2205. var mount = fileData.parent;
  2206. for(var f in mount.fileCache)
  2207. {
  2208. if(fileData.inodeId == mount.fileCache[f])
  2209. mount.clearCached(f);
  2210. }
  2211. assert(fileData.cacheRefCount == 0);
  2212. }
  2213. function cheerpOSClose(fds, fd, cb)
  2214. {
  2215. if(fd < 0 || fd >= fds.length){
  2216. cb();
  2217. return;
  2218. }
  2219. var fdObj = fds[fd];
  2220. if(fdObj === null)
  2221. {
  2222. cb();
  2223. return;
  2224. }
  2225. var fileData = fdObj.fileData;
  2226. // No fileData may be there for FDs which are not files
  2227. if(fileData)
  2228. {
  2229. fileData.refCount = fileData.refCount-1|0;
  2230. if(fileData.refCount===0 && fileData.parent != null)
  2231. {
  2232. if(fileData.dirty)
  2233. {
  2234. for(var p in cosFileWatchPrefixes)
  2235. {
  2236. assert(fileData.path.startsWith("/"));
  2237. var path = fileData.parent.mountPoint + fileData.path.substr(1);
  2238. if(path === p || path.startsWith(p + "/"))
  2239. cosFileWatchPrefixes[p](path);
  2240. }
  2241. }
  2242. // Commit the data immediately to ensure persistence
  2243. if(fileData.mount.close)
  2244. {
  2245. fileData.mount.close(fileData, cb);
  2246. // Reset the callback to not call it again at the end of the function
  2247. cb = null;
  2248. }
  2249. // Make sure there is only one entry in the queue for each file,
  2250. // if there is an existing one, null it out
  2251. var prevIdx = cjGraceTimeQueue.indexOf(fileData);
  2252. if(prevIdx >= 0)
  2253. cjGraceTimeQueue[prevIdx] = null;
  2254. // Put the cached file in the queue, and give it a 10 sec grace time before freeing the memory
  2255. cjGraceTimeQueue.push(fileData);
  2256. setTimeout(cjGraceTimeExpire, 10000);
  2257. }
  2258. }
  2259. fds[fd] = null;
  2260. if(cb)
  2261. cb();
  2262. }
  2263. function socketReadAsync(fileData, fileOffset, buf, off, len, flags, cb)
  2264. {
  2265. assert(len != 0);
  2266. let cnt = off;
  2267. if(fileData.currData === null){
  2268. return cb(0);
  2269. }
  2270. return socketReadLoop(fileData, fileOffset, buf, off, len, flags, cnt, cb);
  2271. }
  2272. function socketReadLoop(fileData, fileOffset, buf, off, len, flags, cnt, cb)
  2273. {
  2274. while(1){
  2275. if(cnt === off+len){
  2276. break;
  2277. }
  2278. if(!fileData.currData || fileData.currPos >= fileData.currData.length){
  2279. while(1){
  2280. if(fileData.chunks.length !== 0){
  2281. break;
  2282. }
  2283. if(cnt>off)
  2284. return cb(cnt-off);
  2285. fileData.blockedThread = function(){
  2286. return socketReadLoop(fileData, fileOffset, buf, off, len, flags, cnt, cb);
  2287. };
  2288. return;
  2289. }
  2290. fileData.currData = fileData.chunks.shift();
  2291. fileData.currPos = 0;
  2292. if(!(fileData.currData instanceof Uint8Array)){
  2293. if(fileData.currData == 'cjRemoteError')
  2294. {
  2295. fileData.currData = null;
  2296. return cb(cnt-off);
  2297. }
  2298. else
  2299. {
  2300. return cb(cnt-off);
  2301. }
  2302. }
  2303. }
  2304. buf[cnt] = fileData.currData[fileData.currPos];
  2305. fileData.currPos = fileData.currPos + 1 | 0;
  2306. cnt++;
  2307. }
  2308. return cb(cnt-off);
  2309. }
  2310. function cheerpNetReadFetchOS(reader,fileData)
  2311. {
  2312. reader.read()
  2313. .then(function(result){
  2314. if(result.done)
  2315. {
  2316. fileData.chunks.push(null);
  2317. }
  2318. else
  2319. {
  2320. if(result.value instanceof ArrayBuffer)
  2321. {
  2322. fileData.chunks.push(new Uint8Array(result.value));
  2323. }
  2324. else
  2325. {
  2326. fileData.chunks.push(result.value);
  2327. }
  2328. }
  2329. if(fileData.blockedThread)
  2330. {
  2331. var blockedThread=fileData.blockedThread;
  2332. fileData.blockedThread=null;
  2333. return blockedThread();
  2334. }
  2335. if(!result.done)
  2336. {
  2337. cheerpNetReadFetchOS(reader, fileData);
  2338. }
  2339. });
  2340. }
  2341. function httpSocketWriteAsync(fileData, fileOffset, buf, off, len, cb)
  2342. {
  2343. let i = 0;
  2344. let cnt = 0;
  2345. if(fileData.currRequest.headersNewLines < 1)
  2346. {
  2347. /*Consume bytes*/
  2348. for(i = off; i < off+len && fileData.currRequest.headersNewLines < 1; i++)
  2349. {
  2350. cnt++;
  2351. let currChar = String.fromCharCode(buf[i]);
  2352. if(currChar === '\n'){ /* Parse */
  2353. let line = fileData.currRequest.currString;
  2354. if(line.startsWith('\r'))
  2355. {
  2356. fileData.currRequest.headersNewLines++;
  2357. }
  2358. else
  2359. {
  2360. if(fileData.currRequest.nLines === 0 && line.indexOf("HTTP/1.1") !== -1)
  2361. {
  2362. let firstLine = line.split(" ");
  2363. fileData.currRequest.method = firstLine[0];
  2364. fileData.currRequest.url = firstLine[1];
  2365. }
  2366. else if(!line.toLowerCase().startsWith("cookie"))
  2367. {
  2368. let key = line.substr(0,line.indexOf(':'));
  2369. let value = line.substr(line.indexOf(':')+2);
  2370. if(key.toLowerCase() === "host")
  2371. {
  2372. if(window.location.protocol == "https:")
  2373. {
  2374. fileData.currRequest.url = "https://" + value + fileData.currRequest.url;
  2375. }
  2376. else
  2377. {
  2378. fileData.currRequest.url = "http://" + value + fileData.currRequest.url;
  2379. }
  2380. }
  2381. else
  2382. {
  2383. fileData.currRequest.headers.append(key, value);
  2384. }
  2385. }
  2386. }
  2387. fileData.currRequest.currString = "";
  2388. fileData.currRequest.nLines++;
  2389. }else
  2390. {
  2391. fileData.currRequest.currString += currChar;
  2392. }
  2393. fileData.currRequest.prevChar = currChar;
  2394. }
  2395. off = off + i - 1;
  2396. }
  2397. if(fileData.currRequest.headersNewLines >= 1)
  2398. {
  2399. if(fileData.currRequest.method === "POST")
  2400. {
  2401. if(!fileData.currRequest.data)
  2402. {
  2403. fileData.currRequest.data = new Uint8Array(parseInt(fileData.currRequest.headers.get("Content-Length")));
  2404. }
  2405. fileData.currRequest.data.set(buf.subarray(off, len), fileData.currRequest.dataIdx);
  2406. fileData.currRequest.dataIdx += len-off+1;
  2407. cnt += len-off;
  2408. }
  2409. if((fileData.currRequest.method === "POST" && fileData.currRequest.dataIdx < fileData.currRequest.headers.get("Content-Length"))
  2410. || (fileData.currRequest.method !== "POST" && fileData.currRequest.headersNewLines < 1))
  2411. {
  2412. return cb(cnt);
  2413. }
  2414. let dict = {credential: 'include', method: fileData.currRequest.method, headers: fileData.currRequest.headers};
  2415. if(fileData.currRequest.data)
  2416. {
  2417. dict.body = fileData.currRequest.data;
  2418. }
  2419. fetch(fileData.currRequest.url, dict)
  2420. .then(function(response)
  2421. {
  2422. let cjStr2AB = function(str) {
  2423. let bufView = new Uint8Array(str.length);
  2424. for (var i=0; i < str.length; i++) {
  2425. bufView[i] = str.charCodeAt(i);
  2426. }
  2427. return bufView;
  2428. };
  2429. if(response.ok)
  2430. {
  2431. let responseStatus = "HTTP/1.1 " + response.status + " " + response.statusText;
  2432. let responseHeaders = response.headers.entries();
  2433. fileData.chunks.push(cjStr2AB(responseStatus+'\r\n'));
  2434. let entry = responseHeaders.next();
  2435. while (!entry.done)
  2436. {
  2437. if(entry.value[0].toLowerCase() === "transfer-encoding")
  2438. {
  2439. entry = responseHeaders.next();
  2440. continue;
  2441. }
  2442. let he = entry.value[0] + ': ' + entry.value[1] + '\r\n';
  2443. fileData.chunks.push(cjStr2AB(he));
  2444. entry = responseHeaders.next();
  2445. }
  2446. fileData.chunks.push(cjStr2AB("\r\n"));
  2447. const reader = response.body.getReader();
  2448. cheerpNetReadFetchOS(reader, fileData);
  2449. }else
  2450. {
  2451. fileData.chunks.push('cjRemoteError');
  2452. }
  2453. })
  2454. .catch(function(err)
  2455. {
  2456. fileData.chunks.push('cjRemoteError');
  2457. });
  2458. }
  2459. else if(fileData.currRequest.currString.length >= 4)
  2460. {
  2461. // Not even 1 line available, can this even be HTTP?
  2462. if(!fileData.currRequest.currString.startsWith("HTTP")) {
  2463. fileData.chunks.push('cjRemoteError');
  2464. return cb(-1);
  2465. }
  2466. }
  2467. return cb(cnt);
  2468. }
  2469. function socketWriteAsync(fileData, fileOffset, buf, off, len, cb)
  2470. {
  2471. var ret = fileData.data.send(buf.subarray(off, off+len));
  2472. if(ret == 0)
  2473. ret = len;
  2474. return cb(ret);
  2475. }
  2476. function udpSocketReadAsync(fileData, fileOffset, buf, off, len, flags, cb)
  2477. {
  2478. debugger;
  2479. }
  2480. function udpSocketWriteAsync(fileData, fileOffset, buf, off, len, cb)
  2481. {
  2482. debugger;
  2483. }
  2484. function socketClose(fileData, cb)
  2485. {
  2486. if (fileData.data)
  2487. {
  2488. fileData.data.close();
  2489. fileData.data = null;
  2490. }
  2491. cb();
  2492. }
  2493. function internalSocketReadAsync(fileData, fileOffset, buf, off, len, flags, cb)
  2494. {
  2495. if(fileData.chunks.length == 0)
  2496. {
  2497. if(fileData.flags & CheerpJFileData.O_NONBLOCK)
  2498. return cb(/*EAGAIN*/-11);
  2499. fileData.blockedThread = function()
  2500. {
  2501. return internalSocketReadAsync(fileData, fileOffset, buf, off, len, flags, cb);
  2502. };
  2503. return;
  2504. }
  2505. // TODO: Read more if possible
  2506. var first = fileData.chunks[0];
  2507. if(first.length < len)
  2508. len = first.length;
  2509. for(var i=0;i<len;i++)
  2510. buf[off + i] = first[i];
  2511. if(len == first.length)
  2512. fileData.chunks.shift();
  2513. else
  2514. fileData.chunks[0] = first.subarray(len);
  2515. return cb(len);
  2516. }
  2517. function internalSocketWriteAsync(fileData, fileOffset, buf, off, len, cb)
  2518. {
  2519. if(len > 0)
  2520. {
  2521. var socket = fileData.data;
  2522. var peer = socket.peerSocket;
  2523. var data = new Uint8Array(buf.subarray(off, off + len));
  2524. peer.recvCb(data);
  2525. }
  2526. return cb(len);
  2527. }
  2528. function internalSocketClose(fileData, cb)
  2529. {
  2530. debugger;
  2531. }
  2532. function internalSocketRecv(recvCb)
  2533. {
  2534. this.recvCb = recvCb;
  2535. }
  2536. function internalSocketConnect(addr, port, cb)
  2537. {
  2538. var boundSocket = InternalSocket.boundSockets[port];
  2539. if(boundSocket)
  2540. {
  2541. var newSocket = new InternalSocket();
  2542. this.peerSocket = newSocket;
  2543. newSocket.peerSocket = this;
  2544. boundSocket.listenCb(newSocket, null, null, 0);
  2545. return cb(0);
  2546. }
  2547. return cb(-1);
  2548. }
  2549. function internalSocketBind(port)
  2550. {
  2551. if(port == 0)
  2552. {
  2553. // Used to assign a port, nothing to do
  2554. return 0;
  2555. }
  2556. InternalSocket.boundSockets[port] = this;
  2557. return 0;
  2558. }
  2559. function internalSocketListen(listenCb)
  2560. {
  2561. this.listenCb = listenCb;
  2562. }
  2563. function InternalSocket()
  2564. {
  2565. this.recvCb = null;
  2566. this.listenCb = null;
  2567. this.peerSocket = null;
  2568. }
  2569. InternalSocket.prototype.recv = internalSocketRecv;
  2570. InternalSocket.prototype.connect = internalSocketConnect;
  2571. InternalSocket.prototype.bind = internalSocketBind;
  2572. InternalSocket.prototype.listen = internalSocketListen;
  2573. InternalSocket.boundSockets = {};
  2574. var SocketInodeOps = { readAsync: socketReadAsync, writeAsync: socketWriteAsync, close: socketClose };
  2575. var UdpSocketInodeOps = { readAsync: udpSocketReadAsync, writeAsync: udpSocketWriteAsync, close: socketClose };
  2576. var httpSocketInodeOps = { readAsync: socketReadAsync, writeAsync: httpSocketWriteAsync, close: null };
  2577. var InternalSocketInodeOps = { readAsync: internalSocketReadAsync, writeAsync: internalSocketWriteAsync, close: internalSocketClose };
  2578. function cheerpOSSocketOpenInternal(fds, mode, socket)
  2579. {
  2580. var fileData = new CheerpJFileData(null, null, 0, 0, 0, 0, 0, 0);
  2581. // Internal sockets are supported unconditionally
  2582. if(mode == 2)
  2583. {
  2584. fileData.mount = InternalSocketInodeOps;
  2585. fileData.data = socket? socket : new InternalSocket();
  2586. fileData.data.recv((data) => {
  2587. fileData.chunks.push(data);
  2588. if(fileData.blockedThread){
  2589. var blockedThread=fileData.blockedThread;
  2590. fileData.blockedThread=null;
  2591. blockedThread();
  2592. }
  2593. });
  2594. }
  2595. else
  2596. {
  2597. if(!cjEnableTailscale)
  2598. {
  2599. if (mode != 0)
  2600. return -1;
  2601. fileData.mount = httpSocketInodeOps;
  2602. fileData.currRequest = {
  2603. headers: new Headers(),
  2604. url: "",
  2605. method: "",
  2606. currString: "",
  2607. prevChar: "",
  2608. firstFetchCall: true,
  2609. headersNewLines: 0,
  2610. dataIdx: 0,
  2611. nLines: 0,
  2612. };
  2613. }
  2614. else
  2615. {
  2616. if (mode == 1)
  2617. {
  2618. fileData.mount = UdpSocketInodeOps;
  2619. fileData.data = socket? socket : cjTailscaleUdpSocket();
  2620. fileData.data.recv((data, addr, port) => {
  2621. fileData.chunks.push({data,addr,port});
  2622. if(fileData.blockedThread){
  2623. var blockedThread=fileData.blockedThread;
  2624. fileData.blockedThread=null;
  2625. blockedThread();
  2626. }
  2627. });
  2628. }
  2629. else
  2630. {
  2631. fileData.mount = SocketInodeOps;
  2632. fileData.data = socket? socket : cjTailscaleSocket();
  2633. fileData.data.recv((data) => {
  2634. // The data is borrowed and we can't use it after this callback
  2635. var copy = data == null? null : new Uint8Array(data);
  2636. fileData.chunks.push(copy);
  2637. if(fileData.blockedThread){
  2638. var blockedThread=fileData.blockedThread;
  2639. fileData.blockedThread=null;
  2640. blockedThread();
  2641. }
  2642. });
  2643. }
  2644. }
  2645. }
  2646. fileData.chunks = [];
  2647. fileData.currData = undefined;
  2648. fileData.currPos = 0;
  2649. fileData.refCount=fileData.refCount+1|0;
  2650. return cheerpOSAllocateFd(fds, fileData);
  2651. }
  2652. function cheerpOSSocketOpen(fds, mode, cb)
  2653. {
  2654. return cb(cheerpOSSocketOpenInternal(fds, mode, undefined));
  2655. }
  2656. function cheerpOSSocketShutdown(fds, fd, how, cb)
  2657. {
  2658. if(fd < 0)
  2659. return cb(-1);
  2660. var fileDesc=fds[fd];
  2661. if(fileDesc == null)
  2662. return cb(-1);
  2663. var fileData=fileDesc.fileData;
  2664. var ret = 0;
  2665. if (fileData.data)
  2666. {
  2667. switch(how)
  2668. {
  2669. case 0:
  2670. ret = fileData.data.shutdownRx();
  2671. break;
  2672. case 1:
  2673. ret = fileData.data.shutdownTx();
  2674. break;
  2675. case 2:
  2676. var ret1 = fileData.data.shutdownRx();
  2677. var ret2 = fileData.data.shutdownTx();
  2678. ret = ret1 != 0? ret1 : ret2;
  2679. break;
  2680. }
  2681. }
  2682. return cb(ret);
  2683. }
  2684. function cheerpOSPoll(fds, fd, timeout, cb)
  2685. {
  2686. if(fd < 0)
  2687. return cb(-1);
  2688. var fileDesc=fds[fd];
  2689. if(fileDesc == null)
  2690. return cb(-1);
  2691. var fileData = fileDesc.fileData;
  2692. if(fileData.currData || fileData.chunks.length > 0)
  2693. return cb(1);
  2694. var timeoutId = 0;
  2695. if(timeout >= 0)
  2696. {
  2697. var timeoutCb = () => {
  2698. fileData.blockedThread = null;
  2699. return cb(0);
  2700. };
  2701. timeoutId = setTimeout(timeoutCb, timeout);
  2702. }
  2703. var pollCb = () => {
  2704. if(timeoutId)
  2705. clearTimeout(timeoutId);
  2706. return cb(1);
  2707. };
  2708. fileData.blockedThread = pollCb;
  2709. }
  2710. function cheerpOSReadAvailable(fds, fd, cb)
  2711. {
  2712. if(fd < 0)
  2713. return cb(-1);
  2714. var fileDesc=fds[fd];
  2715. if(fileDesc == null)
  2716. return cb(-1);
  2717. var tot = 0;
  2718. var data = fileDesc.fileData;
  2719. for(var i = 0; i < data.chunks.length; i++)
  2720. {
  2721. if(data.chunks[i])
  2722. tot += data.chunks[i].length;
  2723. }
  2724. if(data.currData)
  2725. {
  2726. tot += data.currData.length - data.currPos;
  2727. }
  2728. return cb(tot);
  2729. }
  2730. function cheerpOSSocketConnect(fds, fd, ipAddr, ipPort, cb)
  2731. {
  2732. if(fd < 0)
  2733. return cb(-1);
  2734. var fileDesc=fds[fd];
  2735. if(fileDesc == null)
  2736. return cb(-1);
  2737. var fileData=fileDesc.fileData;
  2738. if(!fileData.data)
  2739. {
  2740. // Pretend that the connection succeeds, we'll try to parse an HTTP session in the write handler.
  2741. return cb(0);
  2742. }
  2743. fileData.data.bind(0);
  2744. fileData.data.connect(ipAddr != "unix" ? cjTailscaleParseIp(ipAddr) : "unix", ipPort, cb);
  2745. }
  2746. function cheerpOSSocketListen(fds, fd, backlog, cb)
  2747. {
  2748. if(fd < 0)
  2749. return cb(-1);
  2750. var fileDesc=fds[fd];
  2751. if(fileDesc == null)
  2752. return cb(-1);
  2753. var fileData=fileDesc.fileData;
  2754. if(!fileData.data)
  2755. return cb(-1);
  2756. return cb(fileData.data.listen((socket, addr, port, err) => {
  2757. assert(err == 0);
  2758. fileData.chunks.push({socket,addr,port});
  2759. if(fileData.blockedThread){
  2760. var blockedThread=fileData.blockedThread;
  2761. fileData.blockedThread=null;
  2762. blockedThread();
  2763. }
  2764. }));
  2765. }
  2766. function cheerpOSSocketAccept(fds, fd, cb)
  2767. {
  2768. if(fd < 0)
  2769. return cb(-1);
  2770. var fileDesc=fds[fd];
  2771. if(fileDesc == null)
  2772. return cb(-1);
  2773. var fileData=fileDesc.fileData;
  2774. if(!fileData.data)
  2775. return cb(-1);
  2776. var doRead = () => {
  2777. var first = fileData.chunks.shift();
  2778. var newFd = cheerpOSSocketOpenInternal(fds, (first.socket instanceof InternalSocket) ? 2 : 0, first.socket);
  2779. return cb({newFd,addr:first.addr,port:first.port});
  2780. };
  2781. if(fileData.chunks.length != 0)
  2782. {
  2783. doRead();
  2784. return;
  2785. }
  2786. fileData.blockedThread = doRead;
  2787. return;
  2788. }
  2789. function cheerpOSSocketBind(fds, fd, localPort, cb)
  2790. {
  2791. if(fd < 0)
  2792. return cb(-1);
  2793. var fileDesc=fds[fd];
  2794. if(fileDesc == null)
  2795. return cb(-1);
  2796. var fileData=fileDesc.fileData;
  2797. if(!fileData.data)
  2798. return cb(-1);
  2799. return cb(fileData.data.bind(localPort));
  2800. }
  2801. function cheerpOSSocketSendTo(fds, fd, data, ipAddr, ipPort, cb)
  2802. {
  2803. if(fd < 0)
  2804. return cb(-1);
  2805. var fileDesc=fds[fd];
  2806. if(fileDesc == null)
  2807. return cb(-1);
  2808. var fileData=fileDesc.fileData;
  2809. if(!fileData.data)
  2810. return cb(-1);
  2811. return cb(fileData.data.sendto(data, cjTailscaleParseIp(ipAddr), ipPort));
  2812. }
  2813. function cheerpOSSocketRecv(fds, fd, cb)
  2814. {
  2815. if(fd < 0)
  2816. return cb({data:null,addr:0,port:0});
  2817. var fileDesc=fds[fd];
  2818. if(fileDesc == null)
  2819. return cb({data:null,addr:0,port:0});
  2820. var fileData=fileDesc.fileData;
  2821. if(!fileData.data)
  2822. return cb({data:null,addr:0,port:0});
  2823. var doRead = () => {
  2824. var first = fileData.chunks.shift();
  2825. return cb(first);
  2826. };
  2827. if(fileData.chunks.length != 0)
  2828. {
  2829. doRead();
  2830. return;
  2831. }
  2832. fileData.blockedThread = doRead;
  2833. return;
  2834. }
  2835. function cheerpOSResolveHost(hostName, cb)
  2836. {
  2837. if(hostName=='cheerpjhost')
  2838. hostName = "127.0.0.1";
  2839. if(!cjEnableTailscale)
  2840. return cb((192<<24)|(168<<16)|(1<<8)|1);
  2841. cjTailscaleResolve(hostName).then((ip) =>
  2842. {
  2843. var ip0 = ip & 0xff;
  2844. var ip1 = (ip>>8) & 0xff;
  2845. var ip2 = (ip>>16) & 0xff;
  2846. var ip3 = (ip>>24) & 0xff;
  2847. var javaIp = (ip0<<24) | (ip1<<16) | (ip2<<8) | ip3;
  2848. console.log("host ",hostName, " is ",ip0,ip1,ip2,ip3)
  2849. cb(javaIp);
  2850. });
  2851. }
  2852. var cheerpOSMimeMap = { htm: "text/html", html: "text/html", jpeg: "image/jpeg", jpg: "image/jpeg", js: "text/javascript", pdf: "application/pdf", png: "image/png", rtf: "application/rtf", xml: "text/xml" };
  2853. function cheerpOSGetFileBlobFd(fds, fd, path, cb)
  2854. {
  2855. if(fd < 0){
  2856. return cb(null);
  2857. }
  2858. // Compute file length
  2859. var fileRef = {};
  2860. cheerpOSFStat(fds, fd, fileRef, function()
  2861. {
  2862. var len = fileRef.fileLength;
  2863. var buf = new Uint8Array(len);
  2864. // Read the whole file
  2865. cheerpOSRead(fds, fd, buf, 0, len, function(r)
  2866. {
  2867. assert(len == r);
  2868. var mimeType = null;
  2869. var extIndex = path.lastIndexOf(".");
  2870. if(extIndex >= 0){
  2871. var ext = path.substr(extIndex+1);
  2872. var m = cheerpOSMimeMap[ext];
  2873. if(m)
  2874. mimeType = m;
  2875. }
  2876. cheerpOSClose(fds, fd, function(){});
  2877. var blob=new Blob([buf], {type: mimeType});
  2878. return cb(blob);
  2879. });
  2880. });
  2881. }
  2882. function cheerpOSGetFileBlob(fds, path, cb)
  2883. {
  2884. cheerpOSOpen(fds, path, "r", function(fd)
  2885. {
  2886. return cheerpOSGetFileBlobFd(fds, fd, path, cb);
  2887. });
  2888. }
  2889. function cheerpOSWatchFiles(prefix, cb)
  2890. {
  2891. var prefix = cheerpjNormalizePath(prefix)
  2892. if(cb == null)
  2893. delete cosFileWatchPrefixes[prefix];
  2894. else
  2895. cosFileWatchPrefixes[prefix] = cb;
  2896. }
  2897. function cheerpOSSeek(fds, fd, offset, whence, cb)
  2898. {
  2899. if(fd < 0)
  2900. {
  2901. return cb(-1);
  2902. }
  2903. var fdObj = fds[fd];
  2904. assert(fdObj);
  2905. var newOffset = offset;
  2906. if(whence == 0 /*SEEK_SET*/)
  2907. {
  2908. // Nothing to do
  2909. }
  2910. else if(whence == 2 /*SEEK_END*/)
  2911. {
  2912. assert(offset == 0);
  2913. var fileLength = fdObj.fileData.length;
  2914. newOffset = fileLength;
  2915. }
  2916. else
  2917. {
  2918. assert(whence == 1 /*SEEK_CUR*/);
  2919. var fileOffset = fdObj.offset;
  2920. newOffset = fileOffset + offset;
  2921. }
  2922. fdObj.offset = newOffset;
  2923. return cb(newOffset);
  2924. }
  2925. function cheerpOSFStat(fds, fd, fileRef, cb)
  2926. {
  2927. var fileData = fds[fd].fileData;
  2928. assert(fileData);
  2929. fileRef.fileLength = fileData.length;
  2930. fileRef.permType = fileData.permType;
  2931. fileRef.inodeId = fileData.inodeId;
  2932. fileRef.lastModified = fileData.lastModified;
  2933. return cb();
  2934. }
  2935. function cheerpOSGetFullPath(fds, fd, cb)
  2936. {
  2937. var fileData = fds[fd].fileData;
  2938. assert(fileData);
  2939. fullPath = fileData.parent.mountPoint + fileData.path;
  2940. return cb(fullPath);
  2941. }
  2942. function cheerpOSGetFlags(fds, fd, cb)
  2943. {
  2944. if(fd < 0 || fd >= fds.length)
  2945. {
  2946. return cb(-1);
  2947. }
  2948. var fdObj = fds[fd];
  2949. if(fdObj === null)
  2950. {
  2951. return cb(-1);
  2952. }
  2953. var fileData = fdObj.fileData;
  2954. return cb(fileData.flags);
  2955. }
  2956. function cheerpOSSetFlags(fds, fd, value, cb)
  2957. {
  2958. if(fd < 0 || fd >= fds.length)
  2959. {
  2960. return cb(-1);
  2961. }
  2962. var fdObj = fds[fd];
  2963. if(fdObj === null)
  2964. {
  2965. return cb(-1);
  2966. }
  2967. var fileData = fdObj.fileData;
  2968. fileData.flags = value;
  2969. return cb(0);
  2970. }
  2971. function assert(cond)
  2972. {
  2973. if(!cond)
  2974. debugger
  2975. }