Example #1
0
        public GameFile()
        {
            Flags      = FileFlags.kAll;
            ShaContext = new SHA1CryptoServiceProvider();

            Header = new MediaHeader();
        }
Example #2
0
        public void Read(byte[] buffer, int offset)
        {
            Tag = Utilities.BytesToString(buffer, offset, 8);
            HeaderSize = Utilities.ToUInt32LittleEndian(buffer, 8);
            Version = Utilities.ToUInt32LittleEndian(buffer, 12);
            Flags = (FileFlags)Utilities.ToUInt32LittleEndian(buffer, 16);
            CompressionSize = Utilities.ToInt32LittleEndian(buffer, 20);
            WimGuid = Utilities.ToGuidLittleEndian(buffer, 24);
            PartNumber = Utilities.ToUInt16LittleEndian(buffer, 40);
            TotalParts = Utilities.ToUInt16LittleEndian(buffer, 42);
            ImageCount = Utilities.ToUInt32LittleEndian(buffer, 44);

            OffsetTableHeader = new ShortResourceHeader();
            OffsetTableHeader.Read(buffer, 48);

            XmlDataHeader = new ShortResourceHeader();
            XmlDataHeader.Read(buffer, 72);

            BootMetaData = new ShortResourceHeader();
            BootMetaData.Read(buffer, 96);

            BootIndex = Utilities.ToUInt32LittleEndian(buffer, 120);

            IntegrityHeader = new ShortResourceHeader();
            IntegrityHeader.Read(buffer, 124);
        }
Example #3
0
        /// <summary>
        /// CreateFile2 wrapper. Only available on Windows 8 and above.
        /// </summary>
        public static unsafe SafeFileHandle CreateFile2(
            StringSpan path,
            DesiredAccess desiredAccess,
            ShareModes shareMode,
            CreationDisposition creationDisposition,
            FileAttributes fileAttributes     = FileAttributes.None,
            FileFlags fileFlags               = FileFlags.None,
            SecurityQosFlags securityQosFlags = SecurityQosFlags.None)
        {
            CREATEFILE2_EXTENDED_PARAMETERS extended = new CREATEFILE2_EXTENDED_PARAMETERS()
            {
                dwSize             = (uint)sizeof(CREATEFILE2_EXTENDED_PARAMETERS),
                dwFileAttributes   = fileAttributes,
                dwFileFlags        = fileFlags,
                dwSecurityQosFlags = securityQosFlags
            };

            SafeFileHandle handle = Imports.CreateFile2(
                lpFileName: ref MemoryMarshal.GetReference(path.GetSpanWithoutTerminator()),
                dwDesiredAccess: desiredAccess,
                dwShareMode: shareMode,
                dwCreationDisposition: creationDisposition,
                pCreateExParams: ref extended);

            if (handle.IsInvalid)
            {
                throw Error.GetExceptionForLastError(path.ToString());
            }

            return(handle);
        }
Example #4
0
        /// <summary>
        /// CreateFile wrapper that attempts to use CreateFile2 if running as Windows Store app.
        /// </summary>
        public static SafeFileHandle CreateFile(
            string path,
            DesiredAccess desiredAccess,
            ShareMode shareMode,
            CreationDisposition creationDisposition,
            FileAttributes fileAttributes     = FileAttributes.NONE,
            FileFlags fileFlags               = FileFlags.NONE,
            SecurityQosFlags securityQosFlags = SecurityQosFlags.NONE)
        {
            // Prefer CreateFile2, falling back to CreateFileEx if we can
            if (s_createFileDelegate == null)
            {
                s_createFileDelegate = CreateFile2;
                try
                {
                    return(s_createFileDelegate(path, desiredAccess, shareMode, creationDisposition, fileAttributes, fileFlags, securityQosFlags));
                }
                catch (Exception exception)
                {
                    // Any error other than EntryPointNotFound we've found CreateFile2, rethrow
                    if (!ErrorHelper.IsEntryPointNotFoundException(exception))
                    {
                        throw;
                    }

                    s_createFileDelegate = Delegates.CreateDelegate <CreateFileDelegate>(
                        "WInterop.FileManagement.Desktop.NativeMethods, " + Delegates.DesktopLibrary,
                        "CreateFileW");
                }
            }

            return(s_createFileDelegate(path, desiredAccess, shareMode, creationDisposition, fileAttributes, fileFlags, securityQosFlags));
        }
Example #5
0
 /// <summary>
 /// Creates a new file.
 /// </summary>
 public BinderFile(FileFlags flags, int id, string name, byte[] bytes)
 {
     Flags = flags;
     ID    = id;
     Name  = name;
     Bytes = bytes;
 }
