示例#1
0
        public static void CopyDirectory(this FileSystemManager fs, string sourcePath, string destPath,
                                         CreateFileOptions options = CreateFileOptions.None, IProgressReport logger = null)
        {
            using (DirectoryHandle sourceHandle = fs.OpenDirectory(sourcePath, OpenDirectoryMode.All))
            {
                foreach (DirectoryEntry entry in fs.ReadDirectory(sourceHandle))
                {
                    string subSrcPath = PathTools.Normalize(PathTools.Combine(sourcePath, entry.Name));
                    string subDstPath = PathTools.Normalize(PathTools.Combine(destPath, entry.Name));

                    if (entry.Type == DirectoryEntryType.Directory)
                    {
                        fs.EnsureDirectoryExists(subDstPath);

                        fs.CopyDirectory(subSrcPath, subDstPath, options, logger);
                    }

                    if (entry.Type == DirectoryEntryType.File)
                    {
                        logger?.LogMessage(subSrcPath);
                        fs.CreateOrOverwriteFile(subDstPath, entry.Size, options);

                        fs.CopyFile(subSrcPath, subDstPath, logger);
                    }
                }
            }
        }
示例#2
0
        private void PopulateDirectory(string directory)
        {
            try
            {
                using (DirectoryHandle dhandle =
                           new DirectoryHandle(directory, DirectoryAccess.Query))
                {
                    var objects = dhandle.GetObjects();

                    foreach (var obj in objects)
                    {
                        if (obj.TypeName != "Directory")
                        {
                            continue;
                        }

                        this.GetTreeNode(directory).Nodes.Add(obj.Name, obj.Name);

                        this.PopulateDirectory(this.NormalizePath(directory + "\\" + obj.Name));
                    }
                }
            }
            catch (WindowsException)
            { }
        }
示例#3
0
        public static IEnumerable <DirectoryEntry> EnumerateEntries(this FileSystemManager fs, string path, string searchPattern, SearchOptions searchOptions)
        {
            bool ignoreCase = searchOptions.HasFlag(SearchOptions.CaseInsensitive);
            bool recurse    = searchOptions.HasFlag(SearchOptions.RecurseSubdirectories);

            using (DirectoryHandle sourceHandle = fs.OpenDirectory(path, OpenDirectoryMode.All))
            {
                foreach (DirectoryEntry entry in fs.ReadDirectory(sourceHandle))
                {
                    if (PathTools.MatchesPattern(searchPattern, entry.Name, ignoreCase))
                    {
                        yield return(entry);
                    }

                    if (entry.Type != DirectoryEntryType.Directory || !recurse)
                    {
                        continue;
                    }

                    string subPath = PathTools.Normalize(PathTools.Combine(path, entry.Name));

                    IEnumerable <DirectoryEntry> subEntries = fs.EnumerateEntries(subPath, searchPattern, searchOptions);

                    foreach (DirectoryEntry subEntry in subEntries)
                    {
                        subEntry.FullPath = PathTools.Combine(path, subEntry.Name);
                        yield return(subEntry);
                    }
                }
            }
        }
        public void PrintsConfig()
        {
            const string simpleConfig =
                @"#comment
key1=value1
key2=value2
";

//            const string expectedOutputPattern =
//@"Main config file\: .+\\config.cfg
//Override config file\: N/A
//Values\:
//KEY1\=value1
//KEY2\=value2
//End";

            using (DirectoryHandle tempDir1 = TempDirectoriesFactory.CreateEmpty())
            {
                var localCfgPath = Path.Combine(tempDir1.AbsolutePath, "config.cfg");
                File.WriteAllText(localCfgPath, simpleConfig);
                FileSimpleConfig localConfig = new FileSimpleConfig(localCfgPath);
                var result = localConfig.ToString();
                //verify manually if needed
            }
        }
示例#5
0
        public static Result ReadDirectory(this FileSystemClient fs, out long entriesRead,
                                           Span <DirectoryEntry> entryBuffer, DirectoryHandle handle)
        {
            Result rc;

            if (fs.Impl.IsEnabledAccessLog() && fs.Impl.IsEnabledHandleAccessLog(handle))
            {
                Tick start = fs.Hos.Os.GetSystemTick();
                rc = Get(handle).Read(out entriesRead, entryBuffer);
                Tick end = fs.Hos.Os.GetSystemTick();

                Span <byte> buffer = stackalloc byte[0x50];
                var         sb     = new U8StringBuilder(buffer, true);

                sb.Append(LogEntryBufferCount).AppendFormat(entryBuffer.Length)
                .Append(LogEntryCount).AppendFormat(entriesRead);
                fs.Impl.OutputAccessLog(rc, start, end, handle, new U8Span(sb.Buffer));
            }
            else
            {
                rc = Get(handle).Read(out entriesRead, entryBuffer);
            }

            fs.Impl.AbortIfNeeded(rc);
            return(rc);
        }
