private bool OpenHandle()
 {
     Handle?.Close();
     Handle = null;
     Handle = NativeMethods.CreateFile(DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, EFileAttributes.Overlapped, IntPtr.Zero);
     return(!Handle.IsInvalid);
 }
Exemplo n.º 2
0
        private static bool HasTrimEnabled(string drive)
        {
            Logger.Info("Checking trim enabled for drive: " + drive);
            SafeFileHandle fileW = SSDCheck.CreateFileW(drive, 0U, 3U, IntPtr.Zero, 3U, 128U, IntPtr.Zero);

            if (fileW == null || fileW.IsInvalid)
            {
                Logger.Error("CreateFile failed with message: " + SSDCheck.GetErrorMessage(Marshal.GetLastWin32Error()));
                throw new Exception("check the error message above");
            }
            uint dwIoControlCode = SSDCheck.CTL_CODE(45U, 1280U, 0U, 0U);

            SSDCheck.STORAGE_PROPERTY_QUERY lpInBuffer = new SSDCheck.STORAGE_PROPERTY_QUERY()
            {
                PropertyId = 8,
                QueryType  = 0
            };
            SSDCheck.DEVICE_TRIM_DESCRIPTOR lpOutBuffer = new SSDCheck.DEVICE_TRIM_DESCRIPTOR();
            int num = SSDCheck.DeviceIoControl(fileW, dwIoControlCode, ref lpInBuffer, (uint)Marshal.SizeOf((object)lpInBuffer), ref lpOutBuffer, (uint)Marshal.SizeOf((object)lpOutBuffer), out uint _, IntPtr.Zero) ? 1 : 0;

            fileW?.Close();
            if (num == 0)
            {
                Logger.Error("DeviceIoControl failed to query trim enabled. " + SSDCheck.GetErrorMessage(Marshal.GetLastWin32Error()));
                throw new Exception("check the error message above");
            }
            bool trimEnabled = lpOutBuffer.TrimEnabled;

            Logger.Info(string.Format("Is Trim Enabled: {0}", (object)trimEnabled));
            return(trimEnabled);
        }
Exemplo n.º 3
0
        public DriveAccess(string Path)
        {
            if (Path == null || Path.Length == 0)
                throw new ArgumentNullException("Path");

            driveHandle = CreateFile(Path, 0xC0000000, 0x03, IntPtr.Zero, 0x03, 0x80, IntPtr.Zero);
            if (driveHandle.IsInvalid)
            {
                driveHandle.Close();
                driveHandle.Dispose();
                driveHandle = null;
                throw new Exception("Win32 Exception : 0x" + Convert.ToString(Marshal.GetHRForLastWin32Error(), 16).PadLeft(8, '0'));
            }
            driveStream = new FileStream(driveHandle, FileAccess.ReadWrite);

            IntPtr p = Marshal.AllocHGlobal(24);
            uint returned;
            if (DeviceIoControl(driveHandle.DangerousGetHandle(), 0x00070000, IntPtr.Zero, 0, p, 40, out returned, IntPtr.Zero))
                unsafe { driveGeometry = new DriveGeometry((byte*)p.ToPointer()); }
            else
            {
                Marshal.FreeHGlobal(p);
                throw new Exception("Could not get the drive geometry information!");
            }
            Marshal.FreeHGlobal(p);
        }
Exemplo n.º 4
0
        internal override bool TryReadValue(out long value)
        {
            try
            {
                IntPtr fileIntPtr = NativeMethods.CreateFileW(filename + ":" + Key, NativeConstants.GENERIC_READ, NativeConstants.FILE_SHARE_WRITE, IntPtr.Zero, NativeConstants.OPEN_ALWAYS, 0, IntPtr.Zero);
                if (fileIntPtr.ToInt32() <= 0)
                {
                    value = 0;
                    return false;
                }

                SafeFileHandle streamHandle = new SafeFileHandle(fileIntPtr, true);
                using (BinaryReader reader = new BinaryReader(new FileStream(streamHandle, FileAccess.Read)))
                {
                    value = reader.ReadInt64();
                }
                streamHandle.Close();

                return true;
            }
            catch
            {
                value = 0;
                return false;
            }
        }
Exemplo n.º 5
0
        private static uint GetDiskExtents(char cDrive)
        {
            if (new DriveInfo(cDrive.ToString((IFormatProvider)CultureInfo.InvariantCulture)).DriveType != DriveType.Fixed)
            {
                Logger.Info(string.Format("The drive {0} is not fixed drive.", (object)cDrive));
            }
            string         lpFileName = "\\\\.\\" + cDrive.ToString((IFormatProvider)CultureInfo.InvariantCulture) + ":";
            SafeFileHandle fileW      = SSDCheck.CreateFileW(lpFileName, 0U, 3U, IntPtr.Zero, 3U, 128U, IntPtr.Zero);

            if (fileW == null || fileW.IsInvalid)
            {
                string errorMessage = SSDCheck.GetErrorMessage(Marshal.GetLastWin32Error());
                Logger.Error("CreateFile failed for " + lpFileName + ".  " + errorMessage);
                throw new Exception("check the error message above");
            }
            uint dwIoControlCode = SSDCheck.CTL_CODE(86U, 0U, 0U, 0U);

            SSDCheck.VOLUME_DISK_EXTENTS lpOutBuffer = new SSDCheck.VOLUME_DISK_EXTENTS();
            int num = SSDCheck.DeviceIoControl(fileW, dwIoControlCode, IntPtr.Zero, 0U, ref lpOutBuffer, (uint)Marshal.SizeOf((object)lpOutBuffer), out uint _, IntPtr.Zero) ? 1 : 0;

            fileW?.Close();
            if (num == 0 || lpOutBuffer.Extents.Length != 1)
            {
                Logger.Error("DeviceIoControl failed to query disk extension. " + SSDCheck.GetErrorMessage(Marshal.GetLastWin32Error()));
                throw new Exception("check the error message above");
            }
            uint diskNumber = lpOutBuffer.Extents[0].DiskNumber;

            Logger.Info(string.Format("The physical drive number is: {0}", (object)diskNumber));
            return(diskNumber);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Disconnect from the controller and stop reading data from it
        /// </summary>
        public void Disconnect()
        {
            // close up the stream and handle
            mStream?.Close();
            mStream = null;

            mHandle?.Close();
            mHandle = null;

            timerMotionPlus?.Dispose();
            timerMotionPlus = null;
        }
        public void LockedFileDirectoryDeletion2()
        {
            using (var cleaner = new TestFileCleaner())
            {
                string directory = cleaner.GetTestPath();
                DirectoryMethods.CreateDirectory(directory);
                FileMethods.DirectoryExists(directory).Should().BeTrue();
                string file = cleaner.CreateTestFile(nameof(LockedFileDirectoryDeletion2), directory);

                SafeFileHandle directoryHandle = null;
                using (var handle = FileMethods.CreateFile(file, CreationDisposition.OpenExisting, DesiredAccess.GenericRead, ShareModes.ReadWrite | ShareModes.Delete))
                {
                    handle.IsInvalid.Should().BeFalse();

                    // Mark the file for deletion
                    FileMethods.DeleteFile(file);

                    // Open the directory handle
                    directoryHandle = FileMethods.CreateFile(
                        directory,
                        CreationDisposition.OpenExisting,
                        DesiredAccess.ListDirectory | DesiredAccess.Delete,
                        ShareModes.ReadWrite | ShareModes.Delete,
                        FileAttributes.None,
                        FileFlags.BackupSemantics | FileFlags.DeleteOnClose);
                }

                try
                {
                    // File will be gone now that the handle is closed
                    FileMethods.FileExists(file).Should().BeFalse();

                    directoryHandle.Close();

                    // The directory will not exist as the open handle was closed before it was closed
                    FileMethods.DirectoryExists(directory).Should().BeFalse();
                }
                finally
                {
                    directoryHandle?.Close();
                }
            }
        }
Exemplo n.º 8
0
        internal override bool TryWriteValue(long value)
        {
            try
            {
                IntPtr fileIntPtr = NativeMethods.CreateFileW(filename + ":" + Key, NativeConstants.GENERIC_WRITE, NativeConstants.FILE_SHARE_WRITE, IntPtr.Zero, NativeConstants.OPEN_ALWAYS, 0, IntPtr.Zero);
                if (fileIntPtr.ToInt32() <= 0)
                    return false;

                SafeFileHandle streamHandle = new SafeFileHandle(fileIntPtr, true);
                using (BinaryWriter writer = new BinaryWriter(new FileStream(streamHandle, FileAccess.Write)))
                {
                    writer.Write(value);
                }
                streamHandle.Close();

                return true;
            }
            catch
            {
                return false;
            }
        }
Exemplo n.º 9
0
 public override void Close()
 {
     _fileStream?.Close();
     _fileHandle?.Close();
 }
Exemplo n.º 10
0
 public void Dispose()
 {
     logHandle.Close();
 }
Exemplo n.º 11
0
        public void  Connect()
        {
            bool found = false;
            Guid guid;
            uint index = 0;

            // get the GUID of the HID class
            HIDImports.HidD_GetHidGuid(out guid);

            // get a handle to all devices that are part of the HID class
            // Fun fact:  DIGCF_PRESENT worked on my machine just fine.  I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled...
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports.DIGCF_DEVICEINTERFACE);            // | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports.SP_DEVICE_INTERFACE_DATA diData = new HIDImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // get a device interface to a single device (enumerate all devices)
            while (HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size = 0;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // create a detail struct and set its size
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
                // someday I should figure this out.  Thanks to Paul Miller on this...
                if (IntPtr.Size == 8)
                {
                    diDetail.cbSize = 8;
                }
                else
                {
                    diDetail.cbSize = 5;
                }

                // actually get the detail struct
                if (HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    Debug.WriteLine(index + " " + diDetail.DevicePath + " " + Marshal.GetLastWin32Error());

                    // open a read/write handle to our device using the DevicePath returned
                    mHandle = HIDImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    // create an attributes struct and initialize the size
                    HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);
                    // get the attributes of the current device
                    if (HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if (attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            if (!IsRemoteConnected((int)index))
                            {
                                Debug.WriteLine("Found it!");
                                found    = true;
                                remoteID = (int)index;
                                connectedRemoteIDs.Add(remoteID);

                                // create a nice .NET FileStream wrapping the handle above
                                mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                                // start an async read operation on it
                                BeginAsyncRead();

                                // read the calibration info from the controller
                                ReadCalibration();
                                break;
                            }
                        }
                        else
                        {
                            // otherwise this isn't the controller, so close up the file handle
                            mHandle.Close();
                        }
                    }
                }
                else
                {
                    // failed to get the detail struct
                    throw new Exception("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                // move to the next device
                index++;
            }


            // if we didn't find a Wiimote, throw an exception
            if (!found)
            {
                throw new Exception("No available Wiimote not found.");
            }

            // clean up our list
            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);
        }
Exemplo n.º 12
0
        public GPTScan(string physicalDriveName)
        {
            const uint SectorSize = 512;

            byte[] buff = new byte[512];
            uint   nBytesRead;

            SafeFileHandle shFile = WinApi.CreateFile(physicalDriveName, FileAccess.Read, FileShare.Read, (IntPtr)0, FileMode.Open, 0, (IntPtr)0);

            //LBA0
            WinApi.ReadFile(shFile, buff, 512, out nBytesRead, (IntPtr)0);

            //LBA1 ---------------------------HEADER----------------------------------------------
            Mbr = new MBR(buff);

            UInt64 addr  = 512;
            int    hPart = (int)(addr >> 32);
            uint   lPart = (uint)addr;

            WinApi.SetFilePointer(shFile, lPart, out hPart, (uint)SeekOrigin.Begin);
            if (shFile.IsInvalid)
            {
                throw new InvalidDataException();
            }

            try
            {
                WinApi.ReadFile(shFile, buff, SectorSize, out nBytesRead, (IntPtr)0);
            }
            catch (FileLoadException ex)
            {
                ex.ToString();//!!!!!!!!!!!!!!!!! shit
            }

            Header = new GPTHeader(buff);
            //---------------------------------------------------------------------------- ~Header


            //LBA2...X
            for (uint i = 0; i < Header.getNumberOfPartitionEntries() / (SectorSize / Header.getSizeOfPartitionEntry()); i++)
            {
                addr += 512;
                hPart = (int)(addr >> 32);
                lPart = (uint)addr;
                WinApi.SetFilePointer(shFile, lPart, out hPart, (uint)SeekOrigin.Begin);

                WinApi.ReadFile(shFile, buff, 512, out nBytesRead, (IntPtr)0);

                int offset = 0;//офсет внутри сектора
                for (int j = 0; j < 512 / Header.getSizeOfPartitionEntry(); j++)
                {
                    //---Анализируем гуид на предмет неиспользуемой записи
                    byte[] guidBuff = new byte [16];
                    for (int guidIndex = 0; guidIndex < 16; guidIndex++)
                    {
                        guidBuff[guidIndex] = buff[guidIndex + offset];
                    }
                    Guid guid = new Guid(guidBuff);
                    //----------------------------------------------------------
                    if (!guid.Equals(Guid.Empty))
                    {
                        Sections.Add(new GPTSection(buff, offset));
                    }
                    offset += (int)Header.getSizeOfPartitionEntry();
                }
            }
            shFile.Close();
        }//GPTScan( string PhysicalDriveName )
Exemplo n.º 13
0
 public void Close()
 {
     SafeFileHandle.Close();
 }
Exemplo n.º 14
0
        internal static IEnumerable <FileIdBothDirectoryInfo> EnumerateFileIdBothDirectoryInfoCore(KernelTransaction transaction, SafeFileHandle safeHandle, string path, FileShare shareMode, bool continueOnException, PathFormat pathFormat)
        {
            if (!NativeMethods.IsAtLeastWindowsVista)
            {
                throw new PlatformNotSupportedException(Resources.Requires_Windows_Vista_Or_Higher);
            }

            bool callerHandle = safeHandle != null;

            if (!callerHandle)
            {
                if (Utils.IsNullOrWhiteSpace(path))
                {
                    throw new ArgumentNullException("path");
                }

                string pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

                safeHandle = File.CreateFileCore(transaction, pathLp, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, shareMode, true, PathFormat.LongFullPath);
            }


            try
            {
                if (!NativeMethods.IsValidHandle(safeHandle, Marshal.GetLastWin32Error(), !continueOnException))
                {
                    yield break;
                }

                var fileNameOffset = (int)Marshal.OffsetOf(typeof(NativeMethods.FILE_ID_BOTH_DIR_INFO), "FileName");

                using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize))
                {
                    while (true)
                    {
                        if (!NativeMethods.GetFileInformationByHandleEx(safeHandle, NativeMethods.FileInfoByHandleClass.FileIdBothDirectoryInfo, safeBuffer, (uint)safeBuffer.Capacity))
                        {
                            uint lastError = (uint)Marshal.GetLastWin32Error();
                            switch (lastError)
                            {
                            case Win32Errors.ERROR_SUCCESS:
                            case Win32Errors.ERROR_NO_MORE_FILES:
                            case Win32Errors.ERROR_HANDLE_EOF:
                                yield break;

                            case Win32Errors.ERROR_MORE_DATA:
                                continue;

                            default:
                                NativeError.ThrowException(lastError, path);
                                yield break; // we should never get to this yield break.
                            }
                        }

                        int offset = 0;
                        NativeMethods.FILE_ID_BOTH_DIR_INFO fibdi;
                        do
                        {
                            fibdi = safeBuffer.PtrToStructure <NativeMethods.FILE_ID_BOTH_DIR_INFO>(offset);
                            string fileName = safeBuffer.PtrToStringUni(offset + fileNameOffset, (int)(fibdi.FileNameLength / 2));

                            if (!fileName.Equals(Path.CurrentDirectoryPrefix, StringComparison.OrdinalIgnoreCase) &&
                                !fileName.Equals(Path.ParentDirectoryPrefix, StringComparison.OrdinalIgnoreCase))
                            {
                                yield return(new FileIdBothDirectoryInfo(fibdi, fileName));
                            }

                            offset += fibdi.NextEntryOffset;
                        }while (fibdi.NextEntryOffset != 0);
                    }
                }
            }
            finally
            {
                // Handle is ours, dispose.
                if (!callerHandle && safeHandle != null)
                {
                    safeHandle.Close();
                }
            }
        }