Example #6
0
        public FileFlags GenerateFilesFlag()
        {
            FileFlags res = 0;

            foreach (var ext in Extensions)
            {
                foreach (FileFlags type in Enum.GetValues(typeof(FileFlags)))
                {
                    ExtensionsAttribute attribute = type.GetType()
                                                    .GetField(type.ToString())
                                                    .GetCustomAttributes(typeof(ExtensionsAttribute), false)
                                                    .SingleOrDefault() as ExtensionsAttribute;

                    if (attribute != null && attribute.IsValidFor(ext))
                    {
                        res |= type;
                    }
                }
            }

            if (res == 0)
            {
                res |= Format.FileFlags.Misc;
            }

            return(res);
        }
Example #7
0
 public FileSystemServer()
 {
     Runtime.UpdateFrequency = UpdateFrequency.Update1;
     try
     {
         StorageReader storage_data = new StorageReader(Storage);
         if (Storage.Length > 0)
         {
             uint num_users = storage_data.ReadUInt32();
             for (uint i = 0U; i != num_users; i++)
             {
                 string user_name = storage_data.ReadString();
                 string password  = storage_data.ReadString();
                 if (!(users.ContainsKey(user_name)))
                 {
                     users.Add(user_name, new User(user_name, password));
                 }
             }
             uint num_files = storage_data.ReadUInt32();
             for (uint i = 0U; i != num_files; i++)
             {
                 string    path             = storage_data.ReadString();
                 string    owner            = storage_data.ReadString();
                 FileFlags read_write_flags = (FileFlags)(storage_data.ReadByte());
                 byte[]    data             = storage_data.ReadByteSequence();
                 files.Add(path, new File(path, owner, (read_write_flags & FileFlags.CanEveryoneRead) == FileFlags.CanEveryoneRead, (read_write_flags & FileFlags.CanEveryoneWrite) == FileFlags.CanEveryoneWrite, data));
             }
         }
     }
     catch (StorageReaderArgumentException e)
     {
         Echo(e.ToString());
     }
     fileSystemListener = IGC.RegisterBroadcastListener(fileSystemServerTag);
 }
Example #8
0
        public CopyFileParams(bool overwrite       = true, FileFlags flags = FileFlags.None, FileMetadataCopier?metadataCopier = null, int bufferSize = 0, bool asyncCopy = true,
                              bool ignoreReadError = false, int ignoreReadErrorSectorSize = 0,
                              ProgressReporterFactoryBase?reporterFactory = null)
        {
            if (metadataCopier == null)
            {
                metadataCopier = DefaultFileMetadataCopier;
            }
            if (bufferSize <= 0)
            {
                bufferSize = CoresConfig.FileUtilSettings.FileCopyBufferSize;
            }
            if (reporterFactory == null)
            {
                reporterFactory = NullReporterFactory;
            }
            if (ignoreReadErrorSectorSize <= 0)
            {
                ignoreReadErrorSectorSize = CoresConfig.FileUtilSettings.DefaultSectorSize;
            }

            this.Overwrite                 = overwrite;
            this.Flags                     = flags;
            this.MetadataCopier            = metadataCopier;
            this.BufferSize                = bufferSize;
            this.AsyncCopy                 = asyncCopy;
            this.ProgressReporterFactory   = reporterFactory;
            this.IgnoreReadError           = ignoreReadError;
            this.IgnoreReadErrorSectorSize = ignoreReadErrorSectorSize;
        }
Example #9
0
        // Token: 0x06001AC7 RID: 6855 RVA: 0x0007318C File Offset: 0x0007138C
        private SafeFileHandle OpenFile(string filename, bool openForRead)
        {
            FileMode   creationDisposition;
            FileShare  fileShare;
            FileAccess fileAccess;

            if (openForRead)
            {
                creationDisposition = FileMode.Open;
                fileShare           = FileShare.None;
                fileAccess          = FileAccess.Read;
            }
            else
            {
                creationDisposition = FileMode.Create;
                fileShare           = FileShare.None;
                fileAccess          = FileAccess.Write;
            }
            FileFlags      flags          = FileFlags.FILE_FLAG_NO_BUFFERING;
            SafeFileHandle safeFileHandle = NativeMethods.CreateFile(filename, fileAccess, fileShare, IntPtr.Zero, creationDisposition, flags, IntPtr.Zero);

            if (safeFileHandle.IsInvalid)
            {
                throw new IOException(string.Format("CreateFile({0}) = {1}", filename, Marshal.GetLastWin32Error().ToString()), new Win32Exception());
            }
            return(safeFileHandle);
        }
