Exemple #1
0
        private static SafeCertContextHandle FilterPFXStore(byte[] rawData, string password, PfxCertStoreFlags pfxCertStoreFlags)
        {
            SafeCertStoreHandle hStore;

            unsafe
            {
                fixed(byte *pbRawData = rawData)
                {
                    CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(rawData.Length, pbRawData);

                    hStore = Interop.crypt32.PFXImportCertStore(ref certBlob, password, pfxCertStoreFlags);
                    if (hStore.IsInvalid)
                    {
                        throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
                    }
                    ;
                }
            }

            try
            {
                // Find the first cert with private key. If none, then simply take the very first cert. Along the way, delete the keycontainers
                // of any cert we don't accept.
                SafeCertContextHandle pCertContext = SafeCertContextHandle.InvalidHandle;
                SafeCertContextHandle pEnumContext = null;
                while (Interop.crypt32.CertEnumCertificatesInStore(hStore, ref pEnumContext))
                {
                    if (pEnumContext.ContainsPrivateKey)
                    {
                        if ((!pCertContext.IsInvalid) && pCertContext.ContainsPrivateKey)
                        {
                            // We already found our chosen one. Free up this one's key and move on.
                            SafeCertContextHandleWithKeyContainerDeletion.DeleteKeyContainer(pEnumContext);
                        }
                        else
                        {
                            // Found our first cert that has a private key. Set him up as our chosen one but keep iterating
                            // as we need to free up the keys of any remaining certs.
                            pCertContext.Dispose();
                            pCertContext = pEnumContext.Duplicate();
                        }
                    }
                    else
                    {
                        if (pCertContext.IsInvalid)
                        {
                            pCertContext = pEnumContext.Duplicate(); // Doesn't have a private key but hang on to it anyway in case we don't find any certs with a private key.
                        }
                    }
                }

                if (pCertContext.IsInvalid)
                {
                    // For compat, setting "hr" to ERROR_INVALID_PARAMETER even though ERROR_INVALID_PARAMETER is not actually an HRESULT.
                    throw ErrorCode.ERROR_INVALID_PARAMETER.ToCryptographicException();
                }

                return(pCertContext);
            }
            finally
            {
                hStore.Dispose();
            }
        }
