Exemplo n.º 1
0
 public override FileSystemEntry Create(FileSystemEntry entry)
 {
     Connect();
     if (entry is FileEntry)
         return CreateFile(entry as FileEntry);
     else
         return CreateDirectory(entry as DirectoryEntry);
 }
Exemplo n.º 2
0
        public static void HandleGetDirectory(GetDirectory command, Networking.Client client)
        {
            bool   isError = false;
            string message = null;

            Action <string> onError = (msg) =>
            {
                isError = true;
                message = msg;
            };

            try
            {
                DirectoryInfo dicInfo = new DirectoryInfo(command.RemotePath);

                FileInfo[]      files       = dicInfo.GetFiles();
                DirectoryInfo[] directories = dicInfo.GetDirectories();

                FileSystemEntry[] items = new FileSystemEntry[files.Length + directories.Length];

                int offset = 0;
                for (int i = 0; i < directories.Length; i++, offset++)
                {
                    items[i] = new FileSystemEntry
                    {
                        EntryType         = FileType.Directory, Name = directories[i].Name, Size = 0,
                        LastAccessTimeUtc = directories[i].LastAccessTimeUtc
                    };
                }

                for (int i = 0; i < files.Length; i++)
                {
                    items[i + offset] = new FileSystemEntry
                    {
                        EntryType         = FileType.File, Name = files[i].Name, Size = files[i].Length,
                        ContentType       = FileHelper.GetContentType(Path.GetExtension(files[i].Name)),
                        LastAccessTimeUtc = files[i].LastAccessTimeUtc
                    };
                }

                client.Send(new GetDirectoryResponse {
                    RemotePath = command.RemotePath, Items = items
                });
            }
            catch (UnauthorizedAccessException)
            {
                onError("GetDirectory No permission");
            }
            catch (SecurityException)
            {
                onError("GetDirectory No permission");
            }
            catch (PathTooLongException)
            {
                onError("GetDirectory Path too long");
            }
            catch (DirectoryNotFoundException)
            {
                onError("GetDirectory Directory not found");
            }
            catch (FileNotFoundException)
            {
                onError("GetDirectory File not found");
            }
            catch (IOException)
            {
                onError("GetDirectory I/O error");
            }
            catch (Exception)
            {
                onError("GetDirectory Failed");
            }
            finally
            {
                if (isError && !string.IsNullOrEmpty(message))
                {
                    client.Send(new SetStatusFileManager {
                        Message = message, SetLastDirectorySeen = true
                    });
                }
            }
        }
Exemplo n.º 3
0
        public static ManifestFile FromFileSystemEntry(FileSystemEntry entry)
        {
            using (var stream = entry.Open())
                using (var reader = new BinaryReader(stream, Encoding.ASCII, true))
                {
                    var result = new ManifestFile
                    {
                        Header = ManifestHeader.Parse(reader)
                    };

                    switch (result.Header.Version)
                    {
                    case 5:
                    case 6:
                    case 7:
                        break;

                    default:
                        throw new InvalidDataException();
                    }

                    result.Assets = new Asset[result.Header.AssetCount];
                    for (var i = 0; i < result.Assets.Length; i++)
                    {
                        result.Assets[i] = new Asset
                        {
                            Header = AssetEntry.Parse(reader, result.Header.Version)
                        };
                    }

                    result.AssetReferences = new AssetReference[result.Header.AssetReferenceBufferSize / AssetReference.SizeInBytes];
                    for (var i = 0; i < result.AssetReferences.Length; i++)
                    {
                        result.AssetReferences[i] = AssetReference.Parse(reader);
                    }

                    foreach (var asset in result.Assets)
                    {
                        asset.AssetReferences = new ArraySegment <AssetReference>(
                            result.AssetReferences,
                            (int)asset.Header.AssetReferenceOffset / AssetReference.SizeInBytes,
                            (int)asset.Header.AssetReferenceCount);
                    }

                    {
                        var endPosition        = stream.Position + result.Header.ReferencedManifestNameBufferSize;
                        var manifestReferences = new List <ManifestReference>();

                        while (stream.Position < endPosition)
                        {
                            manifestReferences.Add(ManifestReference.Parse(reader));
                        }
                        result.ManifestReferences = manifestReferences;
                    }

                    {
                        var endPosition = stream.Position + result.Header.AssetNameBufferSize;
                        var assetNames  = ReadNameBuffer(reader, endPosition);

                        foreach (var asset in result.Assets)
                        {
                            asset.Name = assetNames[asset.Header.NameOffset];
                        }
                    }

                    {
                        var endPosition     = stream.Position + result.Header.SourceFileNameBufferSize;
                        var sourceFileNames = ReadNameBuffer(reader, endPosition);

                        foreach (var asset in result.Assets)
                        {
                            asset.SourceFileName = sourceFileNames[asset.Header.SourceFileNameOffset];
                        }
                    }

                    return(result);
                }
        }
        /// <summary>
        /// Set data.
        /// </summary>
        /// <param name="item">Item.</param>
        public override void SetData(FileSystemEntry item)
        {
            base.SetData(item);

            Name.text = item.DisplayName;
        }
Exemplo n.º 5
0
 protected virtual bool ShouldRecurseIntoEntry(ref FileSystemEntry entry)
 {
     throw null;
 }
Exemplo n.º 6
0
 internal override FileSystemEntry ImplGetFileInfo(String Path)
 {
     var FileSystemEntry = new FileSystemEntry(this, Path);
     var stat = csftp.lstat(RealPath(Path));
     FileSystemEntry.Size = stat.Length();
     FileSystemEntry.Time.LastAccessTime = stat.getATime();
     FileSystemEntry.Time.CreationTime = stat.getMTime();
     FileSystemEntry.Time.LastWriteTime = stat.getMTime();
     return FileSystemEntry;
 }
Exemplo n.º 7
0
 public void When_a_directory_is_created_in_the_bucket()
 {
     CreatedEntry = CurrentInstance.Create(
         new FakeDirectoryEntry()
         {
             Created = DateTime.Now.Date,
             Modified = DateTime.Now.Date,
             Name = "subfolder",
             RelativePath = "subfolder"
         }
     );
 }
Exemplo n.º 8
0
        public override void Delete(FileSystemEntry entry)
        {
            Connect();
            var fullPath = Path.Combine(this.BaseDirectory, entry.RelativePath);

            var file = entry as FileEntry;

            if (file != null)
                DeleteFile(file);

            var dir = entry as DirectoryEntry;

            if (dir != null)
                DeleteDirectory(dir);
        }
Exemplo n.º 9
0
 public bool IsMatch(ref FileSystemEntry entry) => IsMatch(GetRelativeDirectory(ref entry), entry.FileName);