Example #10
0
        /// <summary>
        /// CreateFile2 wrapper. Only available on Windows 8 and above.
        /// </summary>
        public static unsafe SafeFileHandle CreateFile2(
            string path,
            DesiredAccess desiredAccess,
            ShareModes shareMode,
            CreationDisposition creationDisposition,
            FileAttributes fileAttributes     = FileAttributes.None,
            FileFlags fileFlags               = FileFlags.None,
            SecurityQosFlags securityQosFlags = SecurityQosFlags.None)
        {
            CREATEFILE2_EXTENDED_PARAMETERS extended = new CREATEFILE2_EXTENDED_PARAMETERS()
            {
                dwSize             = (uint)sizeof(CREATEFILE2_EXTENDED_PARAMETERS),
                dwFileAttributes   = fileAttributes,
                dwFileFlags        = fileFlags,
                dwSecurityQosFlags = securityQosFlags
            };

            SafeFileHandle handle = Imports.CreateFile2(
                lpFileName: path,
                dwDesiredAccess: desiredAccess,
                dwShareMode: shareMode,
                dwCreationDisposition: creationDisposition,
                pCreateExParams: ref extended);

            if (handle.IsInvalid)
            {
                throw Errors.GetIoExceptionForLastError(path);
            }

            return(handle);
        }
Example #11
0
        /// <summary>
        /// CreateFile2 wrapper. Only available on Windows 8 and above.
        /// </summary>
        public static SafeFileHandle CreateFile2(
            string path,
            DesiredAccess desiredAccess,
            ShareMode shareMode,
            CreationDisposition creationDisposition,
            FileAttributes fileAttributes     = FileAttributes.NONE,
            FileFlags fileFlags               = FileFlags.NONE,
            SecurityQosFlags securityQosFlags = SecurityQosFlags.NONE)
        {
            CREATEFILE2_EXTENDED_PARAMETERS extended = new CREATEFILE2_EXTENDED_PARAMETERS();

            extended.dwSize             = (uint)Marshal.SizeOf <CREATEFILE2_EXTENDED_PARAMETERS>();
            extended.dwFileAttributes   = fileAttributes;
            extended.dwFileFlags        = fileFlags;
            extended.dwSecurityQosFlags = securityQosFlags;
            unsafe
            {
                extended.lpSecurityAttributes = null;
            }
            extended.hTemplateFile = IntPtr.Zero;

            SafeFileHandle handle = Direct.CreateFile2(
                lpFileName: path,
                dwDesiredAccess: desiredAccess,
                dwShareMode: shareMode,
                dwCreationDisposition: creationDisposition,
                pCreateExParams: ref extended);

            if (handle.IsInvalid)
            {
                throw ErrorHelper.GetIoExceptionForLastError();
            }

            return(handle);
        }
Example #12
0
        public void Read(IO.EndianReader s)
        {
            s.Owner = this;

            Flags   = s.Read(FileFlagsStreamer.Instance);
            Version = s.ReadUInt16();
            if (Version != kVersion)
            {
                throw new IO.VersionMismatchException(s.BaseStream,
                                                      kVersion, Version);
            }

            Read(s, EnumFlags.Test(Flags, FileFlags.EncryptHeader), Header, MediaHeader.kSizeOf);
            GenerateHash();

            if (EnumFlags.Test(Flags, FileFlags.CompressContent))
            {
                using (var cs = new CompressedStream(true))
                {
                    Read(s, EnumFlags.Test(Flags, FileFlags.EncryptContent), cs,
                         userKey: Header.DataCryptKey, readLeftovers: ReadLeftovers);

                    cs.Decompress();
                    Content = cs.UncompressedData;
                }
            }
            else
            {
                Content = s.ReadBytes((int)(s.BaseStream.Length - s.BaseStream.Position));
            }
        }
Example #13
0
        public void Read(byte[] buffer, int offset)
        {
            Tag             = Utilities.BytesToString(buffer, offset, 8);
            HeaderSize      = Utilities.ToUInt32LittleEndian(buffer, 8);
            Version         = Utilities.ToUInt32LittleEndian(buffer, 12);
            Flags           = (FileFlags)Utilities.ToUInt32LittleEndian(buffer, 16);
            CompressionSize = Utilities.ToInt32LittleEndian(buffer, 20);
            WimGuid         = Utilities.ToGuidLittleEndian(buffer, 24);
            PartNumber      = Utilities.ToUInt16LittleEndian(buffer, 40);
            TotalParts      = Utilities.ToUInt16LittleEndian(buffer, 42);
            ImageCount      = Utilities.ToUInt32LittleEndian(buffer, 44);

            OffsetTableHeader = new ShortResourceHeader();
            OffsetTableHeader.Read(buffer, 48);

            XmlDataHeader = new ShortResourceHeader();
            XmlDataHeader.Read(buffer, 72);

            BootMetaData = new ShortResourceHeader();
            BootMetaData.Read(buffer, 96);

            BootIndex = Utilities.ToUInt32LittleEndian(buffer, 120);

            IntegrityHeader = new ShortResourceHeader();
            IntegrityHeader.Read(buffer, 124);
        }