Exemplo n.º 15
0
        internal void Init(String path, FileMode mode, FileAccess access, int rights, bool useRights, FileShare share, int bufferSize, FileOptions options, Win32Native.SECURITY_ATTRIBUTES secAttrs, String msgPath, bool bFromProxy, bool useLongPath)
        { 
            if (path == null) 
                throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
            if (path.Length == 0) 
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
            Contract.EndContractBlock();

#if !FEATURE_PAL && FEATURE_MACL 
            FileSystemRights fileSystemRights = (FileSystemRights)rights;
#endif 
            // msgPath must be safe to hand back to untrusted code. 

            _fileName = msgPath;  // To handle odd cases of finalizing partially constructed objects. 
            _exposedHandle = false;

#if FEATURE_PAL
            Contract.Assert(!useRights, "Specifying FileSystemRights is not supported on this platform!"); 
#endif
 
            // don't include inheritable in our bounds check for share 
            FileShare tempshare = share & ~FileShare.Inheritable;
            String badArg = null; 

            if (mode < FileMode.CreateNew || mode > FileMode.Append)
                badArg = "mode";
            else if (!useRights && (access < FileAccess.Read || access > FileAccess.ReadWrite)) 
                badArg = "access";
#if !FEATURE_PAL && FEATURE_MACL 
            else if (useRights && (fileSystemRights < FileSystemRights.ReadData || fileSystemRights > FileSystemRights.FullControl)) 
                badArg = "rights";
#endif 
            else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
                badArg = "share";

            if (badArg != null) 
                throw new ArgumentOutOfRangeException(badArg, Environment.GetResourceString("ArgumentOutOfRange_Enum"));
 
            // NOTE: any change to FileOptions enum needs to be matched here in the error validation 
            if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
                throw new ArgumentOutOfRangeException("options", Environment.GetResourceString("ArgumentOutOfRange_Enum")); 

            if (bufferSize <= 0)
                throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
 
            // Write access validation
#if !FEATURE_PAL && FEATURE_MACL 
            if ((!useRights && (access & FileAccess.Write) == 0) 
                || (useRights && (fileSystemRights & FileSystemRights.Write) == 0))
#else 
            if (!useRights && (access & FileAccess.Write) == 0)
#endif //!FEATURE_PAL && FEATURE_MACL
            {
                if (mode==FileMode.Truncate || mode==FileMode.CreateNew || mode==FileMode.Create || mode==FileMode.Append) { 
                    // No write access
                    if (!useRights) 
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&AccessCombo", mode, access)); 
#if !FEATURE_PAL && FEATURE_MACL
                    else 
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&RightsCombo", mode, fileSystemRights));
#endif //!FEATURE_PAL && FEATURE_MACL
                }
            } 

#if !FEATURE_PAL && FEATURE_MACL 
            // FileMode.Truncate only works with GENERIC_WRITE (FileAccess.Write), source:MSDN 
            // For backcomp use FileAccess.Write when FileSystemRights.Write is specified
            if (useRights && (mode == FileMode.Truncate)) { 
                if (fileSystemRights == FileSystemRights.Write) {
                    useRights = false;
                    access = FileAccess.Write;
                } 
                else {
                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileModeTruncate&RightsCombo", mode, fileSystemRights)); 
                } 
            }
#endif 

            int fAccess;
            if (!useRights) {
                fAccess = access == FileAccess.Read? GENERIC_READ: 
                access == FileAccess.Write? GENERIC_WRITE:
                GENERIC_READ | GENERIC_WRITE; 
            } 
            else {
                fAccess = rights; 
            }

            // Get absolute path - Security needs this to prevent something
            // like trying to create a file in c:\tmp with the name 
            // "..\WinNT\System32\ntoskrnl.exe".  Store it for user convenience.
            int maxPath = useLongPath ? Path.MaxLongPath : Path.MaxPath; 
            String filePath = Path.NormalizePath(path, true, maxPath); 

            _fileName = filePath; 

            // Prevent access to your disk drives as raw block devices.
            if (filePath.StartsWith("\\\\.\\", StringComparison.Ordinal))
                throw new ArgumentException(Environment.GetResourceString("Arg_DevicesNotSupported")); 

            // Build up security permissions required, as well as validate we 
            // have a sensible set of parameters.  IE, creating a brand new file 
            // for reading doesn't make much sense.
            FileIOPermissionAccess secAccess = FileIOPermissionAccess.NoAccess; 
#if !FEATURE_PAL && FEATURE_MACL
            if ((!useRights && (access & FileAccess.Read) != 0) || (useRights && (fileSystemRights & FileSystemRights.ReadAndExecute) != 0))
#else
            if (!useRights && (access & FileAccess.Read) != 0) 
#endif //!FEATURE_PAL && FEATURE_MACL
            { 
                if (mode==FileMode.Append) 
                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidAppendMode"));
                else 
                    secAccess = secAccess | FileIOPermissionAccess.Read;
            }
            // I can't think of any combos of FileMode we should disallow if we
            // don't have read access.  Writing would pretty much always be valid 
            // in those cases.
 
            // For any FileSystemRights other than ReadAndExecute, demand Write permission 
            // This is probably bit overkill for TakeOwnership etc but we don't have any
            // matching FileIOPermissionAccess to demand. It is better that we ask for Write permission. 

#if !FEATURE_PAL && FEATURE_MACL
            // FileMode.OpenOrCreate & FileSystemRights.Synchronize can create 0-byte file; demand write
            if ((!useRights && (access & FileAccess.Write) != 0) 
                || (useRights && (fileSystemRights & (FileSystemRights.Write | FileSystemRights.Delete
                                            | FileSystemRights.DeleteSubdirectoriesAndFiles 
                                            | FileSystemRights.ChangePermissions 
                                            | FileSystemRights.TakeOwnership)) != 0)
                || (useRights && ((fileSystemRights & FileSystemRights.Synchronize) != 0) 
                                            && mode==FileMode.OpenOrCreate)
               )
#else
            if (!useRights && (access & FileAccess.Write) != 0) 
#endif //!FEATURE_PAL && FEATURE_MACL
            { 
                if (mode==FileMode.Append) 
                    secAccess = secAccess | FileIOPermissionAccess.Append;
                else 
                    secAccess = secAccess | FileIOPermissionAccess.Write;
            }

#if !FEATURE_PAL && FEATURE_MACL 
            bool specifiedAcl;
            unsafe { 
                specifiedAcl = secAttrs != null && secAttrs.pSecurityDescriptor != null; 
            }
 
            AccessControlActions control = specifiedAcl ? AccessControlActions.Change : AccessControlActions.None;
            new FileIOPermission(secAccess, control, new String[] { filePath }, false, false).Demand();
#else
            new FileIOPermission(secAccess, new String[] { filePath }, false, false).Demand(); 
#endif
            // Our Inheritable bit was stolen from Windows, but should be set in 
            // the security attributes class.  Don't leave this bit set. 
            share &= ~FileShare.Inheritable;
 
            bool seekToEnd = (mode==FileMode.Append);
            // Must use a valid Win32 constant here...
            if (mode == FileMode.Append)
                mode = FileMode.OpenOrCreate; 

            // WRT async IO, do the right thing for whatever platform we're on. 
            // This way, someone can easily write code that opens a file 
            // asynchronously no matter what their platform is.
            if (_canUseAsync && (options & FileOptions.Asynchronous) != 0) 
                _isAsync = true;
            else
                options &= ~FileOptions.Asynchronous;
 
            int flagsAndAttributes = (int) options;
 
#if !FEATURE_PAL 
            // For mitigating local elevation of privilege attack through named pipes
            // make sure we always call CreateFile with SECURITY_ANONYMOUS so that the 
            // named pipe server can't impersonate a high privileged client security context
            flagsAndAttributes|= (Win32Native.SECURITY_SQOS_PRESENT | Win32Native.SECURITY_ANONYMOUS);
#endif
            // Don't pop up a dialog for reading from an emtpy floppy drive 
            int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
            try { 
                String tempPath = filePath; 
                if (useLongPath)
                    tempPath = Path.AddLongPathPrefix(tempPath); 
                _handle = Win32Native.SafeCreateFile(tempPath, fAccess, share, secAttrs, mode, flagsAndAttributes, Win32Native.NULL);

                if (_handle.IsInvalid) {
                    // Return a meaningful exception, using the RELATIVE path to 
                    // the file to avoid returning extra information to the caller
                    // unless they have path discovery permission, in which case 
                    // the full path is fine & useful. 

                    // NT5 oddity - when trying to open "C:\" as a FileStream, 
                    // we usually get ERROR_PATH_NOT_FOUND from the OS.  We should
                    // probably be consistent w/ every other directory.
                    int errorCode = Marshal.GetLastWin32Error();
                    if (errorCode==__Error.ERROR_PATH_NOT_FOUND && filePath.Equals(Directory.InternalGetDirectoryRoot(filePath))) 
                        errorCode = __Error.ERROR_ACCESS_DENIED;
 
                    // We need to give an exception, and preferably it would include 
                    // the fully qualified path name.  Do security check here.  If
                    // we fail, give back the msgPath, which should not reveal much. 
                    // While this logic is largely duplicated in
                    // __Error.WinIOError, we need this for
                    // IsolatedStorageFileStream.
                    bool canGiveFullPath = false; 

                    if (!bFromProxy) 
                    { 
                        try {
                            new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { _fileName }, false, false ).Demand(); 
                            canGiveFullPath = true;
                        }
                        catch(SecurityException) {}
                    } 

                    if (canGiveFullPath) 
                        __Error.WinIOError(errorCode, _fileName); 
                    else
                        __Error.WinIOError(errorCode, msgPath); 
                }
            }
            finally {
                Win32Native.SetErrorMode(oldMode); 
            }
 
            // Disallow access to all non-file devices from the FileStream 
            // constructors that take a String.  Everyone else can call
            // CreateFile themselves then use the constructor that takes an 
            // IntPtr.  Disallows "con:", "com1:", "lpt1:", etc.
            int fileType = Win32Native.GetFileType(_handle);
            if (fileType != Win32Native.FILE_TYPE_DISK) {
                _handle.Close(); 
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"));
            } 
 
#if !FEATURE_PAL
#if !FEATURE_CORECLR 
            // This is necessary for async IO using IO Completion ports via our
            // managed Threadpool API's.  This (theoretically) calls the OS's
            // BindIoCompletionCallback method, and passes in a stub for the
            // LPOVERLAPPED_COMPLETION_ROUTINE.  This stub looks at the Overlapped 
            // struct for this request and gets a delegate to a managed callback
            // from there, which it then calls on a threadpool thread.  (We allocate 
            // our native OVERLAPPED structs 2 pointers too large and store EE state 
            // & GC handles there, one to an IAsyncResult, the other to a delegate.)
            if (_isAsync) { 
                bool b = false;
                // BindHandle requires UnmanagedCode permission
                new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
                try { 
                    b = ThreadPool.BindHandle(_handle);
                } 
                finally { 
                    CodeAccessPermission.RevertAssert();
                    if (!b) { 
                        // We should close the handle so that the handle is not open until SafeFileHandle GC
                        Contract.Assert(!_exposedHandle, "Are we closing handle that we exposed/not own, how?");
                        _handle.Close();
                    } 
                }
                if (!b) 
                    throw new IOException(Environment.GetResourceString("IO.IO_BindHandleFailed")); 
            }
#endif // FEATURE_CORECLR 
#endif //!FEATURE_PAL
            if (!useRights) {
                _canRead = (access & FileAccess.Read) != 0;
                _canWrite = (access & FileAccess.Write) != 0; 
            }
#if !FEATURE_PAL && FEATURE_MACL 
            else { 
                _canRead = (fileSystemRights & FileSystemRights.ReadData) != 0;
                _canWrite = ((fileSystemRights & FileSystemRights.WriteData) != 0) 
                            || ((fileSystemRights & FileSystemRights.AppendData) != 0);
            }
