Ejemplo n.º 1
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="op"></param>
		/// <param name="scope"></param>
		/// <returns></returns>
		private async Task<CallRet> op (FileHandle op, EntryPath scope)
		{
			string url = string.Format ("{0}/{1}/{2}",
			                            Config.RS_HOST,
			                            OPS [(int)op],
			                            Base64URLSafe.Encode (scope.URI));
			return await Call (url);
		}
Ejemplo n.º 2
0
        public static unsafe StorageHotplugInfo GetHotplugInfo(FileHandle fileHandle)
        {
            StorageHotplugInfo hotplugInfo;

            fileHandle.IoControl(IoCtlGetHotplugInfo, null, 0, &hotplugInfo, StorageHotplugInfo.SizeOf);

            return hotplugInfo;
        }
Ejemplo n.º 3
0
		private async Task<CallRet> opFetch(FileHandle op, string fromUrl, EntryPath entryPath)
		{
			string url = string.Format("{0}/{1}/{2}/to/{3}",
										Config.PREFETCH_HOST,
										OPS[(int)op],
										Base64URLSafe.Encode(fromUrl),
										Base64URLSafe.Encode(entryPath.URI));
			return await Call (url);
		}
Ejemplo n.º 4
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="op"></param>
		/// <param name="pair"></param>
		/// <returns></returns>
		private async Task<CallRet> op2 (FileHandle op, EntryPathPair pair)
		{
			string url = string.Format ("{0}/{1}/{2}/{3}",
			                            Config.RS_HOST,
			                            OPS [(int)op],
			                            Base64URLSafe.Encode (pair.URISrc),
			                            Base64URLSafe.Encode (pair.URIDest));
			return await Call(url);
		}
Ejemplo n.º 5
0
		private CallRet opFetch(FileHandle op, string fromUrl, EntryPath entryPath)
		{
			string url = string.Format("{0}/{1}/{2}/to/{3}",
										Config.RS_HOST,
										OPS[(int)op],
										Base64URLSafe.Encode(fromUrl),
										Base64URLSafe.Encode(entryPath.URI));
			return Call (url);
		}
Ejemplo n.º 6
0
 public MappedImage(string fileName, bool readOnly)
 {
     using (var fhandle = FileHandle.CreateWin32(
                fileName,
                readOnly ? (FileAccess.Execute | FileAccess.ReadAttributes | FileAccess.ReadData) :
                (FileAccess.AppendData | FileAccess.Execute | FileAccess.ReadAttributes | FileAccess.ReadData | FileAccess.WriteAttributes | FileAccess.WriteData),
                FileShareMode.Read,
                FileCreationDispositionWin32.OpenExisting
                ))
         this.MapAndLoad(fhandle, readOnly);
 }
Ejemplo n.º 7
0
 public Texture newTexture(FileHandle fileHandle)
 {
     try
     {
         return(new MonoGameTexture(((MonoGameFileHandle)fileHandle).loadFromContentManager <Texture2D>()));
     }
     catch (Exception)
     {
         return(newTexture(fileHandle.readBytes()));
     }
 }
Ejemplo n.º 8
0
 public MailslotHandle(
     string fileName,
     ObjectFlags objectFlags,
     FileHandle rootDirectory,
     FileShareMode shareMode,
     FileCreateOptions openOptions,
     FileAccess access
     )
     : base(fileName, objectFlags, rootDirectory, shareMode, openOptions, access)
 {
 }
Ejemplo n.º 9
0
        public static StorageHotplugInfo GetHotplugInfo(FileHandle fileHandle)
        {
            unsafe
            {
                StorageHotplugInfo hotplugInfo;

                fileHandle.IoControl(IoCtlGetHotplugInfo, null, 0, &hotplugInfo, Marshal.SizeOf(typeof(StorageHotplugInfo)));

                return(hotplugInfo);
            }
        }
 internal static FileProperties GetFileProperties(FileHandle fileHandle)
 {
     return(new FileProperties()
     {
         Author = (string)GetPropertyData(fileHandle, Constants.FileProperties.AUTHOR, TDMChannelDataTypes.DDC_String),
         Description = (string)GetPropertyData(fileHandle, Constants.FileProperties.DESCRIPTION, TDMChannelDataTypes.DDC_String),
         Name = (string)GetPropertyData(fileHandle, Constants.FileProperties.NAME, TDMChannelDataTypes.DDC_String),
         Time = (DateTime)GetPropertyData(fileHandle, Constants.FileProperties.DATETIME, TDMChannelDataTypes.DDC_Timestamp),
         Title = (string)GetPropertyData(fileHandle, Constants.FileProperties.TITLE, TDMChannelDataTypes.DDC_String),
     });
 }
Ejemplo n.º 11
0
        public static StorageHotplugInfo GetHotplugInfo(FileHandle fileHandle)
        {
            unsafe
            {
                StorageHotplugInfo hotplugInfo;

                fileHandle.IoControl(IoCtlGetHotplugInfo, null, 0, &hotplugInfo, Marshal.SizeOf(typeof(StorageHotplugInfo)));

                return hotplugInfo;
            }
        }
Ejemplo n.º 12
0
        public QueueBase(int buffersCount, FileHandle videoDevice)
        {
            if (buffersCount > 32)
            {
                throw new ArgumentOutOfRangeException("Max. buffers count is 32");
            }
            buffers          = new T[buffersCount];
            this.videoDevice = videoDevice;

            m_kernel = new SmallQueue(buffersCount, false);
            m_user   = new SmallQueue(buffersCount, true);
        }