Example #14
0
        // load a single sheet from a book
        void _btnLoadSheet_Click(object sender, System.EventArgs e)
        {
            // choose file
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.DefaultExt = "xls";
            dlg.FileName   = "*.xls";
            if (dlg.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            // clear data source, if any
            _flex.DataSource = null;
            string[] sheets = _flex.LoadExcelSheetNames(dlg.FileName);
            Console.WriteLine("Found {0} sheets in this book.", sheets.Length);
            foreach (string sheet in sheets)
            {
                Console.WriteLine(" - {0}", sheet);
            }

            // load the first sheet in the book
            FileFlags flags = (_chkFixed.Checked)? FileFlags.IncludeFixedCells: FileFlags.None;

            _flex.LoadGrid(dlg.FileName, FileFormatEnum.Excel, flags);
        }
 public FileInstallInfo(string fileName, string destinationFolder, FileFlags flags, DateTime fileDate)
 {
     FileName          = fileName;
     DestinationFolder = destinationFolder;
     Flags             = flags;
     FileDate          = fileDate;
 }
 public DirectoryRecord(byte[] buffer, int offset, Encoding enc)
 {
     name        = "";
     FileVersion = 0;
     directorys  = new Dictionary <string, DirectoryRecord>();
     files       = new Dictionary <string, DirectoryRecord>();
     checked
     {
         recordLength = buffer[0 + offset];
         if (recordLength <= 0)
         {
             return;
         }
         sectorsInExtendedRecord = buffer[1 + offset];
         firstDataSector         = BitConverter.ToUInt32(buffer, 2 + offset);
         dataLength = BitConverter.ToUInt32(buffer, 10 + offset);
         Length     = dataLength;
         try
         {
             DateTime dateTime  = new DateTime(1900 + unchecked ((int)buffer[checked (18 + offset)]), buffer[19 + offset], buffer[20 + offset], buffer[21 + offset], buffer[22 + offset], buffer[23 + offset]);
             DateTime dateTime2 = dateTime;
             RecordingDateAndTime = dateTime2.AddHours(4 *unchecked ((int)buffer[checked (24 + offset)]));
         }
         catch (Exception projectError)
         {
             ProjectData.SetProjectError(projectError);
             RecordingDateAndTime = DateTime.Now;
             ProjectData.ClearProjectError();
         }
     }
     flags = (FileFlags)buffer[checked (25 + offset)];
     checked
     {
         fileUnitSize  = buffer[26 + offset];
         interleaveGap = buffer[27 + offset];
         volSeqNumber  = BitConverter.ToUInt16(buffer, 28 + offset);
         nameLength    = buffer[32 + offset];
         if (nameLength == 1 && (buffer[33 + offset] == 0 || buffer[33 + offset] == 1))
         {
             if (buffer[33 + offset] == 0)
             {
                 name = ".";
             }
             else
             {
                 name = "..";
             }
         }
         else
         {
             name = enc.GetString(buffer, 33 + offset, nameLength);
             if (Strings.InStr(name, ";") != 0)
             {
                 FileVersion = (byte)Conversions.ToInteger(Strings.Split(name, ";")[1]);
                 name        = Strings.Split(name, ";")[0];
             }
         }
         isDirectory = Conversions.ToBoolean(Interaction.IIf(flags == FileFlags.Directory, true, false));
     }
 }
Example #17
0
    protected override async Task DeleteFileImplAsync(string path, FileFlags flags = FileFlags.None, CancellationToken cancel = default)
    {
        using (VfsPathParserContext ctx = await ParsePathInternalAsync(path, cancel))
        {
            if (ctx.Exception != null)
            {
                throw ctx.Exception;
            }

            if (ctx.LastEntity is VfsFile file)
            {
                Debug.Assert(ctx.EntityStack.Count >= 2);
                Debug.Assert(ctx.EntityStack.Last() == file);
                VfsDirectory parentDir = (ctx.EntityStack[ctx.EntityStack.Count - 2] as VfsDirectory) !;
                Debug.Assert(parentDir != null);

                file.ReleaseHandleRef();
                ctx.EntityStack.RemoveAt(ctx.EntityStack.Count - 1);

                await parentDir.RemoveFileAsync(file, cancel);
            }
            else
            {
                throw new VfsNotFoundException(path, "File not found.");
            }
        }
    }
Example #18
0
        /// <summary>
        /// CreateFile wrapper that attempts to use CreateFile2 if running as Windows Store app.
        /// </summary>
        public static SafeFileHandle CreateFile(
            StringSpan path,
            CreationDisposition creationDisposition,
            DesiredAccess desiredAccess       = DesiredAccess.GenericReadWrite,
            ShareModes shareMode              = ShareModes.ReadWrite,
            FileAttributes fileAttributes     = FileAttributes.None,
            FileFlags fileFlags               = FileFlags.None,
            SecurityQosFlags securityQosFlags = SecurityQosFlags.None)
        {
            // Prefer CreateFile2, falling back to CreateFileEx if we can
            if (s_createFileDelegate == null)
            {
                s_createFileDelegate = CreateFile2;
                try
                {
                    return(s_createFileDelegate(path, desiredAccess, shareMode, creationDisposition, fileAttributes, fileFlags, securityQosFlags));
                }
                catch (EntryPointNotFoundException)
                {
                    s_createFileDelegate = Delegates.CreateDelegate <CreateFileDelegate>(
                        "WInterop.Storage.Desktop.NativeMethods, " + Delegates.DesktopLibrary,
                        "CreateFileW");
                }
            }

            return(s_createFileDelegate(path, desiredAccess, shareMode, creationDisposition, fileAttributes, fileFlags, securityQosFlags));
        }
 internal static extern SafeFileHandle CreateFile(
     string lpFileName,
     DesiredAccesses dwDesiredAccess,
     ShareModes dwShareMode,
     ref SECURITY_ATTRIBUTES lpSecurityAttributes,
     int dwCreationDisposition,
     FileFlags dwFlagsAndAttributes,
     int hTemplateFile);
Example #20
0
 public static extern SafeFileHandle CreateFile(
     string filename,
     [MarshalAs(UnmanagedType.U4)] FileAccessAPI access,
     [MarshalAs(UnmanagedType.U4)] FileShare share,
     IntPtr securityAttributes,                                                          // optional SECURITY_ATTRIBUTES struct or IntPtr.Zero
     [MarshalAs(UnmanagedType.U4)] FileMode creation,
     [MarshalAs(UnmanagedType.U4)] FileFlags flagsAndAttributes,
     IntPtr templateFile);
Example #21
0
 /// <summary>
 /// Creates a new file.
 /// </summary>
 public BinderFile(FileFlags flags, int id, string name, byte[] bytes)
 {
     Flags           = flags;
     ID              = id;
     Name            = name;
     Bytes           = bytes;
     CompressionType = DCX.Type.Zlib;
 }
Example #22
0
        public FileChannel CreateFile([NotNull] string file, long offset = 0, long lenght = 0,
                                      FileFlags flags = FileFlags.Default)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));

            int handle = Bass.BASS_StreamCreateFile(file, offset, lenght, (BASSFlag) flags);
            return new FileChannel(handle);
        }