示例#6
0
 public void Setup()
 {
     testDir       = TempDirectoriesFactory.CreateEmpty();
     pathDaily     = Path.Combine(testDir.AbsolutePath, "_event.2014-01-01.txt");
     pathMonthly   = Path.Combine(testDir.AbsolutePath, "_event.2014-01.txt");
     monthlyWriter = new LogWriter(pathDaily, new DateTime(2014, 1, 1), false);
     dailyWriter   = new LogWriter(pathMonthly, new DateTime(2014, 1, 1), false);
 }
示例#7
0
        public void Setup()
        {
            tempDir = TempDirectoriesFactory.CreateEmpty();

            container = new MockingContainer <ChangelogManager>();
            container.Arrange <IBinDirectory>(directory => directory.FullPath).Returns(tempDir.FullName);

            WriteSampleChangelog();
        }
示例#8
0
        public void Setup()
        {
            sourceSoundsDir = TempDirectoriesFactory.CreateByUnzippingFile(Path.Combine("Resources", "sounds_wav.7z"));
            dataDir         = TempDirectoriesFactory.CreateEmpty();
            var waDataDir = Mock.Create <IWurmAssistantDataDirectory>();

            waDataDir.Arrange(directory => directory.DirectoryPath).Returns(dataDir.FullName);
            Kernel.Bind <IWurmAssistantDataDirectory>().ToConstant(waDataDir);
            soundBankDir = Path.Combine(dataDir.FullName, SoundsLibrary.SoundbankDirName);
        }
示例#9
0
        public static Result OpenDirectory(this FileSystemClient fs, out DirectoryHandle handle, U8Span path,
                                           OpenDirectoryMode mode)
        {
            UnsafeHelpers.SkipParamInit(out handle);

            Result             rc;
            U8Span             subPath;
            FileSystemAccessor fileSystem;
            Span <byte>        logBuffer = stackalloc byte[0x300];

            if (fs.Impl.IsEnabledAccessLog())
            {
                Tick start = fs.Hos.Os.GetSystemTick();
                rc = fs.Impl.FindFileSystem(out fileSystem, out subPath, path);
                Tick end = fs.Hos.Os.GetSystemTick();

                var sb = new U8StringBuilder(logBuffer, true);
                sb.Append(LogPath).Append(path).Append((byte)'"').Append(LogOpenMode).AppendFormat((int)mode, 'X');
                logBuffer = sb.Buffer;

                fs.Impl.OutputAccessLogUnlessResultSuccess(rc, start, end, null, new U8Span(logBuffer));
            }
            else
            {
                rc = fs.Impl.FindFileSystem(out fileSystem, out subPath, path);
            }
            fs.Impl.AbortIfNeeded(rc);
            if (rc.IsFailure())
            {
                return(rc);
            }

            DirectoryAccessor accessor;

            if (fs.Impl.IsEnabledAccessLog() && fileSystem.IsEnabledAccessLog())
            {
                Tick start = fs.Hos.Os.GetSystemTick();
                rc = fileSystem.OpenDirectory(out accessor, subPath, mode);
                Tick end = fs.Hos.Os.GetSystemTick();

                fs.Impl.OutputAccessLog(rc, start, end, accessor, new U8Span(logBuffer));
            }
            else
            {
                rc = fileSystem.OpenDirectory(out accessor, subPath, mode);
            }
            fs.Impl.AbortIfNeeded(rc);
            if (rc.IsFailure())
            {
                return(rc);
            }

            handle = new DirectoryHandle(accessor);
            return(Result.Success);
        }
示例#10
0
        private void ChangeDirectory()
        {
            listObjects.Items.Clear();

            if (treeDirectories.SelectedNode != null)
            {
                listObjects.BeginUpdate();

                try
                {
                    using (DirectoryHandle dhandle =
                               new DirectoryHandle(this.NormalizePath(treeDirectories.SelectedNode.FullPath), DirectoryAccess.Query))
                    {
                        var objects = dhandle.GetObjects();

                        foreach (var obj in objects)
                        {
                            var item = listObjects.Items.Add(new ListViewItem(new string[] { obj.Name, obj.TypeName, "" }));

                            if (imageList.Images.ContainsKey(obj.TypeName.ToLower()))
                            {
                                item.ImageKey = obj.TypeName.ToLower();
                            }
                            else
                            {
                                item.ImageKey = "object";
                            }

                            if (obj.TypeName == "SymbolicLink")
                            {
                                try
                                {
                                    using (SymbolicLinkHandle shandle =
                                               new SymbolicLinkHandle(
                                                   this.NormalizePath(
                                                       treeDirectories.SelectedNode.FullPath +
                                                       "\\" + obj.Name),
                                                   SymbolicLinkAccess.Query))
                                        item.SubItems[2].Text = shandle.GetTarget();
                                }
                                catch
                                { }
                            }
                        }
                    }
                }
                catch (WindowsException)
                { }

                listObjects.EndUpdate();
            }
        }