Ejemplo n.º 13
0
    public override ValueTask RemoveProperty(FileHandle fileHandle, string name)
    {
        var localFileHandle = new LocalFileHandle(fileHandle);
        var stats           = StatRealPath(GetRealPath(localFileHandle.Path));

        if (!localFileHandle.IsSameFile(stats))
        {
            throw new FileNotFoundException(fileHandle);
        }

        return(_hintFileTracker.RemoveProperty(localFileHandle.Path, fileHandle, stats, name));
    }
Ejemplo n.º 14
0
        private static OpenFile FindOpenFile(FileHandle handle)
        {
            for (var i = 0; i < OpenFiles.Count; i++)
            {
                if (OpenFiles[i].Handle == handle)
                {
                    return(OpenFiles[i]);
                }
            }

            return(null);
        }
Ejemplo n.º 15
0
        public override async Task ExecuteAsync(HashFileByHandle payload, ITaskExecutionContext executionContext)
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                FileHandle fileHandle   = ResolveFileHandle(payload.HandleId);
                byte[]     fileContents = await ReadFileAsync(fileHandle);

                FileHashInfo fileHashInfo = ComputeHash(fileHandle, fileContents);

                StoreFileHashAndNotifyCompletion(fileHashInfo);
            }
        }
Ejemplo n.º 16
0
        private static void LoadTextures(FileHandle handle)
        {
            foreach (var h in handle.ListFileHandles())
            {
                LoadTexture(h);
            }

            foreach (var h in handle.ListDirectoryHandles())
            {
                LoadTextures(h);
            }
        }
Ejemplo n.º 17
0
        /// <exception cref="System.IO.IOException"/>
        public static Org.Apache.Hadoop.Nfs.Nfs3.Request.READDIRPLUS3Request Deserialize(
            XDR xdr)
        {
            FileHandle handle     = ReadHandle(xdr);
            long       cookie     = xdr.ReadHyper();
            long       cookieVerf = xdr.ReadHyper();
            int        dirCount   = xdr.ReadInt();
            int        maxCount   = xdr.ReadInt();

            return(new Org.Apache.Hadoop.Nfs.Nfs3.Request.READDIRPLUS3Request(handle, cookie,
                                                                              cookieVerf, dirCount, maxCount));
        }
Ejemplo n.º 18
0
 public PSFileHandle(FileHandle handle)
 {
     this.HandleId          = handle.HandleId;
     this.Path              = handle.Path;
     this.ClientIp          = handle.ClientIp;
     this.ClientPort        = handle.ClientPort;
     this.OpenTime          = handle.OpenTime;
     this.LastReconnectTime = handle.LastReconnectTime;
     this.FileId            = handle.FileId;
     this.ParentId          = handle.ParentId;
     this.SessionId         = handle.SessionId;
 }
Ejemplo n.º 19
0
 protected void WriteSignalInfo()
 {
     Debug.Assert(FileHandle != null, DataFileConsts.DataFileIsNotOpen);
     lock (FileAccess)
     {
         FileHandle.Seek(256, SeekOrigin.Begin);
         for (int i = 0; i < FileInfo.NrSignals; i++)
         {
             WriteStringField(SignalInfo[i].FieldValid[(int)EdfSignalInfoBase.Field.SignalLabel], SignalInfo[i].SignalLabel, 16);
         }
         for (int i = 0; i < FileInfo.NrSignals; i++)
         {
             WriteStringField(SignalInfo[i].FieldValid[(int)EdfSignalInfoBase.Field.Transducertype], SignalInfo[i].TransducerType, 80);
         }
         for (int i = 0; i < FileInfo.NrSignals; i++)
         {
             WriteStringField(SignalInfo[i].FieldValid[(int)EdfSignalInfoBase.Field.PhysiDim],
                              SignalInfo[i].IsLogFloat ? EdfConstants.LogFloatSignalLabel : SignalInfo[i].PhysiDim, 8);
         }
         for (int i = 0; i < FileInfo.NrSignals; i++)
         {
             WriteStringField(SignalInfo[i].FieldValid[(int)EdfSignalInfoBase.Field.PhysiMin],
                              TextUtils.DoubleToString(SignalInfo[i].PhysiMin, FormatInfo, 8), 8);
         }
         for (int i = 0; i < FileInfo.NrSignals; i++)
         {
             WriteStringField(SignalInfo[i].FieldValid[(int)EdfSignalInfoBase.Field.PhysiMax],
                              TextUtils.DoubleToString(SignalInfo[i].PhysiMax, FormatInfo, 8), 8);
         }
         for (int i = 0; i < FileInfo.NrSignals; i++)
         {
             WriteStringField(SignalInfo[i].FieldValid[(int)EdfSignalInfoBase.Field.DigiMin], SignalInfo[i].DigiMin.ToString(), 8);
         }
         for (int i = 0; i < FileInfo.NrSignals; i++)
         {
             WriteStringField(SignalInfo[i].FieldValid[(int)EdfSignalInfoBase.Field.DigiMax], SignalInfo[i].DigiMax.ToString(), 8);
         }
         for (int i = 0; i < FileInfo.NrSignals; i++)
         {
             WriteStringField(SignalInfo[i].FieldValid[(int)EdfSignalInfoBase.Field.Prefilter], SignalInfo[i].PreFilter, 80);
         }
         for (int i = 0; i < FileInfo.NrSignals; i++)
         {
             WriteStringField(SignalInfo[i].FieldValid[(int)EdfSignalInfoBase.Field.NrSamples], SignalInfo[i].NrSamples.ToString(), 8);
         }
         for (int i = 0; i < FileInfo.NrSignals; i++)
         {
             WriteStringField(SignalInfo[i].FieldValid[(int)EdfSignalInfoBase.Field.Reserved], SignalInfo[i].Reserved, 32);
             SignalInfo[i].Modified = false;
         }
     }
 }
