File: brltty-hid.c

package info (click to toggle)
brltty 6.9-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 44,844 kB
  • sloc: ansic: 154,246; java: 13,514; sh: 9,934; xml: 5,672; tcl: 2,679; makefile: 2,346; awk: 713; lisp: 366; python: 321; ml: 301
file content (1067 lines) | stat: -rw-r--r-- 25,564 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
/*
 * BRLTTY - A background process providing access to the console screen (when in
 *          text mode) for a blind person using a refreshable braille display.
 *
 * Copyright (C) 1995-2025 by The BRLTTY Developers.
 *
 * BRLTTY comes with ABSOLUTELY NO WARRANTY.
 *
 * This is free software, placed under the terms of the
 * GNU Lesser General Public License, as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any
 * later version. Please see the file LICENSE-LGPL for details.
 *
 * Web Page: http://brltty.app/
 *
 * This software is maintained by Dave Mielke <dave@mielke.cc>.
 */

#include "prologue.h"

#include <stdarg.h>
#include <string.h>
#include <errno.h>

#include "cmdline.h"
#include "cmdput.h"
#include "log.h"
#include "strfmt.h"
#include "parse.h"
#include "io_hid.h"
#include "hid_items.h"
#include "hid_inspect.h"

static int opt_matchUSBDevices;
static int opt_matchBluetoothDevices;

static char *opt_matchVendorIdentifier;
static char *opt_matchProductIdentifier;

static char *opt_matchManufacturerName;
static char *opt_matchProductDescription;
static char *opt_matchSerialNumber;

static char *opt_matchDeviceAddress;
static char *opt_matchDeviceName;

static int opt_showDeviceIdentifiers;
static int opt_showDeviceAddress;
static int opt_showDeviceName;
static int opt_showHostPath;
static int opt_showHostDevice;

static int opt_listItems;
static int opt_listReports;

static char *opt_readReport;
static char *opt_readFeature;

static char *opt_writeReport;
static char *opt_writeFeature;

static int opt_echoInput;
static char *opt_inputTimeout;