示例#11
0
        public DriverHandle(string name, ObjectFlags objectFlags, DirectoryHandle rootDirectory)
        {
            ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);

            try
            {
                this.Handle = KProcessHacker.Instance.KphOpenDriver(oa).ToIntPtr();
            }
            finally
            {
                oa.Dispose();
            }
        }
示例#12
0
        public IEnumerable <DirectoryEntry> ReadDirectory(DirectoryHandle handle)
        {
            if (IsEnabledAccessLog() && IsEnabledHandleAccessLog(handle))
            {
                TimeSpan startTime = Time.GetCurrent();
                IEnumerable <DirectoryEntry> entries = handle.Directory.Read();
                TimeSpan endTime = Time.GetCurrent();

                OutputAccessLog(startTime, endTime, handle, string.Empty);
                return(entries);
            }

            return(handle.Directory.Read());
        }
示例#13
0
        public virtual void Setup()
        {
            // gotcha: this will spam trace output with exceptions:
            Fixture.HttpWebRequestsMock.Arrange(requests => requests.GetResponseAsync(Arg.IsAny <string>()))
            .Throws <NotSupportedException>();

            HtmlWebRequestsDir =
                TempDirectoriesFactory.CreateByUnzippingFile(Path.Combine(TestPaksZippedDirFullPath,
                                                                          "WurmServerTests-wurmdir-webrequests.7z"));

            ClientMock.PopulateFromZip(Path.Combine(TestPaksZippedDirFullPath, "WurmServerTests-wurmdir.7z"));

            Timescope = TimeStub.CreateStubbedScope();
            Timescope.SetAllLocalTimes(MockedNow);
        }
示例#14
0
        public static void CloseDirectory(this FileSystemClient fs, DirectoryHandle handle)
        {
            if (fs.Impl.IsEnabledAccessLog() && fs.Impl.IsEnabledHandleAccessLog(handle))
            {
                Tick start = fs.Hos.Os.GetSystemTick();
                Get(handle).Dispose();
                Tick end = fs.Hos.Os.GetSystemTick();

                fs.Impl.OutputAccessLog(Result.Success, start, end, handle, U8Span.Empty);
            }
            else
            {
                Get(handle).Dispose();
            }
        }
示例#15
0
        public void CloseDirectory(DirectoryHandle handle)
        {
            if (IsEnabledAccessLog() && IsEnabledHandleAccessLog(handle))
            {
                TimeSpan startTime = Time.GetCurrent();
                handle.Directory.Dispose();
                TimeSpan endTime = Time.GetCurrent();

                OutputAccessLog(startTime, endTime, handle, string.Empty);
            }
            else
            {
                handle.Directory.Dispose();
            }
        }
示例#16
0
        public void Setup()
        {
            //logsDir = TempDirectoriesFactory.CreateByCopy(Path.Combine(TestPaksDirFullPath, "MonthlyHeuristicsExtractor-sample-logs"));
            logsDir = TempDirectoriesFactory.CreateByUnzippingFile(Path.Combine(TestPaksZippedDirFullPath, "MonthlyHeuristicsExtractor-sample-logs.7z"));
            string basePath = logsDir.AbsolutePath;

            testFile                    = new FileInfo(Path.Combine(basePath, "Village.2013-03.txt"));
            emptyTestFile               = new FileInfo(Path.Combine(basePath, "Village.2013-03.empty.txt"));
            invalidTestFile             = new FileInfo(Path.Combine(basePath, "Village.2013-03.invaliddata.txt"));
            unrecognizedTestFile        = new FileInfo(Path.Combine(basePath, "unrecognized.txt"));
            dailyLogFile                = new FileInfo(Path.Combine(basePath, "Village.2012-10-24.txt"));
            fileWithBadStamp            = new FileInfo(Path.Combine(basePath, "_Skills.2012-08.txt"));
            fileThatGoesBeyondMonthDays = new FileInfo(Path.Combine(basePath, "Village.2013-04.txt"));
            fileEvent201412             = new FileInfo(Path.Combine(basePath, "_Event.2014-12.txt"));
        }
 public void ReadsOverridesFromDifferentLocation()
 {
     using (DirectoryHandle tempDir1 = TempDirectoriesFactory.CreateEmpty())
     {
         using (DirectoryHandle tempDir2 = TempDirectoriesFactory.CreateEmpty())
         {
             var localCfgPath    = Path.Combine(tempDir1.AbsolutePath, "config.cfg");
             var localCfgUsrPath = Path.Combine(tempDir2.AbsolutePath, "config.cfg.usr");
             File.WriteAllText(localCfgPath, SampleConfig);
             File.WriteAllText(localCfgUsrPath, OverrideConfig);
             FileSimpleConfig localConfig = new FileSimpleConfig(localCfgPath, localCfgUsrPath);
             Expect(localConfig.HasValue("key to be overriden"));
             Expect(localConfig.GetValue("key to be overriden"), EqualTo("overriden value"));
         }
     }
 }