Exemplo n.º 10
0
 protected override bool ShouldRecurseIntoEntry(ref FileSystemEntry entry)
 {
     LastDirectory = new string(entry.Directory);
     return(false);
 }
Exemplo n.º 11
0
 protected override string TransformEntry(ref FileSystemEntry entry)
 => entry.ToFullPath();
Exemplo n.º 12
0
 protected override bool ShouldIncludeEntry(ref FileSystemEntry entry)
 => !entry.IsDirectory;
Exemplo n.º 13
0
 public static Geometry FromFileSystemEntry(AptFile container, FileSystemEntry entry)
 {
     using var stream = entry.Open();
     using var reader = new StreamReader(stream);
     return(Parse(container, reader));
 }
Exemplo n.º 14
0
        public static AniFile FromFileSystemEntry(FileSystemEntry entry)
        {
            RiffChunk rootChunk;

            using (var stream = entry.Open())
                using (var reader = new BinaryReader(stream, Encoding.ASCII, true))
                {
                    rootChunk = RiffChunk.Parse(reader);
                }

            var result = new AniFile();

            foreach (var chunk in ((RiffChunkList)rootChunk.Content).Chunks)
            {
                switch (chunk.Content)
                {
                case RiffChunkList list:
                    switch (list.ListType)
                    {
                    case "INFO":
                        var iconNameChunk = list.Chunks.FirstOrDefault(x => x.ChunkType == "INAM");
                        if (iconNameChunk != null)
                        {
                            result.IconName = ((InfoChunkContent)iconNameChunk.Content).Value;
                        }

                        var iconArtistChunk = list.Chunks.FirstOrDefault(x => x.ChunkType == "IART");
                        if (iconArtistChunk != null)
                        {
                            result.ArtistName = ((InfoChunkContent)iconArtistChunk.Content).Value;
                        }

                        break;

                    case "fram":
                        var iconIndex = 0;
                        foreach (var iconChunk in list.Chunks)
                        {
                            if (iconChunk.ChunkType != "icon")
                            {
                                throw new InvalidDataException();
                            }

                            var iconChunkContent = (IconChunkContent)iconChunk.Content;

                            result.Images[iconIndex++] = iconChunkContent.GetImage(0);
                        }
                        break;
                    }
                    break;

                case AniHeaderChunkContent anih:
                    result.Images = new CursorImage[anih.NumFrames];
                    result.DefaultFrameDisplayRate = anih.DefaultFrameDisplayRate;
                    break;

                case RateChunkContent rate:
                    result.Rates = rate;
                    break;

                case SequenceChunkContent seq:
                    result.Sequence = seq;
                    break;

                default:
                    throw new InvalidDataException();
                }
            }

            return(result);
        }
Exemplo n.º 15
0
    protected override bool ShouldRecurseIntoEntry(ref FileSystemEntry entry)
    {
        ShouldRecurseIntoEntryCalled = true;

        return(base.ShouldRecurseIntoEntry(ref entry));
    }
Exemplo n.º 16
0
        public W3dView(FileSystemEntry entry, Func <IntPtr, Game> createGame)
        {
            _listBox = new ListBox
            {
                Width           = 250,
                ItemTextBinding = Binding.Property((W3dItem v) => v.Name)
            };
            _listBox.SelectedValueChanged += OnSelectedValueChanged;
            Panel1 = _listBox;

            _listBox.SelectedIndex = 0;

            Panel2 = new GameControl
            {
                CreateGame = h =>
                {
                    var game = createGame(h);

                    var modelInstance = game.ContentManager
                                        .Load <Model>(entry.FilePath)
                                        .CreateInstance(game.GraphicsDevice);

                    game.Updating += (sender, e) =>
                    {
                        modelInstance.Update(e.GameTime);
                    };

                    game.BuildingRenderList += (sender, e) =>
                    {
                        modelInstance.SetWorldMatrix(Matrix4x4.Identity);
                        modelInstance.BuildRenderList(e.RenderList, e.Camera);
                    };

                    var enclosingBoundingBox = GetEnclosingBoundingBox(modelInstance);

                    var cameraController = new ArcballCameraController(
                        enclosingBoundingBox.GetCenter(),
                        Vector3.Distance(enclosingBoundingBox.Min, enclosingBoundingBox.Max));

                    game.Scene3D = new Scene3D(
                        game,
                        cameraController,
                        null,
                        null,
                        null,
                        new GameObjectCollection(game.ContentManager),
                        new WaypointCollection(),
                        new WaypointPathCollection(),
                        WorldLighting.CreateDefault());

                    var animations = new List <AnimationInstance>(modelInstance.AnimationInstances);

                    var w3dFile = W3dFile.FromFileSystemEntry(entry);

                    // If this is a skin file, load "external" animations.
                    var externalAnimations = new List <AnimationInstance>();
                    if (w3dFile.HLod != null && w3dFile.HLod.Header.Name.EndsWith("_SKN", StringComparison.OrdinalIgnoreCase))
                    {
                        var namePrefix   = w3dFile.HLod.Header.Name.Substring(0, w3dFile.HLod.Header.Name.LastIndexOf('_') + 1);
                        var parentFolder = Path.GetDirectoryName(w3dFile.FilePath);
                        var pathPrefix   = Path.Combine(parentFolder, namePrefix);
                        foreach (var animationFileEntry in entry.FileSystem.GetFiles(parentFolder))
                        {
                            if (!animationFileEntry.FilePath.StartsWith(pathPrefix, StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }

                            var animationModel = game.ContentManager.Load <Model>(animationFileEntry.FilePath);
                            foreach (var animation in animationModel.Animations)
                            {
                                var externalAnimationInstance = new AnimationInstance(modelInstance, animation);
                                modelInstance.AnimationInstances.Add(externalAnimationInstance);
                                externalAnimations.Add(externalAnimationInstance);
                            }
                        }
                    }

                    var subObjects = new List <W3dItem>();

                    subObjects.Add(new W3dModelItem());

                    foreach (var animation in animations)
                    {
                        subObjects.Add(new W3dAnimationItem(animation, "Animation"));
                    }

                    foreach (var animation in externalAnimations)
                    {
                        subObjects.Add(new W3dAnimationItem(animation, "External Animation"));
                    }

                    _listBox.DataStore = subObjects;

                    return(game);
                }
            };
        }
Exemplo n.º 17
0
 internal override FileSystemEntry ImplGetFileInfo(String Path)
 {
     String CachedRealPath = RealPath(Path);
     var Info = new FileSystemEntry(this, Path);
     Info.Size = Ftp.GetFileSize(CachedRealPath);
     Info.Time.LastWriteTime = Ftp.GetFileDate(CachedRealPath);
     return Info;
 }
Exemplo n.º 18
0
        public static ImageMap FromFileSystemEntry(FileSystemEntry entry)
        {
            var map = new ImageMap();

            using (var stream = entry.Open())
                using (var reader = new StreamReader(stream))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        //process line

                        //skip comments
                        line = line.Split(';').First();

                        if (line.Length == 0)
                        {
                            continue;
                        }

                        var seperators = new string[] { "->", "=" };

                        var list = line.Split(seperators, StringSplitOptions.None);

                        if (list.Length > 2)
                        {
                            throw new InvalidDataException();
                        }

                        //first entry in list is the internal image id
                        var image = Convert.ToInt32(list.First());

                        //second entry is the texture id and optionally bounds
                        var assigment = list.Last().Split(' ');

                        if (assigment.Length < 1)
                        {
                            throw new InvalidDataException();
                        }

                        var texture = Convert.ToInt32(assigment.First());

                        switch (assigment.Length)
                        {
                        case 1:
                            map.Mapping.Add(image, new DirectAssignment(texture));
                            break;

                        case 4:
                            Rectangle rect = new Rectangle(
                                Convert.ToInt32(assigment[0]),
                                Convert.ToInt32(assigment[1]),
                                Convert.ToInt32(assigment[2]),
                                Convert.ToInt32(assigment[3])
                                );

                            map.Mapping.Add(image, new RectangleAssignment(image, rect));
                            break;

                        default:
                            throw new InvalidDataException();
                        }
                    }
                }
            return(map);
        }
