-
Notifications
You must be signed in to change notification settings - Fork 30
/
pcap-linux.c
3738 lines (3400 loc) · 103 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]>
*
* based on previous works of:
* Simon Patarin <[email protected]>
* Phil Wood <[email protected]>
*/
#ifndef lint
static const char rcsid[] _U_ =
"@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.164 2008-12-14 22:00:57 guy Exp $ (LBL)";
#endif
/*
* Known problems with 2.0[.x] kernels:
*
* - The loopback device gives every packet twice; on 2.2[.x] kernels,
* if we use PF_PACKET, we can filter out the transmitted version
* of the packet by using data in the "sockaddr_ll" returned by
* "recvfrom()", but, on 2.0[.x] kernels, we have to use
* PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
* "sockaddr_pkt" which doesn't give us enough information to let
* us do that.
*
* - We have to set the interface's IFF_PROMISC flag ourselves, if
* we're to run in promiscuous mode, which means we have to turn
* it off ourselves when we're done; the kernel doesn't keep track
* of how many sockets are listening promiscuously, which means
* it won't get turned off automatically when no sockets are
* listening promiscuously. We catch "pcap_close()" and, for
* interfaces we put into promiscuous mode, take them out of
* promiscuous mode - which isn't necessarily the right thing to
* do, if another socket also requested promiscuous mode between
* the time when we opened the socket and the time when we close
* the socket.
*
* - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
* return the amount of data that you could have read, rather than
* the amount that was returned, so we can't just allocate a buffer
* whose size is the snapshot length and pass the snapshot length
* as the byte count, and also pass MSG_TRUNC, so that the return
* value tells us how long the packet was on the wire.
*
* This means that, if we want to get the actual size of the packet,
* so we can return it in the "len" field of the packet header,
* we have to read the entire packet, not just the part that fits
* within the snapshot length, and thus waste CPU time copying data
* from the kernel that our caller won't see.
*
* We have to get the actual size, and supply it in "len", because
* otherwise, the IP dissector in tcpdump, for example, will complain
* about "truncated-ip", as the packet will appear to have been
* shorter, on the wire, than the IP header said it should have been.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <sys/mman.h>
#include <linux/if.h>
#include <netinet/in.h>
#include <linux/if_ether.h>
#include <net/if_arp.h>
#include <poll.h>
/*
* Got Wireless Extensions?
*/
#ifdef HAVE_LINUX_WIRELESS_H
#include <linux/wireless.h>
#endif
#include "pcap-int.h"
#include "pcap/sll.h"
#include "pcap/vlan.h"
#ifdef HAVE_DAG_API
#include "pcap-dag.h"
#endif /* HAVE_DAG_API */
#ifdef HAVE_SEPTEL_API
#include "pcap-septel.h"
#endif /* HAVE_SEPTEL_API */
#ifdef PCAP_SUPPORT_USB
#include "pcap-usb-linux.h"
#endif
#ifdef PCAP_SUPPORT_BT
#include "pcap-bt-linux.h"
#endif
/*
* If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
* sockets rather than SOCK_PACKET sockets.
*
* To use them, we include <linux/if_packet.h> rather than
* <netpacket/packet.h>; we do so because
*
* some Linux distributions (e.g., Slackware 4.0) have 2.2 or
* later kernels and libc5, and don't provide a <netpacket/packet.h>
* file;
*
* not all versions of glibc2 have a <netpacket/packet.h> file
* that defines stuff needed for some of the 2.4-or-later-kernel
* features, so if the system has a 2.4 or later kernel, we
* still can't use those features.
*
* We're already including a number of other <linux/XXX.h> headers, and
* this code is Linux-specific (no other OS has PF_PACKET sockets as
* a raw packet capture mechanism), so it's not as if you gain any
* useful portability by using <netpacket/packet.h>
*
* XXX - should we just include <linux/if_packet.h> even if PF_PACKET
* isn't defined? It only defines one data structure in 2.0.x, so
* it shouldn't cause any problems.
*/
#ifdef PF_PACKET
# include <linux/if_packet.h>
/*
* On at least some Linux distributions (for example, Red Hat 5.2),
* there's no <netpacket/packet.h> file, but PF_PACKET is defined if
* you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
* any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
* the PACKET_xxx stuff.
*
* So we check whether PACKET_HOST is defined, and assume that we have
* PF_PACKET sockets only if it is defined.
*/
# ifdef PACKET_HOST
# define HAVE_PF_PACKET_SOCKETS
# ifdef PACKET_AUXDATA
# define HAVE_PACKET_AUXDATA
# endif /* PACKET_AUXDATA */
# endif /* PACKET_HOST */
/* check for memory mapped access avaibility. We assume every needed
* struct is defined if the macro TPACKET_HDRLEN is defined, because it
* uses many ring related structs and macros */
# ifdef TPACKET_HDRLEN
# define HAVE_PACKET_RING
# ifdef TPACKET2_HDRLEN
# define HAVE_TPACKET2
# else
# define TPACKET_V1 0
# endif /* TPACKET2_HDRLEN */
# endif /* TPACKET_HDRLEN */
#endif /* PF_PACKET */
#ifdef SO_ATTACH_FILTER
#include <linux/types.h>
#include <linux/filter.h>
#endif
#ifndef HAVE_SOCKLEN_T
typedef int socklen_t;
#endif
#ifndef MSG_TRUNC
/*
* This is being compiled on a system that lacks MSG_TRUNC; define it
* with the value it has in the 2.2 and later kernels, so that, on
* those kernels, when we pass it in the flags argument to "recvfrom()"
* we're passing the right value and thus get the MSG_TRUNC behavior
* we want. (We don't get that behavior on 2.0[.x] kernels, because
* they didn't support MSG_TRUNC.)
*/
#define MSG_TRUNC 0x20
#endif
#ifndef SOL_PACKET
/*
* This is being compiled on a system that lacks SOL_PACKET; define it
* with the value it has in the 2.2 and later kernels, so that we can
* set promiscuous mode in the good modern way rather than the old
* 2.0-kernel crappy way.
*/
#define SOL_PACKET 263
#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)
/*
* Prototypes for internal functions and methods.
*/
static void map_arphrd_to_dlt(pcap_t *, int, int);
#ifdef HAVE_PF_PACKET_SOCKETS
static short int map_packet_type_to_sll_type(short int);
#endif
static int pcap_activate_linux(pcap_t *);
static int activate_old(pcap_t *);
static int activate_new(pcap_t *);
static int activate_mmap(pcap_t *);
static int pcap_can_set_rfmon_linux(pcap_t *);
static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
static int pcap_inject_linux(pcap_t *, const void *, size_t);
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 void pcap_cleanup_linux(pcap_t *);
#ifdef HAVE_PACKET_RING
#define RING_GET_FRAME(h) (((union thdr **)h->buffer)[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 void pcap_cleanup_linux_mmap(pcap_t *);
static int pcap_read_linux_mmap(pcap_t *, int, pcap_handler , u_char *);
static int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
static int pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf);
static int pcap_getnonblock_mmap(pcap_t *p, char *errbuf);
#endif
/*
* Wrap some ioctl calls
*/
#ifdef HAVE_PF_PACKET_SOCKETS
static int iface_get_id(int fd, const char *device, char *ebuf);
#endif
static int iface_get_mtu(int fd, const char *device, char *ebuf);
static int iface_get_arptype(int fd, const char *device, char *ebuf);
#ifdef HAVE_PF_PACKET_SOCKETS
static int iface_bind(int fd, int ifindex, char *ebuf);
#ifdef IW_MODE_MONITOR
static int has_wext(int sock_fd, const char *device, char *ebuf);
#endif /* IW_MODE_MONITOR */
static int enter_rfmon_mode_wext(pcap_t *handle, int sock_fd,
const char *device);
#endif /* HAVE_PF_PACKET_SOCKETS */
static int iface_bind_old(int fd, const char *device, char *ebuf);
#ifdef SO_ATTACH_FILTER
static int fix_program(pcap_t *handle, struct sock_fprog *fcode);
static int fix_offset(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 };
#endif
pcap_t *
pcap_create(const char *device, char *ebuf)
{
pcap_t *handle;
/*
* A null device name is equivalent to the "any" device.
*/
if (device == NULL)
device = "any";
#ifdef HAVE_DAG_API
if (strstr(device, "dag")) {
return dag_create(device, ebuf);
}
#endif /* HAVE_DAG_API */
#ifdef HAVE_SEPTEL_API
if (strstr(device, "septel")) {
return septel_create(device, ebuf);
}
#endif /* HAVE_SEPTEL_API */
#ifdef PCAP_SUPPORT_BT
if (strstr(device, "bluetooth")) {
return bt_create(device, ebuf);
}
#endif
#ifdef PCAP_SUPPORT_USB
if (strstr(device, "usbmon")) {
return usb_create(device, ebuf);
}
#endif
handle = pcap_create_common(device, ebuf);
if (handle == NULL)
return NULL;
handle->activate_op = pcap_activate_linux;
handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
return handle;
}
static int
pcap_can_set_rfmon_linux(pcap_t *p)
{
#ifdef IW_MODE_MONITOR
int sock_fd;
struct iwreq ireq;
#endif
if (strcmp(p->opt.source, "any") == 0) {
/*
* Monitor mode makes no sense on the "any" device.
*/
return 0;
}
#ifdef IW_MODE_MONITOR
/*
* Bleah. There doesn't appear to be an ioctl to use to ask
* whether a device supports monitor mode; we'll just do
* SIOCGIWMODE and, if it succeeds, assume the device supports
* monitor mode.
*
* Open a socket on which to attempt to get the mode.
* (We assume that if we have Wireless Extensions support
* we also have PF_PACKET support.)
*/
sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sock_fd == -1) {
(void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"socket: %s", pcap_strerror(errno));
return PCAP_ERROR;
}
/*
* Attempt to get the current mode.
*/
strncpy(ireq.ifr_ifrn.ifrn_name, p->opt.source,
sizeof ireq.ifr_ifrn.ifrn_name);
ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
/*
* Well, we got the mode; assume we can set it.
*/
close(sock_fd);
return 1;
}
if (errno == ENODEV) {
/* The device doesn't even exist. */
close(sock_fd);
return PCAP_ERROR_NO_SUCH_DEVICE;
}
close(sock_fd);
#endif
return 0;
}
/*
* With older kernels promiscuous 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 promiscuous 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 promiscuous mode.
*
* Even with newer kernels, we have the same issue with rfmon mode.
*/
static void pcap_cleanup_linux( pcap_t *handle )
{
struct ifreq ifr;
#ifdef IW_MODE_MONITOR
struct iwreq ireq;
#endif
if (handle->md.must_clear != 0) {
/*
* There's something we have to do when closing this
* pcap_t.
*/
if (handle->md.must_clear & MUST_CLEAR_PROMISC) {
/*
* We put the interface into promiscuous mode;
* take it out of promiscuous mode.
*
* XXX - if somebody else wants it in promiscuous
* mode, this code cannot know that, so it'll take
* it out of promiscuous mode. That's not fixable
* in 2.0[.x] kernels.
*/
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, handle->md.device,
sizeof(ifr.ifr_name));
if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
fprintf(stderr,
"Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
"Please adjust manually.\n"
"Hint: This can't happen with Linux >= 2.2.0.\n",
strerror(errno));
} else {
if (ifr.ifr_flags & IFF_PROMISC) {
/*
* Promiscuous mode is currently on;
* turn it off.
*/
ifr.ifr_flags &= ~IFF_PROMISC;
if (ioctl(handle->fd, SIOCSIFFLAGS,
&ifr) == -1) {
fprintf(stderr,
"Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
"Please adjust manually.\n"
"Hint: This can't happen with Linux >= 2.2.0.\n",
strerror(errno));
}
}
}
}
#ifdef IW_MODE_MONITOR
if (handle->md.must_clear & MUST_CLEAR_RFMON) {
/*
* We put the interface into rfmon mode;
* take it out of rfmon mode.
*
* XXX - if somebody else wants it in rfmon
* mode, this code cannot know that, so it'll take
* it out of rfmon mode.
*/
strncpy(ireq.ifr_ifrn.ifrn_name, handle->md.device,
sizeof ireq.ifr_ifrn.ifrn_name);
ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1]
= 0;
ireq.u.mode = handle->md.oldmode;
if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
/*
* Scientist, you've failed.
*/
fprintf(stderr,
"Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
"Please adjust manually.\n",
strerror(errno));
}
}
#endif
/*
* Take this pcap out of the list of pcaps for which we
* have to take the interface out of some mode.
*/
pcap_remove_from_pcaps_to_close(handle);
}
if (handle->md.device != NULL) {
free(handle->md.device);
handle->md.device = NULL;
}
pcap_cleanup_live_common(handle);
}
/*
* Get a handle for a live capture from the given device. You can
* pass NULL as device to get all packages (without link level
* information of course). If you pass 1 as promisc the interface
* will be set to promiscous mode (XXX: I think this usage should
* be deprecated and functions be added to select that later allow
* modification of that values -- Torsten).
*/
static int
pcap_activate_linux(pcap_t *handle)
{
const char *device;
int status = 0;
device = handle->opt.source;
handle->inject_op = pcap_inject_linux;
handle->setfilter_op = pcap_setfilter_linux;
handle->setdirection_op = pcap_setdirection_linux;
handle->set_datalink_op = NULL; /* can't change data link type */
handle->getnonblock_op = pcap_getnonblock_fd;
handle->setnonblock_op = pcap_setnonblock_fd;
handle->cleanup_op = pcap_cleanup_linux;
handle->read_op = pcap_read_linux;
handle->stats_op = pcap_stats_linux;
/*
* The "any" device is a special device which causes us not
* to bind to a particular device and thus to look at all
* devices.
*/
if (strcmp(device, "any") == 0) {
if (handle->opt.promisc) {
handle->opt.promisc = 0;
/* Just a warning. */
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"Promiscuous mode not supported on the \"any\" device");
status = PCAP_WARNING_PROMISC_NOTSUP;
}
}
handle->md.device = strdup(device);
if (handle->md.device == NULL) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
pcap_strerror(errno) );
return PCAP_ERROR;
}
/*
* Current Linux kernels use the protocol family PF_PACKET to
* allow direct access to all packets on the network while
* older kernels had a special socket type SOCK_PACKET to
* implement this feature.
* While this old implementation is kind of obsolete we need
* to be compatible with older kernels for a while so we are
* trying both methods with the newer method preferred.
*/
if ((status = activate_new(handle)) == 1) {
/*
* Success.
* Try to use memory-mapped access.
*/
switch (activate_mmap(handle)) {
case 1:
/* we succeeded; nothing more to do */
return 0;
case 0:
/*
* Kernel doesn't support it - just continue
* with non-memory-mapped access.
*/
status = 0;
break;
case -1:
/*
* We failed to set up to use it, or kernel
* supports it, but we failed to enable it;
* return an error. handle->errbuf contains
* an error message.
*/
status = PCAP_ERROR;
goto fail;
}
}
else if (status == 0) {
/* Non-fatal error; try old way */
if ((status = activate_old(handle)) != 1) {
/*
* Both methods to open the packet socket failed.
* Tidy up and report our failure (handle->errbuf
* is expected to be set by the functions above).
*/
goto fail;
}
} else {
/*
* Fatal error with the new way; just fail.
* status has the error return; if it's PCAP_ERROR,
* handle->errbuf has been set appropriately.
*/
goto fail;
}
/*
* We set up the socket, but not with memory-mapped access.
*/
if (handle->opt.buffer_size != 0) {
/*
* Set the socket buffer size to the specified value.
*/
if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
&handle->opt.buffer_size,
sizeof(handle->opt.buffer_size)) == -1) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"SO_RCVBUF: %s", pcap_strerror(errno));
status = PCAP_ERROR;
goto fail;
}
}
/* Allocate the buffer */
handle->buffer = malloc(handle->bufsize + handle->offset);
if (!handle->buffer) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"malloc: %s", pcap_strerror(errno));
status = PCAP_ERROR;
goto fail;
}
/*
* "handle->fd" is a socket, so "select()" and "poll()"
* should work on it.
*/
handle->selectable_fd = handle->fd;
return status;
fail:
pcap_cleanup_linux(handle);
return status;
}
/*
* Read at most max_packets from the capture stream and call the callback
* for each of them. Returns the number of packets handled or -1 if an
* error occured.
*/
static int
pcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
{
/*
* Currently, on Linux only one packet is delivered per read,
* so we don't loop.
*/
return pcap_read_packet(handle, callback, user);
}
/*
* Read a packet from the socket calling the handler provided by
* the user. Returns the number of packets received or -1 if an
* error occured.
*/
static int
pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
{
u_char *bp;
int offset;
#ifdef HAVE_PF_PACKET_SOCKETS
struct sockaddr_ll from;
struct sll_header *hdrp;
#else
struct sockaddr from;
#endif
#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
struct iovec iov;
struct msghdr msg;
struct cmsghdr *cmsg;
union {
struct cmsghdr cmsg;
char buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
} cmsg_buf;
#else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
socklen_t fromlen;
#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
int packet_len, caplen;
struct pcap_pkthdr pcap_header;
#ifdef HAVE_PF_PACKET_SOCKETS
/*
* If this is a cooked device, leave extra room for a
* fake packet header.
*/
if (handle->md.cooked)
offset = SLL_HDR_LEN;
else
offset = 0;
#else
/*
* This system doesn't have PF_PACKET sockets, so it doesn't
* support cooked devices.
*/
offset = 0;
#endif
/*
* Receive a single packet from the kernel.
* We ignore EINTR, as that might just be due to a signal
* being delivered - if the signal should interrupt the
* loop, the signal handler should call pcap_breakloop()
* to set handle->break_loop (we ignore it on other
* platforms as well).
* We also ignore ENETDOWN, so that we can continue to
* capture traffic if the interface goes down and comes
* back up again; comments in the kernel indicate that
* we'll just block waiting for packets if we try to
* receive from a socket that delivered ENETDOWN, and,
* if we're using a memory-mapped buffer, we won't even
* get notified of "network down" events.
*/
bp = handle->buffer + handle->offset;
#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
msg.msg_name = &from;
msg.msg_namelen = sizeof(from);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = &cmsg_buf;
msg.msg_controllen = sizeof(cmsg_buf);
msg.msg_flags = 0;
iov.iov_len = handle->bufsize - offset;
iov.iov_base = bp + offset;
#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
do {
/*
* Has "pcap_breakloop()" been called?
*/
if (handle->break_loop) {
/*
* Yes - clear the flag that indicates that it
* has, and return -2 as an indication that we
* were told to break out of the loop.
*/
handle->break_loop = 0;
return -2;
}
#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
#else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
fromlen = sizeof(from);
packet_len = recvfrom(
handle->fd, bp + offset,
handle->bufsize - offset, MSG_TRUNC,
(struct sockaddr *) &from, &fromlen);
#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
} while (packet_len == -1 && (errno == EINTR || errno == ENETDOWN));
/* Check if an error occured */
if (packet_len == -1) {
if (errno == EAGAIN)
return 0; /* no packet there */
else {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"recvfrom: %s", pcap_strerror(errno));
return -1;
}
}
#ifdef HAVE_PF_PACKET_SOCKETS
if (!handle->md.sock_packet) {
/*
* Unfortunately, there is a window between socket() and
* bind() where the kernel may queue packets from any
* interface. If we're bound to a particular interface,
* discard packets not from that interface.
*
* (If socket filters are supported, we could do the
* same thing we do when changing the filter; however,
* that won't handle packet sockets without socket
* filter support, and it's a bit more complicated.
* It would save some instructions per packet, however.)
*/
if (handle->md.ifindex != -1 &&
from.sll_ifindex != handle->md.ifindex)
return 0;
/*
* Do checks based on packet direction.
* We can only do this if we're using PF_PACKET; the
* address returned for SOCK_PACKET is a "sockaddr_pkt"
* which lacks the relevant packet type information.
*/
if (from.sll_pkttype == PACKET_OUTGOING) {
/*
* Outgoing packet.
* If this is from the loopback device, reject it;
* we'll see the packet as an incoming packet as well,
* and we don't want to see it twice.
*/
if (from.sll_ifindex == handle->md.lo_ifindex)
return 0;
/*
* If the user only wants incoming packets, reject it.
*/
if (handle->direction == PCAP_D_IN)
return 0;
} else {
/*
* Incoming packet.
* If the user only wants outgoing packets, reject it.
*/
if (handle->direction == PCAP_D_OUT)
return 0;
}
}
#endif
#ifdef HAVE_PF_PACKET_SOCKETS
/*
* If this is a cooked device, fill in the fake packet header.
*/
if (handle->md.cooked) {
/*
* Add the length of the fake header to the length
* of packet data we read.
*/
packet_len += SLL_HDR_LEN;
hdrp = (struct sll_header *)bp;
hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
hdrp->sll_hatype = htons(from.sll_hatype);
hdrp->sll_halen = htons(from.sll_halen);
memcpy(hdrp->sll_addr, from.sll_addr,
(from.sll_halen > SLL_ADDRLEN) ?
SLL_ADDRLEN :
from.sll_halen);
hdrp->sll_protocol = from.sll_protocol;
}
#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
struct tpacket_auxdata *aux;
unsigned int len;
struct vlan_tag *tag;
if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
cmsg->cmsg_level != SOL_PACKET ||
cmsg->cmsg_type != PACKET_AUXDATA)
continue;
aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
if (aux->tp_vlan_tci == 0)
continue;
len = packet_len > iov.iov_len ? iov.iov_len : packet_len;
if (len < 2 * ETH_ALEN)
break;
bp -= VLAN_TAG_LEN;
memmove(bp, bp + VLAN_TAG_LEN, 2 * ETH_ALEN);
tag = (struct vlan_tag *)(bp + 2 * ETH_ALEN);
tag->vlan_tpid = htons(ETH_P_8021Q);
tag->vlan_tci = htons(aux->tp_vlan_tci);
packet_len += VLAN_TAG_LEN;
}
#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
#endif /* HAVE_PF_PACKET_SOCKETS */
/*
* XXX: According to the kernel source we should get the real
* packet len if calling recvfrom with MSG_TRUNC set. It does
* not seem to work here :(, but it is supported by this code
* anyway.
* To be honest the code RELIES on that feature so this is really
* broken with 2.2.x kernels.
* I spend a day to figure out what's going on and I found out
* that the following is happening:
*
* The packet comes from a random interface and the packet_rcv
* hook is called with a clone of the packet. That code inserts
* the packet into the receive queue of the packet socket.
* If a filter is attached to that socket that filter is run
* first - and there lies the problem. The default filter always
* cuts the packet at the snaplen:
*
* # tcpdump -d
* (000) ret #68
*
* So the packet filter cuts down the packet. The recvfrom call
* says "hey, it's only 68 bytes, it fits into the buffer" with
* the result that we don't get the real packet length. This
* is valid at least until kernel 2.2.17pre6.
*
* We currently handle this by making a copy of the filter
* program, fixing all "ret" instructions with non-zero
* operands to have an operand of 65535 so that the filter
* doesn't truncate the packet, and supplying that modified
* filter to the kernel.
*/
caplen = packet_len;
if (caplen > handle->snapshot)
caplen = handle->snapshot;
/* Run the packet filter if not using kernel filter */
if (!handle->md.use_bpf && handle->fcode.bf_insns) {
if (bpf_filter(handle->fcode.bf_insns, bp,
packet_len, caplen) == 0)
{
/* rejected by filter */
return 0;
}
}
/* Fill in our own header data */
if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"SIOCGSTAMP: %s", pcap_strerror(errno));
return -1;
}
pcap_header.caplen = caplen;
pcap_header.len = packet_len;
/*
* Count the packet.
*
* Arguably, we should count them before we check the filter,
* as on many other platforms "ps_recv" counts packets
* handed to the filter rather than packets that passed
* the filter, but if filtering is done in the kernel, we
* can't get a count of packets that passed the filter,
* and that would mean the meaning of "ps_recv" wouldn't
* be the same on all Linux systems.
*
* XXX - it's not the same on all systems in any case;
* ideally, we should have a "get the statistics" call
* that supplies more counts and indicates which of them
* it supplies, so that we supply a count of packets
* handed to the filter only on platforms where that
* information is available.
*
* We count them here even if we can get the packet count
* from the kernel, as we can only determine at run time
* whether we'll be able to get it from the kernel (if
* HAVE_TPACKET_STATS isn't defined, we can't get it from
* the kernel, but if it is defined, the library might
* have been built with a 2.4 or later kernel, but we
* might be running on a 2.2[.x] kernel without Alexey
* Kuznetzov's turbopacket patches, and thus the kernel
* might not be able to supply those statistics). We
* could, I guess, try, when opening the socket, to get
* the statistics, and if we can not increment the count
* here, but it's not clear that always incrementing
* the count is more expensive than always testing a flag
* in memory.
*
* We keep the count in "md.packets_read", and use that for
* "ps_recv" if we can't get the statistics from the kernel.
* We do that because, if we *can* get the statistics from
* the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
* as running counts, as reading the statistics from the
* kernel resets the kernel statistics, and if we directly
* increment "md.stat.ps_recv" here, that means it will
* count packets *twice* on systems where we can get kernel
* statistics - once here, and once in pcap_stats_linux().
*/
handle->md.packets_read++;
/* Call the user supplied callback function */
callback(userdata, &pcap_header, bp);
return 1;
}
static int
pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
{
int ret;
#ifdef HAVE_PF_PACKET_SOCKETS
if (!handle->md.sock_packet) {
/* PF_PACKET socket */
if (handle->md.ifindex == -1) {
/*
* We don't support sending on the "any" device.
*/
strlcpy(handle->errbuf,
"Sending packets isn't supported on the \"any\" device",
PCAP_ERRBUF_SIZE);
return (-1);
}
if (handle->md.cooked) {
/*
* We don't support sending on the "any" device.