Ejemplo n.º 20
0
    public async ValueTask <ReadOnlyMemory <byte>?> GetProperty(FileHandle fileHandle, string name)
    {
        _logger.LogTrace("Get property {@key} to file {@fileHandle}.", name, fileHandle);

        var(@namespace, rawFileHandle) = UnWarpFileHandle(fileHandle);

        if (!_fileSystems.TryGetValue(@namespace, out var fileSystem))
        {
            throw new FileNotFoundException(fileHandle);
        }

        return(await fileSystem.GetProperty(rawFileHandle, name));
    }
Ejemplo n.º 21
0
        internal static XDR Write(FileHandle handle, int xid, long offset, int count, byte
                                  [] data)
        {
            XDR request = new XDR();

            RpcCall.GetInstance(xid, Nfs3Constant.Program, Nfs3Constant.Version, Nfs3Constant.NFSPROC3
                                .Create.GetValue(), new CredentialsNone(), new VerifierNone()).Write(request);
            WRITE3Request write1 = new WRITE3Request(handle, offset, count, Nfs3Constant.WriteStableHow
                                                     .Unstable, ByteBuffer.Wrap(data));

            write1.Serialize(request);
            return(request);
        }
Ejemplo n.º 22
0
    public async ValueTask WriteFile(FileHandle fileHandle, ReadOnlyMemory <byte> content)
    {
        _logger.LogTrace("Write {Length} bytes to file {FileHandle}", content.Length, fileHandle);

        var(@namespace, rawFileHandle) = UnWarpFileHandle(fileHandle);

        if (!_fileSystems.TryGetValue(@namespace, out var fileSystem))
        {
            throw new FileNotFoundException(fileHandle);
        }

        await fileSystem.WriteFile(rawFileHandle, content);
    }
Ejemplo n.º 23
0
    public async ValueTask <ReadOnlyMemory <byte> > ReadFile(FileHandle fileHandle)
    {
        _logger.LogTrace("Read file by {@fileHandle}", fileHandle);

        var(@namespace, rawFileHandle) = UnWarpFileHandle(fileHandle);

        if (!_fileSystems.TryGetValue(@namespace, out var fileSystem))
        {
            throw new FileNotFoundException(fileHandle);
        }

        return(await fileSystem.ReadFile(rawFileHandle));
    }
Ejemplo n.º 24
0
    public async ValueTask <FileHandle> CreateDirectory(FileHandle parentFileHandle, string name)
    {
        _logger.LogTrace("Create directory by {ParentFileHandle} {Name}", parentFileHandle, name);

        var(@namespace, rawFileHandle) = UnWarpFileHandle(parentFileHandle);

        if (!_fileSystems.TryGetValue(@namespace, out var fileSystem))
        {
            throw new FileNotFoundException(parentFileHandle);
        }

        return(WarpFileHandle(@namespace, await fileSystem.CreateDirectory(rawFileHandle, name)));
    }
Ejemplo n.º 25
0
    public async ValueTask <FileHandle> CreateFile(FileHandle parentFileHandle, string name, ReadOnlyMemory <byte> content)
    {
        _logger.LogTrace("Create file {ParentFileHandle} {Name} by {Length} bytes data.", parentFileHandle, name, content);

        var(@namespace, rawFileHandle) = UnWarpFileHandle(parentFileHandle);

        if (!_fileSystems.TryGetValue(@namespace, out var fileSystem))
        {
            throw new FileNotFoundException(parentFileHandle);
        }

        return(WarpFileHandle(@namespace, await fileSystem.CreateFile(rawFileHandle, name, content)));
    }
Ejemplo n.º 26
0
    public async ValueTask <T> ReadFileStream <T>(FileHandle fileHandle, Func <Stream, ValueTask <T> > reader)
    {
        _logger.LogTrace("Read file stream by {@fileHandle}.", fileHandle);

        var(@namespace, rawFileHandle) = UnWarpFileHandle(fileHandle);

        if (!_fileSystems.TryGetValue(@namespace, out var fileSystem))
        {
            throw new FileNotFoundException(fileHandle);
        }

        return(await fileSystem.ReadFileStream(rawFileHandle, reader));
    }
Ejemplo n.º 27
0
    public async ValueTask <string> GetFileName(FileHandle fileHandle)
    {
        _logger.LogTrace("Get file name by file handle {@fileHandle}", fileHandle);

        var(@namespace, rawFileHandle) = UnWarpFileHandle(fileHandle);

        if (!_fileSystems.TryGetValue(@namespace, out var fileSystem))
        {
            throw new FileNotFoundException(fileHandle);
        }

        return(await fileSystem.GetFileName(rawFileHandle));
    }
Ejemplo n.º 28
0
        // The name of the link
        // It contains the target
        /// <exception cref="System.IO.IOException"/>
        public static Org.Apache.Hadoop.Nfs.Nfs3.Request.SYMLINK3Request Deserialize(XDR
                                                                                     xdr)
        {
            FileHandle handle  = ReadHandle(xdr);
            string     name    = xdr.ReadString();
            SetAttr3   symAttr = new SetAttr3();

            symAttr.Deserialize(xdr);
            string symData = xdr.ReadString();

            return(new Org.Apache.Hadoop.Nfs.Nfs3.Request.SYMLINK3Request(handle, name, symAttr
                                                                          , symData));
        }
Ejemplo n.º 29
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void streamFilesRecursiveMustCreateMissingPathDirectoriesImpliedByFileRename() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void StreamFilesRecursiveMustCreateMissingPathDirectoriesImpliedByFileRename()
        {
            File a      = ExistingFile("a");
            File sub    = new File(Path, "sub");              // does not exists
            File target = new File(sub, "b");

            FileHandle handle = Fsa.streamFilesRecursive(a).findAny().get();

            handle.Rename(target);

            assertTrue(Fsa.isDirectory(sub));
            assertTrue(Fsa.fileExists(target));
        }