Exemple #2
0
        /// <summary>
        /// Move one file from source to destination. Create the target directory if necessary.
        /// </summary>
        /// <throws>IO related exceptions</throws>
        private bool MoveFileWithLogging
        (
            string sourceFile,
            string destinationFile
        )
        {
            if (FileSystems.Default.DirectoryExists(destinationFile))
            {
                Log.LogErrorWithCodeFromResources("Move.DestinationIsDirectory", sourceFile, destinationFile);
                return(false);
            }

            if (FileSystems.Default.DirectoryExists(sourceFile))
            {
                // If the source file passed in is actually a directory instead of a file, log a nice
                // error telling the user so.  Otherwise, .NET Framework's File.Move method will throw
                // an FileNotFoundException, which is not very useful to the user.
                Log.LogErrorWithCodeFromResources("Move.SourceIsDirectory", sourceFile);
                return(false);
            }

            // Check the source exists.
            if (!FileSystems.Default.FileExists(sourceFile))
            {
                Log.LogErrorWithCodeFromResources("Move.SourceDoesNotExist", sourceFile);
                return(false);
            }

            // We can't ovewrite a file unless it's writeable
            if (OverwriteReadOnlyFiles && FileSystems.Default.FileExists(destinationFile))
            {
                MakeWriteableIfReadOnly(destinationFile);
            }

            string destinationFolder = Path.GetDirectoryName(destinationFile);

            if (!string.IsNullOrEmpty(destinationFolder) && !FileSystems.Default.DirectoryExists(destinationFolder))
            {
                Log.LogMessageFromResources(MessageImportance.Normal, "Move.CreatesDirectory", destinationFolder);
                Directory.CreateDirectory(destinationFolder);
            }

            // Do not log a fake command line as well, as it's superfluous, and also potentially expensive
            Log.LogMessageFromResources(MessageImportance.Normal, "Move.FileComment", sourceFile, destinationFile);

            // We want to always overwrite any existing destination file.
            // Unlike File.Copy, File.Move does not have an overload to overwrite the destination.
            // We cannot simply delete the destination file first because possibly it is also the source!
            // Nor do we want to just do a Copy followed by a Delete, because for large files that will be slow.
            // We are forced to use Win32's MoveFileEx.
            bool result = NativeMethods.MoveFileEx(sourceFile, destinationFile, Flags);

            if (!result)
            {
                // It failed so we need a nice error message. Unfortunately
                // Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); and
                // throw new IOException((new Win32Exception(error)).Message)
                // do not produce great error messages (eg., "The operation succeeded" (!)).
                // For this reason the BCL has is own mapping in System.IO.__Error.WinIOError
                // which is unfortunately internal.
                // So try to get a nice message by using the BCL Move(), which will likely fail
                // and throw. Otherwise use the "correct" method.
                File.Move(sourceFile, destinationFile);

                // Apparently that didn't throw, so..
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            // If the destination file exists, then make sure it's read-write.
            // The File.Move command copies attributes, but our move needs to
            // leave the file writeable.
            if (FileSystems.Default.FileExists(destinationFile))
            {
                // Make it writable
                MakeWriteableIfReadOnly(destinationFile);
            }

            return(true);
        }
 private static void ThrowLastWin32Error(string message)
 {
     throw new IOException(message, Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
 }
        public void Generate()
        {
            try
            {
                if (threadtoken != IntPtr.Zero)
                {
                    if (!NativeMethods.SetThreadToken(IntPtr.Zero, threadtoken))
                    {
                        throw new COMException(Resource.FormatString("Err_SetThreadToken"), Marshal.GetHRForLastWin32Error());
                    }
                }

                if (wsdlurl.Length <= 0)
                {
                    return;
                }
                Stream    oSchemaStream   = new MemoryStream();
                ArrayList aCodeStreamList = new ArrayList();
                MetaData.RetrieveSchemaFromUrlToStream(wsdlurl, oSchemaStream);
                oSchemaStream.Position = 0;
                MetaData.ConvertSchemaStreamToCodeSourceStream(true, pathname, oSchemaStream, aCodeStreamList);
                MetaData.ConvertCodeSourceStreamToAssemblyFile(aCodeStreamList, filename, null);
            }
            catch (Exception e)
            {
                ComSoapPublishError.Report(e.ToString());
                SavedException  = e;
                ExceptionThrown = true;
                throw;
            }
        }
Exemple #5
0
        public void WriteData(string fileName, string templateFileName, byte[] data, ref long readTime)
        {
            if (!fileName.ToLowerInvariant().EndsWith(".config", StringComparison.Ordinal))
            {
                throw new Exception(System.Web.SR.GetString("Can_not_access_files_other_than_config"));
            }
            bool           flag      = File.Exists(fileName);
            FileInfo       info      = null;
            FileAttributes normal    = FileAttributes.Normal;
            string         path      = null;
            Exception      exception = null;
            FileStream     stream    = null;
            long           ticks     = 0L;
            long           num2      = 0L;

            if (flag && (File.GetLastWriteTimeUtc(fileName).Ticks > readTime))
            {
                throw new Exception(System.Web.SR.GetString("File_changed_since_read", new object[] { fileName }));
            }
            if (flag)
            {
                try
                {
                    info   = new FileInfo(fileName);
                    normal = info.Attributes;
                }
                catch
                {
                }
                if ((normal & (FileAttributes.Hidden | FileAttributes.ReadOnly)) != 0)
                {
                    throw new Exception(System.Web.SR.GetString("File_is_read_only", new object[] { fileName }));
                }
            }
            path = fileName + "." + GetRandomFileExt() + ".tmp";
            for (int i = 0; File.Exists(path); i++)
            {
                if (i > 100)
                {
                    throw new Exception(System.Web.SR.GetString("Unable_to_create_temp_file"));
                }
                path = fileName + "." + GetRandomFileExt() + ".tmp";
            }
            try
            {
                stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite, data.Length, FileOptions.None | FileOptions.WriteThrough);
                stream.Write(data, 0, data.Length);
            }
            catch (Exception exception2)
            {
                exception = exception2;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            if (exception != null)
            {
                try
                {
                    File.Delete(path);
                }
                catch
                {
                }
                throw exception;
            }
            if (flag)
            {
                try
                {
                    this.DuplicateFileAttributes(fileName, path);
                    goto Label_0170;
                }
                catch
                {
                    goto Label_0170;
                }
            }
            if (templateFileName != null)
            {
                try
                {
                    this.DuplicateTemplateAttributes(fileName, templateFileName);
                }
                catch
                {
                }
            }
Label_0170:
            if (!System.Web.UnsafeNativeMethods.MoveFileEx(path, fileName, 11))
            {
                try
                {
                    File.Delete(path);
                }
                catch
                {
                }
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            if (flag)
            {
                info = new FileInfo(fileName)
                {
                    Attributes = normal
                };
            }
            ticks    = File.GetLastWriteTimeUtc(fileName).Ticks;
            num2     = DateTime.UtcNow.Ticks;
            readTime = (num2 > ticks) ? num2 : ticks;
        }
Exemple #6
0
        /// <summary>
        /// Execute message queue.
        /// </summary>
        /// <param name="task">Completion awaiting task</param>
        public void Run(Task task)
        {
            // Run only target thread.
            var currentThreadId = GetCurrentThreadId();

            if (currentThreadId != targetThreadId)
            {
                throw new InvalidOperationException();
            }

            // Schedule task completion for abort message loop.
            task?.ContinueWith(_ =>
                               PostThreadMessage(targetThreadId, WM_QUIT, IntPtr.Zero, IntPtr.Zero));

            // Run message loop (very legacy knowledge...)
            while (true)
            {
                // Get front of queue (or waiting).
                MSG msg;
                var result = GetMessage(out msg, IntPtr.Zero, 0, 0);

                // If message number is WM_QUIT (Cause PostQuitMessage API):
                if (result == 0)
                {
                    // Exit.
                    break;
                }

                // If cause error:
                if (result == -1)
                {
                    // Throw.
                    var hr = Marshal.GetHRForLastWin32Error();
                    Marshal.ThrowExceptionForHR(hr);
                }

                // If message is WM_SC:
                if (msg.msg == WM_SC)
                {
                    // Retreive GCHandles from cookies.
                    var continuationHandle = GCHandle.FromIntPtr(msg.wParam);
                    var stateHandle        = GCHandle.FromIntPtr(msg.lParam);

                    // Retreive continuation and state.
                    var continuation = (SendOrPostCallback)continuationHandle.Target;
                    var state        = stateHandle.Target;

                    // Release handle (Recollectable by GC)
                    continuationHandle.Free();
                    stateHandle.Free();

                    // Invoke continuation.
                    continuation(state);

                    // Consumed message.
                    continue;
                }

                // Translate accelerator (require UI stability)
                TranslateMessage(ref msg);

                // Send to assigned window procedure.
                DispatchMessage(ref msg);
            }
        }
Exemple #7
0
        public static void ChangeColorEffect(float[,] matrix)
        {
            ColorEffect colorEffect = new ColorEffect(matrix);

            if (!NativeMethods.SetMagnificationDesktopColorEffect(ref colorEffect))
            {
                var inner = new Exception("SetMagnificationDesktopColorEffect()", Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
                throw new CannotChangeColorEffectException("An error occured while applying a color effect. Another application using the same API might be interfering...", inner);
            }
        }
Exemple #8
0
 public static Exception LastWin32Exception()
 {
     return(Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
 }
        private void OverlappedIoThreadMainLoop()
        {
            // WaitCommEvent
            bool serialCommPending = false;

            m_SerialCommEvent.Reset();
            NativeOverlapped serialCommOverlapped = new NativeOverlapped();

            serialCommOverlapped.EventHandle = m_SerialCommEvent.SafeWaitHandle.DangerousGetHandle();

            // ReadFile
            bool readPending = false;

            m_ReadEvent.Reset();
            NativeOverlapped readOverlapped = new NativeOverlapped();

            readOverlapped.EventHandle = m_ReadEvent.SafeWaitHandle.DangerousGetHandle();

            // WriteFile
            bool writePending = false;

            m_WriteEvent.Reset();
            NativeOverlapped writeOverlapped = new NativeOverlapped();

            m_ReadByteAvailable         = false;
            writeOverlapped.EventHandle = m_WriteEvent.SafeWaitHandle.DangerousGetHandle();

            // SEt up the types of serial events we want to see.
            UnsafeNativeMethods.SetCommMask(m_ComPortHandle, maskRead);

            bool result;

            NativeMethods.SerialEventMask commEventMask = 0;

            bool running = true;
            uint bytes;
            List <WaitHandle> handles = new List <WaitHandle>(10);

            while (running)
            {
                handles.Clear();
                handles.Add(m_StopRunning);
                handles.Add(m_WriteClearEvent);

#if PL2303_WORKAROUNDS
                // - - - - - - - - - - - - - - - - - - - - - - - - -
                // PROLIFIC PL23030 WORKAROUND
                // - - - - - - - - - - - - - - - - - - - - - - - - -
                // If we have a read pending, we don't request events
                // for reading data. To do so will result in errors.
                // Have no idea why.
                if (readPending)
                {
                    UnsafeNativeMethods.SetCommMask(m_ComPortHandle, maskReadPending);
                }
                else
                {
                    UnsafeNativeMethods.SetCommMask(m_ComPortHandle, maskRead);

                    // While the comm event mask was set to ignore read events, data could have been written
                    // to the input queue. Check for that and if there are bytes waiting or EOF was received,
                    // set the appropriate flags.
                    uint bytesInQueue;
                    bool eofReceived;
                    if (GetReceiveStats(out bytesInQueue, out eofReceived) && (bytesInQueue > 0 || eofReceived))
                    {
                        // Tell DoReadEvent that there is data pending
                        m_ReadByteAvailable = true;
                        m_ReadByteEof      |= eofReceived;
                    }
                }
#else
                UnsafeNativeMethods.SetCommMask(m_ComPortHandle, maskRead);
#endif

                // commEventMask is on the stack, and is therefore fixed
                if (!serialCommPending)
                {
                    serialCommPending = DoWaitCommEvent(out commEventMask, ref serialCommOverlapped);
                }
                if (serialCommPending)
                {
                    handles.Add(m_SerialCommEvent);
                }

                if (!readPending)
                {
                    if (!m_Buffer.Serial.ReadBufferNotFull.WaitOne(0))
                    {
                        SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "{0}: SerialThread: Read Buffer Full", m_Name);
                        handles.Add(m_Buffer.Serial.ReadBufferNotFull);
                    }
                    else
                    {
                        readPending = DoReadEvent(ref readOverlapped);
                    }
                }
                if (readPending)
                {
                    handles.Add(m_ReadEvent);
                }

                if (!writePending)
                {
                    if (!m_Buffer.Serial.WriteBufferNotEmpty.WaitOne(0))
                    {
                        handles.Add(m_Buffer.Serial.WriteBufferNotEmpty);
                    }
                    else
                    {
                        writePending = DoWriteEvent(ref writeOverlapped);
                    }
                }
                if (writePending)
                {
                    handles.Add(m_WriteEvent);
                }

                // We wait up to 100ms, in case we're not actually pending on anything. Normally, we should always be
                // pending on a Comm event. Just in case this is not so (and is a theoretical possibility), we will
                // slip out of this WaitAny() after 100ms and then restart the loop, effectively polling every 100ms in
                // worst case.
                WaitHandle[] whandles = handles.ToArray();
                int          ev       = WaitHandle.WaitAny(whandles, 100);

                if (ev != WaitHandle.WaitTimeout)
                {
                    if (whandles[ev] == m_StopRunning)
                    {
                        SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "{0}: SerialThread: Thread closing", m_Name);
                        result = UnsafeNativeMethods.CancelIo(m_ComPortHandle);
                        if (!result)
                        {
                            int win32Error = Marshal.GetLastWin32Error();
                            int hr         = Marshal.GetHRForLastWin32Error();
                            SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Warning, 0,
                                                            "{0}: SerialThread: CancelIo error {1}", m_Name, win32Error);
                            Marshal.ThrowExceptionForHR(hr);
                        }
                        running = false;
                    }
                    else if (whandles[ev] == m_SerialCommEvent)
                    {
                        result = UnsafeNativeMethods.GetOverlappedResult(m_ComPortHandle, ref serialCommOverlapped, out bytes, true);
                        if (!result)
                        {
                            int win32Error = Marshal.GetLastWin32Error();
                            int hr         = Marshal.GetHRForLastWin32Error();
                            SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Error, 0,
                                                            "{0}: SerialThread: Overlapped WaitCommEvent() error {1}", m_Name, win32Error);
                            Marshal.ThrowExceptionForHR(hr);
                        }
                        ProcessWaitCommEvent(commEventMask);
                        serialCommPending = false;
                    }
                    else if (whandles[ev] == m_ReadEvent)
                    {
                        result = UnsafeNativeMethods.GetOverlappedResult(m_ComPortHandle, ref readOverlapped, out bytes, true);
                        if (!result)
                        {
                            int win32Error = Marshal.GetLastWin32Error();
                            int hr         = Marshal.GetHRForLastWin32Error();
                            // Should never get ERROR_IO_PENDING, as this method is only called when the event is triggered.
                            if (win32Error != WinError.ERROR_OPERATION_ABORTED || bytes > 0)
                            {
                                SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Error, 0,
                                                                "{0}: SerialThread: Overlapped ReadFile() error {1} bytes {2}", m_Name, win32Error, bytes);
                                Marshal.ThrowExceptionForHR(hr);
                            }
                            else
                            {
                                // ERROR_OPERATION_ABORTED may be caused by CancelIo or PurgeComm
                                if (SerialTrace.TraceSer.Switch.ShouldTrace(System.Diagnostics.TraceEventType.Verbose))
                                {
                                    SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0,
                                                                    "{0}: SerialThread: Overlapped ReadFile() error {1} bytes {2}", m_Name, win32Error, bytes);
                                }
                            }
                        }
                        else
                        {
                            ProcessReadEvent(bytes);
                        }
                        readPending = false;
                    }
                    else if (whandles[ev] == m_Buffer.Serial.ReadBufferNotFull)
                    {
                        // The read buffer is no longer full. We just loop back to the beginning to test if we
                        // should read or not.
                    }
                    else if (whandles[ev] == m_WriteEvent)
                    {
                        result = UnsafeNativeMethods.GetOverlappedResult(m_ComPortHandle, ref writeOverlapped, out bytes, true);
                        if (!result)
                        {
                            int win32Error = Marshal.GetLastWin32Error();
                            int hr         = Marshal.GetHRForLastWin32Error();
                            // Should never get ERROR_IO_PENDING, as this method is only called when the event is triggered.
                            if (win32Error != WinError.ERROR_OPERATION_ABORTED || bytes > 0)
                            {
                                SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Error, 0,
                                                                "{0}: SerialThread: Overlapped WriteFile() error {1} bytes {2}", m_Name, win32Error, bytes);
                                Marshal.ThrowExceptionForHR(hr);
                            }
                            else
                            {
                                // ERROR_OPERATION_ABORTED may be caused by CancelIo or PurgeComm
                                if (SerialTrace.TraceSer.Switch.ShouldTrace(System.Diagnostics.TraceEventType.Verbose))
                                {
                                    SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0,
                                                                    "{0}: SerialThread: Overlapped WriteFile() error {1} bytes {2}", m_Name, win32Error, bytes);
                                }
                            }
                        }
                        else
                        {
                            ProcessWriteEvent(bytes);
                        }
                        writePending = false;
                    }
                    else if (whandles[ev] == m_Buffer.Serial.WriteBufferNotEmpty)
                    {
                        // The write buffer is no longer empty. We just loop back to the beginning to test if we
                        // should write or not.
                    }
                    else if (whandles[ev] == m_WriteClearEvent)
                    {
                        if (writePending)
                        {
                            SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "{0}: SerialThread: PurgeComm() write pending", m_Name);
                            m_PurgePending = true;
                            result         = UnsafeNativeMethods.PurgeComm(m_ComPortHandle,
                                                                           NativeMethods.PurgeFlags.PURGE_TXABORT | NativeMethods.PurgeFlags.PURGE_TXCLEAR);
                            if (!result)
                            {
                                int win32Error = Marshal.GetLastWin32Error();
                                int hr         = Marshal.GetHRForLastWin32Error();
                                if (win32Error != WinError.ERROR_OPERATION_ABORTED)
                                {
                                    SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Error, 0,
                                                                    "{0}: SerialThread: PurgeComm() error {1}", m_Name, win32Error);
                                    Marshal.ThrowExceptionForHR(hr);
                                }
                                else
                                {
                                    if (SerialTrace.TraceSer.Switch.ShouldTrace(System.Diagnostics.TraceEventType.Verbose))
                                    {
                                        SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0,
                                                                        "{0}: SerialThread: PurgeComm() error {1}", m_Name, win32Error);
                                    }
                                }
                            }
                        }
                        else
                        {
                            lock (m_Buffer.WriteLock) {
                                SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "{0}: SerialThread: Purged", m_Name);
                                m_Buffer.Serial.Purge();
                                m_WriteClearDoneEvent.Set();
                            }
                        }
                    }
                }

