summaryrefslogtreecommitdiffstats
path: root/src/VBox/Devices/USB/VUSBSnifferPcapNg.cpp
blob: 5ea6a592e1f773609bb4c3a2487f0e5f2a7b3918 (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
/* $Id: VUSBSnifferPcapNg.cpp $ */
/** @file
 * Virtual USB Sniffer facility - PCAP-NG format writer.
 */

/*
 * Copyright (C) 2014-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program 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, in version 3 of the
 * License.
 *
 * This program 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 this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_DRV_VUSB
#include <VBox/log.h>
#include <iprt/buildconfig.h>
#include <iprt/errcore.h>
#include <iprt/mem.h>
#include <iprt/string.h>
#include <iprt/system.h>
#include <iprt/time.h>

#include "VUSBSnifferInternal.h"


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/

/** DumpFile Section Header Block type. */
#define DUMPFILE_SHB_BLOCK_TYPE       UINT32_C(0x0a0d0d0a)
/** The byte order magic value. */
#define DUMPFILE_SHB_BYTE_ORDER_MAGIC UINT32_C(0x1a2b3c4d)
/** Current major version. */
#define DUMPFILE_SHB_VERSION_MAJOR    UINT16_C(1)
/** Current minor version. */
#define DUMPFILE_SHB_VERSION_MINOR    UINT16_C(0)

/** Block type for the interface descriptor block. */
#define DUMPFILE_IDB_BLOCK_TYPE       UINT32_C(0x00000001)
/** USB link type. */
#define DUMPFILE_IDB_LINK_TYPE_USB_LINUX        UINT16_C(189)
#define DUMPFILE_IDB_LINK_TYPE_USB_LINUX_MMAPED UINT16_C(220)

/** Block type for an enhanced packet block. */
#define DUMPFILE_EPB_BLOCK_TYPE       UINT32_C(0x00000006)

/** USB packet event types. */
#define DUMPFILE_USB_EVENT_TYPE_SUBMIT   ('S')
#define DUMPFILE_USB_EVENT_TYPE_COMPLETE ('C')
#define DUMPFILE_USB_EVENT_TYPE_ERROR    ('E')

#define DUMPFILE_OPTION_CODE_END      UINT16_C(0)
#define DUMPFILE_OPTION_CODE_COMMENT  UINT16_C(1)

#define DUMPFILE_OPTION_CODE_HARDWARE UINT16_C(2)
#define DUMPFILE_OPTION_CODE_OS       UINT16_C(3)
#define DUMPFILE_OPTION_CODE_USERAPP  UINT16_C(4)

#define DUMPFILE_IDB_OPTION_TS_RESOLUTION UINT16_C(9)


/*********************************************************************************************************************************
*   DumpFile format structures                                                                                                   *
*********************************************************************************************************************************/

/**
 * DumpFile Block header.
 */
typedef struct DumpFileBlockHdr
{
    /** Block type. */
    uint32_t            u32BlockType;
    /** Block total length. */
    uint32_t            u32BlockTotalLength;
} DumpFileBlockHdr;
/** Pointer to a block header. */
typedef DumpFileBlockHdr *PDumpFileBlockHdr;

/**
 * DumpFile Option header.
 */
typedef struct DumpFileOptionHdr
{
    /** Option code. */
    uint16_t            u16OptionCode;
    /** Block total length. */
    uint16_t            u16OptionLength;
} DumpFileOptionHdr;
/** Pointer to a option header. */
typedef DumpFileOptionHdr *PDumpFileOptionHdr;

/**
 * DumpFile Section Header Block.
 */
typedef struct DumpFileShb
{
    /** Block header. */
    DumpFileBlockHdr    Hdr;
    /** Byte order magic. */
    uint32_t            u32ByteOrderMagic;
    /** Major version. */
    uint16_t            u16VersionMajor;
    /** Minor version. */
    uint16_t            u16VersionMinor;
    /** Section length. */
    uint64_t            u64SectionLength;
} DumpFileShb;
/** Pointer to a Section Header Block. */
typedef DumpFileShb *PDumpFileShb;

/**
 * DumpFile Interface description block.
 */
typedef struct DumpFileIdb
{
    /** Block header. */
    DumpFileBlockHdr    Hdr;
    /** Link type. */
    uint16_t            u16LinkType;
    /** Reserved. */
    uint16_t            u16Reserved;
    /** Maximum number of bytes dumped from each packet. */
    uint32_t            u32SnapLen;
} DumpFileIdb;
/** Pointer to an Interface description block. */
typedef DumpFileIdb *PDumpFileIdb;

/**
 * DumpFile Enhanced packet block.
 */
typedef struct DumpFileEpb
{
    /** Block header. */
    DumpFileBlockHdr    Hdr;
    /** Interface ID. */
    uint32_t            u32InterfaceId;
    /** Timestamp (high). */
    uint32_t            u32TimestampHigh;
    /** Timestamp (low). */
    uint32_t            u32TimestampLow;
    /** Captured packet length. */
    uint32_t            u32CapturedLen;
    /** Original packet length. */
    uint32_t            u32PacketLen;
} DumpFileEpb;
/** Pointer to an Enhanced packet block. */
typedef DumpFileEpb *PDumpFileEpb;

/**
 * USB setup URB data.
 */
typedef struct DumpFileUsbSetup
{
    uint8_t    bmRequestType;
    uint8_t    bRequest;
    uint16_t   wValue;
    uint16_t   wIndex;
    uint16_t   wLength;
} DumpFileUsbSetup;
typedef DumpFileUsbSetup *PDumpFileUsbSetup;

/**
 * USB Isochronous data.
 */
typedef struct DumpFileIsoRec
{
    int32_t    i32ErrorCount;
    int32_t    i32NumDesc;
} DumpFileIsoRec;
typedef DumpFileIsoRec *PDumpFileIsoRec;

/**
 * USB packet header (Linux mmapped variant).
 */
typedef struct DumpFileUsbHeaderLnxMmapped
{
    /** Packet Id. */
    uint64_t    u64Id;
    /** Event type. */
    uint8_t     u8EventType;
    /** Transfer type. */
    uint8_t     u8TransferType;
    /** Endpoint number. */
    uint8_t     u8EndpointNumber;
    /** Device address. */
    uint8_t     u8DeviceAddress;
    /** Bus id. */
    uint16_t    u16BusId;
    /** Setup flag != 0 if the URB setup header is not present. */
    uint8_t     u8SetupFlag;
    /** Data present flag != 0 if the URB data is not present. */
    uint8_t     u8DataFlag;
    /** Timestamp (second part). */
    uint64_t    u64TimestampSec;
    /** Timestamp (us part). */
    uint32_t    u32TimestampUSec;
    /** Status. */
    int32_t     i32Status;
    /** URB length. */
    uint32_t    u32UrbLength;
    /** Recorded data length. */
    uint32_t    u32DataLength;
    /** Union of data for different URB types. */
    union
    {
        DumpFileUsbSetup    UsbSetup;
        DumpFileIsoRec      IsoRec;
    } u;
    int32_t     i32Interval;
    int32_t     i32StartFrame;
    /** Copy of transfer flags. */
    uint32_t    u32XferFlags;
    /** Number of isochronous descriptors. */
    uint32_t    u32NumDesc;
} DumpFileUsbHeaderLnxMmapped;
/** Pointer to a USB packet header. */
typedef DumpFileUsbHeaderLnxMmapped *PDumpFileUsbHeaderLnxMmapped;

AssertCompileSize(DumpFileUsbHeaderLnxMmapped, 64);

/**
 * USB packet isochronous descriptor.
 */
typedef struct DumpFileUsbIsoDesc
{
    int32_t     i32Status;
    uint32_t    u32Offset;
    uint32_t    u32Len;
    uint8_t     au8Padding[4];
} DumpFileUsbIsoDesc;
typedef DumpFileUsbIsoDesc *PDumpFileUsbIsoDesc;


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/

/**
 * The internal VUSB sniffer state.
 */
typedef struct VUSBSNIFFERFMTINT
{
    /** Stream handle. */
    PVUSBSNIFFERSTRM  pStrm;
    /** Current size of the block being written. */
    uint32_t          cbBlockCur;
    /** Maximum size allocated for the block. */
    uint32_t          cbBlockMax;
    /** Current block header. */
    PDumpFileBlockHdr pBlockHdr;
    /** Pointer to the block data which will be written on commit. */
    uint8_t          *pbBlockData;
} VUSBSNIFFERFMTINT;


/*********************************************************************************************************************************
*   Static Variables                                                                                                             *
*********************************************************************************************************************************/

/**
 * Supported file extensions.
 */
static const char *s_apszFileExts[] =
{
    "pcap",
    "pcapng",
    NULL
};


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/

/**
 * Allocates additional space for the block.
 *
 * @returns Pointer to the new unused space or NULL if out of memory.
 * @param   pThis           The VUSB sniffer instance.
 * @param   cbAdditional    The additional memory requested.
 */
static void *vusbSnifferBlockAllocSpace(PVUSBSNIFFERFMTINT pThis, uint32_t cbAdditional)
{
    /* Fast path where we have enough memory allocated. */
    if (pThis->cbBlockCur + cbAdditional <= pThis->cbBlockMax)
    {
        void *pv = pThis->pbBlockData + pThis->cbBlockCur;
        pThis->cbBlockCur += cbAdditional;
        return pv;
    }

    /* Allocate additional memory. */
    uint32_t cbNew = pThis->cbBlockCur + cbAdditional;
    uint8_t *pbDataNew = (uint8_t *)RTMemRealloc(pThis->pbBlockData, cbNew);
    if (pbDataNew)
    {
        pThis->pbBlockData = pbDataNew;
        pThis->pBlockHdr   = (PDumpFileBlockHdr)pbDataNew;

        void *pv = pThis->pbBlockData + pThis->cbBlockCur;
        pThis->cbBlockCur = cbNew;
        pThis->cbBlockMax = cbNew;
        return pv;
    }

    return NULL;
}

/**
 * Adds new data to the current block.
 *
 * @returns VBox status code.
 * @param   pThis           The VUSB sniffer instance.
 * @param   pvData          The data to add.
 * @param   cbData          Amount of data to add.
 */
static int vusbSnifferBlockAddData(PVUSBSNIFFERFMTINT pThis, const void *pvData, uint32_t cbData)
{
    int rc = VINF_SUCCESS;

    Assert(pThis->cbBlockCur);
    AssertPtr(pThis->pBlockHdr);

    void *pv = vusbSnifferBlockAllocSpace(pThis, cbData);
    if (pv)
        memcpy(pv, pvData, cbData);
    else
        rc = VERR_NO_MEMORY;

    return rc;
}

/**
 * Aligns the current block data to a 32bit boundary.
 *
 * @returns VBox status code.
 * @param   pThis           The VUSB sniffer instance.
 */
static int vusbSnifferBlockAlign(PVUSBSNIFFERFMTINT pThis)
{
    int rc = VINF_SUCCESS;

    Assert(pThis->cbBlockCur);

    /* Pad to 32bits. */
    uint8_t abPad[3] = { 0 };
    uint32_t cbPad = RT_ALIGN_32(pThis->cbBlockCur, 4) - pThis->cbBlockCur;

    Assert(cbPad <= 3);
    if (cbPad)
        rc = vusbSnifferBlockAddData(pThis, abPad, cbPad);

    return rc;
}

/**
 * Commits the current block to the capture file.
 *
 * @returns VBox status code.
 * @param   pThis           The VUSB sniffer instance.
 */
static int vusbSnifferBlockCommit(PVUSBSNIFFERFMTINT pThis)
{
    int rc = VINF_SUCCESS;

    AssertPtr(pThis->pBlockHdr);

    rc = vusbSnifferBlockAlign(pThis);
    if (RT_SUCCESS(rc))
    {
        /* Update the block total length field. */
        uint32_t *pcbTotalLength = (uint32_t *)vusbSnifferBlockAllocSpace(pThis, 4);
        if (pcbTotalLength)
        {
            *pcbTotalLength = pThis->cbBlockCur;
            pThis->pBlockHdr->u32BlockTotalLength = pThis->cbBlockCur;

            /* Write the data. */
            rc = pThis->pStrm->pfnWrite(pThis->pStrm, pThis->pbBlockData, pThis->cbBlockCur);
            pThis->cbBlockCur = 0;
            pThis->pBlockHdr  = NULL;
        }
        else
            rc = VERR_NO_MEMORY;
    }

    return rc;
}

/**
 * Starts a new block for capturing.
 *
 * @returns VBox status code.
 * @param   pThis           The VUSB sniffer instance.
 * @param   pBlockHdr       Pointer to the block header for the new block.
 * @param   cbData          Amount of data added with this block.
 */
static int vusbSnifferBlockNew(PVUSBSNIFFERFMTINT pThis, PDumpFileBlockHdr pBlockHdr, uint32_t cbData)
{
    int rc = VINF_SUCCESS;

    /* Validate we don't get called while another block is active. */
    Assert(!pThis->cbBlockCur);
    Assert(!pThis->pBlockHdr);
    pThis->pBlockHdr = (PDumpFileBlockHdr)vusbSnifferBlockAllocSpace(pThis, cbData);
    if (pThis->pBlockHdr)
        memcpy(pThis->pBlockHdr, pBlockHdr, cbData);
    else
        rc = VERR_NO_MEMORY;

    return rc;
}

/**
 * Add a new option to the current block.
 *
 * @returns VBox status code.
 * @param   pThis           The VUSB sniffer instance.
 * @param   u16OptionCode   The option code identifying the type of option.
 * @param   pvOption        Raw data for the option.
 * @param   cbOption        Size of the optiob data.
 */
static int vusbSnifferAddOption(PVUSBSNIFFERFMTINT pThis, uint16_t u16OptionCode, const void *pvOption, size_t cbOption)
{
    AssertStmt((uint16_t)cbOption == cbOption, cbOption = UINT16_MAX);
    DumpFileOptionHdr OptHdr;
    OptHdr.u16OptionCode   = u16OptionCode;
    OptHdr.u16OptionLength = (uint16_t)cbOption;
    int rc = vusbSnifferBlockAddData(pThis, &OptHdr, sizeof(OptHdr));
    if (   RT_SUCCESS(rc)
        && u16OptionCode != DUMPFILE_OPTION_CODE_END
        && cbOption != 0)
    {
        rc = vusbSnifferBlockAddData(pThis, pvOption, (uint16_t)cbOption);
        if (RT_SUCCESS(rc))
            rc = vusbSnifferBlockAlign(pThis);
    }

    return rc;
}


/** @interface_method_impl{VUSBSNIFFERFMT,pfnInit} */
static DECLCALLBACK(int) vusbSnifferFmtPcapNgInit(PVUSBSNIFFERFMTINT pThis, PVUSBSNIFFERSTRM pStrm)
{
    pThis->pStrm       = pStrm;
    pThis->cbBlockCur  = 0;
    pThis->cbBlockMax  = 0;
    pThis->pbBlockData = NULL;

    /* Write header and link type blocks. */
    DumpFileShb Shb;

    Shb.Hdr.u32BlockType        = DUMPFILE_SHB_BLOCK_TYPE;
    Shb.Hdr.u32BlockTotalLength = 0; /* Filled out by lower layer. */
    Shb.u32ByteOrderMagic       = DUMPFILE_SHB_BYTE_ORDER_MAGIC;
    Shb.u16VersionMajor         = DUMPFILE_SHB_VERSION_MAJOR;
    Shb.u16VersionMinor         = DUMPFILE_SHB_VERSION_MINOR;
    Shb.u64SectionLength        = UINT64_C(0xffffffffffffffff); /* -1 */

    /* Write the blocks. */
    int rc = vusbSnifferBlockNew(pThis, &Shb.Hdr, sizeof(Shb));
    if (RT_SUCCESS(rc))
    {
        const char *pszOpt = RTBldCfgTargetDotArch();
        rc = vusbSnifferAddOption(pThis, DUMPFILE_OPTION_CODE_HARDWARE, pszOpt, strlen(pszOpt) + 1);
    }

    if (RT_SUCCESS(rc))
    {
        char szTmp[512];
        size_t cbTmp = sizeof(szTmp);

        RT_ZERO(szTmp);

        /* Build the OS code. */
        rc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, cbTmp);
        if (RT_SUCCESS(rc))
        {
            size_t cb = strlen(szTmp);

            szTmp[cb] = ' ';
            rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, &szTmp[cb + 1], cbTmp - (cb + 1));
            if (RT_SUCCESS(rc))
            {
                cb = strlen(szTmp);
                szTmp[cb] = ' ';
                rc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, &szTmp[cb + 1], cbTmp - (cb + 1));
            }
        }

        if (RT_SUCCESS(rc) || rc == VERR_BUFFER_OVERFLOW)
            rc = vusbSnifferAddOption(pThis, DUMPFILE_OPTION_CODE_OS, szTmp, strlen(szTmp) + 1);
        else
            rc = VINF_SUCCESS; /* Skip OS code if building the string failed. */
    }

    if (RT_SUCCESS(rc))
    {
        /** @todo Add product info. */
    }

    if (RT_SUCCESS(rc))
        rc = vusbSnifferAddOption(pThis, DUMPFILE_OPTION_CODE_END, NULL, 0);
    if (RT_SUCCESS(rc))
        rc = vusbSnifferBlockCommit(pThis);

    /* Write Interface descriptor block. */
    if (RT_SUCCESS(rc))
    {
        DumpFileIdb Idb;

        Idb.Hdr.u32BlockType        = DUMPFILE_IDB_BLOCK_TYPE;
        Idb.Hdr.u32BlockTotalLength = 0; /* Filled out by lower layer. */
        Idb.u16LinkType             = DUMPFILE_IDB_LINK_TYPE_USB_LINUX_MMAPED;
        Idb.u16Reserved             = 0;
        Idb.u32SnapLen              = UINT32_C(0xffffffff);

        rc = vusbSnifferBlockNew(pThis, &Idb.Hdr, sizeof(Idb));
        if (RT_SUCCESS(rc))
        {
            uint8_t u8TsResolution = 9; /* Nano second resolution. */
            /* Add timestamp resolution option. */
            rc = vusbSnifferAddOption(pThis, DUMPFILE_IDB_OPTION_TS_RESOLUTION,
                                      &u8TsResolution, sizeof(u8TsResolution));
        }
        if (RT_SUCCESS(rc))
            rc = vusbSnifferAddOption(pThis, DUMPFILE_OPTION_CODE_END, NULL, 0);
        if (RT_SUCCESS(rc))
            rc = vusbSnifferBlockCommit(pThis);
    }

    if (   RT_FAILURE(rc)
        && pThis->pbBlockData)
        RTMemFree(pThis->pbBlockData);

    return rc;
}