BEGIN_COMMAND_LINE_OPTIONS(programOptions)
  { .word = "match-usb-devices",
    .letter = 'u',
    .setting.flag = &opt_matchUSBDevices,
    .description = strtext("Filter for a USB device (the default if not ambiguous).")
  },

  { .word = "match-bluetooth-devices",
    .letter = 'b',
    .setting.flag = &opt_matchBluetoothDevices,
    .description = strtext("Filter for a Bluetooth device.")
  },

  { .word = "match-vendor-identifier",
    .letter = 'v',
    .argument = strtext("identifier"),
    .setting.string = &opt_matchVendorIdentifier,
    .description = strtext("Match the vendor identifier (four hexadecimal digits).")
  },

  { .word = "match-product-identifier",
    .letter = 'p',
    .argument = strtext("identifier"),
    .setting.string = &opt_matchProductIdentifier,
    .description = strtext("Match the product identifier (four hexadecimal digits).")
  },

  { .word = "match-manufacturer-name",
    .letter = 'm',
    .argument = strtext("string"),
    .setting.string = &opt_matchManufacturerName,
    .description = strtext("Match the start of the manufacturer name (USB only).")
  },

  { .word = "match-product-description",
    .letter = 'd',
    .argument = strtext("string"),
    .setting.string = &opt_matchProductDescription,
    .description = strtext("Match the start of the product description (USB only).")
  },

  { .word = "match-serial-number",
    .letter = 's',
    .argument = strtext("string"),
    .setting.string = &opt_matchSerialNumber,
    .description = strtext("Match the start of the serial number (USB only).")
  },

  { .word = "match-device-address",
    .letter = 'a',
    .argument = strtext("octets"),
    .setting.string = &opt_matchDeviceAddress,
    .description = strtext("Match the full device address (Bluetooth only - all six two-digit, hexadecimal octets separated by a colon [:]).")
  },

  { .word = "match-device-name",
    .letter = 'n',
    .argument = strtext("string"),
    .setting.string = &opt_matchDeviceName,
    .description = strtext("Match the start of the device name (Bluetooth only).")
  },

  { .word = "show-device-identifiers",
    .letter = 'I',
    .setting.flag = &opt_showDeviceIdentifiers,
    .description = strtext("Show the vendor and product identifiers.")
  },

  { .word = "show-device-address",
    .letter = 'A',
    .setting.flag = &opt_showDeviceAddress,
    .description = strtext("Show the device address (USB serial number, Bluetooth device address, etc).")
  },

  { .word = "show-device-name",
    .letter = 'N',
    .setting.flag = &opt_showDeviceName,
    .description = strtext("Show the device name (USB manufacturer and/or product strings, Bluetooth device name, etc).")
  },

  { .word = "show-host-path",
    .letter = 'P',
    .setting.flag = &opt_showHostPath,
    .description = strtext("Show the host path (USB topology, Bluetooth host controller address, etc).")
  },

  { .word = "show-host-device",
    .letter = 'D',
    .setting.flag = &opt_showHostDevice,
    .description = strtext("Show the host device (usually its absolute path).")
  },

  { .word = "list-items",
    .letter = 'l',
    .setting.flag = &opt_listItems,
    .description = strtext("List the HID report descriptor's items.")
  },

  { .word = "list-reports",
    .letter = 'L',
    .setting.flag = &opt_listReports,
    .description = strtext("List each report's identifier and sizes.")
  },

  { .word = "read-report",
    .letter = 'r',
    .argument = strtext("identifier"),
    .setting.string = &opt_readReport,
    .description = strtext("Read (get) an input report (two hexadecimal digits).")
  },

  { .word = "read-feature",
    .letter = 'R',
    .argument = strtext("identifier"),
    .setting.string = &opt_readFeature,
    .description = strtext("Read (get) a feature report (two hexadecimal digits).")
  },

  { .word = "write-report",
    .letter = 'w',
    .argument = strtext("bytes"),
    .setting.string = &opt_writeReport,
    .description = strtext("Write (set) an output report (see below)."),
  },

  { .word = "write-feature",
    .letter = 'W',
    .argument = strtext("bytes"),
    .setting.string = &opt_writeFeature,
    .description = strtext("Write (set) a feature report (see below)."),
  },

  { .word = "echo-input",
    .letter = 'e',
    .setting.flag = &opt_echoInput,
    .description = strtext("Echo (in hexadecimal) input received from the device.")
  },

  { .word = "input-timeout",
    .letter = 't',
    .argument = strtext("integer"),
    .setting.string = &opt_inputTimeout,
    .description = strtext("The input timeout (in seconds).")
  },
END_COMMAND_LINE_OPTIONS(programOptions)

BEGIN_COMMAND_LINE_PARAMETERS(programParameters)
END_COMMAND_LINE_PARAMETERS(programParameters)

BEGIN_COMMAND_LINE_NOTES(programNotes)
  "When writing a report or feature, the bytes don't need to be, but can be, separated from one another by whitespace.",
  "Each byte is either two hexadecimal digits or zero or more braille dot numbers within [square brackets].",
  "A byte may optionally be followed by an asterisk [*] and a decimal count - if not specified, 1 is assumed.",
  "The first byte is the report number - specify 00 for no report number.",
END_COMMAND_LINE_NOTES

BEGIN_COMMAND_LINE_DESCRIPTOR(programDescriptor)
  .name = "brltty-hid",
  .purpose = strtext("Find HID devices, list report descriptors, read/write reports/features, or monitor input from a HID device."),

  .options = &programOptions,
  .parameters = &programParameters,
  .notes = COMMAND_LINE_NOTES(programNotes),
END_COMMAND_LINE_DESCRIPTOR

