-
Notifications
You must be signed in to change notification settings - Fork 862
/
pcap-npf.c
2471 lines (2239 loc) · 64.2 KB
/
pcap-npf.c
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
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2010 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <config.h>
#include <errno.h>
#include <limits.h> /* for INT_MAX */
#define PCAP_DONT_INCLUDE_PCAP_BPF_H
#include <Packet32.h>
#include <pcap-int.h>
#include <pcap/dlt.h>
/*
* XXX - Packet32.h defines bpf_program, so we can't include
* <pcap/bpf.h>, which also defines it; that's why we define
* PCAP_DONT_INCLUDE_PCAP_BPF_H,
*
* However, no header in the WinPcap or Npcap SDKs defines the
* macros for BPF code, so we have to define them ourselves.
*/
#define BPF_RET 0x06
#define BPF_K 0x00
/* Old-school MinGW have these headers in a different place.
*/
#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
#include <ddk/ntddndis.h>
#include <ddk/ndis.h>
#else
#include <ntddndis.h> /* MSVC/TDM-MinGW/MinGW64 */
#endif
#include "diag-control.h"
static int pcap_setfilter_npf(pcap_t *, struct bpf_program *);
static int pcap_setfilter_win32_dag(pcap_t *, struct bpf_program *);
static int pcap_getnonblock_npf(pcap_t *);
static int pcap_setnonblock_npf(pcap_t *, int);
/*dimension of the buffer in the pcap_t structure*/
#define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
/*dimension of the buffer in the kernel driver NPF */
#define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
/* Equivalent to ntohs(), but a lot faster under Windows */
#define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
/*
* Private data for capturing on WinPcap/Npcap devices.
*/
struct pcap_win {
ADAPTER *adapter; /* the packet32 ADAPTER for the device */
int nonblock;
int rfmon_selfstart; /* a flag tells whether the monitor mode is set by itself */
int filtering_in_kernel; /* using kernel filter */
#ifdef ENABLE_REMOTE
int samp_npkt; /* parameter needed for sampling, with '1 out of N' method has been requested */
struct timeval samp_time; /* parameter needed for sampling, with '1 every N ms' method has been requested */
#endif
};
/*
* Define stub versions of the monitor-mode support routines if this
* isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
* WinPcap.
*/
#ifndef HAVE_NPCAP_PACKET_API
static int
PacketIsMonitorModeSupported(PCHAR AdapterName _U_)
{
/*
* We don't support monitor mode.
*/
return (0);
}
static int
PacketSetMonitorMode(PCHAR AdapterName _U_, int mode _U_)
{
/*
* This should never be called, as PacketIsMonitorModeSupported()
* will return 0, meaning "we don't support monitor mode, so
* don't try to turn it on or off".
*/
return (0);
}
static int
PacketGetMonitorMode(PCHAR AdapterName _U_)
{
/*
* This should fail, so that pcap_activate_npf() returns
* PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
* mode.
*/
return (-1);
}
#endif
/*
* If a driver returns an NTSTATUS value:
*
* https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/87fba13e-bf06-450e-83b1-9241dc81e781
*
* with the "Customer" bit set, it will not be mapped to a Windows error
* value in userland, so it will be returned by GetLastError().
*
* Note that "driver" here includes the Npcap NPF driver, as various
* versions would take NT status values and set the "Customer" bit
* before returning the status code. The commit message for the
* change that started doing that is
*
* Returned a customer-defined NTSTATUS in OID requests to avoid
* NTSTATUS-to-Win32 Error code translation.
*
* but I don't know why the goal was to avoid that translation. For
* a while, I suspected that the NT status STATUS_NOT_SUPPORTED was
* getting mapped to ERROR_GEN_FAILURE, but, in the cases where
* attempts to set promiscuous mode on regular Ethernet devices were
* failing with ERROR_GEN_FAILURE, it turns out that the drivers for
* those devices were NetAdapterCx drivers, and Microsoft's NetAdapterCx
* mechanism wasn't providing the correct "bytes processed" value on
* attempts to set OIDs, and the Npcap NPF driver was checking for
* that and returning STATUS_UNSUCCESSFUL, which gets mapped to
* ERROR_GEN_FAILURE, so perhaps there's no need to avoid that
* translation.
*
* Attempting to set the hardware filter on a Microsoft Surface Pro's
* Mobile Broadband Adapter returns an error that appears to be
* NDIS_STATUS_NOT_SUPPORTED ORed with the "Customer" bit, so it's
* probably indicating that it doesn't support that. It was probably
* the NPF driver setting that bit.
*/
#define NT_STATUS_CUSTOMER_DEFINED 0x20000000
/*
* PacketRequest() makes a DeviceIoControl() call to the NPF driver to
* perform the OID request, with a BIOCQUERYOID ioctl. The kernel code
* should get back one of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
* or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't supported by
* the OS or the driver.
*
* Currently, that code may be returned by the Npcap NPF driver with the
* NT_STATUS_CUSTOMER_DEFINED bit. That prevents the return status from
* being mapped to a Windows error code; if the NPF driver were to stop
* ORing in the NT_STATUS_CUSTOMER_DEFINED bit, it's not obvious how those
* the NDIS_STATUS_ values that don't correspond to NTSTATUS values would
* be translated to Windows error values (NDIS_STATUS_NOT_SUPPORTED is
* the same as STATUS_NOT_SUPPORTED, which is an NTSTATUS value that is
* mapped to ERROR_NOT_SUPPORTED).
*/
#define NDIS_STATUS_INVALID_OID 0xc0010017
#define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
#define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
static int
oid_get_request(ADAPTER *adapter, bpf_u_int32 oid, void *data, size_t *lenp,
char *errbuf)
{
PACKET_OID_DATA *oid_data_arg;
/*
* Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
* It should be big enough to hold "*lenp" bytes of data; it
* will actually be slightly larger, as PACKET_OID_DATA has a
* 1-byte data array at the end, standing in for the variable-length
* data that's actually there.
*/
oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
if (oid_data_arg == NULL) {
snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Couldn't allocate argument buffer for PacketRequest");
return (PCAP_ERROR);
}
/*
* No need to copy the data - we're doing a fetch.
*/
oid_data_arg->Oid = oid;
oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
if (!PacketRequest(adapter, FALSE, oid_data_arg)) {
pcapint_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "Error calling PacketRequest");
free(oid_data_arg);
return (-1);
}
/*
* Get the length actually supplied.
*/
*lenp = oid_data_arg->Length;
/*
* Copy back the data we fetched.
*/
memcpy(data, oid_data_arg->Data, *lenp);
free(oid_data_arg);
return (0);
}
static int
pcap_stats_npf(pcap_t *p, struct pcap_stat *ps)
{
struct pcap_win *pw = p->priv;
struct bpf_stat bstats;
/*
* Try to get statistics.
*
* (Please note - "struct pcap_stat" is *not* the same as
* WinPcap's "struct bpf_stat". It might currently have the
* same layout, but let's not cheat.
*
* Note also that we don't fill in ps_capt, as we might have
* been called by code compiled against an earlier version of
* WinPcap that didn't have ps_capt, in which case filling it
* in would stomp on whatever comes after the structure passed
* to us.
*/
if (!PacketGetStats(pw->adapter, &bstats)) {
pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "PacketGetStats error");
return (-1);
}
ps->ps_recv = bstats.bs_recv;
ps->ps_drop = bstats.bs_drop;
/*
* XXX - PacketGetStats() doesn't fill this in, so we just
* return 0.
*/
#if 0
ps->ps_ifdrop = bstats.ps_ifdrop;
#else
ps->ps_ifdrop = 0;
#endif
return (0);
}
/*
* Win32-only routine for getting statistics.
*
* This way is definitely safer than passing the pcap_stat * from the userland.
* In fact, there could happen than the user allocates a variable which is not
* big enough for the new structure, and the library will write in a zone
* which is not allocated to this variable.
*
* In this way, we're pretty sure we are writing on memory allocated to this
* variable.
*
* XXX - but this is the wrong way to handle statistics. Instead, we should
* have an API that returns data in a form like the Options section of a
* pcapng Interface Statistics Block:
*
* https://xml2rfc.tools.ietf.org/cgi-bin/xml2rfc.cgi?url=https://raw.githubusercontent.com/pcapng/pcapng/master/draft-tuexen-opsawg-pcapng.xml&modeAsFormat=html/ascii&type=ascii#rfc.section.4.6
*
* which would let us add new statistics straightforwardly and indicate which
* statistics we are and are *not* providing, rather than having to provide
* possibly-bogus values for statistics we can't provide.
*/
static struct pcap_stat *
pcap_stats_ex_npf(pcap_t *p, int *pcap_stat_size)
{
struct pcap_win *pw = p->priv;
struct bpf_stat bstats;
*pcap_stat_size = sizeof (p->stat);
/*
* Try to get statistics.
*
* (Please note - "struct pcap_stat" is *not* the same as
* WinPcap's "struct bpf_stat". It might currently have the
* same layout, but let's not cheat.)
*/
if (!PacketGetStatsEx(pw->adapter, &bstats)) {
pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "PacketGetStatsEx error");
return (NULL);
}
p->stat.ps_recv = bstats.bs_recv;
p->stat.ps_drop = bstats.bs_drop;
p->stat.ps_ifdrop = bstats.ps_ifdrop;
/*
* Just in case this is ever compiled for a target other than
* Windows, which is somewhere between extremely unlikely and
* impossible.
*/
#ifdef _WIN32
p->stat.ps_capt = bstats.bs_capt;
#endif
return (&p->stat);
}
/* Set the dimension of the kernel-level capture buffer */
static int
pcap_setbuff_npf(pcap_t *p, int dim)
{
struct pcap_win *pw = p->priv;
if(PacketSetBuff(pw->adapter,dim)==FALSE)
{
snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
return (-1);
}
return (0);
}
/* Set the driver working mode */
static int
pcap_setmode_npf(pcap_t *p, int mode)
{
struct pcap_win *pw = p->priv;
if(PacketSetMode(pw->adapter,mode)==FALSE)
{
snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
return (-1);
}
return (0);
}
/*set the minimum amount of data that will release a read call*/
static int
pcap_setmintocopy_npf(pcap_t *p, int size)
{
struct pcap_win *pw = p->priv;
if(PacketSetMinToCopy(pw->adapter, size)==FALSE)
{
snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
return (-1);
}
return (0);
}
static HANDLE
pcap_getevent_npf(pcap_t *p)
{
struct pcap_win *pw = p->priv;
return (PacketGetReadEvent(pw->adapter));
}
static int
pcap_oid_get_request_npf(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
{
struct pcap_win *pw = p->priv;
return (oid_get_request(pw->adapter, oid, data, lenp, p->errbuf));
}
static int
pcap_oid_set_request_npf(pcap_t *p, bpf_u_int32 oid, const void *data,
size_t *lenp)
{
struct pcap_win *pw = p->priv;
PACKET_OID_DATA *oid_data_arg;
/*
* Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
* It should be big enough to hold "*lenp" bytes of data; it
* will actually be slightly larger, as PACKET_OID_DATA has a
* 1-byte data array at the end, standing in for the variable-length
* data that's actually there.
*/
oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
if (oid_data_arg == NULL) {
snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Couldn't allocate argument buffer for PacketRequest");
return (PCAP_ERROR);
}
oid_data_arg->Oid = oid;
oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
memcpy(oid_data_arg->Data, data, *lenp);
if (!PacketRequest(pw->adapter, TRUE, oid_data_arg)) {
pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "Error calling PacketRequest");
free(oid_data_arg);
return (PCAP_ERROR);
}
/*
* Get the length actually copied.
*/
*lenp = oid_data_arg->Length;
/*
* No need to copy the data - we're doing a set.
*/
free(oid_data_arg);
return (0);
}
static u_int
pcap_sendqueue_transmit_npf(pcap_t *p, pcap_send_queue *queue, int sync)
{
struct pcap_win *pw = p->priv;
u_int res;
res = PacketSendPackets(pw->adapter,
queue->buffer,
queue->len,
(BOOLEAN)sync);
if(res != queue->len){
pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "Error queueing packets");
}
return (res);
}
static int
pcap_setuserbuffer_npf(pcap_t *p, int size)
{
unsigned char *new_buff;
if (size<=0) {
/* Bogus parameter */
snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Error: invalid size %d",size);
return (-1);
}
/* Allocate the buffer */
new_buff=(unsigned char*)malloc(sizeof(char)*size);
if (!new_buff) {
snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Error: not enough memory");
return (-1);
}
free(p->buffer);
p->buffer=new_buff;
p->bufsize=size;
return (0);
}
#ifdef HAVE_NPCAP_PACKET_API
/*
* Kernel dump mode isn't supported in Npcap; calls to PacketSetDumpName(),
* PacketSetDumpLimits(), and PacketIsDumpEnded() will get compile-time
* deprecation warnings.
*
* Avoid calling them; just return errors indicating that kernel dump
* mode isn't supported in Npcap.
*/
static int
pcap_live_dump_npf(pcap_t *p, char *filename _U_, int maxsize _U_,
int maxpacks _U_)
{
snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Npcap doesn't support kernel dump mode");
return (-1);
}
static int
pcap_live_dump_ended_npf(pcap_t *p, int sync)
{
snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Npcap doesn't support kernel dump mode");
return (-1);
}
#else /* HAVE_NPCAP_PACKET_API */
static int
pcap_live_dump_npf(pcap_t *p, char *filename, int maxsize, int maxpacks)
{
struct pcap_win *pw = p->priv;
BOOLEAN res;
/* Set the packet driver in dump mode */
res = PacketSetMode(pw->adapter, PACKET_MODE_DUMP);
if(res == FALSE){
snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Error setting dump mode");
return (-1);
}
/* Set the name of the dump file */
res = PacketSetDumpName(pw->adapter, filename, (int)strlen(filename));
if(res == FALSE){
snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Error setting kernel dump file name");
return (-1);
}
/* Set the limits of the dump file */
res = PacketSetDumpLimits(pw->adapter, maxsize, maxpacks);
if(res == FALSE) {
snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Error setting dump limit");
return (-1);
}
return (0);
}
static int
pcap_live_dump_ended_npf(pcap_t *p, int sync)
{
struct pcap_win *pw = p->priv;
return (PacketIsDumpEnded(pw->adapter, (BOOLEAN)sync));
}
#endif /* HAVE_NPCAP_PACKET_API */
static int
pcap_read_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
PACKET Packet;
u_int cc;
int n;
register u_char *bp, *ep;
u_char *datap;
struct pcap_win *pw = p->priv;
cc = p->cc;
if (cc == 0) {
/*
* Has "pcap_breakloop()" been called?
*/
if (p->break_loop) {
/*
* Yes - clear the flag that indicates that it
* has, and return PCAP_ERROR_BREAK to indicate
* that we were told to break out of the loop.
*/
p->break_loop = 0;
return (PCAP_ERROR_BREAK);
}
/*
* Capture the packets.
*
* The PACKET structure had a bunch of extra stuff for
* Windows 9x/Me, but the only interesting data in it
* in the versions of Windows that we support is just
* a copy of p->buffer, a copy of p->buflen, and the
* actual number of bytes read returned from
* PacketReceivePacket(), none of which has to be
* retained from call to call, so we just keep one on
* the stack.
*/
PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
/*
* Did the device go away?
* If so, the error we get can either be
* ERROR_GEN_FAILURE or ERROR_DEVICE_REMOVED.
*/
DWORD errcode = GetLastError();
if (errcode == ERROR_GEN_FAILURE ||
errcode == ERROR_DEVICE_REMOVED) {
/*
* The device on which we're capturing
* went away, or it became unusable
* by NPF due to a suspend/resume.
*
* ERROR_GEN_FAILURE comes from
* STATUS_UNSUCCESSFUL, as well as some
* other NT status codes that the Npcap
* driver is unlikely to return.
* XXX - hopefully no other error
* conditions are indicated by this.
*
* ERROR_DEVICE_REMOVED comes from
* STATUS_DEVICE_REMOVED.
*
* We report the Windows status code
* name and the corresponding NT status
* code name, for the benefit of attempts
* to debug cases where this error is
* reported when the device *wasn't*
* removed, either because it's not
* removable, it's removable but wasn't
* removed, or it's a device that doesn't
* correspond to a physical device.
*
* XXX - we really should return an
* appropriate error for that, but
* pcap_dispatch() etc. aren't
* documented as having error returns
* other than PCAP_ERROR or PCAP_ERROR_BREAK.
*/
const char *errcode_msg;
if (errcode == ERROR_GEN_FAILURE)
errcode_msg = "ERROR_GEN_FAILURE/STATUS_UNSUCCESSFUL";
else
errcode_msg = "ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED";
snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"The interface disappeared (error code %s)",
errcode_msg);
} else {
pcapint_fmt_errmsg_for_win32_err(p->errbuf,
PCAP_ERRBUF_SIZE, errcode,
"PacketReceivePacket error");
}
return (PCAP_ERROR);
}
cc = Packet.ulBytesReceived;
bp = p->buffer;
}
else
bp = p->bp;
/*
* Loop through each packet.
*
* This assumes that a single buffer of packets will have
* <= INT_MAX packets, so the packet count doesn't overflow.
*/
#define bhp ((struct bpf_hdr *)bp)
n = 0;
ep = bp + cc;
for (;;) {
register u_int caplen, hdrlen;
size_t packet_bytes;
/*
* Has "pcap_breakloop()" been called?
* If so, return immediately - if we haven't read any
* packets, clear the flag and return PCAP_ERROR_BREAK
* to indicate that we were told to break out of the loop,
* otherwise leave the flag set, so that the *next* call
* will break out of the loop without having read any
* packets, and return the number of packets we've
* processed so far.
*/
if (p->break_loop) {
if (n == 0) {
p->break_loop = 0;
return (PCAP_ERROR_BREAK);
} else {
p->bp = bp;
p->cc = (u_int) (ep - bp);
return (n);
}
}
if (bp >= ep)
break;
caplen = bhp->bh_caplen;
hdrlen = bhp->bh_hdrlen;
datap = bp + hdrlen;
/*
* Compute the number of bytes for this packet in
* the buffer.
*
* That's the sum of the header length and the packet
* data length plus, if this is not the last packet,
* the padding required to align the next packet on
* the appropriate boundary.
*
* That means that it should be the minimum of the
* number of bytes left in the buffer and the
* rounded-up sum of the header and packet data lengths.
*/
packet_bytes = min((u_int)(ep - bp), Packet_WORDALIGN(caplen + hdrlen));
/*
* Short-circuit evaluation: if using BPF filter
* in kernel, no need to do it now - we already know
* the packet passed the filter.
*
* XXX - pcapint_filter() should always return TRUE if
* handed a null pointer for the program, but it might
* just try to "run" the filter, so we check here.
*/
if (pw->filtering_in_kernel ||
p->fcode.bf_insns == NULL ||
pcapint_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
#ifdef ENABLE_REMOTE
switch (p->rmt_samp.method) {
case PCAP_SAMP_1_EVERY_N:
pw->samp_npkt = (pw->samp_npkt + 1) % p->rmt_samp.value;
/* Discard all packets that are not '1 out of N' */
if (pw->samp_npkt != 0) {
bp += packet_bytes;
continue;
}
break;
case PCAP_SAMP_FIRST_AFTER_N_MS:
{
struct pcap_pkthdr *pkt_header = (struct pcap_pkthdr*) bp;
/*
* Check if the timestamp of the arrived
* packet is smaller than our target time.
*/
if (pkt_header->ts.tv_sec < pw->samp_time.tv_sec ||
(pkt_header->ts.tv_sec == pw->samp_time.tv_sec && pkt_header->ts.tv_usec < pw->samp_time.tv_usec)) {
bp += packet_bytes;
continue;
}
/*
* The arrived packet is suitable for being
* delivered to our caller, so let's update
* the target time.
*/
pw->samp_time.tv_usec = pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
if (pw->samp_time.tv_usec > 1000000) {
pw->samp_time.tv_sec = pkt_header->ts.tv_sec + pw->samp_time.tv_usec / 1000000;
pw->samp_time.tv_usec = pw->samp_time.tv_usec % 1000000;
}
}
}
#endif /* ENABLE_REMOTE */
/*
* XXX A bpf_hdr matches a pcap_pkthdr.
*/
(*callback)(user, (struct pcap_pkthdr*)bp, datap);
bp += packet_bytes;
if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
p->bp = bp;
p->cc = (u_int) (ep - bp);
return (n);
}
} else {
/*
* Skip this packet.
*/
bp += packet_bytes;
}
}
#undef bhp
p->cc = 0;
return (n);
}
/* Send a packet to the network */
static int
pcap_inject_npf(pcap_t *p, const void *buf, int size)
{
struct pcap_win *pw = p->priv;
PACKET pkt;
PacketInitPacket(&pkt, (PVOID)buf, size);
if(PacketSendPacket(pw->adapter,&pkt,TRUE) == FALSE) {
pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "send error: PacketSendPacket failed");
return (-1);
}
/*
* We assume it all got sent if "PacketSendPacket()" succeeded.
* "pcap_inject()" is expected to return the number of bytes
* sent.
*/
return (size);
}
static void
pcap_cleanup_npf(pcap_t *p)
{
struct pcap_win *pw = p->priv;
if (pw->adapter != NULL) {
PacketCloseAdapter(pw->adapter);
pw->adapter = NULL;
}
if (pw->rfmon_selfstart)
{
PacketSetMonitorMode(p->opt.device, 0);
}
pcapint_cleanup_live_common(p);
}
static void
pcap_breakloop_npf(pcap_t *p)
{
pcapint_breakloop_common(p);
struct pcap_win *pw = p->priv;
/* XXX - what if this fails? */
SetEvent(PacketGetReadEvent(pw->adapter));
}
static int
pcap_activate_npf(pcap_t *p)
{
struct pcap_win *pw = p->priv;
NetType type;
int res;
int status = 0;
struct bpf_insn total_insn;
struct bpf_program total_prog;
if (p->opt.rfmon) {
/*
* Monitor mode is supported on Windows Vista and later.
*/
if (PacketGetMonitorMode(p->opt.device) == 1)
{
pw->rfmon_selfstart = 0;
}
else
{
if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
{
pw->rfmon_selfstart = 0;
// Monitor mode is not supported.
if (res == 0)
{
return PCAP_ERROR_RFMON_NOTSUP;
}
else
{
return PCAP_ERROR;
}
}
else
{
pw->rfmon_selfstart = 1;
}
}
}
pw->adapter = PacketOpenAdapter(p->opt.device);
if (pw->adapter == NULL)
{
DWORD errcode = GetLastError();
/*
* What error did we get when trying to open the adapter?
*/
switch (errcode) {
case ERROR_BAD_UNIT:
/*
* There's no such device.
* There's nothing to add, so clear the error
* message.
*/
p->errbuf[0] = '\0';
return (PCAP_ERROR_NO_SUCH_DEVICE);
case ERROR_ACCESS_DENIED:
/*
* There is, but we don't have permission to
* use it.
*
* XXX - we currently get ERROR_BAD_UNIT if the
* user says "no" to the UAC prompt.
*/
snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"The helper program for \"Admin-only Mode\" must be allowed to make changes to your device");
return (PCAP_ERROR_PERM_DENIED);
default:
/*
* Unknown - report details.
*/
pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
errcode, "Error opening adapter");
if (pw->rfmon_selfstart)
{
PacketSetMonitorMode(p->opt.device, 0);
}
return (PCAP_ERROR);
}
}
/*get network type*/
if(PacketGetNetType (pw->adapter,&type) == FALSE)
{
pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "Cannot determine the network type");
goto bad;
}
/*Set the linktype*/
switch (type.LinkType)
{
/*
* NDIS-defined medium types.
*/
case NdisMedium802_3:
p->linktype = DLT_EN10MB;
/*
* This is (presumably) a real Ethernet capture; give it a
* link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
* that an application can let you choose it, in case you're
* capturing DOCSIS traffic that a Cisco Cable Modem
* Termination System is putting out onto an Ethernet (it
* doesn't put an Ethernet header onto the wire, it puts raw
* DOCSIS frames out on the wire inside the low-level
* Ethernet framing).
*/
p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
if (p->dlt_list == NULL)
{
pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
errno, "malloc");
goto bad;
}
p->dlt_list[0] = DLT_EN10MB;
p->dlt_list[1] = DLT_DOCSIS;
p->dlt_count = 2;
break;
case NdisMedium802_5:
/*
* Token Ring.
*/
p->linktype = DLT_IEEE802;
break;
case NdisMediumFddi:
p->linktype = DLT_FDDI;
break;
case NdisMediumWan:
p->linktype = DLT_EN10MB;
break;
case NdisMediumArcnetRaw:
p->linktype = DLT_ARCNET;
break;
case NdisMediumArcnet878_2:
p->linktype = DLT_ARCNET;
break;
case NdisMediumAtm:
p->linktype = DLT_ATM_RFC1483;
break;
case NdisMediumWirelessWan:
p->linktype = DLT_RAW;
break;
case NdisMediumIP:
p->linktype = DLT_RAW;
break;
/*
* Npcap-defined medium types.
*/
case NdisMediumNull:
p->linktype = DLT_NULL;
break;
case NdisMediumCHDLC:
p->linktype = DLT_CHDLC;
break;
case NdisMediumPPPSerial:
p->linktype = DLT_PPP_SERIAL;
break;
case NdisMediumBare80211: