Welcome to mirror list, hosted at ThFree Co, Russian Federation.

WinUsbRegistry.cs « WinUsb « LibWinUsb - github.com/ClusterM/clovershell-client.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d7ef56169e3c6832842c7a416c210ece9ace6bcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
// Copyright © 2006-2010 Travis Robinson. All rights reserved.
// 
// website: http://sourceforge.net/projects/libusbdotnet
// e-mail:  libusbdotnet@gmail.com
// 
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or 
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
// for more details.
// 
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. or 
// visit www.gnu.org.
// 
// 
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using LibUsbDotNet.Internal;
using LibUsbDotNet.Internal.UsbRegex;
using LibUsbDotNet.Main;
using Microsoft.Win32;

namespace LibUsbDotNet.WinUsb
{
    /// <summary> WinUsb specific members for device registry settings.
    /// </summary> 
    public class WinUsbRegistry : UsbRegistry
    {
        private bool mIsDeviceIDParsed;

        private string mDeviceID;

        // Parsed out of the device ID
        private byte mInterfaceID;
        private ushort mVid;
        private ushort mPid;

        /// <summary>
        /// Gets a list of WinUSB device paths for the specified interface guid.
        /// </summary>
        /// <param name="deviceInterfaceGuid">The DeviceInterfaceGUID to search for.</param>
        /// <param name="devicePathList">A list of device paths associated with the <paramref name="deviceInterfaceGuid"/>.</param>
        /// <returns>True of one or more device paths was found.</returns>
        /// <remarks>
        /// Each device path string in the <paramref name="devicePathList"/> represents a seperate WinUSB device (interface).
        /// </remarks>
        /// <seealso cref="GetWinUsbRegistryList"/>
        public static bool GetDevicePathList(Guid deviceInterfaceGuid, out List<String> devicePathList)
        {
            devicePathList = new List<string>();
            int devicePathIndex = 0;
            SetupApi.SP_DEVICE_INTERFACE_DATA interfaceData = SetupApi.SP_DEVICE_INTERFACE_DATA.Empty;
            SetupApi.DeviceInterfaceDetailHelper detailHelper;

            IntPtr deviceInfo = SetupApi.SetupDiGetClassDevs(ref deviceInterfaceGuid, null, IntPtr.Zero, SetupApi.DICFG.PRESENT | SetupApi.DICFG.DEVICEINTERFACE);
            if (deviceInfo != IntPtr.Zero)
            {
                while ((SetupApi.SetupDiEnumDeviceInterfaces(deviceInfo, null, ref deviceInterfaceGuid, devicePathIndex, ref interfaceData)))
                {
                    int length = 1024;
                    detailHelper = new SetupApi.DeviceInterfaceDetailHelper(length);
                    bool bResult = SetupApi.SetupDiGetDeviceInterfaceDetail(deviceInfo, ref interfaceData, detailHelper.Handle, length, out length, null);
                    if (bResult) devicePathList.Add(detailHelper.DevicePath);

                    devicePathIndex++;
                }
            }
            if (devicePathIndex == 0)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetDevicePathList", typeof(SetupApi));

            if (deviceInfo != IntPtr.Zero)
                SetupApi.SetupDiDestroyDeviceInfoList(deviceInfo);

            return (devicePathIndex > 0);
        }