Ejemplo n.º 30
0
        public virtual IActionResult DeleteFile([FromRoute][Required] string path)
        {
            FileHandle file = _fileSystemService.GetFileHandle(path);

            if (file == null)
            {
                return(NotFound());
            }

            _fileSystemService.DeleteFile(file);

            return(Ok());
        }
Ejemplo n.º 31
0
    public async ValueTask <FileStats> Stat(FileHandle fileHandle)
    {
        _logger.LogTrace("Stat file by {FileHandle}", fileHandle);

        var(@namespace, rawFileHandle) = UnWarpFileHandle(fileHandle);

        if (!_fileSystems.TryGetValue(@namespace, out var fileSystem))
        {
            throw new FileNotFoundException(fileHandle);
        }

        return(await fileSystem.Stat(rawFileHandle));
    }
Ejemplo n.º 32
0
    public async ValueTask RemoveProperty(FileHandle fileHandle, string name)
    {
        _logger.LogTrace("Remove property {@key} to file {@fileHandle}.", name, fileHandle);

        var(@namespace, rawFileHandle) = UnWarpFileHandle(fileHandle);

        if (!_fileSystems.TryGetValue(@namespace, out var fileSystem))
        {
            throw new FileNotFoundException(fileHandle);
        }

        await fileSystem.RemoveProperty(rawFileHandle, name);
    }
Ejemplo n.º 33
0
        private void refreshVideoDetail()
        {
            String filePath   = currentLessonModel.videoMainJsonFilePath;
            String jsonString = FileHandle.readJsonFile(filePath);

            currentMainVideoModel = (MainVideoModel)JSONHandle.getObjFromJson <MainVideoModel>(jsonString);
            if (currentMainVideoModel == null)
            {
                currentMainVideoModel = new MainVideoModel();
            }
            else
            {
                mainVideoTItletextBox1.Text = currentMainVideoModel.videoTitle;
                lessonIntroTextBox.Text     = currentMainVideoModel.videoLessonIntro;
                videoDetialLabel.Text       = "第" + (currentLessonModel.orderNum + 1) + "课";
            }


            String zqfilePath   = currentLessonModel.videoZhengJueJsonFilePath;
            String zqjsonString = FileHandle.readJsonFile(zqfilePath);

            List <ItemVideoModel> zqList = (List <ItemVideoModel>)JSONHandle.getObjFromJson <List <ItemVideoModel> >(zqjsonString);

            if (zqList == null)
            {
                return;
            }
            foreach (ItemVideoModel m in zqList)
            {
                zhengQueVideoList.Add(m);
            }

            refreshZhengQueVideoListView();



            String cwfilePath   = currentLessonModel.videoCuoWuJsonFilePath;
            String cwjsonString = FileHandle.readJsonFile(cwfilePath);

            List <ItemVideoModel> cwList = (List <ItemVideoModel>)JSONHandle.getObjFromJson <List <ItemVideoModel> >(cwjsonString);

            if (cwList == null)
            {
                return;
            }
            foreach (ItemVideoModel m in cwList)
            {
                zhengQueVideoList.Add(m);
            }
            refreshCuoWuVideoListView();
        }
Ejemplo n.º 34
0
        public static NamedPipeHandle Create(
            FileAccess access,
            string fileName,
            ObjectFlags objectFlags,
            FileHandle rootDirectory,
            FileShareMode shareMode,
            FileCreationDisposition creationDisposition,
            FileCreateOptions createOptions,
            PipeType type,
            PipeType readMode,
            PipeCompletionMode completionMode,
            int maximumInstances,
            int inboundQuota,
            int outboundQuota,
            long defaultTimeout
            )
        {
            NtStatus         status;
            ObjectAttributes oa = new ObjectAttributes(fileName, objectFlags, rootDirectory);
            IoStatusBlock    isb;
            IntPtr           handle;

            try
            {
                if ((status = Win32.NtCreateNamedPipeFile(
                         out handle,
                         access,
                         ref oa,
                         out isb,
                         shareMode,
                         creationDisposition,
                         createOptions,
                         type,
                         readMode,
                         completionMode,
                         maximumInstances,
                         inboundQuota,
                         outboundQuota,
                         ref defaultTimeout
                         )) >= NtStatus.Error)
                {
                    Win32.ThrowLastError(status);
                }
            }
            finally
            {
                oa.Dispose();
            }

            return(new NamedPipeHandle(handle, true));
        }
Ejemplo n.º 35
0
        /// <exception cref="System.IO.IOException"/>
        public static Org.Apache.Hadoop.Nfs.Nfs3.Request.WRITE3Request Deserialize(XDR xdr
                                                                                   )
        {
            FileHandle handle = ReadHandle(xdr);
            long       offset = xdr.ReadHyper();
            int        count  = xdr.ReadInt();

            Nfs3Constant.WriteStableHow stableHow = Nfs3Constant.WriteStableHow.FromValue(xdr
                                                                                          .ReadInt());
            ByteBuffer data = ByteBuffer.Wrap(xdr.ReadFixedOpaque(xdr.ReadInt()));

            return(new Org.Apache.Hadoop.Nfs.Nfs3.Request.WRITE3Request(handle, offset, count
                                                                        , stableHow, data));
        }
Ejemplo n.º 36
0
        private void MapAndLoad(FileHandle fileHandle, bool readOnly)
        {
            using (Section section = new Section(
                       fileHandle,
                       false,
                       readOnly ? MemoryProtection.ExecuteRead : MemoryProtection.ExecuteReadWrite
                       ))
            {
                _size = (int)fileHandle.GetSize();
                _view = section.MapView(_size);

                this.Load(_view);
            }
        }
