]> sigrok.org Git - libserialport.git/blob - windows.c
use readdir() instead of the deprecated readir_r()
[libserialport.git] / windows.c
1 /*
2  * This file is part of the libserialport project.
3  *
4  * Copyright (C) 2013-2014 Martin Ling <martin-libserialport@earth.li>
5  * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
21 #include <config.h>
22 #include "libserialport.h"
23 #include "libserialport_internal.h"
24
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)
27
28 static void enumerate_hub(struct sp_port *port, const char *hub_name,
29                           const char *parent_path, DEVINST dev_inst);
30
31 static char *wc_to_utf8(PWCHAR wc_buffer, ULONG size)
32 {
33         WCHAR wc_str[(size / sizeof(WCHAR)) + 1];
34         char *utf8_str;
35
36         /* Zero-terminate the wide char string. */
37         memcpy(wc_str, wc_buffer, size);
38         wc_str[sizeof(wc_str) - 1] = 0;
39
40         /* Compute the size of the UTF-8 converted string. */
41         if (!(size = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wc_str, -1,
42                                          NULL, 0, NULL, NULL)))
43                 return NULL;
44
45         /* Allocate UTF-8 output buffer. */
46         if (!(utf8_str = malloc(size)))
47                 return NULL;
48
49         /* Actually converted to UTF-8. */
50         if (!WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wc_str, -1,
51                                  utf8_str, size, NULL, NULL)) {
52                 free(utf8_str);
53                 return NULL;
54         }
55
56         return utf8_str;
57 }
58
59 static char *get_root_hub_name(HANDLE host_controller)
60 {
61         USB_ROOT_HUB_NAME root_hub_name;
62         PUSB_ROOT_HUB_NAME root_hub_name_wc;
63         char *root_hub_name_utf8;
64         ULONG size = 0;
65
66         /* Compute the size of the root hub name string. */
67         if (!DeviceIoControl(host_controller, IOCTL_USB_GET_ROOT_HUB_NAME, 0, 0,
68                              &root_hub_name, sizeof(root_hub_name), &size, NULL))
69                 return NULL;
70
71         /* Allocate wide char root hub name string. */
72         size = root_hub_name.ActualLength;
73         if (!(root_hub_name_wc = malloc(size)))
74                 return NULL;
75
76         /* Actually get the root hub name string. */
77         if (!DeviceIoControl(host_controller, IOCTL_USB_GET_ROOT_HUB_NAME,
78                              NULL, 0, root_hub_name_wc, size, &size, NULL)) {
79                 free(root_hub_name_wc);
80                 return NULL;
81         }
82
83         /* Convert the root hub name string to UTF-8. */
84         root_hub_name_utf8 = wc_to_utf8(root_hub_name_wc->RootHubName, size);
85         free(root_hub_name_wc);
86         return root_hub_name_utf8;
87 }
88
89 static char *get_external_hub_name(HANDLE hub, ULONG connection_index)
90 {
91         USB_NODE_CONNECTION_NAME ext_hub_name;
92         PUSB_NODE_CONNECTION_NAME ext_hub_name_wc;
93         char *ext_hub_name_utf8;
94         ULONG size;
95
96         /* Compute the size of the external hub name string. */
97         ext_hub_name.ConnectionIndex = connection_index;
98         if (!DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_NAME,
99                              &ext_hub_name, sizeof(ext_hub_name),
100                              &ext_hub_name, sizeof(ext_hub_name), &size, NULL))
101                 return NULL;
102
103         /* Allocate wide char external hub name string. */
104         size = ext_hub_name.ActualLength;
105         if (size <= sizeof(ext_hub_name)
106             || !(ext_hub_name_wc = malloc(size)))
107                 return NULL;
108
109         /* Get the name of the external hub attached to the specified port. */
110         ext_hub_name_wc->ConnectionIndex = connection_index;
111         if (!DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_NAME,
112                              ext_hub_name_wc, size,
113                              ext_hub_name_wc, size, &size, NULL)) {
114                 free(ext_hub_name_wc);
115                 return NULL;
116         }
117
118         /* Convert the external hub name string to UTF-8. */
119         ext_hub_name_utf8 = wc_to_utf8(ext_hub_name_wc->NodeName, size);
120         free(ext_hub_name_wc);
121         return ext_hub_name_utf8;
122 }
123
124 static char *get_string_descriptor(HANDLE hub_device, ULONG connection_index,
125                                    UCHAR descriptor_index)
126 {
127         char desc_req_buf[sizeof(USB_DESCRIPTOR_REQUEST) +
128                           MAXIMUM_USB_STRING_LENGTH] = { 0 };
129         PUSB_DESCRIPTOR_REQUEST desc_req = (void *)desc_req_buf;
130         PUSB_STRING_DESCRIPTOR desc = (void *)(desc_req + 1);
131         ULONG size = sizeof(desc_req_buf);
132
133         desc_req->ConnectionIndex = connection_index;
134         desc_req->SetupPacket.wValue = (USB_STRING_DESCRIPTOR_TYPE << 8)
135                                        | descriptor_index;
136         desc_req->SetupPacket.wIndex = 0;
137         desc_req->SetupPacket.wLength = size - sizeof(*desc_req);
138
139         if (!DeviceIoControl(hub_device,
140                              IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION,
141                              desc_req, size, desc_req, size, &size, NULL)
142             || size < 2
143             || desc->bDescriptorType != USB_STRING_DESCRIPTOR_TYPE
144             || desc->bLength != size - sizeof(*desc_req)
145             || desc->bLength % 2)
146                 return NULL;
147
148         return wc_to_utf8(desc->bString, desc->bLength);
149 }
150
151 static void enumerate_hub_ports(struct sp_port *port, HANDLE hub_device,
152                                 ULONG nb_ports, const char *parent_path, DEVINST dev_inst)
153 {
154         char path[MAX_USB_PATH];
155         ULONG index = 0;
156
157         for (index = 1; index <= nb_ports; index++) {
158                 PUSB_NODE_CONNECTION_INFORMATION_EX connection_info_ex;
159                 ULONG size = sizeof(*connection_info_ex) + (30 * sizeof(USB_PIPE_INFO));
160
161                 if (!(connection_info_ex = malloc(size)))
162                         break;
163
164                 connection_info_ex->ConnectionIndex = index;
165                 if (!DeviceIoControl(hub_device,
166                                      IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX,
167                                      connection_info_ex, size,
168                                      connection_info_ex, size, &size, NULL)) {
169                         /*
170                          * Try to get CONNECTION_INFORMATION if
171                          * CONNECTION_INFORMATION_EX did not work.
172                          */
173                         PUSB_NODE_CONNECTION_INFORMATION connection_info;
174
175                         size = sizeof(*connection_info) + (30 * sizeof(USB_PIPE_INFO));
176                         if (!(connection_info = malloc(size))) {
177                                 free(connection_info_ex);
178                                 continue;
179                         }
180                         connection_info->ConnectionIndex = index;
181                         if (!DeviceIoControl(hub_device,
182                                              IOCTL_USB_GET_NODE_CONNECTION_INFORMATION,
183                                              connection_info, size,
184                                              connection_info, size, &size, NULL)) {
185                                 free(connection_info);
186                                 free(connection_info_ex);
187                                 continue;
188                         }
189
190                         connection_info_ex->ConnectionIndex = connection_info->ConnectionIndex;
191                         connection_info_ex->DeviceDescriptor = connection_info->DeviceDescriptor;
192                         connection_info_ex->DeviceIsHub = connection_info->DeviceIsHub;
193                         connection_info_ex->DeviceAddress = connection_info->DeviceAddress;
194                         free(connection_info);
195                 }
196
197                 if (connection_info_ex->DeviceIsHub) {
198                         /* Recursively enumerate external hub. */
199                         PCHAR ext_hub_name;
200                         if ((ext_hub_name = get_external_hub_name(hub_device, index))) {
201                                 snprintf(path, sizeof(path), "%s%ld.",
202                                          parent_path, connection_info_ex->ConnectionIndex);
203                                 enumerate_hub(port, ext_hub_name, path, dev_inst);
204                         }
205                         free(connection_info_ex);
206                 } else {
207                         snprintf(path, sizeof(path), "%s%ld",
208                                  parent_path, connection_info_ex->ConnectionIndex);
209
210                         /* Check if this device is the one we search for. */
211                         if (strcmp(path, port->usb_path)) {
212                                 free(connection_info_ex);
213                                 continue;
214                         }
215
216                         /* Finally grab detailed information regarding the device. */
217                         port->usb_address = connection_info_ex->DeviceAddress + 1;
218                         port->usb_vid = connection_info_ex->DeviceDescriptor.idVendor;
219                         port->usb_pid = connection_info_ex->DeviceDescriptor.idProduct;
220
221                         if (connection_info_ex->DeviceDescriptor.iManufacturer)
222                                 port->usb_manufacturer = get_string_descriptor(hub_device,index,
223                                            connection_info_ex->DeviceDescriptor.iManufacturer);
224                         if (connection_info_ex->DeviceDescriptor.iProduct)
225                                 port->usb_product = get_string_descriptor(hub_device, index,
226                                            connection_info_ex->DeviceDescriptor.iProduct);
227                         if (connection_info_ex->DeviceDescriptor.iSerialNumber) {
228                                 port->usb_serial = get_string_descriptor(hub_device, index,
229                                            connection_info_ex->DeviceDescriptor.iSerialNumber);
230                                 if (port->usb_serial == NULL) {
231                                         //composite device, get the parent's serial number
232                                         char device_id[MAX_DEVICE_ID_LEN];
233                                         if (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS) {
234                                                 if (CM_Get_Device_IDA(dev_inst, device_id, sizeof(device_id), 0) == CR_SUCCESS)
235                                                         port->usb_serial = strdup(strrchr(device_id, '\\')+1);
236                                         }
237                                 }
238                         }
239
240                         free(connection_info_ex);
241                         break;
242                 }
243         }
244 }
245
246 static void enumerate_hub(struct sp_port *port, const char *hub_name,
247                           const char *parent_path, DEVINST dev_inst)
248 {
249         USB_NODE_INFORMATION hub_info;
250         HANDLE hub_device;
251         ULONG size = sizeof(hub_info);
252         char *device_name;
253
254         /* Open the hub with its full name. */
255         if (!(device_name = malloc(strlen("\\\\.\\") + strlen(hub_name) + 1)))
256                 return;
257         strcpy(device_name, "\\\\.\\");
258         strcat(device_name, hub_name);
259         hub_device = CreateFile(device_name, GENERIC_WRITE, FILE_SHARE_WRITE,
260                                 NULL, OPEN_EXISTING, 0, NULL);
261         free(device_name);
262         if (hub_device == INVALID_HANDLE_VALUE)
263                 return;
264
265         /* Get the number of ports of the hub. */
266         if (DeviceIoControl(hub_device, IOCTL_USB_GET_NODE_INFORMATION,
267                             &hub_info, size, &hub_info, size, &size, NULL))
268                 /* Enumerate the ports of the hub. */
269                 enumerate_hub_ports(port, hub_device,
270                    hub_info.u.HubInformation.HubDescriptor.bNumberOfPorts, parent_path, dev_inst);
271
272         CloseHandle(hub_device);
273 }
274
275 static void enumerate_host_controller(struct sp_port *port,
276                                       HANDLE host_controller_device,
277                                       DEVINST dev_inst)
278 {
279         char *root_hub_name;
280
281         if ((root_hub_name = get_root_hub_name(host_controller_device))) {
282                 enumerate_hub(port, root_hub_name, "", dev_inst);
283                 free(root_hub_name);
284         }
285 }
286
287 static void get_usb_details(struct sp_port *port, DEVINST dev_inst_match)
288 {
289         HDEVINFO device_info;
290         SP_DEVINFO_DATA device_info_data;
291         ULONG i, size = 0;
292
293         device_info = SetupDiGetClassDevs(&GUID_CLASS_USB_HOST_CONTROLLER, NULL, NULL,
294                                           DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
295         device_info_data.cbSize = sizeof(device_info_data);
296
297         for (i = 0; SetupDiEnumDeviceInfo(device_info, i, &device_info_data); i++) {
298                 SP_DEVICE_INTERFACE_DATA device_interface_data;
299                 PSP_DEVICE_INTERFACE_DETAIL_DATA device_detail_data;
300                 DEVINST dev_inst = dev_inst_match;
301                 HANDLE host_controller_device;
302
303                 device_interface_data.cbSize = sizeof(device_interface_data);
304                 if (!SetupDiEnumDeviceInterfaces(device_info, 0,
305                                                  &GUID_CLASS_USB_HOST_CONTROLLER,
306                                                  i, &device_interface_data))
307                         continue;
308
309                 if (!SetupDiGetDeviceInterfaceDetail(device_info,&device_interface_data,
310                                                      NULL, 0, &size, NULL)
311                     && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
312                         continue;
313
314                 if (!(device_detail_data = malloc(size)))
315                         continue;
316                 device_detail_data->cbSize = sizeof(*device_detail_data);
317                 if (!SetupDiGetDeviceInterfaceDetail(device_info,&device_interface_data,
318                                                      device_detail_data, size, &size,
319                                                      NULL)) {
320                         free(device_detail_data);
321                         continue;
322                 }
323
324                 while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS
325                        && dev_inst != device_info_data.DevInst) { }
326                 if (dev_inst != device_info_data.DevInst) {
327                         free(device_detail_data);
328                         continue;
329                 }
330
331                 port->usb_bus = i + 1;
332
333                 host_controller_device = CreateFile(device_detail_data->DevicePath,
334                                                     GENERIC_WRITE, FILE_SHARE_WRITE,
335                                                     NULL, OPEN_EXISTING, 0, NULL);
336                 if (host_controller_device != INVALID_HANDLE_VALUE) {
337                         enumerate_host_controller(port, host_controller_device, dev_inst_match);
338                         CloseHandle(host_controller_device);
339                 }
340                 free(device_detail_data);
341         }
342
343         SetupDiDestroyDeviceInfoList(device_info);
344         return;
345 }
346
347 SP_PRIV enum sp_return get_port_details(struct sp_port *port)
348 {
349         /*
350          * Description limited to 127 char, anything longer
351          * would not be user friendly anyway.
352          */
353         char description[128];
354         SP_DEVINFO_DATA device_info_data = { .cbSize = sizeof(device_info_data) };
355         HDEVINFO device_info;
356         int i;
357
358         device_info = SetupDiGetClassDevs(NULL, 0, 0,
359                                           DIGCF_PRESENT | DIGCF_ALLCLASSES);
360         if (device_info == INVALID_HANDLE_VALUE)
361                 RETURN_FAIL("SetupDiGetClassDevs() failed");
362
363         for (i = 0; SetupDiEnumDeviceInfo(device_info, i, &device_info_data); i++) {
364                 HKEY device_key;
365                 DEVINST dev_inst;
366                 char value[8], class[16];
367                 DWORD size, type;
368                 CONFIGRET cr;
369
370                 /* Check if this is the device we are looking for. */
371                 device_key = SetupDiOpenDevRegKey(device_info, &device_info_data,
372                                                   DICS_FLAG_GLOBAL, 0,
373                                                   DIREG_DEV, KEY_QUERY_VALUE);
374                 if (device_key == INVALID_HANDLE_VALUE)
375                         continue;
376                 size = sizeof(value);
377                 if (RegQueryValueExA(device_key, "PortName", NULL, &type, (LPBYTE)value,
378                                      &size) != ERROR_SUCCESS || type != REG_SZ) {
379                         RegCloseKey(device_key);
380                         continue;
381                 }
382                 RegCloseKey(device_key);
383                 value[sizeof(value)-1] = 0;
384                 if (strcmp(value, port->name))
385                         continue;
386
387                 /* Check port transport type. */
388                 dev_inst = device_info_data.DevInst;
389                 size = sizeof(class);
390                 cr = CR_FAILURE;
391                 while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS &&
392                        (cr = CM_Get_DevNode_Registry_PropertyA(dev_inst,
393                                  CM_DRP_CLASS, 0, class, &size, 0)) != CR_SUCCESS) { }
394                 if (cr == CR_SUCCESS) {
395                         if (!strcmp(class, "USB"))
396                                 port->transport = SP_TRANSPORT_USB;
397                 }
398
399                 /* Get port description (friendly name). */
400                 dev_inst = device_info_data.DevInst;
401                 size = sizeof(description);
402                 while ((cr = CM_Get_DevNode_Registry_PropertyA(dev_inst,
403                           CM_DRP_FRIENDLYNAME, 0, description, &size, 0)) != CR_SUCCESS
404                        && CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS) { }
405                 if (cr == CR_SUCCESS)
406                         port->description = strdup(description);
407
408                 /* Get more informations for USB connected ports. */
409                 if (port->transport == SP_TRANSPORT_USB) {
410                         char usb_path[MAX_USB_PATH] = "", tmp[MAX_USB_PATH];
411                         char device_id[MAX_DEVICE_ID_LEN];
412
413                         /* Recurse over parents to build the USB device path. */
414                         dev_inst = device_info_data.DevInst;
415                         do {
416                                 /* Verify that this layer of the tree is USB related. */
417                                 if (CM_Get_Device_IDA(dev_inst, device_id,
418                                                       sizeof(device_id), 0) != CR_SUCCESS
419                                     || strncmp(device_id, "USB\\", 4))
420                                         continue;
421
422                                 /* Discard one layer for composite devices. */
423                                 char compat_ids[512], *p = compat_ids;
424                                 size = sizeof(compat_ids);
425                                 if (CM_Get_DevNode_Registry_PropertyA(dev_inst,
426                                                                       CM_DRP_COMPATIBLEIDS, 0,
427                                                                       &compat_ids,
428                                                                       &size, 0) == CR_SUCCESS) {
429                                         while (*p) {
430                                                 if (!strncmp(p, "USB\\COMPOSITE", 13))
431                                                         break;
432                                                 p += strlen(p) + 1;
433                                         }
434                                         if (*p)
435                                                 continue;
436                                 }
437
438                                 /* Stop the recursion when reaching the USB root. */
439                                 if (!strncmp(device_id, "USB\\ROOT", 8))
440                                         break;
441
442                                 /* Prepend the address of current USB layer to the USB path. */
443                                 DWORD address;
444                                 size = sizeof(address);
445                                 if (CM_Get_DevNode_Registry_PropertyA(dev_inst, CM_DRP_ADDRESS,
446                                                         0, &address, &size, 0) == CR_SUCCESS) {
447                                         strcpy(tmp, usb_path);
448                                         snprintf(usb_path, sizeof(usb_path), "%d%s%s",
449                                                  (int)address, *tmp ? "." : "", tmp);
450                                 }
451                         } while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS);
452
453                         port->usb_path = strdup(usb_path);
454
455                         /* Wake up the USB device to be able to read string descriptor. */
456                         char *escaped_port_name;
457                         HANDLE handle;
458                         if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
459                                 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
460                         sprintf(escaped_port_name, "\\\\.\\%s", port->name);
461                         handle = CreateFile(escaped_port_name, GENERIC_READ, 0, 0,
462                                             OPEN_EXISTING,
463                                             FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, 0);
464                         free(escaped_port_name);
465                         CloseHandle(handle);
466
467                         /* Retrieve USB device details from the device descriptor. */
468                         get_usb_details(port, device_info_data.DevInst);
469                 }
470                 break;
471         }
472
473         SetupDiDestroyDeviceInfoList(device_info);
474
475         RETURN_OK();
476 }
477
478 SP_PRIV enum sp_return list_ports(struct sp_port ***list)
479 {
480         HKEY key;
481         TCHAR *value, *data;
482         DWORD max_value_len, max_data_size, max_data_len;
483         DWORD value_len, data_size, data_len;
484         DWORD type, index = 0;
485         char *name;
486         int name_len;
487         int ret = SP_OK;
488
489         DEBUG("Opening registry key");
490         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
491                         0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
492                 SET_FAIL(ret, "RegOpenKeyEx() failed");
493                 goto out_done;
494         }
495         DEBUG("Querying registry key value and data sizes");
496         if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
497                                 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
498                 SET_FAIL(ret, "RegQueryInfoKey() failed");
499                 goto out_close;
500         }
501         max_data_len = max_data_size / sizeof(TCHAR);
502         if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
503                 SET_ERROR(ret, SP_ERR_MEM, "Registry value malloc failed");
504                 goto out_close;
505         }
506         if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
507                 SET_ERROR(ret, SP_ERR_MEM, "Registry data malloc failed");
508                 goto out_free_value;
509         }
510         DEBUG("Iterating over values");
511         while (
512                 value_len = max_value_len + 1,
513                 data_size = max_data_size,
514                 RegEnumValue(key, index, value, &value_len,
515                         NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
516         {
517                 if (type == REG_SZ) {
518                         data_len = data_size / sizeof(TCHAR);
519                         data[data_len] = '\0';
520 #ifdef UNICODE
521                         name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL);
522 #else
523                         name_len = data_len + 1;
524 #endif
525                         if (!(name = malloc(name_len))) {
526                                 SET_ERROR(ret, SP_ERR_MEM, "Registry port name malloc failed");
527                                 goto out;
528                         }
529 #ifdef UNICODE
530                         WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
531 #else
532                         strcpy(name, data);
533 #endif
534                         DEBUG_FMT("Found port %s", name);
535                         if (!(*list = list_append(*list, name))) {
536                                 SET_ERROR(ret, SP_ERR_MEM, "List append failed");
537                                 free(name);
538                                 goto out;
539                         }
540                         free(name);
541                 }
542                 index++;
543         }
544 out:
545         free(data);
546 out_free_value:
547         free(value);
548 out_close:
549         RegCloseKey(key);
550 out_done:
551
552         return ret;
553 }