Example #23
0
 internal FileRow(
     FileFlags flags,
     uint name,
     uint hashValue)
 {
     this.Flags     = flags;
     this.Name      = name;
     this.HashValue = hashValue;
 }
Example #24
0
 public unsafe static extern HResult StgCreateStorageEx(
     string pwcsName,
     StorageMode grfMode,
     StorageFormat stgfmt,
     FileFlags grfAttrs,
     STGOPTIONS *pStgOptions,
     SECURITY_DESCRIPTOR **pSecurityDescriptor,
     ref Guid riid,
     [MarshalAs(UnmanagedType.IUnknown)] out object ppObjectOpen);
Example #25
0
 public unsafe static extern HResult StgOpenStorageEx(
     string pwcsName,
     StorageMode grfMode,
     StorageFormat stgfmt,
     FileFlags grfAttrs,
     STGOPTIONS *pStgOptions,
     void *reserved2,
     ref Guid riid,
     [MarshalAs(UnmanagedType.IUnknown)] out object ppObjectOpen);
 internal FileRow(
   FileFlags flags,
   uint name,
   uint hashValue)
 {
     this.Flags = flags;
     this.Name = name;
     this.HashValue = hashValue;
 }
 private static extern SafeFileHandle CreateFile
 (
     [MarshalAs(UnmanagedType.LPTStr)] string fileName,
     [MarshalAs(UnmanagedType.U4)] Access desiredAccess,
     [MarshalAs(UnmanagedType.U4)] FileShare shareMode,
     IntPtr securityAttributes, // optional SECURITY_ATTRIBUTES struct or IntPtr.Zero
     [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
     [MarshalAs(UnmanagedType.U4)] FileFlags flagsAndAttributes,
     IntPtr templateFile
 );
Example #28
0
        // Get the file's chunk size
        public static int GetChunkSize(FileFlags flags)
        {
            bool bitsVaries = (flags & FileFlags.BitsVaries) != 0;

            if (bitsVaries)
            {
                return(Marshal.SizeOf(IntPtr.Size == 8 ? typeof(Chunk4) : typeof(Chunk8)));
            }
            return(Marshal.SizeOf(IntPtr.Size == 8 ? typeof(Chunk8) : typeof(Chunk4)));
        }
Example #29
0
 private BinderFileHeader(FileFlags flags, int id, string name, long compressedSize, long uncompressedSize, long dataOffset)
 {
     Flags            = flags;
     ID               = id;
     Name             = name;
     CompressionType  = DCX.Type.Zlib;
     CompressedSize   = compressedSize;
     UncompressedSize = uncompressedSize;
     DataOffset       = dataOffset;
 }
Example #30
0
 public FileHiveStorageOptions(FileSystem fileSystem, string rootDirectoryPath, FileFlags flags = FileFlags.WriteOnlyIfChanged,
                               int maxDataSize = int.MaxValue, bool singleInstance = false, bool putGitIgnore = false, bool globalLock = false)
     : base(maxDataSize)
 {
     this.FileSystem        = fileSystem;
     this.RootDirectoryPath = rootDirectoryPath;
     this.Flags             = flags;
     this.SingleInstance    = singleInstance;
     this.PutGitIgnore      = putGitIgnore;
     this.GlobalLock        = globalLock;
 }
Example #31
0
        // buffer offset util
        protected int GetNextBlock(out ChunkInd dataChunk, BinaryReader reader, FileFlags flags)
        {
            bool swap   = false;
            bool varies = false;

            if ((flags & FileFlags.EndianSwap) == FileFlags.EndianSwap)
            {
                swap = true;
            }
            if ((flags & FileFlags.BitsVaries) == FileFlags.BitsVaries)
            {
                varies = true;
            }

            if (swap)
            {
                throw new NotImplementedException();
            }

            dataChunk = new ChunkInd();

            if (IntPtr.Size == 8)
            {
                if (varies)
                {
                    ChunkPtr4 c = new ChunkPtr4(reader);
                    dataChunk = new ChunkInd(ref c);
                }
                else
                {
                    ChunkPtr8 c = new ChunkPtr8(reader);
                    dataChunk = new ChunkInd(ref c);
                }
            }
            else
            {
                if (varies)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    ChunkPtr4 c = new ChunkPtr4(reader);
                    dataChunk = new ChunkInd(ref c);
                }
            }

            if (dataChunk.Length < 0)
            {
                return(-1);
            }

            return(dataChunk.Length + ChunkUtils.GetOffset(flags));
        }
