Exemple #1
0
        // ReSharper disable InconsistentNaming

        /// <summary>
        /// This does not create a full RootEntry - it does setup SetInMemoryFields().
        /// This test structure.
        ///  Z:\
        ///  Z:\d2a (size 11)
        ///  Z:\d2b\
        ///  Z:\d2b\d3a\
        ///  Z:\d2b\d3a\d4a (size 17)
        ///  Z:\d2c (size 0)
        /// </summary>
        public static RootEntry NewTestRootEntry(out DirEntry de2a, out DirEntry de2b, out DirEntry de2c, out DirEntry de3a, out DirEntry de4a)
        {
            var re1 = new RootEntry {
                Path = @"Z:\"
            };

            de2a = new DirEntry {
                Path = "d2a", Size = 11
            };
            de2b = new DirEntry(true)
            {
                Path = "d2b"
            };
            de2c = new DirEntry {
                Path = "d2c"
            };
            re1.Children.Add(de2c);
            re1.Children.Add(de2a);
            re1.Children.Add(de2b);

            de3a = new DirEntry(true)
            {
                Path = "d3a"
            };
            de2b.Children.Add(de3a);

            de4a = new DirEntry {
                Path = "d4a", Size = 17
            };
            de3a.Children.Add(de4a);

            return(re1);
        }