Exemplo n.º 19
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="Path"></param>
		/// <returns></returns>
		protected override IEnumerable<FileSystemEntry> ImplFindFiles(string Path)
		{
			var DirectoriesListed = new HashSet<string>();

			Path = (Path + "/").TrimStart('/');

			// List Files
			foreach (var ZipArchiveEntry in ZipArchive.Entries)
			{
				var FullName = ZipArchiveEntry.FullName;
				if (!FullName.StartsWith(Path)) continue;

				var Part = FullName.Substring(Path.Length);
				
				// Directory
				if (Part.IndexOf('/') != -1)
				{
					var Folder = Part.Split('/')[0];

					if (!DirectoriesListed.Contains(Folder))
					{
						//Console.WriteLine("Part: {0} : {1}", Part, Folder);

						var Entry = new FileSystemEntry(this, Path + Folder)
						{
							Size = 0,
							Time = new FileSystemEntry.FileTime()
							{
								LastWriteTime = ZipArchiveEntry.LastWriteTime.Date,
							},
							Type = FileSystemEntry.EntryType.Directory,
						};

						DirectoriesListed.Add(Folder);

						//Console.WriteLine(Entry);

						yield return Entry;
					}
					else
					{
						continue;
					}
				}
				// File
				else
				{
					yield return _ConvertFileSystemEntry(ZipArchiveEntry);
				}
			}
		}
Exemplo n.º 20
0
 static string ToImage(ref FileSystemEntry entry) => entry.ToFullPath();
Exemplo n.º 21
0
        internal override IEnumerable<FileSystemEntry> ImplFindFiles(String Path)
        {
            foreach (var i in csftp.ListEntries(RealPath(Path)))
            {
                var LsEntry = (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry)i;
                var FileSystemEntry = new FileSystemEntry(this, Path + "/" + LsEntry.FileName);
                FileSystemEntry.Size = LsEntry.Attributes.Size;
                FileSystemEntry.GroupId = LsEntry.Attributes.getGId();
                FileSystemEntry.UserId = LsEntry.Attributes.getUId();
                if (LsEntry.Attributes.IsDirectory) {
                    FileSystemEntry.Type = VirtualFileSystem.FileSystemEntry.EntryType.Directory;
                } else if (LsEntry.Attributes.IsLink) {
                    FileSystemEntry.Type = VirtualFileSystem.FileSystemEntry.EntryType.Link;
                } else {
                    FileSystemEntry.Type = VirtualFileSystem.FileSystemEntry.EntryType.File;
                }
                FileSystemEntry.Time.CreationTime = LsEntry.Attributes.getMTime();
                FileSystemEntry.Time.LastWriteTime = LsEntry.Attributes.getMTime();
                FileSystemEntry.Time.LastAccessTime = LsEntry.Attributes.getATime();
                //Console.WriteLine("FILE(" + LsEntry.getFilename() + ") : (" + LsEntry.getAttrs().getPermissions() + ") (" + String.Join(",", LsEntry.getAttrs().getExtended()) + ")");
                //Console.WriteLine(String.Format("FILE({}) : ({})", LsEntry.getFilename(), Convert.ToString(LsEntry.getAttrs().getPermissions(), 2)));
                //Console.WriteLine("FILE(" + LsEntry.getFilename() + ") : (" + Convert.ToString(LsEntry.getAttrs().getPermissions(), 2) + ")");

                // Version 3 supported.
                // http://tools.ietf.org/wg/secsh/draft-ietf-secsh-filexfer/
                if (FileSystemEntry.Name.Substring(0, 1) == ".")
                {
                    FileSystemEntry.ExtendedFlags |= VirtualFileSystem.FileSystemEntry.ExtendedFlagsTypes.Hidden;
                }
                yield return FileSystemEntry;
            }
        }
Exemplo n.º 22
0
 static bool IsImage(ref FileSystemEntry entry) =>
 entry.FileName.EndsWith(".png") || entry.FileName.EndsWith(".jpg") ||
 entry.FileName.EndsWith(".jpeg");
Exemplo n.º 23
0
 protected virtual bool ShouldIncludeEntry(ref FileSystemEntry entry)
 {
     throw null;
 }
 protected internal virtual bool ShouldRecurseIntoEntry(ref FileSystemEntry entry) => true;
Exemplo n.º 25
0
 protected abstract TResult TransformEntry(ref FileSystemEntry entry);
        protected internal virtual void DetermineChange(string directory, ref FileChangeList changes, ref FileSystemEntry file)
        {
            string path = file.FileName.ToString();

            FileState fileState = _state.Get(directory, path);

            if (fileState == null) // file added
            {
                fileState                  = new FileState();
                fileState.Directory        = directory;
                fileState.Path             = path;
                fileState.LastWriteTimeUtc = file.LastWriteTimeUtc;
                fileState.Length           = file.Length;
                fileState.Version          = _version;
                _state.Add(directory, path, fileState);
                changes.AddAdded(directory, path);
                return;
            }

            fileState.Version = _version;

            var previousState = fileState;

            if (file.LastWriteTimeUtc != fileState.LastWriteTimeUtc || file.Length != fileState.Length)
            {
                changes.AddChanged(directory, fileState.Path);
                fileState.LastWriteTimeUtc = file.LastWriteTimeUtc;
                fileState.Length           = file.Length;
            }
        }
