]> sigrok.org Git - libsigrok.git/blob - src/serial_hid.c
serial_hid: restrict .list() result set, supported chips only
[libsigrok.git] / src / serial_hid.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2017-2019 Gerhard Sittig <gerhard.sittig@gmx.net>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (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 General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "config.h"
21 #include <glib.h>
22 #ifdef HAVE_LIBHIDAPI
23 #include <hidapi.h>
24 #endif
25 #include <libsigrok/libsigrok.h>
26 #include "libsigrok-internal.h"
27 #include "serial_hid.h"
28 #include <stdlib.h>
29 #include <string.h>
30 #ifdef G_OS_WIN32
31 #include <windows.h> /* for HANDLE */
32 #endif
33
34 #define LOG_PREFIX "serial-hid"
35
36 #ifdef HAVE_SERIAL_COMM
37
38 /**
39  * @file
40  *
41  * Serial port handling, HIDAPI library specific support code.
42  */
43
44 /**
45  * @defgroup grp_serial_hid Serial port handling, HID group
46  *
47  * Make serial-over-HID communication appear like a regular serial port.
48  *
49  * @{
50  */
51
52 #ifdef HAVE_LIBHIDAPI
53 /* {{{ helper routines */
54
55 /* Strip off parity bits for "odd" data bit counts like in 7e1 frames. */
56 static void ser_hid_mask_databits(struct sr_serial_dev_inst *serial,
57         uint8_t *data, size_t len)
58 {
59         uint32_t mask32;
60         uint8_t mask;
61         size_t idx;
62
63         if ((serial->comm_params.data_bits % 8) == 0)
64                 return;
65
66         mask32 = (1UL << serial->comm_params.data_bits) - 1;
67         mask = mask32 & 0xff;
68         for (idx = 0; idx < len; idx++)
69                 data[idx] &= mask;
70 }
71
72 /* }}} */
73 /* {{{ open/close/list/find HIDAPI connection, exchange HID requests and data */
74
75 #define IOKIT_PATH_PREFIX       "IOService:"
76
77 /*
78  * Convert a HIDAPI path (which depends on the target platform, and may
79  * depend on one of several available API variants on that platform) to
80  * something that is usable as a "port name" in conn= specs.
81  *
82  * Since conn= is passed with -d where multiple options (among them conn=)
83  * are separated by colons, port names themselves cannot contain colons.
84  *
85  * Just replace colons by a period in the simple case (Linux platform,
86  * hidapi-libusb implementation, bus/address/interface). Prefix the
87  * HIDAPI path in the complex cases (Linux hidapi-hidraw, Windows, Mac).
88  * Paths with colons outside of libusb based implementations are unhandled
89  * here, but were not yet seen on any sigrok supported platform either.
90  * So just reject them.
91  */
92 static char *get_hidapi_path_copy(const char *path)
93 {
94         static const char *accept = "0123456789abcdefABCDEF:";
95         static const char *keep = "0123456789abcdefABCDEF";
96
97         int has_colon;
98         int is_hex_colon;
99         const char *parse, *remain;
100         char *copy;
101
102         parse = path;
103         has_colon = strchr(parse, ':') != NULL;
104         is_hex_colon = strspn(parse, accept) == strlen(parse);
105         if (is_hex_colon) {
106                 /* All hex digits and colon only. Simple substitution. */
107                 copy = g_strdup_printf("%s%s", SER_HID_USB_PREFIX, parse);
108                 g_strcanon(copy + strlen(SER_HID_USB_PREFIX), keep, '.');
109                 return copy;
110         }
111         if (!has_colon) {
112                 /* "Something raw" and no colon. Add raw= prefix. */
113                 copy = g_strdup_printf("%s%s", SER_HID_RAW_PREFIX, parse);
114                 return copy;
115         }
116         if (g_str_has_prefix(parse, IOKIT_PATH_PREFIX)) do {
117                 /*
118                  * Path starts with Mac IOKit literal which contains the
119                  * colon. Drop that literal from the start of the path,
120                  * and check whether any colon remains which we cannot
121                  * deal with. Fall though to other approaches which could
122                  * be more generic, or to the error path.
123                  */
124                 remain = &parse[strlen(IOKIT_PATH_PREFIX)];
125                 if (strchr(remain, ':'))
126                         break;
127                 copy = g_strdup_printf("%s%s", SER_HID_IOKIT_PREFIX, remain);
128                 return copy;
129         } while (0);
130
131         /* TODO
132          * Consider adding support for more of the currently unhandled
133          * cases. When we get here, the HIDAPI path could be arbitrarily
134          * complex, none of the above "straight" approaches took effect.
135          * Proper escaping or other transformations could get applied,
136          * though they decrease usability the more they obfuscate the
137          * resulting port name. Ideally users remain able to recognize
138          * their device or cable or port after the manipulation.
139          */
140         sr_err("Unsupported HIDAPI path format: %s", path);
141         return NULL;
142 }
143
144 /*
145  * Undo the port name construction that was done during scan. Extract
146  * the HIDAPI path from a conn= input spec (the part after the hid/
147  * prefix and chip type).
148  *
149  * Strip off the "raw" prefix, or undo colon substitution. See @ref
150  * get_hidapi_path_copy() for details.
151  */
152 static char *extract_hidapi_path(const char *copy)
153 {
154         static const char *keep = "0123456789abcdefABCDEF:";
155
156         const char *p;
157         char *path;
158
159         p = copy;
160         if (!p || !*p)
161                 return NULL;
162
163         if (g_str_has_prefix(p, SER_HID_IOKIT_PREFIX)) {
164                 p += strlen(SER_HID_IOKIT_PREFIX);
165                 path = g_strdup_printf("%s%s", IOKIT_PATH_PREFIX, p);
166                 return path;
167         }
168         if (g_str_has_prefix(p, SER_HID_RAW_PREFIX)) {
169                 p += strlen(SER_HID_RAW_PREFIX);
170                 path = g_strdup(p);
171                 return path;
172         }
173         if (g_str_has_prefix(p, SER_HID_USB_PREFIX)) {
174                 p += strlen(SER_HID_USB_PREFIX);
175                 path = g_strdup(p);
176                 g_strcanon(path, keep, ':');
177                 return path;
178         }
179
180         return NULL;
181 }
182
183 /*
184  * Enumerate all devices (no VID:PID is involved). Invoke an 'append'
185  * callback with "path" and "name". Exclusively list connections that
186  * involve supported chip types, because mice and keyboards etc are not
187  * too useful to communicate to measurement equipment.
188  */
189 static GSList *ser_hid_hidapi_list(GSList *list, sr_ser_list_append_t append)
190 {
191         struct hid_device_info *devs, *curdev;
192         const char *chipname;
193         char *path, *name;
194         wchar_t *manuf, *prod, *serno;
195         uint16_t vid, pid;
196         GString *desc;
197
198         devs = hid_enumerate(0x0000, 0x0000);
199         for (curdev = devs; curdev; curdev = curdev->next) {
200                 /*
201                  * Determine the chip name from VID:PID. Exlusively list
202                  * supported connection types (known chips).
203                  */
204                 vid = curdev->vendor_id;
205                 pid = curdev->product_id;
206                 chipname = ser_hid_chip_find_name_vid_pid(vid, pid);
207                 if (!chipname)
208                         continue;
209
210                 /*
211                  * Prefix port names such that open() calls with this
212                  * conn= spec will end up here and contain all details
213                  * that are essential for processing.
214                  */
215                 path = get_hidapi_path_copy(curdev->path);
216                 if (!path)
217                         continue;
218                 name = g_strdup_printf("%s/%s/%s",
219                         SER_HID_CONN_PREFIX, chipname, path);
220                 g_free(path);
221
222                 /*
223                  * Print whatever information was available. Construct
224                  * the description text from pieces. Absence of fields
225                  * is not fatal, we have seen perfectly usable cables
226                  * that only had a VID and PID (permissions were not an
227                  * issue).
228                  */
229                 manuf = curdev->manufacturer_string;
230                 prod = curdev->product_string;
231                 serno = curdev->serial_number;
232                 vid = curdev->vendor_id;
233                 pid = curdev->product_id;
234                 desc = g_string_sized_new(128);
235                 g_string_append_printf(desc, "HID");
236                 if (manuf && wcslen(manuf) != 0)
237                         g_string_append_printf(desc, " %ls", manuf);
238                 if (prod && wcslen(prod) != 0)
239                         g_string_append_printf(desc, " %ls", prod);
240                 if (serno && wcslen(serno) != 0)
241                         g_string_append_printf(desc, " %ls", serno);
242                 if (vid && pid)
243                         g_string_append_printf(desc, " [%04hx.%04hx]", vid, pid);
244                 list = append(list, name, desc->str);
245                 g_string_free(desc, TRUE);
246                 g_free(name);
247         }
248         hid_free_enumeration(devs);
249
250         return list;
251 }
252
253 /*
254  * The HIDAPI specific find_usb() callback, invoked by common serial.c code.
255  * Enumerate devices for the specified VID:PID pair.
256  * Invoke an "append" callback with 'path' for the device.
257  */
258 static GSList *ser_hid_hidapi_find_usb(GSList *list, sr_ser_find_append_t append,
259                 uint16_t vendor_id, uint16_t product_id)
260 {
261         struct hid_device_info *devs, *curdev;
262         const char *name;
263
264         devs = hid_enumerate(vendor_id, product_id);
265         for (curdev = devs; curdev; curdev = curdev->next) {
266                 name = curdev->path;
267                 list = append(list, name);
268         }
269         hid_free_enumeration(devs);
270
271         return list;
272 }
273
274 /* Get the serial number of a device specified by path. */
275 static int ser_hid_hidapi_get_serno(const char *path, char *buf, size_t blen)
276 {
277         char *hidpath;
278         hid_device *dev;
279         wchar_t *serno_wch;
280         int rc;
281
282         if (!path || !*path)
283                 return SR_ERR_ARG;
284         hidpath = extract_hidapi_path(path);
285         dev = hidpath ? hid_open_path(hidpath) : NULL;
286         g_free(hidpath);
287         if (!dev)
288                 return SR_ERR_IO;
289
290         serno_wch = g_malloc0(blen * sizeof(*serno_wch));
291         rc = hid_get_serial_number_string(dev, serno_wch, blen - 1);
292         hid_close(dev);
293         if (rc != 0) {
294                 g_free(serno_wch);
295                 return SR_ERR_IO;
296         }
297
298         snprintf(buf, blen, "%ls", serno_wch);
299         g_free(serno_wch);
300
301         return SR_OK;
302 }
303
304 /* Get the VID and PID of a device specified by path. */
305 static int ser_hid_hidapi_get_vid_pid(const char *path,
306         uint16_t *vid, uint16_t *pid)
307 {
308 #if 0
309         /*
310          * Bummer! It would have been most reliable to just open the
311          * device by the specified path, and grab its VID:PID. But
312          * there is no way to get these parameters, neither in the
313          * HIDAPI itself, nor when cheating and reaching behind the API
314          * and accessing the libusb handle in dirty ways. :(
315          */
316         hid_device *dev;
317
318         if (!path || !*path)
319                 return SR_ERR_ARG;
320         dev = hid_open_path(path);
321         if (!dev)
322                 return SR_ERR_IO;
323         if (vid)
324                 *vid = dev->vendor_id;
325         if (pid)
326                 *pid = dev->product_id;
327         hid_close(dev);
328
329         return SR_OK;
330 #else
331         /*
332          * The fallback approach. Enumerate all devices, compare the
333          * enumerated USB path, and grab the VID:PID. Unfortunately the
334          * caller can provide path specs that differ from enumerated
335          * paths yet mean the same (address the same device). This needs
336          * more attention. Though the specific format of the path and
337          * its meaning are said to be OS specific, which is why we may
338          * not assume anything about it...
339          */
340         char *hidpath;
341         struct hid_device_info *devs, *dev;
342         int found;
343
344         hidpath = extract_hidapi_path(path);
345         if (!hidpath)
346                 return SR_ERR_NA;
347
348         devs = hid_enumerate(0x0000, 0x0000);
349         found = 0;
350         for (dev = devs; dev; dev = dev->next) {
351                 if (strcmp(dev->path, hidpath) != 0)
352                         continue;
353                 if (vid)
354                         *vid = dev->vendor_id;
355                 if (pid)
356                         *pid = dev->product_id;
357                 found = 1;
358                 break;
359         }
360         hid_free_enumeration(devs);
361         g_free(hidpath);
362
363         return found ? SR_OK : SR_ERR_NA;
364 #endif
365 }
366
367 static int ser_hid_hidapi_open_dev(struct sr_serial_dev_inst *serial)
368 {
369         hid_device *hid_dev;
370
371         if (!serial->usb_path || !*serial->usb_path)
372                 return SR_ERR_ARG;
373
374         /*
375          * A path is available, assume that either a GUI or a
376          * user has copied what a previous listing has provided.
377          * Or a scan determined a matching device's USB path.
378          */
379         if (!serial->hid_path)
380                 serial->hid_path = extract_hidapi_path(serial->usb_path);
381         hid_dev = hid_open_path(serial->hid_path);
382         if (!hid_dev) {
383                 g_free((void *)serial->hid_path);
384                 serial->hid_path = NULL;
385                 return SR_ERR_IO;
386         }
387
388         serial->hid_dev = hid_dev;
389         hid_set_nonblocking(hid_dev, 1);
390
391         return SR_OK;
392 }
393
394 static void ser_hid_hidapi_close_dev(struct sr_serial_dev_inst *serial)
395 {
396         if (serial->hid_dev) {
397                 hid_close(serial->hid_dev);
398                 serial->hid_dev = NULL;
399                 g_free((void *)serial->hid_path);
400                 serial->hid_path = NULL;
401         }
402         g_slist_free_full(serial->hid_source_args, g_free);
403         serial->hid_source_args = NULL;
404 }
405
406 struct hidapi_source_args_t {
407         /* Application callback. */
408         sr_receive_data_callback cb;
409         void *cb_data;
410         /* The serial device, to store RX data. */
411         struct sr_serial_dev_inst *serial;
412 };
413
414 /*
415  * Gets periodically invoked by the glib main loop. "Drives" (checks)
416  * progress of USB communication, and invokes the application's callback
417  * which processes RX data (when some has become available), as well as
418  * handles application level timeouts.
419  */
420 static int hidapi_source_cb(int fd, int revents, void *cb_data)
421 {
422         struct hidapi_source_args_t *args;
423         uint8_t rx_buf[SER_HID_CHUNK_SIZE];
424         int rc;
425
426         args = cb_data;
427
428         /*
429          * Drain receive data which the chip might have pending. This is
430          * "a copy" of the "background part" of ser_hid_read(), without
431          * the timeout support code, and not knowing how much data the
432          * application is expecting.
433          */
434         do {
435                 rc = args->serial->hid_chip_funcs->read_bytes(args->serial,
436                                 rx_buf, sizeof(rx_buf), 0);
437                 if (rc > 0) {
438                         ser_hid_mask_databits(args->serial, rx_buf, rc);
439                         sr_ser_queue_rx_data(args->serial, rx_buf, rc);
440                 }
441         } while (rc > 0);
442
443         /*
444          * When RX data became available (now or earlier), pass this
445          * condition to the application callback. Always periodically
446          * run the application callback, since it handles timeouts and
447          * might carry out other tasks as well like signalling progress.
448          */
449         if (sr_ser_has_queued_data(args->serial))
450                 revents |= G_IO_IN;
451         rc = args->cb(fd, revents, args->cb_data);
452
453         return rc;
454 }
455
456 #define WITH_MAXIMUM_TIMEOUT_VALUE      10
457 static int ser_hid_hidapi_setup_source_add(struct sr_session *session,
458         struct sr_serial_dev_inst *serial, int events, int timeout,
459         sr_receive_data_callback cb, void *cb_data)
460 {
461         struct hidapi_source_args_t *args;
462         int rc;
463
464         (void)events;
465
466         /* Optionally enforce a minimum poll period. */
467         if (WITH_MAXIMUM_TIMEOUT_VALUE && timeout > WITH_MAXIMUM_TIMEOUT_VALUE)
468                 timeout = WITH_MAXIMUM_TIMEOUT_VALUE;
469
470         /* Allocate status container for background data reception. */
471         args = g_malloc0(sizeof(*args));
472         args->cb = cb;
473         args->cb_data = cb_data;
474         args->serial = serial;
475
476         /*
477          * Have a periodic timer installed. Register the allocated block
478          * with the serial device, since the GSource's finalizer won't
479          * free the memory, and we haven't bothered to create a custom
480          * HIDAPI specific GSource.
481          */
482         rc = sr_session_source_add(session, -1, events, timeout,
483                         hidapi_source_cb, args);
484         if (rc != SR_OK) {
485                 g_free(args);
486                 return rc;
487         }
488         serial->hid_source_args = g_slist_append(serial->hid_source_args, args);
489
490         return SR_OK;
491 }
492
493 static int ser_hid_hidapi_setup_source_remove(struct sr_session *session,
494         struct sr_serial_dev_inst *serial)
495 {
496         (void)serial;
497
498         (void)sr_session_source_remove(session, -1);
499         /*
500          * Release callback args here already? Can there be more than
501          * one source registered at any time, given that we pass fd -1
502          * which is used as the key for the session?
503          */
504
505         return SR_OK;
506 }
507
508 SR_PRIV int ser_hid_hidapi_get_report(struct sr_serial_dev_inst *serial,
509         uint8_t *data, size_t len)
510 {
511         int rc;
512
513         rc = hid_get_feature_report(serial->hid_dev, data, len);
514         if (rc < 0)
515                 return SR_ERR_IO;
516
517         return rc;
518 }
519
520 SR_PRIV int ser_hid_hidapi_set_report(struct sr_serial_dev_inst *serial,
521         const uint8_t *data, size_t len)
522 {
523         int rc;
524         const wchar_t *err_text;
525
526         rc = hid_send_feature_report(serial->hid_dev, data, len);
527         if (rc < 0) {
528                 err_text = hid_error(serial->hid_dev);
529                 sr_dbg("%s() hidapi error: %ls", __func__, err_text);
530                 return SR_ERR_IO;
531         }
532
533         return rc;
534 }
535
536 SR_PRIV int ser_hid_hidapi_get_data(struct sr_serial_dev_inst *serial,
537         uint8_t ep, uint8_t *data, size_t len, int timeout)
538 {
539         int rc;
540
541         (void)ep;
542
543         if (timeout)
544                 rc = hid_read_timeout(serial->hid_dev, data, len, timeout);
545         else
546                 rc = hid_read(serial->hid_dev, data, len);
547         if (rc < 0)
548                 return SR_ERR_IO;
549         if (rc == 0)
550                 return 0;
551
552         return rc;
553 }
554
555 SR_PRIV int ser_hid_hidapi_set_data(struct sr_serial_dev_inst *serial,
556         uint8_t ep, const uint8_t *data, size_t len, int timeout)
557 {
558         int rc;
559
560         (void)ep;
561         (void)timeout;
562
563         rc = hid_write(serial->hid_dev, data, len);
564         if (rc < 0)
565                 return SR_ERR_IO;
566
567         return rc;
568 }
569
570 /* }}} */
571 /* {{{ support for serial-over-HID chips */
572
573 static struct ser_hid_chip_functions **chips[SER_HID_CHIP_LAST] = {
574         [SER_HID_CHIP_UNKNOWN] = NULL,
575         [SER_HID_CHIP_BTC_BU86X] = &ser_hid_chip_funcs_bu86x,
576         [SER_HID_CHIP_SIL_CP2110] = &ser_hid_chip_funcs_cp2110,
577         [SER_HID_CHIP_VICTOR_DMM] = &ser_hid_chip_funcs_victor,
578         [SER_HID_CHIP_WCH_CH9325] = &ser_hid_chip_funcs_ch9325,
579 };
580
581 static struct ser_hid_chip_functions *get_hid_chip_funcs(enum ser_hid_chip_t chip)
582 {
583         struct ser_hid_chip_functions *funcs;
584
585         if (chip >= ARRAY_SIZE(chips))
586                 return NULL;
587         if (!chips[chip])
588                 return NULL;
589         funcs = *chips[chip];
590         if (!funcs)
591                 return NULL;
592
593         return funcs;
594 }
595
596 static int ser_hid_setup_funcs(struct sr_serial_dev_inst *serial)
597 {
598
599         if (!serial)
600                 return -1;
601
602         if (serial->hid_chip && !serial->hid_chip_funcs) {
603                 serial->hid_chip_funcs = get_hid_chip_funcs(serial->hid_chip);
604                 if (!serial->hid_chip_funcs)
605                         return -1;
606         }
607
608         return 0;
609 }
610
611 /*
612  * Takes a pointer to the chip spec with potentially trailing data,
613  * returns the chip index and advances the spec pointer upon match,
614  * returns SER_HID_CHIP_UNKNOWN upon mismatch.
615  */
616 static enum ser_hid_chip_t ser_hid_chip_find_enum(const char **spec_p)
617 {
618         const gchar *spec;
619         enum ser_hid_chip_t idx;
620         struct ser_hid_chip_functions *desc;
621
622         if (!spec_p || !*spec_p)
623                 return SER_HID_CHIP_UNKNOWN;
624         spec = *spec_p;
625         if (!*spec)
626                 return SER_HID_CHIP_UNKNOWN;
627         for (idx = 0; idx < SER_HID_CHIP_LAST; idx++) {
628                 desc = get_hid_chip_funcs(idx);
629                 if (!desc)
630                         continue;
631                 if (!desc->chipname)
632                         continue;
633                 if (!g_str_has_prefix(spec, desc->chipname))
634                         continue;
635                 spec += strlen(desc->chipname);
636                 *spec_p = spec;
637                 return idx;
638         }
639
640         return SER_HID_CHIP_UNKNOWN;
641 }
642
643 /* See if we can find a chip name for a VID:PID spec. */
644 SR_PRIV const char *ser_hid_chip_find_name_vid_pid(uint16_t vid, uint16_t pid)
645 {
646         size_t chip_idx;
647         struct ser_hid_chip_functions *desc;
648         const struct vid_pid_item *vid_pids;
649
650         for (chip_idx = 0; chip_idx < SER_HID_CHIP_LAST; chip_idx++) {
651                 desc = get_hid_chip_funcs(chip_idx);
652                 if (!desc)
653                         continue;
654                 if (!desc->chipname)
655                         continue;
656                 vid_pids = desc->vid_pid_items;
657                 if (!vid_pids)
658                         continue;
659                 while (vid_pids->vid) {
660                         if (vid_pids->vid == vid && vid_pids->pid == pid)
661                                 return desc->chipname;
662                         vid_pids++;
663                 }
664         }
665
666         return NULL;
667 }
668
669 /**
670  * See if a text string is a valid USB path for a HID device.
671  * @param[in] serial The serial port that is about to get opened.
672  * @param[in] path The (assumed) USB path specification.
673  * @return SR_OK upon success, SR_ERR* upon failure.
674  */
675 static int try_open_path(struct sr_serial_dev_inst *serial, const char *path)
676 {
677         int rc;
678
679         serial->usb_path = g_strdup(path);
680         rc = ser_hid_hidapi_open_dev(serial);
681         ser_hid_hidapi_close_dev(serial);
682         g_free(serial->usb_path);
683         serial->usb_path = NULL;
684
685         return rc;
686 }
687
688 /**
689  * Parse conn= specs for serial over HID communication.
690  *
691  * @param[in] serial The serial port that is about to get opened.
692  * @param[in] spec The caller provided conn= specification.
693  * @param[out] chip_ref Pointer to a chip type (enum).
694  * @param[out] path_ref Pointer to a USB path (text string).
695  * @param[out] serno_ref Pointer to a serial number (text string).
696  *
697  * @return 0 upon success, non-zero upon failure. Fills the *_ref output
698  * values.
699  *
700  * Summary of parsing rules as they are implemented:
701  * - Insist on the "hid" prefix. Accept "hid" alone without any other
702  *   additional field.
703  * - The first field that follows can be a chip spec, yet is optional.
704  * - Any other field is assumed to be either a USB path or a serial
705  *   number. There is no point in specifying both of these, as either
706  *   of them uniquely identifies a device.
707  *
708  * Supported formats resulting from these rules:
709  *   hid[/<chip>]
710  *   hid[/<chip>]/usb=<bus>.<dev>[.<if>]
711  *   hid[/<chip>]/raw=<path>    (may contain slashes!)
712  *   hid[/<chip>]/sn=serno
713  *
714  * This routine just parses the conn= spec, which either was provided by
715  * a user, or may reflect (cite) an item of a previously gathered listing
716  * (clipboard provided by CLI clients, or selected from a GUI form).
717  * Another routine will fill in the blanks, and do the cable selection
718  * when a filter was specified.
719  *
720  * Users will want to use short forms when they need to come up with the
721  * specs by themselves. The "verbose" or seemingly redundant forms (chip
722  * _and_ path/serno spec) are useful when the cable uses non-standard or
723  * not-yet-supported VID:PID items when automatic chip detection fails.
724  */
725 static int ser_hid_parse_conn_spec(
726         struct sr_serial_dev_inst *serial, const char *spec,
727         enum ser_hid_chip_t *chip_ref, char **path_ref, char **serno_ref)
728 {
729         const char *p;
730         enum ser_hid_chip_t chip;
731         char *path, *serno;
732         int rc;
733
734         if (chip_ref)
735                 *chip_ref = SER_HID_CHIP_UNKNOWN;
736         if (path_ref)
737                 *path_ref = NULL;
738         if (serno_ref)
739                 *serno_ref = NULL;
740         chip = SER_HID_CHIP_UNKNOWN;
741         path = serno = NULL;
742
743         if (!serial || !spec || !*spec)
744                 return SR_ERR_ARG;
745         p = spec;
746
747         /* The "hid" prefix is mandatory. */
748         if (!g_str_has_prefix(p, SER_HID_CONN_PREFIX))
749                 return SR_ERR_ARG;
750         p += strlen(SER_HID_CONN_PREFIX);
751
752         /*
753          * Check for prefixed fields, assume chip type spec otherwise.
754          * Paths and serial numbers "are greedy" (span to the end of
755          * the input spec). Chip types are optional, and cannot repeat
756          * multiple times.
757          */
758         while (*p) {
759                 if (*p == '/')
760                         p++;
761                 if (!*p)
762                         break;
763                 if (g_str_has_prefix(p, SER_HID_USB_PREFIX)) {
764                         rc = try_open_path(serial, p);
765                         if (rc != SR_OK)
766                                 return rc;
767                         path = g_strdup(p);
768                         p += strlen(p);
769                 } else if (g_str_has_prefix(p, SER_HID_IOKIT_PREFIX)) {
770                         rc = try_open_path(serial, p);
771                         if (rc != SR_OK)
772                                 return rc;
773                         path = g_strdup(p);
774                         p += strlen(p);
775                 } else if (g_str_has_prefix(p, SER_HID_RAW_PREFIX)) {
776                         rc = try_open_path(serial, p);
777                         if (rc != SR_OK)
778                                 return rc;
779                         path = g_strdup(p);
780                         p += strlen(p);
781                 } else if (g_str_has_prefix(p, SER_HID_SNR_PREFIX)) {
782                         p += strlen(SER_HID_SNR_PREFIX);
783                         serno = g_strdup(p);
784                         p += strlen(p);
785                 } else if (!chip) {
786                         char *copy;
787                         const char *endptr;
788                         copy = g_strdup(p);
789                         endptr = copy;
790                         chip = ser_hid_chip_find_enum(&endptr);
791                         if (!chip) {
792                                 g_free(copy);
793                                 return SR_ERR_ARG;
794                         }
795                         p += endptr - copy;
796                         g_free(copy);
797                 } else {
798                         sr_err("unsupported conn= spec %s, error at %s", spec, p);
799                         return SR_ERR_ARG;
800                 }
801                 if (*p == '/')
802                         p++;
803                 if (path || serno)
804                         break;
805         }
806
807         if (chip_ref)
808                 *chip_ref = chip;
809         if (path_ref && path)
810                 *path_ref = path;
811         if (serno_ref && serno)
812                 *serno_ref = serno;
813
814         return SR_OK;
815 }
816
817 /* Get and compare serial number. Boolean return value. */
818 static int check_serno(const char *path, const char *serno_want)
819 {
820         char *hid_path;
821         char serno_got[128];
822         int rc;
823
824         hid_path = extract_hidapi_path(path);
825         rc = ser_hid_hidapi_get_serno(hid_path, serno_got, sizeof(serno_got));
826         g_free(hid_path);
827         if (rc) {
828                 sr_dbg("DBG: %s(), could not get serial number", __func__);
829                 return 0;
830         }
831
832         return strcmp(serno_got, serno_want) == 0;
833 }
834
835 static GSList *append_find(GSList *devs, const char *path)
836 {
837         char *copy;
838
839         if (!path || !*path)
840                 return devs;
841
842         copy = g_strdup(path);
843         devs = g_slist_append(devs, copy);
844
845         return devs;
846 }
847
848 static GSList *list_paths_for_vids_pids(const struct vid_pid_item *vid_pids)
849 {
850         GSList *list;
851         size_t idx;
852         uint16_t vid, pid;
853
854         list = NULL;
855         for (idx = 0; /* EMPTY */; idx++) {
856                 if (!vid_pids) {
857                         vid = pid = 0;
858                 } else if (!vid_pids[idx].vid) {
859                         break;
860                 } else {
861                         vid = vid_pids[idx].vid;
862                         pid = vid_pids[idx].pid;
863                 }
864                 list = ser_hid_hidapi_find_usb(list, append_find, vid, pid);
865                 if (!vid_pids)
866                         break;
867         }
868
869         return list;
870 }
871
872 /**
873  * Search for a matching USB device for HID communication.
874  *
875  * @param[inout] chip The HID chip type (enum).
876  * @param[inout] usbpath The USB path for the device (string).
877  * @param[in] serno The serial number to search for.
878  *
879  * @retval SR_OK upon success
880  * @retval SR_ERR_* upon failure.
881  *
882  * This routine fills in blanks which the conn= spec parser left open.
883  * When not specified yet, the HID chip type gets determined. When a
884  * serial number was specified, then search the corresponding device.
885  * Upon completion, the chip type and USB path for the device shall be
886  * known, as these are essential for subsequent operation.
887  */
888 static int ser_hid_chip_search(enum ser_hid_chip_t *chip_ref,
889         char **path_ref, const char *serno)
890 {
891         enum ser_hid_chip_t chip;
892         char *path;
893         int have_chip, have_path, have_serno;
894         struct ser_hid_chip_functions *chip_funcs;
895         int rc;
896         int serno_matched;
897         uint16_t vid, pid;
898         const char *name;
899         const struct vid_pid_item *vid_pids;
900         GSList *list, *matched, *matched2, *tmplist;
901
902         if (!chip_ref)
903                 return SR_ERR_ARG;
904         chip = *chip_ref;
905         if (!path_ref)
906                 return SR_ERR_ARG;
907         path = *path_ref;
908
909         /*
910          * Simplify the more complex conditions somewhat by assigning
911          * to local variables. Handle the easiest conditions first.
912          * - Either path or serial number can be specified, but not both
913          *   at the same time.
914          * - When a USB path is given, immediately see which HID chip
915          *   the device has, without the need for enumeration.
916          * - When a serial number is given, enumerate the devices and
917          *   search for that number. Either enumerate all devices of the
918          *   specified HID chip type (try the VID:PID pairs that we are
919          *   aware of), or try all HID devices for unknown chip types.
920          *   Not finding the serial number is fatal.
921          * - When no path was found yet, enumerate the devices and pick
922          *   one of them. Try known VID:PID pairs for a HID chip, or all
923          *   devices for unknown chips. Make sure to pick a device of a
924          *   supported chip type if the chip was not specified.
925          * - Determine the chip type if not yet known. There should be
926          *   a USB path by now, determined in one of the above blocks.
927          */
928         have_chip = (chip != SER_HID_CHIP_UNKNOWN) ? 1 : 0;
929         have_path = (path && *path) ? 1 : 0;
930         have_serno = (serno && *serno) ? 1 : 0;
931         if (have_path && have_serno) {
932                 sr_err("Unsupported combination of USB path and serno");
933                 return SR_ERR_ARG;
934         }
935         chip_funcs = have_chip ? get_hid_chip_funcs(chip) : NULL;
936         if (have_chip && !chip_funcs)
937                 return SR_ERR_NA;
938         if (have_chip && !chip_funcs->vid_pid_items)
939                 return SR_ERR_NA;
940         if (have_path && !have_chip) {
941                 vid = pid = 0;
942                 rc = ser_hid_hidapi_get_vid_pid(path, &vid, &pid);
943                 if (rc != SR_OK)
944                         return rc;
945                 name = ser_hid_chip_find_name_vid_pid(vid, pid);
946                 if (!name || !*name)
947                         return SR_ERR_NA;
948                 chip = ser_hid_chip_find_enum(&name);
949                 if (chip == SER_HID_CHIP_UNKNOWN)
950                         return SR_ERR_NA;
951                 have_chip = 1;
952         }
953         if (have_serno) {
954                 vid_pids = have_chip ? chip_funcs->vid_pid_items : NULL;
955                 list = list_paths_for_vids_pids(vid_pids);
956                 if (!list)
957                         return SR_ERR_NA;
958                 matched = NULL;
959                 for (tmplist = list; tmplist; tmplist = tmplist->next) {
960                         path = get_hidapi_path_copy(tmplist->data);
961                         serno_matched = check_serno(path, serno);
962                         g_free(path);
963                         if (!serno_matched)
964                                 continue;
965                         matched = tmplist;
966                         break;
967                 }
968                 if (!matched)
969                         return SR_ERR_NA;
970                 path = g_strdup(matched->data);
971                 have_path = 1;
972                 g_slist_free_full(list, g_free);
973         }
974         if (!have_path) {
975                 vid_pids = have_chip ? chip_funcs->vid_pid_items : NULL;
976                 list = list_paths_for_vids_pids(vid_pids);
977                 if (!list)
978                         return SR_ERR_NA;
979                 matched = matched2 = NULL;
980                 if (have_chip) {
981                         /* List already only contains specified chip. */
982                         matched = list;
983                         matched2 = list->next;
984                 }
985                 /* Works for lists with one or multiple chips. Saves indentation. */
986                 for (tmplist = list; tmplist; tmplist = tmplist->next) {
987                         if (have_chip)
988                                 break;
989                         path = tmplist->data;
990                         rc = ser_hid_hidapi_get_vid_pid(path, &vid, &pid);
991                         if (rc || !ser_hid_chip_find_name_vid_pid(vid, pid))
992                                 continue;
993                         if (!matched) {
994                                 matched = tmplist;
995                                 continue;
996                         }
997                         if (!matched2) {
998                                 matched2 = tmplist;
999                                 break;
1000                         }
1001                 }
1002                 if (!matched) {
1003                         g_slist_free_full(list, g_free);
1004                         return SR_ERR_NA;
1005                 }
1006                 /*
1007                  * TODO Optionally fail harder, expect users to provide
1008                  * unambiguous cable specs.
1009                  */
1010                 if (matched2)
1011                         sr_info("More than one cable matches, random pick.");
1012                 path = get_hidapi_path_copy(matched->data);
1013                 have_path = 1;
1014                 g_slist_free_full(list, g_free);
1015         }
1016         if (have_path && !have_chip) {
1017                 vid = pid = 0;
1018                 rc = ser_hid_hidapi_get_vid_pid(path, &vid, &pid);
1019                 if (rc != SR_OK)
1020                         return rc;
1021                 name = ser_hid_chip_find_name_vid_pid(vid, pid);
1022                 if (!name || !*name)
1023                         return SR_ERR_NA;
1024                 chip = ser_hid_chip_find_enum(&name);
1025                 if (chip == SER_HID_CHIP_UNKNOWN)
1026                         return SR_ERR_NA;
1027                 have_chip = 1;
1028         }
1029         (void)have_chip;
1030
1031         if (chip_ref)
1032                 *chip_ref = chip;
1033         if (path_ref)
1034                 *path_ref = path;
1035
1036         return SR_OK;
1037 }
1038
1039 /* }}} */
1040 /* {{{ transport methods called by the common serial.c code */
1041
1042 /* See if a serial port's name refers to an HID type. */
1043 SR_PRIV int ser_name_is_hid(struct sr_serial_dev_inst *serial)
1044 {
1045         size_t off;
1046         char sep;
1047
1048         if (!serial)
1049                 return 0;
1050         if (!serial->port || !*serial->port)
1051                 return 0;
1052
1053         /* Accept either "hid" alone, or "hid/" as a prefix. */
1054         if (!g_str_has_prefix(serial->port, SER_HID_CONN_PREFIX))
1055                 return 0;
1056         off = strlen(SER_HID_CONN_PREFIX);
1057         sep = serial->port[off];
1058         if (sep != '\0' && sep != '/')
1059                 return 0;
1060
1061         return 1;
1062 }
1063
1064 static int ser_hid_open(struct sr_serial_dev_inst *serial, int flags)
1065 {
1066         enum ser_hid_chip_t chip;
1067         char *usbpath, *serno;
1068         int rc;
1069
1070         (void)flags;
1071
1072         if (ser_hid_setup_funcs(serial) != 0) {
1073                 sr_err("Cannot determine HID communication library.");
1074                 return SR_ERR_NA;
1075         }
1076
1077         rc = ser_hid_parse_conn_spec(serial, serial->port,
1078                         &chip, &usbpath, &serno);
1079         if (rc != SR_OK)
1080                 return SR_ERR_ARG;
1081
1082         /*
1083          * When a serial number was specified, or when the chip type or
1084          * the USB path were not specified, do a search to determine the
1085          * device's USB path.
1086          */
1087         if (!chip || !usbpath || serno) {
1088                 rc = ser_hid_chip_search(&chip, &usbpath, serno);
1089                 if (rc != 0)
1090                         return SR_ERR_NA;
1091         }
1092
1093         /*
1094          * Open the HID device. Only store chip type and device handle
1095          * when open completes successfully.
1096          */
1097         serial->hid_chip = chip;
1098         if (ser_hid_setup_funcs(serial) != 0) {
1099                 sr_err("Cannot determine HID chip specific routines.");
1100                 return SR_ERR_NA;
1101         }
1102         if (usbpath && *usbpath)
1103                 serial->usb_path = usbpath;
1104         if (serno && *serno)
1105                 serial->usb_serno = serno;
1106
1107         rc = ser_hid_hidapi_open_dev(serial);
1108         if (rc) {
1109                 sr_err("Failed to open HID device.");
1110                 serial->hid_chip = 0;
1111                 g_free(serial->usb_path);
1112                 serial->usb_path = NULL;
1113                 g_free(serial->usb_serno);
1114                 serial->usb_serno = NULL;
1115                 return SR_ERR_IO;
1116         }
1117
1118         if (!serial->rcv_buffer)
1119                 serial->rcv_buffer = g_string_sized_new(SER_HID_CHUNK_SIZE);
1120
1121         return SR_OK;
1122 }
1123
1124 static int ser_hid_close(struct sr_serial_dev_inst *serial)
1125 {
1126         ser_hid_hidapi_close_dev(serial);
1127
1128         return SR_OK;
1129 }
1130
1131 static int ser_hid_set_params(struct sr_serial_dev_inst *serial,
1132         int baudrate, int bits, int parity, int stopbits,
1133         int flowcontrol, int rts, int dtr)
1134 {
1135         if (ser_hid_setup_funcs(serial) != 0)
1136                 return SR_ERR_NA;
1137         if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->set_params)
1138                 return SR_ERR_NA;
1139
1140         return serial->hid_chip_funcs->set_params(serial,
1141                 baudrate, bits, parity, stopbits,
1142                 flowcontrol, rts, dtr);
1143 }
1144
1145 static int ser_hid_setup_source_add(struct sr_session *session,
1146         struct sr_serial_dev_inst *serial, int events, int timeout,
1147         sr_receive_data_callback cb, void *cb_data)
1148 {
1149         return ser_hid_hidapi_setup_source_add(session, serial,
1150                 events, timeout, cb, cb_data);
1151 }
1152
1153 static int ser_hid_setup_source_remove(struct sr_session *session,
1154         struct sr_serial_dev_inst *serial)
1155 {
1156         return ser_hid_hidapi_setup_source_remove(session, serial);
1157 }
1158
1159 static GSList *ser_hid_list(GSList *list, sr_ser_list_append_t append)
1160 {
1161         return ser_hid_hidapi_list(list, append);
1162 }
1163
1164 static GSList *ser_hid_find_usb(GSList *list, sr_ser_find_append_t append,
1165         uint16_t vendor_id, uint16_t product_id)
1166 {
1167         return ser_hid_hidapi_find_usb(list, append, vendor_id, product_id);
1168 }
1169
1170 static int ser_hid_flush(struct sr_serial_dev_inst *serial)
1171 {
1172         if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->flush)
1173                 return SR_ERR_NA;
1174
1175         return serial->hid_chip_funcs->flush(serial);
1176 }
1177
1178 static int ser_hid_drain(struct sr_serial_dev_inst *serial)
1179 {
1180         if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->drain)
1181                 return SR_ERR_NA;
1182
1183         return serial->hid_chip_funcs->drain(serial);
1184 }
1185
1186 static int ser_hid_write(struct sr_serial_dev_inst *serial,
1187         const void *buf, size_t count,
1188         int nonblocking, unsigned int timeout_ms)
1189 {
1190         int total, max_chunk, chunk_len;
1191         int rc;
1192
1193         if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->write_bytes)
1194                 return SR_ERR_NA;
1195         if (!serial->hid_chip_funcs->max_bytes_per_request)
1196                 return SR_ERR_NA;
1197
1198         total = 0;
1199         max_chunk = serial->hid_chip_funcs->max_bytes_per_request;
1200         while (count > 0) {
1201                 chunk_len = count;
1202                 if (max_chunk && chunk_len > max_chunk)
1203                         chunk_len = max_chunk;
1204                 rc = serial->hid_chip_funcs->write_bytes(serial, buf, chunk_len);
1205                 if (rc < 0) {
1206                         sr_err("Error sending transmit data to HID device.");
1207                         return total;
1208                 }
1209                 if (rc != chunk_len) {
1210                         sr_warn("Short transmission to HID device (%d/%d bytes)?",
1211                                         rc, chunk_len);
1212                         return total;
1213                 }
1214                 buf += chunk_len;
1215                 count -= chunk_len;
1216                 total += chunk_len;
1217                 /* TODO
1218                  * Need we wait here? For data to drain through the slow
1219                  * UART. Not all UART-over-HID chips will have FIFOs.
1220                  */
1221                 if (!nonblocking) {
1222                         (void)timeout_ms;
1223                         /* TODO */
1224                 }
1225         }
1226
1227         return total;
1228 }
1229
1230 static int ser_hid_read(struct sr_serial_dev_inst *serial,
1231         void *buf, size_t count,
1232         int nonblocking, unsigned int timeout_ms)
1233 {
1234         gint64 deadline_us, now_us;
1235         uint8_t buffer[SER_HID_CHUNK_SIZE];
1236         int rc;
1237         unsigned int got;
1238
1239         if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->read_bytes)
1240                 return SR_ERR_NA;
1241         if (!serial->hid_chip_funcs->max_bytes_per_request)
1242                 return SR_ERR_NA;
1243
1244         /*
1245          * Immediately satisfy the caller's request from the RX buffer
1246          * if the requested amount of data is available already.
1247          */
1248         if (sr_ser_has_queued_data(serial) >= count)
1249                 return sr_ser_unqueue_rx_data(serial, buf, count);
1250
1251         /*
1252          * When a timeout was specified, then determine the deadline
1253          * where to stop reception.
1254          */
1255         deadline_us = 0;
1256         now_us = 0;             /* Silence a (false) compiler warning. */
1257         if (timeout_ms) {
1258                 now_us = g_get_monotonic_time();
1259                 deadline_us = now_us + timeout_ms * 1000;
1260         }
1261
1262         /*
1263          * Keep receiving from the port until the caller's requested
1264          * amount of data has become available, or the timeout has
1265          * expired. In the absence of a timeout, stop reading when an
1266          * attempt no longer yields receive data.
1267          *
1268          * This implementation assumes that applications will call the
1269          * read routine often enough, or that reception continues in
1270          * background, such that data is not lost and hardware and
1271          * software buffers won't overrun.
1272          */
1273         while (TRUE) {
1274                 /*
1275                  * Determine the timeout (in milliseconds) for this
1276                  * iteration. The 'now_us' timestamp was initially
1277                  * determined above, and gets updated at the bottom of
1278                  * the loop.
1279                  */
1280                 if (deadline_us) {
1281                         timeout_ms = (deadline_us - now_us) / 1000;
1282                         if (!timeout_ms)
1283                                 timeout_ms = 1;
1284                 } else if (nonblocking) {
1285                         timeout_ms = 10;
1286                 } else {
1287                         timeout_ms = 0;
1288                 }
1289
1290                 /*
1291                  * Check the HID transport for the availability of more
1292                  * receive data.
1293                  */
1294                 rc = serial->hid_chip_funcs->read_bytes(serial,
1295                                 buffer, sizeof(buffer), timeout_ms);
1296                 if (rc < 0) {
1297                         sr_dbg("DBG: %s() read error %d.", __func__, rc);
1298                         return SR_ERR;
1299                 }
1300                 if (rc) {
1301                         ser_hid_mask_databits(serial, buffer, rc);
1302                         sr_ser_queue_rx_data(serial, buffer, rc);
1303                 }
1304                 got = sr_ser_has_queued_data(serial);
1305
1306                 /*
1307                  * Stop reading when the requested amount is available,
1308                  * or when the timeout has expired.
1309                  *
1310                  * TODO Consider whether grabbing all RX data is more
1311                  * desirable. Implementing this approach requires a cheap
1312                  * check for the availability of more data on the USB level.
1313                  */
1314                 if (got >= count)
1315                         break;
1316                 if (nonblocking && !rc)
1317                         break;
1318                 if (deadline_us) {
1319                         now_us = g_get_monotonic_time();
1320                         if (now_us >= deadline_us) {
1321                                 sr_dbg("DBG: %s() read loop timeout.", __func__);
1322                                 break;
1323                         }
1324                 }
1325         }
1326
1327         /*
1328          * Satisfy the caller's demand for receive data from previously
1329          * queued incoming data.
1330          */
1331         if (got > count)
1332                 got = count;
1333
1334         return sr_ser_unqueue_rx_data(serial, buf, count);
1335 }
1336
1337 static struct ser_lib_functions serlib_hid = {
1338         .open = ser_hid_open,
1339         .close = ser_hid_close,
1340         .flush = ser_hid_flush,
1341         .drain = ser_hid_drain,
1342         .write = ser_hid_write,
1343         .read = ser_hid_read,
1344         .set_params = ser_hid_set_params,
1345         .set_handshake = std_dummy_set_handshake,
1346         .setup_source_add = ser_hid_setup_source_add,
1347         .setup_source_remove = ser_hid_setup_source_remove,
1348         .list = ser_hid_list,
1349         .find_usb = ser_hid_find_usb,
1350         .get_frame_format = NULL,
1351 };
1352 SR_PRIV struct ser_lib_functions *ser_lib_funcs_hid = &serlib_hid;
1353
1354 /* }}} */
1355 #else
1356
1357 SR_PRIV int ser_name_is_hid(struct sr_serial_dev_inst *serial)
1358 {
1359         (void)serial;
1360
1361         return 0;
1362 }
1363
1364 SR_PRIV struct ser_lib_functions *ser_lib_funcs_hid = NULL;
1365
1366 #endif
1367 #endif
1368 /** @} */