Ejemplo n.º 37
0
        public void initData()
        {
            String cPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\滑雪数据\\jsonData\\";

            switch (type)
            {
            case LType.LTypeErTongShuangBan:
            {
                commonPath        = cPath + "er_tong_shuang_ban_jiao_cheng\\";
                jsonFileLocalPath = commonPath + "lesson_json_er_tong_shuang_ban.txt";
            }
            break;

            case LType.LTypeChengRenShuangBan:
            {
                commonPath        = cPath + "cheng_ren_shuang_ban_jiao_cheng\\";
                jsonFileLocalPath = commonPath + "lesson_json_cheng_ren_shuang_ban.txt";
            }
            break;

            case LType.LTypeErtongDanBan:
            {
                commonPath        = cPath + "er_tong_dan_ban_jiao_cheng\\";
                jsonFileLocalPath = commonPath + "lesson_json_er_tong_dan_ban.txt";
            }
            break;

            case LType.LTypeChengRenDanBan:
            {
                commonPath        = cPath + "cheng_ren_dan_ban_jiao_cheng\\";
                jsonFileLocalPath = commonPath + "lesson_json_cheng_ren_dan_ban.txt";
            }
            break;
            }


            String filePath   = jsonFileLocalPath;
            String jsonString = FileHandle.readJsonFile(filePath);

            List <LessonModel> lList = (List <LessonModel>)JSONHandle.getObjFromJson <List <LessonModel> >(jsonString);

            if (lList == null)
            {
                return;
            }
            foreach (LessonModel m in lList)
            {
                lessonList.Add(m);
            }
        }
Ejemplo n.º 38
0
        public static NamedPipeHandle Create(
            FileAccess access,
            string fileName,
            ObjectFlags objectFlags,
            FileHandle rootDirectory,
            FileShareMode shareMode,
            FileCreationDisposition creationDisposition,
            FileCreateOptions createOptions,
            PipeType type,
            PipeType readMode,
            PipeCompletionMode completionMode,
            int maximumInstances,
            int inboundQuota,
            int outboundQuota,
            long defaultTimeout
            )
        {
            NtStatus status;
            ObjectAttributes oa = new ObjectAttributes(fileName, objectFlags, rootDirectory);
            IoStatusBlock isb;
            IntPtr handle;

            try
            {
                if ((status = Win32.NtCreateNamedPipeFile(
                    out handle,
                    access,
                    ref oa,
                    out isb,
                    shareMode,
                    creationDisposition,
                    createOptions,
                    type,
                    readMode,
                    completionMode,
                    maximumInstances,
                    inboundQuota,
                    outboundQuota,
                    ref defaultTimeout
                    )) >= NtStatus.Error)
                    Win32.ThrowLastError(status);
            }
            finally
            {
                oa.Dispose();
            }

            return new NamedPipeHandle(handle, true);
        }
Ejemplo n.º 39
0
        public static unsafe DiskCacheState GetCacheSetting(FileHandle fileHandle, out bool isPowerProtected)
        {
            DiskCacheSetting diskCacheSetting;

            fileHandle.IoControl(
                IoCtlGetCacheSetting,
                null,
                0,
                &diskCacheSetting,
                DiskCacheSetting.SizeOf
                );

            isPowerProtected = diskCacheSetting.IsPowerProtected;

            return diskCacheSetting.State;
        }
Ejemplo n.º 40
0
        public static DiskCacheState GetCacheSetting(FileHandle fileHandle, out bool isPowerProtected)
        {
            unsafe
            {
                DiskCacheSetting diskCacheSetting;

                fileHandle.IoControl(
                    IoCtlGetCacheSetting,
                    null,
                    0,
                    &diskCacheSetting,
                    Marshal.SizeOf(typeof(DiskCacheSetting))
                    );

                isPowerProtected = diskCacheSetting.IsPowerProtected;

                return diskCacheSetting.State;
            }
        }
Ejemplo n.º 41
0
        public static MailslotHandle Create(
            FileAccess access,
            string fileName,
            ObjectFlags objectFlags,
            FileHandle rootDirectory,
            int quota,
            int maxMessageSize,
            long readTimeout,
            FileCreateOptions createOptions
            )
        {
            NtStatus status;
            ObjectAttributes oa = new ObjectAttributes(fileName, objectFlags, rootDirectory);
            IoStatusBlock isb;
            IntPtr handle;

            try
            {
                if ((status = Win32.NtCreateMailslotFile(
                    out handle,
                    access,
                    ref oa,
                    out isb,
                    createOptions,
                    quota,
                    maxMessageSize,
                    ref readTimeout
                    )) >= NtStatus.Error)
                    Win32.ThrowLastError(status);
            }
            finally
            {
                oa.Dispose();
            }

            return new MailslotHandle(handle, true);
        }
Ejemplo n.º 42
0
        public static DiskCacheState GetCacheSetting(FileHandle fileHandle)
        {
            bool isPowerProtected;

            return GetCacheSetting(fileHandle, out isPowerProtected);
        }