Exemplo n.º 27
0
        public static ConstantData FromFileSystemEntry(FileSystemEntry entry)
        {
            using var stream = entry.Open();
            using var reader = new BinaryReader(stream);
            var data = new ConstantData();

            //validate that this is a correct const
            var magic = reader.ReadFixedLengthString(17);

            if (magic != "Apt constant file")
            {
                throw new InvalidDataException($"Not a supported const file: {magic}");
            }

            reader.BaseStream.Seek(3, SeekOrigin.Current);

            data.AptDataEntryOffset = reader.ReadUInt32();
            var numEntries = reader.ReadUInt32();
            var headerSize = reader.ReadUInt32();

            if (headerSize != 32)
            {
                throw new InvalidDataException("Constant header must be 32 bytes");
            }

            for (var i = 0; i < numEntries; i++)
            {
                var constEntry = new ConstantEntry
                {
                    Type = reader.ReadUInt32AsEnum <ConstantEntryType>()
                };

                //read the number/ string offset
                switch (constEntry.Type)
                {
                case ConstantEntryType.Undef:
                    throw new InvalidDataException("Undefined const entry");

                case ConstantEntryType.String:
                    var strOffset = reader.ReadUInt32();
                    var pos       = reader.BaseStream.Position;
                    reader.BaseStream.Seek(strOffset, SeekOrigin.Begin);
                    constEntry.Value = reader.ReadNullTerminatedString();
                    reader.BaseStream.Seek(pos, SeekOrigin.Begin);
                    break;

                case ConstantEntryType.Register:
                    constEntry.Value = reader.ReadUInt32();
                    break;

                case ConstantEntryType.Boolean:
                    constEntry.Value = reader.ReadBooleanUInt32Checked();
                    break;

                case ConstantEntryType.Float:
                    constEntry.Value = reader.ReadSingle();
                    break;

                case ConstantEntryType.Integer:
                    constEntry.Value = reader.ReadInt32();
                    break;

                case ConstantEntryType.Lookup:
                    constEntry.Value = reader.ReadUInt32();
                    break;

                case ConstantEntryType.None:
                    constEntry.Value = null;
                    break;

                default:
                    throw new InvalidDataException();
                }

                data.Entries.Add(constEntry);
            }

            return(data);
        }
Exemplo n.º 28
0
        public unsafe Cursor(FileSystemEntry entry, GameWindow window)
        {
            _aniFile = AniFile.FromFileSystemEntry(entry);

            var width  = (int)_aniFile.IconWidth;
            var height = (int)_aniFile.IconHeight;

            _surfaces = new Sdl2Interop.SDL_Surface[_aniFile.Images.Length];
            _cursors  = new Sdl2Interop.SDL_Cursor[_aniFile.Images.Length];

            var windowScale = window.WindowScale;

            for (var i = 0; i < _aniFile.Images.Length; i++)
            {
                var pixels = _aniFile.Images[i].PixelsBgra;

                fixed(byte *pixelsPtr = pixels)
                {
                    var surface = Sdl2Interop.SDL_CreateRGBSurfaceWithFormatFrom(
                        pixelsPtr,
                        width,
                        height,
                        32,
                        width * 4,
                        Sdl2Interop.SDL_PixelFormat.SDL_PIXELFORMAT_ABGR8888);

                    if (windowScale != 1.0f)
                    {
                        var scaledWidth  = (int)(windowScale * width);
                        var scaledHeight = (int)(windowScale * height);

                        var scaledSurface = Sdl2Interop.SDL_CreateRGBSurfaceWithFormat(
                            0,
                            scaledWidth,
                            scaledHeight,
                            32,
                            Sdl2Interop.SDL_PixelFormat.SDL_PIXELFORMAT_ABGR8888);

                        Sdl2Interop.SDL_BlitScaled(
                            surface,
                            new Sdl2Interop.SDL_Rect(0, 0, width, height),
                            scaledSurface,
                            new Sdl2Interop.SDL_Rect(0, 0, scaledWidth, scaledHeight));

                        Sdl2Interop.SDL_FreeSurface(surface);

                        surface = scaledSurface;
                    }

                    AddDisposeAction(() => Sdl2Interop.SDL_FreeSurface(surface));

                    _surfaces[i] = surface;
                }

                var cursor = Sdl2Interop.SDL_CreateColorCursor(
                    _surfaces[i],
                    (int)_aniFile.HotspotX,
                    (int)_aniFile.HotspotY);

                AddDisposeAction(() => Sdl2Interop.SDL_FreeCursor(cursor));

                _cursors[i] = cursor;
            }
        }