#if STRESSTEST
                SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "{0}: STRESSTEST SerialThread: Stress Test Delay of 1000ms", m_Name);
                System.Threading.Thread.Sleep(1000);
                NativeMethods.ComStatErrors commStateErrors = new NativeMethods.ComStatErrors();
                NativeMethods.COMSTAT       commStat        = new NativeMethods.COMSTAT();
                result = UnsafeNativeMethods.ClearCommError(m_ComPortHandle, out commStateErrors, out commStat);
                if (result)
                {
                    SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Information, 0,
                                                    "{0}: STRESSTEST SerialThread: ClearCommError errors={1}", m_Name, commStateErrors);
                    SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Information, 0,
                                                    "{0}: STRESSTEST SerialThread: ClearCommError stats flags={1}, InQueue={2}, OutQueue={3}", m_Name, commStat.Flags, commStat.cbInQue, commStat.cbOutQue);
                }
                else
                {
                    SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Warning, 0,
                                                    "{0}: STRESSTEST SerialThread: ClearCommError error: {1}", m_Name, Marshal.GetLastWin32Error());
                }
#endif
            }
        }
Exemple #10
0
        private IntPtr CreateWindow(NativeMethods.BitmapHandle hBitmap, int width, int height, bool topMost)
        {
            if (_defWndProc == null)
            {
                _defWndProc = new MS.Win32.NativeMethods.WndProc(UnsafeNativeMethods.DefWindowProc);
            }

            MS.Win32.NativeMethods.WNDCLASSEX_D wndClass = new MS.Win32.NativeMethods.WNDCLASSEX_D();
            wndClass.cbSize        = Marshal.SizeOf(typeof(MS.Win32.NativeMethods.WNDCLASSEX_D));
            wndClass.style         = 3; /* CS_HREDRAW | CS_VREDRAW */
            wndClass.lpfnWndProc   = null;
            wndClass.hInstance     = _hInstance;
            wndClass.hCursor       = IntPtr.Zero;
            wndClass.lpszClassName = CLASSNAME;
            wndClass.lpszMenuName  = string.Empty;
            wndClass.lpfnWndProc   = _defWndProc;

            // We chose to ignore re-registration errors in RegisterClassEx on the off chance that the user
            // wants to open multiple splash screens.
            _wndClass = MS.Win32.UnsafeNativeMethods.IntRegisterClassEx(wndClass);
            if (_wndClass == 0)
            {
                if (Marshal.GetLastWin32Error() != 0x582) /* class already registered */
                {
                    throw new Win32Exception();
                }
            }

            int screenWidth  = MS.Win32.UnsafeNativeMethods.GetSystemMetrics(SM.CXSCREEN);
            int screenHeight = MS.Win32.UnsafeNativeMethods.GetSystemMetrics(SM.CYSCREEN);
            int x            = (screenWidth - width) / 2;
            int y            = (screenHeight - height) / 2;

            HandleRef nullHandle        = new HandleRef(null, IntPtr.Zero);
            int       windowCreateFlags =
                (int)NativeMethods.WS_EX_WINDOWEDGE |
                NativeMethods.WS_EX_TOOLWINDOW |
                NativeMethods.WS_EX_LAYERED |
                (topMost ? NativeMethods.WS_EX_TOPMOST : 0);

            // CreateWindowEx will either succeed or throw
            IntPtr hWnd = MS.Win32.UnsafeNativeMethods.CreateWindowEx(
                windowCreateFlags,
                CLASSNAME, SR.Get(SRID.SplashScreenIsLoading),
                MS.Win32.NativeMethods.WS_POPUP | MS.Win32.NativeMethods.WS_VISIBLE,
                x, y, width, height,
                nullHandle, nullHandle, new HandleRef(null, _hInstance), IntPtr.Zero);

            // Display the image on the window
            IntPtr hScreenDC  = UnsafeNativeMethods.GetDC(new HandleRef());
            IntPtr memDC      = UnsafeNativeMethods.CreateCompatibleDC(new HandleRef(null, hScreenDC));
            IntPtr hOldBitmap = UnsafeNativeMethods.SelectObject(new HandleRef(null, memDC), hBitmap.MakeHandleRef(null).Handle);

            NativeMethods.POINT newSize        = new NativeMethods.POINT(width, height);
            NativeMethods.POINT newLocation    = new NativeMethods.POINT(x, y);
            NativeMethods.POINT sourceLocation = new NativeMethods.POINT(0, 0);
            _blendFunc                     = new NativeMethods.BLENDFUNCTION();
            _blendFunc.BlendOp             = NativeMethods.AC_SRC_OVER;
            _blendFunc.BlendFlags          = 0;
            _blendFunc.SourceConstantAlpha = 255;
            _blendFunc.AlphaFormat         = 1; /*AC_SRC_ALPHA*/

            bool result = UnsafeNativeMethods.UpdateLayeredWindow(hWnd, hScreenDC, newLocation, newSize,
                                                                  memDC, sourceLocation, 0, ref _blendFunc, NativeMethods.ULW_ALPHA);

            UnsafeNativeMethods.SelectObject(new HandleRef(null, memDC), hOldBitmap);
            UnsafeNativeMethods.ReleaseDC(new HandleRef(), new HandleRef(null, memDC));
            UnsafeNativeMethods.ReleaseDC(new HandleRef(), new HandleRef(null, hScreenDC));

            if (result == false)
            {
                UnsafeNativeMethods.HRESULT.Check(Marshal.GetHRForLastWin32Error());
            }

            return(hWnd);
        }
Exemple #11
0
        private static MetadataReaderProvider GetMetadataReaderProvider(Module module)
        {
            // TODO can the PEReader be pointed at a memory location instead of reading from disk?
            var dllFileContent = File.ReadAllBytes(module.FullyQualifiedName).ToImmutableArray();
            var reader         = new PEReader(dllFileContent);

            TraceSourceLink("probing for embedded symbols: " + module.FullyQualifiedName);
            if (!reader.HasMetadata)
            {
                return(null);
            }

            // https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/tests/PortableExecutable/PEReaderTests.cs
            var embeddedPdb = reader.ReadDebugDirectory().FirstOrDefault(x => x.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);

            if (!embeddedPdb.Equals(default(DebugDirectoryEntry)))
            {
                TraceSourceLink("found embedded symbols: " + module.FullyQualifiedName);
                return(reader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedPdb));
            }

            var sbFile = new StringBuilder(1024);
            var sbPath = new StringBuilder(1024);

            if (SymGetSymbolFile(ProcessHandle, null, module.FullyQualifiedName, SymbolFileType.sfPdb, sbFile, sbFile.Capacity, sbPath, sbPath.Capacity))
            {
                // todo determine if pdb is not portable early
                // https://github.com/tmat/corefx/blob/f808e59c3ef93e141b019d661a4443a0e19c7442/src/System.Diagnostics.StackTrace/src/System/Diagnostics/StackTraceSymbols.CoreCLR.cs#L164
                TraceSourceLink("probing for portable PDB symbols: " + sbFile);
                var pdbFileContent = File.ReadAllBytes(sbFile.ToString()).ToImmutableArray();
                return(MetadataReaderProvider.FromPortablePdbImage(pdbFileContent));
            }
            else
            {
                TraceSourceLink("probing for portable PDB symbols failed: " + Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
            }

            return(null);
        }
Exemple #12
0
        public static string GetTarget(string path)
        {
            SymbolicLinkReparseData reparseDataBuffer;

            using (SafeFileHandle fileHandle = GetFileHandle(path))
            {
                if (fileHandle.IsInvalid)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
#if NET35
                int outBufferSize = Marshal.SizeOf(typeof(SymbolicLinkReparseData));
#else
                int outBufferSize = Marshal.SizeOf <SymbolicLinkReparseData>();
#endif
                IntPtr outBuffer = IntPtr.Zero;
                try
                {
                    outBuffer = Marshal.AllocHGlobal(outBufferSize);
                    bool success = DeviceIoControl(
                        fileHandle.DangerousGetHandle(), ioctlCommandGetReparsePoint, IntPtr.Zero, 0,
                        outBuffer, outBufferSize, out int bytesReturned, IntPtr.Zero);

                    fileHandle.Dispose();

                    if (!success)
                    {
                        if (((uint)Marshal.GetHRForLastWin32Error()) == pathNotAReparsePointError)
                        {
                            return(null);
                        }
                        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                    }

#if NET35
                    reparseDataBuffer = (SymbolicLinkReparseData)Marshal.PtrToStructure(
                        outBuffer, typeof(SymbolicLinkReparseData));
#else
                    reparseDataBuffer = Marshal.PtrToStructure <SymbolicLinkReparseData>(outBuffer);
#endif
                }
                finally
                {
                    Marshal.FreeHGlobal(outBuffer);
                }
            }
            if (reparseDataBuffer.ReparseTag != symLinkTag)
            {
                return(null);
            }

            string target = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer,
                                                       reparseDataBuffer.PrintNameOffset, reparseDataBuffer.PrintNameLength);

            if ((reparseDataBuffer.Flags & symlinkReparsePointFlagRelative) == symlinkReparsePointFlagRelative)
            {
                string basePath     = Path.GetDirectoryName(path.TrimEnd(Path.DirectorySeparatorChar));
                string combinedPath = Path.Combine(basePath, target);
                target = Path.GetFullPath(combinedPath);
            }

            return(target);
        }