        /// <summary>
        /// Gets a list of <see cref="WinUsbRegistry"/> classes for the specified interface guid.
        /// </summary>
        /// <param name="deviceInterfaceGuid">The DeviceInterfaceGUID to search for.</param>
        /// <param name="deviceRegistryList">A list of device paths associated with the <paramref name="deviceInterfaceGuid"/>.</param>
        /// <returns>True of one or more device paths was found.</returns>
        /// <remarks>
        /// Each <see cref="WinUsbRegistry"/> in the <paramref name="deviceRegistryList"/> represents a seperate WinUSB device (interface).
        /// </remarks>
        public static bool GetWinUsbRegistryList(Guid deviceInterfaceGuid, out List<WinUsbRegistry> deviceRegistryList)
        {
            deviceRegistryList = new List<WinUsbRegistry>();

            int devicePathIndex = 0;
            SetupApi.SP_DEVICE_INTERFACE_DATA interfaceData = SetupApi.SP_DEVICE_INTERFACE_DATA.Empty;
            SetupApi.DeviceInterfaceDetailHelper detailHelper;

            SetupApi.SP_DEVINFO_DATA devInfoData = SetupApi.SP_DEVINFO_DATA.Empty;

            // [1]
            IntPtr deviceInfo = SetupApi.SetupDiGetClassDevs(ref deviceInterfaceGuid, null, IntPtr.Zero, SetupApi.DICFG.PRESENT | SetupApi.DICFG.DEVICEINTERFACE);
            if (deviceInfo != IntPtr.Zero)
            {
                while ((SetupApi.SetupDiEnumDeviceInterfaces(deviceInfo, null, ref deviceInterfaceGuid, devicePathIndex, ref interfaceData)))
                {
                    int length = 1024;
                    detailHelper = new SetupApi.DeviceInterfaceDetailHelper(length);
                    bool bResult = SetupApi.SetupDiGetDeviceInterfaceDetail(deviceInfo, ref interfaceData, detailHelper.Handle, length, out length, ref devInfoData);
                    if (bResult)
                    {
                        WinUsbRegistry regInfo = new WinUsbRegistry();

                        SetupApi.getSPDRPProperties(deviceInfo, ref devInfoData, regInfo.mDeviceProperties);

                        // Use the actual winusb device path for SYMBOLIC_NAME_KEY. This will be used to open the device.
                        regInfo.mDeviceProperties.Add(SYMBOLIC_NAME_KEY, detailHelper.DevicePath);

                        //Debug.WriteLine(detailHelper.DevicePath);

                        regInfo.mDeviceInterfaceGuids = new Guid[] { deviceInterfaceGuid };

                        StringBuilder sbDeviceID=new StringBuilder(1024);
                        if (SetupApi.CM_Get_Device_ID(devInfoData.DevInst,sbDeviceID,sbDeviceID.Capacity,0)==SetupApi.CR.SUCCESS)
                        {
                            regInfo.mDeviceProperties[DEVICE_ID_KEY] = sbDeviceID.ToString();
                        }
                        deviceRegistryList.Add(regInfo);
                    }

                    devicePathIndex++;
                }
            }
            if (devicePathIndex == 0)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetDevicePathList", typeof(SetupApi));

            if (deviceInfo != IntPtr.Zero)
                SetupApi.SetupDiDestroyDeviceInfoList(deviceInfo);

            return (devicePathIndex > 0);
        }

        internal WinUsbRegistry() { }

        /// <summary>
        /// Gets a list of available LibUsb devices.
        /// </summary>
        public static List<WinUsbRegistry> DeviceList
        {
            get
            {
                List<WinUsbRegistry> deviceList = new List<WinUsbRegistry>();
                SetupApi.EnumClassDevs(null, SetupApi.DICFG.ALLCLASSES | SetupApi.DICFG.PRESENT, WinUsbRegistryCallBack, deviceList);
                return deviceList;
            }
        }

        /// <summary>
        /// Gets a collection of DeviceInterfaceGuids that are associated with this WinUSB device.
        /// </summary>
        public override Guid[] DeviceInterfaceGuids
        {
            get
            {
                return mDeviceInterfaceGuids;
            }
        }

        /// <summary>
        /// Check this value to determine if the usb device is still connected to the bus and ready to open.
        /// </summary>
        /// <remarks>
        /// Uses the symbolic name as a unique id to determine if this device instance is still attached.
        /// </remarks>
        /// <exception cref="UsbException">An exception is thrown if the <see cref="UsbRegistry.SymbolicName"/> property is null or empty.</exception>
        public override bool IsAlive
        {
            get
            {
                if (String.IsNullOrEmpty(SymbolicName)) throw new UsbException(this, "A symbolic name is required for this property.");

                List<WinUsbRegistry> deviceList = DeviceList;
                foreach (WinUsbRegistry registry in deviceList)
                {
                    if (String.IsNullOrEmpty(registry.SymbolicName)) continue;

                    if (registry.SymbolicName == SymbolicName)
                        return true;
                }
                return false;
            }
        }

        /// <summary>
        /// Opens the USB device for communucation.
        /// </summary>
        /// <returns>Return a new instance of the <see cref="UsbDevice"/> class.
        /// If the device fails to open a null refrence is return. For extended error
        /// information use the <see cref="UsbDevice.UsbErrorEvent"/>.
        ///  </returns>
        public override UsbDevice Device
        {
            get
            {
                WinUsbDevice winUsbDevice;
                Open(out winUsbDevice);
                return winUsbDevice;
            }
        }