#endif //!FEATURE_PAL && FEATURE_MACL
 
            _canSeek = true;
            _isPipe = false; 
            _pos = 0; 
            _bufferSize = bufferSize;
            _readPos = 0; 
            _readLen = 0;
            _writePos = 0;

            // For Append mode... 
            if (seekToEnd) {
                _appendStart = SeekCore(0, SeekOrigin.End); 
            } 
            else {
                _appendStart = -1; 
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Connect to a Wiimote paired to the PC via Bluetooth
        /// </summary>
        public void Connect()
        {
            int index = 0;
            bool found = false;
            Guid guid;

            // get the GUID of the HID class
            HIDImports.HidD_GetHidGuid(out guid);

            // get a handle to all devices that are part of the HID class
            // Fun fact:  DIGCF_PRESENT worked on my machine just fine.  I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled...
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports.SP_DEVICE_INTERFACE_DATA diData = new HIDImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // get a device interface to a single device (enumerate all devices)
            while(HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // create a detail struct and set its size
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
                // someday I should figure this out.  Thanks to Paul Miller on this...
                diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

                // actually get the detail struct
                if(HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    Debug.WriteLine(index + " " + diDetail.DevicePath + " " + Marshal.GetLastWin32Error());

                    // open a read/write handle to our device using the DevicePath returned
                    mHandle = HIDImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    // create an attributes struct and initialize the size
                    HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if(HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if(attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            Debug.WriteLine("Found it!");
                            found = true;

                            // create a nice .NET FileStream wrapping the handle above
                            mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                            // start an async read operation on it
                            BeginAsyncRead();

                            // read the calibration info from the controller
                            try
                            {
                                ReadCalibration();
                            }
                            catch
                            {
                                // if we fail above, try the alternate HID writes
                                mAltWriteMethod = true;
                                ReadCalibration();
                            }

                            // force a status check to get the state of any extensions plugged in at startup
                            GetStatus();

                            break;
                        }
                        else
                        {
                            // otherwise this isn't the controller, so close up the file handle
                            mHandle.Close();
                        }
                    }
                }
                else
                {
                    // failed to get the detail struct
                    throw new WiimoteException("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                // move to the next device
                index++;
            }

            // clean up our list
            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            // if we didn't find a Wiimote, throw an exception
            if(!found)
                throw new WiimoteException("Wiimote not found in HID device list.");
        }
            /// <summary>
            /// Open the port specified by the Port property.
            /// </summary>
            public void Open()
            {
                if (IsDisposed) throw new ObjectDisposedException("NativeSerialPort");
                if (string.IsNullOrWhiteSpace(m_Port)) throw new InvalidOperationException("Port must first be set");
                if (IsOpen) throw new InvalidOperationException("Serial Port currently open");

                m_ComPortHandle = UnsafeNativeMethods.CreateFile(@"\\.\" + m_Port,
                    NativeMethods.FileAccess.GENERIC_READ | NativeMethods.FileAccess.GENERIC_WRITE,
                    NativeMethods.FileShare.FILE_SHARE_NONE,
                    IntPtr.Zero,
                    NativeMethods.CreationDisposition.OPEN_EXISTING,
                    NativeMethods.FileAttributes.FILE_FLAG_OVERLAPPED,
                    IntPtr.Zero);
                if (m_ComPortHandle.IsInvalid) WinIOError();

                NativeMethods.FileType t = UnsafeNativeMethods.GetFileType(m_ComPortHandle);
                if (t != NativeMethods.FileType.FILE_TYPE_CHAR && t != NativeMethods.FileType.FILE_TYPE_UNKNOWN) {
                    m_ComPortHandle.Close();
                    m_ComPortHandle = null;
                    throw new IOException("Wrong Filetype: " + m_Port);
                }

                // Set the default parameters
                UnsafeNativeMethods.SetupComm(m_ComPortHandle, m_DriverInQueue, m_DriverOutQueue);

                m_CommState = new CommState(m_ComPortHandle, m_CommState);
                m_CommProperties = new CommProperties(m_ComPortHandle);
                m_CommModem = new CommModemStatus(m_ComPortHandle);
                CommOverlappedIo commIo = new CommOverlappedIo(m_ComPortHandle, m_CommIo, Port);
                m_CommIo.Dispose();
                m_CommIo = commIo;
            }
Exemplo n.º 18
0
        /// <summary>
        /// Gets disk geometry
        /// </summary>
        internal bool GetDriveGeometry(ref DISK_GEOMETRY diskGeo, int driveID, SafeFileHandle handle)
        {
            //This will serve as our output buffer
            var outBuff = IntPtr.Zero;
            //Our result
            bool bResult;
            //Dummy
            uint dummy;

            //Do our DeviceIoControl stuff
            bResult = DeviceIoControl(handle, (uint)EIOControlCode.IOCTL_DISK_GET_DRIVE_GEOMETRY, IntPtr.Zero, 0, ref diskGeo, (uint)Marshal.SizeOf(typeof(DISK_GEOMETRY)), out dummy, IntPtr.Zero);

            handle.Close();

            return (bResult);
        }
Exemplo n.º 19
0
        private void OpenWiimoteDeviceHandle(string devicePath)
        {
            // open a read/write handle to our device using the DevicePath returned
            wiiHandle = HIDImports.CreateFile(devicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

            // open a read/write handle to the PDA
            pdaHandle = HIDImports.CreateFile("\\\\.\\COM20", FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

            // create an attributes struct and initialize the size
            HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
            attrib.Size = Marshal.SizeOf(attrib);

            // get the attributes of the current device
            if(HIDImports.HidD_GetAttributes(wiiHandle.DangerousGetHandle(), ref attrib))
            {
                // if the vendor and product IDs match up
                if(attrib.VendorID == VID && attrib.ProductID == PID)
                {
                    // create a nice .NET FileStream wrapping the handle above
                    wiiStream = new FileStream(wiiHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                    // create a FileStream wrapping the pdaHandle
                    pdaStream = new FileStream(pdaHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                    // Loop and wait for the PDA to write bytes
                    PDA_ReadWriteLoop();

                }
                else
                {
                    // otherwise this isn't the controller, so close up the file handle
                    wiiHandle.Close();
                    throw new WiimoteException("Attempted to open a non-Wiimote device.");
                }
            }
        }
Exemplo n.º 20
0
		internal void FindEv3()
		{
			int index = 0;
			bool found = false;
			Guid guid;

			// get the GUID of the HID class
			HidImports.HidD_GetHidGuid(out guid);

			// get a handle to all devices that are part of the HID class
			IntPtr hDevInfo = HidImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HidImports.DIGCF_DEVICEINTERFACE | HidImports.DIGCF_PRESENT);

			// create a new interface data struct and initialize its size
			HidImports.SP_DEVICE_INTERFACE_DATA diData = new HidImports.SP_DEVICE_INTERFACE_DATA();
			diData.cbSize = Marshal.SizeOf(diData);

			// get a device interface to a single device (enumerate all devices)
			while(HidImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
			{
				UInt32 size;

				// get the buffer size for this device detail instance (returned in the size parameter)
				HidImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

				// create a detail struct and set its size
				HidImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HidImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

				// yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
				// someday I should figure this out.  Thanks to Paul Miller on this...
				diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

				// actually get the detail struct
				if(HidImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
				{
					Debug.WriteLine("{0}: {1} - {2}", index, diDetail.DevicePath, Marshal.GetLastWin32Error());

					// open a read/write handle to our device using the DevicePath returned
					_handle = HidImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HidImports.EFileAttributes.Overlapped, IntPtr.Zero);

					// create an attributes struct and initialize the size
					HidImports.HIDD_ATTRIBUTES attrib = new HidImports.HIDD_ATTRIBUTES();
					attrib.Size = Marshal.SizeOf(attrib);

					// get the attributes of the current device
					if(HidImports.HidD_GetAttributes(_handle.DangerousGetHandle(), ref attrib))
					{
						// if the vendor and product IDs match up
						if(attrib.VendorID == VID && attrib.ProductID == PID)
						{
							// it's a Ev3
							Debug.WriteLine("Found one!");
							found = true;

							IntPtr preparsedData;
							if(!HidImports.HidD_GetPreparsedData(_handle.DangerousGetHandle(), out preparsedData))
								throw new Exception("Could not get preparsed data for HID device");

							HidImports.HIDP_CAPS caps;
							if(HidImports.HidP_GetCaps(preparsedData, out caps) != HidImports.HIDP_STATUS_SUCCESS)
								throw new Exception("Could not get CAPS for HID device");

							HidImports.HidD_FreePreparsedData(ref preparsedData);

							_inputReport = new byte[caps.InputReportByteLength];
							_outputReport = new byte[caps.OutputReportByteLength];

							// create a nice .NET FileStream wrapping the handle above
							_stream = new FileStream(_handle, FileAccess.ReadWrite, _inputReport.Length, true);

							break;
						}

						_handle.Close();
					}
				}
				else
				{
					// failed to get the detail struct
					throw new Exception("SetupDiGetDeviceInterfaceDetail failed on index " + index);
				}

				// move to the next device
				index++;
			}

			// clean up our list
			HidImports.SetupDiDestroyDeviceInfoList(hDevInfo);

			// if we didn't find a EV3, throw an exception
			if(!found)
				throw new Exception("No LEGO EV3s found in HID device list.");
		}
Exemplo n.º 21
0
		///  <summary>
		///  Call HID functions that use Win32 API functions to locate a HID-class device
		///  by its Vendor ID and Product ID. Open a handle to the device.
		///  </summary>
		///          
		///  <returns>
		///   True if the device is detected, False if not detected.
		///  </returns>

		private Boolean FindTheHid()
		{
			var devicePathName = new String[128];
			String myDevicePathName = "";

			try
			{
				_deviceHandleObtained = false;
				CloseCommunications();

				//  Get the device's Vendor ID and Product ID from the form's text boxes.

				GetVendorAndProductIDsFromTextBoxes(ref _myVendorId, ref _myProductId);

				// Get the HID-class GUID.

				Guid hidGuid = _myHid.GetHidGuid();

				String functionName = "GetHidGuid";
				Debug.WriteLine(_myDebugging.ResultOfApiCall(functionName));
				Debug.WriteLine("  GUID for system HIDs: " + hidGuid.ToString());

				//  Fill an array with the device path names of all attached HIDs.

				Boolean availableHids = _myDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName);

				//  If there is at least one HID, attempt to read the Vendor ID and Product ID
				//  of each device until there is a match or all devices have been examined.

				if (availableHids)
				{
					Int32 memberIndex = 0;

					do
					{
						// Open the handle without read/write access to enable getting information about any HID, even system keyboards and mice.

						_hidHandle = _myHid.OpenHandle(devicePathName[memberIndex], false);

						functionName = "CreateFile";
						Debug.WriteLine(_myDebugging.ResultOfApiCall(functionName));
						Debug.WriteLine("  Returned handle: " + _hidHandle);

						if (!_hidHandle.IsInvalid)
						{
							// The returned handle is valid, 
							// so find out if this is the device we're looking for.

							_myHid.DeviceAttributes.Size = Marshal.SizeOf(_myHid.DeviceAttributes);

							Boolean success = _myHid.GetAttributes(_hidHandle, ref _myHid.DeviceAttributes);

							if (success)
							{
								Debug.WriteLine("  HIDD_ATTRIBUTES structure filled without error.");
								Debug.WriteLine("  Structure size: " + _myHid.DeviceAttributes.Size);
								Debug.WriteLine("  Vendor ID: " + Convert.ToString(_myHid.DeviceAttributes.VendorID, 16));
								Debug.WriteLine("  Product ID: " + Convert.ToString(_myHid.DeviceAttributes.ProductID, 16));
								Debug.WriteLine("  Version Number: " + Convert.ToString(_myHid.DeviceAttributes.VersionNumber, 16));

								if ((_myHid.DeviceAttributes.VendorID == _myVendorId) && (_myHid.DeviceAttributes.ProductID == _myProductId))
								{
									Debug.WriteLine("  Handle obtained to my device");

									//  Display the information in form's list box.

									MyMarshalDataToForm(FormActions.AddItemToListBox, "Handle obtained to my device:");
									MyMarshalDataToForm(FormActions.AddItemToListBox, "  Vendor ID= " + Convert.ToString(_myHid.DeviceAttributes.VendorID, 16));
									MyMarshalDataToForm(FormActions.AddItemToListBox, "  Product ID = " + Convert.ToString(_myHid.DeviceAttributes.ProductID, 16));
									MyMarshalDataToForm(FormActions.ScrollToBottomOfListBox, "");

									_deviceHandleObtained = true;

									myDevicePathName = devicePathName[memberIndex];
								}
								else
								{
									//  It's not a match, so close the handle.

									_deviceHandleObtained = false;
									_hidHandle.Close();
								}
							}
							else
							{
								//  There was a problem retrieving the information.

								Debug.WriteLine("  Error in filling HIDD_ATTRIBUTES structure.");
								_deviceHandleObtained = false;
								_hidHandle.Close();
							}
						}

						//  Keep looking until we find the device or there are no devices left to examine.

						memberIndex = memberIndex + 1;
					}
					while (!((_deviceHandleObtained || (memberIndex == devicePathName.Length))));
				}

				if (_deviceHandleObtained)
				{
					//  The device was detected.
					//  Learn the capabilities of the device.

					_myHid.Capabilities = _myHid.GetDeviceCapabilities(_hidHandle);

					//  Find out if the device is a system mouse or keyboard.

					_hidUsage = _myHid.GetHidUsage(_myHid.Capabilities);

					//  Get the Input report buffer size.

					GetInputReportBufferSize();
					MyMarshalDataToForm(FormActions.EnableInputReportBufferSize, "");

					//Close the handle and reopen it with read/write access.

					_hidHandle.Close();

					_hidHandle = _myHid.OpenHandle(myDevicePathName, true);

					if (_hidHandle.IsInvalid)
					{
						MyMarshalDataToForm(FormActions.AddItemToListBox, "The device is a system " + _hidUsage + ".");
						MyMarshalDataToForm(FormActions.AddItemToListBox, "Windows 2000 and later obtain exclusive access to Input and Output reports for this devices.");
						MyMarshalDataToForm(FormActions.AddItemToListBox, "Windows 8 also obtains exclusive access to Feature reports.");
						MyMarshalDataToForm(FormActions.ScrollToBottomOfListBox, "");
					}
					else
					{
						if (_myHid.Capabilities.InputReportByteLength > 0)
						{
							//  Set the size of the Input report buffer. 

							var inputReportBuffer = new Byte[_myHid.Capabilities.InputReportByteLength];

							_deviceData = new FileStream(_hidHandle, FileAccess.Read | FileAccess.Write, inputReportBuffer.Length, false);
						}

						if (_myHid.Capabilities.OutputReportByteLength > 0)
						{
							Byte[] outputReportBuffer = null;
						}
						//  Flush any waiting reports in the input buffer. (optional)

						_myHid.FlushQueue(_hidHandle);
					}
				}
				else
				{
					MyMarshalDataToForm(FormActions.AddItemToListBox, "Device not found.");
					MyMarshalDataToForm(FormActions.DisableInputReportBufferSize, "");
					EnableFormControls();
					MyMarshalDataToForm(FormActions.ScrollToBottomOfListBox, "");
				}
				return _deviceHandleObtained;
			}
			catch (Exception ex)
			{
				DisplayException(Name, ex);
				throw;
			}
		}
Exemplo n.º 22
0
        private void USBCheckIfPresent()
        {
            //WM_DEVICECHANGE messages by themselves are quite generic, and can be caused by a number of different
            //sources, not just your USB hardware device.  Therefore, must check to find out if any changes relavant
            //to your device (with known VID/PID) took place before doing any kind of opening or closing of handles/endpoints.
            //(the message could have been totally unrelated to your application/USB device)

            if (USBCheckIfPresentAndGetUSBDevicePath())	//Check and make sure at least one device with matching VID/PID is attached
            {
                //If executes to here, this means the device is currently attached and was found.
                //This code needs to decide however what to do, based on whether or not the device was previously known to be
                //attached or not.
                if ((AttachedState == false) || (AttachedButBroken == true))	//Check the previous attachment state
                {
                    uint ErrorStatusWrite;
                    uint ErrorStatusRead;

                    //We obtained the proper device path (from CheckIfPresentAndGetUSBDevicePath() function call), and it
                    //is now possible to open read and write handles to the device.
                    WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                    ErrorStatusWrite = (uint)Marshal.GetLastWin32Error();
                    ReadHandleToUSBDevice = CreateFile(DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                    ErrorStatusRead = (uint)Marshal.GetLastWin32Error();

                    if ((ErrorStatusWrite == ERROR_SUCCESS) && (ErrorStatusRead == ERROR_SUCCESS))
                    {
                        AttachedState = true;		//Let the rest of the PC application know the USB device is connected, and it is safe to read/write to it
                        AttachedButBroken = false;
                        StatusBar.Text = cnc_connected;
                    }
                    else //for some reason the device was physically plugged in, but one or both of the read/write handles didn't open successfully...
                    {
                        AttachedState = false;		//Let the rest of this application known not to read/write to the device.
                        AttachedButBroken = true;	//Flag so that next time a WM_DEVICECHANGE message occurs, can retry to re-open read/write pipes
                        if (ErrorStatusWrite == ERROR_SUCCESS)
                            WriteHandleToUSBDevice.Close();
                        if (ErrorStatusRead == ERROR_SUCCESS)
                            ReadHandleToUSBDevice.Close();
                    }
                }
                //else we did find the device, but AttachedState was already true.  In this case, don't do anything to the read/write handles,
                //since the WM_DEVICECHANGE message presumably wasn't caused by our USB device.
            }
            else	//Device must not be connected (or not programmed with correct firmware)
            {
                if (AttachedState == true)		//If it is currently set to true, that means the device was just now disconnected
                {
                    AttachedState = false;
                    WriteHandleToUSBDevice.Close();
                    ReadHandleToUSBDevice.Close();
                }
                AttachedState = false;
                AttachedButBroken = false;
            }
        }
Exemplo n.º 23
0
        ///  <summary>
        ///  Call HID functions that use Win32 API functions to locate a HID-class device
        ///  by its Vendor ID and Product ID. Open a handle to the device.
        ///  </summary>
        ///
        ///  <returns>
        ///   True if the device is detected, False if not detected.
        ///  </returns>

        private Boolean FindTheHid()
        {
            var    devicePathName   = new String[128];
            String myDevicePathName = "";

            try
            {
                _deviceHandleObtained = false;
                CloseCommunications();
                _myVendorId  = 0x16c0;
                _myProductId = 0x05df;
                // Get the HID-class GUID.
                Guid hidGuid = _myHid.GetHidGuid();

                //  Fill an array with the device path names of all attached HIDs.
                Boolean availableHids = _myDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName);

                //  If there is at least one HID, attempt to read the Vendor ID and Product ID
                //  of each device until there is a match or all devices have been examined.

                if (availableHids)
                {
                    Int32 memberIndex = 0;
                    do
                    {
                        // Open the handle without read/write access to enable getting information about any HID, even system keyboards and mice.
                        _hidHandle = _myHid.OpenHandle(devicePathName[memberIndex], false);

                        if (!_hidHandle.IsInvalid)
                        {
                            // The returned handle is valid,
                            // so find out if this is the device we're looking for.

                            //_myHid.DeviceAttributes.Size = Marshal.SizeOf(_myHid.DeviceAttributes);

                            Boolean success = _myHid.GetAttributes(_hidHandle, ref _myHid.DeviceAttributes);
                            if (success)
                            {
                                //Debug.WriteLine("  HIDD_ATTRIBUTES structure filled without error.");
                                //Debug.WriteLine("  Structure size: " + _myHid.DeviceAttributes.Size);
                                //Debug.WriteLine("  Vendor ID: " + Convert.ToString(_myHid.DeviceAttributes.VendorID, 16));
                                //Debug.WriteLine("  Product ID: " + Convert.ToString(_myHid.DeviceAttributes.ProductID, 16));
                                //Debug.WriteLine("  Version Number: " + Convert.ToString(_myHid.DeviceAttributes.VersionNumber, 16));

                                if ((_myHid.DeviceAttributes.VendorID == _myVendorId) && (_myHid.DeviceAttributes.ProductID == _myProductId))
                                {
                                    //Debug.WriteLine("  Handle obtained to my device");
                                    //  Display the information in form's list box.
                                    //InfoBox.Text += "\nHandle obtained to my device:";
                                    InfoBox.Text          = "  VID=" + Convert.ToString(_myHid.DeviceAttributes.VendorID, 16);
                                    InfoBox.Text         += "  PID=" + Convert.ToString(_myHid.DeviceAttributes.ProductID, 16);
                                    _deviceHandleObtained = true;

                                    myDevicePathName = devicePathName[memberIndex];
                                }
                                else
                                {
                                    //  It's not a match, so close the handle.

                                    _deviceHandleObtained = false;
                                    _hidHandle.Close();
                                }
                            }
                            else
                            {
                                //  There was a problem retrieving the information.

                                //Debug.WriteLine("  Error in filling HIDD_ATTRIBUTES structure.");
                                _deviceHandleObtained = false;
                                _hidHandle.Close();
                            }
                        }

                        //  Keep looking until we find the device or there are no devices left to examine.

                        memberIndex = memberIndex + 1;
                    }while (!((_deviceHandleObtained || (memberIndex == devicePathName.Length))));
                }

                if (_deviceHandleObtained)
                {
                    //  The device was detected.
                    //  Learn the capabilities of the device.

                    _myHid.Capabilities = _myHid.GetDeviceCapabilities(_hidHandle);

                    //  Find out if the device is a system mouse or keyboard.
                    _hidUsage = _myHid.GetHidUsage(_myHid.Capabilities);

                    //Close the handle and reopen it with read/write access.
                    _hidHandle.Close();
                    _hidHandle = _myHid.OpenHandle(myDevicePathName, true);
                    if (_hidHandle.IsInvalid)
                    {
                        InfoBox.Text += "The device is a system " + _hidUsage + ".";
                    }
                    else
                    {
                        if (_myHid.Capabilities.InputReportByteLength > 0)
                        {
                            //  Set the size of the Input report buffer.
                            var inputReportBuffer = new Byte[_myHid.Capabilities.InputReportByteLength];
                            _deviceData    = new FileStream(_hidHandle, FileAccess.Read | FileAccess.Write, inputReportBuffer.Length, false);
                            inputReportBuf = new Byte[_myHid.Capabilities.InputReportByteLength];
                        }

                        if (_myHid.Capabilities.OutputReportByteLength > 0)
                        {
                            Byte[] outputReportBuffer = null;
                        }
                        //  Flush any waiting reports in the input buffer. (optional)
                        _myHid.FlushQueue(_hidHandle);
                    }
                    ErrorBox.Text = "";
                }
                else
                {
                    ErrorBox.Text = "Device not found.";
                }
                return(_deviceHandleObtained);
            }
            catch (Exception ex)
            {
                DisplayException(Name, ex);
                throw;
            }
        }
Exemplo n.º 24
0
        void Read(SafeFileHandle handle)
        {
            FileStream stream = new FileStream(handle, FileAccess.ReadWrite, (int)BUFFER_SIZE, true);
            byte[] buffer = new byte[BUFFER_SIZE];
            ASCIIEncoding encoder = new ASCIIEncoding();

            while (true)
            {
                int bytesRead = 0;

                try
                {
                    bytesRead = stream.Read(buffer, 0, (int)BUFFER_SIZE);
                }
                catch
                {
                    //read error has occurred
                    break;
                }

                //client has disconnected
                if (bytesRead == 0)
                    break;

                //fire message received event
                if (this.MessageReceived != null)
                    this.MessageReceived(encoder.GetString(buffer, 0, bytesRead));
            }

            handle.Close();
        }
Exemplo n.º 25
0
        internal static void FindWiimote(WiimoteFoundDelegate wiimoteFound)
        {
            int index = 0;
            bool found = false;
            Guid guid;
            SafeFileHandle mHandle;

            // get the GUID of the HID class
            HIDImports.HidD_GetHidGuid(out guid);

            // get a handle to all devices that are part of the HID class
            // Fun fact:  DIGCF_PRESENT worked on my machine just fine.  I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled...
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports.SP_DEVICE_INTERFACE_DATA diData = new HIDImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // get a device interface to a single device (enumerate all devices)
            while(HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // create a detail struct and set its size
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
                // someday I should figure this out.  Thanks to Paul Miller on this...
                diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

                // actually get the detail struct
                if(HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    Debug.WriteLine(string.Format("{0}: {1} - {2}", index, diDetail.DevicePath, Marshal.GetLastWin32Error()));

                    // open a read/write handle to our device using the DevicePath returned
                    mHandle = HIDImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    // create an attributes struct and initialize the size
                    HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if(HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if(attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            // it's a Wiimote
                            Debug.WriteLine("Found one!");
                            found = true;

                            // fire the callback function...if the callee doesn't care about more Wiimotes, break out
                            if(!wiimoteFound(diDetail.DevicePath))
                                break;
                        }
                    }
                    mHandle.Close();
                }
                else
                {
                    // failed to get the detail struct
                    throw new WiimoteException("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                // move to the next device
                index++;
            }

            // clean up our list
            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            // if we didn't find a Wiimote, throw an exception
            if(!found)
                throw new WiimoteNotFoundException("No Wiimotes found in HID device list.");
        }
Exemplo n.º 26
0
        internal void FindEv3()
        {
            int  index = 0;
            bool found = false;
            Guid guid;

            // get the GUID of the HID class
            HidImports.HidD_GetHidGuid(out guid);

            // get a handle to all devices that are part of the HID class
            IntPtr hDevInfo = HidImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HidImports.DIGCF_DEVICEINTERFACE | HidImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HidImports.SP_DEVICE_INTERFACE_DATA diData = new HidImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // get a device interface to a single device (enumerate all devices)
            while (HidImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HidImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // create a detail struct and set its size
                HidImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HidImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
                // someday I should figure this out.  Thanks to Paul Miller on this...
                diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

                // actually get the detail struct
                if (HidImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    Debug.WriteLine("{0}: {1} - {2}", index, diDetail.DevicePath, Marshal.GetLastWin32Error());

                    // open a read/write handle to our device using the DevicePath returned
                    _handle = HidImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HidImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    // create an attributes struct and initialize the size
                    HidImports.HIDD_ATTRIBUTES attrib = new HidImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if (HidImports.HidD_GetAttributes(_handle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if (attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            // it's a Ev3
                            Debug.WriteLine("Found one!");
                            found = true;

                            IntPtr preparsedData;
                            if (!HidImports.HidD_GetPreparsedData(_handle.DangerousGetHandle(), out preparsedData))
                            {
                                throw new Exception("Could not get preparsed data for HID device");
                            }

                            HidImports.HIDP_CAPS caps;
                            if (HidImports.HidP_GetCaps(preparsedData, out caps) != HidImports.HIDP_STATUS_SUCCESS)
                            {
                                throw new Exception("Could not get CAPS for HID device");
                            }

                            HidImports.HidD_FreePreparsedData(ref preparsedData);

                            _inputReport  = new byte[caps.InputReportByteLength];
                            _outputReport = new byte[caps.OutputReportByteLength];

                            // create a nice .NET FileStream wrapping the handle above
                            _stream = new FileStream(_handle, FileAccess.ReadWrite, _inputReport.Length, true);

                            break;
                        }

                        _handle.Close();
                    }
                }
                else
                {
                    // failed to get the detail struct
                    throw new Exception("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                // move to the next device
                index++;
            }

            // clean up our list
            HidImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            // if we didn't find a EV3, throw an exception
            if (!found)
            {
                throw new Exception("No LEGO EV3s found in HID device list.");
            }
        }
        public static bool TryConnect(ReportDevice device, Stream deviceStream, string devicePath, SafeFileHandle fileHandle)
        {
            bool success;
            try
            {
                device.Initialize();

                ((MsHidDeviceInfo)device.DeviceInfo).DevicePath = devicePath;
                SetDevicePathConnected(devicePath, true);
                success = true;
            }
            catch (TimeoutException)
            {
                device.Disconnect();
                deviceStream.Dispose();
                fileHandle.Close();
                success = false;
            }
            return success;
        }
Exemplo n.º 28
0
        IList <string> FindHidDevicePathList()
        {
            // TODO: MUSTDO: fix for multiple device connection
            // Use UpdateDevicePathIfDevicePathIsNullOrEmpty() in normal use case.
            // Because if you always use this method in every HID access, CPU usage increase from <1% to 5%-10%.
            // And the UpdateDevicePath() occupies 87.8% of all application CPU times.

            // TODO: MUSTDO: GetInstalledDeviceDevicePathListByInterfaceClassGuid duplicated.  This is not deleted because this code may be faster since it does not get Capability and this was correct.
            // TODO: MUSTDO: Like GetInstalledDeviceDevicePathListByInterfaceClassGuid, it should detect when the app starts and device connection status changes.
            var ret = new List <string>();

            // TODO: MUSTDO: ProductIdは0xA001に統一される。
            foreach (var targetHidGuid in TargetHidGuidList)
            {
                int index = 0;
                // copy
                Guid hidGuid = targetHidGuid;
                NativeMethods.SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA();
                deviceInterfaceData.cbSize = (uint)Marshal.SizeOf(deviceInterfaceData);

                // Enumerate devices.
                var hDevInfo = NativeMethods.SetupDiGetClassDevs(ref hidGuid, IntPtr.Zero, IntPtr.Zero, NativeMethods.DIGCF_DEVICEINTERFACE | NativeMethods.DIGCF_PRESENT);

                while (NativeMethods.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref hidGuid, index, ref deviceInterfaceData))
                {
                    UInt32 size;
                    NativeMethods.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref deviceInterfaceData, IntPtr.Zero, 0, out size, IntPtr.Zero);
                    NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA();
                    deviceInterfaceDetailData.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);
                    // Get detail information
                    NativeMethods.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref deviceInterfaceData, ref deviceInterfaceDetailData, size, out size, IntPtr.Zero);
                    //Debug.WriteLine(index + " " + deviceInterfaceDetailData.DevicePath + " " + Marshal.GetLastWin32Error());

                    // open a read/write handle to our device using the DevicePath returned
                    SafeFileHandle handle = null;
                    try
                    {
                        handle = NativeMethods.CreateFile(deviceInterfaceDetailData.DevicePath, 0, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, NativeMethods.EFileAttributes.Overlapped, IntPtr.Zero);
                        // create an attributes struct and initialize the size
                        NativeMethods.HIDD_ATTRIBUTES attrib = new NativeMethods.HIDD_ATTRIBUTES();
                        attrib.Size = (uint)Marshal.SizeOf(attrib);
                        // get the attributes of the current device
                        if (NativeMethods.HidD_GetAttributes(handle.DangerousGetHandle(), ref attrib))
                        {
                            //Debug.WriteLine(deviceInterfaceDetailData.DevicePath + " " + attrib.VendorID +" / " +attrib.ProductID);

                            // if the vendor and product IDs match up
                            if (attrib.VendorID != VendorId)
                            {
                                continue;
                            }
                            if (attrib.ProductID != ProductId)
                            {
                                continue;
                            }
                            var lowered = deviceInterfaceDetailData.DevicePath.ToLower(System.Globalization.CultureInfo.InvariantCulture);
                            if (lowered.Contains(HidEgsGestureInterfaceTag) == false)
                            {
                                continue;
                            }
                            if (lowered.Contains(HidEgsGestureInterface_VendorSpecificCollectionTag) == false)
                            {
                                continue;
                            }
                            ret.Add(deviceInterfaceDetailData.DevicePath);
                        }
                    }
                    finally
                    {
                        handle.Close();
                        index++;
                    }
                }
            }
            return(ret);
        }
Exemplo n.º 29
0
        ///  <summary>
        ///  Uses a series of API calls to locate a HID-class device
        ///  by its Vendor ID and Product ID.
        ///  Fills myDevicePathName with a path to device found, readHandle and writeHandle. Registers for Device Notifications (attached / detached type of events).
        ///  </summary>
        ///
        ///  <returns>
        ///   True if the device is detected, False if not detected.
        ///  </returns>

        private Boolean FindTheHid(Int32 myVendorID, Int32 myProductID)
        {
            Boolean someHidDevicesFound = false;

            String[] devicePathName = new String[128];
            String   functionName   = "";
            Guid     hidGuid        = Guid.Empty;
            Int32    memberIndex    = 0;
            Boolean  success        = false;

            try
            {
                myDeviceDetected = false;

                Tracer.Trace(string.Format("FindTheHid(0x{0:X04}, 0x{1:X04})", myVendorID, myProductID));

                //  ***
                //  API function: 'HidD_GetHidGuid

                //  Purpose: Retrieves the interface class GUID for the HID class.

                //  Accepts: 'A System.Guid object for storing the GUID.
                //  ***

                Hid.HidD_GetHidGuid(ref hidGuid);

                functionName = "GetHidGuid";
                Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
                Tracer.Trace("  GUID for system HIDs: " + hidGuid.ToString());

                //  Fill an array with the device path names of all attached HIDs.

                someHidDevicesFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName);

                //  If there is at least one HID, attempt to read the Vendor ID and Product ID
                //  of each device until there is a match or all devices have been examined.
                //
                //  Fill myDevicePathName with a path to device found.

                if (someHidDevicesFound)
                {
                    memberIndex = 0;

                    // Tracer.Trace("  total number of HID devices: " + devicePathName.Length);        // will be something like 128, a lot of empty paths there.

                    do
                    {
                        //  ***
                        //  API function:
                        //  CreateFile

                        //  Purpose:
                        //  Retrieves a handle to a device.

                        //  Accepts:
                        //  A device path name returned by SetupDiGetDeviceInterfaceDetail
                        //  The type of access requested (read/write).
                        //  FILE_SHARE attributes to allow other processes to access the device while this handle is open.
                        //  A Security structure or IntPtr.Zero.
                        //  A creation disposition value. Use OPEN_EXISTING for devices.
                        //  Flags and attributes for files. Not used for devices.
                        //  Handle to a template file. Not used.

                        //  Returns: a handle without read or write access.
                        //  This enables obtaining information about all HIDs, even system
                        //  keyboards and mice.
                        //  Separate handles are used for reading and writing.
                        //  ***

                        if (!string.IsNullOrEmpty(devicePathName[memberIndex]))
                        {
                            Tracer.Trace("  trying HID device path '" + devicePathName[memberIndex] + "'");

                            hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);

                            functionName = "CreateFile";
                            Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
                            Tracer.Trace("  FindTheHid(): some HID device found, returned handle: " + hidHandle.ToString());

                            if (!hidHandle.IsInvalid)
                            {
                                //  The returned handle is valid,
                                //  so find out if this is the device we're looking for.

                                //  Set the Size property of DeviceAttributes to the number of bytes in the structure.

                                MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes);

                                //  ***
                                //  API function:
                                //  HidD_GetAttributes

                                //  Purpose:
                                //  Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID,
                                //  Product ID, and Product Version Number for a device.

                                //  Accepts:
                                //  A handle returned by CreateFile.
                                //  A pointer to receive a HIDD_ATTRIBUTES structure.

                                //  Returns:
                                //  True on success, False on failure.
                                //  ***

                                success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes);

                                if (success)
                                {
                                    Tracer.Trace("  HIDD_ATTRIBUTES structure filled without error.");
                                    Tracer.Trace("  Structure size: " + MyHid.DeviceAttributes.Size);
                                    Tracer.Trace(string.Format("  Vendor ID: 0x{0:X04}", MyHid.DeviceAttributes.VendorID));
                                    Tracer.Trace(string.Format("  Product ID: 0x{0:X04}", MyHid.DeviceAttributes.ProductID));
                                    Tracer.Trace(string.Format("  Version Number: 0x{0:X04}", MyHid.DeviceAttributes.VersionNumber));

                                    //  Find out if the device matches the one we're looking for.

                                    if ((MyHid.DeviceAttributes.VendorID == myVendorID) && (MyHid.DeviceAttributes.ProductID == myProductID))
                                    {
                                        Tracer.Trace("  My device detected");

                                        myDeviceDetected = true;

                                        //  Save the DevicePathName for OnDeviceChange().

                                        myDevicePathName = devicePathName[memberIndex];
                                    }
                                    else
                                    {
                                        //  It's not a match, so close the handle.

                                        Tracer.Trace("  (This is not My Device)");

                                        myDeviceDetected = false;
                                        hidHandle.Close();
                                    }
                                }
                                else
                                {
                                    //  There was a problem in retrieving the information.

                                    Tracer.Trace("  Error in filling HIDD_ATTRIBUTES structure.");
                                    myDeviceDetected = false;
                                    hidHandle.Close();
                                }
                            }
                        }

                        //  Keep looking until we find the device or there are no devices left to examine.

                        memberIndex = memberIndex + 1;
                    }while (!((myDeviceDetected || (memberIndex == devicePathName.Length))));
                }

                if (myDeviceDetected)
                {
                    //  The device was detected.
                    //  Register to receive notifications if the device is removed or attached.

                    success = MyDeviceManagement.RegisterForDeviceNotifications(myDevicePathName, WindowHandle, hidGuid, ref deviceNotificationHandle);

                    Tracer.Trace("RegisterForDeviceNotifications = " + success);

                    //  Learn the capabilities of the device.

                    MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle);

                    if (success)
                    {
                        //  Find out if the device is a system mouse or keyboard.

                        hidUsage = MyHid.GetHidUsage(MyHid.Capabilities);

                        //  Get the Input report buffer size.

                        GetInputReportBufferSize();

                        //  Get handles to use in requesting Input and Output reports.

                        readHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, FileIO.FILE_FLAG_OVERLAPPED, 0);

                        functionName = "CreateFile, ReadHandle";
                        Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
                        Tracer.Trace("  FindTheHid(): success, returned handle: " + readHandle.ToString());

                        if (readHandle.IsInvalid)
                        {
                            exclusiveAccess = true;
                            Tracer.Error("The device is a system " + hidUsage + ". Applications can access Feature reports only.");
                        }
                        else
                        {
                            writeHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);

                            functionName = "CreateFile, WriteHandle";
                            Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
                            Tracer.Trace("  FindTheHid(): handle valid, returned handle: " + writeHandle.ToString());

                            //  Flush any waiting reports in the input buffer. (optional)

                            MyHid.FlushQueue(readHandle);
                        }
                    }
                }
                else
                {
                    //  The device wasn't detected.

                    Tracer.Error(string.Format("My Device not found - need a HID with vendorId={0}, productId={1}.", vendorId, productId));
                }
                return(myDeviceDetected);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex);
                throw;
            }
        }
        public static bool Start()
        {
            Guid guid;

            HIDImports.SP_DEVICE_INTERFACE_DATA sp_device_interface_data = new HIDImports.SP_DEVICE_INTERFACE_DATA()
            {
                cbSize = Marshal.SizeOf(typeof(HIDImports.SP_DEVICE_INTERFACE_DATA))
            };

            if (_stream != null)
            {
                throw new InvalidOperationException("No Stream!");
            }

            HIDImports.HidD_GetHidGuid(out guid);
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, 0x10);

            int num = 0;

            while (HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, num++, ref sp_device_interface_data))
            {
                uint num2;
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA {
                    cbSize = (IntPtr.Size == 8) ? (uint)8 : (uint)5
                };

                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref sp_device_interface_data, IntPtr.Zero, 0, out num2, IntPtr.Zero);
                if (HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref sp_device_interface_data, ref deviceInterfaceDetailData, num2, out num2, IntPtr.Zero))
                {
                    HIDImports.HIDD_ATTRIBUTES hidd_attributes = new HIDImports.HIDD_ATTRIBUTES()
                    {
                        Size = Marshal.SizeOf(typeof(HIDImports.HIDD_ATTRIBUTES))
                    };

                    SafeFileHandle handle = HIDImports.CreateFile(deviceInterfaceDetailData.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    if (HIDImports.HidD_GetAttributes(handle.DangerousGetHandle(), ref hidd_attributes))
                    {
                        if (IsAppleWirelessKeyboard(hidd_attributes.VendorID, hidd_attributes.ProductID))
                        {
                            _stream = new FileStream(handle, FileAccess.ReadWrite, 0x16, true);
                            //break;
                        }
                        else
                        {
                            handle.Close();
                        }
                    }
                }
            }

            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            if (_stream != null)
            {
                byte[] buffer = new byte[0x16];
                _stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(SpecialKeyStateChanged), buffer);
                return(true);
            }
            return(false);
        }