static void writeBytesLine (
  const char *format,
  const unsigned char *from, size_t count,
  ...
) PRINTF(1, 4);

static void
writeBytesLine (const char *format, const unsigned char *from, size_t count, ...) {
  const unsigned char *to = from + count;

  char bytes[(count * 3) + 1];
  STR_BEGIN(bytes, sizeof(bytes));

  while (from < to) {
    STR_PRINTF(" %02X", *from++);
  }
  STR_END;

  char label[0X100];
  {
    va_list arguments;
    va_start(arguments, count);
    vsnprintf(label, sizeof(label), format, arguments);
    va_end(arguments);
  }

  putf("%s:%s\n", label, bytes);
  putFlush();
}

static int
openDevice (HidDevice **device) {
  HidFilter filter = {
    .usb = {
      .manufacturerName = opt_matchManufacturerName,
      .productDescription = opt_matchProductDescription,
      .serialNumber = opt_matchSerialNumber,
    },

    .bluetooth = {
      .macAddress = opt_matchDeviceAddress,
      .deviceName = opt_matchDeviceName,
    },

    .flags = {
      .wantUSB = opt_matchUSBDevices,
      .wantBluetooth = opt_matchBluetoothDevices,
    },
  };

  int ok = hidSetFilterIdentifiers(
    &filter, opt_matchVendorIdentifier, opt_matchProductIdentifier
  );

  if (!ok) return 0;
  return hidOpenDeviceWithFilter(device, &filter);
}

static const HidItemsDescriptor *
getItems (HidDevice *device) {
  const HidItemsDescriptor *items = hidGetItems(device);
  if (!items) logMessage(LOG_ERR, "HID items not available");
  return items;
}

static int
getReportSize (HidDevice *device, HidReportIdentifier identifier, HidReportSize *size) {
  const HidItemsDescriptor *items = getItems(device);
  if (!items) return 0;
  return hidReportSize(items, identifier, size);
}

static void
logUnexpectedLength (
  const char *what, HidReportIdentifier identifier,
  size_t expected, size_t actual
) {
  logMessage(LOG_WARNING,
    "unexpected %s length: %02X:"
    " Expected:%"PRIsize " Actual:%"PRIsize,
    what, identifier, expected, actual
  );
}

static int
performShowDeviceIdentifiers (HidDevice *device) {
  HidDeviceIdentifier vendor;
  HidDeviceIdentifier product;

  if (!hidGetDeviceIdentifiers(device, &vendor, &product)) {
    logMessage(LOG_WARNING, "vendor/product identifiers not available");
    return 0;
  }

  putf("Device Identifiers: %04X:%04X\n", vendor, product);
  return 1;
}

static int
performShowDeviceAddress (HidDevice *device) {
  const char *address = hidGetDeviceAddress(device);

  if (!address) {
    logMessage(LOG_WARNING, "device address not available");
    return 0;
  }

  putf("Device Address: %s\n", address);
  return 1;
}

static int
performShowDeviceName (HidDevice *device) {
  const char *name = hidGetDeviceName(device);

  if (!name) {
    logMessage(LOG_WARNING, "device name not available");
    return 0;
  }

  putf("Device Name: %s\n", name);
  return 1;
}

static int
performShowHostPath (HidDevice *device) {
  const char *path = hidGetHostPath(device);

  if (!path) {
    logMessage(LOG_WARNING, "host path not available");
    return 0;
  }

  putf("Host Path: %s\n", path);
  return 1;
}

static int
performShowHostDevice (HidDevice *device) {
  const char *hostDevice = hidGetHostDevice(device);

  if (!hostDevice) {
    logMessage(LOG_WARNING, "host device not available");
    return 0;
  }

  putf("Host Device: %s\n", hostDevice);
  return 1;
}

static int
listItem (const char *line, void *data) {
  putf("%s\n", line);
  return 1;
}