Exemplo n.º 29
0
        // Unused but functional function
        static bool extractISO(string infile, string outfolder = null, int blocksize = 32768)
        {
            if (outfolder == null)
            {
                List <string> tmp = infile.Split('/').Last().Split('.').ToList();
                tmp.RemoveAt(tmp.Count - 1);
                outfolder = String.Join(".", tmp);
                Console.WriteLine(outfolder);
            }

            if (!Directory.Exists(outfolder))
            {
                Directory.CreateDirectory(outfolder);
            }

            XboxISOFileSource      xisosrc = new XboxISOFileSource(infile);
            FileSystemEntry        xfs     = xisosrc.GetFileSystem();
            List <FileSystemEntry> fslist  = xfs.GetFileList();

            foreach (FileSystemEntry fsentry in fslist)
            {
                if (fsentry.FileName == "XDFS Root")
                {
                    continue;
                }

                if (fsentry.IsFolder)
                {
                    Directory.CreateDirectory(outfolder + "\\" + fsentry.FileName);
                    continue;
                }

                Stream z_in = fsentry.GetStream();
                if (z_in.CanRead)
                {
                    FileStream z_out = File.Create(outfolder + "\\" + fsentry.FullPath);

                    int  this_read    = 0;
                    int  total_read   = 0;
                    long left_to_read = z_in.Length;

                    while (left_to_read > 0)
                    {
                        int    local_bs = getReadSize(left_to_read, blocksize);
                        byte[] data     = new byte[local_bs + 1];
                        this_read = z_in.Read(data, 0, local_bs);
                        z_out.Write(data, 0, this_read);
                        total_read   += this_read;
                        left_to_read -= this_read;
                        Console.Write("\rWriting File: " + fsentry.FullPath + ":\t" + friendlyBytes((long)total_read) + "/" + friendlyBytes((long)z_in.Length) + "         ");
                    }
                    Console.Write("\n");
                    z_in.Close();
                    z_out.Close();
                }
                else
                {
                    Console.WriteLine("Internal Error: Could not read ISO file " + fsentry.FullPath);
                    z_in.Close();
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 30
0
        internal static SMBCommand GetNTCreateResponse(SMBHeader header, NTCreateAndXRequest request, object share, StateObject state)
        {
            bool   isExtended = (request.Flags & NTCreateFlags.NT_CREATE_REQUEST_EXTENDED_RESPONSE) > 0;
            string path       = request.FileName;

            if (share is NamedPipeShare)
            {
                RemoteService service = ((NamedPipeShare)share).GetService(path);
                if (service != null)
                {
                    ushort fileID = state.AddOpenedFile(path);
                    if (isExtended)
                    {
                        return(CreateResponseExtendedForNamedPipe(fileID));
                    }
                    else
                    {
                        return(CreateResponseForNamedPipe(fileID));
                    }
                }

                header.Status = NTStatus.STATUS_OBJECT_PATH_NOT_FOUND;
                return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
            }
            else // FileSystemShare
            {
                FileSystemShare fileSystemShare = (FileSystemShare)share;
                IFileSystem     fileSystem      = fileSystemShare.FileSystem;
                bool            forceDirectory  = (request.CreateOptions & CreateOptions.FILE_DIRECTORY_FILE) > 0;
                bool            forceFile       = (request.CreateOptions & CreateOptions.FILE_NON_DIRECTORY_FILE) > 0;

                if (forceDirectory & (request.CreateDisposition != CreateDisposition.FILE_CREATE &&
                                      request.CreateDisposition != CreateDisposition.FILE_OPEN &&
                                      request.CreateDisposition != CreateDisposition.FILE_OPEN_IF))
                {
                    header.Status = NTStatus.STATUS_INVALID_PARAMETER;
                    return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                }

                // Windows will try to access named streams (alternate data streams) regardless of the FILE_NAMED_STREAMS flag, we need to prevent this behaviour.
                if (path.Contains(":"))
                {
                    // Windows Server 2003 will return STATUS_OBJECT_NAME_NOT_FOUND
                    header.Status = NTStatus.STATUS_NO_SUCH_FILE;
                    return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                }

                FileSystemEntry entry = fileSystem.GetEntry(path);
                if (request.CreateDisposition == CreateDisposition.FILE_OPEN)
                {
                    if (entry == null)
                    {
                        header.Status = NTStatus.STATUS_OBJECT_PATH_NOT_FOUND;
                        return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                    }

                    if (entry.IsDirectory && forceFile)
                    {
                        header.Status = NTStatus.STATUS_FILE_IS_A_DIRECTORY;
                        return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                    }

                    if (!entry.IsDirectory && forceDirectory)
                    {
                        // Not sure if that's the correct response
                        header.Status = NTStatus.STATUS_OBJECT_NAME_COLLISION;
                        return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                    }
                }
                else if (request.CreateDisposition == CreateDisposition.FILE_CREATE)
                {
                    if (entry != null)
                    {
                        // File already exists, fail the request
                        header.Status = NTStatus.STATUS_OBJECT_NAME_COLLISION;
                        return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                    }

                    string userName = state.GetConnectedUserName(header.UID);
                    if (!fileSystemShare.HasWriteAccess(userName))
                    {
                        header.Status = NTStatus.STATUS_ACCESS_DENIED;
                        return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                    }

                    try
                    {
                        if (forceDirectory)
                        {
                            entry = fileSystem.CreateDirectory(path);
                        }
                        else
                        {
                            entry = fileSystem.CreateFile(path);
                        }
                    }
                    catch (IOException ex)
                    {
                        ushort errorCode = IOExceptionHelper.GetWin32ErrorCode(ex);
                        if (errorCode == (ushort)Win32Error.ERROR_SHARING_VIOLATION)
                        {
                            header.Status = NTStatus.STATUS_SHARING_VIOLATION;
                            return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                        }
                        else
                        {
                            header.Status = NTStatus.STATUS_DATA_ERROR;
                            return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        header.Status = NTStatus.STATUS_ACCESS_DENIED;
                        return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                    }
                }
                else if (request.CreateDisposition == CreateDisposition.FILE_OPEN_IF ||
                         request.CreateDisposition == CreateDisposition.FILE_OVERWRITE ||
                         request.CreateDisposition == CreateDisposition.FILE_OVERWRITE_IF ||
                         request.CreateDisposition == CreateDisposition.FILE_SUPERSEDE)
                {
                    entry = fileSystem.GetEntry(path);
                    if (entry == null)
                    {
                        if (request.CreateDisposition == CreateDisposition.FILE_OVERWRITE)
                        {
                            header.Status = NTStatus.STATUS_OBJECT_PATH_NOT_FOUND;
                            return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                        }

                        string userName = state.GetConnectedUserName(header.UID);
                        if (!fileSystemShare.HasWriteAccess(userName))
                        {
                            header.Status = NTStatus.STATUS_ACCESS_DENIED;
                            return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                        }

                        try
                        {
                            if (forceDirectory)
                            {
                                entry = fileSystem.CreateDirectory(path);
                            }
                            else
                            {
                                entry = fileSystem.CreateFile(path);
                            }
                        }
                        catch (IOException ex)
                        {
                            ushort errorCode = IOExceptionHelper.GetWin32ErrorCode(ex);
                            if (errorCode == (ushort)Win32Error.ERROR_SHARING_VIOLATION)
                            {
                                header.Status = NTStatus.STATUS_SHARING_VIOLATION;
                                return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                            }
                            else
                            {
                                header.Status = NTStatus.STATUS_DATA_ERROR;
                                return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                            }
                        }
                        catch (UnauthorizedAccessException)
                        {
                            header.Status = NTStatus.STATUS_ACCESS_DENIED;
                            return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                        }
                    }
                    else
                    {
                        if (request.CreateDisposition == CreateDisposition.FILE_OVERWRITE ||
                            request.CreateDisposition == CreateDisposition.FILE_OVERWRITE_IF ||
                            request.CreateDisposition == CreateDisposition.FILE_SUPERSEDE)
                        {
                            string userName = state.GetConnectedUserName(header.UID);
                            if (!fileSystemShare.HasWriteAccess(userName))
                            {
                                header.Status = NTStatus.STATUS_ACCESS_DENIED;
                                return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                            }

                            // Truncate the file
                            try
                            {
                                Stream stream = fileSystem.OpenFile(path, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite);
                                stream.Close();
                            }
                            catch (IOException ex)
                            {
                                ushort errorCode = IOExceptionHelper.GetWin32ErrorCode(ex);
                                if (errorCode == (ushort)Win32Error.ERROR_SHARING_VIOLATION)
                                {
                                    header.Status = NTStatus.STATUS_SHARING_VIOLATION;
                                    return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                                }
                                else
                                {
                                    header.Status = NTStatus.STATUS_DATA_ERROR;
                                    return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                                }
                            }
                            catch (UnauthorizedAccessException)
                            {
                                header.Status = NTStatus.STATUS_ACCESS_DENIED;
                                return(new ErrorResponse(CommandName.SMB_COM_NT_CREATE_ANDX));
                            }
                        }
                    }
                }
                else
                {
                    throw new InvalidRequestException();
                }
                bool   isSequentialAccess = (request.CreateOptions & CreateOptions.FILE_SEQUENTIAL_ONLY) > 0;
                ushort fileID             = state.AddOpenedFile(path, isSequentialAccess);
                if (isExtended)
                {
                    NTCreateAndXResponseExtended response = CreateResponseExtendedFromFileSystemEntry(entry, fileID);
                    if ((request.Flags & NTCreateFlags.NT_CREATE_REQUEST_OPBATCH) > 0)
                    {
                        response.OpLockLevel = OpLockLevel.BatchOpLockGranted;
                    }
                    return(response);
                }
                else
                {
                    NTCreateAndXResponse response = CreateResponseFromFileSystemEntry(entry, fileID);
                    if ((request.Flags & NTCreateFlags.NT_CREATE_REQUEST_OPBATCH) > 0)
                    {
                        response.OpLockLevel = OpLockLevel.BatchOpLockGranted;
                    }
                    return(response);
                }
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// Returns the file system entries located on the specified path.
        /// </summary>
        /// <param name="path">The path of the directory to search.</param>
        /// <param name="searchPattern">The search string to match against the names of files in path.</param>
        /// <param name="recursive">A value that specifies whether subdirectories are included in the search.</param>
        /// <returns>An array containing the file system entries.</returns>
        /// <exception cref="System.ArgumentNullException">The path is null.</exception>
        /// <exception cref="System.ArgumentException">
        /// The path is empty, or consists only of white space characters.
        /// or
        /// The path is in an invalid format.
        /// or
        /// The path exceeds the maximum length supported by the file system.
        /// or
        /// The path does not exist.
        /// or
        /// The path is a file.
        /// or
        /// The search pattern is an invalid format.
        /// </exception>
        /// <exception cref="System.UnauthorizedAccessException">The caller does not have the required permission for the path.</exception>
        /// <exception cref="ConnectionException">No connection is available to the file system.</exception>
        public override FileSystemEntry[] GetFileSystemEntries(String path, String searchPattern, Boolean recursive)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (String.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException(StorageMessages.PathIsEmpty, nameof(path));
            }

            try
            {
                // read the names of the entries
                String[] entryNames = Directory.GetFileSystemEntries(path, searchPattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

                // read directory and file info
                FileSystemEntry[] result = new FileSystemEntry[entryNames.Length];

                for (Int32 entryIndex = 0; entryIndex < entryNames.Length; entryIndex++)
                {
                    // check whether the entry is a file or directory
                    if (Directory.Exists(entryNames[entryIndex]))
                    {
                        DirectoryInfo info = new DirectoryInfo(entryNames[entryIndex]);

                        result[entryIndex] = new FileSystemEntry(info.FullName, info.Name, FileSystemEntryType.Directory, info.CreationTime, info.LastAccessTime, info.LastWriteTime, 0);
                    }
                    else
                    {
                        FileInfo info = new FileInfo(entryNames[entryIndex]);

                        result[entryIndex] = new FileSystemEntry(info.FullName, info.Name, FileSystemEntryType.File, info.CreationTime, info.LastAccessTime, info.LastWriteTime, info.Length);
                    }
                }

                return(result);
            }
            catch (ArgumentException ex)
            {
                if (ex.ParamName == nameof(searchPattern))
                {
                    throw new ArgumentException(StorageMessages.InvalidSearchPattern, nameof(searchPattern), ex);
                }
                else
                {
                    throw new ArgumentException(StorageMessages.PathIsInInvalidFormat, nameof(path), ex);
                }
            }
            catch (PathTooLongException ex)
            {
                throw new ArgumentException(StorageMessages.PathIsTooLong, nameof(path), ex);
            }
            catch (DirectoryNotFoundException ex)
            {
                throw new ArgumentException(StorageMessages.PathDoesNotExist, nameof(path), ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                throw new UnauthorizedAccessException(StorageMessages.PathUnauthorized, ex);
            }
            catch (IOException ex)
            {
                if (File.Exists(path))
                {
                    throw new ArgumentException(StorageMessages.PathIsFile, nameof(path), ex);
                }

                throw new ConnectionException(StorageMessages.NoConnectionToFileSystem, ex);
            }
        }
Exemplo n.º 32
0
        private static NTCreateAndXResponseExtended CreateResponseExtendedFromFileSystemEntry(FileSystemEntry entry, ushort fileID)
        {
            NTCreateAndXResponseExtended response = new NTCreateAndXResponseExtended();

            if (entry.IsDirectory)
            {
                response.ExtFileAttributes = ExtendedFileAttributes.Directory;
                response.Directory         = true;
            }
            else
            {
                response.ExtFileAttributes = ExtendedFileAttributes.Normal;
            }
            response.FID                      = fileID;
            response.CreateTime               = entry.CreationTime;
            response.LastAccessTime           = entry.LastAccessTime;
            response.LastWriteTime            = entry.LastWriteTime;
            response.LastChangeTime           = entry.LastWriteTime;
            response.CreateDisposition        = CreateDisposition.FILE_OPEN;
            response.AllocationSize           = InfoHelper.GetAllocationSize(entry.Size);
            response.EndOfFile                = entry.Size;
            response.ResourceType             = ResourceType.FileTypeDisk;
            response.FileStatus               = FileStatus.NO_EAS | FileStatus.NO_SUBSTREAMS | FileStatus.NO_REPARSETAG;
            response.MaximalAccessRights.File = FileAccessMask.FILE_READ_DATA | FileAccessMask.FILE_WRITE_DATA | FileAccessMask.FILE_APPEND_DATA |
                                                FileAccessMask.FILE_READ_EA | FileAccessMask.FILE_WRITE_EA |
                                                FileAccessMask.FILE_EXECUTE |
                                                FileAccessMask.FILE_READ_ATTRIBUTES | FileAccessMask.FILE_WRITE_ATTRIBUTES |
                                                FileAccessMask.DELETE | FileAccessMask.READ_CONTROL | FileAccessMask.WRITE_DAC | FileAccessMask.WRITE_OWNER | FileAccessMask.SYNCHRONIZE;
            response.GuestMaximalAccessRights.File = FileAccessMask.FILE_READ_DATA | FileAccessMask.FILE_WRITE_DATA |
                                                     FileAccessMask.FILE_READ_EA | FileAccessMask.FILE_WRITE_EA |
                                                     FileAccessMask.FILE_READ_ATTRIBUTES | FileAccessMask.FILE_WRITE_ATTRIBUTES |
                                                     FileAccessMask.READ_CONTROL | FileAccessMask.SYNCHRONIZE;
            return(response);
        }
 protected override string TransformEntry(ref FileSystemEntry entry)
 => entry.FileName.ToString();
Exemplo n.º 34
0
 public static EnumeratedFileData FromFileSystemEntry(ref FileSystemEntry entry)
 {
     if (entry.IsDirectory)
     {
         return(default);
Exemplo n.º 35
0
        public NTStatus CreateFile(out object handle, out FileStatus fileStatus, string path, AccessMask desiredAccess, FileAttributes fileAttributes, ShareAccess shareAccess, CreateDisposition createDisposition, CreateOptions createOptions, SecurityContext securityContext)
        {
            handle     = null;
            fileStatus = FileStatus.FILE_DOES_NOT_EXIST;
            FileAccess createAccess         = NTFileStoreHelper.ToCreateFileAccess(desiredAccess, createDisposition);
            bool       requestedWriteAccess = (createAccess & FileAccess.Write) > 0;

            bool forceDirectory = (createOptions & CreateOptions.FILE_DIRECTORY_FILE) > 0;
            bool forceFile      = (createOptions & CreateOptions.FILE_NON_DIRECTORY_FILE) > 0;

            if (forceDirectory & (createDisposition != CreateDisposition.FILE_CREATE &&
                                  createDisposition != CreateDisposition.FILE_OPEN &&
                                  createDisposition != CreateDisposition.FILE_OPEN_IF &&
                                  createDisposition != CreateDisposition.FILE_SUPERSEDE))
            {
                return(NTStatus.STATUS_INVALID_PARAMETER);
            }

            // Windows will try to access named streams (alternate data streams) regardless of the FILE_NAMED_STREAMS flag, we need to prevent this behaviour.
            if (!m_fileSystem.SupportsNamedStreams && path.Contains(":"))
            {
                // Windows Server 2003 will return STATUS_OBJECT_NAME_NOT_FOUND
                return(NTStatus.STATUS_NO_SUCH_FILE);
            }

            FileSystemEntry entry = null;

            try
            {
                entry = m_fileSystem.GetEntry(path);
            }
            catch (FileNotFoundException)
            {
            }
            catch (DirectoryNotFoundException)
            {
            }
            catch (Exception ex)
            {
                if (ex is IOException || ex is UnauthorizedAccessException)
                {
                    NTStatus status = ToNTStatus(ex);
                    Log(Severity.Verbose, "CreateFile: Error retrieving '{0}'. {1}.", path, status);
                    return(status);
                }
                else
                {
                    throw;
                }
            }

            if (createDisposition == CreateDisposition.FILE_OPEN)
            {
                if (entry == null)
                {
                    return(NTStatus.STATUS_NO_SUCH_FILE);
                }

                fileStatus = FileStatus.FILE_EXISTS;
                if (entry.IsDirectory && forceFile)
                {
                    return(NTStatus.STATUS_FILE_IS_A_DIRECTORY);
                }

                if (!entry.IsDirectory && forceDirectory)
                {
                    return(NTStatus.STATUS_OBJECT_PATH_INVALID);
                }
            }
            else if (createDisposition == CreateDisposition.FILE_CREATE)
            {
                if (entry != null)
                {
                    // File already exists, fail the request
                    Log(Severity.Verbose, "CreateFile: File '{0}' already exists.", path);
                    fileStatus = FileStatus.FILE_EXISTS;
                    return(NTStatus.STATUS_OBJECT_NAME_COLLISION);
                }

                if (!requestedWriteAccess)
                {
                    return(NTStatus.STATUS_ACCESS_DENIED);
                }

                try
                {
                    if (forceDirectory)
                    {
                        Log(Severity.Information, "CreateFile: Creating directory '{0}'", path);
                        entry = m_fileSystem.CreateDirectory(path);
                    }
                    else
                    {
                        Log(Severity.Information, "CreateFile: Creating file '{0}'", path);
                        entry = m_fileSystem.CreateFile(path);
                    }
                }
                catch (Exception ex)
                {
                    if (ex is IOException || ex is UnauthorizedAccessException)
                    {
                        NTStatus status = ToNTStatus(ex);
                        Log(Severity.Verbose, "CreateFile: Error creating '{0}'. {1}.", path, status);
                        return(status);
                    }
                    else
                    {
                        throw;
                    }
                }
                fileStatus = FileStatus.FILE_CREATED;
            }
            else if (createDisposition == CreateDisposition.FILE_OPEN_IF ||
                     createDisposition == CreateDisposition.FILE_OVERWRITE ||
                     createDisposition == CreateDisposition.FILE_OVERWRITE_IF ||
                     createDisposition == CreateDisposition.FILE_SUPERSEDE)
            {
                if (entry == null)
                {
                    if (createDisposition == CreateDisposition.FILE_OVERWRITE)
                    {
                        return(NTStatus.STATUS_OBJECT_PATH_NOT_FOUND);
                    }

                    if (!requestedWriteAccess)
                    {
                        return(NTStatus.STATUS_ACCESS_DENIED);
                    }

                    try
                    {
                        if (forceDirectory)
                        {
                            Log(Severity.Information, "CreateFile: Creating directory '{0}'", path);
                            entry = m_fileSystem.CreateDirectory(path);
                        }
                        else
                        {
                            Log(Severity.Information, "CreateFile: Creating file '{0}'", path);
                            entry = m_fileSystem.CreateFile(path);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is IOException || ex is UnauthorizedAccessException)
                        {
                            NTStatus status = ToNTStatus(ex);
                            Log(Severity.Verbose, "CreateFile: Error creating '{0}'. {1}.", path, status);
                            return(status);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    fileStatus = FileStatus.FILE_CREATED;
                }
                else
                {
                    fileStatus = FileStatus.FILE_EXISTS;
                    if (createDisposition == CreateDisposition.FILE_OPEN_IF)
                    {
                        if (entry.IsDirectory && forceFile)
                        {
                            return(NTStatus.STATUS_FILE_IS_A_DIRECTORY);
                        }

                        if (!entry.IsDirectory && forceDirectory)
                        {
                            return(NTStatus.STATUS_OBJECT_PATH_INVALID);
                        }
                    }
                    else
                    {
                        if (!requestedWriteAccess)
                        {
                            return(NTStatus.STATUS_ACCESS_DENIED);
                        }

                        if (createDisposition == CreateDisposition.FILE_OVERWRITE ||
                            createDisposition == CreateDisposition.FILE_OVERWRITE_IF)
                        {
                            // Truncate the file
                            try
                            {
                                Stream temp = m_fileSystem.OpenFile(path, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite, FileOptions.None);
                                temp.Close();
                            }
                            catch (Exception ex)
                            {
                                if (ex is IOException || ex is UnauthorizedAccessException)
                                {
                                    NTStatus status = ToNTStatus(ex);
                                    Log(Severity.Verbose, "CreateFile: Error truncating '{0}'. {1}.", path, status);
                                    return(status);
                                }
                                else
                                {
                                    throw;
                                }
                            }
                            fileStatus = FileStatus.FILE_OVERWRITTEN;
                        }
                        else if (createDisposition == CreateDisposition.FILE_SUPERSEDE)
                        {
                            // Delete the old file
                            try
                            {
                                m_fileSystem.Delete(path);
                            }
                            catch (Exception ex)
                            {
                                if (ex is IOException || ex is UnauthorizedAccessException)
                                {
                                    NTStatus status = ToNTStatus(ex);
                                    Log(Severity.Verbose, "CreateFile: Error deleting '{0}'. {1}.", path, status);
                                    return(status);
                                }
                                else
                                {
                                    throw;
                                }
                            }

                            try
                            {
                                if (forceDirectory)
                                {
                                    Log(Severity.Information, "CreateFile: Creating directory '{0}'", path);
                                    entry = m_fileSystem.CreateDirectory(path);
                                }
                                else
                                {
                                    Log(Severity.Information, "CreateFile: Creating file '{0}'", path);
                                    entry = m_fileSystem.CreateFile(path);
                                }
                            }
                            catch (Exception ex)
                            {
                                if (ex is IOException || ex is UnauthorizedAccessException)
                                {
                                    NTStatus status = ToNTStatus(ex);
                                    Log(Severity.Verbose, "CreateFile: Error creating '{0}'. {1}.", path, status);
                                    return(status);
                                }
                                else
                                {
                                    throw;
                                }
                            }
                            fileStatus = FileStatus.FILE_SUPERSEDED;
                        }
                    }
                }
            }
            else
            {
                return(NTStatus.STATUS_INVALID_PARAMETER);
            }

            FileAccess fileAccess = NTFileStoreHelper.ToFileAccess(desiredAccess);
            Stream     stream;

            if (fileAccess == (FileAccess)0 || entry.IsDirectory)
            {
                stream = null;
            }
            else
            {
                // Note that SetFileInformationByHandle/FILE_DISPOSITION_INFO has no effect if the handle was opened with FILE_DELETE_ON_CLOSE.
                NTStatus openStatus = OpenFileStream(out stream, path, fileAccess, shareAccess, createOptions);
                if (openStatus != NTStatus.STATUS_SUCCESS)
                {
                    return(openStatus);
                }
            }

            bool deleteOnClose = (createOptions & CreateOptions.FILE_DELETE_ON_CLOSE) > 0;

            handle = new FileHandle(path, entry.IsDirectory, stream, deleteOnClose);
            if (fileStatus != FileStatus.FILE_CREATED &&
                fileStatus != FileStatus.FILE_OVERWRITTEN &&
                fileStatus != FileStatus.FILE_SUPERSEDED)
            {
                fileStatus = FileStatus.FILE_OPENED;
            }
            return(NTStatus.STATUS_SUCCESS);
        }
Exemplo n.º 36
0
 public void LoadSaveFile(FileSystemEntry entry)
 {
     SaveFile.Load(entry, this);
 }
		static void Is(string expect, FileSystemEntry entry)
		{
			Assert.AreEqual(expect, entry.RelativePath);
		}
Exemplo n.º 38
0
        public GameStream(FileSystemEntry manifestFileEntry, Game game)
        {
            ManifestFileEntry = manifestFileEntry;
            ManifestFile      = ManifestFile.FromFileSystemEntry(manifestFileEntry);

            _assetReferenceToAssetLookup = new Dictionary <AssetReference, Asset>();
            foreach (var asset in ManifestFile.Assets)
            {
                var assetReference = new AssetReference(
                    asset.Header.TypeId,
                    asset.Header.InstanceId);
                _assetReferenceToAssetLookup[assetReference] = asset;
            }

            var assetParseContext = new AssetParseContext(game);

            // Parse .bin, .relo, and .imp files simultaneously.
            ParseStreamFile(".bin", 3132817408u, binReader =>
            {
                ParseStreamFile(".relo", 3133014016u, reloReader =>
                {
                    ParseStreamFile(".imp", 3132162048u, impReader =>
                    {
                        foreach (var asset in ManifestFile.Assets)
                        {
                            ReadBinReloImpData(
                                binReader,
                                reloReader,
                                impReader,
                                asset,
                                out var instanceData,
                                out var relocationData,
                                out var imports);

                            asset.AssetImports = imports;

                            if (instanceData.Length == 0)
                            {
                                continue;
                            }

                            if (Enum.IsDefined(typeof(AssetType), asset.Header.TypeId)) // TODO: Remove this.
                            {
                                if (AssetReaderCatalog.TryGetAssetReader(asset.Header.TypeId, out var assetReader))
                                {
                                    using (var instanceDataStream = new MemoryStream(instanceData, false))
                                        using (var instanceDataReader = new BinaryReader(instanceDataStream, Encoding.ASCII, true))
                                        {
                                            var zero = instanceDataReader.ReadUInt32();
                                            if (zero != 0)
                                            {
                                                throw new InvalidDataException();
                                            }

                                            asset.InstanceData = assetReader(asset, instanceDataReader, imports, assetParseContext);

                                            var assetCollection = assetParseContext.AssetStore.GetAssetCollection(asset.Header.TypeId);
                                            if (assetCollection != null) // TODO: Eventually this shouldn't be null.
                                            {
                                                assetCollection.Add(asset.InstanceData);
                                            }
                                            else
                                            {
                                                var singleAssetStorage = assetParseContext.AssetStore.GetSingleAsset(asset.Header.TypeId);
                                                if (singleAssetStorage != null) // TODO: Eventually this shouldn't be null.
                                                {
                                                    singleAssetStorage.Current = (BaseAsset)asset.InstanceData;
                                                }
                                            }
                                        }
                                }
                                else
                                {
                                    // TODO
                                }
                            }
                            else
                            {
                                // TODO
                                Logger.Info($"Missing AssetType: {asset.Name.Split(':')[0]} = 0x{asset.Header.TypeId.ToString("X")},");
                            }
                        }
                    });
                });
Exemplo n.º 39
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="Path"></param>
		/// <param name="FileTime"></param>
		protected override void ImplSetFileTime(string Path, FileSystemEntry.FileTime FileTime)
		{
			throw new NotImplementedException();
		}
Exemplo n.º 40
0
        public void When_a_file_is_created_in_the_bucket()
        {
            var ms = new MemoryStream(Guid.NewGuid().ToByteArray());
            ms.Position = 0;

            CreatedEntry = CurrentInstance.Create(
                new FakeFileEntry(ms)
                {
                    Size = 100,
                    Created = DateTime.Now.Date,
                    Modified = DateTime.Now.Date,
                    Name = "File.bin",
                    RelativePath = "File.bin"
                }
            );
        }