Exemple #13
0
        /// <summary>
        ///     Add commands to a shortcut menu.
        /// </summary>
        /// <param name="hMenu">A handle to the shortcut menu.</param>
        /// <param name="iMenu">
        ///     The zero-based position at which to insert the first new menu item.
        /// </param>
        /// <param name="idCmdFirst">
        ///     The minimum value that the handler can specify for a menu item ID.
        /// </param>
        /// <param name="idCmdLast">
        ///     The maximum value that the handler can specify for a menu item ID.
        /// </param>
        /// <param name="uFlags">
        ///     Optional flags that specify how the shortcut menu can be changed.
        /// </param>
        /// <returns>
        ///     If successful, returns an HRESULT value that has its severity value set
        ///     to SEVERITY_SUCCESS and its code value set to the offset of the largest
        ///     command identifier that was assigned, plus one.
        /// </returns>
        public int QueryContextMenu(
            IntPtr hMenu,
            uint iMenu,
            uint idCmdFirst,
            uint idCmdLast,
            uint uFlags)
        {
            // If uFlags include CMF_DEFAULTONLY then we should not do anything.
            if (((uint)CMF.CMF_DEFAULTONLY & uFlags) != 0)
            {
                return(WinError.MAKE_HRESULT(WinError.SEVERITY_SUCCESS, 0, 0));
            }

            // Add a separator.
            var sep = new MENUITEMINFO();

            sep.cbSize = (uint)Marshal.SizeOf(sep);
            sep.fMask  = MIIM.MIIM_TYPE;
            sep.fType  = MFT.MFT_SEPARATOR;
            if (!NativeMethods.InsertMenuItem(hMenu, 0, true, ref sep))
            {
                return(Marshal.GetHRForLastWin32Error());
            }

            // Register item 0: Submenu
            var hSubMenu = NativeMethods.CreatePopupMenu();
            var item     = menuItems[0];

            RegisterMenuItem(0, idCmdFirst, item.Text, true, item.Bitmap, hSubMenu, 1, hMenu);

            // Register item 1: RunDefault
            item = menuItems[1];
            RegisterMenuItem(1, idCmdFirst, item.Text, true, item.Bitmap, IntPtr.Zero, 0, hSubMenu);

            // Add a separator.
            sep        = new MENUITEMINFO();
            sep.cbSize = (uint)Marshal.SizeOf(sep);
            sep.fMask  = MIIM.MIIM_TYPE;
            sep.fType  = MFT.MFT_SEPARATOR;
            NativeMethods.InsertMenuItem(hSubMenu, 1, true, ref sep);

            // Register item 2 (Submenu->ManageApp).
            item = menuItems[2];
            RegisterMenuItem(2, idCmdFirst, item.Text, true, item.Bitmap, IntPtr.Zero, 2, hSubMenu);

            // Register item 3 (Submenu->ManageAll).
            item = menuItems[3];
            RegisterMenuItem(3, idCmdFirst, item.Text, true, item.Bitmap, IntPtr.Zero, 3, hSubMenu);

            //Register user-defined profiles.
            //We should count down to 4.
            for (var i = menuItems.Count - 1; i > 3; i--)
            {
                item = menuItems[i];
                if (item.ShowInMainMenu == true)
                {
                    RegisterMenuItem((uint)i, idCmdFirst, item.Text, item.Enabled, item.Bitmap, IntPtr.Zero, 1, hMenu);
                }
                else
                {
                    RegisterMenuItem((uint)i, idCmdFirst, item.Text, item.Enabled, item.Bitmap, IntPtr.Zero, 0, hSubMenu);
                }
            }

            // Add a separator.
            sep        = new MENUITEMINFO();
            sep.cbSize = (uint)Marshal.SizeOf(sep);
            sep.fMask  = MIIM.MIIM_TYPE;
            sep.fType  = MFT.MFT_SEPARATOR;
            NativeMethods.InsertMenuItem(hSubMenu,
                                         (uint)menuItems.FindAll(t => t.ShowInMainMenu != true).Count - 4,
                                         true,
                                         ref sep);

            // Return an HRESULT value with the severity set to SEVERITY_SUCCESS.
            // Set the code value to the total number of items added.
            return(WinError.MAKE_HRESULT(WinError.SEVERITY_SUCCESS, 0, 3 + (uint)menuItems.Count));
        }
Exemple #14
0
        private static ICertificatePal FromBlobOrFile(byte[] rawData, string fileName, string password, X509KeyStorageFlags keyStorageFlags)
        {
            Debug.Assert(rawData != null || fileName != null);

            bool loadFromFile = (fileName != null);

            PfxCertStoreFlags pfxCertStoreFlags = MapKeyStorageFlags(keyStorageFlags);
            bool persistKeySet = (0 != (keyStorageFlags & X509KeyStorageFlags.PersistKeySet));

            CertEncodingType      msgAndCertEncodingType;
            ContentType           contentType;
            FormatType            formatType;
            SafeCertStoreHandle   hCertStore   = null;
            SafeCryptMsgHandle    hCryptMsg    = null;
            SafeCertContextHandle pCertContext = null;

            try
            {
                unsafe
                {
                    fixed(byte *pRawData = rawData)
                    {
                        fixed(char *pFileName = fileName)
                        {
                            CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(loadFromFile ? 0 : rawData.Length, pRawData);

                            CertQueryObjectType objectType = loadFromFile ? CertQueryObjectType.CERT_QUERY_OBJECT_FILE : CertQueryObjectType.CERT_QUERY_OBJECT_BLOB;
                            void *pvObject = loadFromFile ? (void *)pFileName : (void *)&certBlob;

                            bool success = Interop.crypt32.CryptQueryObject(
                                objectType,
                                pvObject,
                                X509ExpectedContentTypeFlags,
                                X509ExpectedFormatTypeFlags,
                                0,
                                out msgAndCertEncodingType,
                                out contentType,
                                out formatType,
                                out hCertStore,
                                out hCryptMsg,
                                out pCertContext
                                );

                            if (!success)
                            {
                                int hr = Marshal.GetHRForLastWin32Error();
                                throw hr.ToCryptographicException();
                            }
                        }
                    }

                    if (contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED || contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED)
                    {
                        pCertContext = GetSignerInPKCS7Store(hCertStore, hCryptMsg);
                    }
                    else if (contentType == ContentType.CERT_QUERY_CONTENT_PFX)
                    {
                        if (loadFromFile)
                        {
                            rawData = File.ReadAllBytes(fileName);
                        }
                        pCertContext = FilterPFXStore(rawData, password, pfxCertStoreFlags);
                    }

                    CertificatePal pal = new CertificatePal(pCertContext, deleteKeyContainer: !persistKeySet);

                    pCertContext = null;
                    return(pal);
                }
            }
            finally
            {
                if (hCertStore != null)
                {
                    hCertStore.Dispose();
                }
                if (hCryptMsg != null)
                {
                    hCryptMsg.Dispose();
                }
                if (pCertContext != null)
                {
                    pCertContext.Dispose();
                }
            }
        }