static int
performListItems (HidDevice *device) {
  const HidItemsDescriptor *items = getItems(device);
  if (!items) return 0;

  hidListItems(items, listItem, NULL);
  return 1;
}

static int
performListReports (HidDevice *device) {
  const HidItemsDescriptor *items = getItems(device);
  if (!items) return 0;

  HidReports *reports = hidGetReports(items);
  if (!reports) return 0;

  for (unsigned int index=0; index<reports->count; index+=1) {
    unsigned char identifier = reports->identifiers[index];
    HidReportSize size;

    char line[0X40];
    STR_BEGIN(line, sizeof(line));
    STR_PRINTF("Report %02X:", identifier);

    if (hidReportSize(items, identifier, &size)) {
      typedef struct {
        const char *label;
        const size_t value;
      } SizeEntry;

      const SizeEntry sizeTable[] = {
        { .value = size.input,
          .label = "In",
        },

        { .value = size.output,
          .label = "Out",
        },

        { .value = size.feature,
          .label = "Ftr",
        },
      };

      const SizeEntry *size = sizeTable;
      const SizeEntry *end = size + ARRAY_COUNT(sizeTable);

      while (size < end) {
        if (size->value) {
          STR_PRINTF(" %s:%"PRIsize, size->label, size->value);
        }

        size += 1;
      }
    }

    STR_END;
    putf("%s\n", line);
  }

  free(reports);
  return 1;
}

static int
isReportIdentifier (HidReportIdentifier *identifier, const char *string, unsigned char minimum) {
  if (strlen(string) != 2) return 0;

  char *end;
  unsigned long int value = strtoul(string, &end, 0X10);
  if (*end) return 0;

  if (value > UINT8_MAX) return 0;
  *identifier = value;
  return 1;
}

static int
isReportDefined (
  HidDevice *device, const char *what, HidReportIdentifier identifier,
  HidReportSize *reportSize, size_t *size
) {
  if (getReportSize(device, identifier, reportSize)) {
    if (*size) {
      return 1;
    }
  }

  logMessage(LOG_ERR, "%s report not defined: %02X", what, identifier);
  return 0;
}

static int
verifyRead (
  HidDevice *device, const char *what, HidReportIdentifier identifier,
  HidReportSize *reportSize, size_t *size
) {
  int isDefined = isReportDefined(
    device, what, identifier,
    reportSize, size
  );

  return isDefined;
}

static HidReportIdentifier readReportIdentifier;

static int
parseReadReport (void) {
  const char *operand = opt_readReport;
  if (!*operand) return 1;
  if (isReportIdentifier(&readReportIdentifier, operand, 0)) return 1;

  logMessage(LOG_ERR, "invalid input report identifier: %s", operand);
  return 0;
}

static int
performReadReport (HidDevice *device) {
  HidReportIdentifier identifier = readReportIdentifier;

  HidReportSize reportSize;
  size_t *size = &reportSize.input;

  int verified = verifyRead(
    device, "input", identifier,
    &reportSize, size
  );

  if (verified) {
    size_t length = *size;
    unsigned char report[length];

    report[0] = identifier;
    ssize_t result = hidGetReport(device, report, length);

    if (result == -1) {
      logSystemError("hidGetReport");
    } else {
      writeBytesLine("Input Report: %02X", report, result, identifier);
      if (result == length) return 1;
      logUnexpectedLength("report read", identifier, length, result);
    }
  }

  return 0;
}

static HidReportIdentifier readFeatureIdentifier;

static int
parseReadFeature (void) {
  const char *operand = opt_readFeature;
  if (!*operand) return 1;
  if (isReportIdentifier(&readFeatureIdentifier, operand, 1)) return 1;

  logMessage(LOG_ERR, "invalid feature report identifier: %s", operand);
  return 0;
}

