Exemple #1
0
        private static readonly int BUF_LEN = 8192 + 8; //8 bytes for the leading USN

        #endregion Fields

        #region Methods

        public static bool Build_Volume_Mapping(SafeFileHandle roothandle, Win32Api.USN_JOURNAL_DATA currentUsnState, Action<Win32Api.UsnEntry> func)
        {
            Debug.WriteLine("Starting Build_Volume_Mapping");

            DateTime startTime = DateTime.Now;

            Win32Api.MFT_ENUM_DATA med;
            med.StartFileReferenceNumber = 0;
            med.LowUsn = 0;
            med.HighUsn = currentUsnState.NextUsn;

            using(var med_struct = new StructWrapper(med))
            using(var rawdata = new Raw_Array_Wrapper(BUF_LEN))
            {
                uint outBytesReturned = 0;

                while(Win32Api.DeviceIoControl(
                    roothandle.DangerousGetHandle(),
                    Win32Api.FSCTL_ENUM_USN_DATA,
                    med_struct.Ptr,
                    med_struct.Size,
                    rawdata.Ptr,
                    rawdata.Size,
                    out outBytesReturned,
                    IntPtr.Zero))
                {
                    outBytesReturned = outBytesReturned - sizeof(Int64);
                    IntPtr pUsnRecord = System.IntPtr.Add(rawdata.Ptr, sizeof(Int64));//need to skip 8 bytes because the first 8 bytes are to a usn number, which isnt in the structure
                    while(outBytesReturned > 60)
                    {
                        var usnEntry = new Win32Api.UsnEntry(pUsnRecord);
                        pUsnRecord = System.IntPtr.Add(pUsnRecord, (int)usnEntry.RecordLength);
                        func(usnEntry);

                        if(usnEntry.RecordLength > outBytesReturned)
                            outBytesReturned = 0;// prevent overflow
                        else
                            outBytesReturned -= usnEntry.RecordLength;
                    }
                    Marshal.WriteInt64(med_struct.Ptr, Marshal.ReadInt64(rawdata.Ptr, 0));//read the usn that we skipped and place it into the nextusn
                }
                var possiblerror = Marshal.GetLastWin32Error();
                if(possiblerror < 0)
                    throw new Win32Exception(possiblerror);
            }
            Debug.WriteLine("Time took: " + (DateTime.Now - startTime).TotalMilliseconds + "ms");
            return true;
        }
Exemple #2
0
 public int SetHook()
 {
     hProc = new Win32Api.HookProc(MouseHookProc);
     hHook = Win32Api.SetWindowsHookEx(WH_MOUSE_LL, hProc, IntPtr.Zero, 0);
     return(hHook);
 }
Exemple #3
0
        public UpdateContext GetUpdateContext()
        {
            var updateContext = new UpdateContext();

            var directoryName = Path.GetDirectoryName(config.FullFileName);

            if (directoryName == null)
            {
                throw new InvalidOperationException("Couldn't get directory name that the app is running from");
            }
            var directory = new DirectoryInfo(directoryName);

            // If the application is executing from the TEMP folder, then it's probably been executed from a .zip that has been
            // opened and temporarily extracted by Windows Explorer or 7-zip etc
            var isTempFolder = directoryName.StartsWith(Path.GetTempPath(), StringComparison.OrdinalIgnoreCase);

            // If the application is executing from the special Downloads folder, we can't really count it as "installed"
            // and it should probably be copied somewhere to be considered as installed and allowed to have shortcuts etc
            var downloadsFolder  = Win32Api.GetKnownFolderPath(Win32Api.KnownFolders.Downloads, Win32Api.SpecialFolderOption.DoNotVerify);
            var isDownloadFolder = directoryName.StartsWith(downloadsFolder, StringComparison.OrdinalIgnoreCase);

            var filename = this.config.FileName;

            // We won't count as "installed" if we're running from temp or downloads
            updateContext.IsDeployed = !isTempFolder && !isDownloadFolder;

            // Check for in-place update of exe (.update.exe)
            var extensionless = Path.GetFileNameWithoutExtension(filename);

            if (extensionless.EndsWith(config.UpdateSuffix, StringComparison.OrdinalIgnoreCase))
            {
                updateContext.IsUpdate     = true;
                updateContext.PackageType  = PackageType.Executable;
                updateContext.UpdateSource = new FileInfo(config.FullFileName);
                var destinationName = extensionless.Substring(0, extensionless.Length - config.UpdateSuffix.Length);
                updateContext.UpdateDestination = new FileInfo(Path.Combine(Path.GetDirectoryName(config.FullFileName), destinationName + ".exe"));
                return(updateContext);
            }

            // Check for archive update (update parent folder from extracted sub folder containing updates)
            if (Path.GetExtension(directoryName).Equals(config.UpdateSuffix))
            {
                updateContext.IsUpdate          = true;
                updateContext.PackageType       = PackageType.Archive;
                updateContext.UpdateSource      = directory;
                updateContext.UpdateDestination = directory.Parent;

                return(updateContext);
            }

            // Check if the app is executing from the TEMP folder, in which case it's been extracted
            // and executed from a zip file
            if (isTempFolder)
            {
                updateContext.IsUpdate          = false;
                updateContext.IsDeployed        = false;
                updateContext.PackageType       = PackageType.Archive;
                updateContext.UpdateSource      = directory;
                updateContext.UpdateDestination = new FileInfo(config.InstallPath);
                return(updateContext);
            }

            // Are we running from the Downloads folder?
            if (isDownloadFolder)
            {
                // If we're in a sub directory under Downloads then we can consider this an archive package (one or more files, in own folder)
                if (directory.Parent != null && directory.Parent.FullName.Equals(downloadsFolder, StringComparison.OrdinalIgnoreCase))
                {
                    updateContext.IsUpdate          = true;
                    updateContext.PackageType       = PackageType.Archive;
                    updateContext.UpdateSource      = directory;
                    updateContext.UpdateDestination = directory.Parent;
                }
                else
                {
                    updateContext.IsUpdate          = false;
                    updateContext.PackageType       = PackageType.Executable;
                    updateContext.UpdateSource      = new FileInfo(config.FullFileName);
                    updateContext.UpdateDestination = new FileInfo(config.InstallPath);
                }

                return(updateContext);
            }

            return(null);
        }
Exemple #4
0
        /// <summary>
        /// Called when the user presses a key
        /// </summary>
        // ReSharper disable once RedundantAssignment
        public static bool KeyDownHandler(KeyEventArgs e)
        {
            // if set to true, the keyinput is completly intercepted, otherwise npp sill does its stuff
            bool handled = false;

            MenuItem menuItem = null;

            try {
                // Since it's a keydown message, we can receive this a lot if the user let a button pressed
                var isSpamming = Utils.IsSpamming(e.KeyCode.ToString(), 100, true);

                // check if the user triggered a 3P function defined in the AppliMenu
                menuItem = TriggeredMenuItem(AppliMenu.Instance.ShortcutableItemList, isSpamming, e, ref handled);
                if (handled)
                {
                    return(true);
                }

                // Autocompletion
                if (AutoCompletion.IsVisible)
                {
                    handled = AutoCompletion.PerformKeyDown(e);
                }

                // next tooltip
                if (!handled && InfoToolTip.IsVisible && e.Control && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down))
                {
                    if (e.KeyCode == Keys.Up)
                    {
                        InfoToolTip.IndexToShow--;
                    }
                    else
                    {
                        InfoToolTip.IndexToShow++;
                    }
                    InfoToolTip.TryToShowIndex();
                    handled = true;
                }

                if (handled)
                {
                    return(true);
                }

                // Ok so... when we open a form in notepad++, we can't use the overrides PreviewKeyDown / KeyDown
                // like we normally can, for some reasons, they don't react to certain keys (like enter!)
                // It only works "almost normally" if we ShowDialog() the form?!
                // So i gave up and handle things here!
                // Each control / form that should use a key not handled by Npp should implement a method
                // "PerformKeyDown" that will be triggered from here (see below)
                var curControl = Win32Api.GetFocusedControl();
                if (curControl != null)
                {
                    var invokeResponse = curControl.InvokeMethod("PerformKeyDown", new[] { (object)e });
                    if (invokeResponse != null && (bool)invokeResponse)
                    {
                        return(true);
                    }
                }
                var curWindow = Control.FromHandle(WinApi.GetForegroundWindow());
                if (curWindow != null)
                {
                    var invokeResponse = curWindow.InvokeMethod("PerformKeyDown", new[] { (object)e });
                    if (invokeResponse != null && (bool)invokeResponse)
                    {
                        return(true);
                    }
                }

                // Close interfacePopups
                if (e.KeyCode == Keys.PageDown || e.KeyCode == Keys.PageUp || e.KeyCode == Keys.Next || e.KeyCode == Keys.Prior)
                {
                    ClosePopups();
                }
            } catch (Exception ex) {
                ErrorHandler.ShowErrors(ex, "Occurred in : " + (menuItem == null ? new ShortcutKey(e.Control, e.Alt, e.Shift, e.KeyCode).ToString() : menuItem.ItemId));
            }

            return(handled);
        }
        //--------------------------------------------------------------------------------------------------

        public void SetWindowEnabled(bool bIsEnabled)
        {
            var hRefWnd = new HandleRef(this, new System.Windows.Interop.WindowInteropHelper(_TransparentInputWindow).Handle);

            Win32Api.EnableWindow(hRefWnd, bIsEnabled);
        }
        internal static int FontSizeToHeight(int size, IntPtr hDc)
        {
            int devCap = Gdi32.GetDeviceCaps(hDc, LogPixels.LOGPIXELSY);

            return(-Win32Api.MulDiv(size, devCap, 72));
        }
Exemple #7
0
Fichier : Npp.cs Projet : niandy/3P
 /// <summary>
 /// This message is used for your plugin's dockable dialog. S
 /// Send this message to update (redraw) the dialog. hDlg is the handle of your dialog to be updated
 /// </summary>
 public static void RedrawDialog(IntPtr handle)
 {
     Win32Api.SendMessage(Handle, NppMsg.NPPM_DMMUPDATEDISPINFO, 0, handle);
 }
        private static string GetActualPath(NtfsUsnJournal journal, Win32Api.UsnEntry item)
        {
            string actualPath = null;

            string rawPath;
            var usnRtnCode = journal.GetPathFromFileReference(item.ParentFileReferenceNumber, out rawPath);

            if (usnRtnCode == NtfsUsnJournal.UsnJournalReturnCode.USN_JOURNAL_SUCCESS && 0 != String.Compare(rawPath, "Unavailable", StringComparison.OrdinalIgnoreCase))
            {
                actualPath = $"{journal.MountPoint.TrimEnd('\\')}{rawPath.TrimEnd('\\')}\\{item.Name}";
            }
            else
            {
                return actualPath;
            }
            if (actualPath.ToLowerInvariant().StartsWith($"{journal.MountPoint.TrimEnd('\\')}\\System Volume Information".ToLowerInvariant()))
            {
                return actualPath;
            }
            return actualPath;
        }
Exemple #9
0
Fichier : Npp.cs Projet : niandy/3P
 /// <summary>
 /// Reload given document
 /// </summary>
 public static void Reload(string path, bool askConfirmation)
 {
     Win32Api.SendMessage(Handle, NppMsg.NPPM_RELOADFILE, askConfirmation ? 1 : 0, path);
 }