Exemplo n.º 31
0
        public static string ExecuteShellCommand(int PPID, bool BlockDLLs, string Command)
        {
            var saHandles = new SECURITY_ATTRIBUTES();

            saHandles.nLength              = Marshal.SizeOf(saHandles);
            saHandles.bInheritHandle       = true;
            saHandles.lpSecurityDescriptor = IntPtr.Zero;

            IntPtr hStdOutRead;
            IntPtr hStdOutWrite;
            IntPtr hDupStdOutWrite = IntPtr.Zero;

            CreatePipe(
                out hStdOutRead,
                out hStdOutWrite,
                ref saHandles,
                0);

            SetHandleInformation(
                hStdOutRead,
                HANDLE_FLAGS.INHERIT,
                0);

            var pInfo = new PROCESS_INFORMATION();
            var siEx  = new STARTUPINFOEX();

            siEx.StartupInfo.cb         = Marshal.SizeOf(siEx);
            siEx.StartupInfo.hStdErr    = hStdOutWrite;
            siEx.StartupInfo.hStdOutput = hStdOutWrite;

            string result = string.Empty;

            try
            {
                var lpSize = IntPtr.Zero;
                if (BlockDLLs)
                {
                    InitializeProcThreadAttributeList(
                        IntPtr.Zero,
                        2,
                        0,
                        ref lpSize);

                    siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);

                    InitializeProcThreadAttributeList(
                        siEx.lpAttributeList,
                        2,
                        0,
                        ref lpSize);

                    var lpMitigationPolicy = Marshal.AllocHGlobal(IntPtr.Size);
                    Marshal.WriteInt64(lpMitigationPolicy, (long)BINARY_SIGNATURE_POLICY.PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON);

                    UpdateProcThreadAttribute(
                        siEx.lpAttributeList,
                        0,
                        0x20007,
                        lpMitigationPolicy,
                        (IntPtr)IntPtr.Size,
                        IntPtr.Zero,
                        IntPtr.Zero);
                }
                else
                {
                    InitializeProcThreadAttributeList(
                        IntPtr.Zero,
                        1,
                        0,
                        ref lpSize);

                    siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);

                    InitializeProcThreadAttributeList(
                        siEx.lpAttributeList,
                        1,
                        0,
                        ref lpSize);
                }

                var parentHandle = OpenProcess(
                    0x0080 | 0x0040,
                    false,
                    PPID);

                var lpParentProcess = Marshal.AllocHGlobal(IntPtr.Size);
                Marshal.WriteIntPtr(lpParentProcess, parentHandle);

                UpdateProcThreadAttribute(
                    siEx.lpAttributeList,
                    0,
                    0x00020000,
                    lpParentProcess,
                    (IntPtr)IntPtr.Size,
                    IntPtr.Zero,
                    IntPtr.Zero);

                var hCurrent = Process.GetCurrentProcess().Handle;

                DuplicateHandle(
                    hCurrent,
                    hStdOutWrite,
                    parentHandle,
                    ref hDupStdOutWrite,
                    0,
                    true,
                    0x00000001 | 0x00000002);

                siEx.StartupInfo.hStdErr    = hDupStdOutWrite;
                siEx.StartupInfo.hStdOutput = hDupStdOutWrite;

                siEx.StartupInfo.dwFlags     = 0x00000001 | 0x00000100;
                siEx.StartupInfo.wShowWindow = 0;

                var ps = new SECURITY_ATTRIBUTES();
                var ts = new SECURITY_ATTRIBUTES();
                ps.nLength = Marshal.SizeOf(ps);
                ts.nLength = Marshal.SizeOf(ts);

                CreateProcess(
                    null,
                    Command,
                    ref ps,
                    ref ts,
                    true,
                    CREATION_FLAGS.CREATE_NO_WINDOW | CREATION_FLAGS.EXTENDED_STARTUPINFO_PRESENT,
                    IntPtr.Zero,
                    null,
                    ref siEx,
                    out pInfo);

                var safeHandle = new SafeFileHandle(hStdOutRead, false);
                var encoding   = Encoding.GetEncoding(GetConsoleOutputCP());
                var reader     = new StreamReader(new FileStream(safeHandle, FileAccess.Read, 4096, false), encoding, true);

                var exit = false;

                try
                {
                    do
                    {
                        if (WaitForSingleObject(pInfo.hProcess, 100) == 0)
                        {
                            exit = true;
                        }

                        char[] buf = null;
                        int    bytesRead;
                        uint   bytesToRead = 0;

                        var peekRet = PeekNamedPipe(
                            hStdOutRead,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            ref bytesToRead,
                            IntPtr.Zero);

                        if (peekRet == true && bytesToRead == 0)
                        {
                            if (exit == true)
                            {
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }

                        if (bytesToRead > 4096)
                        {
                            bytesToRead = 4096;
                        }

                        buf       = new char[bytesToRead];
                        bytesRead = reader.Read(buf, 0, buf.Length);
                        if (bytesRead > 0)
                        {
                            result += new string(buf);
                        }
                    } while (true);
                    reader.Close();
                }
                catch { }
                finally
                {
                    safeHandle.Close();
                }

                CloseHandle(hStdOutRead);
            }
            catch { }
            finally
            {
                DeleteProcThreadAttributeList(siEx.lpAttributeList);
                Marshal.FreeHGlobal(siEx.lpAttributeList);
                CloseHandle(pInfo.hProcess);
                CloseHandle(pInfo.hThread);
            }

            return(result);
        }