static int
performReadFeature (HidDevice *device) {
  HidReportIdentifier identifier = readFeatureIdentifier;

  HidReportSize reportSize;
  size_t *size = &reportSize.feature;

  int verified = verifyRead(
    device, "feature", identifier,
    &reportSize, size
  );

  if (verified) {
    size_t length = *size;
    unsigned char feature[length];

    feature[0] = identifier;
    ssize_t result = hidGetFeature(device, feature, length);

    if (result == -1) {
      logSystemError("hidGetFeature");
    } else {
      writeBytesLine("Feature Report: %02X", feature, result, identifier);
      if (result == length) return 1;
      logUnexpectedLength("feature read", identifier, length, result);
    }
  }

  return 0;
}

static int
isHexadecimal (unsigned char *digit, char character) {
  const char string[] = {character, 0};
  char *end;
  long int value = strtol(string, &end, 0X10);

  if (*end) {
    logMessage(LOG_ERR, "invalid hexadecimal digit: %c", character);
    return 0;
  }

  *digit = value;
  return 1;
}

static int
parseBytes (
  const char *bytes, const char *what, unsigned char *buffer,
  size_t bufferSize, size_t *bufferUsed
) {
  unsigned char *out = buffer;
  const unsigned char *end = out + bufferSize;

  if (*bytes) {
    const char *in = bytes;
    unsigned char byte = 0;
    unsigned int count = 1;

    enum {NEXT, HEX, DOTS, COUNT};
    unsigned int state = NEXT;

    while (*in) {
      char character = *in++;

      switch (state) {
        case NEXT: {
          if (iswspace(character)) continue;

          if (character == '[') {
            state = DOTS;
            continue;
          }

          unsigned char digit;
          if (!isHexadecimal(&digit, character)) return 0;

          byte = digit << 4;
          state = HEX;
          continue;
        }

        case HEX: {
          unsigned char digit;
          if (!isHexadecimal(&digit, character)) return 0;

          byte |= digit;
          state = NEXT;
          break;
        }

        case DOTS: {
          if (character == ']') {
            state = NEXT;
            break;
          }

          if ((character < '1') || (character > '8')) {
            logMessage(LOG_ERR, "invalid dot number: %c", character);
            return 0;
          }
          unsigned char bit = 1 << (character - '1');

          if (byte & bit) {
            logMessage(LOG_ERR, "duplicate dot number: %c", character);
            return 0;
          }

          byte |= bit;
          continue;
        }

        case COUNT: {
          if (iswspace(character)) break;
          int digit = character - '0';

          if ((digit < 0) || (digit > 9)) {
            logMessage(LOG_ERR, "invalid count digit: %c", character);
            return 0;
          }

          if (!digit) {
            if (!count) {
              logMessage(LOG_ERR, "first digit of count can't be 0");
              return 0;
            }
          }

          count *= 10;
          count += digit;

          if (!*in) break;
          continue;
        }

        default:
          logMessage(LOG_ERR, "unexpected bytes parser state: %u", state);
          return 0;
      }

      if (state == COUNT) {
        if (!count) {
          logMessage(LOG_ERR, "missing count");
          return 0;
        }

        state = NEXT;
      } else if (*in == '*') {
        in += 1;
        state = COUNT;
        count = 0;
        continue;
      }

      while (count--) {
        if (out == end) {
          logMessage(LOG_ERR, "%s buffer too small", what);
          return 0;
        }

        *out++ = byte;
      }

      byte = 0;
      count = 1;
    }

    if (state != NEXT) {
      logMessage(LOG_ERR, "incomplete %s specification", what);
      return 0;
    }
  }

  *bufferUsed = out - buffer;
  return 1;
}

static int
verifyWrite (
  HidDevice *device, const char *what, unsigned char *identifier,
  HidReportSize *reportSize, size_t *expectedSize,
  const unsigned char *buffer, size_t actualSize
) {
  *identifier = buffer[0];

  int isDefined = isReportDefined(
    device, what, *identifier,
    reportSize, expectedSize
  );

  if (!isDefined) return 0;
  if (!*identifier) *expectedSize += 1;

  if (actualSize != *expectedSize) {
    logMessage(LOG_ERR,
      "incorrect %s report size: %02X:"
      " Expected:%"PRIsize " Actual:%"PRIsize,
      what, *identifier, *expectedSize, actualSize
    );

    return 0;
  }

  return 1;
}