Exemple #10
0
Fichier : Npp.cs Projet : niandy/3P
 /// <summary>
 /// Allows to execute one of Npp's command
 /// </summary>
 /// <param name="cmd"></param>
 public static void RunCommand(NppMenuCmd cmd)
 {
     Win32Api.SendMessage(Handle, NppMsg.NPPM_MENUCOMMAND, 0, cmd);
 }
Exemple #11
0
Fichier : Npp.cs Projet : niandy/3P
 /// <summary>
 /// Sending this message to get the current index in the view that you indicates in iView : MAIN_VIEW or SUB_VIEW
 /// Returned value is -1 if the view is invisible (hidden), otherwise is the current index
 /// </summary>
 public static int CurrentDocIndexInView(int view)
 {
     return(Win32Api.SendMessage(Handle, NppMsg.NPPM_GETCURRENTDOCINDEX, 0, view).ToInt32());
 }
Exemple #12
0
Fichier : Npp.cs Projet : niandy/3P
 /// <summary>
 /// Use this message to set/remove the check on menu item. cmdID is the command ID which corresponds to the menu item.
 /// </summary>
 public static void SetMenuItemCheck(int cmdId, bool @checked)
 {
     Win32Api.SendMessage(Handle, NppMsg.NPPM_SETMENUITEMCHECK, cmdId, @checked);
 }
Exemple #13
0
Fichier : Npp.cs Projet : niandy/3P
 /// <summary>
 /// Send this message to hide the dialog. handle is the handle of your dialog to be hidden.
 /// </summary>
 public static void HideDockableDialog(IntPtr handle)
 {
     Win32Api.SendMessage(Handle, NppMsg.NPPM_DMMHIDE, 0, handle);
 }
Exemple #14
0
Fichier : Npp.cs Projet : niandy/3P
 /// <summary>
 /// Send this message to show the dialog. handle is the handle of your dialog to be shown
 /// </summary>
 public static void ShowDockableDialog(IntPtr handle)
 {
     Win32Api.SendMessage(Handle, NppMsg.NPPM_DMMSHOW, 0, handle);
 }
Exemple #15
0
        public static void QueryUsnJournal(SafeFileHandle roothandle, ref Win32Api.USN_JOURNAL_DATA usnJournalState)
        {
            int sizeUsnJournalState = Marshal.SizeOf(usnJournalState);
            UInt32 cb;
            if(!Win32Api.DeviceIoControl(
                   roothandle.DangerousGetHandle(),
                  Win32Api.FSCTL_QUERY_USN_JOURNAL,
                  IntPtr.Zero,
                  0,
                  out usnJournalState,
                  sizeUsnJournalState,
                  out cb,
                  IntPtr.Zero))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());

            }
        }
Exemple #16
0
        public static void GetUsnJournalEntries(SafeFileHandle roothandle, Win32Api.USN_JOURNAL_DATA previousUsnState,
            UInt32 reasonMask,
            out List<Win32Api.UsnEntry> usnEntries,
            out Win32Api.USN_JOURNAL_DATA newUsnState)
        {
            usnEntries = new List<Win32Api.UsnEntry>();
            newUsnState = new Win32Api.USN_JOURNAL_DATA();

            QueryUsnJournal(roothandle, ref newUsnState);

            Win32Api.READ_USN_JOURNAL_DATA rujd = new Win32Api.READ_USN_JOURNAL_DATA();
            rujd.StartUsn = previousUsnState.NextUsn;
            rujd.ReasonMask = reasonMask;
            rujd.ReturnOnlyOnClose = 0;
            rujd.Timeout = 0;
            rujd.bytesToWaitFor = 0;
            rujd.UsnJournalId = previousUsnState.UsnJournalID;

            using(var med_struct = new StructWrapper(rujd))
            using(var rawdata = new Raw_Array_Wrapper(BUF_LEN))
            {
                uint outBytesReturned = 0;
                var nextusn = previousUsnState.NextUsn;
                while(nextusn < newUsnState.NextUsn && Win32Api.DeviceIoControl(
                         roothandle.DangerousGetHandle(),
                        Win32Api.FSCTL_READ_USN_JOURNAL,
                        med_struct.Ptr,
                        med_struct.Size,
                        rawdata.Ptr,
                        rawdata.Size,
                        out outBytesReturned,
                        IntPtr.Zero))
                {
                    outBytesReturned = outBytesReturned - sizeof(Int64);
                    IntPtr pUsnRecord = System.IntPtr.Add(rawdata.Ptr, sizeof(Int64));//point safe arithmetic!~!!
                    while(outBytesReturned > 60)   // while there are at least one entry in the usn journal
                    {
                        var usnEntry = new Win32Api.UsnEntry(pUsnRecord);
                        if(usnEntry.USN > newUsnState.NextUsn)
                            break;
                        usnEntries.Add(usnEntry);
                        pUsnRecord = System.IntPtr.Add(pUsnRecord, (int)usnEntry.RecordLength);//point safe arithmetic!~!!
                        outBytesReturned -= usnEntry.RecordLength;
                    }
                    nextusn = Marshal.ReadInt64(rawdata.Ptr, 0);
                    Marshal.WriteInt64(med_struct.Ptr, nextusn);//read the usn that we skipped and place it into the nextusn
                }
            }
        }
Exemple #17
0
        static bool RollBack(InstallInfo info)
        {
            // Unregister assembly
            foreach (string item in info.FilesToRegister)
            {
                string targetFilePath = Path.Combine(info.TargetPath, item);
                RegisterDLL(targetFilePath, false, true);
                RegisterDLL(targetFilePath, true, true);
            }

            // Delete files
            RestartExplorer restartExplorer = new RestartExplorer();

            restartExplorer.Execute(() =>
            {
                // Remove files
                foreach (string filename in info.FilesToCopy)
                {
                    string targetFilePath = Path.Combine(info.TargetPath, filename);

                    if (File.Exists(targetFilePath))
                    {
                        Console.Write($"Deleting {filename}.. ");
                        File.Delete(targetFilePath);
                        Console.WriteLine("OK.");
                    }
                }
            });

            Console.Write($"Deleting {InstallerExecutableName}.. ");

            try
            {
                if (Win32Api.DeleteFile(Path.Combine(info.TargetPath, InstallerExecutableName)))
                {
                    Console.WriteLine("OK.");
                }
                else
                {
                    Win32Api.MoveFileEx(Path.Combine(info.TargetPath, InstallerExecutableName), null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
                    Console.WriteLine("Scheduled for deletion after next reboot.");
                }
            }
            catch
            {
                Win32Api.MoveFileEx(Path.Combine(info.TargetPath, InstallerExecutableName), null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
                Console.WriteLine("Scheduled for deletion after next reboot.");
            }

            if (Directory.Exists(info.TargetPath))
            {
                Console.Write("Deleting target directory.. ");

                try
                {
                    Directory.Delete(info.TargetPath);
                    Console.WriteLine("OK.");
                }
                catch
                {
                    Win32Api.MoveFileEx(info.TargetPath, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
                    Console.WriteLine("Scheduled for deletion after next reboot.");
                }
            }

            Console.Write("Removing uninstall info from registry.. ");
            DeleteUninstaller();
            Console.WriteLine("OK.");

            return(true);
        }
Exemple #18
0
 public NTFS_File(Win32Api.UsnEntry u)
 {
     Entry = u;
     Children = new List<NTFS_File>();
     Parent = null;
 }
Exemple #19
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length < 2)
                {
                    Console.WriteLine(
                        "Command line syntax:\n\tfilter.exe index scenario \n\tindex - network interface index.\n\tscenario - sample set of filters to load.\n\tYou can use ListAdapters to determine correct index.");
                    Console.WriteLine("Available Scenarios:");
                    Console.WriteLine("1 - Redirect only IPv4 DNS packets for processing in user mode.");
                    Console.WriteLine("2 - Redirect only HTTP(TCP port 80) packets for processing in user mode. Both IPv4 and IPv6 protocols.");
                    Console.WriteLine("3 - Drop all IPv4 ICMP packets. Redirect all other packets to user mode (default behaviour).");
                    Console.WriteLine("4 - Block IPv4 access to http://www.ntkernel.com. Pass all other packets without processing in user mode.");
                    Console.WriteLine("5 - Redirect only ARP/RARP packets to user mode. Pass all others.");
                    return;
                }

                var adapterIndex = uint.Parse(args[0]) - 1;
                var scena        = uint.Parse(args[1]);

                var driverPtr = Ndisapi.OpenFilterDriver();
                if (!Ndisapi.IsDriverLoaded(driverPtr))
                {
                    Console.WriteLine("Driver not installed on this system of failed to load.");
                    return;
                }

                // Retrieve adapter list
                var adapters = new TCP_AdapterList();
                Ndisapi.GetTcpipBoundAdaptersInfo(driverPtr, ref adapters);

                // Set tunnel mode for the selected network interface
                var mode = new ADAPTER_MODE
                {
                    dwFlags        = Ndisapi.MSTCP_FLAG_SENT_TUNNEL | Ndisapi.MSTCP_FLAG_RECV_TUNNEL,
                    hAdapterHandle = adapters.m_nAdapterHandle[adapterIndex]
                };

                Ndisapi.SetAdapterMode(driverPtr, ref mode);

                // Create and set event for the adapter
                var manualResetEvent = new ManualResetEvent(false);
                Ndisapi.SetPacketEvent(driverPtr, adapters.m_nAdapterHandle[adapterIndex], manualResetEvent.SafeWaitHandle);

                var filtersTable = new STATIC_FILTER_TABLE();
                filtersTable.m_StaticFilters = new STATIC_FILTER[256];

                switch (scena)
                {
                case 1:
                    filtersTable.m_TableSize = 3;

                    //**************************************************************************************
                    // 1. Outgoing DNS requests filter: REDIRECT OUT UDP packets with destination PORT 53
                    // Common values
                    filtersTable.m_StaticFilters[0].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[0].m_ValidFields      = Ndisapi.NETWORK_LAYER_VALID | Ndisapi.TRANSPORT_LAYER_VALID;
                    filtersTable.m_StaticFilters[0].m_FilterAction     = Ndisapi.FILTER_PACKET_REDIRECT;
                    filtersTable.m_StaticFilters[0].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_SEND;

                    // Network layer filter
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_dwUnionSelector    = Ndisapi.IPV4;
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_ValidFields = Ndisapi.IP_V4_FILTER_PROTOCOL;
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_Protocol    = 17;  //IPPROTO_UDP

                    // Transport layer filter
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_dwUnionSelector                = Ndisapi.TCPUDP;
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_TcpUdp.m_ValidFields           = Ndisapi.TCPUDP_DEST_PORT;
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_TcpUdp.m_DestPort.m_StartRange = 53;     // DNS
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_TcpUdp.m_DestPort.m_EndRange   = 53;

                    //****************************************************************************************
                    // 2. Incoming DNS responses filter: REDIRECT IN UDP packets with source PORT 53
                    // Common values
                    filtersTable.m_StaticFilters[1].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[1].m_ValidFields      = Ndisapi.NETWORK_LAYER_VALID | Ndisapi.TRANSPORT_LAYER_VALID;
                    filtersTable.m_StaticFilters[1].m_FilterAction     = Ndisapi.FILTER_PACKET_REDIRECT;
                    filtersTable.m_StaticFilters[1].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_RECEIVE;

                    // Network layer filter
                    filtersTable.m_StaticFilters[1].m_NetworkFilter.m_dwUnionSelector    = Ndisapi.IPV4;
                    filtersTable.m_StaticFilters[1].m_NetworkFilter.m_IPv4.m_ValidFields = Ndisapi.IP_V4_FILTER_PROTOCOL;
                    filtersTable.m_StaticFilters[1].m_NetworkFilter.m_IPv4.m_Protocol    = 17; //IPPROTO_UDP

                    // Transport layer filter
                    filtersTable.m_StaticFilters[1].m_TransportFilter.m_dwUnionSelector                  = Ndisapi.TCPUDP;
                    filtersTable.m_StaticFilters[1].m_TransportFilter.m_TcpUdp.m_ValidFields             = Ndisapi.TCPUDP_SRC_PORT;
                    filtersTable.m_StaticFilters[1].m_TransportFilter.m_TcpUdp.m_SourcePort.m_StartRange = 53;     // DNS
                    filtersTable.m_StaticFilters[1].m_TransportFilter.m_TcpUdp.m_SourcePort.m_EndRange   = 53;

                    //***************************************************************************************
                    // 3. Pass all packets (skipped by previous filters) without processing in user mode
                    // Common values
                    filtersTable.m_StaticFilters[2].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[2].m_ValidFields      = 0;
                    filtersTable.m_StaticFilters[2].m_FilterAction     = Ndisapi.FILTER_PACKET_PASS;
                    filtersTable.m_StaticFilters[2].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_RECEIVE | Ndisapi.PACKET_FLAG_ON_SEND;

                    break;

                case 2:
                    filtersTable.m_TableSize = 5;

                    //**************************************************************************************
                    // 1. Outgoing HTTP requests filter: REDIRECT OUT TCP packets with destination PORT 80 IPv4
                    // Common values
                    filtersTable.m_StaticFilters[0].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[0].m_ValidFields      = Ndisapi.NETWORK_LAYER_VALID | Ndisapi.TRANSPORT_LAYER_VALID;
                    filtersTable.m_StaticFilters[0].m_FilterAction     = Ndisapi.FILTER_PACKET_REDIRECT;
                    filtersTable.m_StaticFilters[0].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_SEND;

                    // Network layer filter
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_dwUnionSelector    = Ndisapi.IPV4;
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_ValidFields = Ndisapi.IP_V4_FILTER_PROTOCOL;
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_Protocol    = 6; //IPPROTO_TCP

                    // Transport layer filter
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_dwUnionSelector                = Ndisapi.TCPUDP;
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_TcpUdp.m_ValidFields           = Ndisapi.TCPUDP_DEST_PORT;
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_TcpUdp.m_DestPort.m_StartRange = 80;     // HTTP
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_TcpUdp.m_DestPort.m_EndRange   = 80;

                    //****************************************************************************************
                    // 2. Incoming HTTP responses filter: REDIRECT IN TCP packets with source PORT 80 IPv4
                    // Common values
                    filtersTable.m_StaticFilters[1].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[1].m_ValidFields      = Ndisapi.NETWORK_LAYER_VALID | Ndisapi.TRANSPORT_LAYER_VALID;
                    filtersTable.m_StaticFilters[1].m_FilterAction     = Ndisapi.FILTER_PACKET_REDIRECT;
                    filtersTable.m_StaticFilters[1].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_RECEIVE;

                    // Network layer filter
                    filtersTable.m_StaticFilters[1].m_NetworkFilter.m_dwUnionSelector    = Ndisapi.IPV4;
                    filtersTable.m_StaticFilters[1].m_NetworkFilter.m_IPv4.m_ValidFields = Ndisapi.IP_V4_FILTER_PROTOCOL;
                    filtersTable.m_StaticFilters[1].m_NetworkFilter.m_IPv4.m_Protocol    = 6;  //IPPROTO_TCP

                    // Transport layer filter
                    filtersTable.m_StaticFilters[1].m_TransportFilter.m_dwUnionSelector                  = Ndisapi.TCPUDP;
                    filtersTable.m_StaticFilters[1].m_TransportFilter.m_TcpUdp.m_ValidFields             = Ndisapi.TCPUDP_SRC_PORT;
                    filtersTable.m_StaticFilters[1].m_TransportFilter.m_TcpUdp.m_SourcePort.m_StartRange = 80;     // HTTP
                    filtersTable.m_StaticFilters[1].m_TransportFilter.m_TcpUdp.m_SourcePort.m_EndRange   = 80;

                    //****************************************************************************************
                    // 3. Outgoing HTTP requests filter: REDIRECT OUT TCP packets with destination PORT 80 IPv6
                    // Common values
                    filtersTable.m_StaticFilters[2].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[2].m_ValidFields      = Ndisapi.NETWORK_LAYER_VALID | Ndisapi.TRANSPORT_LAYER_VALID;
                    filtersTable.m_StaticFilters[2].m_FilterAction     = Ndisapi.FILTER_PACKET_REDIRECT;
                    filtersTable.m_StaticFilters[2].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_SEND;

                    // Network layer filter
                    filtersTable.m_StaticFilters[2].m_NetworkFilter.m_dwUnionSelector    = Ndisapi.IPV6;
                    filtersTable.m_StaticFilters[2].m_NetworkFilter.m_IPv4.m_ValidFields = Ndisapi.IP_V6_FILTER_PROTOCOL;
                    filtersTable.m_StaticFilters[2].m_NetworkFilter.m_IPv4.m_Protocol    = 6;  //IPPROTO_TCP

                    // Transport layer filter
                    filtersTable.m_StaticFilters[2].m_TransportFilter.m_dwUnionSelector                = Ndisapi.TCPUDP;
                    filtersTable.m_StaticFilters[2].m_TransportFilter.m_TcpUdp.m_ValidFields           = Ndisapi.TCPUDP_DEST_PORT;
                    filtersTable.m_StaticFilters[2].m_TransportFilter.m_TcpUdp.m_DestPort.m_StartRange = 80;     // HTTP
                    filtersTable.m_StaticFilters[2].m_TransportFilter.m_TcpUdp.m_DestPort.m_EndRange   = 80;

                    //****************************************************************************************
                    // 4. Incoming HTTP responses filter: REDIRECT IN TCP packets with source PORT 80 IPv6
                    // Common values
                    filtersTable.m_StaticFilters[3].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[3].m_ValidFields      = Ndisapi.NETWORK_LAYER_VALID | Ndisapi.TRANSPORT_LAYER_VALID;
                    filtersTable.m_StaticFilters[3].m_FilterAction     = Ndisapi.FILTER_PACKET_REDIRECT;
                    filtersTable.m_StaticFilters[3].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_RECEIVE;

                    // Network layer filter
                    filtersTable.m_StaticFilters[3].m_NetworkFilter.m_dwUnionSelector    = Ndisapi.IPV6;
                    filtersTable.m_StaticFilters[3].m_NetworkFilter.m_IPv4.m_ValidFields = Ndisapi.IP_V6_FILTER_PROTOCOL;
                    filtersTable.m_StaticFilters[3].m_NetworkFilter.m_IPv4.m_Protocol    = 6; // IPPROTO_TCP

                    // Transport layer filter
                    filtersTable.m_StaticFilters[3].m_TransportFilter.m_dwUnionSelector                  = Ndisapi.TCPUDP;
                    filtersTable.m_StaticFilters[3].m_TransportFilter.m_TcpUdp.m_ValidFields             = Ndisapi.TCPUDP_SRC_PORT;
                    filtersTable.m_StaticFilters[3].m_TransportFilter.m_TcpUdp.m_SourcePort.m_StartRange = 80;     // HTTP
                    filtersTable.m_StaticFilters[3].m_TransportFilter.m_TcpUdp.m_SourcePort.m_EndRange   = 80;

                    //***************************************************************************************
                    // 5. Pass all packets (skipped by previous filters) without processing in user mode
                    // Common values
                    filtersTable.m_StaticFilters[4].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[4].m_ValidFields      = 0;
                    filtersTable.m_StaticFilters[4].m_FilterAction     = Ndisapi.FILTER_PACKET_PASS;
                    filtersTable.m_StaticFilters[4].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_RECEIVE | Ndisapi.PACKET_FLAG_ON_SEND;

                    break;

                case 3:
                    filtersTable.m_TableSize = 5;

                    //**************************************************************************************
                    // 1. Block all ICMP packets
                    // Common values
                    filtersTable.m_StaticFilters[0].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[0].m_ValidFields      = Ndisapi.NETWORK_LAYER_VALID;
                    filtersTable.m_StaticFilters[0].m_FilterAction     = Ndisapi.FILTER_PACKET_DROP;
                    filtersTable.m_StaticFilters[0].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_SEND | Ndisapi.PACKET_FLAG_ON_RECEIVE;

                    // Network layer filter
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_dwUnionSelector    = Ndisapi.IPV4;
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_ValidFields = Ndisapi.IP_V4_FILTER_PROTOCOL;
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_Protocol    = 1; //IPPROTO_ICMP

                    break;

                case 4:

                    filtersTable.m_TableSize = 2;

                    //**************************************************************************************
                    // 1. Outgoing HTTP requests filter: DROP OUT TCP packets with destination IP 104.196.49.47 PORT 80 - 443 (http://www.ntkernel.com)
                    // Common values
                    filtersTable.m_StaticFilters[0].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[0].m_ValidFields      = Ndisapi.NETWORK_LAYER_VALID | Ndisapi.TRANSPORT_LAYER_VALID;
                    filtersTable.m_StaticFilters[0].m_FilterAction     = Ndisapi.FILTER_PACKET_DROP;
                    filtersTable.m_StaticFilters[0].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_SEND;

                    // Network layer filter
                    var address = new in_addr();
                    var mask    = new in_addr();

                    // IP address 104.196.49.47
                    address.s_b1 = 104;
                    address.s_b2 = 196;
                    address.s_b3 = 49;
                    address.s_b4 = 47;

                    // Network mask 255.255.255.255
                    mask.s_b1 = 255;
                    mask.s_b2 = 255;
                    mask.s_b3 = 255;
                    mask.s_b4 = 255;

                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_dwUnionSelector    = Ndisapi.IPV4;
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_ValidFields = Ndisapi.IP_V4_FILTER_PROTOCOL | Ndisapi.IP_V4_FILTER_DEST_ADDRESS;
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_DestAddress.m_AddressType       = Ndisapi.IP_SUBNET_V4_TYPE;
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_DestAddress.m_IpSubnet.m_Ip     = address.s_addr; // IP address
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_DestAddress.m_IpSubnet.m_IpMask = mask.s_addr;    // network mask
                    filtersTable.m_StaticFilters[0].m_NetworkFilter.m_IPv4.m_Protocol = 6;                                     //IPPROTO_TCP

                    // Transport layer filter
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_dwUnionSelector                = Ndisapi.TCPUDP;
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_TcpUdp.m_ValidFields           = Ndisapi.TCPUDP_DEST_PORT;
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_TcpUdp.m_DestPort.m_StartRange = 80;    // HTTP
                    filtersTable.m_StaticFilters[0].m_TransportFilter.m_TcpUdp.m_DestPort.m_EndRange   = 443;   //HTTPS

                    //***************************************************************************************
                    // 2. Pass all packets (skipped by previous filters) without processing in user mode
                    // Common values
                    filtersTable.m_StaticFilters[1].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[1].m_ValidFields      = 0;
                    filtersTable.m_StaticFilters[1].m_FilterAction     = Ndisapi.FILTER_PACKET_PASS;
                    filtersTable.m_StaticFilters[1].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_RECEIVE | Ndisapi.PACKET_FLAG_ON_SEND;

                    break;

                case 5:

                    filtersTable.m_TableSize = 3;

                    //**************************************************************************************
                    // 1. Redirects all ARP packets to be processes by user mode application
                    // Common values
                    filtersTable.m_StaticFilters[0].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[0].m_ValidFields      = Ndisapi.DATA_LINK_LAYER_VALID;
                    filtersTable.m_StaticFilters[0].m_FilterAction     = Ndisapi.FILTER_PACKET_REDIRECT;
                    filtersTable.m_StaticFilters[0].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_SEND | Ndisapi.PACKET_FLAG_ON_RECEIVE;
                    filtersTable.m_StaticFilters[0].m_DataLinkFilter.m_dwUnionSelector             = Ndisapi.ETH_802_3;
                    filtersTable.m_StaticFilters[0].m_DataLinkFilter.m_Eth8023Filter.m_ValidFields = Ndisapi.ETH_802_3_PROTOCOL;
                    filtersTable.m_StaticFilters[0].m_DataLinkFilter.m_Eth8023Filter.m_Protocol    = 0x0806;  // ETH_P_ARP;


                    //**************************************************************************************
                    // 1. Redirects all RARP packets to be processes by user mode application
                    // Common values
                    filtersTable.m_StaticFilters[1].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[1].m_ValidFields      = Ndisapi.DATA_LINK_LAYER_VALID;
                    filtersTable.m_StaticFilters[1].m_FilterAction     = Ndisapi.FILTER_PACKET_REDIRECT;
                    filtersTable.m_StaticFilters[1].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_SEND | Ndisapi.PACKET_FLAG_ON_RECEIVE;
                    filtersTable.m_StaticFilters[1].m_DataLinkFilter.m_dwUnionSelector             = Ndisapi.ETH_802_3;
                    filtersTable.m_StaticFilters[1].m_DataLinkFilter.m_Eth8023Filter.m_ValidFields = Ndisapi.ETH_802_3_PROTOCOL;
                    filtersTable.m_StaticFilters[1].m_DataLinkFilter.m_Eth8023Filter.m_Protocol    = 0x0806;  // ETH_P_ARP;


                    //***************************************************************************************
                    // 2. Pass all packets (skipped by previous filters) without processing in user mode
                    // Common values
                    filtersTable.m_StaticFilters[2].m_Adapter          = 0; // applied to all adapters
                    filtersTable.m_StaticFilters[2].m_ValidFields      = 0;
                    filtersTable.m_StaticFilters[2].m_FilterAction     = Ndisapi.FILTER_PACKET_PASS;
                    filtersTable.m_StaticFilters[2].m_dwDirectionFlags = Ndisapi.PACKET_FLAG_ON_RECEIVE | Ndisapi.PACKET_FLAG_ON_SEND;

                    break;

                default:
                    Console.WriteLine("Unknown test scenario specified. Exiting.");
                    return;
                }

                // Load filters into driver
                Ndisapi.SetPacketFilterTable(driverPtr, ref filtersTable);

                // Allocate and initialize packet structures
                var request   = new ETH_REQUEST();
                var buffer    = new INTERMEDIATE_BUFFER();
                var bufferPtr = Marshal.AllocHGlobal(Marshal.SizeOf(buffer));

                Win32Api.ZeroMemory(bufferPtr, Marshal.SizeOf(buffer));

                request.hAdapterHandle   = adapters.m_nAdapterHandle[adapterIndex];
                request.EthPacket.Buffer = bufferPtr;

                while (true)
                {
                    manualResetEvent.WaitOne();

                    while (Ndisapi.ReadPacket(driverPtr, ref request))
                    {
                        buffer = (INTERMEDIATE_BUFFER)Marshal.PtrToStructure(bufferPtr, typeof(INTERMEDIATE_BUFFER));

                        WriteToConsole(buffer, bufferPtr);

                        if (buffer.m_dwDeviceFlags == Ndisapi.PACKET_FLAG_ON_SEND)
                        {
                            Ndisapi.SendPacketToAdapter(driverPtr, ref request);
                        }
                        else
                        {
                            Ndisapi.SendPacketToMstcp(driverPtr, ref request);
                        }
                    }

                    manualResetEvent.Reset();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemple #20
0
 /// <summary>
 /// Saves a copy of the current document
 /// </summary>
 public void SaveAsCopy(string path)
 {
     Win32Api.SendMessage(Handle, NppMsg.NPPM_SAVECURRENTFILEAS, 1, path);
 }
Exemple #21
0
        private void buttonAccept_Click(object sender, EventArgs e)
        {
            if (windows.Count <= 0 || listWindows.SelectedIndices.Count <= 0)
            {
                return;                                                               //If there are zero windows or nothing is selected, do nothing
            }
            Window w = windows[listWindows.SelectedItems[0].Index];

            //Get some information for the selected window, to be used in settings its style
            Win32Api.tagWINDOWINFO info = new Win32Api.tagWINDOWINFO();
            Win32Api.GetWindowInfo(w.Handle, out info);

            //Get the current windows style
            uint lStyle = (uint)info.dwStyle;

            Console.WriteLine(lStyle); //DEBUG


            switch (comboBorderStyle.SelectedIndex)
            {
            case 0:                                                    //None
                lStyle &= ~(Win32Api.WS_CAPTION | Win32Api.WS_BORDER); //Bit shit that shift
                break;

            case 1:                                    //Sizable
                lStyle = lStyle | Win32Api.WS_CAPTION; //These two enumerations make the border exist
                lStyle = lStyle | Win32Api.WS_BORDER;
                break;

            case 2:                        //Custom
                lStyle = GetCustomStyle(); //Get the custom style selected in the advanced menu
                break;

            default:
                break;
            }

            //Set the window properties
            Win32Api.SetWindowLong((IntPtr)w.Handle, (int)Win32Api.WindowLongFlags.GWL_STYLE, (int)lStyle);

            //Window settings are cached, so we must set the position to update them
            Win32Api.SetWindowPos((IntPtr)w.Handle, IntPtr.Zero, info.rcWindow.Left, info.rcWindow.Top, info.rcWindow.Right - info.rcWindow.Left, info.rcWindow.Bottom - info.rcWindow.Top, Win32Api.SetWindowPosFlags.FrameChanged);

            //Now for the Window State
            switch (comboWinStyle.SelectedIndex)
            {
            case 0:     //Normal
                Win32Api.ShowWindowAsync((IntPtr)w.Handle, 1);
                break;

            case 1:     //Minimized
                Win32Api.ShowWindowAsync((IntPtr)w.Handle, 2);
                break;

            case 2:     //Maximised
                Win32Api.ShowWindowAsync((IntPtr)w.Handle, 3);
                break;

            default:
                break;
            }
        }
        internal static int FontHeightToSize(int height, IntPtr hDc)
        {
            int devCap = Gdi32.GetDeviceCaps(hDc, LogPixels.LOGPIXELSY);

            return(-Win32Api.MulDivReverse(height, devCap, 72));
        }
Exemple #23
0
        /// <summary>Returns an enumerable collection of <see cref="UsnEntry"/> entries that meet specified criteria.</summary>
        /// <param name="filter">The filter.</param>
        /// <param name="onlyFiles">If gets only the file entries.</param>
        public IEnumerable <UsnEntry> EnumerateUsnEntries(string filter, bool?onlyFiles)
        {
            var usnState = new USN_JOURNAL_DATA_V0();

            if (QueryUsnJournal(ref usnState) != (int)UsnJournalReturnCode.USN_JOURNAL_SUCCESS)
            {
                throw new Win32Exception("Failed to query the USN journal on the volume.");
            }

            // Set up MFT_ENUM_DATA_V0 structure.
            var mftData = new MFT_ENUM_DATA_V0
            {
                StartFileReferenceNumber = 0,
                LowUsn  = 0,
                HighUsn = usnState.NextUsn
            };

            var mftDataSize   = Marshal.SizeOf(mftData);
            var mftDataBuffer = Marshal.AllocHGlobal(mftDataSize);

            Win32Api.ZeroMemory(mftDataBuffer, mftDataSize);
            Marshal.StructureToPtr(mftData, mftDataBuffer, true);


            // Set up the data buffer which receives the USN_RECORD data.
            const int pDataSize = sizeof(ulong) + 10000;
            var       pData     = Marshal.AllocHGlobal(pDataSize);

            Win32Api.ZeroMemory(pData, pDataSize);


            // Gather up volume's directories.
            while (Win32Api.DeviceIoControl(
                       _usnJournalRootHandle,
                       Win32Api.FSCTL_ENUM_USN_DATA,
                       mftDataBuffer,
                       mftDataSize,
                       pData,
                       pDataSize,
                       out var outBytesReturned,
                       IntPtr.Zero))
            {
                var pUsnRecord = new IntPtr(pData.ToInt64() + sizeof(long));

                // While there is at least one entry in the USN journal.
                while (outBytesReturned > 60)
                {
                    var usnEntry = new UsnEntry(pUsnRecord);

                    switch (onlyFiles)
                    {
                    case true when usnEntry.IsFolder:
                    case false when !usnEntry.IsFolder:
                    {
                        pUsnRecord        = new IntPtr(pUsnRecord.ToInt64() + usnEntry.RecordLength);
                        outBytesReturned -= usnEntry.RecordLength;
                        continue;
                    }
                    }

                    if (string.IsNullOrWhiteSpace(filter))
                    {
                        yield return(usnEntry);
                    }
                    else
                    {
                        var options = new GlobOptions {
                            Evaluation = { CaseInsensitive = true }
                        };
                        var glob = Glob.Parse(filter, options);
                        if (glob.IsMatch(usnEntry.Name.AsSpan()))
                        {
                            yield return(usnEntry);
                        }
                    }

                    pUsnRecord        = new IntPtr(pUsnRecord.ToInt64() + usnEntry.RecordLength);
                    outBytesReturned -= usnEntry.RecordLength;
                }

                Marshal.WriteInt64(mftDataBuffer, Marshal.ReadInt64(pData, 0));
            }

            Marshal.FreeHGlobal(pData);
        }
Exemple #24
0
        static void Main(string[] Args)
        {
            // Connect the application to console to have proper output there if requested.
            bool consoleRedirectionWorked = Win32Api.RedirectConsole();

            // Start with command line parsing.
            string userDir = System.IO.Path.Combine(System.IO.Path.Combine(
                                                        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                                        "MySQL"), "Workbench");

            Logger.InitLogger(userDir);

            if (!consoleRedirectionWorked)
            {
                Logger.LogError("Workbench", "Console redirection failed.\n");
            }

            System.Reflection.Assembly asm = System.Reflection.Assembly.GetEntryAssembly();
            string    baseDir   = System.IO.Path.GetDirectoryName(asm.Location);
            WbOptions wbOptions = new WbOptions(baseDir, userDir, true);

            if (!wbOptions.parse_args(Args, asm.Location))
            {
                Logger.LogInfo("Workbench", "Command line params told us to shut down.\n");
                return;
            }

            PrintInitialLogInfo();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Hook into the exception handling to establish our own handling.
            AppDomain currentDomain = AppDomain.CurrentDomain; // CLR

            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);

            Application.ThreadException += // Windows Forms
                                           new System.Threading.ThreadExceptionEventHandler(OnGuiUnhandledException);

            // Read some early values which cannot be stored in the preferences (since they are loaded
            // later) from registry.
            bool   singleInstance = true;
            string lastVersion    = "";
            string currentVersion = GetApplicationMetaInfo(ApplicationMetaInfo.Version);

            Logger.LogInfo("Workbench", "Current version given by meta info is: " + currentVersion + '\n');
            RegistryKey wbKey = Registry.CurrentUser;

            try
            {
                wbKey = wbKey.OpenSubKey(@"Software\Oracle\MySQL Workbench", false);
                if (wbKey != null)
                {
                    if (wbKey.GetValue("DisableSingleInstance", 0).ToString() == "1")
                    {
                        singleInstance = false;
                    }
                    lastVersion = wbKey.GetValue("LastStartedAs", "").ToString();
                }
                else
                {
                    Registry.CurrentUser.CreateSubKey(@"Software\Oracle\MySQL Workbench");
                }
            }
            catch (Exception e)
            {
                Logger.LogError("Workbench", "Error while checking single instance reg key: " + e.Message + '\n');
            }
            finally
            {
                if (wbKey != null)
                {
                    wbKey.Close();
                }
            }

            // First check if this is the first instance of Workbench (if enabled).
            // The setting for single-instance is stored in the registry as it is Windows-only
            // and loading of the application settings happens later.
            if (singleInstance)
            {
                if (!ApplicationInstanceManager.CreateSingleInstance(
                        Assembly.GetExecutingAssembly().GetName().Name, Args, SingleInstanceCallback))
                {
                    Logger.LogInfo("Workbench", "Exiting as another instance of WB is already running.\n");
                    return;
                }
            }

            // Give the main thread a proper name, so we can later check for it when needed.
            Thread.CurrentThread.Name = "mainthread";

            // Change the working dir to to application path.
            // This is necessary because all our internal data files etc. are located under the app dir
            // and WB could have been called from a different dir.
            string workdir = System.IO.Directory.GetCurrentDirectory();

            System.IO.Directory.SetCurrentDirectory(baseDir);

            // Next check if this is the first start of a new version of WB. In this case remove all
            // compiled python files. They will be automatically recreated and can produce problems
            // under certain circumstances.
            if (currentVersion != lastVersion)
            {
                Logger.LogInfo("Workbench", "This is the first start of a new version. Doing some clean up.\n");
                List <string> failed = new List <string>();
                RemoveCompiledPythonFiles(baseDir, failed);

                // TODO: decide if we wanna ask the user to remove those files manually or just ignore them.
            }

            // Some people don't have c:\windows\system32 in PATH, so we need to set it here
            // for WBA to find the needed commands
            String systemFolder = Environment.GetFolderPath(Environment.SpecialFolder.System);
            String cleanedPath  = Environment.GetEnvironmentVariable("PATH");

            String [] paths = cleanedPath.Split(new char[] { ';' });
            cleanedPath = "";

            // Strip all python related dirs from PATH to avoid conflicts with other Python installations.
            foreach (String path in paths)
            {
                if (!path.ToLower().Contains("python"))
                {
                    cleanedPath = cleanedPath + ";" + path;
                }
            }
            Environment.SetEnvironmentVariable("PATH", systemFolder + cleanedPath);
            Logger.LogInfo("Workbench", "Setting PATH to: " + systemFolder + cleanedPath + '\n');

            // Clear PYTHONPATH environment variable, as we do not need it but our python impl
            // seriously gets confused with it.
            Environment.SetEnvironmentVariable("PYTHONPATH", workdir + "\\python\\Lib;" + workdir + "\\python\\DLLs;" + workdir + "\\python");
            Environment.SetEnvironmentVariable("PYTHONHOME", workdir + "\\python");

            // Initialize forms stuff.
            MySQL.Forms.Manager formsManager = MySQL.Forms.Manager.get_instance(); // Creates the singleton.

            // init extra mforms things that are delegated to the frontend, indirectly through RecordsetWrapper in wbpublic
            MySQL.Grt.Db.RecordsetWrapper.init_mforms(MySQL.Grt.Db.RecordsetView.create);

            #region Runtime path check

            // Currently WB has trouble running from a path containing non-ASCII characters.
            // Actually, our third party libraries have (namely lua, python, ctemplate),
            // as they don't consider Unicode file names (encoded as UTF-8) which leads to file-not-found
            // errors. Refuse to work in such a path for now.
            foreach (Char c in baseDir)
            {
                if (c > 0x7f)
                {
                    MessageBox.Show("MySQL Workbench cannot be executed from a path that contains non-ASCII characters.\n" +
                                    "This problem is imposed by used third-party libraries.\n" +
                                    "Please run this application from the default installation path or at least a path which is all ASCII characters.",
                                    "MySQL Workbench Execution Problem", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            #endregion

            #region Release check (outdated beta or rc version)

            // check the date of the executable and suggest to install a new version if this is a beta or rc
            if (GetApplicationMetaInfo(ApplicationMetaInfo.Configuration).ToUpper().IndexOf("BETA") >= 0 ||
                GetApplicationMetaInfo(ApplicationMetaInfo.Configuration).ToUpper().IndexOf("RC") >= 0)
            {
                DateTime fileDate = System.IO.File.GetCreationTime(Application.ExecutablePath);

                if (DateTime.Now.Subtract(fileDate).TotalDays > 45)
                {
                    Logger.LogInfo("Workbench", "Found an old WB pre release. Showing warning.\n");
                    if (MessageBox.Show("This version of MySQL Workbench is older than 45 days and most probably outdated. "
                                        + Environment.NewLine
                                        + "It is recommended to upgrade to a newer version if available. "
                                        + Environment.NewLine
                                        + "Press [OK] to check for a new version and exit the application. "
                                        + "Press [Cancel] to continue using this version.",
                                        "MySQL Workbench Version Outdated", MessageBoxButtons.OKCancel,
                                        MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.OK)
                    {
                        CheckForNewVersion();
                        return;
                    }
                }
            }

            #endregion

            #region Variables and Splashscreen

            #endregion

            #region Initialize GRT

            // Try to instantiate the Workbench context and the GRT Manager and catch exceptions
            try
            {
                // Create Workbench Context
                wbContext = new WbContext(wbOptions.Verbose);

                if (wbContext != null)
                {
                    // Create the GRT Manager instance
                    grtManager = wbContext.get_grt_manager();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }

            #endregion

            // If the Workbench Context and GRT Manager were successfully created,
            // initialize the application
            if (wbContext != null && grtManager != null)
            {
                #region Initialize Callbacks and Mainform

                mainForm = new MainForm(wbContext);

                // Initialize the Workbench context
                ManagedApplication formsApplication = new ManagedApplication(
                    new AppCommandDelegate(mainForm.ApplicationCommand),
                    mainForm.dockDelegate);

                callbacks = new WbFrontendCallbacks(
                    new WbFrontendCallbacks.StrStrStrStrDelegate(mainForm.ShowFileDialog),
                    new WbFrontendCallbacks.VoidStrDelegate(mainForm.ShowStatusText),
                    new WbFrontendCallbacks.BoolStrStrFloatDelegate(mainForm.ShowProgress),
                    new WbFrontendCallbacks.CanvasViewStringStringDelegate(mainForm.CreateNewDiagram),
                    new WbFrontendCallbacks.VoidCanvasViewDelegate(mainForm.DestroyView),
                    new WbFrontendCallbacks.VoidCanvasViewDelegate(mainForm.SwitchedView),
                    new WbFrontendCallbacks.VoidCanvasViewDelegate(mainForm.ToolChanged),
                    new WbFrontendCallbacks.IntPtrGRTManagerModuleStrStrGrtListFlagsDelegate(mainForm.OpenPlugin),
                    new WbFrontendCallbacks.VoidIntPtrDelegate(mainForm.ShowPlugin),
                    new WbFrontendCallbacks.VoidIntPtrDelegate(mainForm.HidePlugin),
                    new WbFrontendCallbacks.VoidRefreshTypeStringIntPtrDelegate(mainForm.RefreshGUI),
                    new WbFrontendCallbacks.VoidBoolDelegate(mainForm.LockGUI),
                    new WbFrontendCallbacks.VoidStrDelegate(mainForm.PerformCommand),
                    new WbFrontendCallbacks.BoolDelegate(mainForm.QuitApplication));

                // TODO: check return value and show error message.
                // Currently the return value is always true. In case of an error an exception is raised.
                // That should change.
                wbContext.init(callbacks, wbOptions,
                               new WbContext.VoidStrUIFormDelegate(mainForm.CreateMainFormView)
                               );

                // command registration must be done after WBContext init
                mainForm.PostInit();

                // Set the Application.Idle event handler
                Application.Idle += new EventHandler(OnApplicationIdle);

                // Don't call the idle handler too often.
                timer          = new System.Windows.Forms.Timer();
                timer.Interval = 100;
                timer.Tick    += new EventHandler(timer_Tick);
                timer.Start();

                // Trigger GRT idle tasks
                grtManager.perform_idle_tasks();

                // Setup Menus
                wbContext.validate_edit_menu();
                mainForm.Show();
                Logger.LogInfo("Workbench", "UI is up\n");

                // Tell the backend our main UI is ready. This will also load a model if it was given via command line
                // and opens the overview form for it.
                wbContext.finished_loading(wbOptions);

                // Right before we go to work and everything was loaded write the current version to registry
                // to allow us later to find out if we ran a new version the first time.
                try
                {
                    wbKey = Registry.CurrentUser.OpenSubKey(@"Software\Oracle\MySQL Workbench", true);
                    if (wbKey != null)
                    {
                        wbKey.SetValue("LastStartedAs", currentVersion);
                    }
                }
                catch (Exception e)
                {
                    Logger.LogError("Workbench", "Couldn't write regkey LastStartedAs: " + e.Message + '\n');
                }
                finally
                {
                    if (wbKey != null)
                    {
                        wbKey.Close();
                    }
                }

                // Start the Application if we are not already shutting down.
                if (!wbContext.is_quitting())
                {
                    try
                    {
                        Logger.LogInfo("Workbench", "Running the application\n");
                        Application.Run(new ApplicationContext(mainForm));
                    }
                    catch (Exception e)
                    {
                        HandleException(e);
                    }
                }

                #endregion

                Logger.LogInfo("Workbench", "Shutting down Workbench\n");

                timer.Stop();
                timer.Dispose();

                // shutdown wb context
                if (wbContext != null)
                {
                    while (wbContext.is_busy())
                    {
                        wbContext.flush_idle_tasks();
                    }

                    wbContext.finalize();
                    wbContext.Dispose();
                }
                formsApplication.Dispose();
                formsManager.Dispose();

                GC.Collect();
            }

            Win32Api.ReleaseConsole();

            Logger.LogInfo("Workbench", "Done\n");
        }
Exemple #25
0
        /// <summary>Given a file reference number GetPathFromFrn() calculates the full path in the out parameter 'path'.</summary>
        /// <param name="frn">A 64-bit file reference number</param>
        /// <param name="path"></param>
        /// <returns>
        /// USN_JOURNAL_SUCCESS                 GetPathFromFrn() function succeeded.
        /// VOLUME_NOT_NTFS                     volume is not an NTFS volume.
        /// INVALID_HANDLE_VALUE                NtfsUsnJournal object failed initialization.
        /// ERROR_ACCESS_DENIED                 accessing the USN journal requires admin rights, see remarks.
        /// INVALID_FILE_REFERENCE_NUMBER       file reference number not found in Master File Table.
        /// ERROR_INVALID_FUNCTION              error generated by NtCreateFile() or NtQueryInformationFile() call.
        /// ERROR_FILE_NOT_FOUND                error generated by NtCreateFile() or NtQueryInformationFile() call.
        /// ERROR_PATH_NOT_FOUND                error generated by NtCreateFile() or NtQueryInformationFile() call.
        /// ERROR_TOO_MANY_OPEN_FILES           error generated by NtCreateFile() or NtQueryInformationFile() call.
        /// ERROR_INVALID_HANDLE                error generated by NtCreateFile() or NtQueryInformationFile() call.
        /// ERROR_INVALID_DATA                  error generated by NtCreateFile() or NtQueryInformationFile() call.
        /// ERROR_NOT_SUPPORTED                 error generated by NtCreateFile() or NtQueryInformationFile() call.
        /// ERROR_INVALID_PARAMETER             error generated by NtCreateFile() or NtQueryInformationFile() call.
        /// ERROR_INVALID_USER_BUFFER           error generated by NtCreateFile() or NtQueryInformationFile() call.
        /// USN_JOURNAL_ERROR                   unspecified USN journal error.
        /// </returns>
        /// <remarks>
        /// If function returns ERROR_ACCESS_DENIED you need to run application as an Administrator.
        /// </remarks>
        public bool TryGetPathFromFileId(ulong frn, out string path)
        {
            path = null;
            if (_isNtfsVolume)
            {
                if (_usnJournalRootHandle.ToInt64() != Win32Api.INVALID_HANDLE_VALUE)
                {
                    if (frn != 0)
                    {
                        long           allocSize = 0;
                        UNICODE_STRING unicodeString;
                        var            objAttributes = new OBJECT_ATTRIBUTES();
                        var            ioStatusBlock = new IO_STATUS_BLOCK();
                        var            hFile         = IntPtr.Zero;

                        var buffer       = Marshal.AllocHGlobal(4096);
                        var refPtr       = Marshal.AllocHGlobal(8);
                        var objAttIntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(objAttributes));

                        // Pointer >> fileid.
                        Marshal.WriteInt64(refPtr, (long)frn);

                        unicodeString.Length        = 8;
                        unicodeString.MaximumLength = 8;
                        unicodeString.Buffer        = refPtr;

                        // Copy unicode structure to pointer.
                        Marshal.StructureToPtr(unicodeString, objAttIntPtr, true);


                        //  InitializeObjectAttributes.
                        objAttributes.Length        = (ulong)Marshal.SizeOf(objAttributes);
                        objAttributes.ObjectName    = objAttIntPtr;
                        objAttributes.RootDirectory = _usnJournalRootHandle;
                        objAttributes.Attributes    = (int)Win32Api.OBJ_CASE_INSENSITIVE;


                        var fOk = Win32Api.NtCreateFile(ref hFile, FileAccess.Read, ref objAttributes, ref ioStatusBlock, ref allocSize, 0,
                                                        FileShare.ReadWrite, Win32Api.FILE_OPEN_IF, Win32Api.FILE_OPEN_BY_FILE_ID /* | Win32Api.FILE_OPEN_FOR_BACKUP_INTENT*/, IntPtr.Zero, 0);


                        if (fOk == 0)
                        {
                            fOk = Win32Api.NtQueryInformationFile(hFile, ref ioStatusBlock, buffer, 4096, FILE_INFORMATION_CLASS.FileNameInformation);

                            if (fOk == 0)
                            {
                                // The first 4 bytes are the name length.
                                var nameLength = Marshal.ReadInt32(buffer, 0);

                                // The next bytes are the name.
                                path = Marshal.PtrToStringUni(new IntPtr(buffer.ToInt64() + 4), nameLength / 2);

                                return(true);
                            }
                            else
                            {
                                // throw new Exception($"NtQueryInformationFile failed with error: 0x{fOk:X8}");
                            }
                        }
                        else
                        {
                            // throw new Exception($"NtCreateFile failed with error: {fOk:X8}");
                        }


                        Win32Api.CloseHandle(hFile);
                        Marshal.FreeHGlobal(buffer);
                        Marshal.FreeHGlobal(objAttIntPtr);
                        Marshal.FreeHGlobal(refPtr);
                    }
                }
            }

            return(false);
        }
Exemple #26
0
 /// <summary>
 /// Returns true if the cursor is within the form window
 /// </summary>
 public static bool IsMouseIn()
 {
     return(Win32Api.IsCursorIn(_form.Handle));
 }
Exemple #27
0
        public IEnumerable <UsnEntry> ReadUsnEntries(USN_JOURNAL_DATA_V0 previousUsnState, uint reasonMask, string filter, bool?onlyFiles)
        {
            var newUsnState = new USN_JOURNAL_DATA_V0();
            var lastError   = (int)UsnJournalReturnCode.VOLUME_NOT_NTFS;

            if (_isNtfsVolume)
            {
                if (_usnJournalRootHandle.ToInt64() != Win32Api.INVALID_HANDLE_VALUE)
                {
                    // Get current USN journal state.
                    lastError = QueryUsnJournal(ref newUsnState);
                    if (lastError == (int)UsnJournalReturnCode.USN_JOURNAL_SUCCESS)
                    {
                        var bReadMore = true;

                        // Sequentially process the USN journal looking for image file entries.
                        const int pbDataSize = sizeof(ulong) * 16384;
                        var       pbData     = Marshal.AllocHGlobal(pbDataSize);
                        Win32Api.ZeroMemory(pbData, pbDataSize);

                        var rujd = new READ_USN_JOURNAL_DATA_V0
                        {
                            StartUsn          = (ulong)previousUsnState.NextUsn,
                            ReasonMask        = reasonMask,
                            ReturnOnlyOnClose = 0,
                            Timeout           = 0,
                            BytesToWaitFor    = 0,
                            UsnJournalId      = previousUsnState.UsnJournalID
                        };

                        var sizeRujd   = Marshal.SizeOf(rujd);
                        var rujdBuffer = Marshal.AllocHGlobal(sizeRujd);
                        Win32Api.ZeroMemory(rujdBuffer, sizeRujd);
                        Marshal.StructureToPtr(rujd, rujdBuffer, true);

                        // Read USN journal entries.
                        while (bReadMore)
                        {
                            var bRtn = Win32Api.DeviceIoControl(_usnJournalRootHandle, Win32Api.FSCTL_READ_USN_JOURNAL, rujdBuffer, sizeRujd, pbData, pbDataSize, out var outBytesReturned, IntPtr.Zero);
                            if (bRtn)
                            {
                                var pUsnRecord = new IntPtr(pbData.ToInt64() + sizeof(ulong));

                                // While there is at least one entry in the USN journal.
                                while (outBytesReturned > 60)
                                {
                                    var usnEntry = new UsnEntry(pUsnRecord);

                                    // Only read until the current usn points beyond the current state's USN.
                                    if (usnEntry.USN >= newUsnState.NextUsn)
                                    {
                                        bReadMore = false;
                                        break;
                                    }

                                    switch (onlyFiles)
                                    {
                                    case true when usnEntry.IsFolder:
                                    case false when !usnEntry.IsFolder:
                                    {
                                        pUsnRecord        = new IntPtr(pUsnRecord.ToInt64() + usnEntry.RecordLength);
                                        outBytesReturned -= usnEntry.RecordLength;
                                        continue;
                                    }
                                    }

                                    if (string.IsNullOrWhiteSpace(filter))
                                    {
                                        yield return(usnEntry);
                                    }
                                    else
                                    {
                                        var options = new GlobOptions {
                                            Evaluation = { CaseInsensitive = true }
                                        };
                                        var glob = Glob.Parse(filter, options);
                                        if (glob.IsMatch(usnEntry.Name.AsSpan()))
                                        {
                                            yield return(usnEntry);
                                        }
                                    }

                                    pUsnRecord        = new IntPtr(pUsnRecord.ToInt64() + usnEntry.RecordLength);
                                    outBytesReturned -= usnEntry.RecordLength;
                                }
                            }

                            else
                            {
                                var lastWin32Error = Marshal.GetLastWin32Error();
                                if (lastWin32Error == (int)Win32Errors.ERROR_HANDLE_EOF)
                                {
                                    lastError = (int)UsnJournalReturnCode.USN_JOURNAL_SUCCESS;
                                }

                                break;
                            }

                            var nextUsn = Marshal.ReadInt64(pbData, 0);
                            if (nextUsn >= newUsnState.NextUsn)
                            {
                                break;
                            }

                            Marshal.WriteInt64(rujdBuffer, nextUsn);
                        }

                        Marshal.FreeHGlobal(rujdBuffer);
                        Marshal.FreeHGlobal(pbData);
                    }
                }
                else
                {
                    lastError = (int)UsnJournalReturnCode.INVALID_HANDLE_VALUE;
                }
            }
        }
Exemple #28
0
        /// <summary>
        /// Snapshots the VM and gets its (maybe partial) StorageLayout
        /// </summary>
        /// <returns>
        /// The physical disks.
        /// </returns> retrieve a
        public StorageLayout BuildStorageLayout()
        {
            StorageLayout sl = new StorageLayout();

            // http://jo0ls-dotnet-stuff.blogspot.fr/2008/12/howto-get-physical-drive-string.html

            foreach (DriveInfo di in DriveInfo.GetDrives())
            {
                if (di.DriveType != DriveType.Fixed /*&& di.DriveType != DriveType.Network*/)
                {
                    continue;
                }
                string devicePath = @"\\.\" + di.RootDirectory.ToString().TrimEnd(new char[] { '\\' });
                Console.WriteLine("Mounted dev path=" + devicePath);


                IntPtr handle = Win32Api.CreateFile(devicePath, Win32Api.GENERIC_READ | Win32Api.GENERIC_WRITE,
                                                    Win32Api.FILE_SHARE_READ | Win32Api.FILE_SHARE_WRITE, IntPtr.Zero,
                                                    Win32Api.OPEN_EXISTING, 0 /*Win32Api.FILE_FLAG_BACKUP_SEMANTICS | (uint)Alphaleonis.Win32.Filesystem.FileSystemRights.SystemSecurity*/, IntPtr.Zero);
                openHandles.Add(handle);

                // Then query underlying partition(s)
                Win32Api.DiskExtents extents = new Win32Api.DiskExtents();

                int  size = 0;
                bool ok   = Win32Api.DeviceIoControl(handle, (uint)Win32Api.Ioctls.GetVolumeDiskExtents, IntPtr.Zero,
                                                     0, ref extents, Marshal.SizeOf(extents), out size, IntPtr.Zero);
                //Console.WriteLine ("DeviceIoControl : "+(new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error())).Message);
                if (!ok)
                {
                    Console.WriteLine("DeviceIoControl failed : " + (new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error())).Message);
                    int    blobSize = Marshal.SizeOf(typeof(Win32Api.DiskExtents)) + (extents.numberOfExtents - 1) * Marshal.SizeOf(typeof(Win32Api.DiskExtent));
                    IntPtr pBlob    = Marshal.AllocHGlobal(blobSize);
                    uint   dataSize = 0;
                    ok = Win32Api.DeviceIoControl(handle, (uint)Win32Api.Ioctls.GetVolumeDiskExtents, IntPtr.Zero, 0, pBlob, blobSize, out dataSize, IntPtr.Zero);
                    if (ok)
                    {
                        IntPtr pNext = new IntPtr(pBlob.ToInt32() + IntPtr.Size /*4*/);                        // is this always ok on 64 bit OSes? ToInt64?
                        for (int i = 0; i < extents.numberOfExtents; i++)
                        {
                            // DiskExtent diskExtentN = DirectCast(Marshal.PtrToStructure(pNext, GetType(DiskExtent)), DiskExtent)
                            Win32Api.DiskExtent diskExtentN = (Win32Api.DiskExtent)Marshal.PtrToStructure(pNext, typeof(Win32Api.DiskExtent));
                            // physicalDrives.Add("\\.\PhysicalDrive" & diskExtentN.DiskNumber.ToString)
                            Console.WriteLine("found multiple backing part disk=: " + diskExtentN.DiskNumber + ", offset=" + diskExtentN.StartingOffset + ", length=" + diskExtentN.ExtentLength);

                            pNext = new IntPtr(pNext.ToInt32() + Marshal.SizeOf(typeof(Win32Api.DiskExtent)));
                        }
                    }
                    else
                    {
                        Console.WriteLine("DeviceIoControl for multiple backing extents failed : " + (new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error())).Message);
                    }
                }
                else
                {
                    Console.WriteLine("found part disk=: " + extents.first.DiskNumber + ", offset=" + extents.first.StartingOffset + ", length=" + extents.first.ExtentLength);
                }

                Disk disk = new Disk();
                disk.Path = @"\\.\PhysicalDrive" + extents.first.DiskNumber.ToString();              //+disk.Id;

                IntPtr physDiskHandle = Win32Api.CreateFile(disk.Path, Win32Api.GENERIC_READ | Win32Api.GENERIC_WRITE,
                                                            Win32Api.FILE_SHARE_READ | Win32Api.FILE_SHARE_WRITE, IntPtr.Zero,
                                                            Win32Api.OPEN_EXISTING, 0 /*Win32Api.FILE_FLAG_BACKUP_SEMANTICS | (uint)Alphaleonis.Win32.Filesystem.FileSystemRights.SystemSecurity*/, IntPtr.Zero);
                //Console.WriteLine ("CreateFile : "+(new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error())).Message);
                openHandles.Add(physDiskHandle);
                disk.BlockStream = new FileStream(physDiskHandle, FileAccess.Read);
                disk.Id          = (string)extents.first.DiskNumber.ToString();

                // now get the disk geometry to obtain physical sector size
                Win32Api.DISK_GEOMETRY diskGeometry = new Win32Api.DISK_GEOMETRY();
                ok = Win32Api.DeviceIoControl(physDiskHandle, (uint)Win32Api.Ioctls.DiskGetDriveGeometry, IntPtr.Zero,
                                              0, ref diskGeometry, Marshal.SizeOf(diskGeometry), out size, IntPtr.Zero);

                Win32Api.MEDIA_SERIAL_NUMBER_DATA diskSerial = new Win32Api.MEDIA_SERIAL_NUMBER_DATA();
                ok = Win32Api.DeviceIoControl(physDiskHandle, (uint)Win32Api.Ioctls.GetMediaSerialNumber, IntPtr.Zero,
                                              0, ref diskSerial, Marshal.SizeOf(diskSerial), out size, IntPtr.Zero);
                Console.WriteLine("DeviceIoControl : " + (new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error())).Message);

                disk.SectorSize = (uint)diskGeometry.BytesPerSector;
                if (diskSerial.SerialNumberData != null)
                {
                    disk.Id = System.Text.Encoding.Default.GetString(diskSerial.SerialNumberData);
                }

                disk.Size = diskGeometry.DiskSize;
                if (!sl.Entries.Contains(disk))
                {
                    sl.Entries.Add(disk);
                }

                Partition p = new Partition();
                p.Offset = (ulong)extents.first.StartingOffset / disk.SectorSize;
                p.Size   = extents.first.ExtentLength;

                FileSystem fs = new FileSystem();
                fs.Path               = devicePath;
                fs.DriveFormat        = fs.DriveFormat;
                fs.MountPoint         = di.RootDirectory.ToString();
                fs.OriginalMountPoint = di.RootDirectory.ToString();
                fs.AvailableFreeSpace = di.AvailableFreeSpace;
                fs.Size               = di.TotalSize;
                p.AddChild(fs);
                Console.WriteLine("created new FS, mnt=" + fs.MountPoint);
                foreach (IDiskElement de in sl.Entries)
                {
                    if (de is Disk && de.Id == disk.Id)
                    {
                        Console.WriteLine("adding new part to layout");
                        de.AddChild(p);
                    }
                }
            }


            return(sl);
        }
Exemple #29
0
        /// <summary>This function queries the USN journal on the volume.</summary>
        /// <param name="usnJournalState">the USN_JOURNAL_DATA object that is associated with this volume</param>
        private int QueryUsnJournal(ref USN_JOURNAL_DATA_V0 usnJournalState)
        {
            Win32Api.DeviceIoControl(_usnJournalRootHandle, Win32Api.FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, out usnJournalState, Marshal.SizeOf(usnJournalState), out _, IntPtr.Zero);

            return(Marshal.GetLastWin32Error());
        }
Exemple #30
0
        public static List<Win32Api.UsnEntry> Get_Changes(SafeFileHandle roothandle, Win32Api.USN_JOURNAL_DATA startUsnState)
        {
            uint reasonMask = Win32Api.USN_REASON_DATA_OVERWRITE |
                   Win32Api.USN_REASON_DATA_EXTEND |
                   Win32Api.USN_REASON_NAMED_DATA_OVERWRITE |
                   Win32Api.USN_REASON_NAMED_DATA_TRUNCATION |
                    Win32Api.USN_REASON_FILE_CREATE |
                    Win32Api.USN_REASON_FILE_DELETE |
                   Win32Api.USN_REASON_EA_CHANGE |
                   Win32Api.USN_REASON_SECURITY_CHANGE |
                   Win32Api.USN_REASON_RENAME_OLD_NAME |
                   Win32Api.USN_REASON_RENAME_NEW_NAME |
                   Win32Api.USN_REASON_INDEXABLE_CHANGE |
                   Win32Api.USN_REASON_BASIC_INFO_CHANGE |
                   Win32Api.USN_REASON_HARD_LINK_CHANGE |
                   Win32Api.USN_REASON_COMPRESSION_CHANGE |
                   Win32Api.USN_REASON_ENCRYPTION_CHANGE |
                   Win32Api.USN_REASON_OBJECT_ID_CHANGE |
                   Win32Api.USN_REASON_REPARSE_POINT_CHANGE |
                   Win32Api.USN_REASON_STREAM_CHANGE |
            Win32Api.USN_REASON_CLOSE;

            var changes = new List<Win32Api.UsnEntry>();
            Win32Api.USN_JOURNAL_DATA newUsnState;
            GetUsnJournalEntries(roothandle, startUsnState, reasonMask, out changes, out newUsnState);
            return changes;
        }
 /// <summary>
 /// Releases unmanaged resources
 /// </summary>
 protected override void DisposeUnmanaged()
 {
     Win32Api.FreeLibrary(PtrLib);
     base.DisposeUnmanaged();
 }
        public void LoginHandler(SessionHandler session)
        {
            try
            {
                var login       = session.CompletedBuffer.GetMessageEntity <LoginPack>();
                var syncContext = new SessionSyncContext()
                {
                    IPv4                 = login.IPV4,
                    MachineName          = login.MachineName,
                    Remark               = login.Remark,
                    CpuInfo              = login.ProcessorInfo,
                    CoreCount            = login.ProcessorCount,
                    MemroySize           = login.MemorySize,
                    StarupDateTime       = login.StartRunTime,
                    Version              = login.ServiceVison,
                    AdminName            = login.UserName,
                    OSVersion            = login.OSVersion,
                    IsCameraExist        = login.ExistCameraDevice,
                    IsRecordExist        = login.ExitsRecordDevice,
                    IsPlayerExist        = login.ExitsPlayerDevice,
                    IsOpenScreenRecord   = login.OpenScreenRecord,
                    IsOpenScreenView     = login.OpenScreenWall,
                    IdentifyId           = login.IdentifyId,
                    RecordScreenIsAction = false,              //桌面记录状态
                    RecordScreenHeight   = login.RecordHeight, //用于桌面记录的高
                    RecordScreenWidth    = login.RecordWidth,  //用于桌面记录宽
                    RecordScreenSpanTime = login.RecordSpanTime,
                    Session              = session
                };

                _syncContexts.Add(syncContext);
                var listItem = new USessionListItem(syncContext);
                syncContext.OnSessionListItem = listItem;
                session.AppTokens[SysConstants.INDEX_WORKER] = syncContext;
                onlineList.Items.Add(listItem);

                //是否开启桌面视图
                if (syncContext.IsOpenScreenView != true)
                {
                    listItem.BackColor = _closeScreenColor;
                }
                else
                {
                    byte[] data = MessageHelper.CopyMessageHeadTo(MessageHead.S_MAIN_DESKTOPVIEW, new byte[] { 0 });//强制创建视图
                    session.SendAsync(data);
                }

                //是否桌面记录
                if (syncContext.IsOpenScreenRecord)
                {
                    byte[] data = MessageHelper.CopyMessageHeadTo(MessageHead.S_MAIN_SCREEN_RECORD_OPEN,
                                                                  new DesktopRecordGetFramePack()
                    {
                        Height   = syncContext.RecordScreenHeight,
                        Width    = syncContext.RecordScreenWidth,
                        TimeSpan = syncContext.RecordScreenSpanTime
                    });
                    session.SendAsync(data);
                }

                _connect_count++;
                stripConnectedNum.Text = _connect_count.ToString();

                Win32Api.FlashWindow(this.Handle, true); //上线任务栏图标闪烁

                this.WriteRuninglog("计算机:" + syncContext.MachineName + "(" + syncContext.Remark + ") -->已连接控制端!", "ok");
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorByCurrentMethod(ex);
                //可能是旧版本上线包
            }
        }
Exemple #33
0
        /// <summary>
        /// Erzeugt einen Screenshot dieses Fensters.
        /// </summary>
        /// <param name="isClientWnd">Handelt es sich um das Handle eines Client-Fensters oder nícht.</param>
        /// <param name="nCmdShow">Der WindowShowStyle.</param>
        /// <param name="timeForRedrawing">Die Zeit, die gewartet werden soll, bis der Screenshot gemacht wird.</param>
        /// <returns>Der Screenshot oder <see langword="null" />, wenn nicht ermittelbar.</returns>
        public Bitmap MakeScreenshot(bool isClientWnd = false,
                                     Win32Api.WindowShowStyle nCmdShow = Win32Api.WindowShowStyle.Restore,
                                     TimeSpan?timeForRedrawing         = null)
        {
            var appWndHandle = this.HWnd;

            if (appWndHandle == IntPtr.Zero ||
                !Win32Api.IsWindow(appWndHandle) ||
                !Win32Api.IsWindowVisible(appWndHandle))
            {
                return(null);
            }

            if (Win32Api.IsIconic(appWndHandle))
            {
                Win32Api.ShowWindow(appWndHandle, nCmdShow);    // show it
            }

            if (!Win32Api.SetForegroundWindow(appWndHandle))
            {
                return(null);    // can't bring it to front
            }

            if (timeForRedrawing.HasValue)
            {
                // give it some time to redraw
                Thread.Sleep(timeForRedrawing.Value);
            }

            RECT appRect;
            var  res = isClientWnd ? Win32Api.GetClientRect(appWndHandle, out appRect) : Win32Api.GetWindowRect(appWndHandle, out appRect);

            if (!res ||
                appRect.Height == 0 ||
                appRect.Width == 0)
            {
                return(null);    // some hidden window
            }

            if (isClientWnd)
            {
                var lt = new Point(appRect.Left, appRect.Top);
                var rb = new Point(appRect.Right, appRect.Bottom);
                Win32Api.ClientToScreen(appWndHandle, ref lt);
                Win32Api.ClientToScreen(appWndHandle, ref rb);

                appRect.Left   = lt.X;
                appRect.Top    = lt.Y;
                appRect.Right  = rb.X;
                appRect.Bottom = rb.Y;
            }

            // intersect with the Desktop rectangle and get what's visible
            var  desktopHandle = Win32Api.GetDesktopWindow();
            RECT desktopRect;

            Win32Api.GetWindowRect(desktopHandle, out desktopRect);

            RECT visibleRect;

            if (!Win32Api.IntersectRect(out visibleRect, ref desktopRect, ref appRect))
            {
                visibleRect = appRect;
            }

            if (Win32Api.IsRectEmpty(ref visibleRect))
            {
                return(null);
            }

            var width   = visibleRect.Width;
            var height  = visibleRect.Height;
            var hdcTo   = IntPtr.Zero;
            var hdcFrom = IntPtr.Zero;
            var hBitmap = IntPtr.Zero;

            try
            {
                Bitmap clsRet = null;

                // get device context of the window...
                hdcFrom = isClientWnd ? Win32Api.GetDC(appWndHandle) : Win32Api.GetWindowDC(appWndHandle);

                // create dc that we can draw to...
                hdcTo   = Win32Api.CreateCompatibleDC(hdcFrom);
                hBitmap = Win32Api.CreateCompatibleBitmap(hdcFrom, width, height);

                //  validate...
                if (hBitmap != IntPtr.Zero)
                {
                    // copy...
                    var x = appRect.Left < 0 ? -appRect.Left : 0;
                    var y = appRect.Top < 0 ? -appRect.Top : 0;

                    var hLocalBitmap = Win32Api.SelectObject(hdcTo, hBitmap);
                    Win32Api.BitBlt(hdcTo, 0, 0, width, height, hdcFrom, x, y, Win32Api.SRCCOPY);
                    Win32Api.SelectObject(hdcTo, hLocalBitmap);

                    // create bitmap for window image...
                    clsRet = System.Drawing.Image.FromHbitmap(hBitmap);
                }

                return(clsRet);
            }
            finally
            {
                //  release...

                if (hdcFrom != IntPtr.Zero)
                {
                    Win32Api.ReleaseDC(appWndHandle, hdcFrom);
                }

                if (hdcTo != IntPtr.Zero)
                {
                    Win32Api.DeleteDC(hdcTo);
                }

                if (hBitmap != IntPtr.Zero)
                {
                    Win32Api.DeleteObject(hBitmap);
                }
            }
        }
        /// <summary>
        /// This function queries the usn journal on the volume.
        /// </summary>
        /// <param name="usnJournalState">the USN_JOURNAL_DATA object that is associated with this volume</param>
        /// <returns>
        /// The success state of the <c>WinApi32.DeviceIoControl</c> call.
        /// </returns>
        private bool QueryUsnJournal(ref Win32Api.USN_JOURNAL_DATA usnJournalState)
        {
            UInt32 cb;

            return Win32Api.DeviceIoControl(
                _usnJournalRootHandle,
                Win32Api.FSCTL_QUERY_USN_JOURNAL,
                IntPtr.Zero,
                0,
                out usnJournalState,
                Marshal.SizeOf(usnJournalState),
                out cb,
                IntPtr.Zero
            );
        }
Exemple #35
0
        /// <summary>
        /// Initialisiert eine neue Instanz der Klasse <see cref="GuiApp" />.
        /// </summary>
        /// <param name="proc">Der zugrundeliegende Prozess.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="proc" /> ist <see langword="null" />.
        /// </exception>
        public GuiApp(Process proc)
        {
            if (proc == null)
            {
                throw new ArgumentNullException("proc");
            }

            var desktopHandle = Win32Api.GetDesktopWindow();

            Win32Api.GetWindowRect(desktopHandle,
                                   out DESKTOP_SIZE);

            this._PROCESS   = proc;
            this._REAL_HWND = IntPtr.Zero;

            var windowHandleList = new List <IntPtr>();

            var listHandle = default(GCHandle);

            try
            {
                if (proc.MainWindowHandle == IntPtr.Zero)
                {
                    throw new ApplicationException("Can't add a process with no MainFrame");
                }

                var maxRect = default(RECT);    // init with 0
                if (IsValidGUIWnd(proc.MainWindowHandle, DESKTOP_SIZE))
                {
                    this._REAL_HWND = proc.MainWindowHandle;
                    return;
                }

                // the mainFrame is size == 0, so we look for the 'real' window
                listHandle = GCHandle.Alloc(windowHandleList);
                foreach (ProcessThread pt in proc.Threads)
                {
                    Win32Api.EnumThreadWindows((uint)pt.Id,
                                               new Win32Api.EnumThreadDelegate(EnumThreadCallback),
                                               GCHandle.ToIntPtr(listHandle));
                }

                this._WINDOW_HANDLES = windowHandleList.ToArray();

                // get the biggest visible window in the current proc
                var maxHWnd = IntPtr.Zero;
                foreach (var hWnd in _WINDOW_HANDLES)
                {
                    RECT crtWndRect;

                    // do we have a valid rect for this window
                    if (Win32Api.IsWindowVisible(hWnd) && Win32Api.GetWindowRect(hWnd, out crtWndRect) &&
                        crtWndRect.Height > maxRect.Height && crtWndRect.Width > maxRect.Width)
                    {
                        // if the rect is outside the desktop, it's a dummy window

                        RECT visibleRect;
                        if (Win32Api.IntersectRect(out visibleRect, ref this.DESKTOP_SIZE, ref crtWndRect) &&
                            !Win32Api.IsRectEmpty(ref visibleRect))
                        {
                            maxHWnd = hWnd;
                            maxRect = crtWndRect;
                        }
                    }
                }

                if (maxHWnd != IntPtr.Zero &&
                    maxRect.Width > 0 &&
                    maxRect.Height > 0)
                {
                    this._REAL_HWND = maxHWnd;
                }
                else
                {
                    this._REAL_HWND = proc.MainWindowHandle;    // just add something even if it's a bad window
                }
            }
            finally
            {
                if (listHandle != default(GCHandle) &&
                    listHandle.IsAllocated)
                {
                    listHandle.Free();
                }
            }
        }
 private void PopulateFlags(RawUSNEntry dbEntry, Win32Api.UsnEntry entry)
 {
     uint value = entry.Reason & Win32Api.USN_REASON_DATA_OVERWRITE;
     if (0 != value)
     {
         dbEntry.DataOverwrite = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_DATA_EXTEND;
     if (0 != value)
     {
         dbEntry.DataExtend = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_DATA_TRUNCATION;
     if (0 != value)
     {
         dbEntry.DataTruncation = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_NAMED_DATA_OVERWRITE;
     if (0 != value)
     {
         dbEntry.NamedDataOverwrite = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_NAMED_DATA_EXTEND;
     if (0 != value)
     {
         dbEntry.NamedDataExtend = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_NAMED_DATA_TRUNCATION;
     if (0 != value)
     {
         dbEntry.NamedDataTruncation = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_FILE_CREATE;
     if (0 != value)
     {
         dbEntry.FileCreate = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_FILE_DELETE;
     if (0 != value)
     {
         dbEntry.FileDelete = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_EA_CHANGE;
     if (0 != value)
     {
         dbEntry.EaChange = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_SECURITY_CHANGE;
     if (0 != value)
     {
         dbEntry.SecurityChange = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_RENAME_OLD_NAME;
     if (0 != value)
     {
         dbEntry.RenameOldName = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_RENAME_NEW_NAME;
     if (0 != value)
     {
         dbEntry.RenameNewName = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_INDEXABLE_CHANGE;
     if (0 != value)
     {
         dbEntry.IndexableChange = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_BASIC_INFO_CHANGE;
     if (0 != value)
     {
         dbEntry.BasicInfoChange = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_HARD_LINK_CHANGE;
     if (0 != value)
     {
         dbEntry.HardLinkChange = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_COMPRESSION_CHANGE;
     if (0 != value)
     {
         dbEntry.CompressionChange = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_ENCRYPTION_CHANGE;
     if (0 != value)
     {
         dbEntry.EncryptionChange = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_OBJECT_ID_CHANGE;
     if (0 != value)
     {
         dbEntry.ObjectIdChange = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_REPARSE_POINT_CHANGE;
     if (0 != value)
     {
         dbEntry.ReparsePointChange = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_STREAM_CHANGE;
     if (0 != value)
     {
         dbEntry.StreamChange = true;
     }
     value = entry.Reason & Win32Api.USN_REASON_CLOSE;
     if (0 != value)
     {
         dbEntry.Close = true;
     }
 }
Exemple #37
0
 /// <summary>
 /// Saves the current document
 /// </summary>
 public void Save()
 {
     Win32Api.SendMessage(Handle, NppMsg.NPPM_SAVECURRENTFILE, 0, 0);
 }
        private static bool RegisterRawInputDevice(Win32Api.RawInput.RAWINPUTDEVICE device)
        {
            RawInput.RAWINPUTDEVICE[] devices = new RawInput.RAWINPUTDEVICE[1];        // Raw input devices.

            devices[0] = device;
            return RawInput.RegisterRawInputDevices(devices, 1, Marshal.SizeOf(typeof(RawInput.RAWINPUTDEVICE)));
        }
Exemple #39
0
Fichier : Npp.cs Projet : niandy/3P
 /// <summary>
 /// For each created dialog in your plugin, you should register it (and unregister while destroy it) to Notepad++ by using this message.
 /// If this message is ignored, then your dialog won't react with the key stroke messages such as TAB key.
 /// For the good functioning of your plugin dialog, you're recommended to not ignore this message.
 /// </summary>
 public static void UnRegisterToNpp(IntPtr handle)
 {
     Win32Api.SendMessage(Handle, NppMsg.NPPM_MODELESSDIALOG, (int)NppMsg.MODELESSDIALOGREMOVE, handle);
 }