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 wc_bytes)
33 ULONG wc_length = wc_bytes / sizeof(WCHAR);
36 char *utf8_str = NULL;
38 /* Allocate aligned wide char buffer */
39 if (!(wc_str = malloc((wc_length + 1) * sizeof(WCHAR))))
42 /* Zero-terminate the wide char string. */
43 memcpy(wc_str, wc_buffer, wc_bytes);
44 wc_str[wc_length] = 0;
46 /* Compute the size of the UTF-8 converted string. */
47 if (!(utf8_bytes = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wc_str, -1,
48 NULL, 0, NULL, NULL)))
51 /* Allocate UTF-8 output buffer. */
52 if (!(utf8_str = malloc(utf8_bytes)))
55 /* Actually converted to UTF-8. */
56 if (!WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wc_str, -1,
57 utf8_str, utf8_bytes, NULL, NULL)) {
70 static char *get_root_hub_name(HANDLE host_controller)
72 USB_ROOT_HUB_NAME root_hub_name;
73 PUSB_ROOT_HUB_NAME root_hub_name_wc;
74 char *root_hub_name_utf8;
77 /* Compute the size of the root hub name string. */
78 if (!DeviceIoControl(host_controller, IOCTL_USB_GET_ROOT_HUB_NAME, 0, 0,
79 &root_hub_name, sizeof(root_hub_name), &size, NULL))
82 /* Allocate wide char root hub name string. */
83 size = root_hub_name.ActualLength;
84 if (!(root_hub_name_wc = malloc(size)))
87 /* Actually get the root hub name string. */
88 if (!DeviceIoControl(host_controller, IOCTL_USB_GET_ROOT_HUB_NAME,
89 NULL, 0, root_hub_name_wc, size, &size, NULL)) {
90 free(root_hub_name_wc);
94 /* Convert the root hub name string to UTF-8. */
95 root_hub_name_utf8 = wc_to_utf8(root_hub_name_wc->RootHubName, size - offsetof(USB_ROOT_HUB_NAME, RootHubName));
96 free(root_hub_name_wc);
97 return root_hub_name_utf8;
100 static char *get_external_hub_name(HANDLE hub, ULONG connection_index)
102 USB_NODE_CONNECTION_NAME ext_hub_name;
103 PUSB_NODE_CONNECTION_NAME ext_hub_name_wc;
104 char *ext_hub_name_utf8;
107 /* Compute the size of the external hub name string. */
108 ext_hub_name.ConnectionIndex = connection_index;
109 if (!DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_NAME,
110 &ext_hub_name, sizeof(ext_hub_name),
111 &ext_hub_name, sizeof(ext_hub_name), &size, NULL))
114 /* Allocate wide char external hub name string. */
115 size = ext_hub_name.ActualLength;
116 if (size <= sizeof(ext_hub_name)
117 || !(ext_hub_name_wc = malloc(size)))
120 /* Get the name of the external hub attached to the specified port. */
121 ext_hub_name_wc->ConnectionIndex = connection_index;
122 if (!DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_NAME,
123 ext_hub_name_wc, size,
124 ext_hub_name_wc, size, &size, NULL)) {
125 free(ext_hub_name_wc);
129 /* Convert the external hub name string to UTF-8. */
130 ext_hub_name_utf8 = wc_to_utf8(ext_hub_name_wc->NodeName, size - offsetof(USB_NODE_CONNECTION_NAME, NodeName));
131 free(ext_hub_name_wc);
132 return ext_hub_name_utf8;
135 static char *get_string_descriptor(HANDLE hub_device, ULONG connection_index,
136 UCHAR descriptor_index)
138 char desc_req_buf[sizeof(USB_DESCRIPTOR_REQUEST) +
139 MAXIMUM_USB_STRING_LENGTH] = { 0 };
140 PUSB_DESCRIPTOR_REQUEST desc_req = (void *)desc_req_buf;
141 PUSB_STRING_DESCRIPTOR desc = (void *)(desc_req + 1);
142 ULONG size = sizeof(desc_req_buf);
144 desc_req->ConnectionIndex = connection_index;
145 desc_req->SetupPacket.wValue = (USB_STRING_DESCRIPTOR_TYPE << 8)
147 desc_req->SetupPacket.wIndex = 0;
148 desc_req->SetupPacket.wLength = size - sizeof(*desc_req);
150 if (!DeviceIoControl(hub_device,
151 IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION,
152 desc_req, size, desc_req, size, &size, NULL)
154 || desc->bDescriptorType != USB_STRING_DESCRIPTOR_TYPE
155 || desc->bLength != size - sizeof(*desc_req)
156 || desc->bLength % 2)
159 return wc_to_utf8(desc->bString, desc->bLength - offsetof(USB_STRING_DESCRIPTOR, bString));
162 static void enumerate_hub_ports(struct sp_port *port, HANDLE hub_device,
163 ULONG nb_ports, const char *parent_path, DEVINST dev_inst)
165 char path[MAX_USB_PATH];
168 for (index = 1; index <= nb_ports; index++) {
169 PUSB_NODE_CONNECTION_INFORMATION_EX connection_info_ex;
170 ULONG size = sizeof(*connection_info_ex) + (30 * sizeof(USB_PIPE_INFO));
172 if (!(connection_info_ex = malloc(size)))
175 connection_info_ex->ConnectionIndex = index;
176 if (!DeviceIoControl(hub_device,
177 IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX,
178 connection_info_ex, size,
179 connection_info_ex, size, &size, NULL)) {
181 * Try to get CONNECTION_INFORMATION if
182 * CONNECTION_INFORMATION_EX did not work.
184 PUSB_NODE_CONNECTION_INFORMATION connection_info;
186 size = sizeof(*connection_info) + (30 * sizeof(USB_PIPE_INFO));
187 if (!(connection_info = malloc(size))) {
188 free(connection_info_ex);
191 connection_info->ConnectionIndex = index;
192 if (!DeviceIoControl(hub_device,
193 IOCTL_USB_GET_NODE_CONNECTION_INFORMATION,
194 connection_info, size,
195 connection_info, size, &size, NULL)) {
196 free(connection_info);
197 free(connection_info_ex);
201 connection_info_ex->ConnectionIndex = connection_info->ConnectionIndex;
202 connection_info_ex->DeviceDescriptor = connection_info->DeviceDescriptor;
203 connection_info_ex->DeviceIsHub = connection_info->DeviceIsHub;
204 connection_info_ex->DeviceAddress = connection_info->DeviceAddress;
205 free(connection_info);
208 if (connection_info_ex->DeviceIsHub) {
209 /* Recursively enumerate external hub. */
211 if ((ext_hub_name = get_external_hub_name(hub_device, index))) {
212 snprintf(path, sizeof(path), "%s%ld.",
213 parent_path, connection_info_ex->ConnectionIndex);
214 enumerate_hub(port, ext_hub_name, path, dev_inst);
216 free(connection_info_ex);
218 snprintf(path, sizeof(path), "%s%ld",
219 parent_path, connection_info_ex->ConnectionIndex);
221 /* Check if this device is the one we search for. */
222 if (strcmp(path, port->usb_path)) {
223 free(connection_info_ex);
227 /* Finally grab detailed information regarding the device. */
228 port->usb_address = connection_info_ex->DeviceAddress + 1;
229 port->usb_vid = connection_info_ex->DeviceDescriptor.idVendor;
230 port->usb_pid = connection_info_ex->DeviceDescriptor.idProduct;
232 if (connection_info_ex->DeviceDescriptor.iManufacturer)
233 port->usb_manufacturer = get_string_descriptor(hub_device, index,
234 connection_info_ex->DeviceDescriptor.iManufacturer);
235 if (connection_info_ex->DeviceDescriptor.iProduct)
236 port->usb_product = get_string_descriptor(hub_device, index,
237 connection_info_ex->DeviceDescriptor.iProduct);
238 if (connection_info_ex->DeviceDescriptor.iSerialNumber) {
239 port->usb_serial = get_string_descriptor(hub_device, index,
240 connection_info_ex->DeviceDescriptor.iSerialNumber);
241 if (port->usb_serial == NULL) {
242 //composite device, get the parent's serial number
243 char device_id[MAX_DEVICE_ID_LEN];
244 if (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS) {
245 if (CM_Get_Device_IDA(dev_inst, device_id, sizeof(device_id), 0) == CR_SUCCESS)
246 port->usb_serial = strdup(strrchr(device_id, '\\')+1);
251 free(connection_info_ex);
257 static void enumerate_hub(struct sp_port *port, const char *hub_name,
258 const char *parent_path, DEVINST dev_inst)
260 USB_NODE_INFORMATION hub_info;
262 ULONG size = sizeof(hub_info);
265 /* Open the hub with its full name. */
266 if (!(device_name = malloc(strlen("\\\\.\\") + strlen(hub_name) + 1)))
268 strcpy(device_name, "\\\\.\\");
269 strcat(device_name, hub_name);
270 hub_device = CreateFile(device_name, GENERIC_WRITE, FILE_SHARE_WRITE,
271 NULL, OPEN_EXISTING, 0, NULL);
273 if (hub_device == INVALID_HANDLE_VALUE)
276 /* Get the number of ports of the hub. */
277 if (DeviceIoControl(hub_device, IOCTL_USB_GET_NODE_INFORMATION,
278 &hub_info, size, &hub_info, size, &size, NULL))
279 /* Enumerate the ports of the hub. */
280 enumerate_hub_ports(port, hub_device,
281 hub_info.u.HubInformation.HubDescriptor.bNumberOfPorts, parent_path, dev_inst);
283 CloseHandle(hub_device);
286 static void enumerate_host_controller(struct sp_port *port,
287 HANDLE host_controller_device,
292 if ((root_hub_name = get_root_hub_name(host_controller_device))) {
293 enumerate_hub(port, root_hub_name, "", dev_inst);
298 static void get_usb_details(struct sp_port *port, DEVINST dev_inst_match)
300 HDEVINFO device_info;
301 SP_DEVINFO_DATA device_info_data;
304 device_info = SetupDiGetClassDevs(&GUID_CLASS_USB_HOST_CONTROLLER, NULL, NULL,
305 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
306 device_info_data.cbSize = sizeof(device_info_data);
308 for (i = 0; SetupDiEnumDeviceInfo(device_info, i, &device_info_data); i++) {
309 SP_DEVICE_INTERFACE_DATA device_interface_data;
310 PSP_DEVICE_INTERFACE_DETAIL_DATA device_detail_data;
311 DEVINST dev_inst = dev_inst_match;
312 HANDLE host_controller_device;
314 device_interface_data.cbSize = sizeof(device_interface_data);
315 if (!SetupDiEnumDeviceInterfaces(device_info, 0,
316 &GUID_CLASS_USB_HOST_CONTROLLER,
317 i, &device_interface_data))
320 if (!SetupDiGetDeviceInterfaceDetail(device_info,&device_interface_data,
321 NULL, 0, &size, NULL)
322 && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
325 if (!(device_detail_data = malloc(size)))
327 device_detail_data->cbSize = sizeof(*device_detail_data);
328 if (!SetupDiGetDeviceInterfaceDetail(device_info,&device_interface_data,
329 device_detail_data, size, &size,
331 free(device_detail_data);
335 while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS
336 && dev_inst != device_info_data.DevInst) { }
337 if (dev_inst != device_info_data.DevInst) {
338 free(device_detail_data);
342 port->usb_bus = i + 1;
344 host_controller_device = CreateFile(device_detail_data->DevicePath,
345 GENERIC_WRITE, FILE_SHARE_WRITE,
346 NULL, OPEN_EXISTING, 0, NULL);
347 if (host_controller_device != INVALID_HANDLE_VALUE) {
348 enumerate_host_controller(port, host_controller_device, dev_inst_match);
349 CloseHandle(host_controller_device);
351 free(device_detail_data);
354 SetupDiDestroyDeviceInfoList(device_info);
358 SP_PRIV enum sp_return get_port_details(struct sp_port *port)
361 * Description limited to 127 char, anything longer
362 * would not be user friendly anyway.
364 char description[128];
365 SP_DEVINFO_DATA device_info_data = { .cbSize = sizeof(device_info_data) };
366 HDEVINFO device_info;
369 device_info = SetupDiGetClassDevs(NULL, 0, 0,
370 DIGCF_PRESENT | DIGCF_ALLCLASSES);
371 if (device_info == INVALID_HANDLE_VALUE)
372 RETURN_FAIL("SetupDiGetClassDevs() failed");
374 for (i = 0; SetupDiEnumDeviceInfo(device_info, i, &device_info_data); i++) {
377 char value[8], class[16];
381 /* Check if this is the device we are looking for. */
382 device_key = SetupDiOpenDevRegKey(device_info, &device_info_data,
384 DIREG_DEV, KEY_QUERY_VALUE);
385 if (device_key == INVALID_HANDLE_VALUE)
387 size = sizeof(value);
388 if (RegQueryValueExA(device_key, "PortName", NULL, &type, (LPBYTE)value,
389 &size) != ERROR_SUCCESS || type != REG_SZ) {
390 RegCloseKey(device_key);
393 RegCloseKey(device_key);
394 value[sizeof(value) - 1] = 0;
395 if (strcmp(value, port->name))
398 /* Check port transport type. */
399 dev_inst = device_info_data.DevInst;
400 size = sizeof(class);
402 while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS &&
403 (cr = CM_Get_DevNode_Registry_PropertyA(dev_inst,
404 CM_DRP_CLASS, 0, class, &size, 0)) != CR_SUCCESS) { }
405 if (cr == CR_SUCCESS) {
406 if (!strcmp(class, "USB"))
407 port->transport = SP_TRANSPORT_USB;
410 /* Get port description (friendly name). */
411 dev_inst = device_info_data.DevInst;
412 size = sizeof(description);
413 while ((cr = CM_Get_DevNode_Registry_PropertyA(dev_inst,
414 CM_DRP_FRIENDLYNAME, 0, description, &size, 0)) != CR_SUCCESS
415 && CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS) { }
416 if (cr == CR_SUCCESS)
417 port->description = strdup(description);
419 /* Get more informations for USB connected ports. */
420 if (port->transport == SP_TRANSPORT_USB) {
421 char usb_path[MAX_USB_PATH] = "", tmp[MAX_USB_PATH];
422 char device_id[MAX_DEVICE_ID_LEN];
424 /* Recurse over parents to build the USB device path. */
425 dev_inst = device_info_data.DevInst;
427 /* Verify that this layer of the tree is USB related. */
428 if (CM_Get_Device_IDA(dev_inst, device_id,
429 sizeof(device_id), 0) != CR_SUCCESS
430 || strncmp(device_id, "USB\\", 4))
433 /* Discard one layer for composite devices. */
434 char compat_ids[512], *p = compat_ids;
435 size = sizeof(compat_ids);
436 if (CM_Get_DevNode_Registry_PropertyA(dev_inst,
437 CM_DRP_COMPATIBLEIDS, 0,
439 &size, 0) == CR_SUCCESS) {
441 if (!strncmp(p, "USB\\COMPOSITE", 13))
449 /* Stop the recursion when reaching the USB root. */
450 if (!strncmp(device_id, "USB\\ROOT", 8))
453 /* Prepend the address of current USB layer to the USB path. */
455 size = sizeof(address);
456 if (CM_Get_DevNode_Registry_PropertyA(dev_inst, CM_DRP_ADDRESS,
457 0, &address, &size, 0) == CR_SUCCESS) {
458 strcpy(tmp, usb_path);
459 snprintf(usb_path, sizeof(usb_path), "%d%s%s",
460 (int)address, *tmp ? "." : "", tmp);
462 } while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS);
464 port->usb_path = strdup(usb_path);
466 /* Wake up the USB device to be able to read string descriptor. */
467 char *escaped_port_name;
469 if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
470 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
471 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
472 handle = CreateFile(escaped_port_name, GENERIC_READ, 0, 0,
474 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, 0);
475 free(escaped_port_name);
478 /* Retrieve USB device details from the device descriptor. */
479 get_usb_details(port, device_info_data.DevInst);
484 SetupDiDestroyDeviceInfoList(device_info);
489 SP_PRIV enum sp_return list_ports(struct sp_port ***list)
493 DWORD max_value_len, max_data_size, max_data_len;
494 DWORD value_len, data_size, data_len;
495 DWORD type, index = 0;
501 DEBUG("Opening registry key");
502 if ((result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
503 0, KEY_QUERY_VALUE, &key)) != ERROR_SUCCESS) {
504 /* It's possible for this key to not exist if there are no serial ports
505 * at all. In that case we're done. Return a failure for any other error. */
506 if (result != ERROR_FILE_NOT_FOUND) {
507 SetLastError(result);
508 SET_FAIL(ret, "RegOpenKeyEx() failed");
512 DEBUG("Querying registry key value and data sizes");
513 if ((result = RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
514 &max_value_len, &max_data_size, NULL, NULL)) != ERROR_SUCCESS) {
515 SetLastError(result);
516 SET_FAIL(ret, "RegQueryInfoKey() failed");
519 max_data_len = max_data_size / sizeof(TCHAR);
520 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
521 SET_ERROR(ret, SP_ERR_MEM, "Registry value malloc failed");
524 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
525 SET_ERROR(ret, SP_ERR_MEM, "Registry data malloc failed");
528 DEBUG("Iterating over values");
530 value_len = max_value_len + 1,
531 data_size = max_data_size,
532 RegEnumValue(key, index, value, &value_len,
533 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
535 if (type == REG_SZ) {
536 data_len = data_size / sizeof(TCHAR);
537 data[data_len] = '\0';
539 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL);
541 name_len = data_len + 1;
543 if (!(name = malloc(name_len))) {
544 SET_ERROR(ret, SP_ERR_MEM, "Registry port name malloc failed");
548 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
552 DEBUG_FMT("Found port %s", name);
553 if (!(*list = list_append(*list, name))) {
554 SET_ERROR(ret, SP_ERR_MEM, "List append failed");