static unsigned char writeReportBuffer[0X1000];
static size_t writeReportLength;

static int
parseWriteReport (void) {
  return parseBytes(
    opt_writeReport, "output report", writeReportBuffer,
    ARRAY_COUNT(writeReportBuffer), &writeReportLength
  );
}

static int
performWriteReport (HidDevice *device) {
  const unsigned char *report = writeReportBuffer;
  size_t length = writeReportLength;

  unsigned char identifier;
  HidReportSize reportSize;

  int verified = verifyWrite(
    device, "output", &identifier,
    &reportSize, &reportSize.output,
    report, length
  );

  if (verified) {
    writeBytesLine("Writing Report: %02X", report, length, identifier);
    ssize_t result = hidSetReport(device, report, length);

    if (result == -1) {
      logSystemError("hidSetReport");
    } else if (result == length) {
      return 1;
    } else {
      logUnexpectedLength("report write", identifier, length, result);
    }
  }

  return 0;
}

static unsigned char writeFeatureBuffer[0X1000];
static size_t writeFeatureLength;

static int
parseWriteFeature (void) {
  return parseBytes(
    opt_writeFeature, "feature report", writeFeatureBuffer,
    ARRAY_COUNT(writeFeatureBuffer), &writeFeatureLength
  );
}

static int
performWriteFeature (HidDevice *device) {
  const unsigned char *feature = writeFeatureBuffer;
  size_t length = writeFeatureLength;

  unsigned char identifier;
  HidReportSize reportSize;

  int verified = verifyWrite(
    device, "feature", &identifier,
    &reportSize, &reportSize.feature,
    feature, length
  );

  if (verified) {
    writeBytesLine("Writing Feature: %02X", feature, length, identifier);
    ssize_t result = hidSetFeature(device, feature, length);

    if (result == -1) {
      logSystemError("hidSetFeature");
    } else if (result == length) {
      return 1;
    } else {
      logUnexpectedLength("feature write", identifier, length, result);
    }
  }

  return 0;
}

static int inputTimeout;

static int
parseInputTimeout (void) {
  inputTimeout = 10;

  static const int minimum = 1;
  static const int maximum = 99;

  if (!validateInteger(&inputTimeout, opt_inputTimeout, &minimum, &maximum)) {
    logMessage(LOG_ERR, "invalid input timeout: %s", opt_inputTimeout);
    return 0;
  }

  inputTimeout *= 1000;
  return 1;
}

static int
performEchoInput (HidDevice *device) {
  HidReportSize reportSize;
  const size_t *inputSize = &reportSize.input;

  unsigned char reportIdentifier = 0;
  int hasReportIdentifiers = !getReportSize(device, reportIdentifier, &reportSize);

  unsigned char buffer[0X1000];
  size_t bufferSize = sizeof(buffer);

  unsigned char *from = buffer;
  unsigned char *to = from;
  const unsigned char *end = from + bufferSize;

  while (hidAwaitInput(device, inputTimeout)) {
    ssize_t result = hidReadData(device, to, (end - to), 1000, 100);

    if (result == -1) {
      logMessage(LOG_ERR, "input error: %s", strerror(errno));
      return 0;
    }

    to += result;

    while (from < to) {
      if (hasReportIdentifiers) {
        reportIdentifier = *from;

        if (!getReportSize(device, reportIdentifier, &reportSize)) {
          logMessage(LOG_ERR, "input report not defined: %02X", reportIdentifier);
          return 0;
        }
      }

      if (!*inputSize) {
        logMessage(LOG_ERR, "input report size is zero: %02X", reportIdentifier);
        return 0;
      }

      size_t count = to - from;

      if (*inputSize > count) {
        if (from == buffer) {
          logMessage(LOG_ERR,
            "input report too large: %02X: %"PRIsize " > %"PRIsize,
            reportIdentifier, *inputSize, count
          );

          return 0;
        }

        memmove(buffer, from, count);
        from = buffer;
        to = from + count;

        break;
      }

      writeBytesLine("Input Report", from, *inputSize);
      from += *inputSize;
    }
  }

  return 1;
}