Example #32
0
        static void Main(string[] args)
        {
            //System.IO.FileAttributes
            FileFlags fileState = FileFlags.Directory | FileFlags.Encrypted;

            if (fileState.HasFlag(FileFlags.Directory))
            {
                // this is a directory
            }
            Console.WriteLine(fileState);
        }
Example #33
0
        public string HashString()
        {
            string hash = CreationTime.ToBinary().ToString() +
                          (Description ?? "").GetHashCode().ToString() +
                          FileFlags.GetHashCode().ToString() +
                          MD5.GetHashCode().ToString() +
                          Size.GetHashCode().ToString() +
                          Version.GetHashCode().ToString();

            return(IO.MD5FromString(hash));
        }
Example #34
0
        public static int GetOffset(FileFlags flags)
        {
            // if the file is saved in a
            // different format, get the
            // file's chunk size

            if (IntPtr.Size == 8)
            {
                if ((flags & FileFlags.BitsVaries) != 0)
                    return Marshal.SizeOf(typeof(ChunkPtr4));
                else
                    return Marshal.SizeOf(typeof(ChunkPtr8));
            }

            if ((flags & FileFlags.BitsVaries) != 0)
                return Marshal.SizeOf(typeof(ChunkPtr8));
            return Marshal.SizeOf(typeof(ChunkPtr4));
        }