Exemple #15
0
        public bool Install(string path, out string errorMessage)
        {
            var manager = NativeMethods.OpenSCManager(null, null,
                                                      ServiceControlManagerAccessRights.SC_MANAGER_ALL_ACCESS);

            if (manager == IntPtr.Zero)
            {
                errorMessage = "OpenSCManager returned zero.";
                return(false);
            }

            var service = NativeMethods.CreateService(manager, id, id,
                                                      ServiceAccessRights.SERVICE_ALL_ACCESS,
                                                      ServiceType.SERVICE_KERNEL_DRIVER, StartType.SERVICE_DEMAND_START,
                                                      ErrorControl.SERVICE_ERROR_NORMAL, path, null, null, null, null,
                                                      null);

            if (service == IntPtr.Zero)
            {
                if (Marshal.GetHRForLastWin32Error() == ERROR_SERVICE_EXISTS)
                {
                    errorMessage = "Service already exists";
                    return(false);
                }
                else
                {
                    errorMessage = "CreateService returned the error: " +
                                   Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message;
                    NativeMethods.CloseServiceHandle(manager);
                    return(false);
                }
            }

            if (!NativeMethods.StartService(service, 0, null))
            {
                if (Marshal.GetHRForLastWin32Error() != ERROR_SERVICE_ALREADY_RUNNING)
                {
                    errorMessage = "StartService returned the error: " +
                                   Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message;
                    NativeMethods.CloseServiceHandle(service);
                    NativeMethods.CloseServiceHandle(manager);
                    return(false);
                }
            }

            NativeMethods.CloseServiceHandle(service);
            NativeMethods.CloseServiceHandle(manager);

#if !NETSTANDARD2_0
            try {
                // restrict the driver access to system (SY) and builtin admins (BA)
                // TODO: replace with a call to IoCreateDeviceSecure in the driver
                var fileSecurity = System.IO.File.GetAccessControl(@"\\.\" + id);
                fileSecurity.SetSecurityDescriptorSddlForm(
                    "O:BAG:SYD:(A;;FA;;;SY)(A;;FA;;;BA)");
                System.IO.File.SetAccessControl(@"\\.\" + id, fileSecurity);
            } catch { }
#endif
            errorMessage = null;
            return(true);
        }
        /// <summary>
        /// Check if we should ReadFile() and process the data if serial data is immediately.
        /// available.
        /// </summary>
        /// <remarks>
        /// This function should be called if there is no existing pending read operation. It
        /// will check if there is data to read (indicated by the variable m_ReadByteAvailable,
        /// which is set by ProcessWaitCommEvent()) and then issue a ReadFile(). If the result
        /// indicates that asynchronous I/O is happening, <b>true</b> is returned. Else this
        /// function automatically calls ProcessReadEvent() with the number of bytes read. If
        /// an asynchronous operation is pending, then you should wait on the event in the
        /// overlapped structure not call this function until GetOverlappedResult() has
        /// been called.
        /// </remarks>
        /// <param name="overlap">The overlap structure to use for reading.</param>
        /// <returns>If the operation is pending or not.</returns>
        private bool DoReadEvent(ref NativeOverlapped overlap)
        {
            // If WaitCommEvent() hasn't been called, there's no data
            if (!m_ReadByteAvailable)
            {
                return(false);
            }

            // Read Buffer is full, so can't write into it.
            if (!m_Buffer.Serial.ReadBufferNotFull.WaitOne(0))
            {
                return(false);
            }

            // As C# can't convert an offset in the array to a pointer, we have to do
            // our own marshalling with (IntPtr)ReadBufferOffsetEnd that is the address
            // at the end of the read buffer.
            IntPtr bufPtr;
            uint   bufLen;

            lock (m_Buffer.ReadLock) {
                bufPtr = m_Buffer.Serial.ReadBufferOffsetEnd;
                bufLen = (uint)m_Buffer.Serial.ReadBuffer.WriteLength;
            }

            uint bufRead;
            bool result = UnsafeNativeMethods.ReadFile(m_ComPortHandle, bufPtr, bufLen, out bufRead, ref overlap);
            int  w32err = Marshal.GetLastWin32Error();
            int  hr     = Marshal.GetHRForLastWin32Error();

            if (SerialTrace.TraceSer.Switch.ShouldTrace(System.Diagnostics.TraceEventType.Verbose))
            {
                SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0,
                                                "{0}: SerialThread: DoReadEvent: ReadFile({1}, {2}, {3}) == {4}", m_Name,
                                                m_ComPortHandle.DangerousGetHandle(), bufPtr, bufLen, result);
            }
            if (!result)
            {
                if (w32err == WinError.ERROR_OPERATION_ABORTED)
                {
                    SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Information, 0,
                                                    "{0}: SerialThread: DoReadEvent: ReadFile() error {1}", m_Name, w32err);
                    return(false);
                }
                if (w32err != WinError.ERROR_IO_PENDING)
                {
                    SerialTrace.TraceSer.TraceEvent(System.Diagnostics.TraceEventType.Error, 0,
                                                    "{0}: SerialThread: DoReadEvent: ReadFile() error {1}", m_Name, w32err);
                    // In case an unexpected error occurs here, we kill the thread and indicate an error.
                    // One reason for this happening is a device error, or the device is removed from the
                    // system.
                    Marshal.ThrowExceptionForHR(hr);
                }
            }
            else
            {
                // MS Documentation for ReadFile() says that the 'bufRead' parameter should be NULL.
                // However, in the case that the COMMTIMEOUTS is set up so that no wait is required
                // (see COMMTIMEOUTS in Win32 API), this function will actually not perform an
                // asynchronous I/O operation and return the number of bytes copied in bufRead.
                ProcessReadEvent(bufRead);
            }
            return(!result);
        }
        Create(string fileName, MapProtection protection,
               long maxSize, String name)
        {
            MemoryMappedFile map = new MemoryMappedFile();

            if (!map.Is64bit && maxSize > uint.MaxValue)
            {
                throw new ConstraintException("32bit systems support max size of 4gb.");
            }

            // open file first
            IntPtr hFile = INVALID_HANDLE_VALUE;

            if (!string.IsNullOrEmpty(fileName))
            {
                if (maxSize == 0)
                {
                    if (!File.Exists(fileName))
                    {
                        throw new Exception(string.Format("Winterdom.IO.FileMap.MemoryMappedFile.Create - \"{0}\" does not exist ==> Unable to map entire file", fileName));
                    }

                    FileInfo backingFileInfo = new FileInfo(fileName);
                    maxSize = backingFileInfo.Length;

                    if (maxSize == 0)
                    {
                        throw new Exception(string.Format("Winterdom.IO.FileMap.MemoryMappedFile.Create - \"{0}\" is zero bytes ==> Unable to map entire file", fileName));
                    }
                }

                // determine file access needed
                // we'll always need generic read access
                int desiredAccess = GENERIC_READ;
                if ((protection == MapProtection.PageReadWrite) ||
                    (protection == MapProtection.PageWriteCopy))
                {
                    desiredAccess |= GENERIC_WRITE;
                }

                // open or create the file
                // if it doesn't exist, it gets created
                hFile = Win32MapApis.CreateFile(
                    fileName, desiredAccess, 0,
                    IntPtr.Zero, OPEN_ALWAYS, 0, IntPtr.Zero
                    );
                if (hFile == INVALID_HANDLE_VALUE)
                {
                    throw new FileMapIOException(Marshal.GetHRForLastWin32Error());
                }

                map._fileName = fileName;
            }

            map._hMap = Win32MapApis.CreateFileMapping(
                hFile, IntPtr.Zero, (int)protection,
                (int)((maxSize >> 32) & 0xFFFFFFFF),
                (int)(maxSize & 0xFFFFFFFF), name
                );

            // close file handle, we don't need it
            if (hFile != INVALID_HANDLE_VALUE)
            {
                Win32MapApis.CloseHandle(hFile);
            }
            if (map._hMap == NULL_HANDLE)
            {
                throw new FileMapIOException(Marshal.GetHRForLastWin32Error());
            }

            map._protection = protection;
            map._maxSize    = maxSize;

            return(map);
        }
        protected override void CreateDeviceDependentResources()
        {
            _dxgiFactory = CreateDxgiFactory();
            _dxgiAdapter = GetDxgiAdapter();
            _d3dDevice   = CreateD3DDevice();
            StartInfoPump();
            _commandQueue = CreateCommandQueue();

            CreateDescriptorHeaps();

            for (int i = 0; i < FrameCount; i++)
            {
                _commandAllocators[i] = CreateCommandAllocator();
            }

            _fence       = CreateFence();
            _fenceValues = CreateFenceValues();
            _fenceEvent  = CreateFenceEvent();

            _rootSignature        = CreateRootSignature();
            _pipelineState        = CreatePipelineState();
            _graphicsCommandLists = CreateGraphicsCommandLists();

            SilkMarshal.ThrowHResult(CommandAllocator->Reset());
            SilkMarshal.ThrowHResult(GraphicsCommandList->Reset(CommandAllocator, PipelineState));

            CreateAssets();

            ID3D12CommandAllocator *CreateCommandAllocator()
            {
                ID3D12CommandAllocator *commandAllocator;

                var iid = ID3D12CommandAllocator.Guid;

                SilkMarshal.ThrowHResult
                (
                    D3DDevice->CreateCommandAllocator
                        (CommandListType.CommandListTypeDirect, &iid, (void **)&commandAllocator)
                );

                return(commandAllocator);
            }

            ID3D12CommandQueue *CreateCommandQueue()
            {
                var queueDesc = new CommandQueueDesc();

                ID3D12CommandQueue *commandQueue;

                var iid = ID3D12CommandQueue.Guid;

                SilkMarshal.ThrowHResult(D3DDevice->CreateCommandQueue(&queueDesc, &iid, (void **)&commandQueue));

                return(commandQueue);
            }

            ID3D12Device *CreateD3DDevice()
            {
                ID3D12Device *d3dDevice;

                var iid = ID3D12Device.Guid;

                SilkMarshal.ThrowHResult
                (
                    D3D12.CreateDevice
                        ((IUnknown *)_dxgiAdapter, D3DFeatureLevel.D3DFeatureLevel110, &iid, (void **)&d3dDevice)
                );

                return(d3dDevice);
            }

            IDXGIFactory4 *CreateDxgiFactory()
            {
                var dxgiFactoryFlags = TryEnableDebugLayer() ? 0x01 : 0u;

                IDXGIFactory4 *dxgiFactory;

                var iid = IDXGIFactory4.Guid;

                SilkMarshal.ThrowHResult(Dxgi.CreateDXGIFactory2(dxgiFactoryFlags, &iid, (void **)&dxgiFactory));

                return(dxgiFactory);
            }

            ID3D12Fence *CreateFence()
            {
                ID3D12Fence *fence;

                var iid = ID3D12Fence.Guid;

                SilkMarshal.ThrowHResult
                    (D3DDevice->CreateFence(InitialValue: 0, FenceFlags.FenceFlagNone, &iid, (void **)&fence));

                return(fence);
            }

            IntPtr CreateFenceEvent()
            {
                var fenceEvent = SilkMarshal.CreateWindowsEvent(null, false, false, null);

                if (fenceEvent == IntPtr.Zero)
                {
                    var hr = Marshal.GetHRForLastWin32Error();
                    Marshal.ThrowExceptionForHR(hr);
                }

                return(fenceEvent);
            }

            ulong[] CreateFenceValues()
            {
                var fenceValues = new ulong[FrameCount];

                fenceValues[0] = 1;
                return(fenceValues);
            }

            ID3D12GraphicsCommandList *[] CreateGraphicsCommandLists()
            {
                var graphicsCommandLists = new ID3D12GraphicsCommandList *[FrameCount];

                for (uint i = 0u; i < FrameCount; i++)
                {
                    ID3D12GraphicsCommandList *graphicsCommandList;

                    var iid = ID3D12GraphicsCommandList.Guid;
                    SilkMarshal.ThrowHResult
                    (
                        D3DDevice->CreateCommandList
                        (
                            nodeMask: 0, CommandListType.CommandListTypeDirect, _commandAllocators[i], PipelineState,
                            &iid, (void **)&graphicsCommandList
                        )
                    );

                    SilkMarshal.ThrowHResult(graphicsCommandList->Close());
                    graphicsCommandLists[i] = graphicsCommandList;
                }

                return(graphicsCommandLists);
            }

            IDXGIAdapter1 *GetDxgiAdapter()
            {
                if (UseWarpDevice)
                {
                    IDXGIAdapter1 *adapter;

                    var iid = IDXGIAdapter.Guid;
                    SilkMarshal.ThrowHResult(_dxgiFactory->EnumWarpAdapter(&iid, (void **)&adapter));

                    return(adapter);
                }
                else
                {
                    return(GetHardwareAdapter((IDXGIFactory1 *)_dxgiFactory));
                }
            }

            bool TryEnableDebugLayer()
            {
#if DEBUG
                // Enable the debug layer (requires the Graphics Tools "optional feature").
                // NOTE: Enabling the debug layer after device creation will invalidate the active device.

                using ComPtr <ID3D12Debug> debugController = null;
                var iid = ID3D12Debug.Guid;
                var hr  = D3D12.GetDebugInterface(&iid, (void **)&debugController);

                if (HResult.IndicatesSuccess(hr))
                {
                    debugController.Get().EnableDebugLayer();
                    Log.LogInformation("Debug layer enabled");
                    return(_debug = true);
                }
                else
                {
                    Log.LogWarning
                    (
                        Marshal.GetExceptionForHR(hr),
                        $"Failed to enable debug layer, failed with result {hr} (0x{hr:x8})"
                    );
                }
#endif

                return(false);
            }

            void StartInfoPump()
            {
#if DEBUG
                if (!_debug)
                {
                    Log.LogInformation("Skipped creation of info pump due to the debug layer not being enabled.");
                    return;
                }

                var iid = ID3D12InfoQueue.Guid;
                fixed(ID3D12InfoQueue ** @out = &_infoQueue)
                {
                    SilkMarshal.ThrowHResult(D3DDevice->QueryInterface(&iid, (void **)@out));
                }

                _infoPumpCancellationToken = new();
                _infoPump = Task.Run
                            (
                    () =>
                {
                    Log.LogInformation("Info queue pump started");
                    while (!_infoPumpCancellationToken.Token.IsCancellationRequested)
                    {
                        var numMessages = _infoQueue->GetNumStoredMessages();
                        if (numMessages == 0)
                        {
                            continue;
                        }

                        for (var i = 0ul; i < numMessages; i++)
                        {
                            nuint msgByteLength;
                            SilkMarshal.ThrowHResult(_infoQueue->GetMessageA(i, null, &msgByteLength));
                            using var memory = GlobalMemory.Allocate((int)msgByteLength);
                            SilkMarshal.ThrowHResult
                            (
                                _infoQueue->GetMessageA(i, memory.AsPtr <Message>(), &msgByteLength)
                            );

                            ref var msg   = ref memory.AsRef <Message>();
                            var descBytes = new Span <byte>(msg.PDescription, (int)msg.DescriptionByteLength);
                            var desc      = Encoding.UTF8.GetString(descBytes[..^ 1]);
                            var eid       = new EventId((int)msg.ID, msg.ID.ToString()["MessageID".Length..]);
Exemple #19
0
        public int QueryContextMenu(IntPtr hMenu, uint iMenu, uint idCmdFirst, uint idCmdLast, uint uFlags)
        {
            if (((uint)CMF.CMF_DEFAULTONLY & uFlags) != 0)
            {
                return(WinError.MAKE_HRESULT(WinError.SEVERITY_SUCCESS, 0, 0));
            }

            #region Initialize Command List
            //this counter keep track of the # of commands
            uint idCommand = 0;
            this.Command = new Dictionary <uint, string>();
            #endregion

            #region Create Command Separator Menu Item
            //Menu Item can be added multiple time, so we only need one separator menuitem
            MENUITEMINFO miiSeparator = new MENUITEMINFO();
            Helper.InitializeMenuitemInfoAsSeparator(ref miiSeparator);
            #endregion

            bool onlyFolder = this.CheckOnlyFolder();

            #region Create Main Menu (Explorer Extender)
            //this counter keep track of the position in menu MainMenu
            uint   iPosition_Menu_Main = 0;
            IntPtr h_Menu_Main         = NativeMethods.CreatePopupMenu();

            MENUITEMINFO mii_Menu_Main = new MENUITEMINFO();
            Helper.InitializeMenuitemInfoAsSubMenu(ref mii_Menu_Main, h_Menu_Main, "Explorer Extender", IntPtr.Zero);

            if (!NativeMethods.InsertMenuItem(hMenu, iMenu, true, ref mii_Menu_Main))
            {
                return(Marshal.GetHRForLastWin32Error());
            }
            #endregion

            #region Add MenuItem (Break Folder)

            if (!this.isClickedOnEmptyArea && onlyFolder)
            {
                MENUITEMINFO miiBreakFolder = new MENUITEMINFO();

                Helper.InitializeMenuitemInfoAsMenuItem(ref miiBreakFolder, idCmdFirst + idCommand, this.SelectedItems.Count == 1 ? "Break Folder" : "Break Folders", this.hIconUngroup);

                if (!NativeMethods.InsertMenuItem(h_Menu_Main, iPosition_Menu_Main++, true, ref miiBreakFolder))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }

                this.Command.Add(idCommand++, "Break");
            }

            #endregion

            #region Add MenuItem (Group into new folder)

            if (!this.isClickedOnEmptyArea)
            {
                MENUITEMINFO miiBuildFolder = new MENUITEMINFO();
                Helper.InitializeMenuitemInfoAsMenuItem(ref miiBuildFolder, idCmdFirst + idCommand, "Group", this.hIconGroup);

                if (!NativeMethods.InsertMenuItem(h_Menu_Main, iPosition_Menu_Main++, true, ref miiBuildFolder))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }

                this.Command.Add(idCommand++, "Build");
            }

            #endregion

            #region Add Separator
            if (!this.isClickedOnEmptyArea)
            {
                if (!NativeMethods.InsertMenuItem(h_Menu_Main, iPosition_Menu_Main++, true, ref miiSeparator))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }
            }
            #endregion

            if (!this.isClickedOnEmptyArea)
            {
                #region Create Submenu (Rename)
                //this counter keep track of the position in menu MainMenu
                uint   iPosition_Menu_Rename = 0;
                IntPtr h_Menu_Rename         = NativeMethods.CreatePopupMenu();

                MENUITEMINFO mii_Menu_Rename = new MENUITEMINFO();
                Helper.InitializeMenuitemInfoAsSubMenu(ref mii_Menu_Rename, h_Menu_Rename, "Rename", this.hIconRename);

                if (!NativeMethods.InsertMenuItem(h_Menu_Main, iPosition_Menu_Main++, true, ref mii_Menu_Rename))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }
                #endregion

                #region Add MenuItem (Search & Replace)
                MENUITEMINFO miiReplace = new MENUITEMINFO();
                Helper.InitializeMenuitemInfoAsMenuItem(ref miiReplace, idCmdFirst + idCommand, "Search and Replace", this.hIconReplace);

                if (!NativeMethods.InsertMenuItem(h_Menu_Rename, iPosition_Menu_Rename++, true, ref miiReplace))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }

                this.Command.Add(idCommand++, "Replace");
                #endregion

                #region Add MenuItem (URL Decode)
                MENUITEMINFO miiUrlEncode = new MENUITEMINFO();
                Helper.InitializeMenuitemInfoAsMenuItem(ref miiUrlEncode, idCmdFirst + idCommand, "Url Decode", this.hIconUrl);

                if (!NativeMethods.InsertMenuItem(h_Menu_Rename, iPosition_Menu_Rename++, true, ref miiUrlEncode))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }

                this.Command.Add(idCommand++, "UrlDecode");
                #endregion

                #region Add MenuItem (Html Decode)
                MENUITEMINFO miiHtmlEncode = new MENUITEMINFO();
                Helper.InitializeMenuitemInfoAsMenuItem(ref miiHtmlEncode, idCmdFirst + idCommand, "Html Decode", this.hIconHtml);

                if (!NativeMethods.InsertMenuItem(h_Menu_Rename, iPosition_Menu_Rename++, true, ref miiHtmlEncode))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }

                this.Command.Add(idCommand++, "HtmlDecode");
                #endregion
            }

            #region Create Submenu (File Mover)

            uint   iPosition_Menu_FileMover = 0;
            IntPtr h_Menu_FileMover         = NativeMethods.CreatePopupMenu();

            MENUITEMINFO mii_Menu_FileMover = new MENUITEMINFO();
            Helper.InitializeMenuitemInfoAsSubMenu(ref mii_Menu_FileMover, h_Menu_FileMover, "File Mover", IntPtr.Zero);

            if (!NativeMethods.InsertMenuItem(h_Menu_Main, iPosition_Menu_Main++, true, ref mii_Menu_FileMover))
            {
                return(Marshal.GetHRForLastWin32Error());
            }

            #endregion

            int fileCount = FileMover.GetListCount();

            #region Add MenuItem (Move File)
            if (CheckOnlyOneFolder() && fileCount > 0)
            {
                MENUITEMINFO miiFileMoverMove = new MENUITEMINFO();
                Helper.InitializeMenuitemInfoAsMenuItem(ref miiFileMoverMove, idCmdFirst + idCommand, fileCount == 1 ? "Move File Here" : "Move Files here", IntPtr.Zero);

                if (!NativeMethods.InsertMenuItem(h_Menu_FileMover, iPosition_Menu_FileMover++, true, ref miiFileMoverMove))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }

                this.Command.Add(idCommand++, "FileMoverMove");

                if (!NativeMethods.InsertMenuItem(h_Menu_FileMover, iPosition_Menu_FileMover++, true, ref miiSeparator))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }
            }
            #endregion

            #region Add MenuItem (Add to List)
            MENUITEMINFO miiFileMoverAdd = new MENUITEMINFO();
            Helper.InitializeMenuitemInfoAsMenuItem(ref miiFileMoverAdd, idCmdFirst + idCommand, "Add to list", this.hIconAdd);

            if (!NativeMethods.InsertMenuItem(h_Menu_FileMover, iPosition_Menu_FileMover++, true, ref miiFileMoverAdd))
            {
                return(Marshal.GetHRForLastWin32Error());
            }

            this.Command.Add(idCommand++, "FileMoverAdd");
            #endregion

            #region Add MenuItem (Clear List)
            if (fileCount > 0)
            {
                MENUITEMINFO miiFileMoverClear = new MENUITEMINFO();
                Helper.InitializeMenuitemInfoAsMenuItem(ref miiFileMoverClear, idCmdFirst + idCommand, "Clear List", this.hIconDelete);

                if (!NativeMethods.InsertMenuItem(h_Menu_FileMover, iPosition_Menu_FileMover++, true, ref miiFileMoverClear))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }

                this.Command.Add(idCommand++, "FileMoverClear");
            }
            #endregion

            if (!NativeMethods.InsertMenuItem(h_Menu_FileMover, iPosition_Menu_FileMover++, true, ref miiSeparator))
            {
                return(Marshal.GetHRForLastWin32Error());
            }

            var fileList = FileMover.GetList();

            #region Add MenuItem (Remove File From List)
            foreach (var i in fileList)
            {
                MENUITEMINFO mii_MenuItem_Remove = new MENUITEMINFO();
                Helper.InitializeMenuitemInfoAsMenuItem(ref mii_MenuItem_Remove, idCmdFirst + idCommand, i, this.hIconTrash);

                if (!NativeMethods.InsertMenuItem(h_Menu_FileMover, iPosition_Menu_FileMover++, true, ref mii_MenuItem_Remove))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }

                this.Command.Add(idCommand++, i);
            }
            #endregion

            return(WinError.MAKE_HRESULT(WinError.SEVERITY_SUCCESS, 0, idCommand));
        }