Exemplo n.º 32
0
 public void Close()
 {
     FlushFileBuffers(iFile);
     iFile.Close();
 }
Exemplo n.º 33
0
        void ListenForClients()
        {
            SECURITY_DESCRIPTOR sd = new SECURITY_DESCRIPTOR();

            // set the Security Descriptor to be completely permissive
            InitializeSecurityDescriptor(ref sd, SECURITY_DESCRIPTOR_REVISION);
            SetSecurityDescriptorDacl(ref sd, true, IntPtr.Zero, false);

            IntPtr ptrSD = Marshal.AllocCoTaskMem(Marshal.SizeOf(sd));

            Marshal.StructureToPtr(sd, ptrSD, false);

            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES
            {
                nLength = Marshal.SizeOf(sd),
                lpSecurityDescriptor = ptrSD,
                bInheritHandle       = 1
            };

            IntPtr ptrSA = Marshal.AllocCoTaskMem(Marshal.SizeOf(sa));

            Marshal.StructureToPtr(sa, ptrSA, false);


            while (true)
            {
                // Creates an instance of a named pipe for one client
                SafeFileHandle clientHandle =
                    CreateNamedPipe(
                        PipeName,

                        // DUPLEX | FILE_FLAG_OVERLAPPED = 0x00000003 | 0x40000000;
                        0x40000003,
                        0,
                        255,
                        BUFFER_SIZE,
                        BUFFER_SIZE,
                        0,
                        ptrSA);

                //could not create named pipe instance
                if (clientHandle.IsInvalid)
                {
                    continue;
                }

                int success = ConnectNamedPipe(clientHandle, IntPtr.Zero);

                //could not connect client
                if (success == 0)
                {
                    // close the handle, and wait for the next client
                    clientHandle.Close();
                    continue;
                }

                Client client = new Client
                {
                    handle = clientHandle
                };

                lock (clients)
                    clients.Add(client);

                Thread readThread = new Thread(Read)
                {
                    IsBackground = true
                };
                readThread.Start(client);
            }

            // free up the ptrs (never reached due to infinite loop)
            // Marshal.FreeCoTaskMem(ptrSD);
            // Marshal.FreeCoTaskMem(ptrSA);
        }
Exemplo n.º 34
0
        // this method is used by SerialPort upon SerialStream's creation
        internal SerialStream(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeout, int writeTimeout, Handshake handshake,
                              bool dtrEnable, bool rtsEnable, bool discardNull, byte parityReplace)
        {
            if (portName == null)
            {
                throw new ArgumentException(SR.Arg_InvalidSerialPort, nameof(portName));
            }

            // Error checking done in SerialPort.

            SafeFileHandle tempHandle = OpenPort(portName);

            if (tempHandle.IsInvalid)
            {
                throw new ArgumentException(SR.Arg_InvalidSerialPort, nameof(portName));
            }

            try
            {
                _handle = tempHandle;
                // set properties of the stream that exist as members in SerialStream
                _portName     = portName;
                _handshake    = handshake;
                _parity       = parity;
                _readTimeout  = readTimeout;
                _writeTimeout = writeTimeout;
                _baudRate     = baudRate;
                _stopBits     = stopBits;
                _dataBits     = dataBits;
                _parity       = parity;

                if (Interop.Termios.TermiosReset(_handle, _baudRate, _dataBits, _stopBits, _parity, _handshake) != 0)
                {
                    throw new ArgumentException();
                }

                DtrEnable = dtrEnable;
                // query and cache the initial RtsEnable value
                // so that set_RtsEnable can do the (value != rtsEnable) optimization
                //_rtsEnable = (GetDcbFlag(NativeMethods.FRTSCONTROL) == NativeMethods.RTS_CONTROL_ENABLE);
                _rtsEnable = RtsEnable;

                BaudRate = baudRate;

                // now set this.RtsEnable to the specified value.
                // Handshake takes precedence, this will be a nop if
                // handshake is either RequestToSend or RequestToSendXOnXOff
                if ((handshake != Handshake.RequestToSend && handshake != Handshake.RequestToSendXOnXOff))
                {
                    RtsEnable = rtsEnable;
                }
            }
            catch
            {
                // if there are any exceptions after the call to CreateFile, we need to be sure to close the
                // handle before we let them continue up.
                tempHandle.Close();
                _handle = null;
                throw;
            }
        }
Exemplo n.º 35
0
        internal static void FindWiimote(WiimoteFoundDelegate wiimoteFound)
        {
            int            index = 0;
            bool           found = false;
            Guid           guid;
            SafeFileHandle wiiHandle;

            // get the GUID of the HID class
            HIDImports.HidD_GetHidGuid(out guid);

            // get a handle to all devices that are part of the HID class
            // Fun fact:  DIGCF_PRESENT worked on my machine just fine.  I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled...
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports.DIGCF_DEVICEINTERFACE);            // | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports.SP_DEVICE_INTERFACE_DATA diData = new HIDImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // get a device interface to a single device (enumerate all devices)
            while (HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // create a detail struct and set its size
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
                // someday I should figure this out.  Thanks to Paul Miller on this...
                diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

                // actually get the detail struct
                if (HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    Debug.WriteLine(string.Format("{0}: {1} - {2}", index, diDetail.DevicePath, Marshal.GetLastWin32Error()));

                    // open a read/write handle to our device using the DevicePath returned
                    wiiHandle = HIDImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    // create an attributes struct and initialize the size
                    HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if (HIDImports.HidD_GetAttributes(wiiHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if (attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            // it's a Wiimote
                            Debug.WriteLine("Found one!");
                            found = true;

                            // fire the callback function...if the callee doesn't care about more Wiimotes, break out
                            if (!wiimoteFound(diDetail.DevicePath))
                            {
                                break;
                            }
                        }
                    }
                    wiiHandle.Close();
                }
                else
                {
                    // failed to get the detail struct
                    throw new WiimoteException("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                // move to the next device
                index++;
            }

            // clean up our list
            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            // if we didn't find a Wiimote, throw an exception
            if (!found)
            {
                throw new WiimoteNotFoundException("No Wiimotes found in HID device list.");
            }
        }
Exemplo n.º 36
0
        internal static SafeFileHandle CreateFileCore(KernelTransaction transaction, string path, ExtendedFileAttributes attributes, FileSecurity fileSecurity, FileMode fileMode, FileSystemRights fileSystemRights, FileShare fileShare, bool checkPath, PathFormat pathFormat)
        {
            if (checkPath && pathFormat == PathFormat.RelativePath)
            {
                Path.CheckSupportedPathFormat(path, true, true);
            }

            // When isFile == null, we're working with a device.
            // When opening a VOLUME or removable media drive (for example, a floppy disk drive or flash memory thumb drive),
            // the path string should be the following form: "\\.\X:"
            // Do not use a trailing backslash (\), which indicates the root.

            string pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);

            PrivilegeEnabler privilegeEnabler = null;


            // CreateFileXxx() does not support FileMode.Append mode.
            if (fileMode == FileMode.Append)
            {
                fileMode          = FileMode.OpenOrCreate;
                fileSystemRights &= FileSystemRights.AppendData; // Add right.
            }


            if (fileSecurity != null)
            {
                fileSystemRights |= (FileSystemRights)0x1000000; // Set right.
            }
            // AccessSystemSecurity = 0x1000000    AccessSystemAcl access type.
            // MaximumAllowed       = 0x2000000    MaximumAllowed  access type.

            if ((fileSystemRights & (FileSystemRights)0x1000000) != 0 ||
                (fileSystemRights & (FileSystemRights)0x2000000) != 0)
            {
                privilegeEnabler = new PrivilegeEnabler(Privilege.Security);
            }


            using (privilegeEnabler)
                using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(fileSecurity))
                {
                    SafeFileHandle handle = transaction == null || !NativeMethods.IsAtLeastWindowsVista

                                            // CreateFile() / CreateFileTransacted()
                                            // In the ANSI version of this function, the name is limited to MAX_PATH characters.
                                            // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
                                            // 2013-01-13: MSDN confirms LongPath usage.

               ? NativeMethods.CreateFile(pathLp, fileSystemRights, fileShare, securityAttributes, fileMode, attributes, IntPtr.Zero)
               : NativeMethods.CreateFileTransacted(pathLp, fileSystemRights, fileShare, securityAttributes, fileMode, attributes, IntPtr.Zero, transaction.SafeHandle, IntPtr.Zero, IntPtr.Zero);

                    int lastError = Marshal.GetLastWin32Error();

                    if (handle != null && handle.IsInvalid)
                    {
                        handle.Close();
                        NativeError.ThrowException(lastError, pathLp);
                    }

                    return(handle);
                }
        }
Exemplo n.º 37
0
 public void Close()
 {
     m_hFile.Close();
 }
Exemplo n.º 38
0
        // A Volume could be on many physical drives.
        // Returns a list of string containing each physical drive the volume uses.
        // For CD Drives with no disc in it will return an empty list.
        private List <string> GetPhysicalDriveStrings(DriveInfo driveInfo)
        {
            SafeFileHandle sfh            = null;
            List <string>  physicalDrives = new List <string>(1);
            string         path           = "\\\\.\\" + driveInfo.RootDirectory.ToString().TrimEnd('\\');

            try
            {
                sfh = NativeMethods.CreateFile(path, 0, FileShareRead | Filesharewrite, IntPtr.Zero, OpenExisting, 0, IntPtr.Zero);

                int         bytesReturned  = 0;
                DiskExtents de1            = new DiskExtents();
                int         numDiskExtents = 0;
                bool        result         = NativeMethods.DeviceIoControl(sfh
                                                                           , IoctlVolumeGetVolumeDiskExtents
                                                                           , IntPtr.Zero
                                                                           , 0
                                                                           , ref de1
                                                                           , Marshal.SizeOf(de1)
                                                                           , ref bytesReturned, IntPtr.Zero);
                DiskExtents de1Cast = (DiskExtents)de1;
                if (result == true)
                {
                    // there was only one disk extent. So the volume lies on 1 physical drive.
                    physicalDrives.Add("\\\\.\\PhysicalDrive" + de1Cast.first.DiskNumber.ToString());
                    return(physicalDrives);
                }
                if (Marshal.GetLastWin32Error() == IncorrectFunction)
                {
                    // The drive is removable and removed, like a CDRom with nothing in it.
                    return(physicalDrives);
                }
                if (Marshal.GetLastWin32Error() == MoreDataIsAvailable)
                {
                    // This drive is part of a mirror or volume - handle it below.
                }
                else if (Marshal.GetLastWin32Error() != ErrorInsufficientBuffer)
                {
                    throw new Win32Exception();
                }
                // Houston, we have a spanner. The volume is on multiple disks.
                // Untested...
                // We need a blob of memory for the DISK_EXTENTS structure, and all the DISK_EXTENTS

                int    blobSize = Marshal.SizeOf(typeof(DiskExtents)) + (de1Cast.numberOfExtents - 1) * Marshal.SizeOf(typeof(DiskExtent));
                IntPtr pBlob    = Marshal.AllocHGlobal(blobSize);
                result = NativeMethods.DeviceIoControl(sfh, IoctlVolumeGetVolumeDiskExtents, IntPtr.Zero, 0, pBlob, blobSize, ref bytesReturned, IntPtr.Zero);
                if (result == false)
                {
                    throw new Win32Exception();
                }
                // Read them out one at a time.
                IntPtr pNext = new IntPtr(pBlob.ToInt64() + 8);
                // is this always ok on 64 bit OSes? ToInt64?
                for (int i = 0; i <= de1Cast.numberOfExtents - 1; i++)
                {
                    DiskExtent diskExtentN = (DiskExtent)Marshal.PtrToStructure(pNext, typeof(DiskExtent));
                    physicalDrives.Add("\\\\.\\PhysicalDrive" + diskExtentN.DiskNumber.ToString());
                    pNext = new IntPtr(pNext.ToInt32() + Marshal.SizeOf(typeof(DiskExtent)));
                }
                return(physicalDrives);
            }
            finally
            {
                if (sfh != null)
                {
                    if (sfh.IsInvalid == false)
                    {
                        sfh.Close();
                    }
                    sfh.Dispose();
                }
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// This method uses GetOverlappedResult to detect that Windows7 dynamic compat mode is currently active.
        /// In this mode, GetOverlappedResult now always waits on the overlapped event, even if results are ready!
        /// Before the Windows7 fix: GetOverlappedResult did not wait, so event remained active
        /// The trick here is to simulate the same behavior and test the overlapped event status!
        /// </summary>
        private static bool TestWindows7DynamicContext()
        {
            AutoResetEvent   overlappedEvent = new AutoResetEvent(false);
            NativeOverlapped overlapped      = new NativeOverlapped();

            overlapped.EventHandle = overlappedEvent.SafeWaitHandle.DangerousGetHandle();

            bool           isActive         = false;
            string         tmpFile          = Path.GetTempFileName();
            SafeFileHandle readStreamHandle = null;

            try
            {
                readStreamHandle = NativeMethods.CreateFile(
                    tmpFile,
                    NativeMethods.GENERIC_WRITE,
                    0,                                  // no sharing
                    IntPtr.Zero,                        // default sec attributes
                    NativeMethods.OPEN_ALWAYS,          // open or create
                    NativeMethods.FILE_FLAG_OVERLAPPED, // enable overlapped
                    IntPtr.Zero                         // no template
                    );

                if (readStreamHandle == null || readStreamHandle.IsInvalid)
                {
                    throw new System.ComponentModel.Win32Exception();
                }

                // read from file using async API
                byte[] tempBuf = Encoding.ASCII.GetBytes("Windows7CompatTest");
                int    numberOfBytesWritten = 0;
                bool   res = NativeMethods.WriteFile(readStreamHandle, tempBuf, tempBuf.Length, ref numberOfBytesWritten, ref overlapped);
                if (!res)
                {
                    int lastError = Marshal.GetLastWin32Error();
                    if (lastError != 0 && lastError != NativeMethods.ERROR_IO_PENDING)
                    {
                        throw new System.ComponentModel.Win32Exception(lastError);
                    }
                }

                // ensure overlapped result has completed
                while (!NativeMethods.HasOverlappedIoCompleted(overlapped))
                {
                    Thread.Sleep(1);
                }

                // the event must be set
                bool isSet = overlappedEvent.WaitOne(0);
                Trace.Assert(isSet, "IO has completed, but event is not signalled yet!");
                overlappedEvent.Set(); // reset it back

                // call into GetOverlappedResult with TRUE flag
                // if Win7 compat mode is active: GetOverlappedResult will wait and reset the event, ignoring the fact that IO is completed
                // in not (or if not running on Win7): GetOverlappedResult does not wait if IO is completed, leaving the event signalled
                res = NativeMethods.GetOverlappedResult(readStreamHandle, ref overlapped, out numberOfBytesWritten, true);
                if (!res)
                {
                    throw new System.ComponentModel.Win32Exception();
                }

                // if GetOverlappedResult actually waits after IO completion ends (and WaitOne returns false),
                // the app dynamic compat context is Win7 or Windows 2008 R2
                isActive = !overlappedEvent.WaitOne(0); // returns immediately
            }
            finally
            {
                if (readStreamHandle != null)
                {
                    readStreamHandle.Close();
                }

                if (File.Exists(tmpFile))
                {
                    File.Delete(tmpFile);
                }
            }

            return(isActive);
        }
Exemplo n.º 40
0
        public bool ScanDirectory(string DirPrefix, ScanCallback Callback, BuildDBInfo UserData)
        {
            PInvoke.WIN32_FIND_DATA FindData;

            var DirIndice = (uint)Directories.Count - 1;

            var SearchString = DirPrefix + "*";

            var FindHandle = PInvoke.FindFirstFile(SearchString, out FindData);

            if (FindHandle == PInvoke.INVALID_HANDLE_VALUE)
            {
                return(false);
            }

            do
            {
                UInt64 FileSize = ((FindData.nFileSizeHigh << 32) | FindData.nFileSizeLow);

                FileInfo       Info   = new FileInfo(FindData.cFileName, DirIndice, FileSize, FindData.dwFileAttributes);
                SafeFileHandle Handle = null;

                // DonLL't ever include '.L' and '..'
                if (Info.Name == "." || Info.Name == "..")
                {
                    continue;
                }

                //Info.FullName = DirPrefix + Info.Name;

                Info.Clusters = 0;
                if (GetClusterInfo(Info, ref Handle))
                {
                    UInt64 TotalClusters = Info.Fragments.Aggregate <Extent, ulong>(0, (current, ext) => current + ext.Length);

                    Info.Clusters = TotalClusters;
                }
                else
                {
                    Info.Attributes.Unmovable = true;
                    Info.Attributes.Process   = false;
                }

                if (Info.Attributes.Process)
                {
                    Info.Attributes.Process = ShouldProcess(Info.Attributes);
                }

                // Run the user-defined callback function
                var CallbackResult = Callback(ref Info, ref Handle, ref UserData);

                if (!Handle.IsInvalid && !Handle.IsClosed)
                {
                    Handle.Close();
                }

                if (!CallbackResult)
                {
                    break;
                }

                // If directory, perform recursion
                if (Info.Attributes.Directory)
                {
                    var Dir = GetDBDir(Info.DirIndice);
                    Dir += Info.Name;
                    Dir += "\\";

                    Directories.Add(Dir);
                    ScanDirectory(Dir, Callback, UserData);
                }
            } while (PInvoke.FindNextFile(FindHandle, out FindData));

            PInvoke.FindClose(FindHandle);
            return(false);
        }
Exemplo n.º 41
0
        private void Search_For_Wiimotes()
        {
            // 1. Get the GUID of the HID class
            HIDImports2.HidD_GetHidGuid(out guid);

            // 2. get a handle to all devices that are part of the HID class
            IntPtr hDevInfo = HIDImports2.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports2.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports2.SP_DEVICE_INTERFACE_DATA diData = new HIDImports2.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // 3. get a device interface to a single device (enumerate all devices)
            while (HIDImports2.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                // create a detail struct and set its size
                HIDImports2.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports2.SP_DEVICE_INTERFACE_DETAIL_DATA();
                diDetail.cbSize = 5; //should be: (uint)Marshal.SizeOf(diDetail);, but that's the wrong size

                UInt32 size = 0;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports2.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // actually get the detail struct
                if (HIDImports2.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    // open a read/write handle to our device using the DevicePath returned
                    mHandle = HIDImports2.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports2.EFileAttributes.Overlapped, IntPtr.Zero);

                    // 4. create an attributes struct and initialize the size
                    HIDImports2.HIDD_ATTRIBUTES attrib = new HIDImports2.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if (HIDImports2.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if ((attrib.VendorID == VID_old && attrib.ProductID == PID_old) || (attrib.VendorID == VID_new && attrib.ProductID == PID_new))
                        {
                            // 5. create a nice .NET FileStream wrapping the handle above
                            mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);
                            Console.WriteLine("Wii remote found");
                        }
                        else
                            mHandle.Close();
                    }
                }

                // move to the next device
                index++;
            }

            // 6. clean up our list
            HIDImports2.SetupDiDestroyDeviceInfoList(hDevInfo);
        }