        private void parseDeviceID()
        {
            if (mIsDeviceIDParsed) return;
            
            mIsDeviceIDParsed = true;

            byte bTemp;
            ushort uTemp;

            MatchCollection matches = RegHardwareID.GlobalInstance.Matches(DeviceID);
            foreach (Match match in matches)
            {
                foreach (NamedGroup namedGroup in RegHardwareID.NAMED_GROUPS)
                {
                    Group g = match.Groups[namedGroup.GroupNumber];
                   if (g.Success)
                   {
                       switch ((RegHardwareID.ENamedGroups)namedGroup.GroupNumber)
                       {
                           case RegHardwareID.ENamedGroups.Vid:
                               if (ushort.TryParse(g.Value, NumberStyles.HexNumber, null, out uTemp))
                               {
                                   mVid = uTemp;
                                   break;
                               }
                               break;
                           case RegHardwareID.ENamedGroups.Pid:
                               if (ushort.TryParse(g.Value, NumberStyles.HexNumber, null, out uTemp))
                               {
                                   mPid = uTemp;
                                   break;
                               } 
                               break;
                           case RegHardwareID.ENamedGroups.Rev:
                               break;
                           case RegHardwareID.ENamedGroups.MI:
                               if (Byte.TryParse(g.Value, NumberStyles.HexNumber, null, out bTemp))
                               {
                                   mInterfaceID = bTemp;
                                   break;
                               }
                               break;
                           default:
                               throw new ArgumentOutOfRangeException();
                       }
                   }
                }

            }
        }

        /// <summary>
        /// Gets the device instance id.
        /// </summary>
        /// <remarks>
        /// For more information on device instance ids, see the <a href="http://msdn.microsoft.com/en-us/library/ff538405%28v=VS.85%29.aspx">CM_Get_Device_ID Function</a> at MSDN.
        /// </remarks>
        public string DeviceID
        {
            get
            {
                if (ReferenceEquals(mDeviceID,null))
                {
                    object oDeviceID;
                    if (mDeviceProperties.TryGetValue(DEVICE_ID_KEY, out oDeviceID))
                    {
                        mDeviceID = oDeviceID.ToString();
                    }
                    else
                    {
                        mDeviceID = string.Empty;
                    }
                }
                return mDeviceID;
            }
        }

        /// <summary>
        /// VendorID
        /// </summary>
        /// <remarks>This value is parsed out of the <see cref="DeviceID"/> field.</remarks>
        public override int Vid
        {
            get
            {
                parseDeviceID();
                return mVid;
            }
        }

        /// <summary>
        /// ProductID
        /// </summary>
        /// <remarks>This value is parsed out of the <see cref="DeviceID"/> field.</remarks>
        public override int Pid
        {
            get
            {
                parseDeviceID();
                return mPid;
            }
        }


        ///<summary>
        /// Gets the interface ID this WinUSB device (interface) is associated with.
        ///</summary>
        /// <remarks>This value is parsed out of the <see cref="DeviceID"/> field.</remarks>
        public byte InterfaceID
        {
            get
            {
                parseDeviceID();
                return (byte) mInterfaceID;
            }
        }

        /// <summary>
        /// Opens the USB device for communucation.
        /// </summary>
        /// <param name="usbDevice">The newly created UsbDevice.</param>
        /// <returns>True on success.</returns>
        public override bool Open(out UsbDevice usbDevice)
        {
            usbDevice = null;
            WinUsbDevice winUsbDevice;
            bool bSuccess = Open(out winUsbDevice);
            if (bSuccess)
                usbDevice = winUsbDevice;
            return bSuccess;
        }

        /// <summary>
        /// Opens the USB device for communucation.
        /// </summary>
        /// <param name="usbDevice">Returns an opened WinUsb device on success, null on failure.</param>
        /// <returns>True on success.</returns>
        public bool Open(out WinUsbDevice usbDevice)
        {
            usbDevice = null;

            if (String.IsNullOrEmpty(SymbolicName)) return false;
            if (WinUsbDevice.Open(SymbolicName, out usbDevice))
            {
                usbDevice.mUsbRegistry = this;
                return true;
            }
            return false;
        }