Exemple #2
0
        private void Read()
        {
            uint   fsize = (uint)br.BaseStream.Length;
            string magic = Encoding.ASCII.GetString(br.ReadBytes(2));

            if (magic != Magic)
            {
                throw new FormatException($"Invalid DZip file: missing {Magic}");
            }
            byte major = br.ReadByte();
            byte minor = br.ReadByte();

            if (major > MajorVersion)
            {
                throw new FormatException($"Invalid DZip file: version is {major}.{minor}, this supports {MajorVersion}.{MinorVersion}");
            }
            uint offset   = br.ReadUInt32();
            uint numfiles = br.ReadUInt32();

            int entrySize = (major == 1) ? V1DirEntrySize : V2DirEntrySize;

            if ((numfiles & 0xF8000000) == 0xF8000000 || offset >= fsize || numfiles * entrySize > fsize)
            {
                throw new FormatException($"Invalid DZip file: missing directory");
            }

            br.BaseStream.Seek(offset, SeekOrigin.Begin);
            for (var i = 0; i < numfiles; i++)
            {
                DirEntry e = new DirEntry(br);
                Entries[e.Name] = e;
            }
        }
            private void _read()
            {
                _unused1           = m_io.EnsureFixedContents(new byte[] { 0 });
                _systemId          = System.Text.Encoding.GetEncoding("UTF-8").GetString(m_io.ReadBytes(32));
                _volumeId          = System.Text.Encoding.GetEncoding("UTF-8").GetString(m_io.ReadBytes(32));
                _unused2           = m_io.EnsureFixedContents(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
                _volSpaceSize      = new U4bi(m_io, this, m_root);
                _unused3           = m_io.EnsureFixedContents(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
                _volSetSize        = new U2bi(m_io, this, m_root);
                _volSeqNum         = new U2bi(m_io, this, m_root);
                _logicalBlockSize  = new U2bi(m_io, this, m_root);
                _pathTableSize     = new U4bi(m_io, this, m_root);
                _lbaPathTableLe    = m_io.ReadU4le();
                _lbaOptPathTableLe = m_io.ReadU4le();
                _lbaPathTableBe    = m_io.ReadU4be();
                _lbaOptPathTableBe = m_io.ReadU4be();
                __raw_rootDir      = m_io.ReadBytes(34);
                var io___raw_rootDir = new KaitaiStream(__raw_rootDir);

                _rootDir              = new DirEntry(io___raw_rootDir, this, m_root);
                _volSetId             = System.Text.Encoding.GetEncoding("UTF-8").GetString(m_io.ReadBytes(128));
                _publisherId          = System.Text.Encoding.GetEncoding("UTF-8").GetString(m_io.ReadBytes(128));
                _dataPreparerId       = System.Text.Encoding.GetEncoding("UTF-8").GetString(m_io.ReadBytes(128));
                _applicationId        = System.Text.Encoding.GetEncoding("UTF-8").GetString(m_io.ReadBytes(128));
                _copyrightFileId      = System.Text.Encoding.GetEncoding("UTF-8").GetString(m_io.ReadBytes(38));
                _abstractFileId       = System.Text.Encoding.GetEncoding("UTF-8").GetString(m_io.ReadBytes(36));
                _bibliographicFileId  = System.Text.Encoding.GetEncoding("UTF-8").GetString(m_io.ReadBytes(37));
                _volCreateDatetime    = new DecDatetime(m_io, this, m_root);
                _volModDatetime       = new DecDatetime(m_io, this, m_root);
                _volExpireDatetime    = new DecDatetime(m_io, this, m_root);
                _volEffectiveDatetime = new DecDatetime(m_io, this, m_root);
                _fileStructureVersion = m_io.ReadU1();
                _unused4              = m_io.ReadU1();
                _applicationArea      = m_io.ReadBytes(512);
            }
        protected void InitRootWithFile()
        {
            var nowUtc = new DateTime(2011, 12, 01, 17, 15, 13, DateTimeKind.Utc);

            _rootEntry = new RootEntry {
                Path            = @"T:\",
                VolumeName      = "TestVolume",
                DirEntryCount   = 1,
                FileEntryCount  = 0,
                DriveLetterHint = @"Z",
                AvailSpace      = 754321,
                TotalSpace      = 654321,
                ScanStartUTC    = nowUtc,
                ScanEndUTC      = nowUtc.AddMilliseconds(34),
                DefaultFileName = "TestRootEntry.cde",
                ActualFileName  = @".\TestRootEntry.cde",
                Description     = "Test Root Entry Description",
            };

            _dirEntry = new DirEntry
            {
                Path     = @"Test",
                Size     = 531,
                Modified = new DateTime(2010, 11, 02, 18, 16, 12, DateTimeKind.Unspecified),
            };
            _rootEntry.Children.Add(_dirEntry);
            _rootEntry.SetInMemoryFields();
            _pairDirEntry = new PairDirEntry(_rootEntry, _dirEntry);

            _rootList.Add(_rootEntry);
        }
Exemple #5
0
        // TODO: We should update the inode bitmap if necessary
        public void DeleteNode(BobFsNode node)
        {
            if (!IsDirectory)
            {
                throw new InvalidOperationException("Current node is not a directory.");
            }

            int      runner = 0;
            DirEntry entry  = new DirEntry();

            while (runner < Size)
            {
                entry.ReadFrom(this, runner);

                if (entry.Inum == node.Inum)
                {
                    int read;
                    while ((read = ReadAll(runner + (8 + entry.Name.Length), _tmpBuffer, 0, BobFs.BlockSize)) != 0)
                    {
                        WriteAll(runner, _tmpBuffer, 0, read);
                        runner += read;
                    }

                    Size -= (uint)(8 + entry.Name.Length);
                    return;
                }

                runner += 8 + entry.Name.Length; // Point to next direntry's inum
            }

            throw new Exception("Node not found.");
        }
Exemple #6
0
    //
    // Summary:
    //     Creates a subdirectory or subdirectories on the specified path with the specified
    //     security. The specified path can be relative to this instance of the System.IO.DirectoryInfo
    //     class.
    //
    // Parameters:
    //   path:
    //     The specified path. This cannot be a different disk volume or Universal Naming
    //     Convention (UNC) name.
    //
    //   directorySecurity:
    //     The security to apply.
    //
    // Returns:
    //     The last directory specified in path.
    //
    // Exceptions:
    //   T:System.ArgumentException:
    //     path does not specify a valid file path or contains invalid DirectoryInfo characters.
    //
    //   T:System.ArgumentNullException:
    //     path is null.
    //
    //   T:System.IO.DirectoryNotFoundException:
    //     The specified path is invalid, such as being on an unmapped drive.
    //
    //   T:System.IO.IOException:
    //     The subdirectory cannot be created.-or- A file or directory already has the name
    //     specified by path.
    //
    //   T:System.IO.PathTooLongException:
    //     The specified path, file name, or both exceed the system-defined maximum length.
    //     For example, on Windows-based platforms, paths must be less than 248 characters,
    //     and file names must be less than 260 characters. The specified path, file name,
    //     or both are too long.
    //
    //   T:System.Security.SecurityException:
    //     The caller does not have code access permission to create the directory.-or-The
    //     caller does not have code access permission to read the directory described by
    //     the returned System.IO.DirectoryInfo object. This can occur when the path parameter
    //     describes an existing directory.
    //
    //   T:System.NotSupportedException:
    //     path contains a colon character (:) that is not part of a drive label ("C:\").
    public DirEntry CreateSubdirectory(string path, DirectorySecurity directorySecurity)
    {
        var d = new DirEntry(path, this);

        d.Create(directorySecurity);
        return(d);
    }
 void FillDirTree()
 {
     rootEntry_ = new DirEntry {
         directory_ = RootPath, shortName_ = new System.IO.DirectoryInfo(RootPath).Name
     };
     rootEntry_.PopulateChildren();
 }
Exemple #8
0
        public void AddDirectory(string name)
        {
            var d = new DirEntry(name, DirEntry);

            d.exists = true;
            DirEntry.directories.Add(d);
        }
Exemple #9
0
        public void TestHashingWorks()
        {
            var de5 = new DirEntry {
                Path = "de5", Size = 11, IsPartialHash = false
            }; de5.SetHash(11);
            var de6 = new DirEntry {
                Path = "de6", Size = 11, IsPartialHash = false
            }; de6.SetHash(12);
            var de7 = new DirEntry {
                Path = "de7", Size = 11, IsPartialHash = true
            }; de7.SetHash(12);
            var de8 = new DirEntry {
                Path = "de8", Size = 11, IsPartialHash = false
            }; de8.SetHash(12);

            var ah5 = Hash16.EqualityComparer.StaticGetHashCode(de5.Hash);
            var ah6 = Hash16.EqualityComparer.StaticGetHashCode(de6.Hash);
            var ah7 = Hash16.EqualityComparer.StaticGetHashCode(de7.Hash);
            var ah8 = Hash16.EqualityComparer.StaticGetHashCode(de8.Hash);

            Console.WriteLine($"de5.Hash {ah5}  de6.Hash {ah6} de7.Hash {ah7} de8.Hash {ah8}");

            var a5 = DirEntry.EqualityComparer.StaticGetHashCode(de5);
            var a6 = DirEntry.EqualityComparer.StaticGetHashCode(de6);
            var a7 = DirEntry.EqualityComparer.StaticGetHashCode(de7);
            var a8 = DirEntry.EqualityComparer.StaticGetHashCode(de8);

            Console.WriteLine($"de5 {a5}  de6 {a6} de7 {a7} de8 {a8}");
        }
Exemple #10
0
 private Color CreateRowValuesForDirectory(IList <string> vals, DirEntry dirEntry, Color itemColor)
 {
     vals[0] = dirEntry.Path;
     vals[1] = dirEntry.Size.ToString();
     if (dirEntry.IsDirectory)
     {
         itemColor = _listViewDirForeColor;
         if (dirEntry.IsDirectory)
         {
             var val = dirEntry.Size.ToHRString()
                       + " <Dir";
             if (dirEntry.IsReparsePoint)
             {
                 val += " R";
             }
             if (dirEntry.IsSymbolicLink)
             {
                 val += " S";
             }
             vals[1] = val + ">";
         }
     }
     vals[2] = dirEntry.IsModifiedBad ? "<Bad Date>" : string.Format(_config.DateFormatYMDHMS, dirEntry.Modified);
     return(itemColor);
 }
Exemple #11
0
    public CsvFileSystem(DirEntry mountPoint, FileEntry device, OperatingSystem os)
    {
        this.device     = device;
        this.mountPoint = mountPoint;

        Load();
    }
Exemple #12
0
        public Texture2D LoadTexture(DirEntry entry)
        {
            Texture2D texture;

            if (_textures.TryGetValue(entry.Name, out texture))
            {
                return(texture);
            }

            var data = LoadData(entry);

            if (data[0] != 'D' || data[1] != 'D' || data[2] != 'S' || data[3] != ' ')
            {
                // Compressed
                data = FalcomDecompressor.Decompress(data);
            }

            using (var stream = new MemoryStream(data))
            {
                var image = DDS.LoadImage(stream);
                texture = new Texture2D(GraphicsDevice, image.Width, image.Height);
                texture.SetData(image.Data);
            }

            _textures[entry.Name] = texture;

            return(texture);
        }
Exemple #13
0
    public void CreateDirectory(DirEntry directory, DirectorySecurity directorySecurity)
    {
        var path = mountPoint.GetRelativePathTo(directory);
        var id   = GetOrCreateEntry(path);

        Save();
    }
Exemple #14
0
        public FileUserControl(DirEntry myFile)
        {
            try
            {
                ImageSource imageSource;
                InitializeComponent();

                DirEntry = myFile;

                if (MainWindow.User == myFile.FileOwner)
                {
                    imageSource = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\..\\..\\Resorces\\edit.png"));
                }
                else
                {
                    imageSource = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\..\\..\\Resorces\\edit-not-validated.png"));
                }

                imageIO.Source             = imageSource;
                nameLabel.Content          = myFile.FileName;
                TextBlockFileUse.Text      = "size file: " + myFile.FileSize.ToString() + " KB";
                TextBlockFileUseOwner.Text = "Owner:Rabbi " + myFile.FileOwner.ToString() + ".";

                if (myFile.FileOwner != MainWindow.User)
                {
                    //OpenAddOnlyMenuItem.Visibility = Visibility.Collapsed;
                    OpenMenuItem.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception exp)
            {
                ErrorHandling.ShowError(exp.Message);
            }
        }
Exemple #15
0
 private void DirEdit_Click(object sender, EventArgs e)
 {
     DirEntry.Enabled = true;
     DirEntry.Focus();
     button2.Visible = true;
     DirEdit.Visible = false;
 }
Exemple #16
0
        protected void InitRootWithDirDirFileWithDir()
        {
            InitRootWithDir();
            var dirEntry2 = new DirEntry(true)
            {
                Path = @"Test2"
            };
            var dirEntry3 = new DirEntry(true)
            {
                Path     = @"Test3",
                Size     = 12312,
                Modified = new DateTime(2009, 10, 03, 19, 17, 13, DateTimeKind.Unspecified),
            };
            var dirEntry4 = new DirEntry
            {
                Path     = @"Test4",
                Size     = 32312,
                Modified = new DateTime(2008, 10, 04, 20, 18, 14, DateTimeKind.Unspecified),
            };

            _dirEntry.Children.Add(dirEntry2);
            _rootEntry.Children.Add(dirEntry3);
            _rootEntry.Children.Add(dirEntry4);
            _rootEntry.SetInMemoryFields();
            _pairDirEntry = new PairDirEntry(_rootEntry, _dirEntry);

            _rootList.Add(_rootEntry);
        }
Exemple #17
0
        public Animation LoadAnimation(DirEntry entry)
        {
            Texture2D texture;
            var       chData = FalcomDecompressor.Decompress(LoadData(entry));

            using (var chStream = new MemoryStream(chData))
            {
                texture = AnimationLoader.LoadImage(GraphicsDevice, chStream);
            }

            ushort?[][,] animationInfo;
            var cpFile = Path.GetFileNameWithoutExtension(entry.Name);

            if (cpFile.EndsWith(" "))
            {
                cpFile = cpFile.Substring(0, cpFile.Length - 1) + "P";
            }
            var cpFileEntry = FindByName(cpFile, "_CP");
            var cpData      = FalcomDecompressor.Decompress(LoadData(cpFileEntry));

            using (var cpStream = new MemoryStream(cpData))
            {
                animationInfo = AnimationLoader.LoadInfo(cpStream);
            }

            return(new Animation(animationInfo, texture));
        }
Exemple #18
0
        public Stream GetFile(string path)
        {
            DirEntry e = Entries[path];

            stream.Seek(e.Offset, SeekOrigin.Begin);

            bool demoMode = false;

            switch (e.Type)
            {
            case DirEntryType.Store:
                // TODO: this is wrong
                byte[] raw = br.ReadBytes((int)e.Real);
                return(new MemoryStream(raw));

            case DirEntryType.DEM:
            case DirEntryType.Nehahra:
                demoMode = true;
                break;
            }

            byte[] compressed = br.ReadBytes((int)e.Size);
            //if (!demoMode)
            return(new ZlibStream(new MemoryStream(compressed), CompressionMode.Decompress));
        }
Exemple #19
0
 public UpdateHandle(DirEntry dirEntry)
 {
     DirEntry    = dirEntry;
     mountPoints = Directories.Where(d => d.isMountPoint).ToArray();
     Directories.Clear();
     Files.Clear();
 }
Exemple #20
0
        private Animation GetCharacterInfo(int id, out Vector3 position)
        {
            int chipIndex;

            position = Vector3.Zero;

            DirEntry animationEntry = null;

            if (id >= 257)
            {
                var chId = string.Format("CH{0:D5}", (id - 257) * 10);
                animationEntry = ResourceLoader.FindByName(chId);
            }
            else
            {
                var npc = GetNpcById(id);
                if (npc == null)
                {
                    return(null);
                }

                chipIndex = npc.ChipIndex;
                position  = ToPosition(npc.X, npc.Y, npc.Z);
                var chip = Scenario.ChipInfo[chipIndex];
                animationEntry = ResourceLoader.FindByIndex(chip.ChipIndex);
            }

            if (animationEntry == null)
            {
                return(null);
            }

            return(ResourceLoader.LoadAnimation(animationEntry));
        }
Exemple #21
0
        private int DirectoryCompare(DirEntry de1, DirEntry de2)
        {
            int compareResult;
            var directoryHelper = _clientForm.DirectoryListViewHelper;
            var column          = directoryHelper.SortColumn;

            switch (column)
            {
            case 0:     // SearchResult ListView Name column
                compareResult = de1.PathCompareWithDirTo(de2);
                break;

            case 1:     // SearchResult ListView Size column
                compareResult = de1.SizeCompareWithDirTo(de2);
                break;

            case 2:     // SearchResult ListView Modified column
                compareResult = de1.ModifiedCompareTo(de2);
                break;

            default:
                throw new Exception($"Problem column {column} not handled for sort.");
            }
            if (directoryHelper.ColumnSortOrder == SortOrder.Descending)
            {
                compareResult *= -1;
            }
            return(compareResult);
        }
Exemple #22
0
        public void SetFullPath_OnRootDirectory_SetsAllFullPaths()
        {
            var re = new RootEntry {
                Path = @"C:\"
            };
            var fe1 = new DirEntry {
                Path = "fe1"
            };
            var de2 = new DirEntry(true)
            {
                Path = "de2"
            };
            var fe3 = new DirEntry {
                Path = "fe3"
            };

            re.Children.Add(fe1);
            re.Children.Add(de2);
            de2.Children.Add(fe3);
            re.SetInMemoryFields();

            Assert.That(re.FullPath, Is.EqualTo(@"C:\"));
            Assert.That(fe1.FullPath, Is.Null); // Is.EqualTo(@"C:\fe1")); FullPath only set on directories to save memory.
            Assert.That(de2.FullPath, Is.EqualTo(@"C:\de2"));
            Assert.That(fe3.FullPath, Is.Null); //Is.EqualTo(@"C:\de2\fe3"));
        }
        public RenameFolderDialog(DirEntry dirEntry)
        {
            InitializeComponent();

            _dirEntry         = dirEntry;
            txt_new_name.Text = dirEntry.Name;
            txt_new_name.Focus();
        }
Exemple #24
0
        public void TraverseTreesCopyHash_RunWithDirEntry_Exception()
        {
            var reSource = new DirEntry {
                Path = "Moo"
            };

            Assert.Throws <ArgumentException>(() => reSource.TraverseTreesCopyHash(null), "source and destination must be not null.");
        }
Exemple #25
0
        public void FindFunc_Spec_for_substring_matcher()
        {
            FindOptions findOptions = null;
            RootEntry   rootEntry   = null;
            DirEntry    testFile    = null;

            before = () =>
            {
                findOptions = new FindOptions();
                rootEntry   = new RootEntry {
                    FullPath = @"C:\"
                };
                testFile = new DirEntry(false)
                {
                    Path = @"TestFile1"
                };
            };

            describe["with test entry \"TestFile1\""] = () => {
                describe["given that matcher excludes path"] = () => {
                    it["can't find \"x\""] = () => {
                        findOptions.Pattern = "x";
                        var matcher = findOptions.GetPatternMatcher();
                        matcher(rootEntry, testFile).should_be_false();
                    };

                    it["can find \"estFi\""] = () => {
                        findOptions.Pattern = "estFi";
                        var matcher = findOptions.GetPatternMatcher();
                        matcher(rootEntry, testFile).should_be_true();
                    };

                    it["can find \"testfile\" [note case variance]"] = () => {
                        findOptions.Pattern = "testfile";
                        var matcher = findOptions.GetPatternMatcher();
                        matcher(rootEntry, testFile).should_be_true();
                    };

                    it["can't find string \"C:\""] = () => {
                        findOptions.Pattern = @"C:";
                        var matcher = findOptions.GetPatternMatcher();
                        matcher(rootEntry, testFile).should_be_false();
                    };
                };

                describe["given that matcher includes path"] = () => {
                    before = () => {
                        findOptions.IncludePath = true;
                    };

                    it["can find string \"C:\" in name including path "] = () => {
                        findOptions.Pattern = @"C:";
                        var matcher = findOptions.GetPatternMatcher();
                        matcher(rootEntry, testFile).should_be_true();
                    };
                };
            };
        }
Exemple #26
0
 private void SelectFileInDirectoryTab(DirEntry dirEntry)
 {
     if (!dirEntry.IsDirectory)
     {
         var index           = _directoryList.IndexOf(dirEntry);
         var directoryHelper = _clientForm.DirectoryListViewHelper;
         directoryHelper.SelectItem(index);
     }
 }
Exemple #27
0
        public Texture2D LoadImage(DirEntry entry)
        {
            var chData = FalcomDecompressor.Decompress(LoadData(entry));

            using (var chStream = new MemoryStream(chData))
            {
                return(ChLoader.LoadImage(GraphicsDevice, entry.DatFilePath, entry.Name, chStream));
            }
        }
Exemple #28
0
 private static void AddDirectoryChildren(TreeNode treeNode, DirEntry dirEntry)
 {
     if (dirEntry.IsDirectory)
     {
         var newTreeNode = NewTreeNode(dirEntry);
         treeNode.Nodes.Add(newTreeNode);
         SetDummyChildNode(newTreeNode, dirEntry);
     }
 }
Exemple #29
0
    public DirEntry GetDirEntry(string name)
    {
        var dir = Directories.FirstOrDefault(d => d.Name == name);

        if (dir == null)
        {
            dir = new DirEntry(name, this);
        }

        return(dir);
    }
        public void TraverseTree_EmptyTree_ActionNotRun()
        {
            var mockAction = MockRepository.GenerateMock <TraverseFunc>();

            mockAction.Stub(x => x(null, null));
            var de = new DirEntry();

            de.TraverseTreePair(mockAction);

            mockAction.AssertWasNotCalled(x => x(null, null));
        }
Exemple #31
0
        /// <summary>
        /// Destroys the file with the given logical file name.
        /// </summary>
        public void Destroy(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                throw new FileSystemException("Cannot destroy a file with a null, empty, or pure whitespace name.");
            var nameBytes = Encoding.UTF8.GetBytes(fileName);
            if (nameBytes.Length > MaxFileNameLength)
                throw new FileSystemException("File name too long.");

            int descriptorIndex, directoryEntryIndex;
            if (!SearchDirectory(nameBytes, out directoryEntryIndex, out descriptorIndex))
                throw new FileSystemException("No such file exists.");
            if (descriptorIndex == 0)
                throw new FileSystemException("Cannot delete system directory file.");

            // Close open file table if neccessary.
            int fileHandle;
            if (SearchOpenFileTable(descriptorIndex, out fileHandle))
                Close(fileHandle);

            // Clear the entry from the directory file.
            var dirEntry = new DirEntry();
            WriteDirEntry(directoryEntryIndex, dirEntry);

            // Destroy descriptor.
            var descriptor = ReadDescriptor(descriptorIndex);
            // Free reserved blocks.
            for(int i = 0; i < MaxBlocksPerFile; i++)
            {
                // Break as soon as we find the first non-reserved index.
                if (descriptor.DiskMap[i] == -1)
                    break;
                SetBitmapBit(descriptor.DiskMap[i], false);
                ClearBlock(descriptor.DiskMap[i]);
                descriptor.DiskMap[i] = -1;
            }
            descriptor.Length = -1;
            WriteDescriptor(descriptorIndex, descriptor);
        }
Exemple #32
0
 private void WriteDirEntry(int dirEntryIndex, DirEntry entry)
 {
     var data = new byte[DirectoryEntrySize];
     IntToBytes(data, 0, entry.DescriptorIndex);
     for (int i = 0; i < MaxFileNameLength; i++)
         data[sizeof(int) + i] = entry.Name[i];
     Seek(0, dirEntryIndex * DirectoryEntrySize);
     FileWrite(0, data, DirectoryEntrySize);
 }
Exemple #33
0
        /// <summary>
        /// Creates a new file with the given logical file name.
        /// </summary>
        public void Create(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                throw new FileSystemException("Cannot create a file with a null, empty, or pure whitespace name.");
            var nameBytes = Encoding.UTF8.GetBytes(fileName);
            if (nameBytes.Length > MaxFileNameLength)
                throw new FileSystemException("File name too long.");
            int unused1, unused2;
            if (SearchDirectory(nameBytes, out unused1, out unused2))
                throw new FileSystemException("Duplicate file name.");

            int descriptorIndex = FindFreeDescriptor();
            var descriptor = new Descriptor();
            descriptor.Length = 0;
            WriteDescriptor(descriptorIndex, descriptor);

            int dirEntryIndex = FindFreeDirEntry();
            var dirEntry = new DirEntry();
            dirEntry.DescriptorIndex = descriptorIndex;
            for (int i = 0; i < nameBytes.Length; i++)
                dirEntry.Name[i] = nameBytes[i];
            WriteDirEntry(dirEntryIndex, dirEntry);
        }
Exemple #34
0
 private DirEntry ReadDirEntry(int dirEntryIndex)
 {
     var data = new byte[DirectoryEntrySize];
     Seek(0, dirEntryIndex * DirectoryEntrySize);
     FileRead(0, data, DirectoryEntrySize);
     var entry = new DirEntry();
     entry.DescriptorIndex = BytesToInt(data, 0);
     for (int i = 0; i < MaxFileNameLength; i++)
         entry.Name[i] = data[sizeof(int) + i];
     return entry;
 }
        public void Save(string strFilePdb, string strCreatorId, string strTypeId)
        {
            // First sort all the files by name

            string[] astrFileNames = new string[m_alsFiles.Count];
            for (int iFile = 0; iFile < m_alsFiles.Count; iFile++) {
                File file = (File)m_alsFiles[iFile];
                astrFileNames[iFile] = file.str.ToLower();
            }
            File[] afile = (File[])m_alsFiles.ToArray(typeof(File));
            Array.Sort(astrFileNames, afile, new FilenameComparer());

            // Create the record bytes

            ArrayList alsDirEntries = new ArrayList();
            ArrayList alsRecords = new ArrayList();
            ushort irec = 1;
            foreach (File file in afile) {
                // Get filename only, check length

                string strFile = file.str.ToLower();
                if (strFile.Length >= s_cbFilenameMax)
                    throw new Exception("The file " + strFile + " is too long. Must be " + (s_cbFilenameMax - 1) + "chars max.");

                // Read the file into chunks

                BinaryReader brdr = new BinaryReader(new MemoryStream(file.ab));
                byte crec = 0;
                while (brdr.BaseStream.Position < brdr.BaseStream.Length) {
                    int cbLeft = (int)(brdr.BaseStream.Length - brdr.BaseStream.Position);
                    int cbRead = cbLeft < s_cbRecordMax ? cbLeft : s_cbRecordMax;
                    byte[] abChunk = brdr.ReadBytes(cbRead);
                    alsRecords.Add(PackRecord(abChunk, file.fCompress));
                    crec++;
                }
                brdr.Close();

                // Make a directory entry for this file

                DirEntry de = new DirEntry();
                de.strFile = strFile;
                de.irec = irec;
                de.crec = crec;
                alsDirEntries.Add(de);
                irec += de.crec;

            #if false
                Console.WriteLine(de.strFile + ", " + de.crec + " recs");
            #endif
            }

            // Insert the record for the directory entries

            alsRecords.Insert(0, PackRecord(MakeDirectoryRecord(alsDirEntries), false));

            // Create and save a .pdb around these records

            PalmDatabase pdb = new PalmDatabase();
            pdb.SetRecordData(alsRecords);
            pdb.Name = Path.GetFileName(Path.GetFullPath(strFilePdb));
            pdb.CreatorId = IdFromString(strCreatorId);
            pdb.TypeId = IdFromString(strTypeId);
            pdb.Save(strFilePdb);
        }
Exemple #36
0
        DirEntry[] GetDirectory(Stream strm, bool checkOnly)
        {
            byte[] buf = new byte[4];
            byte[] fileList;
            DirEntry[] results;
            int files;
            string key = "";
            BinaryReader rd = new BinaryReader(strm);

            rd.Read(buf, 0, 4);
            files = FromBE(rd.ReadInt32());

            if ((Encoding.ASCII.GetString(buf, 0, 4) != "VIS3") || (files > (1 << 24)))
                return null;

            results = new DirEntry[files];
            if (checkOnly)
                return results;

            fileList = new byte[6 + files * 16];
            rd.Read(fileList, 0, fileList.Length);
            // find decryption key
            foreach (string s in DecryptionKeys)
            {
                byte[] tmp = Decrypt(fileList, s);
                if (Encoding.ASCII.GetString(tmp, 0, 3) == "HDR"
                    && tmp[3] == 0
                    && tmp[4] == 0
                    && tmp[5] == 0)
                {
                    key = s;
                    fileList = tmp;
                    break;
                }
            }
            if (key == "")
                throw new InvalidOperationException("Unknown encryption key");

            using (BinaryReader rd2 = new BinaryReader(new MemoryStream(fileList)))
            {
                rd2.BaseStream.Seek(3, SeekOrigin.Begin); // skip the 6 bytes ID
                for (int i = 0; i < files; i++)
                {
                    results[i].Offset = FromBE(rd2.ReadInt32());
                    results[i].CompressedSize = FromBE(rd2.ReadInt32());
                    results[i].Size = FromBE(rd2.ReadInt32());
                    results[i].Flags = FromBE(rd2.ReadInt32());
                }
                // we should read the final "END" marker here...
            }

            // populate file entry list
            return results;
        }
Exemple #37
0
        /// <summary>
        /// Resets the file system's state to its initial value.
        /// </summary>
        public void Init()
        {
            disk = new Disk(BlockCount, BlockSize);
            oft = new OftEntry[MaxOpenFiles];
            for (int i = 0; i < MaxOpenFiles; i++)
                oft[i] = new OftEntry();

            // Mark the blocks needed for the bitmap and
            // the file descriptors as reserved.
            for (int i = 0; i < BitmapBlockCount + DescriptorBlockCount; i++)
                SetBitmapBit(i, true);

            // Initialize all descriptors to blank.
            var descriptor = new Descriptor();
            for (int i = 1; i < DescriptorCount; i++)
                WriteDescriptor(i, descriptor);

            // Initialize the directory descriptor.
            descriptor.Length = 0;
            WriteDescriptor(0, descriptor);

            // Initialize directory's oft entry.
            var oftDir = oft[0];
            oftDir.DescriptorIndex = 0;

            // Initialize the directory file.
            var dirEntry = new DirEntry();
            for (int i = 1; i < DirectoryEntryCount; i++)
                WriteDirEntry(i, dirEntry);

            // Create the directory entry which describes the
            // directory itself.
            dirEntry.DescriptorIndex = 0;
            dirEntry.Name[0] = (byte)'d';
            dirEntry.Name[1] = (byte)'i';
            dirEntry.Name[2] = (byte)'r';
            WriteDirEntry(0, dirEntry);

            var dirDesc = ReadDescriptor(0);
        }