forked from the-tcpdump-group/libpcap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pcap-linux.c
5793 lines (5334 loc) · 161 KB
/
pcap-linux.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
/*
* pcap-linux.c: Packet capture interface to the Linux kernel
*
* Copyright (c) 2000 Torsten Landschoff <[email protected]>
* Sebastian Krahmer <[email protected]>
*
* License: BSD
*
* 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. The names of the authors may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Modifications: Added PACKET_MMAP support
* Paolo Abeni <[email protected]>
* Added TPACKET_V3 support
* Gabor Tatarka <[email protected]>
*
* based on previous works of:
* Simon Patarin <[email protected]>
* Phil Wood <[email protected]>
*
* Monitor-mode support for mac80211 includes code taken from the iw
* command; the copyright notice for that code is
*
* Copyright (c) 2007, 2008 Johannes Berg
* Copyright (c) 2007 Andy Lutomirski
* Copyright (c) 2007 Mike Kershaw
* Copyright (c) 2008 Gábor Stefanik
*
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#define _GNU_SOURCE
#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <limits.h>
#include <endian.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <sys/mman.h>
#include <linux/if.h>
#include <linux/if_packet.h>
#include <linux/sockios.h>
#include <linux/ethtool.h>
#include <netinet/in.h>
#include <linux/if_ether.h>
#include <linux/if_arp.h>
#include <poll.h>
#include <dirent.h>
#include <sys/eventfd.h>
#include "pcap-int.h"
#include "pcap-util.h"
#include "pcap/sll.h"
#include "pcap/vlan.h"
#include "pcap/can_socketcan.h"
#include "diag-control.h"
/*
* We require TPACKET_V2 support.
*/
#ifndef TPACKET2_HDRLEN
#error "Libpcap will only work if TPACKET_V2 is supported; you must build for a 2.6.27 or later kernel"
#endif
/* check for memory mapped access availability. We assume every needed
* struct is defined if the macro TPACKET_HDRLEN is defined, because it
* uses many ring related structs and macros */
#ifdef TPACKET3_HDRLEN
# define HAVE_TPACKET3
#endif /* TPACKET3_HDRLEN */
/*
* Not all compilers that are used to compile code to run on Linux have
* these builtins. For example, older versions of GCC don't, and at
* least some people are doing cross-builds for MIPS with older versions
* of GCC.
*/
#ifndef HAVE___ATOMIC_LOAD_N
#define __atomic_load_n(ptr, memory_model) (*(ptr))
#endif
#ifndef HAVE___ATOMIC_STORE_N
#define __atomic_store_n(ptr, val, memory_model) *(ptr) = (val)
#endif
#define packet_mmap_acquire(pkt) \
(__atomic_load_n(&pkt->tp_status, __ATOMIC_ACQUIRE) != TP_STATUS_KERNEL)
#define packet_mmap_release(pkt) \
(__atomic_store_n(&pkt->tp_status, TP_STATUS_KERNEL, __ATOMIC_RELEASE))
#define packet_mmap_v3_acquire(pkt) \
(__atomic_load_n(&pkt->hdr.bh1.block_status, __ATOMIC_ACQUIRE) != TP_STATUS_KERNEL)
#define packet_mmap_v3_release(pkt) \
(__atomic_store_n(&pkt->hdr.bh1.block_status, TP_STATUS_KERNEL, __ATOMIC_RELEASE))
#include <linux/types.h>
#include <linux/filter.h>
#ifdef HAVE_LINUX_NET_TSTAMP_H
#include <linux/net_tstamp.h>
#endif
/*
* For checking whether a device is a bonding device.
*/
#include <linux/if_bonding.h>
/*
* Got libnl?
*/
#ifdef HAVE_LIBNL
#include <linux/nl80211.h>
#include <netlink/genl/genl.h>
#include <netlink/genl/family.h>
#include <netlink/genl/ctrl.h>
#include <netlink/msg.h>
#include <netlink/attr.h>
#endif /* HAVE_LIBNL */
#ifndef HAVE_SOCKLEN_T
typedef int socklen_t;
#endif
#define MAX_LINKHEADER_SIZE 256
/*
* When capturing on all interfaces we use this as the buffer size.
* Should be bigger then all MTUs that occur in real life.
* 64kB should be enough for now.
*/
#define BIGGER_THAN_ALL_MTUS (64*1024)
/*
* Private data for capturing on Linux PF_PACKET sockets.
*/
struct pcap_linux {
long long sysfs_dropped; /* packets reported dropped by /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors */
struct pcap_stat stat;
char *device; /* device name */
int filter_in_userland; /* must filter in userland */
u_int blocks_to_filter_in_userland;
int must_do_on_close; /* stuff we must do when we close */
int timeout; /* timeout for buffering */
int cooked; /* using SOCK_DGRAM rather than SOCK_RAW */
int ifindex; /* interface index of device we're bound to */
int lo_ifindex; /* interface index of the loopback device */
int netdown; /* we got an ENETDOWN and haven't resolved it */
bpf_u_int32 oldmode; /* mode to restore when turning monitor mode off */
char *mondevice; /* mac80211 monitor device we created */
u_char *mmapbuf; /* memory-mapped region pointer */
size_t mmapbuflen; /* size of region */
int vlan_offset; /* offset at which to insert vlan tags; if -1, don't insert */
u_int tp_version; /* version of tpacket_hdr for mmaped ring */
u_int tp_hdrlen; /* hdrlen of tpacket_hdr for mmaped ring */
u_char *oneshot_buffer; /* buffer for copy of packet */
int poll_timeout; /* timeout to use in poll() */
#ifdef HAVE_TPACKET3
unsigned char *current_packet; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
int packets_left; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
#endif
int poll_breakloop_fd; /* fd to an eventfd to break from blocking operations */
};
/*
* Stuff to do when we close.
*/
#define MUST_CLEAR_RFMON 0x00000001 /* clear rfmon (monitor) mode */
#define MUST_DELETE_MONIF 0x00000002 /* delete monitor-mode interface */
/*
* Prototypes for internal functions and methods.
*/
static int is_wifi(const char *);
static int pcap_activate_linux(pcap_t *);
static int setup_socket(pcap_t *, int);
static int setup_mmapped(pcap_t *);
static int pcap_can_set_rfmon_linux(pcap_t *);
static int pcap_inject_linux(pcap_t *, const void *, int);
static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
static int pcap_set_datalink_linux(pcap_t *, int);
union thdr {
struct tpacket2_hdr *h2;
#ifdef HAVE_TPACKET3
struct tpacket_block_desc *h3;
#endif
u_char *raw;
};
#define RING_GET_FRAME_AT(h, offset) (((u_char **)h->buffer)[(offset)])
#define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
static void destroy_ring(pcap_t *handle);
static int create_ring(pcap_t *handle);
static int prepare_tpacket_socket(pcap_t *handle);
static int pcap_read_linux_mmap_v2(pcap_t *, int, pcap_handler , u_char *);
#ifdef HAVE_TPACKET3
static int pcap_read_linux_mmap_v3(pcap_t *, int, pcap_handler , u_char *);
#endif
static int pcap_setnonblock_linux(pcap_t *p, int nonblock);
static int pcap_getnonblock_linux(pcap_t *p);
static void pcapint_oneshot_linux(u_char *user, const struct pcap_pkthdr *h,
const u_char *bytes);
/*
* In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
* vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
* or "on VLAN 0". There is no flag set in the tp_status field to
* distinguish between them.
*
* In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
* field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
* in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
* the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
*
* With a pre-3.0 kernel, we cannot distinguish between packets with no
* VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
* there's nothing we can do about that.
*
* So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
* continue the behavior of earlier libpcaps, wherein we treated packets
* with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
* on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
* with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
* VLAN tags. This does the right thing on 3.0 and later kernels, and
* continues the old unfixably-imperfect behavior on pre-3.0 kernels.
*
* If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
* has that value in 3.0 and later kernels.
*/
#ifdef TP_STATUS_VLAN_VALID
#define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
#else
/*
* This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
* so we test with the value it has in the 3.0 and later kernels, so
* we can test it if we're running on a system that has it. (If we're
* running on a system that doesn't have it, it won't be set in the
* tp_status field, so the tests of it will always fail; that means
* we behave the way we did before we introduced this macro.)
*/
#define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
#endif
#ifdef TP_STATUS_VLAN_TPID_VALID
# define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
#else
# define VLAN_TPID(hdr, hv) ETH_P_8021Q
#endif
/*
* Required select timeout if we're polling for an "interface disappeared"
* indication - 1 millisecond.
*/
static const struct timeval netdown_timeout = {
0, 1000 /* 1000 microseconds = 1 millisecond */
};
/*
* Wrap some ioctl calls
*/
static int iface_get_id(int fd, const char *device, char *ebuf);
static int iface_get_mtu(int fd, const char *device, char *ebuf);
static int iface_get_arptype(int fd, const char *device, char *ebuf);
static int iface_bind(int fd, int ifindex, char *ebuf, int protocol);
static int enter_rfmon_mode(pcap_t *handle, int sock_fd,
const char *device);
static int iface_get_ts_types(const char *device, pcap_t *handle,
char *ebuf);
static int iface_get_offload(pcap_t *handle);
static int fix_program(pcap_t *handle, struct sock_fprog *fcode);
static int fix_offset(pcap_t *handle, struct bpf_insn *p);
static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
static int reset_kernel_filter(pcap_t *handle);
static struct sock_filter total_insn
= BPF_STMT(BPF_RET | BPF_K, 0);
static struct sock_fprog total_fcode
= { 1, &total_insn };
static int iface_dsa_get_proto_info(const char *device, pcap_t *handle);
pcap_t *
pcapint_create_interface(const char *device, char *ebuf)
{
pcap_t *handle;
handle = PCAP_CREATE_COMMON(ebuf, struct pcap_linux);
if (handle == NULL)
return NULL;
handle->activate_op = pcap_activate_linux;
handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
/*
* See what time stamp types we support.
*/
if (iface_get_ts_types(device, handle, ebuf) == -1) {
pcap_close(handle);
return NULL;
}
/*
* We claim that we support microsecond and nanosecond time
* stamps.
*
* XXX - with adapter-supplied time stamps, can we choose
* microsecond or nanosecond time stamps on arbitrary
* adapters?
*/
handle->tstamp_precision_list = malloc(2 * sizeof(u_int));
if (handle->tstamp_precision_list == NULL) {
pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
errno, "malloc");
pcap_close(handle);
return NULL;
}
handle->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
handle->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
handle->tstamp_precision_count = 2;
/*
* Start out with the breakloop handle not open; we don't
* need it until we're activated and ready to capture.
*/
struct pcap_linux *handlep = handle->priv;
handlep->poll_breakloop_fd = -1;
return handle;
}
#ifdef HAVE_LIBNL
/*
* If interface {if_name} is a mac80211 driver, the file
* /sys/class/net/{if_name}/phy80211 is a symlink to
* /sys/class/ieee80211/{phydev_name}, for some {phydev_name}.
*
* On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
* least, has a "wmaster0" device and a "wlan0" device; the
* latter is the one with the IP address. Both show up in
* "tcpdump -D" output. Capturing on the wmaster0 device
* captures with 802.11 headers.
*
* airmon-ng searches through /sys/class/net for devices named
* monN, starting with mon0; as soon as one *doesn't* exist,
* it chooses that as the monitor device name. If the "iw"
* command exists, it does
*
* iw dev {if_name} interface add {monif_name} type monitor
*
* where {monif_name} is the monitor device. It then (sigh) sleeps
* .1 second, and then configures the device up. Otherwise, if
* /sys/class/ieee80211/{phydev_name}/add_iface is a file, it writes
* {mondev_name}, without a newline, to that file, and again (sigh)
* sleeps .1 second, and then iwconfig's that device into monitor
* mode and configures it up. Otherwise, you can't do monitor mode.
*
* All these devices are "glued" together by having the
* /sys/class/net/{if_name}/phy80211 links pointing to the same
* place, so, given a wmaster, wlan, or mon device, you can
* find the other devices by looking for devices with
* the same phy80211 link.
*
* To turn monitor mode off, delete the monitor interface,
* either with
*
* iw dev {monif_name} interface del
*
* or by sending {monif_name}, with no NL, down
* /sys/class/ieee80211/{phydev_name}/remove_iface
*
* Note: if you try to create a monitor device named "monN", and
* there's already a "monN" device, it fails, as least with
* the netlink interface (which is what iw uses), with a return
* value of -ENFILE. (Return values are negative errnos.) We
* could probably use that to find an unused device.
*
* Yes, you can have multiple monitor devices for a given
* physical device.
*/
/*
* Is this a mac80211 device? If so, fill in the physical device path and
* return 1; if not, return 0. On an error, fill in handle->errbuf and
* return PCAP_ERROR.
*/
static int
get_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
size_t phydev_max_pathlen)
{
char *pathstr;
ssize_t bytes_read;
/*
* Generate the path string for the symlink to the physical device.
*/
if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: Can't generate path name string for /sys/class/net device",
device);
return PCAP_ERROR;
}
bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
if (bytes_read == -1) {
if (errno == ENOENT) {
/*
* This either means that the directory
* /sys/class/net/{device} exists but doesn't
* have anything named "phy80211" in it,
* in which case it's not a mac80211 device,
* or that the directory doesn't exist,
* in which case the device doesn't exist.
*
* Directly check whether the directory
* exists.
*/
struct stat statb;
free(pathstr);
if (asprintf(&pathstr, "/sys/class/net/%s", device) == -1) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: Can't generate path name string for /sys/class/net device",
device);
return PCAP_ERROR;
}
if (stat(pathstr, &statb) == -1) {
if (errno == ENOENT) {
/*
* No such device.
*/
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: %s doesn't exist",
device, pathstr);
free(pathstr);
return PCAP_ERROR_NO_SUCH_DEVICE;
}
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: Can't stat %s: %s",
device, pathstr, strerror(errno));
free(pathstr);
return PCAP_ERROR;
}
/*
* Path to the directory that would contain
* "phy80211" exists, but "phy80211" doesn't
* exist; that means it's not a mac80211
* device.
*/
return 0;
}
if (errno == EINVAL) {
/*
* Exists, but it's not a symlink; assume that
* means it's not a mac80211 device.
*/
return 0;
}
pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
errno, "%s: Can't readlink %s", device, pathstr);
free(pathstr);
return PCAP_ERROR;
}
free(pathstr);
phydev_path[bytes_read] = '\0';
return 1;
}
struct nl80211_state {
struct nl_sock *nl_sock;
struct nl_cache *nl_cache;
struct genl_family *nl80211;
};
static int
nl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
{
int err;
state->nl_sock = nl_socket_alloc();
if (!state->nl_sock) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: failed to allocate netlink handle", device);
return PCAP_ERROR;
}
if (genl_connect(state->nl_sock)) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: failed to connect to generic netlink", device);
goto out_handle_destroy;
}
err = genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache);
if (err < 0) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: failed to allocate generic netlink cache: %s",
device, nl_geterror(-err));
goto out_handle_destroy;
}
state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
if (!state->nl80211) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: nl80211 not found", device);
goto out_cache_free;
}
return 0;
out_cache_free:
nl_cache_free(state->nl_cache);
out_handle_destroy:
nl_socket_free(state->nl_sock);
return PCAP_ERROR;
}
static void
nl80211_cleanup(struct nl80211_state *state)
{
genl_family_put(state->nl80211);
nl_cache_free(state->nl_cache);
nl_socket_free(state->nl_sock);
}
static int
del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
const char *device, const char *mondevice);
static int
add_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
const char *device, const char *mondevice)
{
struct pcap_linux *handlep = handle->priv;
int ifindex;
struct nl_msg *msg;
int err;
ifindex = iface_get_id(sock_fd, device, handle->errbuf);
if (ifindex == -1)
return PCAP_ERROR;
msg = nlmsg_alloc();
if (!msg) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: failed to allocate netlink msg", device);
return PCAP_ERROR;
}
genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
0, NL80211_CMD_NEW_INTERFACE, 0);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
DIAG_OFF_NARROWING
NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
DIAG_ON_NARROWING
NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
err = nl_send_auto_complete(state->nl_sock, msg);
if (err < 0) {
if (err == -NLE_FAILURE) {
/*
* Device not available; our caller should just
* keep trying. (libnl 2.x maps ENFILE to
* NLE_FAILURE; it can also map other errors
* to that, but there's not much we can do
* about that.)
*/
nlmsg_free(msg);
return 0;
} else {
/*
* Real failure, not just "that device is not
* available.
*/
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: nl_send_auto_complete failed adding %s interface: %s",
device, mondevice, nl_geterror(-err));
nlmsg_free(msg);
return PCAP_ERROR;
}
}
err = nl_wait_for_ack(state->nl_sock);
if (err < 0) {
if (err == -NLE_FAILURE) {
/*
* Device not available; our caller should just
* keep trying. (libnl 2.x maps ENFILE to
* NLE_FAILURE; it can also map other errors
* to that, but there's not much we can do
* about that.)
*/
nlmsg_free(msg);
return 0;
} else {
/*
* Real failure, not just "that device is not
* available.
*/
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: nl_wait_for_ack failed adding %s interface: %s",
device, mondevice, nl_geterror(-err));
nlmsg_free(msg);
return PCAP_ERROR;
}
}
/*
* Success.
*/
nlmsg_free(msg);
/*
* Try to remember the monitor device.
*/
handlep->mondevice = strdup(mondevice);
if (handlep->mondevice == NULL) {
pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
errno, "strdup");
/*
* Get rid of the monitor device.
*/
del_mon_if(handle, sock_fd, state, device, mondevice);
return PCAP_ERROR;
}
return 1;
nla_put_failure:
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: nl_put failed adding %s interface",
device, mondevice);
nlmsg_free(msg);
return PCAP_ERROR;
}
static int
del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
const char *device, const char *mondevice)
{
int ifindex;
struct nl_msg *msg;
int err;
ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
if (ifindex == -1)
return PCAP_ERROR;
msg = nlmsg_alloc();
if (!msg) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: failed to allocate netlink msg", device);
return PCAP_ERROR;
}
genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
0, NL80211_CMD_DEL_INTERFACE, 0);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
err = nl_send_auto_complete(state->nl_sock, msg);
if (err < 0) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: nl_send_auto_complete failed deleting %s interface: %s",
device, mondevice, nl_geterror(-err));
nlmsg_free(msg);
return PCAP_ERROR;
}
err = nl_wait_for_ack(state->nl_sock);
if (err < 0) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: nl_wait_for_ack failed adding %s interface: %s",
device, mondevice, nl_geterror(-err));
nlmsg_free(msg);
return PCAP_ERROR;
}
/*
* Success.
*/
nlmsg_free(msg);
return 1;
nla_put_failure:
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"%s: nl_put failed deleting %s interface",
device, mondevice);
nlmsg_free(msg);
return PCAP_ERROR;
}
#endif /* HAVE_LIBNL */
static int pcap_protocol(pcap_t *handle)
{
int protocol;
protocol = handle->opt.protocol;
if (protocol == 0)
protocol = ETH_P_ALL;
return htons(protocol);
}
static int
pcap_can_set_rfmon_linux(pcap_t *handle)
{
#ifdef HAVE_LIBNL
char phydev_path[PATH_MAX+1];
int ret;
#endif
if (strcmp(handle->opt.device, "any") == 0) {
/*
* Monitor mode makes no sense on the "any" device.
*/
return 0;
}
#ifdef HAVE_LIBNL
/*
* Bleah. There doesn't seem to be a way to ask a mac80211
* device, through libnl, whether it supports monitor mode;
* we'll just check whether the device appears to be a
* mac80211 device and, if so, assume the device supports
* monitor mode.
*/
ret = get_mac80211_phydev(handle, handle->opt.device, phydev_path,
PATH_MAX);
if (ret < 0)
return ret; /* error */
if (ret == 1)
return 1; /* mac80211 device */
#endif
return 0;
}
/*
* Grabs the number of missed packets by the interface from
* /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors.
*
* Compared to /proc/net/dev this avoids counting software drops,
* but may be unimplemented and just return 0.
* The author has found no straightforward way to check for support.
*/
static long long int
linux_get_stat(const char * if_name, const char * stat) {
ssize_t bytes_read;
int fd;
char buffer[PATH_MAX];
snprintf(buffer, sizeof(buffer), "/sys/class/net/%s/statistics/%s", if_name, stat);
fd = open(buffer, O_RDONLY);
if (fd == -1)
return 0;
bytes_read = read(fd, buffer, sizeof(buffer) - 1);
close(fd);
if (bytes_read == -1)
return 0;
buffer[bytes_read] = '\0';
return strtoll(buffer, NULL, 10);
}
static long long int
linux_if_drops(const char * if_name)
{
long long int missed = linux_get_stat(if_name, "rx_missed_errors");
long long int fifo = linux_get_stat(if_name, "rx_fifo_errors");
return missed + fifo;
}
/*
* Monitor mode is kind of interesting because we have to reset the
* interface before exiting. The problem can't really be solved without
* some daemon taking care of managing usage counts. If we put the
* interface into monitor mode, we set a flag indicating that we must
* take it out of that mode when the interface is closed, and, when
* closing the interface, if that flag is set we take it out of monitor
* mode.
*/
static void pcap_cleanup_linux( pcap_t *handle )
{
struct pcap_linux *handlep = handle->priv;
#ifdef HAVE_LIBNL
struct nl80211_state nlstate;
int ret;
#endif /* HAVE_LIBNL */
if (handlep->must_do_on_close != 0) {
/*
* There's something we have to do when closing this
* pcap_t.
*/
#ifdef HAVE_LIBNL
if (handlep->must_do_on_close & MUST_DELETE_MONIF) {
ret = nl80211_init(handle, &nlstate, handlep->device);
if (ret >= 0) {
ret = del_mon_if(handle, handle->fd, &nlstate,
handlep->device, handlep->mondevice);
nl80211_cleanup(&nlstate);
}
if (ret < 0) {
fprintf(stderr,
"Can't delete monitor interface %s (%s).\n"
"Please delete manually.\n",
handlep->mondevice, handle->errbuf);
}
}
#endif /* HAVE_LIBNL */
/*
* Take this pcap out of the list of pcaps for which we
* have to take the interface out of some mode.
*/
pcapint_remove_from_pcaps_to_close(handle);
}
if (handle->fd != -1) {
/*
* Destroy the ring buffer (assuming we've set it up),
* and unmap it if it's mapped.
*/
destroy_ring(handle);
}
if (handlep->oneshot_buffer != NULL) {
munmap(handlep->oneshot_buffer, handle->snapshot);
handlep->oneshot_buffer = NULL;
}
if (handlep->mondevice != NULL) {
free(handlep->mondevice);
handlep->mondevice = NULL;
}
if (handlep->device != NULL) {
free(handlep->device);
handlep->device = NULL;
}
if (handlep->poll_breakloop_fd != -1) {
close(handlep->poll_breakloop_fd);
handlep->poll_breakloop_fd = -1;
}
pcapint_cleanup_live_common(handle);
}
#ifdef HAVE_TPACKET3
/*
* Some versions of TPACKET_V3 have annoying bugs/misfeatures
* around which we have to work. Determine if we have those
* problems or not.
* 3.19 is the first release with a fixed version of
* TPACKET_V3. We treat anything before that as
* not having a fixed version; that may really mean
* it has *no* version.
*/
static int has_broken_tpacket_v3(void)
{
struct utsname utsname;
const char *release;
long major, minor;
int matches, verlen;
/* No version information, assume broken. */
if (uname(&utsname) == -1)
return 1;
release = utsname.release;
/* A malformed version, ditto. */
matches = sscanf(release, "%ld.%ld%n", &major, &minor, &verlen);
if (matches != 2)
return 1;
if (release[verlen] != '.' && release[verlen] != '\0')
return 1;
/* OK, a fixed version. */
if (major > 3 || (major == 3 && minor >= 19))
return 0;
/* Too old :( */
return 1;
}
#endif
/*
* Set the timeout to be used in poll() with memory-mapped packet capture.
*/
static void
set_poll_timeout(struct pcap_linux *handlep)
{
#ifdef HAVE_TPACKET3
int broken_tpacket_v3 = has_broken_tpacket_v3();
#endif
if (handlep->timeout == 0) {
#ifdef HAVE_TPACKET3
/*
* XXX - due to a set of (mis)features in the TPACKET_V3
* kernel code prior to the 3.19 kernel, blocking forever
* with a TPACKET_V3 socket can, if few packets are
* arriving and passing the socket filter, cause most
* packets to be dropped. See libpcap issue #335 for the
* full painful story.
*
* The workaround is to have poll() time out very quickly,
* so we grab the frames handed to us, and return them to
* the kernel, ASAP.
*/
if (handlep->tp_version == TPACKET_V3 && broken_tpacket_v3)
handlep->poll_timeout = 1; /* don't block for very long */
else
#endif
handlep->poll_timeout = -1; /* block forever */
} else if (handlep->timeout > 0) {
#ifdef HAVE_TPACKET3
/*
* For TPACKET_V3, the timeout is handled by the kernel,
* so block forever; that way, we don't get extra timeouts.
* Don't do that if we have a broken TPACKET_V3, though.
*/
if (handlep->tp_version == TPACKET_V3 && !broken_tpacket_v3)
handlep->poll_timeout = -1; /* block forever, let TPACKET_V3 wake us up */
else
#endif
handlep->poll_timeout = handlep->timeout; /* block for that amount of time */
} else {
/*
* Non-blocking mode; we call poll() to pick up error
* indications, but we don't want it to wait for
* anything.
*/
handlep->poll_timeout = 0;
}
}
static void pcap_breakloop_linux(pcap_t *handle)
{
pcapint_breakloop_common(handle);
struct pcap_linux *handlep = handle->priv;
uint64_t value = 1;
if (handlep->poll_breakloop_fd != -1) {
/*
* XXX - pcap_breakloop() doesn't have a return value,
* so we can't indicate an error.
*/
DIAG_OFF_WARN_UNUSED_RESULT
(void)write(handlep->poll_breakloop_fd, &value, sizeof(value));