]> sigrok.org Git - libserialport.git/blob - windows.c
Fix missing variable on macosx.
[libserialport.git] / windows.c
1 /*
2  * This file is part of the libserialport project.
3  *
4  * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation, either version 3 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "libserialport.h"
21 #include "libserialport_internal.h"
22
23 /* USB path is a string of at most 8 decimal numbers < 128 separated by dots */
24 #define MAX_USB_PATH  (8*3 + 7*1 + 1)
25
26 static void enumerate_hub(struct sp_port *port, char *hub_name,
27                           char *parent_path);
28
29 static char *wc_to_utf8(PWCHAR wc_buffer, ULONG size)
30 {
31         WCHAR wc_str[size/sizeof(WCHAR)+1];
32         char *utf8_str;
33
34         /* zero terminate the wide char string */
35         memcpy(wc_str, wc_buffer, size);
36         wc_str[sizeof(wc_str)-1] = 0;
37
38         /* compute the size of the utf8 converted string */
39         if (!(size = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wc_str, -1,
40                                          NULL, 0, NULL, NULL)))
41                 return NULL;
42
43         /* allocate utf8 output buffer */
44         if (!(utf8_str = malloc(size)))
45                 return NULL;
46
47         /* actually converted to utf8 */
48         if (!WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wc_str, -1,
49                                  utf8_str, size, NULL, NULL)) {
50                 free(utf8_str);
51                 return NULL;
52         }
53
54         return utf8_str;
55 }
56
57 static char *get_root_hub_name(HANDLE host_controller)
58 {
59         USB_ROOT_HUB_NAME  root_hub_name;
60         PUSB_ROOT_HUB_NAME root_hub_name_wc;
61         char *root_hub_name_utf8;
62         ULONG size = 0;
63
64         /* compute the size of the root hub name string */
65         if (!DeviceIoControl(host_controller, IOCTL_USB_GET_ROOT_HUB_NAME, 0, 0,
66                              &root_hub_name, sizeof(root_hub_name), &size, NULL))
67                 return NULL;
68
69         /* allocate wide char root hub name string */
70         size = root_hub_name.ActualLength;
71         if (!(root_hub_name_wc = malloc(size)))
72                 return NULL;
73
74         /* actually get the root hub name string */
75         if (!DeviceIoControl(host_controller, IOCTL_USB_GET_ROOT_HUB_NAME,
76                              NULL, 0, root_hub_name_wc, size, &size, NULL)) {
77                 free(root_hub_name_wc);
78                 return NULL;
79         }
80
81         /* convert the root hub name string to utf8 */
82         root_hub_name_utf8 = wc_to_utf8(root_hub_name_wc->RootHubName, size);
83         free(root_hub_name_wc);
84         return root_hub_name_utf8;
85 }
86
87 static char *get_external_hub_name(HANDLE hub, ULONG connection_index)
88 {
89         USB_NODE_CONNECTION_NAME  ext_hub_name;
90         PUSB_NODE_CONNECTION_NAME ext_hub_name_wc;
91         char *ext_hub_name_utf8;
92         ULONG size;
93
94         /* compute the size of the external hub name string */
95         ext_hub_name.ConnectionIndex = connection_index;
96         if (!DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_NAME,
97                              &ext_hub_name, sizeof(ext_hub_name),
98                              &ext_hub_name, sizeof(ext_hub_name), &size, NULL))
99                 return NULL;
100
101         /* allocate wide char external hub name string */
102         size = ext_hub_name.ActualLength;
103         if (size <= sizeof(ext_hub_name)
104             || !(ext_hub_name_wc = malloc(size)))
105                 return NULL;
106
107         /* get the name of the external hub attached to the specified port */
108         ext_hub_name_wc->ConnectionIndex = connection_index;
109         if (!DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_NAME,
110                              ext_hub_name_wc, size,
111                              ext_hub_name_wc, size, &size, NULL)) {
112                 free(ext_hub_name_wc);
113                 return NULL;
114         }
115
116         /* convert the external hub name string to utf8 */
117         ext_hub_name_utf8 = wc_to_utf8(ext_hub_name_wc->NodeName, size);
118         free(ext_hub_name_wc);
119         return ext_hub_name_utf8;
120 }
121
122 static char *get_string_descriptor(HANDLE hub_device, ULONG connection_index,
123                                    UCHAR descriptor_index)
124 {
125         char desc_req_buf[sizeof(USB_DESCRIPTOR_REQUEST) +
126                           MAXIMUM_USB_STRING_LENGTH] = { 0 };
127         PUSB_DESCRIPTOR_REQUEST desc_req = (void *) desc_req_buf;
128         PUSB_STRING_DESCRIPTOR  desc     = (void *) (desc_req + 1);
129         ULONG size = sizeof(desc_req_buf);
130
131         desc_req->ConnectionIndex     = connection_index;
132         desc_req->SetupPacket.wValue  = (USB_STRING_DESCRIPTOR_TYPE << 8)
133                                         | descriptor_index;
134         desc_req->SetupPacket.wIndex  = 0;
135         desc_req->SetupPacket.wLength = size - sizeof(*desc_req);
136
137         if (!DeviceIoControl(hub_device,
138                              IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION,
139                              desc_req, size, desc_req, size, &size, NULL)
140             || size < 2
141             || desc->bDescriptorType != USB_STRING_DESCRIPTOR_TYPE
142             || desc->bLength != size - sizeof(*desc_req)
143             || desc->bLength % 2)
144                 return NULL;
145
146         return wc_to_utf8(desc->bString, desc->bLength);
147 }
148
149 static void enumerate_hub_ports(struct sp_port *port, HANDLE hub_device,
150                                 ULONG nb_ports, char *parent_path)
151 {
152         char path[MAX_USB_PATH];
153         ULONG index = 0;
154
155         for (index = 1; index <= nb_ports; index++) {
156                 PUSB_NODE_CONNECTION_INFORMATION_EX connection_info_ex;
157                 ULONG size = sizeof(*connection_info_ex) + 30*sizeof(USB_PIPE_INFO);
158
159                 if (!(connection_info_ex = malloc(size)))
160                         break;
161
162                 connection_info_ex->ConnectionIndex = index;
163                 if (!DeviceIoControl(hub_device,
164                                      IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX,
165                                      connection_info_ex, size,
166                                      connection_info_ex, size, &size, NULL)) {
167                         /* try to get CONNECTION_INFORMATION if CONNECTION_INFORMATION_EX
168                            did not work */
169                         PUSB_NODE_CONNECTION_INFORMATION connection_info;
170
171                         size = sizeof(*connection_info) + 30*sizeof(USB_PIPE_INFO);
172                         if (!(connection_info = malloc(size))) {
173                                 free(connection_info_ex);
174                                 continue;
175                         }
176                         connection_info->ConnectionIndex = index;
177                         if (!DeviceIoControl(hub_device,
178                                              IOCTL_USB_GET_NODE_CONNECTION_INFORMATION,
179                                              connection_info, size,
180                                              connection_info, size, &size, NULL)) {
181                                 free(connection_info);
182                                 free(connection_info_ex);
183                                 continue;
184                         }
185
186                         connection_info_ex->ConnectionIndex = connection_info->ConnectionIndex;
187                         connection_info_ex->DeviceDescriptor = connection_info->DeviceDescriptor;
188                         connection_info_ex->DeviceIsHub = connection_info->DeviceIsHub;
189                         connection_info_ex->DeviceAddress = connection_info->DeviceAddress;
190                         free(connection_info);
191                 }
192
193                 if (connection_info_ex->DeviceIsHub) {
194                         /* recursively enumerate external hub */
195                         PCHAR ext_hub_name;
196                         if ((ext_hub_name = get_external_hub_name(hub_device, index))) {
197                                 snprintf(path, sizeof(path), "%s%ld.",
198                                          parent_path, connection_info_ex->ConnectionIndex);
199                                 enumerate_hub(port, ext_hub_name, path);
200                         }
201                         free(connection_info_ex);
202                 } else {
203                         snprintf(path, sizeof(path), "%s%ld",
204                                  parent_path, connection_info_ex->ConnectionIndex);
205
206                         /* check if this device is the one we search for */
207                         if (strcmp(path, port->usb_path)) {
208                                 free(connection_info_ex);
209                                 continue;
210                         }
211
212                         /* finally grab detailed informations regarding the device */
213                         port->usb_address = connection_info_ex->DeviceAddress + 1;
214                         port->usb_vid = connection_info_ex->DeviceDescriptor.idVendor;
215                         port->usb_pid = connection_info_ex->DeviceDescriptor.idProduct;
216
217                         if (connection_info_ex->DeviceDescriptor.iManufacturer)
218                                 port->usb_manufacturer = get_string_descriptor(hub_device,index,
219                                            connection_info_ex->DeviceDescriptor.iManufacturer);
220                         if (connection_info_ex->DeviceDescriptor.iProduct)
221                                 port->usb_product = get_string_descriptor(hub_device, index,
222                                            connection_info_ex->DeviceDescriptor.iProduct);
223                         if (connection_info_ex->DeviceDescriptor.iSerialNumber)
224                                 port->usb_serial = get_string_descriptor(hub_device, index,
225                                            connection_info_ex->DeviceDescriptor.iSerialNumber);
226
227                         free(connection_info_ex);
228                         break;
229                 }
230         }
231 }
232
233 static void enumerate_hub(struct sp_port *port, char *hub_name,
234                           char *parent_path)
235 {
236         USB_NODE_INFORMATION hub_info;
237         HANDLE hub_device;
238         ULONG size = sizeof(hub_info);
239         char *device_name;
240
241         /* open the hub with its full name */
242         if (!(device_name = malloc(strlen("\\\\.\\") + strlen(hub_name) + 1)))
243                 return;
244         strcpy(device_name, "\\\\.\\");
245         strcat(device_name, hub_name);
246         hub_device = CreateFile(device_name, GENERIC_WRITE, FILE_SHARE_WRITE,
247                                 NULL, OPEN_EXISTING, 0, NULL);
248         free(device_name);
249         if (hub_device == INVALID_HANDLE_VALUE)
250                 return;
251
252         /* get the number of ports of the hub */
253         if (DeviceIoControl(hub_device, IOCTL_USB_GET_NODE_INFORMATION,
254                             &hub_info, size, &hub_info, size, &size, NULL))
255                 /* enumarate the ports of the hub */
256                 enumerate_hub_ports(port, hub_device,
257                    hub_info.u.HubInformation.HubDescriptor.bNumberOfPorts, parent_path);
258
259         CloseHandle(hub_device);
260 }
261
262 static void enumerate_host_controller(struct sp_port *port,
263                                       HANDLE host_controller_device)
264 {
265         char *root_hub_name;
266
267         if ((root_hub_name = get_root_hub_name(host_controller_device))) {
268                 enumerate_hub(port, root_hub_name, "");
269                 free(root_hub_name);
270         }
271 }
272
273 static void get_usb_details(struct sp_port *port, DEVINST dev_inst_match)
274 {
275         HDEVINFO device_info;
276         SP_DEVINFO_DATA device_info_data;
277         ULONG i, size = 0;
278
279         device_info = SetupDiGetClassDevs(&GUID_CLASS_USB_HOST_CONTROLLER,NULL,NULL,
280                                           DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
281         device_info_data.cbSize = sizeof(device_info_data);
282
283         for (i=0; SetupDiEnumDeviceInfo(device_info, i, &device_info_data); i++) {
284                 SP_DEVICE_INTERFACE_DATA device_interface_data;
285                 PSP_DEVICE_INTERFACE_DETAIL_DATA device_detail_data;
286                 DEVINST dev_inst = dev_inst_match;
287                 HANDLE host_controller_device;
288
289                 device_interface_data.cbSize = sizeof(device_interface_data);
290                 if (!SetupDiEnumDeviceInterfaces(device_info, 0,
291                                                  &GUID_CLASS_USB_HOST_CONTROLLER,
292                                                  i, &device_interface_data))
293                         continue;
294
295                 if (!SetupDiGetDeviceInterfaceDetail(device_info,&device_interface_data,
296                                                      NULL, 0, &size, NULL)
297                     && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
298                         continue;
299
300                 if (!(device_detail_data = malloc(size)))
301                         continue;
302                 device_detail_data->cbSize = sizeof(*device_detail_data);
303                 if (!SetupDiGetDeviceInterfaceDetail(device_info,&device_interface_data,
304                                                      device_detail_data, size, &size,
305                                                      NULL)) {
306                         free(device_detail_data);
307                         continue;
308                 }
309
310                 while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS
311                        && dev_inst != device_info_data.DevInst) { }
312                 if (dev_inst != device_info_data.DevInst) {
313                         free(device_detail_data);
314                         continue;
315                 }
316
317                 port->usb_bus = i + 1;
318
319                 host_controller_device = CreateFile(device_detail_data->DevicePath,
320                                                     GENERIC_WRITE, FILE_SHARE_WRITE,
321                                                     NULL, OPEN_EXISTING, 0, NULL);
322                 if (host_controller_device != INVALID_HANDLE_VALUE) {
323                         enumerate_host_controller(port, host_controller_device);
324                         CloseHandle(host_controller_device);
325                 }
326                 free(device_detail_data);
327         }
328
329         SetupDiDestroyDeviceInfoList(device_info);
330         return;
331 }
332
333 enum sp_return get_port_details(struct sp_port *port)
334 {
335         /* Description limited to 127 char,
336            anything longer would not be user friendly anyway */
337         char description[128];
338         SP_DEVINFO_DATA device_info_data = { .cbSize = sizeof(device_info_data) };
339         HDEVINFO device_info;
340         int i;
341
342         device_info = SetupDiGetClassDevs(NULL, 0, 0,
343                                           DIGCF_PRESENT | DIGCF_ALLCLASSES);
344         if (device_info == INVALID_HANDLE_VALUE)
345                 RETURN_FAIL("SetupDiGetClassDevs() failed");
346
347         for (i=0; SetupDiEnumDeviceInfo(device_info, i, &device_info_data); i++) {
348                 HKEY device_key;
349                 DEVINST dev_inst;
350                 char value[8], class[16];
351                 DWORD size, type;
352                 CONFIGRET cr;
353
354                 /* check if this is the device we are looking for */
355                 if (!(device_key = SetupDiOpenDevRegKey(device_info, &device_info_data,
356                                                         DICS_FLAG_GLOBAL, 0,
357                                                         DIREG_DEV, KEY_QUERY_VALUE)))
358                         continue;
359                 size = sizeof(value);
360                 if (RegQueryValueExA(device_key, "PortName", NULL, &type, (LPBYTE)value,
361                                      &size) != ERROR_SUCCESS || type != REG_SZ)
362                         continue;
363                 RegCloseKey(device_key);
364                 value[sizeof(value)-1] = 0;
365                 if (strcmp(value, port->name))
366                         continue;
367
368                 /* check port transport type */
369                 dev_inst = device_info_data.DevInst;
370                 size = sizeof(class);
371                 cr = CR_FAILURE;
372                 while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS &&
373                        (cr = CM_Get_DevNode_Registry_PropertyA(dev_inst,
374                                  CM_DRP_CLASS, 0, class, &size, 0)) != CR_SUCCESS) { }
375                 if (cr == CR_SUCCESS) {
376                         if (!strcmp(class, "USB"))
377                                 port->transport = SP_TRANSPORT_USB;
378                 }
379
380                 /* get port description (friendly name) */
381                 dev_inst = device_info_data.DevInst;
382                 size = sizeof(description);
383                 while ((cr = CM_Get_DevNode_Registry_PropertyA(dev_inst,
384                           CM_DRP_FRIENDLYNAME, 0, description, &size, 0)) != CR_SUCCESS
385                        && CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS) { }
386                 if (cr == CR_SUCCESS)
387                         port->description = strdup(description);
388
389                 /* get more informations for USB connected ports */
390                 if (port->transport == SP_TRANSPORT_USB) {
391                         char usb_path[MAX_USB_PATH] = "", tmp[MAX_USB_PATH];
392                         char device_id[MAX_DEVICE_ID_LEN];
393
394                         /* recurse over parents to build the USB device path */
395                         dev_inst = device_info_data.DevInst;
396                         do {
397                                 /* verify that this layer of the tree is USB related */
398                                 if (CM_Get_Device_IDA(dev_inst, device_id,
399                                                       sizeof(device_id), 0) != CR_SUCCESS
400                                     || strncmp(device_id, "USB\\", 4))
401                                         continue;
402
403                                 /* discard one layer for composite devices */
404                                 char compat_ids[512], *p = compat_ids;
405                                 size = sizeof(compat_ids);
406                                 if (CM_Get_DevNode_Registry_PropertyA(dev_inst,
407                                                                       CM_DRP_COMPATIBLEIDS, 0,
408                                                                       &compat_ids,
409                                                                       &size, 0) == CR_SUCCESS) {
410                                         while (*p) {
411                                                 if (!strncmp(p, "USB\\COMPOSITE", 13))
412                                                         break;
413                                                 p += strlen(p) + 1;
414                                         }
415                                         if (*p)
416                                                 continue;
417                                 }
418
419                                 /* stop the recursion when reaching the USB root */
420                                 if (!strncmp(device_id, "USB\\ROOT", 8))
421                                         break;
422
423                                 /* prepend the address of current USB layer to the USB path */
424                                 DWORD address;
425                                 size = sizeof(address);
426                                 if (CM_Get_DevNode_Registry_PropertyA(dev_inst, CM_DRP_ADDRESS,
427                                                         0, &address, &size, 0) == CR_SUCCESS) {
428                                         strcpy(tmp, usb_path);
429                                         snprintf(usb_path, sizeof(usb_path), "%d%s%s",
430                                                  (int)address, *tmp ? "." : "", tmp);
431                                 }
432                         } while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS);
433
434                         port->usb_path = strdup(usb_path);
435
436                         /* wake up the USB device to be able to read string descriptor */
437                         char *escaped_port_name;
438                         HANDLE handle;
439                         if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
440                                 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
441                         sprintf(escaped_port_name, "\\\\.\\%s", port->name);
442                         handle = CreateFile(escaped_port_name, GENERIC_READ, 0, 0,
443                                             OPEN_EXISTING,
444                                             FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, 0);
445                         free(escaped_port_name);
446                         CloseHandle(handle);
447
448                         /* retrive USB device details from the device descriptor */
449                         get_usb_details(port, device_info_data.DevInst);
450                 }
451                 break;
452         }
453
454         RETURN_OK();
455 }
456