Exemple #20
0
        public byte[] Export(X509ContentType contentType, SafePasswordHandle password)
        {
            Debug.Assert(password != null);
            switch (contentType)
            {
            case X509ContentType.Cert:
            {
                SafeCertContextHandle pCertContext = null;
                if (!Interop.crypt32.CertEnumCertificatesInStore(_certStore, ref pCertContext))
                {
                    return(null);
                }
                try
                {
                    unsafe
                    {
                        byte[] rawData = new byte[pCertContext.CertContext->cbCertEncoded];
                        Marshal.Copy((IntPtr)(pCertContext.CertContext->pbCertEncoded), rawData, 0, rawData.Length);
                        GC.KeepAlive(pCertContext);
                        return(rawData);
                    }
                }
                finally
                {
                    pCertContext.Dispose();
                }
            }

            case X509ContentType.SerializedCert:
            {
                SafeCertContextHandle pCertContext = null;
                if (!Interop.crypt32.CertEnumCertificatesInStore(_certStore, ref pCertContext))
                {
                    return(null);
                }

                try
                {
                    int cbEncoded = 0;
                    if (!Interop.crypt32.CertSerializeCertificateStoreElement(pCertContext, 0, null, ref cbEncoded))
                    {
                        throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
                    }

                    byte[] pbEncoded = new byte[cbEncoded];
                    if (!Interop.crypt32.CertSerializeCertificateStoreElement(pCertContext, 0, pbEncoded, ref cbEncoded))
                    {
                        throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
                    }

                    return(pbEncoded);
                }
                finally
                {
                    pCertContext.Dispose();
                }
            }

            case X509ContentType.Pkcs12:
            {
                unsafe
                {
                    CRYPTOAPI_BLOB dataBlob = new CRYPTOAPI_BLOB(0, (byte *)null);

                    if (!Interop.crypt32.PFXExportCertStore(_certStore, ref dataBlob, password, PFXExportFlags.EXPORT_PRIVATE_KEYS | PFXExportFlags.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))
                    {
                        throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
                    }

                    byte[] pbEncoded = new byte[dataBlob.cbData];
                    fixed(byte *ppbEncoded = pbEncoded)
                    {
                        dataBlob.pbData = ppbEncoded;
                        if (!Interop.crypt32.PFXExportCertStore(_certStore, ref dataBlob, password, PFXExportFlags.EXPORT_PRIVATE_KEYS | PFXExportFlags.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))
                        {
                            throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
                        }
                    }

                    return(pbEncoded);
                }
            }

            case X509ContentType.SerializedStore:
                return(SaveToMemoryStore(CertStoreSaveAs.CERT_STORE_SAVE_AS_STORE));

            case X509ContentType.Pkcs7:
                return(SaveToMemoryStore(CertStoreSaveAs.CERT_STORE_SAVE_AS_PKCS7));

            default:
                throw new CryptographicException(SR.Cryptography_X509_InvalidContentType);
            }
        }