Exemplo n.º 42
0
      internal static DateTime GetChangeTimeInternal(bool isFolder, KernelTransaction transaction, SafeFileHandle safeHandle, string path, bool getUtc, PathFormat pathFormat)
      {
         if (!NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(Resources.RequiresWindowsVistaOrHigher);

         bool callerHandle = safeHandle != null;
         if (!callerHandle)
         {
            if (pathFormat != PathFormat.LongFullPath && Utils.IsNullOrWhiteSpace(path))
               throw new ArgumentNullException("path");

            string pathLp = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars);

            safeHandle = CreateFileInternal(transaction, pathLp, isFolder ? ExtendedFileAttributes.BackupSemantics : ExtendedFileAttributes.Normal, null, FileMode.Open, FileSystemRights.ReadData, FileShare.ReadWrite, true, PathFormat.LongFullPath);
         }


         try
         {
            NativeMethods.IsValidHandle(safeHandle);
            
            using (var safeBuffer = new SafeGlobalMemoryBufferHandle(IntPtr.Size + Marshal.SizeOf(typeof(NativeMethods.FileBasicInfo))))
            {
               NativeMethods.FileBasicInfo fbi;

               if (!NativeMethods.GetFileInformationByHandleEx_FileBasicInfo(safeHandle, NativeMethods.FileInfoByHandleClass.FileBasicInfo, out fbi, (uint)safeBuffer.Capacity))
                  NativeError.ThrowException(Marshal.GetLastWin32Error());

               safeBuffer.StructureToPtr(fbi, true);
               NativeMethods.FileTime changeTime = safeBuffer.PtrToStructure<NativeMethods.FileBasicInfo>().ChangeTime;

               return getUtc
                  ? DateTime.FromFileTimeUtc(changeTime)
                  : DateTime.FromFileTime(changeTime);
            }
         }
         finally
         {
            // Handle is ours, dispose.
            if (!callerHandle && safeHandle != null)
               safeHandle.Close();
         }
      }
Exemplo n.º 43
0
    public static string GetTarget(string path)
    {
        SymbolicLinkReparseData reparseDataBuffer;

        using (SafeFileHandle fileHandle = getFileHandle(path))
        {
            if (fileHandle.IsInvalid)
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            int    outBufferSize = Marshal.SizeOf(typeof(SymbolicLinkReparseData));
            IntPtr outBuffer     = IntPtr.Zero;
            try
            {
                outBuffer = Marshal.AllocHGlobal(outBufferSize);
                int  bytesReturned;
                bool success = DeviceIoControl(
                    fileHandle.DangerousGetHandle(), ioctlCommandGetReparsePoint, IntPtr.Zero, 0,
                    outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero);

                fileHandle.Close();

                if (!success)
                {
                    var errorCode = Marshal.GetLastWin32Error();

                    if (errorCode == 4390)
                    {
                        throw new Exception("这个目录不是一个硬链接目录!");
                    }

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

                reparseDataBuffer = (SymbolicLinkReparseData)Marshal.PtrToStructure(
                    outBuffer, typeof(SymbolicLinkReparseData));
            }
            finally
            {
                Marshal.FreeHGlobal(outBuffer);
            }
        }

        var target1 = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer).Trim();

        target1 = ResolvePath(target1);
        return(target1);

        if (reparseDataBuffer.ReparseTag != symLinkTag)
        {
            return(null);
        }

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

        return(target);
    }
      internal static IEnumerable<FileIdBothDirectoryInfo> EnumerateFileIdBothDirectoryInfoInternal(KernelTransaction transaction, SafeFileHandle safeHandle, string path, FileShare shareMode, bool continueOnException, PathFormat pathFormat)
      {
         if (!NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(Resources.RequiresWindowsVistaOrHigher);

         bool callerHandle = safeHandle != null;
         if (!callerHandle)
         {
            if (Utils.IsNullOrWhiteSpace(path))
               throw new ArgumentNullException("path");

            string pathLp = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

            safeHandle = File.CreateFileInternal(transaction, pathLp, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, shareMode, true, PathFormat.LongFullPath);
         }


         try
         {
            if (!NativeMethods.IsValidHandle(safeHandle, Marshal.GetLastWin32Error(), !continueOnException))
               yield break;

            // 2014-10-16: Number of returned items depends on the size of the buffer.
            // That does not seem right, investigate.
            using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize))
            {
               NativeMethods.IsValidHandle(safeBuffer, Marshal.GetLastWin32Error());

               long fileNameOffset = Marshal.OffsetOf(typeof(NativeMethods.FileIdBothDirInfo), "FileName").ToInt64();

               while (NativeMethods.GetFileInformationByHandleEx(safeHandle, NativeMethods.FileInfoByHandleClass.FileIdBothDirectoryInfo, safeBuffer.DangerousGetHandle(), NativeMethods.DefaultFileBufferSize))
               {
                  // CA2001:AvoidCallingProblematicMethods

                  IntPtr buffer = IntPtr.Zero;
                  bool successRef = false;
                  safeBuffer.DangerousAddRef(ref successRef);

                  // MSDN: The DangerousGetHandle method poses a security risk because it can return a handle that is not valid.
                  if (successRef)
                     buffer = safeBuffer.DangerousGetHandle();

                  safeBuffer.DangerousRelease();

                  if (buffer == IntPtr.Zero)
                     NativeError.ThrowException(Resources.HandleDangerousRef);

                  // CA2001:AvoidCallingProblematicMethods


                  while (buffer != IntPtr.Zero)
                  {
                     NativeMethods.FileIdBothDirInfo fibdi = Utils.MarshalPtrToStructure<NativeMethods.FileIdBothDirInfo>(0, buffer);

                     string fileName = Marshal.PtrToStringUni(new IntPtr(fileNameOffset + buffer.ToInt64()), (int)(fibdi.FileNameLength / 2));

                     if (!Utils.IsNullOrWhiteSpace(fileName) &&
                         !fileName.Equals(Path.CurrentDirectoryPrefix, StringComparison.OrdinalIgnoreCase) &&
                         !fileName.Equals(Path.ParentDirectoryPrefix, StringComparison.OrdinalIgnoreCase))
                        yield return new FileIdBothDirectoryInfo(fibdi, fileName);


                     buffer = fibdi.NextEntryOffset == 0
                        ? IntPtr.Zero
                        : new IntPtr(buffer.ToInt64() + fibdi.NextEntryOffset);
                  }
               }

               int lastError = Marshal.GetLastWin32Error();
               switch ((uint)lastError)
               {
                  case Win32Errors.ERROR_SUCCESS:
                  case Win32Errors.ERROR_NO_MORE_FILES:
                  case Win32Errors.ERROR_HANDLE_EOF:
                     yield break;

                  default:
                     NativeError.ThrowException(lastError, path);
                     break;
               }
            }
         }
         finally
         {
            // Handle is ours, dispose.
            if (!callerHandle && safeHandle != null)
               safeHandle.Close();
         }
      }
Exemplo n.º 45
0
      internal static long GetSizeInternal(KernelTransaction transaction, SafeFileHandle safeHandle, string path, PathFormat pathFormat)
      {
         bool callerHandle = safeHandle != null;
         if (!callerHandle)
         {
            string pathLp = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

            safeHandle = CreateFileInternal(transaction, pathLp, ExtendedFileAttributes.None, null, FileMode.Open, FileSystemRights.ReadData, FileShare.Read, true, PathFormat.LongFullPath);
         }


         long fileSize;

         try
         {
            NativeMethods.GetFileSizeEx(safeHandle, out fileSize);
         }
         finally
         {
            // Handle is ours, dispose.
            if (!callerHandle && safeHandle != null)
               safeHandle.Close();
         }

         return fileSize;
      }
Exemplo n.º 46
0
        //connect to the driver.  We'll iterate through all present HID devices and find the one that matches our target VENDORID and PRODUCTID
        public void Connect()
        {
            DoLog("Connecting...");
            if (Connected)
            {
                DoLog("Already connected.");
                return;
            }

            HidD_GetHidGuid(out HIDGuid);

            var PnPHandle = SetupDiGetClassDevs(ref HIDGuid, IntPtr.Zero, IntPtr.Zero, (int)(DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE));

            if (PnPHandle == (IntPtr)INVALID_HANDLE_VALUE)
            {
                DoLog("Connect: SetupDiGetClassDevs failed.");
                return;
            }

            var  bFoundMyDevice = false;
            uint i = 0;

            //we coudld use a lot more failure and exception logging during this loop
            bool bFoundADevice;

            do
            {
                var DevInterfaceData = new SP_DEVICE_INTERFACE_DATA();
                DevInterfaceData.cbSize = (uint)Marshal.SizeOf(DevInterfaceData);
                bFoundADevice           = SetupDiEnumDeviceInterfaces(PnPHandle, IntPtr.Zero, ref HIDGuid, i, ref DevInterfaceData);
                if (bFoundADevice)
                {
                    var DevInfoData = new SP_DEVINFO_DATA();
                    DevInfoData.cbSize = (uint)Marshal.SizeOf(DevInfoData);
                    var result3 = SetupDiGetDeviceInterfaceDetail(PnPHandle, DevInterfaceData, IntPtr.Zero, 0, out var needed, DevInfoData);
                    if (!result3)
                    {
                        var error = Marshal.GetLastWin32Error();
                        if (error == 122)
                        {
                            //it's supposed to give an error 122 as we just only retrieved the data size needed, so this is as designed
                            var DeviceInterfaceDetailData = Marshal.AllocHGlobal((int)needed);
                            try
                            {
                                var size = needed;
                                Marshal.WriteInt32(DeviceInterfaceDetailData, IntPtr.Size == 8 ? 8 : 6);
                                var result4 = SetupDiGetDeviceInterfaceDetail(PnPHandle, DevInterfaceData, DeviceInterfaceDetailData, size, out needed, DevInfoData);
                                if (!result4)
                                {
                                    //shouldn't be an error here
                                    var error1 = Marshal.GetLastWin32Error();
                                    //todo: go +1 and contine the loop...this exception handing is incomplete
                                }
                                var pDevicePathName = new IntPtr(DeviceInterfaceDetailData.ToInt64() + 4);
                                FDevicePathName = Marshal.PtrToStringAuto(pDevicePathName);
                                //see if this driver has readwrite access
                                FDevHandle = CreateFile(FDevicePathName, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite, IntPtr.Zero, System.IO.FileMode.Open, 0, IntPtr.Zero);
                                if (FDevHandle.IsInvalid)
                                {
                                    FDevHandle = CreateFile(FDevicePathName, 0, System.IO.FileShare.ReadWrite, IntPtr.Zero, System.IO.FileMode.Open, 0, IntPtr.Zero);
                                }
                                if (!FDevHandle.IsInvalid)
                                {
                                    //this device has readwrite access, could it be the device we are looking for?
                                    var HIDAttributes = new HIDD_ATTRIBUTES();
                                    HIDAttributes.Size = Marshal.SizeOf(HIDAttributes);
                                    var success = HidD_GetAttributes(FDevHandle, ref HIDAttributes);
                                    if (success && HIDAttributes.VendorID == VendorID && HIDAttributes.ProductID == ProductID)
                                    {
                                        //this is the device we are looking for
                                        bFoundMyDevice = true;
                                        Connected      = true;
                                        DoLog("Connected.");
                                        //normally you would start a read thread here, but we aren't doing that in this example. We'll just call .ReadData instead.
                                        //we won't close our file handle here as it will be need in .SendData.
                                    }
                                    else
                                    {
                                        //not the device we are looking for
                                        FDevHandle.Close();
                                    }
                                }
                            }
                            finally
                            {
                                Marshal.FreeHGlobal(DeviceInterfaceDetailData);
                            }
                        }
                    }
                }
                i++;
            } while ((bFoundADevice) & (!bFoundMyDevice));
        }
Exemplo n.º 47
0
        // Attempts to find the device of interest and attach to it (open file handles).
        // Returns ture if something has changed (attached/detached), false if there was no change.
        public void AttemptAttach()
        {
            // First check and make sure at least one device with matching VID/PID is attached
            if (!GetUSBDevicePath())
            {
                // Device must not be connected (or not programmed with correct firmware)...

                if (_state == AttachedState.NotAttached)
                    return;

                // If AttachedState is currently set to true, it means the device was just now disconnected
                WriteHandleToUSBDevice.Close();
                ReadHandleToUSBDevice.Close();
                _state = AttachedState.NotAttached;

                if (USBDeviceRemoved != null)
                    USBDeviceRemoved(this);

                return;
            }

            // If we get here, it means that the device is currently connected and was found.
            // We need to decide what to do, based on whether or not the device was previously known to be
            // connected or not.

            // If we are already attached to the device just do nothing
            if (_state == AttachedState.Attached)
                return;

            uint ErrorStatusWrite;
            uint ErrorStatusRead;

            // We obtained the proper device path (from CheckIfPresentAndGetUSBDevicePath() function call), and it
            // is now possible to open read and write handles to the device.
            WriteHandleToUSBDevice = Win32Wrapper.CreateFile(DevicePath, Win32Wrapper.GENERIC_WRITE, Win32Wrapper.FILE_SHARE_READ | Win32Wrapper.FILE_SHARE_WRITE, IntPtr.Zero, Win32Wrapper.OPEN_EXISTING, 0, IntPtr.Zero);
            ErrorStatusWrite = (uint)Marshal.GetLastWin32Error();
            ReadHandleToUSBDevice = Win32Wrapper.CreateFile(DevicePath, Win32Wrapper.GENERIC_READ, Win32Wrapper.FILE_SHARE_READ | Win32Wrapper.FILE_SHARE_WRITE, IntPtr.Zero, Win32Wrapper.OPEN_EXISTING, 0, IntPtr.Zero);
            ErrorStatusRead = (uint)Marshal.GetLastWin32Error();

            if (ErrorStatusWrite == Win32Wrapper.ERROR_SUCCESS && ErrorStatusRead == Win32Wrapper.ERROR_SUCCESS)
                _state = AttachedState.Attached;
            else // for some reason the device is physically plugged in, but one or both of the read/write handles didn't open successfully...
            {
                // Flag so that next time a WM_DEVICECHANGE message occurs, can retry to re-open read/write pipes
                _state = AttachedState.AttachedButBroken;

                if (ErrorStatusWrite == Win32Wrapper.ERROR_SUCCESS)
                    WriteHandleToUSBDevice.Close();

                if (ErrorStatusRead == Win32Wrapper.ERROR_SUCCESS)
                    ReadHandleToUSBDevice.Close();
            }

            if (USBDeviceAttached != null)
                USBDeviceAttached(this);

            return;
        }