Ejemplo n.º 43
0
        private void LoadOffsetsTable(FileHandle f)
        {
            uint offsetsCount = f.BlockCount + 1;
            //if ((f.Entry.Flags & FileSectorCrc) != 0)
            //    ++offsetsCount;

            f.BlockOffsets = new uint[offsetsCount];

            if ((f.Entry.Flags & CompressedFlagsMask) == 0) {
                // we can just generate the offsets if the file is not compressed,
                // and there will be no offset table to read anyway
                for (uint i = 0; i < offsetsCount - 1; ++i)
                    f.BlockOffsets[i] = BlockSize * i;
                f.BlockOffsets[offsetsCount - 1] = f.Entry.FSize;
                return;
            }

            // load table
            var offsetsSize = (int)(4 * offsetsCount);
            var offsetsBuffer = new byte[offsetsSize];
            f.Stream.Seek(f.Entry.FilePos, SeekOrigin.Begin);
            f.Stream.Read(offsetsBuffer, 0, offsetsSize);
            Buffer.BlockCopy(offsetsBuffer, 0, f.BlockOffsets, 0, offsetsSize);

            // decrypt table
            if ((f.Entry.Flags & FileEncrypted) != 0)
                Decrypt(f.BlockOffsets, 0, (int)offsetsCount, f.DecryptionKey - 1);

            // verify table
            for (int i = 0; i < f.BlockCount; ++i) {
                uint offset0 = f.BlockOffsets[i];
                uint offset1 = f.BlockOffsets[i + 1];
                if (offset1 <= offset0)
                    throw new Exception("corrupt offset table");
            }
        }
Ejemplo n.º 44
0
        public MPQStream Open(string path)
        {
            int index = BlockIndexForPath(path);
            if (index < 0)
                throw new FileNotFoundException();

            var f = new FileHandle {
                Path = path,
                Stream = new FileStream(archivePath, FileMode.Open, FileAccess.Read)
            };
            GetBlockEntry(index, out f.Entry);

            if ((f.Entry.Flags & FileCompress) != 0)
                throw new NotImplementedException();
            if ((f.Entry.Flags & FileFixKey) != 0)
                throw new NotImplementedException();
            if ((f.Entry.Flags & FilePatchFile) != 0)
                throw new NotImplementedException();
            if ((f.Entry.Flags & FileSingleUnit) != 0)
                throw new NotImplementedException();
            if ((f.Entry.Flags & FileSectorCrc) != 0)
                throw new NotImplementedException();
            if ((f.Entry.Flags & ~AllFlagsMask) != 0)
                throw new Exception("unknown flags present");
            if (f.Entry.FSize == 0)
                throw new Exception("file size is zero");

            if ((f.Entry.Flags & FileDeleteMarker) != 0)
                throw new FileNotFoundException();
            if ((f.Entry.Flags & FileExists) == 0)
                throw new FileNotFoundException();

            if ((f.Entry.Flags & FileEncrypted) != 0)
                f.DecryptionKey = FileKey(f.Path, ref f.Entry);

            f.Pos = 0;
            f.BlockIndex = 0xffffffff; // initially invalid
            f.BlockCount = 1 + (f.Entry.FSize - 1) / BlockSize;
            f.BlockSize = 0;
            f.BlockBuffer = new byte[BlockSize];
            f.TempBuffer = new byte[BlockSize];
            f.CryptBuffer = new uint[BlockSize / 4];
            LoadOffsetsTable(f);

            return new MPQStream(this, f);
        }
Ejemplo n.º 45
0
        public static bool Wait(string name, long timeout, bool relative)
        {
            using (var npfsHandle = new FileHandle(
                Win32.NamedPipePath + "\\",
                FileShareMode.ReadWrite,
                FileCreateOptions.SynchronousIoNonAlert,
                FileAccess.ReadAttributes | (FileAccess)StandardRights.Synchronize
                ))
            {
                using (var data = new MemoryAlloc(FilePipeWaitForBuffer.NameOffset + name.Length * 2))
                {
                    FilePipeWaitForBuffer info = new FilePipeWaitForBuffer();

                    info.Timeout = timeout;
                    info.TimeoutSpecified = true;
                    info.NameLength = name.Length * 2;
                    data.WriteStruct<FilePipeWaitForBuffer>(info);
                    data.WriteUnicodeString(FilePipeWaitForBuffer.NameOffset, name);

                    NtStatus status;
                    int returnLength;

                    status = npfsHandle.FsControl(FsCtlWait, data, data.Size, IntPtr.Zero, 0, out returnLength);

                    if (status == NtStatus.IoTimeout)
                        return false;

                    if (status >= NtStatus.Error)
                        Win32.ThrowLastError(status);

                    return true;
                }
            }
        }
Ejemplo n.º 46
0
 public MappedImage(FileHandle fileHandle, bool readOnly)
 {
     this.MapAndLoad(fileHandle, readOnly);
 }
Ejemplo n.º 47
0
        private void MapAndLoad(FileHandle fileHandle, bool readOnly)
        {
            using (Section section = new Section(
                fileHandle,
                false,
                readOnly ? MemoryProtection.ExecuteRead : MemoryProtection.ExecuteReadWrite
                ))
            {
                _size = (int)fileHandle.GetSize();
                _view = section.MapView(_size);
                _memory = _view;

                byte* start = (byte*)_memory;

                if (start[0] != 'M' || start[1] != 'Z')
                    throw new Exception("The file is not a valid executable image.");

                _ntHeaders = this.GetNtHeaders();
                _sections = (ImageSectionHeader*)((byte*)&_ntHeaders->OptionalHeader + _ntHeaders->FileHeader.SizeOfOptionalHeader);
                _magic = _ntHeaders->OptionalHeader.Magic;

                if (_magic != Win32.Pe32Magic && _magic != Win32.Pe32PlusMagic)
                    throw new Exception("The file is not a PE32 or PE32+ image.");
            }
        }
Ejemplo n.º 48
0
        public static unsafe void SetCacheSetting(FileHandle fileHandle, DiskCacheState state, bool isPowerProtected)
        {
            DiskCacheSetting diskCacheSetting;

            diskCacheSetting.Version = DiskCacheSetting.SizeOf;
            diskCacheSetting.State = state;
            diskCacheSetting.IsPowerProtected = isPowerProtected;

            fileHandle.IoControl(
                IoCtlSetCacheSetting,
                &diskCacheSetting,
                DiskCacheSetting.SizeOf,
                null,
                0
                );
        }