        /*
        private static bool WinUsbRegistryCallBack(IntPtr deviceInfoSet,
                                                   int deviceIndex,
                                                   ref SetupApi.SP_DEVINFO_DATA deviceInfoData,
                                                   object classEnumeratorCallbackParam1)
        {

            List<WinUsbRegistry> deviceList = (List<WinUsbRegistry>) classEnumeratorCallbackParam1;

            RegistryValueKind propertyType;
            byte[] propBuffer = new byte[256];
            int requiredSize;
            bool isNew = true;
            bool bSuccess;

            bSuccess = SetupApi.SetupDiGetCustomDeviceProperty(deviceInfoSet,
                                                                    ref deviceInfoData,
                                                                    DEVICE_INTERFACE_GUIDS,
                                                                    SetupApi.DICUSTOMDEVPROP.NONE,
                                                                    out propertyType,
                                                                    propBuffer,
                                                                    propBuffer.Length,
                                                                    out requiredSize);
            if (bSuccess)
            {
                string[] devInterfaceGuids = GetAsStringArray(propBuffer, requiredSize);

                foreach (String devInterfaceGuid in devInterfaceGuids)
                {
                    Guid g = new Guid(devInterfaceGuid);
                    List<string> devicePaths;
                    if (SetupApi.GetDevicePathList(g, out devicePaths))
                    {
                        foreach (string devicePath in devicePaths)
                        {
                            WinUsbRegistry regInfo = new WinUsbRegistry();

                            SetupApi.getSPDRPProperties(deviceInfoSet, ref deviceInfoData, regInfo.mDeviceProperties);

                            // Use the actual winusb device path for SYMBOLIC_NAME_KEY. This will be used to open the device.
                            regInfo.mDeviceProperties.Add(SYMBOLIC_NAME_KEY, devicePath);

                            regInfo.mDeviceInterfaceGuids = new Guid[] { g };

                            // Don't add duplicate devices (with the same device path)
                            WinUsbRegistry foundRegistry=null;
                            foreach (WinUsbRegistry usbRegistry in deviceList)
                            {
                                if (usbRegistry.SymbolicName == regInfo.SymbolicName)
                                {
                                    foundRegistry = usbRegistry;
                                    break;
                                }
                            }
                            if (foundRegistry == null)
                                deviceList.Add(regInfo);
                            else
                            {
                                if (isNew)
                                {
                                    deviceList.Remove(foundRegistry);
                                    deviceList.Add(regInfo);
                                }
                                else
                                {

                                    // If the device path already exists, add this compatible guid 
                                    // to the foundRegstry guid list.
                                    List<Guid> newGuidList = new List<Guid>(foundRegistry.mDeviceInterfaceGuids);
                                    if (!newGuidList.Contains(g))
                                    {
                                        newGuidList.Add(g);
                                        foundRegistry.mDeviceInterfaceGuids = newGuidList.ToArray();
                                    }
                                }
                            }
                            isNew = false;
                        }
                    }
                }
            }

            return false;
        }
        */
        private static bool WinUsbRegistryCallBack(IntPtr deviceInfoSet,
                                           int deviceIndex,
                                           ref SetupApi.SP_DEVINFO_DATA deviceInfoData,
                                           object classEnumeratorCallbackParam1)
        {

            List<WinUsbRegistry> deviceList = (List<WinUsbRegistry>)classEnumeratorCallbackParam1;

            RegistryValueKind propertyType;
            byte[] propBuffer = new byte[256];
            int requiredSize;
            bool bSuccess;

            bSuccess = SetupApi.SetupDiGetCustomDeviceProperty(deviceInfoSet,
                                                                    ref deviceInfoData,
                                                                    DEVICE_INTERFACE_GUIDS,
                                                                    SetupApi.DICUSTOMDEVPROP.NONE,
                                                                    out propertyType,
                                                                    propBuffer,
                                                                    propBuffer.Length,
                                                                    out requiredSize);
            if (bSuccess)
            {
                string[] devInterfaceGuids = GetAsStringArray(propBuffer, requiredSize);

                foreach (String devInterfaceGuid in devInterfaceGuids)
                {
                    Guid g = new Guid(devInterfaceGuid);
                    List<WinUsbRegistry> tempList;
                    if (GetWinUsbRegistryList(g, out tempList))
                    {
                        foreach (WinUsbRegistry regInfo in tempList)
                        {
                            // Don't add duplicate devices (with the same device path)
                            WinUsbRegistry foundRegistry = null;
                            foreach (WinUsbRegistry usbRegistry in deviceList)
                            {
                                if (usbRegistry.SymbolicName == regInfo.SymbolicName)
                                {
                                    foundRegistry = usbRegistry;
                                    break;
                                }
                            }
                            if (foundRegistry == null)
                                deviceList.Add(regInfo);
                            else
                            {
                                // If the device path already exists, add this compatible guid 
                                // to the foundRegstry guid list.
                                List<Guid> newGuidList = new List<Guid>(foundRegistry.mDeviceInterfaceGuids);
                                if (!newGuidList.Contains(g))
                                {
                                    newGuidList.Add(g);
                                    foundRegistry.mDeviceInterfaceGuids = newGuidList.ToArray();
                                }
                            }
                        }
                    }
                }
            }

            return false;
        }

    }
}