Example #35
0
        public override void Read(BufferReader reader, RecordHeader header)
        {
            base.Read(reader, header);

            flags = (FileFlags)reader.ReadInt16();
            branchFile = reader.ReadString(8);
            reader.Skip(2); // reserved; always 0
            branchOffset = reader.ReadInt32();
            projectOffset = reader.ReadInt32();
            branchCount = reader.ReadInt16();
            projectCount = reader.ReadInt16();
            firstCheckoutOffset = reader.ReadInt32();
            lastCheckoutOffset = reader.ReadInt32();
            dataCrc = (uint)reader.ReadInt32();
            reader.Skip(8); // reserved; always 0
            lastRevDateTime = reader.ReadDateTime();
            modificationDateTime = reader.ReadDateTime();
            creationDateTime = reader.ReadDateTime();
            // remaining appears to be trash
        }
Example #36
0
            public DirectoryRecord(byte[] data, uint offset, bool isRootDirectory = false)
            {
                IsRootDirectory = isRootDirectory;

                RecordLength = data[offset + 0];
                ExtAttrRecordLength = data[offset + 1];
                LBALocation = ByteConverter.ToUInt32(data, offset + 2);
                DataLength = ByteConverter.ToUInt32(data, offset + 10);
                RecordingDateTime = new DateTime(data, offset + 18);
                TheFileFlags = (FileFlags)data[offset + 25];
                FileUnitSize = data[offset + 26];
                FileInterleaveGapSize = data[offset + 27];
                VolumeSequenceNumber = ByteConverter.ToUInt16(data, offset + 28);
                FileIdentifierLength = data[offset + 32];
                FileIdentifier = IsRootDirectory ? "ROOT_DIRECTORY" : ByteConverter.GetASCIIStringFromASCII(data, offset + 33, FileIdentifierLength);
            }
			internal BSAHeader4(BinaryReader br)
			{
				br.BaseStream.Position += 4;
				bsaVersion = br.ReadUInt32();
				directorySize = br.ReadInt32();
				archiveFlags = br.ReadInt32();
				folderCount = br.ReadInt32();
				fileCount = br.ReadInt32();
				totalFolderNameLength = br.ReadInt32();
				totalFileNameLength = br.ReadInt32();
				fileFlags = (FileFlags)br.ReadInt32();
			}
 private bool fileFlags_HasFlag(FileFlags fileFlags1, FileFlags fileFlags2)
 {
     return (((fileFlags1 & fileFlags2)) == fileFlags2);
 }
Example #39
0
 // Get the file's chunk size
 public static int GetChunkSize(FileFlags flags)
 {
     bool bitsVaries = (flags & FileFlags.BitsVaries) != 0;
     if (bitsVaries)
     {
         return Marshal.SizeOf(IntPtr.Size == 8 ? typeof(Chunk4) : typeof(Chunk8));
     }
     return Marshal.SizeOf(IntPtr.Size == 8 ? typeof(Chunk8) : typeof(Chunk4));
 }
 private bool FileHeader_HasFlag(FileFlags fileFlags1, FileFlags fileFlags2)
 {
     return (fileFlags1&fileFlags2)==fileFlags2;
 }
Example #41
0
        // buffer offset util
        protected int GetNextBlock(out ChunkInd dataChunk, BinaryReader reader, FileFlags flags)
        {
            bool swap = false;
            bool varies = false;

            if ((flags & FileFlags.EndianSwap) == FileFlags.EndianSwap)
                swap = true;
            if ((flags & FileFlags.BitsVaries) == FileFlags.BitsVaries)
                varies = true;

            if (swap)
            {
                throw new NotImplementedException();
            }

            dataChunk = new ChunkInd();

            if (IntPtr.Size == 8)
            {
                if (varies)
                {
                    ChunkPtr4 c = new ChunkPtr4(reader);
                    dataChunk = new ChunkInd(ref c);
                }
                else
                {
                    ChunkPtr8 c = new ChunkPtr8(reader);
                    dataChunk = new ChunkInd(ref c);
                }
            }
            else
            {
                if (varies)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    ChunkPtr4 c = new ChunkPtr4(reader);
                    dataChunk = new ChunkInd(ref c);
                }
            }

            if (dataChunk.Length < 0)
                return -1;

            return dataChunk.Length + ChunkUtils.GetOffset(flags);
        }