static int
parseOperands (void) {
  typedef struct {
    int (*parse) (void);
  } OperandEntry;

  static const OperandEntry operandTable[] = {
    { .parse = parseReadReport,
    },

    { .parse = parseReadFeature,
    },

    { .parse = parseWriteReport,
    },

    { .parse = parseWriteFeature,
    },

    { .parse = parseInputTimeout,
    },
  };

  const OperandEntry *operand = operandTable;
  const OperandEntry *end = operand + ARRAY_COUNT(operandTable);

  while (operand < end) {
    if (!operand->parse()) return 0;
    operand += 1;
  }

  return 1;
}

static int
performActions (HidDevice *device) {
  typedef struct {
    int (*perform) (HidDevice *device);
    unsigned char isFlag:1;

    union {
      char **string;
      int *flag;
    } option;
  } ActionEntry;

  static const ActionEntry actionTable[] = {
    { .perform = performShowDeviceIdentifiers,
      .isFlag = 1,
      .option.flag = &opt_showDeviceIdentifiers,
    },

    { .perform = performShowDeviceAddress,
      .isFlag = 1,
      .option.flag = &opt_showDeviceAddress,
    },

    { .perform = performShowDeviceName,
      .isFlag = 1,
      .option.flag = &opt_showDeviceName,
    },

    { .perform = performShowHostPath,
      .isFlag = 1,
      .option.flag = &opt_showHostPath,
    },

    { .perform = performShowHostDevice,
      .isFlag = 1,
      .option.flag = &opt_showHostDevice,
    },

    { .perform = performListItems,
      .isFlag = 1,
      .option.flag = &opt_listItems,
    },

    { .perform = performListReports,
      .isFlag = 1,
      .option.flag = &opt_listReports,
    },

    { .perform = performReadReport,
      .option.string = &opt_readReport,
    },

    { .perform = performReadFeature,
      .option.string = &opt_readFeature,
    },

    { .perform = performWriteReport,
      .option.string = &opt_writeReport,
    },

    { .perform = performWriteFeature,
      .option.string = &opt_writeFeature,
    },

    { .perform = performEchoInput,
      .isFlag = 1,
      .option.flag = &opt_echoInput,
    },
  };

  const ActionEntry *action = actionTable;
  const ActionEntry *end = action + ARRAY_COUNT(actionTable);

  while (action < end) {
    int perform = 0;

    if (action->isFlag) {
      if (*action->option.flag) perform = 1;
    } else {
      if (**action->option.string) perform = 1;
    }

    if (perform) {
      if (!action->perform(device)) {
        return 0;
      }
    }

    action += 1;
  }

  return 1;
}

int
main (int argc, char *argv[]) {
  PROCESS_COMMAND_LINE(programDescriptor, argc, argv);

  if (!parseOperands()) return PROG_EXIT_SYNTAX;
  ProgramExitStatus exitStatus = PROG_EXIT_SUCCESS;
  HidDevice *device = NULL;

  if (!openDevice(&device)) {
    exitStatus = PROG_EXIT_SYNTAX;
  } else if (!device) {
    logMessage(LOG_ERR, "device not found");
    exitStatus = PROG_EXIT_SEMANTIC;
  } else {
    if (!performActions(device)) exitStatus = PROG_EXIT_FATAL;
    hidCloseDevice(device);
  }

  return exitStatus;
}