Ejemplo n.º 49
0
 /// <summary>
 /// Gets the device name associated with the specified file name.
 /// </summary>
 /// <param name="fileName">
 /// A file name referring to a DOS drive. For example: "\??\C:" (no 
 /// trailing backslash).
 /// </param>
 /// <returns>The device name associated with the DOS drive.</returns>
 public static string GetDeviceName(string fileName)
 {
     using (FileHandle fhandle = new FileHandle(
         fileName,
         FileShareMode.ReadWrite,
         FileCreateOptions.SynchronousIoNonAlert,
         FileAccess.ReadAttributes | (FileAccess)StandardRights.Synchronize
         ))
         return GetDeviceName(fhandle);
 }
Ejemplo n.º 50
0
        private static string GetReparsePointTarget(FileHandle fhandle)
        {
            using (MemoryAlloc data = new MemoryAlloc(FileSystem.MaximumReparseDataBufferSize))
            {
                fhandle.IoControl(FileSystem.FsCtlGetReparsePoint, IntPtr.Zero, 0, data, data.Size);

                FileSystem.ReparseDataBuffer buffer = data.ReadStruct<FileSystem.ReparseDataBuffer>();

                // Make sure it is in fact a mount point.
                if (buffer.ReparseTag != (uint)IoReparseTag.MountPoint)
                    Win32.Throw(NtStatus.InvalidParameter);

                return data.ReadUnicodeString(
                    FileSystem.ReparseDataBuffer.MountPointPathBuffer + buffer.SubstituteNameOffset,
                    buffer.SubstituteNameLength / 2
                    );
            }
        }
Ejemplo n.º 51
0
 public static void EjectMedia(FileHandle fileHandle)
 {
     fileHandle.IoControl(IoCtlEjectMedia, IntPtr.Zero, 0, IntPtr.Zero, 0);
 }