/** @interface_method_impl{VUSBSNIFFERFMT,pfnDestroy} */
static DECLCALLBACK(void) vusbSnifferFmtPcapNgDestroy(PVUSBSNIFFERFMTINT pThis)
{
    if (pThis->pbBlockData)
        RTMemFree(pThis->pbBlockData);
}


/** @interface_method_impl{VUSBSNIFFERFMT,pfnRecordEvent} */
static DECLCALLBACK(int) vusbSnifferFmtPcapNgRecordEvent(PVUSBSNIFFERFMTINT pThis, PVUSBURB pUrb, VUSBSNIFFEREVENT enmEvent)
{
    DumpFileEpb Epb;
    DumpFileUsbHeaderLnxMmapped UsbHdr;
    uint32_t cbCapturedLength = sizeof(UsbHdr);
    uint8_t *pbData = NULL;

    RTTIMESPEC TimeNow;
    RTTimeNow(&TimeNow);
    uint64_t u64TimestampEvent = RTTimeSpecGetNano(&TimeNow);

    /* Start with the enhanced packet block. */
    Epb.Hdr.u32BlockType        = DUMPFILE_EPB_BLOCK_TYPE;
    Epb.Hdr.u32BlockTotalLength = 0;
    Epb.u32InterfaceId          = 0;
    Epb.u32TimestampHigh        = (u64TimestampEvent >> 32) & UINT32_C(0xffffffff);
    Epb.u32TimestampLow         = u64TimestampEvent & UINT32_C(0xffffffff);

    UsbHdr.u64Id = (uintptr_t)pUrb; /** @todo check whether the pointer is a good ID. */
    uint32_t cbUrbLength;
    switch (enmEvent)
    {
        case VUSBSNIFFEREVENT_SUBMIT:
            UsbHdr.u8EventType = DUMPFILE_USB_EVENT_TYPE_SUBMIT;
            cbUrbLength = pUrb->cbData;
            break;
        case VUSBSNIFFEREVENT_COMPLETE:
            UsbHdr.u8EventType = DUMPFILE_USB_EVENT_TYPE_COMPLETE;
            cbUrbLength = pUrb->cbData;
            break;
        case VUSBSNIFFEREVENT_ERROR_SUBMIT:
        case VUSBSNIFFEREVENT_ERROR_COMPLETE:
            UsbHdr.u8EventType = DUMPFILE_USB_EVENT_TYPE_ERROR;
            cbUrbLength = 0;
            break;
        default:
            AssertMsgFailed(("Invalid event type %d\n", enmEvent));
            cbUrbLength = 0;
    }
    uint32_t cbDataLength = cbUrbLength;
    pbData = &pUrb->abData[0];

    uint32_t cIsocPkts = 0;
    switch (pUrb->enmType)
    {
        case VUSBXFERTYPE_ISOC:
        {
            int32_t cErrors = 0;

            UsbHdr.u8TransferType = 0;
            cIsocPkts = pUrb->cIsocPkts;
            for (unsigned i = 0; i < cIsocPkts; i++)
                if (   pUrb->aIsocPkts[i].enmStatus != VUSBSTATUS_OK
                    && pUrb->aIsocPkts[i].enmStatus != VUSBSTATUS_NOT_ACCESSED)
                    cErrors++;

            UsbHdr.u.IsoRec.i32ErrorCount = cErrors;
            UsbHdr.u.IsoRec.i32NumDesc    = pUrb->cIsocPkts;
            cbCapturedLength += cIsocPkts * sizeof(DumpFileUsbIsoDesc);
            break;
        }
        case VUSBXFERTYPE_BULK:
            UsbHdr.u8TransferType = 3;
            break;
        case VUSBXFERTYPE_INTR:
            UsbHdr.u8TransferType = 1;
            break;
        case VUSBXFERTYPE_CTRL:
        case VUSBXFERTYPE_MSG:
            UsbHdr.u8TransferType = 2;
            break;
        default:
            AssertMsgFailed(("invalid transfer type %d\n", pUrb->enmType));
    }

    if (pUrb->enmDir == VUSBDIRECTION_IN)
    {
        if (enmEvent == VUSBSNIFFEREVENT_SUBMIT)
            cbDataLength = 0;
    }
    else if (pUrb->enmDir == VUSBDIRECTION_OUT)
    {
        if (   enmEvent == VUSBSNIFFEREVENT_COMPLETE
            || pUrb->enmType == VUSBXFERTYPE_CTRL
            || pUrb->enmType == VUSBXFERTYPE_MSG)
            cbDataLength = 0;
    }
    else if (   pUrb->enmDir == VUSBDIRECTION_SETUP
             && cbDataLength >= sizeof(VUSBSETUP))
        cbDataLength -= sizeof(VUSBSETUP);

    Epb.u32CapturedLen = cbCapturedLength + cbDataLength;
    Epb.u32PacketLen   = cbCapturedLength + cbUrbLength;

    UsbHdr.u8EndpointNumber = pUrb->EndPt | (pUrb->enmDir == VUSBDIRECTION_IN ? 0x80 : 0x00);
    UsbHdr.u8DeviceAddress  = pUrb->DstAddress;
    UsbHdr.u16BusId         = 0;
    UsbHdr.u8DataFlag       = cbDataLength ? 0 : 1;
    UsbHdr.u64TimestampSec  = u64TimestampEvent / RT_NS_1SEC_64;
    UsbHdr.u32TimestampUSec = u64TimestampEvent / RT_NS_1US_64 - UsbHdr.u64TimestampSec * RT_US_1SEC;
    UsbHdr.i32Status        = pUrb->enmStatus;
    UsbHdr.u32UrbLength     = cbUrbLength;
    UsbHdr.u32DataLength    = cbDataLength + cIsocPkts * sizeof(DumpFileUsbIsoDesc);
    UsbHdr.i32Interval      = 0;
    UsbHdr.i32StartFrame    = 0;
    UsbHdr.u32XferFlags     = 0;
    UsbHdr.u32NumDesc       = cIsocPkts;

    if (   (pUrb->enmType == VUSBXFERTYPE_MSG || pUrb->enmType == VUSBXFERTYPE_CTRL)
        && enmEvent == VUSBSNIFFEREVENT_SUBMIT)
    {
        PVUSBSETUP pSetup = (PVUSBSETUP)pUrb->abData;

        UsbHdr.u.UsbSetup.bmRequestType = pSetup->bmRequestType;
        UsbHdr.u.UsbSetup.bRequest      = pSetup->bRequest;
        UsbHdr.u.UsbSetup.wValue        = pSetup->wValue;
        UsbHdr.u.UsbSetup.wIndex        = pSetup->wIndex;
        UsbHdr.u.UsbSetup.wLength       = pSetup->wLength;
        UsbHdr.u8SetupFlag              = 0;
    }
    else
        UsbHdr.u8SetupFlag  = '-'; /* Follow usbmon source here. */

    /* Write the packet to the capture file. */
    int rc = vusbSnifferBlockNew(pThis, &Epb.Hdr, sizeof(Epb));
    if (RT_SUCCESS(rc))
        rc = vusbSnifferBlockAddData(pThis, &UsbHdr, sizeof(UsbHdr));

    /* Add Isochronous descriptors now. */
    for (unsigned i = 0; i < cIsocPkts && RT_SUCCESS(rc); i++)
    {
        DumpFileUsbIsoDesc IsoDesc;
        IsoDesc.i32Status = pUrb->aIsocPkts[i].enmStatus;
        IsoDesc.u32Offset = pUrb->aIsocPkts[i].off;
        IsoDesc.u32Len    = pUrb->aIsocPkts[i].cb;
        rc = vusbSnifferBlockAddData(pThis, &IsoDesc, sizeof(IsoDesc));
    }

    /* Record data. */
    if (   RT_SUCCESS(rc)
        && cbDataLength)
        rc = vusbSnifferBlockAddData(pThis, pbData, cbDataLength);

    if (RT_SUCCESS(rc))
        rc = vusbSnifferAddOption(pThis, DUMPFILE_OPTION_CODE_END, NULL, 0);

    if (RT_SUCCESS(rc))
        rc = vusbSnifferBlockCommit(pThis);

    return rc;
}

/**
 * VUSB sniffer format writer.
 */
const VUSBSNIFFERFMT g_VUsbSnifferFmtPcapNg =
{
    /** szName */
    "PCAPNG",
    /** pszDesc */
    "PCAP-NG format writer compatible with WireShark",
    /** papszFileExts */
    &s_apszFileExts[0],
    /** cbFmt */
    sizeof(VUSBSNIFFERFMTINT),
    /** pfnInit */
    vusbSnifferFmtPcapNgInit,
    /** pfnDestroy */
    vusbSnifferFmtPcapNgDestroy,
    /** pfnRecordEvent */
    vusbSnifferFmtPcapNgRecordEvent
};