Exemplo n.º 48
0
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        public int attemptUSBConnection()
        {
            // Register for WM_DEVICECHANGE notifications.  This code uses these messages to detect plug and play connection/disconnection events for USB devices
            DEV_BROADCAST_DEVICEINTERFACE DeviceBroadcastHeader = new DEV_BROADCAST_DEVICEINTERFACE();

            DeviceBroadcastHeader.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
            DeviceBroadcastHeader.dbcc_size       = (uint)Marshal.SizeOf(DeviceBroadcastHeader);
            DeviceBroadcastHeader.dbcc_reserved   = 0;                  //Reserved says not to use...
            DeviceBroadcastHeader.dbcc_classguid  = InterfaceClassGuid;

            // Need to get the address of the DeviceBroadcastHeader to call RegisterDeviceNotification(), but
            // can't use "&DeviceBroadcastHeader".  Instead, using a roundabout means to get the address by
            // making a duplicate copy using Marshal.StructureToPtr().
            IntPtr pDeviceBroadcastHeader = IntPtr.Zero;                                          // Make a pointer.

            pDeviceBroadcastHeader = Marshal.AllocHGlobal(Marshal.SizeOf(DeviceBroadcastHeader)); // allocate memory for a new DEV_BROADCAST_DEVICEINTERFACE structure, and return the address
            Marshal.StructureToPtr(DeviceBroadcastHeader, pDeviceBroadcastHeader, false);         // Copies the DeviceBroadcastHeader structure into the memory already allocated at DeviceBroadcastHeaderWithPointer
            RegisterDeviceNotification(this.Handle, pDeviceBroadcastHeader, DEVICE_NOTIFY_WINDOW_HANDLE);

            // Now make an initial attempt to find the USB device, if it was already connected to the PC and enumerated prior to launching the application.
            // If it is connected and present, we should open read and write handles to the device so we can communicate with it later.
            // If it was not connected, we will have to wait until the user plugs the device in, and the WM_DEVICECHANGE callback function can process
            // the message and again search for the device.

            IntPtr DeviceInfoTable = IntPtr.Zero;
            SP_DEVICE_INTERFACE_DATA        InterfaceDataStructure         = new SP_DEVICE_INTERFACE_DATA();
            SP_DEVICE_INTERFACE_DETAIL_DATA DetailedInterfaceDataStructure = new SP_DEVICE_INTERFACE_DETAIL_DATA();
            SP_DEVINFO_DATA DevInfoData = new SP_DEVINFO_DATA();

            uint   InterfaceIndex      = 0;
            uint   dwRegType           = 0;
            uint   dwRegSize           = 0;
            uint   dwRegSize2          = 0;
            uint   StructureSize       = 0;
            IntPtr PropertyValueBuffer = IntPtr.Zero;
            bool   MatchFound          = false;
            uint   ErrorStatus;
            uint   loopCounter = 0;

            String DeviceIDToFind = deviceID;

            // First populate a list of plugged in devices (by specifying "DIGCF_PRESENT"), which are of the specified class GUID.
            DeviceInfoTable = SetupDiGetClassDevs(ref InterfaceClassGuid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

            if (DeviceInfoTable == IntPtr.Zero)
            {
                return(CONNECTION_NOT_SUCCESSFUL);
            }

            // Now look through the list we just populated.  We are trying to see if any of them match our device.
            while (true)
            {
                InterfaceDataStructure.cbSize = (uint)Marshal.SizeOf(InterfaceDataStructure);
                if (SetupDiEnumDeviceInterfaces(DeviceInfoTable, IntPtr.Zero, ref InterfaceClassGuid, InterfaceIndex, ref InterfaceDataStructure))
                {
                    ErrorStatus = (uint)Marshal.GetLastWin32Error();
                    if (ErrorStatus == ERROR_NO_MORE_ITEMS)
                    {                                                                           // did we reach the end of the list of matching devices in the DeviceInfoTable?
                        // cound not find the device.  Must not have been attached.
                        SetupDiDestroyDeviceInfoList(DeviceInfoTable);                          // clean up the old structure we no longer need.
                        return(CONNECTION_NOT_SUCCESSFUL);
                    }
                }
                else
                {                                                                       // else some other kind of unknown error ocurred...
                    ErrorStatus = (uint)Marshal.GetLastWin32Error();
                    SetupDiDestroyDeviceInfoList(DeviceInfoTable);                      // Clean up the old structure we no longer need.
                    return(CONNECTION_NOT_SUCCESSFUL);
                }

                // Now retrieve the hardware ID from the registry.  The hardware ID contains the VID and PID, which we will then
                // check to see if it is the correct device or not.

                // Initialize an appropriate SP_DEVINFO_DATA structure.  We need this structure for SetupDiGetDeviceRegistryProperty().
                DevInfoData.cbSize = (uint)Marshal.SizeOf(DevInfoData);
                SetupDiEnumDeviceInfo(DeviceInfoTable, InterfaceIndex, ref DevInfoData);

                // First query for the size of the hardware ID, so we can know how big a buffer to allocate for the data.
                SetupDiGetDeviceRegistryProperty(DeviceInfoTable, ref DevInfoData, SPDRP_HARDWAREID, ref dwRegType, IntPtr.Zero, 0, ref dwRegSize);

                // Allocate a buffer for the hardware ID.
                // Should normally work, but could throw exception "OutOfMemoryException" if not enough resources available.
                PropertyValueBuffer = Marshal.AllocHGlobal((int)dwRegSize);

                // Retrieve the hardware IDs for the current device we are looking at.  PropertyValueBuffer gets filled with a
                // REG_MULTI_SZ (array of null terminated strings).  To find a device, we only care about the very first string in the
                // buffer, which will be the "device ID".  The device ID is a string which contains the VID and PID, in the example
                // format "Vid_04d8&Pid_003f".
                SetupDiGetDeviceRegistryProperty(DeviceInfoTable, ref DevInfoData, SPDRP_HARDWAREID, ref dwRegType, PropertyValueBuffer, dwRegSize, ref dwRegSize2);

                // Now check if the first string in the hardware ID matches the device ID of the USB device we are trying to find.
                String DeviceIDFromRegistry = Marshal.PtrToStringUni(PropertyValueBuffer); // Make a new string, fill it with the contents from the PropertyValueBuffer

                Marshal.FreeHGlobal(PropertyValueBuffer);                                  // no longer need the PropertyValueBuffer, free the memory to prevent potential memory leaks

                // Convert both strings to lower case.  This makes the code more robust/portable accross OS Versions
                DeviceIDFromRegistry = DeviceIDFromRegistry.ToLowerInvariant();
                DeviceIDToFind       = DeviceIDToFind.ToLowerInvariant();
                // Now check if the hardware ID we are looking at contains the correct VID/PID
                MatchFound = DeviceIDFromRegistry.Contains(DeviceIDToFind);
                if (MatchFound == true)
                {
                    // Device must have been found.  In order to open I/O file handle(s), we will need the actual device path first.
                    // We can get the path by calling SetupDiGetDeviceInterfaceDetail(), however, we have to call this function twice:  The first
                    // time to get the size of the required structure/buffer to hold the detailed interface data, then a second time to actually
                    // get the structure (after we have allocated enough memory for the structure.)
                    DetailedInterfaceDataStructure.cbSize = (uint)Marshal.SizeOf(DetailedInterfaceDataStructure);

                    // First call populates "StructureSize" with the correct value
                    SetupDiGetDeviceInterfaceDetail(DeviceInfoTable, ref InterfaceDataStructure, IntPtr.Zero, 0, ref StructureSize, IntPtr.Zero);

                    // Need to call SetupDiGetDeviceInterfaceDetail() again, this time specifying a pointer to a SP_DEVICE_INTERFACE_DETAIL_DATA buffer with the correct size of RAM allocated.
                    // First need to allocate the unmanaged buffer and get a pointer to it.
                    IntPtr pUnmanagedDetailedInterfaceDataStructure = IntPtr.Zero;                                           // Declare a pointer.
                    pUnmanagedDetailedInterfaceDataStructure = Marshal.AllocHGlobal((int)StructureSize);                     // Reserve some unmanaged memory for the structure.
                    DetailedInterfaceDataStructure.cbSize    = 6;                                                            // Initialize the cbSize parameter (4 bytes for DWORD + 2 bytes for unicode null terminator)
                    Marshal.StructureToPtr(DetailedInterfaceDataStructure, pUnmanagedDetailedInterfaceDataStructure, false); //Copy managed structure contents into the unmanaged memory buffer.

                    // Now call SetupDiGetDeviceInterfaceDetail() a second time to receive the device path in the structure at pUnmanagedDetailedInterfaceDataStructure.
                    if (SetupDiGetDeviceInterfaceDetail(DeviceInfoTable, ref InterfaceDataStructure, pUnmanagedDetailedInterfaceDataStructure, StructureSize, IntPtr.Zero, IntPtr.Zero))
                    {
                        // Need to extract the path information from the unmanaged "structure".  The path starts at (pUnmanagedDetailedInterfaceDataStructure + sizeof(DWORD)).
                        IntPtr pToDevicePath = new IntPtr((uint)pUnmanagedDetailedInterfaceDataStructure.ToInt32() + 4); //Add 4 to the pointer (to get the pointer to point to the path, instead of the DWORD cbSize parameter)
                        DevicePath = Marshal.PtrToStringUni(pToDevicePath);                                              // Now copy the path information into the globally defined DevicePath String.

                        // We now have the proper device path, and we can finally use the path to open I/O handle(s) to the device.
                        SetupDiDestroyDeviceInfoList(DeviceInfoTable);                                          // Clean up the old structure we no longer need.
                        Marshal.FreeHGlobal(pUnmanagedDetailedInterfaceDataStructure);                          // No longer need this unmanaged SP_DEVICE_INTERFACE_DETAIL_DATA buffer.  We already extracted the path information.

                        uint ErrorStatusWrite;
                        uint ErrorStatusRead;
                        // we now have the proper device path, and we can finally open read and write handles to the device.
                        WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                        ErrorStatusWrite       = (uint)Marshal.GetLastWin32Error();
                        ReadHandleToUSBDevice  = CreateFile(DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                        ErrorStatusRead        = (uint)Marshal.GetLastWin32Error();

                        if ((ErrorStatusWrite == ERROR_SUCCESS) && (ErrorStatusRead == ERROR_SUCCESS))
                        {
                            return(CONNECTION_SUCCESSFUL);
                        }
                        else
                        {                                                                                               // for some reason the device was physically plugged in, but one or both of the read/write handles didn't open successfully...
                            if (ErrorStatusWrite == ERROR_SUCCESS)
                            {
                                WriteHandleToUSBDevice.Close();
                            }
                            if (ErrorStatusRead == ERROR_SUCCESS)
                            {
                                ReadHandleToUSBDevice.Close();
                            }
                            return(CONNECTION_NOT_SUCCESSFUL);
                        }
                    }
                    else
                    {                                                                           // Some unknown failure occurred
                        uint ErrorCode = (uint)Marshal.GetLastWin32Error();
                        SetupDiDestroyDeviceInfoList(DeviceInfoTable);                          // Clean up the old structure.
                        Marshal.FreeHGlobal(pUnmanagedDetailedInterfaceDataStructure);          // No longer need this unmanaged SP_DEVICE_INTERFACE_DETAIL_DATA buffer.  We already extracted the path information.
                        return(CONNECTION_NOT_SUCCESSFUL);
                    }
                }
                InterfaceIndex++;
                loopCounter++;
                if (loopCounter > 200)
                {                                      // if more than 200 times through the loop . . .
                    return(CONNECTION_NOT_SUCCESSFUL); // give up and bail
                }
            }                                          // end of while(true)
        }
Exemplo n.º 49
0
        ///  <summary>
        ///  Uses a series of API calls to locate a HID-class device
        ///  by its Vendor ID and Product ID.
        ///  </summary>
        ///          
        ///  <returns>
        ///   True if the device is detected, False if not detected.
        ///  </returns>
        private Boolean FindTheHid()
        {
            Boolean deviceFound = false;
            String[] devicePathName = new String[ 128 ];
            String functionName = "";
            Guid hidGuid = Guid.Empty;
            Int32 memberIndex = 0;
            Int32 myProductID = 0;
            Int32 myVendorID = 0;
            Boolean success = false;

            try
            {
                myDeviceDetected = false;
                CloseCommunications();

                //  Get the device's Vendor ID and Product ID from the form's text boxes.

                GetVendorAndProductIDsFromTextBoxes( ref myVendorID, ref myProductID );

                //  ***
                //  API function: 'HidD_GetHidGuid

                //  Purpose: Retrieves the interface class GUID for the HID class.

                //  Accepts: 'A System.Guid object for storing the GUID.
                //  ***

                Hid.HidD_GetHidGuid( ref hidGuid );

                functionName = "GetHidGuid";
                Debug.WriteLine( MyDebugging.ResultOfAPICall( functionName ) );
                Debug.WriteLine( "  GUID for system HIDs: " + hidGuid.ToString() );

                //  Fill an array with the device path names of all attached HIDs.

                deviceFound = MyDeviceManagement.FindDeviceFromGuid( hidGuid, ref devicePathName );

                //  If there is at least one HID, attempt to read the Vendor ID and Product ID
                //  of each device until there is a match or all devices have been examined.

                if ( deviceFound )
                {
                    memberIndex = 0;

                    do
                    {
                        //  ***
                        //  API function:
                        //  CreateFile

                        //  Purpose:
                        //  Retrieves a handle to a device.

                        //  Accepts:
                        //  A device path name returned by SetupDiGetDeviceInterfaceDetail
                        //  The type of access requested (read/write).
                        //  FILE_SHARE attributes to allow other processes to access the device while this handle is open.
                        //  A Security structure or IntPtr.Zero.
                        //  A creation disposition value. Use OPEN_EXISTING for devices.
                        //  Flags and attributes for files. Not used for devices.
                        //  Handle to a template file. Not used.

                        //  Returns: a handle without read or write access.
                        //  This enables obtaining information about all HIDs, even system
                        //  keyboards and mice.
                        //  Separate handles are used for reading and writing.
                        //  ***

                        // Open the handle without read/write access to enable getting information about any HID, even system keyboards and mice.

                        hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0,  FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);

                        functionName = "CreateFile";
                        Debug.WriteLine( MyDebugging.ResultOfAPICall( functionName ) );

                        Debug.WriteLine( "  Returned handle: " + hidHandle.ToString() );

                        if (!hidHandle.IsInvalid)
                        {
                            //  The returned handle is valid,
                            //  so find out if this is the device we're looking for.

                            //  Set the Size property of DeviceAttributes to the number of bytes in the structure.

                            MyHid.DeviceAttributes.Size = Marshal.SizeOf( MyHid.DeviceAttributes );

                            //  ***
                            //  API function:
                            //  HidD_GetAttributes

                            //  Purpose:
                            //  Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID,
                            //  Product ID, and Product Version Number for a device.

                            //  Accepts:
                            //  A handle returned by CreateFile.
                            //  A pointer to receive a HIDD_ATTRIBUTES structure.

                            //  Returns:
                            //  True on success, False on failure.
                            //  ***

                            success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes);

                            if ( success )
                            {
                                Debug.WriteLine( "  HIDD_ATTRIBUTES structure filled without error." );
                                Debug.WriteLine( "  Structure size: " + MyHid.DeviceAttributes.Size );
                                Debug.WriteLine("  Vendor ID: " + Convert.ToString(MyHid.DeviceAttributes.VendorID, 16));
                                Debug.WriteLine("  Product ID: " + Convert.ToString(MyHid.DeviceAttributes.ProductID, 16));
                                Debug.WriteLine("  Version Number: " + Convert.ToString(MyHid.DeviceAttributes.VersionNumber, 16));

                                //  Find out if the device matches the one we're looking for.

                                if ( ( MyHid.DeviceAttributes.VendorID == myVendorID ) && ( MyHid.DeviceAttributes.ProductID == myProductID ) )
                                {
                                    Debug.WriteLine( "  My device detected" );

                                    //  Display the information in form's list box.

                                    lstResults.Items.Add( "Device detected:" );
                                    lstResults.Items.Add("  Vendor ID= " + Convert.ToString(MyHid.DeviceAttributes.VendorID, 16));
                                    lstResults.Items.Add("  Product ID = " + Convert.ToString(MyHid.DeviceAttributes.ProductID, 16));

                                    ScrollToBottomOfListBox();

                                    myDeviceDetected = true;

                                    //  Save the DevicePathName for OnDeviceChange().

                                    myDevicePathName = devicePathName[ memberIndex ];
                                }
                                else
                                {
                                    //  It's not a match, so close the handle.

                                    myDeviceDetected = false;
                                    hidHandle.Close();
                                }
                            }
                            else
                            {
                                //  There was a problem in retrieving the information.

                                Debug.WriteLine( "  Error in filling HIDD_ATTRIBUTES structure." );
                                myDeviceDetected = false;
                                hidHandle.Close();
                            }
                        }

                        //  Keep looking until we find the device or there are no devices left to examine.

                        memberIndex = memberIndex + 1;
                    }
                    while (  ! ( ( myDeviceDetected || ( memberIndex == devicePathName.Length ) ) ) );
                }

                if ( myDeviceDetected )
                {
                    //  The device was detected.
                    //  Register to receive notifications if the device is removed or attached.

                    success = MyDeviceManagement.RegisterForDeviceNotifications( myDevicePathName, FrmMy.Handle, hidGuid, ref deviceNotificationHandle );

                    Debug.WriteLine( "RegisterForDeviceNotifications = " + success );

                    //  Learn the capabilities of the device.

                    MyHid.Capabilities = MyHid.GetDeviceCapabilities( hidHandle );

                    if ( success )
                    {
                        //  Find out if the device is a system mouse or keyboard.

                        hidUsage = MyHid.GetHidUsage( MyHid.Capabilities );

                        //  Get the Input report buffer size.

                        GetInputReportBufferSize();
                        cmdInputReportBufferSize.Enabled = true;

                        //Close the handle and reopen it with read/write access.

                        hidHandle.Close();
                        hidHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ | FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);

                        if ( hidHandle.IsInvalid )
                        {
                            exclusiveAccess = true;
                            lstResults.Items.Add( "The device is a system " + hidUsage + "." );
                            lstResults.Items.Add( "Windows 2000 and Windows XP obtain exclusive access to Input and Output reports for this devices." );
                            lstResults.Items.Add( "Applications can access Feature reports only." );
                            ScrollToBottomOfListBox();
                        }

                        else
                        {
                            if (MyHid.Capabilities.InputReportByteLength > 0)
                            {
                                //  Set the size of the Input report buffer.

                                Byte[] inputReportBuffer = null;

                                inputReportBuffer = new Byte[MyHid.Capabilities.InputReportByteLength];

                                fileStreamDeviceData = new FileStream(hidHandle, FileAccess.Read | FileAccess.Write, inputReportBuffer.Length, false);
                            }

                            if (MyHid.Capabilities.OutputReportByteLength > 0)
                            {
                                Byte[] outputReportBuffer = null;
                                outputReportBuffer = new Byte[MyHid.Capabilities.OutputReportByteLength];
                            }

                            //  Flush any waiting reports in the input buffer. (optional)

                            MyHid.FlushQueue( hidHandle );
                        }
                    }
                }
                else
                {
                    //  The device wasn't detected.

                    lstResults.Items.Add( "Device not found." );
                    cmdInputReportBufferSize.Enabled = false;
                    cmdOnce.Enabled = true;

                    Debug.WriteLine( " Device not found." );

                    ScrollToBottomOfListBox();
                }
                return myDeviceDetected;
            }
            catch ( Exception ex )
            {
                DisplayException( this.Name, ex );
                throw ;
            }
        }
 internal void Abort() => SafeFileHandle.Close();