Ejemplo n.º 52
0
 public static void EjectMedia(char driveLetter)
 {
     using (var fhandle = new FileHandle(@"\??\" + driveLetter + ":", FileAccess.GenericRead))
         EjectMedia(fhandle);
 }
Ejemplo n.º 53
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="opName"></param>
 /// <param name="keys"></param>
 /// <returns></returns>
 private string getBatchOp_2(FileHandle op, EntryPathPair[] keys)
 {
     if (keys.Length < 1)
         return string.Empty;
     StringBuilder sb = new StringBuilder ();
     for (int i = 0; i < keys.Length - 1; i++) {
         string item = string.Format ("op=/{0}/{1}/{2}&",
                                      OPS [(int)op],
                                      Base64URLSafe.Encode (keys [i].URISrc),
                                      Base64URLSafe.Encode (keys [i].URIDest));
         sb.Append (item);
     }
     string litem = string.Format ("op=/{0}/{1}/{2}", OPS [(int)op],
                                   Base64URLSafe.Encode (keys [keys.Length - 1].URISrc),
                                   Base64URLSafe.Encode (keys [keys.Length - 1].URIDest));
     return sb.Append (litem).ToString ();
 }
Ejemplo n.º 54
0
        public KProcessHacker(string deviceName, string fileName)
        {
            _deviceName = deviceName;

            if (IntPtr.Size != 4)
                throw new NotSupportedException("KProcessHacker does not support 64-bit Windows.");

            try
            {
                _fileHandle = new FileHandle(
                    @"\Device\" + deviceName,
                    0,
                    FileAccess.GenericRead | FileAccess.GenericWrite
                    );
            }
            catch (WindowsException ex)
            {
                if (
                    ex.Status == NtStatus.NoSuchDevice ||
                    ex.Status == NtStatus.NoSuchFile ||
                    ex.Status == NtStatus.ObjectNameNotFound
                    )
                {

                    ServiceHandle shandle;

                    using (var scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
                    {
                        shandle = scm.CreateService(
                            deviceName,
                            deviceName,
                            ServiceType.KernelDriver,
                            fileName
                            );
                        shandle.Start();
                    }

                    try
                    {
                        _fileHandle = new FileHandle(
                            @"\Device\" + deviceName,
                            0,
                            FileAccess.GenericRead | FileAccess.GenericWrite
                            );
                    }
                    finally
                    {

                        shandle.Delete();
                    }
                }
                else
                {
                    throw ex;
                }
            }

            _fileHandle.SetHandleFlags(Win32HandleFlags.ProtectFromClose, Win32HandleFlags.ProtectFromClose);

            byte[] bytes = _fileHandle.Read(4);

            fixed (byte* bytesPtr = bytes)
                _baseControlNumber = *(uint*)bytesPtr;

            try
            {
                _features = this.GetFeatures();
            }
            catch
            { }
        }
Ejemplo n.º 55
0
        public MainWindow()
        {
            InitializeComponent();

            Win32.LoadLibrary("C:\\Program Files\\Debugging Tools for Windows (x86)\\dbghelp.dll");

            SymbolProvider symbols = new SymbolProvider(ProcessHandle.Current);

            SymbolProvider.Options |= SymbolOptions.PublicsOnly;

            IntPtr ntdllBase = Loader.GetDllHandle("ntdll.dll");
            FileHandle ntdllFileHandle = null;
            Section section = null;

            ProcessHandle.Current.EnumModules((module) =>
                {
                    if (module.BaseName.Equals("ntdll.dll", StringComparison.InvariantCultureIgnoreCase))
                    {
                        section = new Section(
                            ntdllFileHandle = new FileHandle(@"\??\" + module.FileName,
                                FileShareMode.ReadWrite,
                                FileAccess.GenericExecute | FileAccess.GenericRead
                                ),
                            true,
                            MemoryProtection.ExecuteRead
                            );

                        symbols.LoadModule(module.FileName, module.BaseAddress, module.Size);
                        return false;
                    }

                    return true;
                });

            SectionView view = section.MapView((int)ntdllFileHandle.GetSize());

            ntdllFileHandle.Dispose();

            symbols.EnumSymbols("ntdll!Zw*", (symbol) =>
                {
                    int number = Marshal.ReadInt32(
                        (symbol.Address.ToIntPtr().Decrement(ntdllBase)).Increment(view.Memory).Increment(1));

                    _sysCallNames.Add(
                        number,
                        "Nt" + symbol.Name.Substring(2)
                        );

                    return true;
                });

            view.Dispose();
            section.Dispose();

            symbols.Dispose();

            KProcessHacker.Instance = new KProcessHacker();

            _logger = new SsLogger(4096, false);
            _logger.EventBlockReceived += new EventBlockReceivedDelegate(logger_EventBlockReceived);
            _logger.ArgumentBlockReceived += new ArgumentBlockReceivedDelegate(logger_ArgumentBlockReceived);
            _logger.AddPreviousModeRule(FilterType.Include, KProcessorMode.UserMode);
            _logger.AddProcessIdRule(FilterType.Exclude, ProcessHandle.GetCurrentId());

            listEvents.SetDoubleBuffered(true);
        }
Ejemplo n.º 56
0
        public static string GetMountPointTarget(string fileName)
        {
            // Special cases for DOS drives.

            // "C:", "C:\"
            if (
                (fileName.Length == 2 && fileName[1] == ':') ||
                (fileName.Length == 3 && fileName[1] == ':' && fileName[2] == '\\')
                )
            {
                return GetVolumeName(fileName[0]);
            }

            // "\\.\C:\", "\\?\C:\" (and variants without the trailing backslash"
            if (
                (fileName.Length == 6 || fileName.Length == 7) &&
                fileName[0] == '\\' &&
                fileName[1] == '\\' &&
                (fileName[2] == '.' || fileName[2] == '?') &&
                fileName[3] == '\\' &&
                fileName[5] == ':'
                )
            {
                return GetVolumeName(fileName[4]);
            }

            // "\??\C:"
            if (
                fileName.Length == 6 &&
                fileName[0] == '\\' &&
                fileName[1] == '?' &&
                fileName[2] == '?' &&
                fileName[3] == '\\' &&
                fileName[5] == ':'
                )
            {
                return GetVolumeName(fileName[4]);
            }

            // Query the reparse point.
            using (var fhandle = new FileHandle(
                fileName,
                FileShareMode.ReadWrite,
                FileCreateOptions.OpenReparsePoint | FileCreateOptions.SynchronousIoNonAlert,
                FileAccess.GenericRead
                ))
            {
                return GetReparsePointTarget(fhandle);
            }
        }
Ejemplo n.º 57
0
        private void MapAndLoad(FileHandle fileHandle, bool readOnly)
        {
            using (Section section = new Section(
                fileHandle,
                false,
                readOnly ? MemoryProtection.ExecuteRead : MemoryProtection.ExecuteReadWrite
                ))
            {
                _size = (int)fileHandle.FileSize;
                _view = section.MapView(_size);

                this.Load(_view);
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Creates a connection to KProcessHacker.
        /// </summary>
        /// <param name="deviceName">The name of the KProcessHacker service and device.</param>
        public KProcessHacker2(string deviceName)
        {
            _deviceName = deviceName;

            try
            {
                _fileHandle = new FileHandle(
                    @"\Device\" + deviceName,
                    0,
                    FileAccess.GenericRead | FileAccess.GenericWrite
                    );
            }
            catch (WindowsException ex)
            {
                if (
                    ex.Status == NtStatus.NoSuchDevice ||
                    ex.Status == NtStatus.NoSuchFile ||
                    ex.Status == NtStatus.ObjectNameNotFound
                    )
                {
                    LoadService();
                }
                else
                {
                    throw ex;
                }
            }

            _fileHandle.SetHandleFlags(Win32HandleFlags.ProtectFromClose, Win32HandleFlags.ProtectFromClose);
            _features = this.KphGetFeatures();
        }
Ejemplo n.º 59
0
        public static string GetDeviceName(FileHandle fhandle)
        {
            using (MemoryAlloc data = new MemoryAlloc(600))
            {
                fhandle.IoControl(IoCtlQueryDeviceName, IntPtr.Zero, 0, data, data.Size);

                MountDevName name = data.ReadStruct<MountDevName>();

                return data.ReadUnicodeString(MountDevName.NameOffset, name.NameLength / 2);
            }
        }
Ejemplo n.º 60
0
        public void LoadService()
        {
            // Attempt to load the driver, then try again.
            ServiceHandle shandle;
            bool created = false;

            try
            {
                using (shandle = new ServiceHandle(_deviceName, ServiceAccess.Start))
                {
                    shandle.Start();
                }
            }
            catch
            {
                using (ServiceManagerHandle scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
                {
                    shandle = scm.CreateService(
                        _deviceName,
                        _deviceName,
                        ServiceType.KernelDriver,
                        Application.StartupPath + "\\kprocesshacker.sys"
                        );
                    shandle.Start();
                    created = true;
                }
            }

            try
            {
                _fileHandle = new FileHandle(
                    @"\Device\" + _deviceName,
                    0,
                    FileAccess.GenericRead | FileAccess.GenericWrite
                    );
            }
            finally
            {
                if (created)
                {
                    // The SCM will delete the service when it is stopped.
                    shandle.Delete();
                }

                shandle.Dispose();
            }
        }