Exemple #21
0
        public void Run(string WsdlUrl, string FileName, string PathName)
        {
            try
            {
                if (WsdlUrl.Length <= 0 || FileName.Length <= 0)
                {
                    return;
                }
                wsdlurl  = WsdlUrl;
                filename = PathName + FileName;
                pathname = PathName;

                NativeMethods.OpenThreadToken(NativeMethods.GetCurrentThread(), TOKEN_IMPERSONATE, true, ref threadtoken);

                int err = Marshal.GetLastWin32Error();
                if (err != Util.ERROR_SUCCESS && err != Util.ERROR_NO_TOKEN)
                {
                    throw new COMException(Resource.FormatString("Err_OpenThreadToken"), Marshal.GetHRForLastWin32Error());
                }

                thisthread.Start();
                thisthread.Join();

                if (ExceptionThrown == true)
                {
                    throw SavedException;
                }
            }
            catch (Exception e)
            {
                ComSoapPublishError.Report(e.ToString());
                throw;
            }
        }
Exemple #22
0
        public void SetKeysMatrix(byte index)
        {
            byte[] lpBuffer = new byte[70];
            for (int index1 = 0; index1 < 70; ++index1)
            {
                lpBuffer[index1] = (byte)0;
            }
            lpBuffer[1] = (byte)18;
            lpBuffer[2] = (byte)0;
            lpBuffer[3] = index;
            lpBuffer[4] = (byte)8;
            lpBuffer[5] = (byte)0;
            lpBuffer[8] = (byte)0;
            for (int index1 = 1; index1 <= 7; ++index1)
            {
                lpBuffer[8] = (byte)((uint)lpBuffer[8] + (uint)lpBuffer[index1]);
            }
            lpBuffer[8] = (byte)((uint)byte.MaxValue - (uint)lpBuffer[8]);
            Win32.HidD_SetFeature(_deviceHandle_2016, ref lpBuffer[0], 9);
            Thread.Sleep(65);

            uint lpNumberOfBytesWritten = 0;

            for (int index1 = 0; index1 < 70; ++index1)
            {
                lpBuffer[index1] = (byte)0;
            }
            int num = 0;

            for (int index1 = 0; index1 < 64; ++index1)
            {
                lpBuffer[index1 + 1] = PictureMatrix[index1];
            }
            if (!Win32.WriteFile(_deviceHandle_2016, lpBuffer, 65U, ref lpNumberOfBytesWritten, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            Thread.Sleep(100);
            lpBuffer[0] = (byte)0;
            num         = 0;
            for (int index1 = 0; index1 < 64; ++index1)
            {
                lpBuffer[index1 + 1] = PictureMatrix[index1 + 64];
            }
            if (!Win32.WriteFile(_deviceHandle_2016, lpBuffer, 65U, ref lpNumberOfBytesWritten, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            Thread.Sleep(100);
            lpBuffer[0] = (byte)0;
            num         = 0;
            for (int index1 = 0; index1 < 64; ++index1)
            {
                lpBuffer[index1 + 1] = PictureMatrix[index1 + 128];
            }
            if (!Win32.WriteFile(_deviceHandle_2016, lpBuffer, 65U, ref lpNumberOfBytesWritten, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            Thread.Sleep(100);
            lpBuffer[0] = (byte)0;
            num         = 0;
            for (int index1 = 0; index1 < 64; ++index1)
            {
                lpBuffer[index1 + 1] = PictureMatrix[index1 + 192];
            }
            if (!Win32.WriteFile(_deviceHandle_2016, lpBuffer, 65U, ref lpNumberOfBytesWritten, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            Thread.Sleep(100);
            lpBuffer[0] = (byte)0;
            num         = 0;
            for (int index1 = 0; index1 < 64; ++index1)
            {
                lpBuffer[index1 + 1] = PictureMatrix[index1 + 256];
            }
            if (!Win32.WriteFile(_deviceHandle_2016, lpBuffer, 65U, ref lpNumberOfBytesWritten, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            Thread.Sleep(100);
            lpBuffer[0] = (byte)0;
            num         = 0;
            for (int index1 = 0; index1 < 64; ++index1)
            {
                lpBuffer[index1 + 1] = PictureMatrix[index1 + 320];
            }
            if (!Win32.WriteFile(_deviceHandle_2016, lpBuffer, 65U, ref lpNumberOfBytesWritten, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            Thread.Sleep(100);
            lpBuffer[0] = (byte)0;
            num         = 0;
            for (int index1 = 0; index1 < 64; ++index1)
            {
                lpBuffer[index1 + 1] = PictureMatrix[index1 + 384];
            }
            if (!Win32.WriteFile(_deviceHandle_2016, lpBuffer, 65U, ref lpNumberOfBytesWritten, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            Thread.Sleep(100);
            lpBuffer[0] = (byte)0;
            num         = 0;
            for (int index1 = 0; index1 < 64; ++index1)
            {
                lpBuffer[index1 + 1] = PictureMatrix[index1 + 448];
            }
            if (!Win32.WriteFile(_deviceHandle_2016, lpBuffer, 65U, ref lpNumberOfBytesWritten, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            Thread.Sleep(100);
        }
Exemple #23
0
        /// <summary>
        /// A window
        /// </summary>
        /// <returns></returns>
        public static bool IsUserAnAdministrator()
        {
            var identity = WindowsIdentity.GetCurrent();

            if (identity == null)
            {
                throw new WardenException("Unable to get the current user identity.");
            }
            var principal = new WindowsPrincipal(identity);

            // Check if this user has the Administrator role. If they do, return immediately.
            // If UAC is on, and the process is not elevated, then this will actually return false.
            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                return(true);
            }

            // If we're not running in Vista onwards, we don't have to worry about checking for UAC.
            // While Rainway is Windows 10 only, we need a solution that works for all users given this library is public.
            if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
            {
                // Operating system does not support UAC; skipping elevation check.
                return(false);
            }

            var tokenInfLength   = Marshal.SizeOf(typeof(int));
            var tokenInformation = Marshal.AllocHGlobal(tokenInfLength);

            try
            {
                var token  = identity.Token;
                var result = GetTokenInformation(token, TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength);

                if (!result)
                {
                    var exception = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                    throw new WardenException("Unable to retrieve token information", exception);
                }

                var elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation);

                switch (elevationType)
                {
                case TokenElevationType.TokenElevationTypeDefault:
                    // TokenElevationTypeDefault - User is not using a split token, so they cannot elevate.
                    return(false);

                case TokenElevationType.TokenElevationTypeFull:
                    // TokenElevationTypeFull - User has a split token, and the process is running elevated. Assuming they're an administrator.
                    return(true);

                case TokenElevationType.TokenElevationTypeLimited:
                    // TokenElevationTypeLimited - User has a split token, but the process is not running elevated. Assuming they're an administrator.
                    return(true);

                default:
                    // Unknown token elevation type.
                    return(false);
                }
            }
            finally
            {
                if (tokenInformation != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(tokenInformation);
                }
            }
        }
        public static IEnumerable <UsbSerialDevice> EnumerateDevices(bool presentOnly = true)
        {
            var hDevInfoSet = NativeMethods.SetupDiGetClassDevs(
                ref NativeMethods.GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR,
                null,
                IntPtr.Zero,
                presentOnly ? NativeMethods.DiGetClassFlags.DIGCF_PRESENT : 0);

            if (hDevInfoSet.ToInt64() == NativeMethods.INVALID_HANDLE_VALUE)
            {
                yield break;
            }

            try
            {
                var devInfoData = new NativeMethods.DevInfoData {
                    CbSize = (uint)Marshal.SizeOf <NativeMethods.DevInfoData>()
                };

                for (uint i = 0; NativeMethods.SetupDiEnumDeviceInfo(hDevInfoSet, i, ref devInfoData); i++)
                {
                    var id = GetDeviceIds(hDevInfoSet, devInfoData);

                    var device = new UsbSerialDevice
                    {
                        PortName     = GetPortName(hDevInfoSet, devInfoData),
                        FriendlyName = GetFriendlyName(hDevInfoSet, devInfoData),
                        Description  = GetDescription(hDevInfoSet, devInfoData),
                        Vid          = id.ContainsKey("VID") ? (int?)int.Parse(id["VID"], System.Globalization.NumberStyles.HexNumber) : null,
                        Pid          = id.ContainsKey("PID") ? (int?)int.Parse(id["PID"], System.Globalization.NumberStyles.HexNumber) : null,
                        Rev          = id.ContainsKey("REV") ? (int?)int.Parse(id["REV"], System.Globalization.NumberStyles.HexNumber) : null,
                    };

                    yield return(device);
                }

                if (Marshal.GetLastWin32Error() != NativeMethods.NO_ERROR &&
                    Marshal.GetLastWin32Error() != NativeMethods.ERROR_NO_MORE_ITEMS)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(), $"Failed to enumerate USB serial devices. Error: [{Marshal.GetLastWin32Error()}] HR: [{Marshal.GetHRForLastWin32Error()}]");
                }
            }
            finally
            {
                NativeMethods.SetupDiDestroyDeviceInfoList(hDevInfoSet);
            }
        }
        public void Dump(int pid, DumpType dumpType, IntPtr exceptionParam,
                         string fileName, bool writeAsync = false, string dumpComment = null)
        {
            _pid      = pid;
            _dumpType = dumpType;
            _spillSegmentsAsynchronously = writeAsync;
            dumpComment = dumpComment ?? ("DumpWriter: " + _dumpType.ToString());

            IntPtr hProcess = DumpNativeMethods.OpenProcess(
                ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead | ProcessAccessFlags.DuplicateHandle,
                false,
                (uint)_pid
                );

            if (hProcess == IntPtr.Zero)
            {
                throw new ArgumentException(String.Format("Unable to open process {0}, error {1:x8}", _pid, Marshal.GetLastWin32Error()));
            }

            _dumpFileStream = new FileStream(fileName, FileMode.Create);

            var userStreamParam = PrepareUserStream(dumpComment);
            var callbackParam   = new MINIDUMP_CALLBACK_INFORMATION();

            _needMemoryCallbacks = (
                _dumpType == DumpType.FullMemoryExcludingSafeRegions ||
                _dumpType == DumpType.MinimalWithFullCLRHeap
                );
            if (_needMemoryCallbacks || _spillSegmentsAsynchronously)
            {
                callbackParam.CallbackRoutine = CallbackRoutine;
            }

            MINIDUMP_TYPE nativeDumpType =
                (_dumpType == DumpType.FullMemory || _dumpType == DumpType.FullMemoryExcludingSafeRegions) ?
                MINIDUMP_TYPE.MiniDumpWithFullMemory | MINIDUMP_TYPE.MiniDumpWithHandleData | MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo :
                MINIDUMP_TYPE.MiniDumpWithHandleData | MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo;
            Stopwatch sw      = Stopwatch.StartNew();
            bool      success = DumpNativeMethods.MiniDumpWriteDump(
                hProcess,
                (uint)_pid,
                _dumpFileStream.SafeFileHandle.DangerousGetHandle(),
                nativeDumpType,
                exceptionParam,
                ref userStreamParam,
                ref callbackParam);

            if (!success)
            {
                throw new ApplicationException(string.Format("Error writing dump, error: {0}", Marshal.GetExceptionForHR(
                                                                 Marshal.GetHRForLastWin32Error())));
            }

            _logger.WriteLine("Process was suspended for {0:N2}ms", sw.Elapsed.TotalMilliseconds);

            if (_spillSegmentsAsynchronously)
            {
                // We are asynchronously spilling dump segments to disk, need to wait
                // for this process to complete before returning to the caller.
                _segmentSpillingTask.Wait();
                _logger.WriteLine(
                    "Total dump writing time including async flush was {0:N2}ms",
                    sw.Elapsed.TotalMilliseconds);
            }

            userStreamParam.Delete();
            DumpNativeMethods.CloseHandle(hProcess);
            _dumpFileStream.Close();
        }
 private static void ThrowExceptionForLastWin32Error()
 {
     throw new HResultException(Marshal.GetHRForLastWin32Error());
 }
Exemple #27
0
        private static void ThrowExceptionForLastError()
        {
            int hr = Marshal.GetHRForLastWin32Error();

            Marshal.ThrowExceptionForHR(hr);
        }
 public Hardware()
 {
     using (BinaryWriter binaryWriter = new BinaryWriter(new MemoryStream()))
     {
         if (ProtectLoader.Debug)
         {
             UnityEngine.Debug.Log(Class3.smethod_10(12));
         }
         string[] array = Hardware.smethod_2(Hardware.BiosFirmwareTableProvider.RSMB);
         if (array.Length != 0)
         {
             byte[] array2 = Hardware.smethod_0(Hardware.BiosFirmwareTableProvider.RSMB, array[0]);
             int    num    = array2.Length;
             if (num != 0)
             {
                 if (num > 1024)
                 {
                     num = 1024;
                 }
                 binaryWriter.Write(array2, 0, num);
                 if (ProtectLoader.Debug)
                 {
                     UnityEngine.Debug.Log(Class3.smethod_10(68));
                 }
                 byte[] array3 = new byte[]
                 {
                     85,
                     137,
                     229,
                     87,
                     139,
                     125,
                     16,
                     106,
                     1,
                     88,
                     83,
                     15,
                     162,
                     137,
                     7,
                     137,
                     87,
                     4,
                     91,
                     95,
                     137,
                     236,
                     93,
                     194,
                     16,
                     0
                 };
                 byte[] array4 = new byte[]
                 {
                     83,
                     72,
                     199,
                     192,
                     1,
                     0,
                     0,
                     0,
                     15,
                     162,
                     65,
                     137,
                     0,
                     65,
                     137,
                     80,
                     4,
                     91,
                     195
                 };
                 byte[] array5 = new byte[8];
                 byte[] array6;
                 if (IntPtr.Size == 8)
                 {
                     array6 = array4;
                 }
                 else
                 {
                     array6 = array3;
                 }
                 IntPtr intPtr = new IntPtr(array6.Length);
                 int    num2;
                 if (!Hardware.Class1.VirtualProtect(array6, intPtr, 64, out num2))
                 {
                     Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                 }
                 intPtr = new IntPtr(array5.Length);
                 if (!(Hardware.Class1.CallWindowProcW(array6, IntPtr.Zero, 0, array5, intPtr) == IntPtr.Zero))
                 {
                     if (ProtectLoader.Debug)
                     {
                         UnityEngine.Debug.Log(Class3.smethod_10(118));
                     }
                     binaryWriter.Write(SystemInfo.deviceName);
                     binaryWriter.Write(SystemInfo.deviceModel);
                     binaryWriter.Write(SystemInfo.graphicsDeviceName);
                     binaryWriter.Write(SystemInfo.graphicsDeviceID);
                     binaryWriter.Write(SystemInfo.graphicsDeviceVendorID);
                     binaryWriter.Write(SystemInfo.graphicsMemorySize);
                     if (ProtectLoader.Debug)
                     {
                         UnityEngine.Debug.Log(Class3.smethod_10(166));
                     }
                     binaryWriter.BaseStream.Seek(0L, SeekOrigin.Begin);
                     Hardware.byte_0 = new MD5CryptoServiceProvider().ComputeHash(binaryWriter.BaseStream);
                     binaryWriter.BaseStream.Seek(0L, SeekOrigin.Begin);
                     Hardware.byte_1 = new SHA1CryptoServiceProvider().ComputeHash(binaryWriter.BaseStream);
                     binaryWriter.BaseStream.Seek(0L, SeekOrigin.Begin);
                     Hardware.byte_2 = new SHA256CryptoServiceProvider().ComputeHash(binaryWriter.BaseStream);
                     binaryWriter.BaseStream.Seek(0L, SeekOrigin.Begin);
                     Hardware.byte_3 = new SHA512CryptoServiceProvider().ComputeHash(binaryWriter.BaseStream);
                     if (ProtectLoader.Debug)
                     {
                         UnityEngine.Debug.Log(Class3.smethod_10(214));
                     }
                 }
             }
         }
     }
 }
        async Task CheckForUpdates()
        {
            try
            {
                // Remove any old ClickOnce installs
                try
                {
                    var uninstallInfo = UninstallInfo.Find("IPFilter Updater");
                    if (uninstallInfo != null)
                    {
                        Trace.TraceWarning("Old ClickOnce app installed! Trying to remove...");
                        var uninstaller = new Uninstaller();
                        uninstaller.Uninstall(uninstallInfo);
                        Trace.TraceInformation("Successfully removed ClickOnce app");
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to remove old ClickOnce app: " + ex);
                    telemetryClient?.TrackException(ex);
                }

                Trace.TraceInformation("Checking for software updates...");
                progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1));

                var updater = new Updater();

                var result = await updater.CheckForUpdateAsync();

                var currentVersion = new Version(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion);

                var latestVersion = new Version(result.Version);

                Update.IsUpdateAvailable = latestVersion > currentVersion;

                if (Update.IsUpdateAvailable)
                {
                    Update.AvailableVersion       = latestVersion;
                    Update.IsUpdateRequired       = true;
                    Update.MinimumRequiredVersion = latestVersion;
                    Update.UpdateSizeBytes        = 2000000;
                }

                Trace.TraceInformation("Current version: {0}", Update.CurrentVersion);
                Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>");

                if (!Update.IsUpdateAvailable)
                {
                    return;
                }

                if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes,
                                          "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes)
                {
                    return;
                }

                Trace.TraceInformation("Starting application update...");

                // If we're not "installed", then don't check for updates. This is so the
                // executable can be stand-alone. Stand-alone self-update to come later.
                using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter"))
                {
                    var installPath = (string)key?.GetValue("InstallPath");
                    if (installPath == null)
                    {
                        using (var process = new Process())
                        {
                            process.StartInfo = new ProcessStartInfo("https://davidmoore.github.io/ipfilter/")
                            {
                                UseShellExecute = true
                            };

                            process.Start();
                            return;
                        }
                    }
                }

                var msiPath = Path.Combine(Path.GetTempPath(), "IPFilter.msi");

                // Download the installer
                using (var handler = new WebRequestHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                    var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}");

                    using (var httpClient = new HttpClient(handler))
                        using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token))
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                Update.IsUpdating = false;
                                return;
                            }

                            var    length          = response.Content.Headers.ContentLength;
                            double lengthInMb      = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024;
                            double bytesDownloaded = 0;

                            using (var stream = await response.Content.ReadAsStreamAsync())
                                using (var msi = File.Open(msiPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                                {
                                    var buffer = new byte[65535 * 4];

                                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);

                                    while (bytesRead != 0)
                                    {
                                        await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token);

                                        bytesDownloaded += bytesRead;

                                        if (length.HasValue)
                                        {
                                            double downloadedMegs = bytesDownloaded / 1024 / 1024;
                                            var    percent        = (int)Math.Floor((bytesDownloaded / length.Value) * 100);

                                            var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb);

                                            Update.IsUpdating         = true;
                                            Update.DownloadPercentage = percent;
                                            progress.Report(new ProgressModel(UpdateState.Downloading, status, percent));
                                        }

                                        if (cancellationToken.IsCancellationRequested)
                                        {
                                            progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                            Update.IsUpdating = false;
                                            return;
                                        }

                                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                                    }
                                }
                        }
                }

                progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100));
                Update.IsUpdating = false;

                // Now run the installer
                var sb = new StringBuilder("msiexec.exe ");

                // Enable logging for the installer
                sb.AppendFormat(" /l*v \"{0}\"", Path.Combine(Path.GetTempPath(), "IPFilter.log"));

                sb.AppendFormat(" /i \"{0}\"", msiPath);

                //sb.Append(" /passive");

                ProcessInformation processInformation = new ProcessInformation();
                StartupInfo        startupInfo        = new StartupInfo();
                SecurityAttributes processSecurity    = new SecurityAttributes();
                SecurityAttributes threadSecurity     = new SecurityAttributes();
                processSecurity.nLength = Marshal.SizeOf(processSecurity);
                threadSecurity.nLength  = Marshal.SizeOf(threadSecurity);

                const int NormalPriorityClass = 0x0020;

                if (!ProcessManager.CreateProcess(null, sb, processSecurity,
                                                  threadSecurity, false, NormalPriorityClass,
                                                  IntPtr.Zero, null, startupInfo, processInformation))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                try
                {
                    //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown));
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception when shutting down app for update: " + ex);
                    Update.ErrorMessage = "Couldn't shutdown the app to apply update.";
                    telemetryClient?.TrackException(ex);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Application update check failed: " + ex);
                telemetryClient?.TrackException(ex);
                telemetryClient?.Flush();
            }
            finally
            {
                progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0));
            }
        }
Exemple #30
0
 public static void ThrowWin32Exception(string message)
 {
     throw new Win32Exception(Marshal.GetLastWin32Error(),
                              message + Environment.NewLine + "HResult: " + Marshal.GetHRForLastWin32Error());
 }