Exemplo n.º 51
0
        private void OpenWiimoteDeviceHandle(string devicePath)
        {
            // open a read/write handle to our device using the DevicePath returned
            mHandle = HIDImports.CreateFile(devicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

            // create an attributes struct and initialize the size
            HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
            attrib.Size = Marshal.SizeOf(attrib);

            // get the attributes of the current device
            if(HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
            {
                // if the vendor and product IDs match up
                if(attrib.VendorID == VID && attrib.ProductID == PID)
                {
                    // create a nice .NET FileStream wrapping the handle above
                    mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                    // start an async read operation on it
                    BeginAsyncRead();

                    // read the calibration info from the controller
                    try
                    {
                        ReadWiimoteCalibration();
                    }
                    catch
                    {
                        // if we fail above, try the alternate HID writes
                        mAltWriteMethod = true;
                        ReadWiimoteCalibration();
                    }

                    // force a status check to get the state of any extensions plugged in at startup
                    GetStatus();
                }
                else
                {
                    // otherwise this isn't the controller, so close up the file handle
                    mHandle.Close();
                    throw new WiimoteException("Attempted to open a non-Wiimote device.");
                }
            }
        }
Exemplo n.º 52
0
        public MainForm()
        {
            InitializeComponent();

            //Register for WM_DEVICECHANGE notifications.  This code uses these messages to detect plug and play connection/disconnection events for USB devices
            DEV_BROADCAST_DEVICEINTERFACE DeviceBroadcastHeader = new DEV_BROADCAST_DEVICEINTERFACE();
            DeviceBroadcastHeader.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
            DeviceBroadcastHeader.dbcc_size = (uint)Marshal.SizeOf(DeviceBroadcastHeader);
            DeviceBroadcastHeader.dbcc_reserved = 0;	//Reserved says not to use...
            DeviceBroadcastHeader.dbcc_classguid = InterfaceClassGuid;

            //Need to get the address of the DeviceBroadcastHeader to call RegisterDeviceNotification(), but
            //can't use "&DeviceBroadcastHeader".  Instead, using a roundabout means to get the address by
            //making a duplicate copy using Marshal.StructureToPtr().
            IntPtr pDeviceBroadcastHeader = IntPtr.Zero;  //Make a pointer.
            pDeviceBroadcastHeader = Marshal.AllocHGlobal(Marshal.SizeOf(DeviceBroadcastHeader)); //allocate memory for a new DEV_BROADCAST_DEVICEINTERFACE structure, and return the address
            Marshal.StructureToPtr(DeviceBroadcastHeader, pDeviceBroadcastHeader, false);  //Copies the DeviceBroadcastHeader structure into the memory already allocated at DeviceBroadcastHeaderWithPointer
            RegisterDeviceNotification(this.Handle, pDeviceBroadcastHeader, DEVICE_NOTIFY_WINDOW_HANDLE);

            if (USBCheckIfPresentAndGetUSBDevicePath())	//Check and make sure at least one device with matching VID/PID is attached
            {
                uint ErrorStatusWrite;
                uint ErrorStatusRead;

                //We now have the proper device path, and we can finally open read and write handles to the device.
                WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                ErrorStatusWrite = (uint)Marshal.GetLastWin32Error();
                ReadHandleToUSBDevice = CreateFile(DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                ErrorStatusRead = (uint)Marshal.GetLastWin32Error();

                if ((ErrorStatusWrite == ERROR_SUCCESS) && (ErrorStatusRead == ERROR_SUCCESS))
                {
                    AttachedState = true;		//Let the rest of the PC application know the USB device is connected, and it is safe to read/write to it
                    AttachedButBroken = false;
                    StatusBar.Text = cnc_connected;
                }
                else //for some reason the device was physically plugged in, but one or both of the read/write handles didn't open successfully...
                {
                    AttachedState = false;		//Let the rest of this application known not to read/write to the device.
                    AttachedButBroken = true;	//Flag so that next time a WM_DEVICECHANGE message occurs, can retry to re-open read/write pipes
                    if (ErrorStatusWrite == ERROR_SUCCESS)
                        WriteHandleToUSBDevice.Close();
                    if (ErrorStatusRead == ERROR_SUCCESS)
                        ReadHandleToUSBDevice.Close();
                }
            }
            else	//Device must not be connected (or not programmed with correct firmware)
            {
                AttachedState = false;
                AttachedButBroken = false;
            }

            if (AttachedState == true)
            {
                StatusBar.Text = cnc_connected;
            }
            else
            {
                StatusBar.Text = cnc_not_connected;
            }

            ReadWriteThread.RunWorkerAsync();
        }
Exemplo n.º 53
0
        internal void Init(String path, FileMode mode, FileAccess access, int rights, bool useRights, FileShare share, int bufferSize, FileOptions options, Win32Native.SECURITY_ATTRIBUTES secAttrs, String msgPath, bool bFromProxy)
        {
            // msgPath must be safe to hand back to untrusted code.

            _fileName = msgPath;  // To handle odd cases of finalizing partially constructed objects.
            _exposedHandle = false;

            if (path == null)
                throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
            if (path.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));

            BCLDebug.Assert(!useRights, "Specifying FileSystemRights is not supported on this platform!");
          
            // don't include inheritable in our bounds check for share
            FileShare tempshare = share & ~FileShare.Inheritable;
            String badArg = null;

            if (mode < FileMode.CreateNew || mode > FileMode.Append)
                badArg = "mode";
            else if (!useRights && (access < FileAccess.Read || access > FileAccess.ReadWrite))
                badArg = "access";
            else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
                badArg = "share";
            
            if (badArg != null)
                throw new ArgumentOutOfRangeException(badArg, Environment.GetResourceString("ArgumentOutOfRange_Enum"));
            
            // NOTE: any change to FileOptions enum needs to be matched here in the error validation
            if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
                throw new ArgumentOutOfRangeException("options", Environment.GetResourceString("ArgumentOutOfRange_Enum"));

            if (bufferSize <= 0)
                throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));

            // Write access validation
            if (!useRights && (access & FileAccess.Write) == 0) { 
                if (mode==FileMode.Truncate || mode==FileMode.CreateNew || mode==FileMode.Create || mode==FileMode.Append) {
                    // No write access
                    if (!useRights)
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_InvalidFileMode&AccessCombo"), mode, access));
                }
            }


            int fAccess;
            if (!useRights) {
                fAccess = access == FileAccess.Read? GENERIC_READ:
                access == FileAccess.Write? GENERIC_WRITE:
                GENERIC_READ | GENERIC_WRITE;
            }
            else {
                fAccess = rights;
            }
            
            // Get absolute path - Security needs this to prevent something
            // like trying to create a file in c:\tmp with the name 
            // "..\WinNT\System32\ntoskrnl.exe".  Store it for user convenience.
            String filePath = Path.GetFullPathInternal(path);

            _fileName = filePath;

            // Prevent access to your disk drives as raw block devices.
            if (filePath.StartsWith("\\\\.\\", StringComparison.Ordinal))
                throw new ArgumentException(Environment.GetResourceString("Arg_DevicesNotSupported"));

            // Build up security permissions required, as well as validate we
            // have a sensible set of parameters.  IE, creating a brand new file
            // for reading doesn't make much sense.
            FileIOPermissionAccess secAccess = FileIOPermissionAccess.NoAccess;
            if (!useRights && (access & FileAccess.Read) != 0) {
                if (mode==FileMode.Append)
                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidAppendMode"));
                else
                    secAccess = secAccess | FileIOPermissionAccess.Read;
            }
            // I can't think of any combos of FileMode we should disallow if we
            // don't have read access.  Writing would pretty much always be valid
            // in those cases.

            // For any FileSystemRights other than ReadAndExecute, demand Write permission
            // This is probably bit overkill for TakeOwnership etc but we don't have any 
            // matching FileIOPermissionAccess to demand. It is better that we ask for Write permission.

            if (!useRights && (access & FileAccess.Write) != 0) { 
                if (mode==FileMode.Append)
                    secAccess = secAccess | FileIOPermissionAccess.Append;
                else
                    secAccess = secAccess | FileIOPermissionAccess.Write;
            }

            new FileIOPermission(secAccess, new String[] { filePath }, false, false).Demand();
            // Our Inheritable bit was stolen from Windows, but should be set in
            // the security attributes class.  Don't leave this bit set.
            share &= ~FileShare.Inheritable;

            bool seekToEnd = (mode==FileMode.Append);
            // Must use a valid Win32 constant here...
            if (mode == FileMode.Append)
                mode = FileMode.OpenOrCreate;

            // WRT async IO, do the right thing for whatever platform we're on.
            // This way, someone can easily write code that opens a file 
            // asynchronously no matter what their platform is.  
            if (_canUseAsync && (options & FileOptions.Asynchronous) != 0)
                _isAsync = true;
            else
                options &= ~FileOptions.Asynchronous;

            int flagsAndAttributes = (int) options;
            
            // Don't pop up a dialog for reading from an emtpy floppy drive
            int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
            try {
                _handle = Win32Native.SafeCreateFile(filePath, fAccess, share, secAttrs, mode, flagsAndAttributes, Win32Native.NULL);
				
                if (_handle.IsInvalid) {
                    // Return a meaningful exception, using the RELATIVE path to
                    // the file to avoid returning extra information to the caller
                    // unless they have path discovery permission, in which case
                    // the full path is fine & useful.
                    
                    // NT5 oddity - when trying to open "C:\" as a FileStream,
                    // we usually get ERROR_PATH_NOT_FOUND from the OS.  We should
                    // probably be consistent w/ every other directory.
                    int errorCode = Marshal.GetLastWin32Error();
                    if (errorCode==__Error.ERROR_PATH_NOT_FOUND && filePath.Equals(Directory.InternalGetDirectoryRoot(filePath)))
                        errorCode = __Error.ERROR_ACCESS_DENIED;
    
                    // We need to give an exception, and preferably it would include
                    // the fully qualified path name.  Do security check here.  If
                    // we fail, give back the msgPath, which should not reveal much.
                    // While this logic is largely duplicated in 
                    // __Error.WinIOError, we need this for 
                    // IsolatedStorageFileStream.
                    bool canGiveFullPath = false;
    
                    if (!bFromProxy)
                    {
                        try {
                            new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { _fileName }, false, false ).Demand();
                            canGiveFullPath = true;
                        }
                        catch(SecurityException) {}
                    }
    
                    if (canGiveFullPath)
                        __Error.WinIOError(errorCode, _fileName);
                    else
                        __Error.WinIOError(errorCode, msgPath);
                }
            }
            finally {
                Win32Native.SetErrorMode(oldMode);
            }
                
            // Disallow access to all non-file devices from the FileStream
            // constructors that take a String.  Everyone else can call 
            // CreateFile themselves then use the constructor that takes an 
            // IntPtr.  Disallows "con:", "com1:", "lpt1:", etc.
            int fileType = Win32Native.GetFileType(_handle);
            if (fileType != Win32Native.FILE_TYPE_DISK) {
                _handle.Close();
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"));
            }

            if (!useRights) {
                _canRead = (access & FileAccess.Read) != 0;
                _canWrite = (access & FileAccess.Write) != 0;
            }

            _canSeek = true;
            _isPipe = false;
            _pos = 0;
            _bufferSize = bufferSize;
            _readPos = 0;
            _readLen = 0;
            _writePos = 0;

            // For Append mode...
            if (seekToEnd) {
                _appendStart = SeekCore(0, SeekOrigin.End);
            }
            else {
                _appendStart = -1;
            }
        }
Exemplo n.º 54
0
        public bool FindNia()
        {
            bool success = false;

            try
            {
                // Get the guid for the system hid class
                Guid hidGuid = Guid.Empty;
                GenericHid.Hid.HidD_GetHidGuid(ref hidGuid);

                // Find all devices of type hid
                string[] deviceCollection = new String[128];
                bool devicesFound = DeviceManagement.FindDeviceFromGuid(hidGuid, ref deviceCollection);
                
                // Did we find any hid devices ?            
                if (devicesFound)
                {
                    int memberIndex = 0;
                    do
                    {
                        // try to get a handle on the current hid device in the list
						hidHandle = GenericHid.FileIO.CreateFile(deviceCollection[memberIndex], 0, GenericHid.FileIO.FILE_SHARE_READ | GenericHid.FileIO.FILE_SHARE_WRITE, null, GenericHid.FileIO.OPEN_EXISTING, 0, 0);

                        if (!hidHandle.IsInvalid)
                        {                            
                            // Set the Size property of DeviceAttributes to the number of bytes in the structure.
                            MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes);

                            // try to get the hid's information
							success = GenericHid.Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes);
                            if (success)
                            {
                                if ((MyHid.DeviceAttributes.VendorID == 4660) & (MyHid.DeviceAttributes.ProductID == 0))
                                {
                                    NiaDetected = true;

                                    // Save the DevicePathName for OnDeviceChange().
                                    NiaPathName = deviceCollection[memberIndex];
                                }
                                else
                                {
                                    NiaDetected = false;
                                    hidHandle.Close();
                                }
                            }
                            else
                            {
                                NiaDetected = false;
                                hidHandle.Close();
                            }
                        }

                        //  Keep looking until we find the device or there are no devices left to examine.
                        memberIndex = memberIndex + 1;

                    } while (!((NiaDetected | (memberIndex == deviceCollection.Length))));

                    // Did we find a NIA ?
                    if (NiaDetected)
                    {
                        // The device was detected.
                        // Register to receive notifications if the device is removed or attached.
                        success = DeviceManagement.RegisterForDeviceNotifications(this.NiaPathName, this.Handle, hidGuid, ref deviceNotificationHandle);

                        if (success)
                        {
                            //  Get handles to use in requesting Input and Output reports.
							readHandle = GenericHid.FileIO.CreateFile(this.NiaPathName, GenericHid.FileIO.GENERIC_READ, GenericHid.FileIO.FILE_SHARE_READ | GenericHid.FileIO.FILE_SHARE_WRITE, null, GenericHid.FileIO.OPEN_EXISTING, GenericHid.FileIO.FILE_FLAG_OVERLAPPED, 0);

                            if (!readHandle.IsInvalid)
                            {
								writeHandle = GenericHid.FileIO.CreateFile(this.NiaPathName, GenericHid.FileIO.GENERIC_WRITE, GenericHid.FileIO.FILE_SHARE_READ | GenericHid.FileIO.FILE_SHARE_WRITE, null, GenericHid.FileIO.OPEN_EXISTING, 0, 0);
                                MyHid.FlushQueue(readHandle);
                                
                                ZedInit();
                            }
                        }
                    }
                }

                return NiaDetected;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }