summaryrefslogtreecommitdiff
path: root/src/usbhid-dump.c
blob: 194a912ddb2d78ee66bb1a93b08c4b350b1c8ed8 (plain)
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
/** @file
 * @brief usbhid-dump - entry point
 *
 * Copyright (C) 2010 Nikolai Kondrashov
 *
 * This file is part of usbhid-dump.
 *
 * Usbhid-dump is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Usbhid-dump is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with usbhid-dump; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @author Nikolai Kondrashov <spbnick@gmail.com>
 *
 * @(#) $Id$
 */

#include "uhd/iface.h"
#include "uhd/str.h"
#include "uhd/libusb.h"

#include <assert.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <stdio.h>
#include <libusb-1.0/libusb.h>

#include "config.h"

/**
 * Maximum descriptor size.
 *
 * 4096 here is maximum control buffer length.
 */
#define MAX_DESCRIPTOR_SIZE 4096

/**
 * USB I/O timeout
 */
#define TIMEOUT 1000

#define ERROR(_fmt, _args...) \
    fprintf(stderr, _fmt "\n", ##_args)

#define FAILURE(_fmt, _args...) \
    fprintf(stderr, "Failed to " _fmt "\n", ##_args)

#define LIBUSB_FAILURE(_fmt, _args...) \
    FAILURE(_fmt ": %s", ##_args, libusb_strerror(err))

#define ERROR_CLEANUP(_fmt, _args...) \
    do {                                \
        ERROR(_fmt, ##_args);           \
        goto cleanup;                   \
    } while (0)

#define FAILURE_CLEANUP(_fmt, _args...) \
    ERROR_CLEANUP("Failed to " _fmt, ##_args)

#define LIBUSB_ERROR_CLEANUP(_fmt, _args...) \
    ERROR_CLEANUP(_fmt ": %s", ##_args, libusb_strerror(err))

#define LIBUSB_FAILURE_CLEANUP(_fmt, _args...) \
    LIBUSB_ERROR_CLEANUP("Failed to " _fmt, ##_args)

#define LIBUSB_WATCH(_expr, _fmt, _args...) \
    do {                                    \
        err = _expr;                        \
        if (err != LIBUSB_SUCCESS)          \
            LIBUSB_FAILURE(_fmt, ##_args);  \
    } while (0)

#define LIBUSB_GUARD(_expr, _fmt, _args...) \
    do {                                            \
        err = _expr;                                \
        if (err != LIBUSB_SUCCESS)                  \
            LIBUSB_FAILURE_CLEANUP(_fmt, ##_args);  \
    } while (0)

/**< Number of the signal causing the exit */
static volatile sig_atomic_t exit_signum  = 0;

static void
exit_sighandler(int signum)
{
    if (exit_signum == 0)
        exit_signum = signum;
}

/**< "Stream paused" flag - non-zero if paused */
static volatile sig_atomic_t stream_paused = 0;

static void
stream_pause_sighandler(int signum)
{
    (void)signum;
    stream_paused = 1;
}

static void
stream_resume_sighandler(int signum)
{
    (void)signum;
    stream_paused = 0;
}

/**< "Stream feedback" flag - non-zero if feedback is enabled */
static volatile sig_atomic_t stream_feedback = 0;

static bool
usage(FILE *stream, const char *progname)
{
    return
        fprintf(
            stream,
"Usage: %s [OPTION]... <bus> <dev> [if]\n"
"Dump a USB device HID report descriptor(s) and/or stream(s)."
"\n"
"Arguments:\n"
"  bus                      bus number (1-255)\n"
"  dev                      device address (1-255)\n"
"  if                       interface number (0-254);\n"
"                           if omitted, all device HID interfaces\n"
"                           are dumped\n"
"\n"
"Options:\n"
"  -h, --help               output this help message and exit\n"
"  -v, --version            output version information and exit\n"
"  -e, --entity=STRING      what to dump: either \"descriptor\",\n"
"                           \"stream\" or \"all\"; value can be\n"
"                           abbreviated\n"
"  -p, --stream-paused      start with the stream dump output paused\n"
"  -f, --stream-feedback    enable stream dumping feedback: for every\n"
"                           transfer dumped a dot is printed to stderr\n"
"\n"
"Default options: --entity=descriptor\n"
"\n"
"Signals:\n"
"  USR1/USR2                pause/resume the stream dump output\n"
"\n",
            progname) >= 0;
}


static bool
version(FILE *stream)
{
    return
        fprintf(
            stream,
PACKAGE_STRING "\n"
"Copyright (C) 2010 Nikolai Kondrashov\n"
"License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>.\n"
"\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n") >= 0;
}


static void
dump(uint8_t        iface_num,
     const char    *entity,
     const uint8_t *ptr,
     size_t         len)
{
    static const char   xd[]    = "0123456789ABCDEF";
    static char         buf[]   = " XX\n";
    size_t              pos;
    uint8_t             b;
    struct timeval      tv;

    gettimeofday(&tv, NULL);

    fprintf(stdout, "%.3hhu:%-16s %20llu.%.6u\n",
            iface_num, entity,
            (unsigned long long int)tv.tv_sec,
            (unsigned int)tv.tv_usec);

    for (pos = 1; len > 0; len--, ptr++, pos++)
    {
        b = *ptr;
        buf[1] = xd[b >> 4];
        buf[2] = xd[b & 0xF];

        fwrite(buf, ((pos % 16 == 0) ? 4 : 3), 1, stdout);
    }

    if (pos % 16 != 1)
        fputc('\n', stdout);
    fputc('\n', stdout);

    fflush(stdout);
}


static bool
dump_iface_list_descriptor(const uhd_iface *list)
{
    const uhd_iface    *iface;
    uint8_t             buf[MAX_DESCRIPTOR_SIZE];
    int                 rc;
    enum libusb_error   err;

    UHD_IFACE_LIST_FOR_EACH(iface, list)
    {
        rc = libusb_control_transfer(iface->handle,
                                     /* See HID spec, 7.1.1 */
                                     0x81,
                                     LIBUSB_REQUEST_GET_DESCRIPTOR,
                                     (LIBUSB_DT_REPORT << 8), iface->number,
                                     buf, sizeof(buf), TIMEOUT);
        if (rc < 0)
        {
            err = rc;
            LIBUSB_FAILURE("retrieve interface #%hhu "
                           "report descriptor", iface->number);
            return false;
        }
        dump(iface->number, "DESCRIPTOR", buf, rc);
    }

    return true;
}


static void
dump_iface_list_stream_cb(struct libusb_transfer *transfer)
{
    enum libusb_error   err;
    uhd_iface          *iface;

    assert(transfer != NULL);

    iface = (uhd_iface *)transfer->user_data;
    assert(uhd_iface_valid(iface));

    /* Clear interface "has transfer submitted" flag */
    iface->submitted = false;

    switch (transfer->status)
    {
        case LIBUSB_TRANSFER_COMPLETED:
            /* Dump the result */
            if (!stream_paused)
            {
                dump(iface->number, "STREAM",
                     transfer->buffer, transfer->actual_length);
                if (stream_feedback)
                    fputc('.', stderr);
            }
            /* Resubmit the transfer */
            err = libusb_submit_transfer(transfer);
            if (err != LIBUSB_SUCCESS)
                LIBUSB_FAILURE("resubmit a transfer");
            /* Set interface "has transfer submitted" flag */
            iface->submitted = true;
            break;
#define MAP(_name) \
    case LIBUSB_TRANSFER_##_name:                               \
        fprintf(stderr, "%.3hhu:%s\n", iface->number, #_name);  \
        break

        MAP(ERROR);
        MAP(TIMED_OUT);
        MAP(STALL);
        MAP(NO_DEVICE);
        MAP(OVERFLOW);

#undef MAP
        default:
            break;
    }
}


static bool
dump_iface_list_stream(libusb_context *ctx, uhd_iface *list)
{
    bool                        result              = false;
    enum libusb_error           err;
    size_t                      transfer_num        = 0;
    struct libusb_transfer    **transfer_list       = NULL;
    struct libusb_transfer    **ptransfer;
    uhd_iface                  *iface;
    bool                        submitted           = false;

    UHD_IFACE_LIST_FOR_EACH(iface, list)
    {
        /* Set report protocol */
        LIBUSB_GUARD(uhd_iface_set_protocol(list, true, TIMEOUT),
                     "set report protocol on an interface");
        /* Set infinite idle duration */
        LIBUSB_GUARD(uhd_iface_set_idle(list, 0, TIMEOUT),
                     "set infinite idle duration on an interface");
    }

    /* Calculate number of interfaces and thus transfers */
    transfer_num = uhd_iface_list_len(list);

    /* Allocate transfer list */
    transfer_list = malloc(sizeof(*transfer_list) * transfer_num);
    if (transfer_list == NULL)
        FAILURE_CLEANUP("allocate transfer list");

    /* Zero transfer list */
    for (ptransfer = transfer_list;
         (size_t)(ptransfer - transfer_list) < transfer_num;
         ptransfer++)
        *ptransfer = NULL;

    /* Allocate transfers */
    for (ptransfer = transfer_list;
         (size_t)(ptransfer - transfer_list) < transfer_num;
         ptransfer++)
    {
        *ptransfer = libusb_alloc_transfer(0);
        if (*ptransfer == NULL)
            FAILURE_CLEANUP("allocate a transfer");
        /*
         * Set user_data to NULL explicitly, since libusb_alloc_transfer
         * does memset to zero only and zero is not NULL, strictly speaking.
         */
        (*ptransfer)->user_data = NULL;
    }

    /* Initialize the transfers as interrupt transfers */
    for (ptransfer = transfer_list, iface = list;
         (size_t)(ptransfer - transfer_list) < transfer_num;
         ptransfer++, iface = iface->next)
    {
        void           *buf;
        const size_t    len = iface->int_in_ep_maxp;

        /* Allocate the transfer buffer */
        buf = malloc(len);   
        if (len > 0 && buf == NULL)
            FAILURE_CLEANUP("allocate a transfer buffer");

        /* Initialize the transfer */
        libusb_fill_interrupt_transfer(*ptransfer,
                                       iface->handle, iface->int_in_ep_addr,
                                       buf, len,
                                       dump_iface_list_stream_cb,
                                       (void *)iface,
                                       /* Infinite timeout */
                                       0);

        /* Ask to free the buffer when the transfer is freed */
        (*ptransfer)->flags |= LIBUSB_TRANSFER_FREE_BUFFER;
    }

    /* Submit first transfer requests */
    for (ptransfer = transfer_list;
         (size_t)(ptransfer - transfer_list) < transfer_num;
         ptransfer++)
    {
        err = libusb_submit_transfer(*ptransfer);
        if (err != LIBUSB_SUCCESS)
            LIBUSB_ERROR_CLEANUP("submit a transfer");
        /* Set interface "has transfer submitted" flag */
        ((uhd_iface *)(*ptransfer)->user_data)->submitted = true;
        /* Set "have any submitted transfers" flag */
        submitted = true;
    }

    /* Run the event machine */
    while (submitted && exit_signum == 0)
    {
        /* Handle the transfer events */
        err = libusb_handle_events(ctx);
        if (err != LIBUSB_SUCCESS && err != LIBUSB_ERROR_INTERRUPTED)
            LIBUSB_FAILURE_CLEANUP("handle transfer events");

        /* Check if there are any submitted transfers left */
        submitted = false;
        for (ptransfer = transfer_list;
             (size_t)(ptransfer - transfer_list) < transfer_num;
             ptransfer++)
        {
            iface = (uhd_iface *)(*ptransfer)->user_data;

            if (iface != NULL && iface->submitted)
                submitted = true;
        }
    }

    /* If all the transfers were terminated unexpectedly */
    if (transfer_num > 0 && !submitted)
        ERROR_CLEANUP("No more interfaces to dump");

    result = true;

cleanup:

    /* Cancel the transfers */
    if (submitted)
    {
        submitted = false;
        for (ptransfer = transfer_list;
             (size_t)(ptransfer - transfer_list) < transfer_num;
             ptransfer++)
        {
            iface = (uhd_iface *)(*ptransfer)->user_data;

            if (iface != NULL && iface->submitted)
            {
                err = libusb_cancel_transfer(*ptransfer);
                if (err == LIBUSB_SUCCESS)
                    submitted = true;
                else
                {
                    LIBUSB_FAILURE("cancel a transfer, ignoring");
                    /*
                     * XXX are we really sure
                     * the transfer won't be finished?
                     */
                    iface->submitted = false;
                }
            }
        }
    }

    /* Wait for transfer cancellation */
    while (submitted)
    {
        /* Handle cancellation events */
        err = libusb_handle_events(ctx);
        if (err != LIBUSB_SUCCESS && err != LIBUSB_ERROR_INTERRUPTED)
        {
            LIBUSB_FAILURE("handle transfer cancellation events, "
                           "aborting transfer cancellation");
            break;
        }

        /* Check if there are any submitted transfers left */
        submitted = false;
        for (ptransfer = transfer_list;
             (size_t)(ptransfer - transfer_list) < transfer_num;
             ptransfer++)
        {
            iface = (uhd_iface *)(*ptransfer)->user_data;

            if (iface != NULL && iface->submitted)
                submitted = true;
        }
    }

    /*
     * Free transfer list along with non-submitted transfers and their
     * buffers.
     */
    if (transfer_list != NULL)
    {
        for (ptransfer = transfer_list;
             (size_t)(ptransfer - transfer_list) < transfer_num;
             ptransfer++)
        {
            iface = (uhd_iface *)(*ptransfer)->user_data;

            /*
             * Only free a transfer if it is not submitted. Better leak some
             * memory than have some important memory overwritten.
             */
            if (iface == NULL || !iface->submitted)
                libusb_free_transfer(*ptransfer);
        }

        free(transfer_list);
    }

    return result;
}


static int
run(bool    dump_descriptor,
    bool    dump_stream,
    uint8_t bus_num,
    uint8_t dev_addr,
    int     iface_num)
{
    int                     result      = 1;
    enum libusb_error       err;
    libusb_context         *ctx         = NULL;
    libusb_device_handle   *handle      = NULL;
    uhd_iface              *iface_list  = NULL;
    uhd_iface              *iface;

    /* Initialize libusb context */
    err = libusb_init(&ctx);
    if (err != LIBUSB_SUCCESS)
        LIBUSB_FAILURE_CLEANUP("create libusb context");

    /* Set libusb debug level */
    libusb_set_debug(ctx, 3);

    /* Find and open the device */
    err = libusb_open_device_with_bus_dev(ctx, bus_num, dev_addr, &handle);
    if (err != LIBUSB_SUCCESS)
        LIBUSB_FAILURE_CLEANUP("find and open the device");

    /* Retrieve the list of HID interfaces from a device */
    err = uhd_iface_list_new_from_dev(handle, &iface_list);
    if (err != LIBUSB_SUCCESS)
        LIBUSB_FAILURE_CLEANUP("find a HID interface");

    /* Filter the interface list by specified interface number */
    iface_list = uhd_iface_list_fltr_by_num(iface_list, iface_num);
    if (uhd_iface_list_empty(iface_list))
        ERROR_CLEANUP("No matching HID interfaces");

    /* Detach and claim the interfaces */
    UHD_IFACE_LIST_FOR_EACH(iface, iface_list)
    {
        LIBUSB_GUARD(uhd_iface_detach(iface),
                     "detach an interface from the kernel driver");
        LIBUSB_GUARD(uhd_iface_claim(iface),
                     "claim an interface");
    }

    /* Run with the prepared interface list */
    result = (!dump_descriptor || dump_iface_list_descriptor(iface_list)) &&
             (!dump_stream || dump_iface_list_stream(ctx, iface_list))
               ? 0
               : 1;

cleanup:

    /* Release and attach the interfaces back */
    UHD_IFACE_LIST_FOR_EACH(iface, iface_list)
    {
        LIBUSB_GUARD(uhd_iface_release(iface),
                     "release an interface");
        LIBUSB_GUARD(uhd_iface_attach(iface),
                     "attach an interface to the kernel driver");
    }

    /* Free the interface list */
    uhd_iface_list_free(iface_list);

    /* Free the device */
    if (handle != NULL)
        libusb_close(handle);

    /* Cleanup libusb context, if necessary */
    if (ctx != NULL)
        libusb_exit(ctx);

    return result;
}


typedef enum opt_val {
    OPT_VAL_HELP            = 'h',
    OPT_VAL_VERSION         = 'v',
    OPT_VAL_ENTITY          = 'e',
    OPT_VAL_STREAM_PAUSED   = 'p',
    OPT_VAL_STREAM_FEEDBACK = 'f',
} opt_val;


int
main(int argc, char **argv)
{
    static const struct option long_opt_list[] = {
        {.val       = OPT_VAL_HELP,
         .name      = "help",
         .has_arg   = no_argument,
         .flag      = NULL},
        {.val       = OPT_VAL_VERSION,
         .name      = "version",
         .has_arg   = no_argument,
         .flag      = NULL},
        {.val       = OPT_VAL_ENTITY,
         .name      = "entity",
         .has_arg   = required_argument,
         .flag      = NULL},
        {.val       = OPT_VAL_STREAM_PAUSED,
         .name      = "stream-paused",
         .has_arg   = no_argument,
         .flag      = NULL},
        {.val       = OPT_VAL_STREAM_FEEDBACK,
         .name      = "stream-feedback",
         .has_arg   = no_argument,
         .flag      = NULL},
        {.val       = 0,
         .name      = NULL,
         .has_arg   = 0,
         .flag      = NULL}
    };

    static const char  *short_opt_list = "hve:pf";

    int             result;

    char            c;
    const char     *bus_str;
    const char     *dev_str;
    const char     *if_str      = "";

    const char    **arg_list[] = {&bus_str, &dev_str, &if_str};
    const size_t    req_arg_num = 2;
    const size_t    max_arg_num = 3;
    size_t          i;
    char           *end;

    bool            dump_descriptor = true;
    bool            dump_stream     = false;
    long            bus_num;
    long            dev_num;
    long            if_num          = -1;

    struct sigaction    sa;

#define USAGE_ERROR(_fmt, _args...) \
    do {                                                \
        fprintf(stderr, _fmt "\n", ##_args);            \
        usage(stderr, program_invocation_short_name);   \
        return 1;                                       \
    } while (0)

    /*
     * Parse command line arguments
     */
    while ((c = getopt_long(argc, argv,
                            short_opt_list, long_opt_list, NULL)) >= 0)
    {
        switch (c)
        {
            case OPT_VAL_HELP:
                usage(stdout, program_invocation_short_name);
                return 0;
                break;
            case OPT_VAL_VERSION:
                version(stdout);
                return 0;
                break;
            case OPT_VAL_ENTITY:
                if (strncmp(optarg, "descriptor", strlen(optarg)) == 0)
                {
                    dump_descriptor = true;
                    dump_stream = false;
                }
                else if (strncmp(optarg, "stream", strlen(optarg)) == 0)
                {
                    dump_descriptor = false;
                    dump_stream = true;
                }
                else if (strncmp(optarg, "all", strlen(optarg)) == 0)
                {
                    dump_descriptor = true;
                    dump_stream = true;
                }
                else
                    USAGE_ERROR("Unknown entity \"%s\"", optarg);

                break;
            case OPT_VAL_STREAM_PAUSED:
                stream_paused = 1;
                break;
            case OPT_VAL_STREAM_FEEDBACK:
                stream_feedback = 1;
                break;
            case '?':
                usage(stderr, program_invocation_short_name);
                return 1;
                break;
        }
    }

    /*
     * Assign positional parameters
     */
    for (i = 0; i < max_arg_num && optind < argc; i++, optind++)
        *arg_list[i] = argv[optind];

    if (i < req_arg_num)
        USAGE_ERROR("Not enough arguments");

    /*
     * Parse and verify positional parameters
     */
    errno = 0;
    bus_num = strtol(bus_str, &end, 0);
    if (errno != 0 || !uhd_strisblank(end) ||
        bus_num <= 0 || bus_num > 255)
        USAGE_ERROR("Invalid bus number \"%s\"", bus_str);

    errno = 0;
    dev_num = strtol(dev_str, &end, 0);
    if (errno != 0 || !uhd_strisblank(end) ||
        dev_num <= 0 || dev_num > 255)
        USAGE_ERROR("Invalid device address \"%s\"", dev_str);

    if (!uhd_strisblank(if_str))
    {
        errno = 0;
        if_num = strtol(if_str, &end, 0);
        if (errno != 0 || !uhd_strisblank(end) ||
            if_num < 0 || if_num >= 255)
            USAGE_ERROR("Invalid interface number \"%s\"", if_str);
    }

    /*
     * Setup signal handlers
     */
    /* Setup SIGINT to terminate gracefully */
    sigaction(SIGINT, NULL, &sa);
    if (sa.sa_handler != SIG_IGN)
    {
        sa.sa_handler = exit_sighandler;
        sigemptyset(&sa.sa_mask);
        sigaddset(&sa.sa_mask, SIGTERM);
        sa.sa_flags = 0;    /* NOTE: no SA_RESTART on purpose */
        sigaction(SIGINT, &sa, NULL);
    }

    /* Setup SIGTERM to terminate gracefully */
    sigaction(SIGTERM, NULL, &sa);
    if (sa.sa_handler != SIG_IGN)
    {
        sa.sa_handler = exit_sighandler;
        sigemptyset(&sa.sa_mask);
        sigaddset(&sa.sa_mask, SIGINT);
        sa.sa_flags = 0;    /* NOTE: no SA_RESTART on purpose */
        sigaction(SIGTERM, &sa, NULL);
    }

    /* Setup SIGUSR1/SIGUSR2 to pause/resume the stream output */
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    sa.sa_handler = stream_pause_sighandler;
    sigaction(SIGUSR1, &sa, NULL);
    sa.sa_handler = stream_resume_sighandler;
    sigaction(SIGUSR2, &sa, NULL);

    /* Make stdout buffered - we will flush it explicitly */
    setbuf(stdout, NULL);

    result = run(dump_descriptor, dump_stream, bus_num, dev_num, if_num);

    /*
     * Restore signal handlers
     */
    sigaction(SIGINT, NULL, &sa);
    if (sa.sa_handler != SIG_IGN)
        signal(SIGINT, SIG_DFL);

    sigaction(SIGTERM, NULL, &sa);
    if (sa.sa_handler != SIG_IGN)
        signal(SIGTERM, SIG_DFL);

    /*
     * Reproduce the signal used to stop the program to get proper exit
     * status.
     */
    if (exit_signum != 0)
        raise(exit_signum);

    return result;
}