示例#18
0
        public void Setup()
        {
            wurmApiConfig = new WurmApiConfig {
                Platform = Platform.Linux
            };

            system = new LogFileStreamReaderFactory(wurmApiConfig);

            ubuntuDir = TempDirectoriesFactory.CreateByUnzippingFile(Path.Combine(TestPaksZippedDirFullPath,
                                                                                  "ubuntu-wurm-dir.7z"));

            sampleLogFilePath = Path.Combine(ubuntuDir.AbsolutePath,
                                             "players",
                                             "aldur",
                                             "logs",
                                             "_Event.2015-08.txt");
        }
示例#19
0
        public WurmClientMock([NotNull] DirectoryHandle dir, bool createBasicDirs, Platform targetPlatform)
        {
            if (dir == null)
            {
                throw new ArgumentNullException(nameof(dir));
            }
            this.dir            = dir;
            this.targetPlatform = targetPlatform;

            var dirinfo = new DirectoryInfo(dir.AbsolutePath);

            WurmDir = dirinfo.CreateSubdirectory("wurm");

            if (createBasicDirs)
            {
                CreateBasicDirectories();
            }

            InstallDirectory = Mock.Create <IWurmClientInstallDirectory>();
            InstallDirectory.Arrange(directory => directory.FullPath).Returns(Path.Combine(dir.AbsolutePath, "wurm"));
        }
示例#20
0
        private void PopulateDirectory(string directory)
        {
            try
            {
                using (DirectoryHandle dhandle =
                    new DirectoryHandle(directory, DirectoryAccess.Query))
                {
                    var objects = dhandle.GetObjects();

                    foreach (var obj in objects)
                    {
                        if (obj.TypeName != "Directory")
                            continue;

                        this.GetTreeNode(directory).Nodes.Add(obj.Name, obj.Name);

                        this.PopulateDirectory(this.NormalizePath(directory + "\\" + obj.Name));
                    }
                }
            }
            catch (WindowsException)
            { }
        }
示例#21
0
        public static bool ObjectExists(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(false);
            }
            if (name == "\\")
            {
                return(true);
            }

            string[] s        = name.Split('\\');
            string   lastPart = s[s.Length - 1];
            string   dirPart  = name.Substring(0, name.Length - lastPart.Length - 1); // -1 char to leave out the trailing backslash

            try
            {
                using (var dhandle = new DirectoryHandle(dirPart, DirectoryAccess.Query))
                {
                    var objects = dhandle.GetObjects();

                    foreach (var obj in objects)
                    {
                        if (obj.Name.Equals(lastPart, StringComparison.OrdinalIgnoreCase))
                        {
                            return(true);
                        }
                    }

                    return(false);
                }
            }
            catch (WindowsException)
            {
                return(false);
            }
        }
示例#22
0
        public DirectoryHandle OpenDirectory(string path, OpenDirectoryMode mode)
        {
            FindFileSystem(path.AsSpan(), out FileSystemAccessor fileSystem, out ReadOnlySpan <char> subPath)
            .ThrowIfFailure();

            DirectoryHandle handle;

            if (IsEnabledAccessLog() && fileSystem.IsAccessLogEnabled)
            {
                TimeSpan          startTime = Time.GetCurrent();
                DirectoryAccessor dir       = fileSystem.OpenDirectory(subPath.ToString(), mode);
                handle = new DirectoryHandle(dir);
                TimeSpan endTime = Time.GetCurrent();

                OutputAccessLog(startTime, endTime, handle, $", path: \"{path}\", open_mode: {mode}");
            }
            else
            {
                DirectoryAccessor dir = fileSystem.OpenDirectory(subPath.ToString(), mode);
                handle = new DirectoryHandle(dir);
            }

            return(handle);
        }
示例#23
0
 public void Setup()
 {
     dir = TempDirectoriesFactory.CreateEmpty();
     sqLiteDataStorage = new SqLiteDataStorage(dir.FullName);
 }
示例#24
0
        private void unloadMenuItem_Click(object sender, EventArgs e)
        {
            if (!PhUtils.ShowConfirmMessage(
                    "Unload",
                    _pid != 4 ? "the selected module" : "the selected driver",
                    _pid != 4 ?
                    "Unloading a module may cause the process to crash." :
                    "Unloading a driver may cause system instability.",
                    true
                    ))
            {
                return;
            }

            if (_pid == 4)
            {
                try
                {
                    var    moduleItem  = (ModuleItem)listModules.SelectedItems[0].Tag;
                    string serviceName = null;

                    // Try to find the name of the service key for the driver by
                    // looping through the objects in the Driver directory and
                    // opening each one.
                    using (var dhandle = new DirectoryHandle("\\Driver", DirectoryAccess.Query))
                    {
                        foreach (var obj in dhandle.GetObjects())
                        {
                            try
                            {
                                using (var driverHandle = new DriverHandle("\\Driver\\" + obj.Name))
                                {
                                    if (driverHandle.GetBasicInformation().DriverStart == moduleItem.BaseAddress)
                                    {
                                        serviceName = driverHandle.GetServiceKeyName();
                                        break;
                                    }
                                }
                            }
                            catch
                            { }
                        }
                    }

                    // If we didn't find the service name, use the driver base name.
                    if (serviceName == null)
                    {
                        if (moduleItem.Name.ToLower().EndsWith(".sys"))
                        {
                            serviceName = moduleItem.Name.Remove(moduleItem.Name.Length - 4, 4);
                        }
                        else
                        {
                            serviceName = moduleItem.Name;
                        }
                    }

                    RegistryKey servicesKey =
                        Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services", true);
                    bool        serviceKeyCreated;
                    RegistryKey serviceKey;

                    // Check if the service key exists so that we don't delete it
                    // later if it does.
                    if (Array.Exists <string>(servicesKey.GetSubKeyNames(),
                                              (keyName) => (string.Compare(keyName, serviceName, true) == 0)))
                    {
                        serviceKeyCreated = false;
                    }
                    else
                    {
                        serviceKeyCreated = true;
                        // Create the service key.
                        serviceKey = servicesKey.CreateSubKey(serviceName);

                        serviceKey.SetValue("ErrorControl", 1, RegistryValueKind.DWord);
                        serviceKey.SetValue("ImagePath", "\\??\\" + moduleItem.FileName, RegistryValueKind.ExpandString);
                        serviceKey.SetValue("Start", 1, RegistryValueKind.DWord);
                        serviceKey.SetValue("Type", 1, RegistryValueKind.DWord);
                        serviceKey.Close();
                        servicesKey.Flush();
                    }

                    try
                    {
                        Windows.UnloadDriver(serviceName);
                    }
                    finally
                    {
                        if (serviceKeyCreated)
                        {
                            servicesKey.DeleteSubKeyTree(serviceName);
                        }

                        servicesKey.Close();
                    }

                    listModules.SelectedItems.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to unload the driver. Make sure Process Hacker " +
                                    "is running with administrative privileges. Error:\n\n" +
                                    ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                try
                {
                    using (ProcessHandle phandle = new ProcessHandle(_pid,
                                                                     Program.MinProcessQueryRights | ProcessAccess.VmOperation |
                                                                     ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.CreateThread))
                    {
                        IntPtr baseAddress = ((ModuleItem)listModules.SelectedItems[0].Tag).BaseAddress;

                        phandle.SetModuleReferenceCount(baseAddress, 1);

                        ThreadHandle thread;

                        if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
                        {
                            // Use RtlCreateUserThread to bypass session boundaries. Since
                            // LdrUnloadDll is a native function we don't need to notify CSR.
                            thread = phandle.CreateThread(
                                Loader.GetProcedure("ntdll.dll", "LdrUnloadDll"),
                                baseAddress
                                );
                        }
                        else
                        {
                            // On XP it seems we need to notify CSR...
                            thread = phandle.CreateThreadWin32(
                                Loader.GetProcedure("kernel32.dll", "FreeLibrary"),
                                baseAddress
                                );
                        }

                        thread.Wait(1000 * Win32.TimeMsTo100Ns);

                        NtStatus exitStatus = thread.GetExitStatus();

                        if (exitStatus == NtStatus.DllNotFound)
                        {
                            if (IntPtr.Size == 8)
                            {
                                PhUtils.ShowError("Unable to find the module to unload. This may be caused " +
                                                  "by an attempt to unload a mapped file or a 32-bit module.");
                            }
                            else
                            {
                                PhUtils.ShowError("Unable to find the module to unload. This may be caused " +
                                                  "by an attempt to unload a mapped file.");
                            }
                        }
                        else
                        {
                            exitStatus.ThrowIf();
                        }

                        thread.Dispose();
                    }

                    listModules.SelectedItems.Clear();
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to unload the module", ex);
                }
            }
        }
 public void BaseSetup()
 {
     directoryHandle = TempDirectoriesFactory.CreateEmpty();
 }
示例#26
0
 // ==========================
 // Operations on directory handles
 // ==========================
 public int GetDirectoryEntryCount(DirectoryHandle handle)
 {
     return(handle.Directory.GetEntryCount());
 }
示例#27
0
        private void ChangeDirectory()
        {
            listObjects.Items.Clear();

            if (treeDirectories.SelectedNode != null)
            {
                listObjects.BeginUpdate();

                try
                {
                    using (DirectoryHandle dhandle =
                        new DirectoryHandle(this.NormalizePath(treeDirectories.SelectedNode.FullPath), DirectoryAccess.Query))
                    {
                        var objects = dhandle.GetObjects();

                        foreach (var obj in objects)
                        {
                            var item = listObjects.Items.Add(new ListViewItem(new string[] { obj.Name, obj.TypeName, "" }));

                            if (imageList.Images.ContainsKey(obj.TypeName.ToLower()))
                                item.ImageKey = obj.TypeName.ToLower();
                            else
                                item.ImageKey = "object";

                            if (obj.TypeName == "SymbolicLink")
                            {
                                try
                                {
                                    using (SymbolicLinkHandle shandle =
                                        new SymbolicLinkHandle(
                                            this.NormalizePath(
                                            treeDirectories.SelectedNode.FullPath +
                                            "\\" + obj.Name),
                                            SymbolicLinkAccess.Query))
                                        item.SubItems[2].Text = shandle.GetTarget();
                                }
                                catch
                                { }
                            }
                        }
                    }
                }
                catch (WindowsException)
                { }

                listObjects.EndUpdate();
            }
        }
示例#28
0
        private void unloadMenuItem_Click(object sender, EventArgs e)
        {
            if (!PhUtils.ShowConfirmMessage(
                "Unload",
                _pid != 4 ? "the selected module" : "the selected driver",
                _pid != 4 ?
                "Unloading a module may cause the process to crash." :
                "Unloading a driver may cause system instability.",
                true
                ))
                return;

            if (_pid == 4)
            {
                try
                {
                    ModuleItem moduleItem = listModules.SelectedItems[0].Tag as ModuleItem;
                    string serviceName = null;

                    // Try to find the name of the service key for the driver by 
                    // looping through the objects in the Driver directory and 
                    // opening each one.
                    using (DirectoryHandle dhandle = new DirectoryHandle("\\Driver", DirectoryAccess.Query))
                    {
                        foreach (DirectoryHandle.ObjectEntry obj in dhandle.GetObjects())
                        {
                            try
                            {
                                using (DriverHandle driverHandle = new DriverHandle("\\Driver\\" + obj.Name))
                                {
                                    if (driverHandle.BasicInformation.DriverStart == moduleItem.BaseAddress.ToIntPtr())
                                    {
                                        serviceName = driverHandle.ServiceKeyName;
                                        break;
                                    }
                                }
                            }
                            catch
                            { }
                        }
                    }

                    // If we didn't find the service name, use the driver base name.
                    if (string.IsNullOrEmpty(serviceName))
                    {
                        if (moduleItem.Name.EndsWith(".sys", StringComparison.OrdinalIgnoreCase))
                            serviceName = moduleItem.Name.Remove(moduleItem.Name.Length - 4, 4);
                        else
                            serviceName = moduleItem.Name;
                    }

                    RegistryKey servicesKey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services", true);
                    bool serviceKeyCreated;
                    RegistryKey serviceKey;

                    // Check if the service key exists so that we don't delete it 
                    // later if it does.
                    if (Array.Exists(servicesKey.GetSubKeyNames(),  keyName => string.Compare(keyName, serviceName, true) == 0))
                    {
                        serviceKeyCreated = false;
                    }
                    else
                    {
                        serviceKeyCreated = true;
                        // Create the service key.
                        serviceKey = servicesKey.CreateSubKey(serviceName);

                        serviceKey.SetValue("ErrorControl", 1, RegistryValueKind.DWord);
                        serviceKey.SetValue("ImagePath", "\\??\\" + moduleItem.FileName, RegistryValueKind.ExpandString);
                        serviceKey.SetValue("Start", 1, RegistryValueKind.DWord);
                        serviceKey.SetValue("Type", 1, RegistryValueKind.DWord);
                        serviceKey.Close();
                        servicesKey.Flush();
                    }

                    try
                    {
                        Windows.UnloadDriver(serviceName);
                    }
                    finally
                    {
                        if (serviceKeyCreated)
                            servicesKey.DeleteSubKeyTree(serviceName);

                        servicesKey.Close();
                    }

                    listModules.SelectedItems.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to unload the driver. Make sure Process Hacker " +
                        "is running with administrative privileges. Error:\n\n" +
                        ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                try
                {
                    using (ProcessHandle phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights | ProcessAccess.VmOperation |
                        ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.CreateThread))
                    {
                        IntPtr baseAddress = (listModules.SelectedItems[0].Tag as ModuleItem).BaseAddress.ToIntPtr();

                        phandle.SetModuleReferenceCount(baseAddress, 1);

                        ThreadHandle thread;

                        if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
                        {
                            // Use RtlCreateUserThread to bypass session boundaries. Since 
                            // LdrUnloadDll is a native function we don't need to notify CSR.
                            thread = phandle.CreateThread(
                                Loader.GetProcedure("ntdll.dll", "LdrUnloadDll"),
                                baseAddress
                                );
                        }
                        else
                        {
                            // On XP it seems we need to notify CSR...
                            thread = phandle.CreateThreadWin32(
                                Loader.GetProcedure("kernel32.dll", "FreeLibrary"),
                                baseAddress
                                );
                        }

                        thread.Wait(1000 * Win32.TimeMsTo100Ns);

                        NtStatus exitStatus = thread.GetExitStatus();

                        if (exitStatus == NtStatus.DllNotFound)
                        {
                            if (OSVersion.Architecture == OSArch.Amd64)
                            {
                                PhUtils.ShowError("Unable to find the module to unload. This may be caused by an attempt to unload a mapped file or a 32-bit module.");
                            }
                            else
                            {
                                PhUtils.ShowError("Unable to find the module to unload. This may be caused by an attempt to unload a mapped file.");
                            }
                        }
                        else
                        {
                            exitStatus.ThrowIf();
                        }

                        thread.Dispose();
                    }

                    listModules.SelectedItems.Clear();
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to unload the module", ex);
                }
            }
        }
示例#29
0
 public virtual void Setup()
 {
     dir = TempDirectoriesFactory.CreateEmpty();
 }
 public void Setup()
 {
     DataDir = TempDirectoriesFactory.CreateEmpty();
     var lib = new PersistentCollectionsLibrary(new FlatFilesPersistenceStrategy(DataDir.AbsolutePath));
     System = new SortedServerHistory(lib.DefaultCollection.GetObject<WurmApi.Modules.Wurm.ServerHistory.PersistentModel.ServerHistory>("default"));
 }
 public void Setup()
 {
     dirHandle = TempDirectoriesFactory.CreateEmpty();
     strategy  = CreatePersistenceStrategy();
 }
示例#32
0
        private void unloadMenuItem_Click(object sender, EventArgs e)
        {
            if (!PhUtils.ShowConfirmMessage(
                "Unload",
                _pid != 4 ? "the selected module" : "the selected driver",
                _pid != 4 ?
                "Unloading a module may cause the process to crash." :
                "Unloading a driver may cause system instability.",
                true
                ))
                return;

            if (_pid == 4)
            {
                try
                {
                    var moduleItem = (ModuleItem)listModules.SelectedItems[0].Tag;
                    string serviceName = null;

                    using (var dhandle = new DirectoryHandle("\\Driver", DirectoryAccess.Query))
                    {
                        foreach (var obj in dhandle.GetObjects())
                        {
                            try
                            {
                                using (var driverHandle = new DriverHandle("\\Driver\\" + obj.Name))
                                {
                                    if (driverHandle.GetBasicInformation().DriverStart == moduleItem.BaseAddress)
                                    {
                                        serviceName = driverHandle.GetServiceKeyName();
                                        break;
                                    }
                                }
                            }
                            catch
                            { }
                        }
                    }

                    if (serviceName == null)
                    {
                        if (moduleItem.Name.ToLower().EndsWith(".sys"))
                            serviceName = moduleItem.Name.Remove(moduleItem.Name.Length - 4, 4);
                        else
                            serviceName = moduleItem.Name;
                    }

                    RegistryKey servicesKey =
                        Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services", true);
                    bool serviceKeyCreated;
                    RegistryKey serviceKey;

                    if (Array.Exists<string>(servicesKey.GetSubKeyNames(),
                        (keyName) => (string.Compare(keyName, serviceName, true) == 0)))
                    {
                        serviceKeyCreated = false;
                    }
                    else
                    {
                        serviceKeyCreated = true;

                        serviceKey = servicesKey.CreateSubKey(serviceName);

                        serviceKey.SetValue("ErrorControl", 1, RegistryValueKind.DWord);
                        serviceKey.SetValue("ImagePath", "\\??\\" + moduleItem.FileName, RegistryValueKind.ExpandString);
                        serviceKey.SetValue("Start", 1, RegistryValueKind.DWord);
                        serviceKey.SetValue("Type", 1, RegistryValueKind.DWord);
                        serviceKey.Close();
                        servicesKey.Flush();
                    }

                    try
                    {
                        Windows.UnloadDriver(serviceName);
                    }
                    finally
                    {
                        if (serviceKeyCreated)
                            servicesKey.DeleteSubKeyTree(serviceName);

                        servicesKey.Close();
                    }

                    listModules.SelectedItems.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to unload the driver. Make sure Process Hacker " +
                        "is running with administrative privileges. Error:\n\n" +
                        ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                try
                {
                    using (ProcessHandle phandle = new ProcessHandle(_pid,
                        Program.MinProcessQueryRights | ProcessAccess.VmOperation |
                        ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.CreateThread))
                    {
                        IntPtr baseAddress = ((ModuleItem)listModules.SelectedItems[0].Tag).BaseAddress;

                        phandle.SetModuleReferenceCount(baseAddress, 1);

                        ThreadHandle thread;

                        if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
                        {

                            thread = phandle.CreateThread(
                                Loader.GetProcedure("ntdll.dll", "LdrUnloadDll"),
                                baseAddress
                                );
                        }
                        else
                        {

                            thread = phandle.CreateThreadWin32(
                                Loader.GetProcedure("kernel32.dll", "FreeLibrary"),
                                baseAddress
                                );
                        }

                        thread.Wait(1000 * Win32.TimeMsTo100Ns);

                        NtStatus exitStatus = thread.GetExitStatus();

                        if (exitStatus == NtStatus.DllNotFound)
                        {
                            if (IntPtr.Size == 8)
                            {
                                PhUtils.ShowError("Unable to find the module to unload. This may be caused " +
                                    "by an attempt to unload a mapped file or a 32-bit module.");
                            }
                            else
                            {
                                PhUtils.ShowError("Unable to find the module to unload. This may be caused " +
                                    "by an attempt to unload a mapped file.");
                            }
                        }
                        else
                        {
                            exitStatus.ThrowIf();
                        }

                        thread.Dispose();
                    }

                    listModules.SelectedItems.Clear();
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to unload the module", ex);
                }
            }
        }
示例#33
0
 internal bool IsEnabledHandleAccessLog(DirectoryHandle handle)
 {
     return(handle.Directory.Parent.IsAccessLogEnabled);
 }
示例#34
0
 public void Setup()
 {
     dir = TempDirectoriesFactory.CreateEmpty();
     flatFilesDataStorage = new FlatFilesDataStorage(dir.FullName);
 }
示例#35
0
        public static bool ObjectExists(string name)
        {
            if (string.IsNullOrEmpty(name))
                return false;
            if (name == "\\")
                return true;

            string[] s = name.Split('\\');
            string lastPart = s[s.Length - 1];
            string dirPart = name.Substring(0, name.Length - lastPart.Length - 1); // -1 char to leave out the trailing backslash

            try
            {
                using (var dhandle = new DirectoryHandle(dirPart, ProcessHacker.Native.Security.DirectoryAccess.Query))
                {
                    var objects = dhandle.GetObjects();

                    foreach (var obj in objects)
                    {
                        if (obj.Name.Equals(lastPart, StringComparison.OrdinalIgnoreCase))
                            return true;
                    }

                    return false;
                }
            }
            catch (WindowsException)
            {
                return false;
            }
        }
示例#36
0
 internal void OutputAccessLog(TimeSpan startTime, TimeSpan endTime, DirectoryHandle handle, string message, [CallerMemberName] string caller = "")
 {
     AccessLog.Log(startTime, endTime, handle.GetId(), message, caller);
 }