Example #42
0
        protected void ParseHeader()
        {
            string header = Encoding.UTF8.GetString(_fileBuffer, 0, SizeOfBlenderHeader);
            if (!header.Substring(0, 6).Equals(_headerString.Substring(0, 6)))
            {
                return;
            }

            if (header[6] == 'd')
            {
                _flags |= FileFlags.DoublePrecision;
            }

            int.TryParse(header.Substring(9), out _version);

            // swap ptr sizes...
            if (header[7] == '-')
            {
                _flags |= FileFlags.File64;
                if (IntPtr.Size != 8)
                    _flags |= FileFlags.BitsVaries;
            }
            else if (IntPtr.Size == 8)
            {
                _flags |= FileFlags.BitsVaries;
            }

            // swap endian...
            if (header[8] == 'V')
            {
                if (BitConverter.IsLittleEndian)
                    _flags |= FileFlags.EndianSwap;
            }
            else
            {
                if (!BitConverter.IsLittleEndian)
                    _flags |= FileFlags.EndianSwap;
            }

            _flags |= FileFlags.OK;
        }
Example #43
0
        protected void ParseInternal(FileVerboseMode verboseMode, byte[] memDna)
        {
            if ((_flags & FileFlags.OK) != FileFlags.OK)
            {
                return;
            }

            ChunkInd dna = new ChunkInd();
            dna.OldPtr = 0;

            MemoryStream memory = new MemoryStream(_fileBuffer, false);
            BinaryReader reader = new BinaryReader(memory);

            int i = 0;
            while (memory.Position < memory.Length)
            {
                // looking for the data's starting position
                // and the start of SDNA decls

                byte[] code = reader.ReadBytes(4);
                string codes = ASCIIEncoding.ASCII.GetString(code);

                if (_dataStart == 0 && codes.Equals("REND"))
                {
                    _dataStart = memory.Position;
                }

                if (codes.Equals("DNA1"))
                {
                    // read the DNA1 block and extract SDNA
                    reader.BaseStream.Position = i;
                    if (GetNextBlock(out dna, reader, _flags) > 0)
                    {
                        string sdnaname = ASCIIEncoding.ASCII.GetString(reader.ReadBytes(8));
                        if (sdnaname.Equals("SDNANAME"))
                        {
                            dna.OldPtr = i + ChunkUtils.GetOffset(_flags);
                        }
                        else
                        {
                            dna.OldPtr = 0;
                        }
                    }
                    else
                    {
                        dna.OldPtr = 0;
                    }
                }
                else if (codes.Equals("SDNA"))
                {
                    // Some Bullet files are missing the DNA1 block
                    // In Blender it's DNA1 + ChunkUtils::getOffset() + SDNA + NAME
                    // In Bullet tests its SDNA + NAME

                    dna.OldPtr = i;
                    dna.Length = (int)memory.Length - i;

                    // Also no REND block, so exit now.
                    if (_version == 276)
                    {
                        break;
                    }
                }

                if (_dataStart != 0 && dna.OldPtr != 0)
                {
                    break;
                }

                i++;
                memory.Position = i;
            }

            if (dna.OldPtr == 0 || dna.Length == 0)
            {
                //Console.WriteLine("Failed to find DNA1+SDNA pair");
                _flags &= ~FileFlags.OK;
                reader.Dispose();
                memory.Dispose();
                return;
            }

            _fileDna = new Dna();

            // _fileDna.Init will convert part of DNA file endianness to current CPU endianness if necessary
            memory.Position = dna.OldPtr;
            _fileDna.Init(reader, (_flags & FileFlags.EndianSwap) != 0);

            if (_version == 276)
            {
                for (i = 0; i < _fileDna.NumNames; i++)
                {
                    if (_fileDna.GetName(i).Equals("int"))
                    {
                        _flags |= FileFlags.BrokenDna;
                    }
                }
                if ((_flags & FileFlags.BrokenDna) == FileFlags.BrokenDna)
                {
                    //Console.WriteLine("warning: fixing some broken DNA version");
                }
            }

            //if ((verboseMode & FileVerboseMode.DumpDnaTypeDefinitions) == FileVerboseMode.DumpDnaTypeDefinitions)
            //    _fileDna.DumpTypeDefinitions();

            _memoryDna = new Dna();
            using (MemoryStream memory2 = new MemoryStream(memDna, false))
            {
                using (BinaryReader reader2 = new BinaryReader(memory2))
                {
                    _memoryDna.Init(reader2, !BitConverter.IsLittleEndian);
                }
            }

            if (_memoryDna.NumNames != _fileDna.NumNames)
            {
                _flags |= FileFlags.VersionVaries;
                //Console.WriteLine ("Warning, file DNA is different than built in, performance is reduced. Best to re-export file with a matching version/platform");
            }

            if (_memoryDna.LessThan(_fileDna))
            {
                //Console.WriteLine ("Warning, file DNA is newer than built in.");
            }

            _fileDna.InitCmpFlags(_memoryDna);

            ParseData();

            ResolvePointers(verboseMode);

            UpdateOldPointers();

            reader.Dispose();
            memory.Dispose();
        }