2 * This file is part of the libserialport project.
4 * Copyright (C) 2013-2014 Martin Ling <martin-libserialport@earth.li>
5 * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "libserialport.h"
23 #include "libserialport_internal.h"
25 /* USB path is a string of at most 8 decimal numbers < 128 separated by dots. */
26 #define MAX_USB_PATH ((8 * 3) + (7 * 1) + 1)
28 static void enumerate_hub(struct sp_port *port, const char *hub_name,
29 const char *parent_path, DEVINST dev_inst);
31 static char *wc_to_utf8(PWCHAR wc_buffer, ULONG size)
33 ULONG wc_length = size / sizeof(WCHAR);
35 char *utf8_str = NULL;
37 /* Allocate aligned wide char buffer */
38 if (!(wc_str = malloc(size + sizeof(WCHAR))))
41 /* Zero-terminate the wide char string. */
42 memcpy(wc_str, wc_buffer, size);
43 wc_str[wc_length] = 0;
45 /* Compute the size of the UTF-8 converted string. */
46 if (!(size = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wc_str, -1,
47 NULL, 0, NULL, NULL)))
50 /* Allocate UTF-8 output buffer. */
51 if (!(utf8_str = malloc(size)))
54 /* Actually converted to UTF-8. */
55 if (!WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wc_str, -1,
56 utf8_str, size, NULL, NULL)) {
69 static char *get_root_hub_name(HANDLE host_controller)
71 USB_ROOT_HUB_NAME root_hub_name;
72 PUSB_ROOT_HUB_NAME root_hub_name_wc;
73 char *root_hub_name_utf8;
76 /* Compute the size of the root hub name string. */
77 if (!DeviceIoControl(host_controller, IOCTL_USB_GET_ROOT_HUB_NAME, 0, 0,
78 &root_hub_name, sizeof(root_hub_name), &size, NULL))
81 /* Allocate wide char root hub name string. */
82 size = root_hub_name.ActualLength;
83 if (!(root_hub_name_wc = malloc(size)))
86 /* Actually get the root hub name string. */
87 if (!DeviceIoControl(host_controller, IOCTL_USB_GET_ROOT_HUB_NAME,
88 NULL, 0, root_hub_name_wc, size, &size, NULL)) {
89 free(root_hub_name_wc);
93 /* Convert the root hub name string to UTF-8. */
94 root_hub_name_utf8 = wc_to_utf8(root_hub_name_wc->RootHubName, size - offsetof(USB_ROOT_HUB_NAME, RootHubName));
95 free(root_hub_name_wc);
96 return root_hub_name_utf8;
99 static char *get_external_hub_name(HANDLE hub, ULONG connection_index)
101 USB_NODE_CONNECTION_NAME ext_hub_name;
102 PUSB_NODE_CONNECTION_NAME ext_hub_name_wc;
103 char *ext_hub_name_utf8;
106 /* Compute the size of the external hub name string. */
107 ext_hub_name.ConnectionIndex = connection_index;
108 if (!DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_NAME,
109 &ext_hub_name, sizeof(ext_hub_name),
110 &ext_hub_name, sizeof(ext_hub_name), &size, NULL))
113 /* Allocate wide char external hub name string. */
114 size = ext_hub_name.ActualLength;
115 if (size <= sizeof(ext_hub_name)
116 || !(ext_hub_name_wc = malloc(size)))
119 /* Get the name of the external hub attached to the specified port. */
120 ext_hub_name_wc->ConnectionIndex = connection_index;
121 if (!DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_NAME,
122 ext_hub_name_wc, size,
123 ext_hub_name_wc, size, &size, NULL)) {
124 free(ext_hub_name_wc);
128 /* Convert the external hub name string to UTF-8. */
129 ext_hub_name_utf8 = wc_to_utf8(ext_hub_name_wc->NodeName, size - offsetof(USB_NODE_CONNECTION_NAME, NodeName));
130 free(ext_hub_name_wc);
131 return ext_hub_name_utf8;
134 static char *get_string_descriptor(HANDLE hub_device, ULONG connection_index,
135 UCHAR descriptor_index)
137 char desc_req_buf[sizeof(USB_DESCRIPTOR_REQUEST) +
138 MAXIMUM_USB_STRING_LENGTH] = { 0 };
139 PUSB_DESCRIPTOR_REQUEST desc_req = (void *)desc_req_buf;
140 PUSB_STRING_DESCRIPTOR desc = (void *)(desc_req + 1);
141 ULONG size = sizeof(desc_req_buf);
143 desc_req->ConnectionIndex = connection_index;
144 desc_req->SetupPacket.wValue = (USB_STRING_DESCRIPTOR_TYPE << 8)
146 desc_req->SetupPacket.wIndex = 0;
147 desc_req->SetupPacket.wLength = size - sizeof(*desc_req);
149 if (!DeviceIoControl(hub_device,
150 IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION,
151 desc_req, size, desc_req, size, &size, NULL)
153 || desc->bDescriptorType != USB_STRING_DESCRIPTOR_TYPE
154 || desc->bLength != size - sizeof(*desc_req)
155 || desc->bLength % 2)
158 return wc_to_utf8(desc->bString, desc->bLength - offsetof(USB_STRING_DESCRIPTOR, bString));
161 static void enumerate_hub_ports(struct sp_port *port, HANDLE hub_device,
162 ULONG nb_ports, const char *parent_path, DEVINST dev_inst)
164 char path[MAX_USB_PATH];
167 for (index = 1; index <= nb_ports; index++) {
168 PUSB_NODE_CONNECTION_INFORMATION_EX connection_info_ex;
169 ULONG size = sizeof(*connection_info_ex) + (30 * sizeof(USB_PIPE_INFO));
171 if (!(connection_info_ex = malloc(size)))
174 connection_info_ex->ConnectionIndex = index;
175 if (!DeviceIoControl(hub_device,
176 IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX,
177 connection_info_ex, size,
178 connection_info_ex, size, &size, NULL)) {
180 * Try to get CONNECTION_INFORMATION if
181 * CONNECTION_INFORMATION_EX did not work.
183 PUSB_NODE_CONNECTION_INFORMATION connection_info;
185 size = sizeof(*connection_info) + (30 * sizeof(USB_PIPE_INFO));
186 if (!(connection_info = malloc(size))) {
187 free(connection_info_ex);
190 connection_info->ConnectionIndex = index;
191 if (!DeviceIoControl(hub_device,
192 IOCTL_USB_GET_NODE_CONNECTION_INFORMATION,
193 connection_info, size,
194 connection_info, size, &size, NULL)) {
195 free(connection_info);
196 free(connection_info_ex);
200 connection_info_ex->ConnectionIndex = connection_info->ConnectionIndex;
201 connection_info_ex->DeviceDescriptor = connection_info->DeviceDescriptor;
202 connection_info_ex->DeviceIsHub = connection_info->DeviceIsHub;
203 connection_info_ex->DeviceAddress = connection_info->DeviceAddress;
204 free(connection_info);
207 if (connection_info_ex->DeviceIsHub) {
208 /* Recursively enumerate external hub. */
210 if ((ext_hub_name = get_external_hub_name(hub_device, index))) {
211 snprintf(path, sizeof(path), "%s%ld.",
212 parent_path, connection_info_ex->ConnectionIndex);
213 enumerate_hub(port, ext_hub_name, path, dev_inst);
215 free(connection_info_ex);
217 snprintf(path, sizeof(path), "%s%ld",
218 parent_path, connection_info_ex->ConnectionIndex);
220 /* Check if this device is the one we search for. */
221 if (strcmp(path, port->usb_path)) {
222 free(connection_info_ex);
226 /* Finally grab detailed information regarding the device. */
227 port->usb_address = connection_info_ex->DeviceAddress + 1;
228 port->usb_vid = connection_info_ex->DeviceDescriptor.idVendor;
229 port->usb_pid = connection_info_ex->DeviceDescriptor.idProduct;
231 if (connection_info_ex->DeviceDescriptor.iManufacturer)
232 port->usb_manufacturer = get_string_descriptor(hub_device, index,
233 connection_info_ex->DeviceDescriptor.iManufacturer);
234 if (connection_info_ex->DeviceDescriptor.iProduct)
235 port->usb_product = get_string_descriptor(hub_device, index,
236 connection_info_ex->DeviceDescriptor.iProduct);
237 if (connection_info_ex->DeviceDescriptor.iSerialNumber) {
238 port->usb_serial = get_string_descriptor(hub_device, index,
239 connection_info_ex->DeviceDescriptor.iSerialNumber);
240 if (port->usb_serial == NULL) {
241 //composite device, get the parent's serial number
242 char device_id[MAX_DEVICE_ID_LEN];
243 if (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS) {
244 if (CM_Get_Device_IDA(dev_inst, device_id, sizeof(device_id), 0) == CR_SUCCESS)
245 port->usb_serial = strdup(strrchr(device_id, '\\')+1);
250 free(connection_info_ex);
256 static void enumerate_hub(struct sp_port *port, const char *hub_name,
257 const char *parent_path, DEVINST dev_inst)
259 USB_NODE_INFORMATION hub_info;
261 ULONG size = sizeof(hub_info);
264 /* Open the hub with its full name. */
265 if (!(device_name = malloc(strlen("\\\\.\\") + strlen(hub_name) + 1)))
267 strcpy(device_name, "\\\\.\\");
268 strcat(device_name, hub_name);
269 hub_device = CreateFile(device_name, GENERIC_WRITE, FILE_SHARE_WRITE,
270 NULL, OPEN_EXISTING, 0, NULL);
272 if (hub_device == INVALID_HANDLE_VALUE)
275 /* Get the number of ports of the hub. */
276 if (DeviceIoControl(hub_device, IOCTL_USB_GET_NODE_INFORMATION,
277 &hub_info, size, &hub_info, size, &size, NULL))
278 /* Enumerate the ports of the hub. */
279 enumerate_hub_ports(port, hub_device,
280 hub_info.u.HubInformation.HubDescriptor.bNumberOfPorts, parent_path, dev_inst);
282 CloseHandle(hub_device);
285 static void enumerate_host_controller(struct sp_port *port,
286 HANDLE host_controller_device,
291 if ((root_hub_name = get_root_hub_name(host_controller_device))) {
292 enumerate_hub(port, root_hub_name, "", dev_inst);
297 static void get_usb_details(struct sp_port *port, DEVINST dev_inst_match)
299 HDEVINFO device_info;
300 SP_DEVINFO_DATA device_info_data;
303 device_info = SetupDiGetClassDevs(&GUID_CLASS_USB_HOST_CONTROLLER, NULL, NULL,
304 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
305 device_info_data.cbSize = sizeof(device_info_data);
307 for (i = 0; SetupDiEnumDeviceInfo(device_info, i, &device_info_data); i++) {
308 SP_DEVICE_INTERFACE_DATA device_interface_data;
309 PSP_DEVICE_INTERFACE_DETAIL_DATA device_detail_data;
310 DEVINST dev_inst = dev_inst_match;
311 HANDLE host_controller_device;
313 device_interface_data.cbSize = sizeof(device_interface_data);
314 if (!SetupDiEnumDeviceInterfaces(device_info, 0,
315 &GUID_CLASS_USB_HOST_CONTROLLER,
316 i, &device_interface_data))
319 if (!SetupDiGetDeviceInterfaceDetail(device_info,&device_interface_data,
320 NULL, 0, &size, NULL)
321 && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
324 if (!(device_detail_data = malloc(size)))
326 device_detail_data->cbSize = sizeof(*device_detail_data);
327 if (!SetupDiGetDeviceInterfaceDetail(device_info,&device_interface_data,
328 device_detail_data, size, &size,
330 free(device_detail_data);
334 while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS
335 && dev_inst != device_info_data.DevInst) { }
336 if (dev_inst != device_info_data.DevInst) {
337 free(device_detail_data);
341 port->usb_bus = i + 1;
343 host_controller_device = CreateFile(device_detail_data->DevicePath,
344 GENERIC_WRITE, FILE_SHARE_WRITE,
345 NULL, OPEN_EXISTING, 0, NULL);
346 if (host_controller_device != INVALID_HANDLE_VALUE) {
347 enumerate_host_controller(port, host_controller_device, dev_inst_match);
348 CloseHandle(host_controller_device);
350 free(device_detail_data);
353 SetupDiDestroyDeviceInfoList(device_info);
357 SP_PRIV enum sp_return get_port_details(struct sp_port *port)
360 * Description limited to 127 char, anything longer
361 * would not be user friendly anyway.
363 char description[128];
364 SP_DEVINFO_DATA device_info_data = { .cbSize = sizeof(device_info_data) };
365 HDEVINFO device_info;
368 device_info = SetupDiGetClassDevs(NULL, 0, 0,
369 DIGCF_PRESENT | DIGCF_ALLCLASSES);
370 if (device_info == INVALID_HANDLE_VALUE)
371 RETURN_FAIL("SetupDiGetClassDevs() failed");
373 for (i = 0; SetupDiEnumDeviceInfo(device_info, i, &device_info_data); i++) {
376 char value[8], class[16];
380 /* Check if this is the device we are looking for. */
381 device_key = SetupDiOpenDevRegKey(device_info, &device_info_data,
383 DIREG_DEV, KEY_QUERY_VALUE);
384 if (device_key == INVALID_HANDLE_VALUE)
386 size = sizeof(value);
387 if (RegQueryValueExA(device_key, "PortName", NULL, &type, (LPBYTE)value,
388 &size) != ERROR_SUCCESS || type != REG_SZ) {
389 RegCloseKey(device_key);
392 RegCloseKey(device_key);
393 value[sizeof(value) - 1] = 0;
394 if (strcmp(value, port->name))
397 /* Check port transport type. */
398 dev_inst = device_info_data.DevInst;
399 size = sizeof(class);
401 while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS &&
402 (cr = CM_Get_DevNode_Registry_PropertyA(dev_inst,
403 CM_DRP_CLASS, 0, class, &size, 0)) != CR_SUCCESS) { }
404 if (cr == CR_SUCCESS) {
405 if (!strcmp(class, "USB"))
406 port->transport = SP_TRANSPORT_USB;
409 /* Get port description (friendly name). */
410 dev_inst = device_info_data.DevInst;
411 size = sizeof(description);
412 while ((cr = CM_Get_DevNode_Registry_PropertyA(dev_inst,
413 CM_DRP_FRIENDLYNAME, 0, description, &size, 0)) != CR_SUCCESS
414 && CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS) { }
415 if (cr == CR_SUCCESS)
416 port->description = strdup(description);
418 /* Get more informations for USB connected ports. */
419 if (port->transport == SP_TRANSPORT_USB) {
420 char usb_path[MAX_USB_PATH] = "", tmp[MAX_USB_PATH];
421 char device_id[MAX_DEVICE_ID_LEN];
423 /* Recurse over parents to build the USB device path. */
424 dev_inst = device_info_data.DevInst;
426 /* Verify that this layer of the tree is USB related. */
427 if (CM_Get_Device_IDA(dev_inst, device_id,
428 sizeof(device_id), 0) != CR_SUCCESS
429 || strncmp(device_id, "USB\\", 4))
432 /* Discard one layer for composite devices. */
433 char compat_ids[512], *p = compat_ids;
434 size = sizeof(compat_ids);
435 if (CM_Get_DevNode_Registry_PropertyA(dev_inst,
436 CM_DRP_COMPATIBLEIDS, 0,
438 &size, 0) == CR_SUCCESS) {
440 if (!strncmp(p, "USB\\COMPOSITE", 13))
448 /* Stop the recursion when reaching the USB root. */
449 if (!strncmp(device_id, "USB\\ROOT", 8))
452 /* Prepend the address of current USB layer to the USB path. */
454 size = sizeof(address);
455 if (CM_Get_DevNode_Registry_PropertyA(dev_inst, CM_DRP_ADDRESS,
456 0, &address, &size, 0) == CR_SUCCESS) {
457 strcpy(tmp, usb_path);
458 snprintf(usb_path, sizeof(usb_path), "%d%s%s",
459 (int)address, *tmp ? "." : "", tmp);
461 } while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS);
463 port->usb_path = strdup(usb_path);
465 /* Wake up the USB device to be able to read string descriptor. */
466 char *escaped_port_name;
468 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
469 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
470 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
471 handle = CreateFile(escaped_port_name, GENERIC_READ, 0, 0,
473 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, 0);
474 free(escaped_port_name);
477 /* Retrieve USB device details from the device descriptor. */
478 get_usb_details(port, device_info_data.DevInst);
483 SetupDiDestroyDeviceInfoList(device_info);
488 SP_PRIV enum sp_return list_ports(struct sp_port ***list)
492 DWORD max_value_len, max_data_size, max_data_len;
493 DWORD value_len, data_size, data_len;
494 DWORD type, index = 0;
500 DEBUG("Opening registry key");
501 if ((result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
502 0, KEY_QUERY_VALUE, &key)) != ERROR_SUCCESS) {
503 /* It's possible for this key to not exist if there are no serial ports
504 * at all. In that case we're done. Return a failure for any other error. */
505 if (result != ERROR_FILE_NOT_FOUND) {
506 SetLastError(result);
507 SET_FAIL(ret, "RegOpenKeyEx() failed");
511 DEBUG("Querying registry key value and data sizes");
512 if ((result = RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
513 &max_value_len, &max_data_size, NULL, NULL)) != ERROR_SUCCESS) {
514 SetLastError(result);
515 SET_FAIL(ret, "RegQueryInfoKey() failed");
518 max_data_len = max_data_size / sizeof(TCHAR);
519 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
520 SET_ERROR(ret, SP_ERR_MEM, "Registry value malloc failed");
523 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
524 SET_ERROR(ret, SP_ERR_MEM, "Registry data malloc failed");
527 DEBUG("Iterating over values");
529 value_len = max_value_len + 1,
530 data_size = max_data_size,
531 RegEnumValue(key, index, value, &value_len,
532 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
534 if (type == REG_SZ) {
535 data_len = data_size / sizeof(TCHAR);
536 data[data_len] = '\0';
538 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL);
540 name_len = data_len + 1;
542 if (!(name = malloc(name_len))) {
543 SET_ERROR(ret, SP_ERR_MEM, "Registry port name malloc failed");
547 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
551 DEBUG_FMT("Found port %s", name);
552 if (!(*list = list_append(*list, name))) {
553 SET_ERROR(ret, SP_ERR_MEM, "List append failed");