Coverage Report

Created: 2026-10-17 08:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libpcap/pcap-linux.c
Line
Count
Source
1
/*
2
 *  pcap-linux.c: Packet capture interface to the Linux kernel
3
 *
4
 *  Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
5
 *           Sebastian Krahmer  <krahmer@cs.uni-potsdam.de>
6
 *
7
 *  License: BSD
8
 *
9
 *  Redistribution and use in source and binary forms, with or without
10
 *  modification, are permitted provided that the following conditions
11
 *  are met:
12
 *
13
 *  1. Redistributions of source code must retain the above copyright
14
 *     notice, this list of conditions and the following disclaimer.
15
 *  2. Redistributions in binary form must reproduce the above copyright
16
 *     notice, this list of conditions and the following disclaimer in
17
 *     the documentation and/or other materials provided with the
18
 *     distribution.
19
 *  3. The names of the authors may not be used to endorse or promote
20
 *     products derived from this software without specific prior
21
 *     written permission.
22
 *
23
 *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
24
 *  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
25
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
26
 *
27
 *  Modifications:     Added PACKET_MMAP support
28
 *                     Paolo Abeni <paolo.abeni@email.it>
29
 *                     Added TPACKET_V3 support
30
 *                     Gabor Tatarka <gabor.tatarka@ericsson.com>
31
 *
32
 *                     based on previous works of:
33
 *                     Simon Patarin <patarin@cs.unibo.it>
34
 *                     Phil Wood <cpw@lanl.gov>
35
 *
36
 * Monitor-mode support for mac80211 includes code taken from the iw
37
 * command; the copyright notice for that code is
38
 *
39
 * Copyright (c) 2007, 2008 Johannes Berg
40
 * Copyright (c) 2007   Andy Lutomirski
41
 * Copyright (c) 2007   Mike Kershaw
42
 * Copyright (c) 2008   Gábor Stefanik
43
 *
44
 * All rights reserved.
45
 *
46
 * Redistribution and use in source and binary forms, with or without
47
 * modification, are permitted provided that the following conditions
48
 * are met:
49
 * 1. Redistributions of source code must retain the above copyright
50
 *    notice, this list of conditions and the following disclaimer.
51
 * 2. Redistributions in binary form must reproduce the above copyright
52
 *    notice, this list of conditions and the following disclaimer in the
53
 *    documentation and/or other materials provided with the distribution.
54
 * 3. The name of the author may not be used to endorse or promote products
55
 *    derived from this software without specific prior written permission.
56
 *
57
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
58
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
59
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
60
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
61
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
62
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
63
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
64
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
65
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67
 * SUCH DAMAGE.
68
 */
69
70
71
#ifndef _GNU_SOURCE
72
#define _GNU_SOURCE
73
#endif
74
75
#include <config.h>
76
77
#include <errno.h>
78
#include <stdio.h>
79
#include <stdlib.h>
80
#include <unistd.h>
81
#include <fcntl.h>
82
#include <string.h>
83
#include <limits.h>
84
#include <endian.h>
85
#include <sys/stat.h>
86
#include <sys/socket.h>
87
#include <sys/ioctl.h>
88
#include <sys/utsname.h>
89
#include <sys/mman.h>
90
#include <linux/if.h>
91
#include <linux/if_packet.h>
92
#include <linux/sockios.h>
93
#include <linux/ethtool.h>
94
#include <netinet/in.h>
95
#include <linux/if_ether.h>
96
#include <linux/netlink.h>
97
98
#include <linux/if_arp.h>
99
#ifndef ARPHRD_IEEE802154
100
  // Linux before 2.6.31
101
  #define ARPHRD_IEEE802154 804
102
#endif
103
#ifndef ARPHRD_IEEE802154_MONITOR
104
  // Linux before 3.5
105
  #define ARPHRD_IEEE802154_MONITOR 805
106
#endif
107
#ifndef ARPHRD_NETLINK
108
  // Linux before 3.11
109
  #define ARPHRD_NETLINK 824
110
#endif
111
#ifndef ARPHRD_6LOWPAN
112
  // Linux before 3.14
113
  #define ARPHRD_6LOWPAN 825
114
#endif
115
#ifndef ARPHRD_VSOCKMON
116
  // Linux before 4.12
117
  #define ARPHRD_VSOCKMON 826
118
#endif
119
#ifndef ARPHRD_LAPD
120
  /*
121
   * ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
122
   * is needed, please report it to <daniele@orlandi.com>
123
   */
124
0
  #define ARPHRD_LAPD 8445
125
#endif
126
127
#include <poll.h>
128
#include <dirent.h>
129
#include <sys/eventfd.h>
130
131
#include "pcap-int.h"
132
#include "pcap-util.h"
133
#include "pcap-snf.h"
134
#include "pcap/sll.h"
135
#include "pcap/vlan.h"
136
#include "pcap/can_socketcan.h"
137
138
#include "diag-control.h"
139
140
/*
141
 * We require TPACKET_V2 support.
142
 */
143
#ifndef TPACKET2_HDRLEN
144
#error "Libpcap will only work if TPACKET_V2 is supported; you must build for a 2.6.27 or later kernel"
145
#endif
146
147
/* check for memory mapped access availability. We assume every needed
148
 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
149
 * uses many ring related structs and macros */
150
#ifdef TPACKET3_HDRLEN
151
# define HAVE_TPACKET3
152
#endif /* TPACKET3_HDRLEN */
153
154
/*
155
 * Not all compilers that are used to compile code to run on Linux have
156
 * these builtins.  For example, older versions of GCC don't, and at
157
 * least some people are doing cross-builds for MIPS with older versions
158
 * of GCC.
159
 */
160
#ifndef HAVE___ATOMIC_LOAD_N
161
#define __atomic_load_n(ptr, memory_model)    (*(ptr))
162
#endif
163
#ifndef HAVE___ATOMIC_STORE_N
164
#define __atomic_store_n(ptr, val, memory_model)  *(ptr) = (val)
165
#endif
166
167
#define packet_mmap_acquire(pkt) \
168
0
  (__atomic_load_n(&pkt->tp_status, __ATOMIC_ACQUIRE) != TP_STATUS_KERNEL)
169
#define packet_mmap_release(pkt) \
170
0
  (__atomic_store_n(&pkt->tp_status, TP_STATUS_KERNEL, __ATOMIC_RELEASE))
171
#define packet_mmap_v3_acquire(pkt) \
172
0
  (__atomic_load_n(&pkt->hdr.bh1.block_status, __ATOMIC_ACQUIRE) != TP_STATUS_KERNEL)
173
#define packet_mmap_v3_release(pkt) \
174
0
  (__atomic_store_n(&pkt->hdr.bh1.block_status, TP_STATUS_KERNEL, __ATOMIC_RELEASE))
175
176
#include <linux/types.h>
177
#include <linux/filter.h>
178
179
#ifdef HAVE_LINUX_NET_TSTAMP_H
180
#include <linux/net_tstamp.h>
181
#endif
182
183
/*
184
 * For checking whether a device is a bonding device.
185
 */
186
#include <linux/if_bonding.h>
187
188
/*
189
 * Got libnl?
190
 */
191
#ifdef HAVE_LIBNL
192
#include <linux/nl80211.h>
193
194
#include <netlink/genl/genl.h>
195
#include <netlink/genl/family.h>
196
#include <netlink/genl/ctrl.h>
197
#include <netlink/msg.h>
198
#include <netlink/attr.h>
199
#endif /* HAVE_LIBNL */
200
201
#ifndef HAVE_SOCKLEN_T
202
typedef int   socklen_t;
203
#endif
204
205
0
#define MAX_LINKHEADER_SIZE 256
206
207
/*
208
 * When capturing on all interfaces we use this as the buffer size.
209
 * Should be bigger then all MTUs that occur in real life.
210
 * 64kB should be enough for now.
211
 */
212
0
#define BIGGER_THAN_ALL_MTUS  (64*1024)
213
214
/*
215
 * Private data for capturing on Linux PF_PACKET sockets.
216
 */
217
struct pcap_linux {
218
  long long sysfs_dropped; /* packets reported dropped by /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors */
219
  struct pcap_stat stat;
220
221
  char  *device;  /* device name */
222
  int filter_in_userland; /* must filter in userland */
223
  u_int blocks_to_filter_in_userland;
224
  int must_do_on_close; /* stuff we must do when we close */
225
  int timeout;  /* timeout for buffering */
226
  int cooked;   /* using SOCK_DGRAM rather than SOCK_RAW */
227
  int ifindex;  /* interface index of device we're bound to */
228
  int lo_ifindex; /* interface index of the loopback device */
229
  int netdown;  /* we got an ENETDOWN and haven't resolved it */
230
  bpf_u_int32 oldmode;  /* mode to restore when turning monitor mode off */
231
  char  *mondevice; /* mac80211 monitor device we created */
232
  u_char  *mmapbuf; /* memory-mapped region pointer */
233
  size_t  mmapbuflen; /* size of region */
234
  int vlan_offset;  /* offset at which to insert vlan tags; if -1, don't insert */
235
  u_int tp_version; /* version of tpacket_hdr for mmaped ring */
236
  u_int tp_hdrlen;  /* hdrlen of tpacket_hdr for mmaped ring */
237
  u_char  *oneshot_buffer; /* buffer for copy of packet */
238
  int poll_timeout; /* timeout to use in poll() */
239
#ifdef HAVE_TPACKET3
240
  unsigned char *current_packet; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
241
  int packets_left; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
242
#endif
243
  int poll_breakloop_fd; /* fd to an eventfd to break from blocking operations */
244
};
245
246
/*
247
 * Stuff to do when we close.
248
 */
249
#define MUST_DELETE_MONIF 0x00000001  /* delete monitor-mode interface */
250
251
/*
252
 * Prototypes for internal functions and methods.
253
 */
254
static int is_wifi(const char *);
255
static int pcap_activate_linux(pcap_t *);
256
static int setup_socket(pcap_t *, int);
257
static int setup_mmapped(pcap_t *);
258
static int pcap_can_set_rfmon_linux(pcap_t *);
259
static int pcap_inject_linux(pcap_t *, const void *, int);
260
static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
261
static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
262
static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
263
static int pcap_set_datalink_linux(pcap_t *, int);
264
265
union thdr {
266
  struct tpacket2_hdr   *h2;
267
#ifdef HAVE_TPACKET3
268
  struct tpacket_block_desc *h3;
269
#endif
270
  u_char        *raw;
271
};
272
273
0
#define RING_GET_FRAME_AT(h, offset) (((u_char **)h->buffer)[(offset)])
274
0
#define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
275
276
static void destroy_ring(pcap_t *handle);
277
static int create_ring(pcap_t *handle);
278
static int prepare_tpacket_socket(pcap_t *handle);
279
static int pcap_read_linux_mmap_v2(pcap_t *, int, pcap_handler , u_char *);
280
#ifdef HAVE_TPACKET3
281
static int pcap_read_linux_mmap_v3(pcap_t *, int, pcap_handler , u_char *);
282
#endif
283
static int pcap_setnonblock_linux(pcap_t *p, int nonblock);
284
static int pcap_getnonblock_linux(pcap_t *p);
285
static void pcapint_oneshot_linux(u_char *user, const struct pcap_pkthdr *h,
286
    const u_char *bytes);
287
288
/*
289
 * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
290
 * vlan_tci field in the skbuff is.  0 can either mean "not on a VLAN"
291
 * or "on VLAN 0".  There is no flag set in the tp_status field to
292
 * distinguish between them.
293
 *
294
 * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
295
 * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
296
 * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
297
 * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
298
 *
299
 * With a pre-3.0 kernel, we cannot distinguish between packets with no
300
 * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
301
 * there's nothing we can do about that.
302
 *
303
 * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
304
 * continue the behavior of earlier libpcaps, wherein we treated packets
305
 * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
306
 * on VLAN 0.  We do this by treating packets with a tp_vlan_tci of 0 and
307
 * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
308
 * VLAN tags.  This does the right thing on 3.0 and later kernels, and
309
 * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
310
 *
311
 * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
312
 * has that value in 3.0 and later kernels.
313
 */
314
#ifdef TP_STATUS_VLAN_VALID
315
0
  #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
316
#else
317
  /*
318
   * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
319
   * so we test with the value it has in the 3.0 and later kernels, so
320
   * we can test it if we're running on a system that has it.  (If we're
321
   * running on a system that doesn't have it, it won't be set in the
322
   * tp_status field, so the tests of it will always fail; that means
323
   * we behave the way we did before we introduced this macro.)
324
   */
325
  #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
326
#endif
327
328
#ifdef TP_STATUS_VLAN_TPID_VALID
329
0
# define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
330
#else
331
# define VLAN_TPID(hdr, hv) ETH_P_8021Q
332
#endif
333
334
/*
335
 * Required select timeout if we're polling for an "interface disappeared"
336
 * indication - 1 millisecond.
337
 */
338
static const struct timeval netdown_timeout = {
339
  0, 1000   /* 1000 microseconds = 1 millisecond */
340
};
341
342
/*
343
 * Wrap some ioctl calls
344
 */
345
static int  iface_get_id(int fd, const char *device, char *ebuf);
346
static int  iface_get_mtu(int fd, const char *device, char *ebuf);
347
static int  iface_get_arptype(int fd, const char *device, char *ebuf);
348
static int  iface_bind(int fd, int ifindex, char *ebuf, int protocol);
349
static int  enter_rfmon_mode(pcap_t *handle, int sock_fd,
350
    const char *device);
351
static int  iface_get_ts_types(const char *device, pcap_t *handle,
352
    char *ebuf);
353
static int  iface_get_offload(pcap_t *handle);
354
355
static int  fix_program(pcap_t *handle, struct sock_fprog *fcode);
356
static int  fix_offset(pcap_t *handle, struct bpf_insn *p);
357
static int  set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
358
static int  reset_kernel_filter(pcap_t *handle);
359
360
static struct sock_filter total_insn
361
  = BPF_STMT(BPF_RET | BPF_K, 0);
362
static struct sock_fprog  total_fcode
363
  = { 1, &total_insn };
364
365
static int  iface_dsa_get_proto_info(const char *device, pcap_t *handle);
366
367
pcap_t *
368
pcapint_create_interface(const char *device, char *ebuf)
369
0
{
370
0
  pcap_t *handle;
371
372
0
  handle = PCAP_CREATE_COMMON(ebuf, struct pcap_linux);
373
0
  if (handle == NULL)
374
0
    return NULL;
375
376
0
  handle->activate_op = pcap_activate_linux;
377
0
  handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
378
379
  /*
380
   * See what time stamp types we support.
381
   */
382
0
  if (iface_get_ts_types(device, handle, ebuf) == -1) {
383
0
    pcap_close(handle);
384
0
    return NULL;
385
0
  }
386
387
  /*
388
   * We claim that we support microsecond and nanosecond time
389
   * stamps.
390
   *
391
   * XXX - with adapter-supplied time stamps, can we choose
392
   * microsecond or nanosecond time stamps on arbitrary
393
   * adapters?
394
   */
395
0
  handle->tstamp_precision_list = malloc(2 * sizeof(u_int));
396
0
  if (handle->tstamp_precision_list == NULL) {
397
0
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
398
0
        errno, "malloc");
399
0
    pcap_close(handle);
400
0
    return NULL;
401
0
  }
402
0
  handle->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
403
0
  handle->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
404
0
  handle->tstamp_precision_count = 2;
405
406
  /*
407
   * Start out with the breakloop handle not open; we don't
408
   * need it until we're activated and ready to capture.
409
   */
410
0
  struct pcap_linux *handlep = handle->priv;
411
0
  handlep->poll_breakloop_fd = -1;
412
413
0
  return handle;
414
0
}
415
416
#ifdef HAVE_LIBNL
417
/*
418
 * If interface {if_name} is a mac80211 driver, the file
419
 * /sys/class/net/{if_name}/phy80211 is a symlink to
420
 * /sys/class/ieee80211/{phydev_name}, for some {phydev_name}.
421
 *
422
 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
423
 * least, has a "wmaster0" device and a "wlan0" device; the
424
 * latter is the one with the IP address.  Both show up in
425
 * "tcpdump -D" output.  Capturing on the wmaster0 device
426
 * captures with 802.11 headers.
427
 *
428
 * airmon-ng searches through /sys/class/net for devices named
429
 * monN, starting with mon0; as soon as one *doesn't* exist,
430
 * it chooses that as the monitor device name.  If the "iw"
431
 * command exists, it does
432
 *
433
 *    iw dev {if_name} interface add {monif_name} type monitor
434
 *
435
 * where {monif_name} is the monitor device.  It then (sigh) sleeps
436
 * .1 second, and then configures the device up.  Otherwise, if
437
 * /sys/class/ieee80211/{phydev_name}/add_iface is a file, it writes
438
 * {mondev_name}, without a newline, to that file, and again (sigh)
439
 * sleeps .1 second, and then iwconfig's that device into monitor
440
 * mode and configures it up.  Otherwise, you can't do monitor mode.
441
 *
442
 * All these devices are "glued" together by having the
443
 * /sys/class/net/{if_name}/phy80211 links pointing to the same
444
 * place, so, given a wmaster, wlan, or mon device, you can
445
 * find the other devices by looking for devices with
446
 * the same phy80211 link.
447
 *
448
 * To turn monitor mode off, delete the monitor interface,
449
 * either with
450
 *
451
 *    iw dev {monif_name} interface del
452
 *
453
 * or by sending {monif_name}, with no NL, down
454
 * /sys/class/ieee80211/{phydev_name}/remove_iface
455
 *
456
 * Note: if you try to create a monitor device named "monN", and
457
 * there's already a "monN" device, it fails, as least with
458
 * the netlink interface (which is what iw uses), with a return
459
 * value of -ENFILE.  (Return values are negative errnos.)  We
460
 * could probably use that to find an unused device.
461
 *
462
 * Yes, you can have multiple monitor devices for a given
463
 * physical device.
464
 */
465
466
/*
467
 * Is this a mac80211 device?  If so, fill in the physical device path and
468
 * return 1; if not, return 0.  On an error, fill in handle->errbuf and
469
 * return PCAP_ERROR.
470
 */
471
static int
472
get_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
473
    size_t phydev_max_pathlen)
474
{
475
  char *pathstr;
476
  ssize_t bytes_read;
477
478
  /*
479
   * Generate the path string for the symlink to the physical device.
480
   */
481
  if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
482
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
483
        "%s: Can't generate path name string for /sys/class/net device",
484
        device);
485
    return PCAP_ERROR;
486
  }
487
  bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
488
  if (bytes_read == -1) {
489
    if (errno == ENOENT) {
490
      /*
491
       * This either means that the directory
492
       * /sys/class/net/{device} exists but doesn't
493
       * have anything named "phy80211" in it,
494
       * in which case it's not a mac80211 device,
495
       * or that the directory doesn't exist,
496
       * in which case the device doesn't exist.
497
       *
498
       * Directly check whether the directory
499
       * exists.
500
       */
501
      struct stat statb;
502
503
      free(pathstr);
504
      if (asprintf(&pathstr, "/sys/class/net/%s", device) == -1) {
505
        snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
506
            "%s: Can't generate path name string for /sys/class/net device",
507
            device);
508
        return PCAP_ERROR;
509
      }
510
      if (stat(pathstr, &statb) == -1) {
511
        if (errno == ENOENT) {
512
          /*
513
           * No such device.
514
           */
515
          snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
516
              "%s: %s doesn't exist",
517
              device, pathstr);
518
          free(pathstr);
519
          return PCAP_ERROR_NO_SUCH_DEVICE;
520
        }
521
        snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
522
            "%s: Can't stat %s: %s",
523
            device, pathstr, strerror(errno));
524
        free(pathstr);
525
        return PCAP_ERROR;
526
      }
527
528
      /*
529
       * Path to the directory that would contain
530
       * "phy80211" exists, but "phy80211" doesn't
531
       * exist; that means it's not a mac80211
532
       * device.
533
       */
534
      free(pathstr);
535
      return 0;
536
    }
537
    if (errno == EINVAL) {
538
      /*
539
       * Exists, but it's not a symlink; assume that
540
       * means it's not a mac80211 device.
541
       */
542
      free(pathstr);
543
      return 0;
544
    }
545
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
546
        errno, "%s: Can't readlink %s", device, pathstr);
547
    free(pathstr);
548
    return PCAP_ERROR;
549
  }
550
  free(pathstr);
551
  phydev_path[bytes_read] = '\0';
552
  return 1;
553
}
554
555
struct nl80211_state {
556
  struct nl_sock *nl_sock;
557
  struct nl_cache *nl_cache;
558
  struct genl_family *nl80211;
559
};
560
561
static int
562
nl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
563
{
564
  int err;
565
566
  state->nl_sock = nl_socket_alloc();
567
  if (!state->nl_sock) {
568
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
569
        "%s: failed to allocate netlink handle", device);
570
    return PCAP_ERROR;
571
  }
572
573
  if (genl_connect(state->nl_sock)) {
574
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
575
        "%s: failed to connect to generic netlink", device);
576
    goto out_handle_destroy;
577
  }
578
579
  err = genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache);
580
  if (err < 0) {
581
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
582
        "%s: failed to allocate generic netlink cache: %s",
583
        device, nl_geterror(-err));
584
    goto out_handle_destroy;
585
  }
586
587
  state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
588
  if (!state->nl80211) {
589
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
590
        "%s: nl80211 not found", device);
591
    goto out_cache_free;
592
  }
593
594
  return 0;
595
596
out_cache_free:
597
  nl_cache_free(state->nl_cache);
598
out_handle_destroy:
599
  nl_socket_free(state->nl_sock);
600
  return PCAP_ERROR;
601
}
602
603
static void
604
nl80211_cleanup(struct nl80211_state *state)
605
{
606
  genl_family_put(state->nl80211);
607
  nl_cache_free(state->nl_cache);
608
  nl_socket_free(state->nl_sock);
609
}
610
611
static int
612
del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
613
    const char *device, const char *mondevice);
614
615
static int
616
if_type_cb(struct nl_msg *msg, void* arg)
617
{
618
  struct nlmsghdr* ret_hdr = nlmsg_hdr(msg);
619
  struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
620
  int *type = (int*)arg;
621
622
  struct genlmsghdr *gnlh = (struct genlmsghdr*) nlmsg_data(ret_hdr);
623
624
  nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
625
    genlmsg_attrlen(gnlh, 0), NULL);
626
627
  /*
628
   * We sent a message asking for info about a single index.
629
   * To be really paranoid, we could check if the index matched
630
   * by examining nla_get_u32(tb_msg[NL80211_ATTR_IFINDEX]).
631
   */
632
633
  if (tb_msg[NL80211_ATTR_IFTYPE]) {
634
    *type = nla_get_u32(tb_msg[NL80211_ATTR_IFTYPE]);
635
  }
636
637
  return NL_SKIP;
638
}
639
640
static int
641
get_if_type(pcap_t *handle, int sock_fd, struct nl80211_state *state,
642
    const char *device, int *type)
643
{
644
  int ifindex;
645
  struct nl_msg *msg;
646
  int err;
647
648
  ifindex = iface_get_id(sock_fd, device, handle->errbuf);
649
  if (ifindex == -1)
650
    return PCAP_ERROR;
651
652
  msg = nlmsg_alloc();
653
  if (!msg) {
654
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
655
        "%s: failed to allocate netlink msg", device);
656
    return PCAP_ERROR;
657
  }
658
659
  genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ,
660
        genl_family_get_id(state->nl80211), 0,
661
        0, NL80211_CMD_GET_INTERFACE, 0);
662
  NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
663
664
  err = nl_send_auto(state->nl_sock, msg);
665
  nlmsg_free(msg);
666
  if (err < 0) {
667
    if (err == -NLE_FAILURE) {
668
      /*
669
       * Device not available; our caller should just
670
       * keep trying.  (libnl 2.x maps ENFILE to
671
       * NLE_FAILURE; it can also map other errors
672
       * to that, but there's not much we can do
673
       * about that.)
674
       */
675
      return 0;
676
    } else {
677
      /*
678
       * Real failure, not just "that device is not
679
       * available.
680
       */
681
      snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
682
          "%s: nl_send_auto failed getting interface type: %s",
683
          device, nl_geterror(-err));
684
      return PCAP_ERROR;
685
    }
686
  }
687
688
  struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
689
  nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, if_type_cb, (void*)type);
690
  err = nl_recvmsgs(state->nl_sock, cb);
691
  nl_cb_put(cb);
692
693
  if (err < 0) {
694
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
695
        "%s: nl_recvmsgs failed getting interface type: %s",
696
        device, nl_geterror(-err));
697
    return PCAP_ERROR;
698
  }
699
700
  /*
701
  * If this is a mac80211 device not in monitor mode, nl_sock will be
702
  * reused for add_mon_if. So we must wait for the ACK here so that
703
  * add_mon_if does not receive it instead and incorrectly interpret
704
  * the ACK as its NEW_INTERFACE command succeeding, even when it fails.
705
  */
706
  err = nl_wait_for_ack(state->nl_sock);
707
  if (err < 0) {
708
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
709
        "%s: nl_wait_for_ack failed getting interface type: %s",
710
        device, nl_geterror(-err));
711
    return PCAP_ERROR;
712
  }
713
714
  /*
715
   * Success.
716
   */
717
  return 1;
718
719
nla_put_failure:
720
  snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
721
      "%s: nl_put failed getting interface type",
722
      device);
723
  nlmsg_free(msg);
724
  // Do not call nl_cb_put(): nl_cb_alloc() has not been called.
725
  return PCAP_ERROR;
726
}
727
728
static int
729
add_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
730
    const char *device, const char *mondevice)
731
{
732
  struct pcap_linux *handlep = handle->priv;
733
  int ifindex;
734
  struct nl_msg *msg;
735
  int err;
736
737
  ifindex = iface_get_id(sock_fd, device, handle->errbuf);
738
  if (ifindex == -1)
739
    return PCAP_ERROR;
740
741
  msg = nlmsg_alloc();
742
  if (!msg) {
743
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
744
        "%s: failed to allocate netlink msg", device);
745
    return PCAP_ERROR;
746
  }
747
748
  genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ,
749
        genl_family_get_id(state->nl80211), 0,
750
        0, NL80211_CMD_NEW_INTERFACE, 0);
751
  NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
752
DIAG_OFF_NARROWING
753
  NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
754
DIAG_ON_NARROWING
755
  NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
756
757
  err = nl_send_sync(state->nl_sock, msg); // calls nlmsg_free()
758
  if (err < 0) {
759
    switch (err) {
760
761
    case -NLE_FAILURE:
762
    case -NLE_AGAIN:
763
      /*
764
       * Device not available; our caller should just
765
       * keep trying.  (libnl 2.x maps ENFILE to
766
       * NLE_FAILURE; it can also map other errors
767
       * to that, but there's not much we can do
768
       * about that.)
769
       */
770
      return 0;
771
772
    case -NLE_OPNOTSUPP:
773
      /*
774
       * Device is a mac80211 device but adding it as a
775
       * monitor mode device isn't supported.  Report our
776
       * error.
777
       */
778
      return PCAP_ERROR_RFMON_NOTSUP;
779
780
    default:
781
      /*
782
       * Real failure, not just "that device is not
783
       * available."  Report a generic error, using the
784
       * error message from libnl.
785
       */
786
      snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
787
          "%s: nl_send_sync failed adding %s interface: %s",
788
          device, mondevice, nl_geterror(-err));
789
      return PCAP_ERROR;
790
    }
791
  }
792
793
  /*
794
   * Success.
795
   */
796
797
  /*
798
   * Try to remember the monitor device.
799
   */
800
  handlep->mondevice = strdup(mondevice);
801
  if (handlep->mondevice == NULL) {
802
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
803
        errno, "strdup");
804
    /*
805
     * Get rid of the monitor device.
806
     */
807
    del_mon_if(handle, sock_fd, state, device, mondevice);
808
    return PCAP_ERROR;
809
  }
810
  return 1;
811
812
nla_put_failure:
813
  snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
814
      "%s: nl_put failed adding %s interface",
815
      device, mondevice);
816
  nlmsg_free(msg);
817
  return PCAP_ERROR;
818
}
819
820
static int
821
del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
822
    const char *device, const char *mondevice)
823
{
824
  int ifindex;
825
  struct nl_msg *msg;
826
  int err;
827
828
  ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
829
  if (ifindex == -1)
830
    return PCAP_ERROR;
831
832
  msg = nlmsg_alloc();
833
  if (!msg) {
834
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
835
        "%s: failed to allocate netlink msg", device);
836
    return PCAP_ERROR;
837
  }
838
839
  genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ,
840
        genl_family_get_id(state->nl80211), 0,
841
        0, NL80211_CMD_DEL_INTERFACE, 0);
842
  NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
843
844
  err = nl_send_sync(state->nl_sock, msg); // calls nlmsg_free()
845
  if (err < 0) {
846
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
847
        "%s: nl_send_sync failed deleting %s interface: %s",
848
        device, mondevice, nl_geterror(-err));
849
    return PCAP_ERROR;
850
  }
851
852
  /*
853
   * Success.
854
   */
855
  return 1;
856
857
nla_put_failure:
858
  snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
859
      "%s: nl_put failed deleting %s interface",
860
      device, mondevice);
861
  nlmsg_free(msg);
862
  return PCAP_ERROR;
863
}
864
#endif /* HAVE_LIBNL */
865
866
static int pcap_protocol(pcap_t *handle)
867
0
{
868
0
  int protocol;
869
870
0
  protocol = handle->opt.protocol;
871
0
  if (protocol == 0)
872
0
    protocol = ETH_P_ALL;
873
874
0
  return htons(protocol);
875
0
}
876
877
static int
878
pcap_can_set_rfmon_linux(pcap_t *handle)
879
0
{
880
#ifdef HAVE_LIBNL
881
  char phydev_path[PATH_MAX+1];
882
  int ret;
883
#endif
884
885
0
  if (strcmp(handle->opt.device, "any") == 0) {
886
    /*
887
     * Monitor mode makes no sense on the "any" device.
888
     */
889
0
    return 0;
890
0
  }
891
892
#ifdef HAVE_LIBNL
893
  /*
894
   * Bleah.  There doesn't seem to be a way to ask a mac80211
895
   * device, through libnl, whether it supports monitor mode;
896
   * we'll just check whether the device appears to be a
897
   * mac80211 device and, if so, assume the device supports
898
   * monitor mode.
899
   */
900
  ret = get_mac80211_phydev(handle, handle->opt.device, phydev_path,
901
      PATH_MAX);
902
  if (ret < 0)
903
    return ret; /* error */
904
  if (ret == 1)
905
    return 1; /* mac80211 device */
906
#endif
907
908
0
  return 0;
909
0
}
910
911
/*
912
 * Grabs the number of missed packets by the interface from
913
 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors.
914
 *
915
 * Compared to /proc/net/dev this avoids counting software drops,
916
 * but may be unimplemented and just return 0.
917
 * The author has found no straightforward way to check for support.
918
 */
919
static long long int
920
0
linux_get_stat(const char * if_name, const char * stat_name) {
921
0
  ssize_t bytes_read;
922
0
  int fd;
923
0
  char buffer[PATH_MAX];
924
925
0
  snprintf(buffer, sizeof(buffer), "/sys/class/net/%s/statistics/%s", if_name, stat_name);
926
0
  fd = open(buffer, O_RDONLY);
927
0
  if (fd == -1)
928
0
    return 0;
929
930
0
  bytes_read = read(fd, buffer, sizeof(buffer) - 1);
931
0
  close(fd);
932
0
  if (bytes_read == -1)
933
0
    return 0;
934
0
  buffer[bytes_read] = '\0';
935
936
0
  return strtoll(buffer, NULL, 10);
937
0
}
938
939
static long long int
940
linux_if_drops(const char * if_name)
941
0
{
942
0
  long long int dropped = linux_get_stat(if_name, "rx_dropped");
943
0
  long long int missed = linux_get_stat(if_name, "rx_missed_errors");
944
0
  long long int fifo = linux_get_stat(if_name, "rx_fifo_errors");
945
0
  return dropped + missed + fifo;
946
0
}
947
948
949
/*
950
 * Monitor mode is kind of interesting because we have to reset the
951
 * interface before exiting. The problem can't really be solved without
952
 * some daemon taking care of managing usage counts.  If we put the
953
 * interface into monitor mode, we set a flag indicating that we must
954
 * take it out of that mode when the interface is closed, and, when
955
 * closing the interface, if that flag is set we take it out of monitor
956
 * mode.
957
 */
958
959
static void pcap_cleanup_linux( pcap_t *handle )
960
0
{
961
0
  struct pcap_linux *handlep = handle->priv;
962
#ifdef HAVE_LIBNL
963
  struct nl80211_state nlstate;
964
  int ret;
965
#endif /* HAVE_LIBNL */
966
967
0
  if (handlep->must_do_on_close != 0) {
968
    /*
969
     * There's something we have to do when closing this
970
     * pcap_t.
971
     */
972
#ifdef HAVE_LIBNL
973
    if (handlep->must_do_on_close & MUST_DELETE_MONIF) {
974
      ret = nl80211_init(handle, &nlstate, handlep->device);
975
      if (ret >= 0) {
976
        ret = del_mon_if(handle, handle->fd, &nlstate,
977
            handlep->device, handlep->mondevice);
978
        nl80211_cleanup(&nlstate);
979
      }
980
      if (ret < 0) {
981
        fprintf(stderr,
982
            "Can't delete monitor interface %s (%s).\n"
983
            "Please delete manually.\n",
984
            handlep->mondevice, handle->errbuf);
985
      }
986
    }
987
#endif /* HAVE_LIBNL */
988
989
    /*
990
     * Take this pcap out of the list of pcaps for which we
991
     * have to take the interface out of some mode.
992
     */
993
0
    pcapint_remove_from_pcaps_to_close(handle);
994
0
  }
995
996
0
  if (handle->fd != -1) {
997
    /*
998
     * Destroy the ring buffer (assuming we've set it up),
999
     * and unmap it if it's mapped.
1000
     */
1001
0
    destroy_ring(handle);
1002
0
  }
1003
1004
0
  if (handlep->oneshot_buffer != NULL) {
1005
0
    munmap(handlep->oneshot_buffer, handle->snapshot);
1006
0
    handlep->oneshot_buffer = NULL;
1007
0
  }
1008
1009
0
  if (handlep->mondevice != NULL) {
1010
0
    free(handlep->mondevice);
1011
0
    handlep->mondevice = NULL;
1012
0
  }
1013
0
  if (handlep->device != NULL) {
1014
0
    free(handlep->device);
1015
0
    handlep->device = NULL;
1016
0
  }
1017
1018
0
  if (handlep->poll_breakloop_fd != -1) {
1019
0
    close(handlep->poll_breakloop_fd);
1020
0
    handlep->poll_breakloop_fd = -1;
1021
0
  }
1022
0
  pcapint_cleanup_live_common(handle);
1023
0
}
1024
1025
#ifdef HAVE_TPACKET3
1026
/*
1027
 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1028
 * around which we have to work.  Determine if we have those
1029
 * problems or not.
1030
 * 3.19 is the first release with a fixed version of
1031
 * TPACKET_V3.  We treat anything before that as
1032
 * not having a fixed version; that may really mean
1033
 * it has *no* version.
1034
 */
1035
static int has_broken_tpacket_v3(void)
1036
0
{
1037
0
  struct utsname utsname;
1038
0
  const char *release;
1039
0
  long major, minor;
1040
0
  int matches, verlen;
1041
1042
  /* No version information, assume broken. */
1043
0
  if (uname(&utsname) == -1)
1044
0
    return 1;
1045
0
  release = utsname.release;
1046
1047
  /* A malformed version, ditto. */
1048
0
  matches = sscanf(release, "%ld.%ld%n", &major, &minor, &verlen);
1049
0
  if (matches != 2)
1050
0
    return 1;
1051
0
  if (release[verlen] != '.' && release[verlen] != '\0')
1052
0
    return 1;
1053
1054
  /* OK, a fixed version. */
1055
0
  if (major > 3 || (major == 3 && minor >= 19))
1056
0
    return 0;
1057
1058
  /* Too old :( */
1059
0
  return 1;
1060
0
}
1061
#endif
1062
1063
/*
1064
 * Set the timeout to be used in poll() with memory-mapped packet capture.
1065
 */
1066
static void
1067
set_poll_timeout(struct pcap_linux *handlep)
1068
0
{
1069
0
#ifdef HAVE_TPACKET3
1070
0
  int broken_tpacket_v3 = has_broken_tpacket_v3();
1071
0
#endif
1072
0
  if (handlep->timeout == 0) {
1073
0
#ifdef HAVE_TPACKET3
1074
    /*
1075
     * XXX - due to a set of (mis)features in the TPACKET_V3
1076
     * kernel code prior to the 3.19 kernel, blocking forever
1077
     * with a TPACKET_V3 socket can, if few packets are
1078
     * arriving and passing the socket filter, cause most
1079
     * packets to be dropped.  See libpcap issue #335 for the
1080
     * full painful story.
1081
     *
1082
     * The workaround is to have poll() time out very quickly,
1083
     * so we grab the frames handed to us, and return them to
1084
     * the kernel, ASAP.
1085
     */
1086
0
    if (handlep->tp_version == TPACKET_V3 && broken_tpacket_v3)
1087
0
      handlep->poll_timeout = 1; /* don't block for very long */
1088
0
    else
1089
0
#endif
1090
0
      handlep->poll_timeout = -1; /* block forever */
1091
0
  } else if (handlep->timeout > 0) {
1092
0
#ifdef HAVE_TPACKET3
1093
    /*
1094
     * For TPACKET_V3, the timeout is handled by the kernel,
1095
     * so block forever; that way, we don't get extra timeouts.
1096
     * Don't do that if we have a broken TPACKET_V3, though.
1097
     */
1098
0
    if (handlep->tp_version == TPACKET_V3 && !broken_tpacket_v3)
1099
0
      handlep->poll_timeout = -1; /* block forever, let TPACKET_V3 wake us up */
1100
0
    else
1101
0
#endif
1102
0
      handlep->poll_timeout = handlep->timeout; /* block for that amount of time */
1103
0
  } else {
1104
    /*
1105
     * Non-blocking mode; we call poll() to pick up error
1106
     * indications, but we don't want it to wait for
1107
     * anything.
1108
     */
1109
0
    handlep->poll_timeout = 0;
1110
0
  }
1111
0
}
1112
1113
static void pcap_breakloop_linux(pcap_t *handle)
1114
0
{
1115
0
  pcapint_breakloop_common(handle);
1116
0
  struct pcap_linux *handlep = handle->priv;
1117
1118
0
  uint64_t value = 1;
1119
1120
0
  if (handlep->poll_breakloop_fd != -1) {
1121
    /*
1122
     * XXX - pcap_breakloop() doesn't have a return value,
1123
     * so we can't indicate an error.
1124
     */
1125
0
DIAG_OFF_WARN_UNUSED_RESULT
1126
0
    (void)write(handlep->poll_breakloop_fd, &value, sizeof(value));
1127
0
DIAG_ON_WARN_UNUSED_RESULT
1128
0
  }
1129
0
}
1130
1131
/*
1132
 * Set the offset at which to insert VLAN tags.
1133
 * That should be the offset of the type field.
1134
 */
1135
static void
1136
set_vlan_offset(pcap_t *handle)
1137
0
{
1138
0
  struct pcap_linux *handlep = handle->priv;
1139
1140
0
  switch (handle->linktype) {
1141
1142
0
  case DLT_EN10MB:
1143
    /*
1144
     * The type field is after the destination and source
1145
     * MAC address.
1146
     */
1147
0
    handlep->vlan_offset = 2 * ETH_ALEN;
1148
0
    break;
1149
1150
0
  case DLT_LINUX_SLL:
1151
    /*
1152
     * The type field is in the last 2 bytes of the
1153
     * DLT_LINUX_SLL header.
1154
     */
1155
0
    handlep->vlan_offset = SLL_HDR_LEN - 2;
1156
0
    break;
1157
1158
0
  default:
1159
0
    handlep->vlan_offset = -1; /* unknown */
1160
0
    break;
1161
0
  }
1162
0
}
1163
1164
static int
1165
pcap_activate_linux(pcap_t *handle)
1166
0
{
1167
0
  struct pcap_linux *handlep = handle->priv;
1168
0
  const char  *device;
1169
0
  int   is_any_device;
1170
0
  struct ifreq  ifr;
1171
0
  int   status;
1172
0
  int   ret;
1173
1174
0
  device = handle->opt.device;
1175
1176
  /*
1177
   * Start out assuming no warnings.
1178
   */
1179
0
  status = 0;
1180
1181
  /*
1182
   * Make sure the name we were handed will fit into the ioctls we
1183
   * might perform on the device; if not, return a "No such device"
1184
   * indication, as the Linux kernel shouldn't support creating
1185
   * a device whose name won't fit into those ioctls.
1186
   *
1187
   * "Will fit" means "will fit, complete with a null terminator",
1188
   * so if the length, which does *not* include the null terminator,
1189
   * is greater than *or equal to* the size of the field into which
1190
   * we'll be copying it, that won't fit.
1191
   */
1192
0
  if (strlen(device) >= sizeof(ifr.ifr_name)) {
1193
    /*
1194
     * There's nothing more to say, so clear the error
1195
     * message.
1196
     */
1197
0
    handle->errbuf[0] = '\0';
1198
0
    status = PCAP_ERROR_NO_SUCH_DEVICE;
1199
0
    goto fail;
1200
0
  }
1201
1202
  /*
1203
   * Turn a negative snapshot value (invalid), a snapshot value of
1204
   * 0 (unspecified), or a value bigger than the normal maximum
1205
   * value, into the maximum allowed value.
1206
   *
1207
   * If some application really *needs* a bigger snapshot
1208
   * length, we should just increase MAXIMUM_SNAPLEN.
1209
   */
1210
0
  if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
1211
0
    handle->snapshot = MAXIMUM_SNAPLEN;
1212
1213
0
  handlep->device = strdup(device);
1214
0
  if (handlep->device == NULL) {
1215
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1216
0
        errno, "strdup");
1217
0
    status = PCAP_ERROR;
1218
0
    goto fail;
1219
0
  }
1220
1221
  /*
1222
   * The "any" device is a special device which causes us not
1223
   * to bind to a particular device and thus to look at all
1224
   * devices.
1225
   */
1226
0
  is_any_device = (strcmp(device, "any") == 0);
1227
0
  if (is_any_device) {
1228
0
    if (handle->opt.promisc) {
1229
0
      handle->opt.promisc = 0;
1230
      /* Just a warning. */
1231
0
      snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1232
0
          "Promiscuous mode not supported on the \"any\" device");
1233
0
      status = PCAP_WARNING_PROMISC_NOTSUP;
1234
0
    }
1235
0
  }
1236
1237
  /* copy timeout value */
1238
0
  handlep->timeout = handle->opt.timeout;
1239
1240
  /*
1241
   * If we're in promiscuous mode, then we probably want
1242
   * to see when the interface drops packets too, so get an
1243
   * initial count from
1244
   * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1245
   */
1246
0
  if (handle->opt.promisc)
1247
0
    handlep->sysfs_dropped = linux_if_drops(handlep->device);
1248
1249
  /*
1250
   * If the "any" device is specified, try to open a SOCK_DGRAM.
1251
   * Otherwise, open a SOCK_RAW.
1252
   */
1253
0
  ret = setup_socket(handle, is_any_device);
1254
0
  if (ret < 0) {
1255
    /*
1256
     * Fatal error; the return value is the error code,
1257
     * and handle->errbuf has been set to an appropriate
1258
     * error message.
1259
     */
1260
0
    status = ret;
1261
0
    goto fail;
1262
0
  }
1263
0
  if (ret > 0) {
1264
    /*
1265
     * We got a warning; return that, as handle->errbuf
1266
     * might have been overwritten by this warning.
1267
     */
1268
0
    status = ret;
1269
0
  }
1270
1271
  /*
1272
   * Success (possibly with a warning).
1273
   *
1274
   * First, try to allocate an event FD for breakloop, if
1275
   * we're not going to start in non-blocking mode.
1276
   */
1277
0
  if (!handle->opt.nonblock) {
1278
0
    handlep->poll_breakloop_fd = eventfd(0, EFD_NONBLOCK);
1279
0
    if (handlep->poll_breakloop_fd == -1) {
1280
      /*
1281
       * Failed.
1282
       */
1283
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
1284
0
          PCAP_ERRBUF_SIZE, errno, "could not open eventfd");
1285
0
      status = PCAP_ERROR;
1286
0
      goto fail;
1287
0
    }
1288
0
  }
1289
1290
  /*
1291
   * Succeeded.
1292
   * Try to set up memory-mapped access.
1293
   */
1294
0
  ret = setup_mmapped(handle);
1295
0
  if (ret < 0) {
1296
    /*
1297
     * We failed to set up to use it, or the
1298
     * kernel supports it, but we failed to
1299
     * enable it.  The return value is the
1300
     * error status to return and, if it's
1301
     * PCAP_ERROR, handle->errbuf contains
1302
     * the error message.
1303
     */
1304
0
    status = ret;
1305
0
    goto fail;
1306
0
  }
1307
0
  if (ret > 0) {
1308
    /*
1309
     * We got a warning; return that, as handle->errbuf
1310
     * might have been overwritten by this warning.
1311
     */
1312
0
    status = ret;
1313
0
  }
1314
1315
  /*
1316
   * We succeeded.  status has been set to the status to return,
1317
   * which might be 0, or might be a PCAP_WARNING_ value.
1318
   */
1319
  /*
1320
   * Now that we have activated the mmap ring, we can
1321
   * set the correct protocol.
1322
   */
1323
0
  if ((ret = iface_bind(handle->fd, handlep->ifindex,
1324
0
      handle->errbuf, pcap_protocol(handle))) != 0) {
1325
0
    status = ret;
1326
0
    goto fail;
1327
0
  }
1328
1329
0
  handle->inject_op = pcap_inject_linux;
1330
0
  handle->setfilter_op = pcap_setfilter_linux;
1331
0
  handle->setdirection_op = pcap_setdirection_linux;
1332
0
  handle->set_datalink_op = pcap_set_datalink_linux;
1333
0
  handle->setnonblock_op = pcap_setnonblock_linux;
1334
0
  handle->getnonblock_op = pcap_getnonblock_linux;
1335
0
  handle->cleanup_op = pcap_cleanup_linux;
1336
0
  handle->stats_op = pcap_stats_linux;
1337
0
  handle->breakloop_op = pcap_breakloop_linux;
1338
1339
0
  switch (handlep->tp_version) {
1340
1341
0
  case TPACKET_V2:
1342
0
    handle->read_op = pcap_read_linux_mmap_v2;
1343
0
    break;
1344
0
#ifdef HAVE_TPACKET3
1345
0
  case TPACKET_V3:
1346
0
    handle->read_op = pcap_read_linux_mmap_v3;
1347
0
    break;
1348
0
#endif
1349
0
  }
1350
0
  handle->oneshot_callback = pcapint_oneshot_linux;
1351
0
  handle->selectable_fd = handle->fd;
1352
1353
0
  return status;
1354
1355
0
fail:
1356
0
  pcap_cleanup_linux(handle);
1357
0
  return status;
1358
0
}
1359
1360
static int
1361
pcap_set_datalink_linux(pcap_t *handle, int dlt)
1362
0
{
1363
0
  handle->linktype = dlt;
1364
1365
  /*
1366
   * Update the offset at which to insert VLAN tags for the
1367
   * new link-layer type.
1368
   */
1369
0
  set_vlan_offset(handle);
1370
1371
0
  return 0;
1372
0
}
1373
1374
/*
1375
 * linux_check_direction()
1376
 *
1377
 * Do checks based on packet direction.
1378
 */
1379
static inline int
1380
linux_check_direction(const pcap_t *handle, const struct sockaddr_ll *sll)
1381
0
{
1382
0
  struct pcap_linux *handlep = handle->priv;
1383
1384
0
  if (sll->sll_pkttype == PACKET_OUTGOING) {
1385
    /*
1386
     * Outgoing packet.
1387
     * If this is from the loopback device, reject it;
1388
     * we'll see the packet as an incoming packet as well,
1389
     * and we don't want to see it twice.
1390
     */
1391
0
    if (sll->sll_ifindex == handlep->lo_ifindex)
1392
0
      return 0;
1393
1394
    /*
1395
     * If this is an outgoing CAN frame, and the user doesn't
1396
     * want only outgoing packets, reject it; CAN devices
1397
     * and drivers, and the CAN stack, always arrange to
1398
     * loop back transmitted packets, so they also appear
1399
     * as incoming packets.  We don't want duplicate packets,
1400
     * and we can't easily distinguish packets looped back
1401
     * by the CAN layer than those received by the CAN layer,
1402
     * so we eliminate this packet instead.
1403
     *
1404
     * We check whether this is a CAN frame by checking whether
1405
     * the device's hardware type is ARPHRD_CAN.
1406
     */
1407
0
    if (sll->sll_hatype == ARPHRD_CAN &&
1408
0
         handle->direction != PCAP_D_OUT)
1409
0
      return 0;
1410
1411
    /*
1412
     * If the user only wants incoming packets, reject it.
1413
     */
1414
0
    if (handle->direction == PCAP_D_IN)
1415
0
      return 0;
1416
0
  } else {
1417
    /*
1418
     * Incoming packet.
1419
     * If the user only wants outgoing packets, reject it.
1420
     */
1421
0
    if (handle->direction == PCAP_D_OUT)
1422
0
      return 0;
1423
0
  }
1424
0
  return 1;
1425
0
}
1426
1427
/*
1428
 * Check whether the device to which the pcap_t is bound still exists.
1429
 * We do so by asking what address the socket is bound to, and checking
1430
 * whether the ifindex in the address is -1, meaning "that device is gone",
1431
 * or some other value, meaning "that device still exists".
1432
 */
1433
static int
1434
device_still_exists(pcap_t *handle)
1435
0
{
1436
0
  struct pcap_linux *handlep = handle->priv;
1437
0
  struct sockaddr_ll addr;
1438
0
  socklen_t addr_len;
1439
1440
  /*
1441
   * If handlep->ifindex is -1, the socket isn't bound, meaning
1442
   * we're capturing on the "any" device; that device never
1443
   * disappears.  (It should also never be configured down, so
1444
   * we shouldn't even get here, but let's make sure.)
1445
   */
1446
0
  if (handlep->ifindex == -1)
1447
0
    return (1); /* it's still here */
1448
1449
  /*
1450
   * OK, now try to get the address for the socket.
1451
   */
1452
0
  addr_len = sizeof (addr);
1453
0
  if (getsockname(handle->fd, (struct sockaddr *) &addr, &addr_len) == -1) {
1454
    /*
1455
     * Error - report an error and return -1.
1456
     */
1457
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1458
0
        errno, "getsockname failed");
1459
0
    return (-1);
1460
0
  }
1461
0
  if (addr.sll_ifindex == -1) {
1462
    /*
1463
     * This means the device went away.
1464
     */
1465
0
    return (0);
1466
0
  }
1467
1468
  /*
1469
   * The device presumably just went down.
1470
   */
1471
0
  return (1);
1472
0
}
1473
1474
static int
1475
pcap_inject_linux(pcap_t *handle, const void *buf, int size)
1476
0
{
1477
0
  struct pcap_linux *handlep = handle->priv;
1478
0
  int ret;
1479
1480
0
  if (handlep->ifindex == -1) {
1481
    /*
1482
     * We don't support sending on the "any" device.
1483
     */
1484
0
    pcapint_strlcpy(handle->errbuf,
1485
0
        "Sending packets isn't supported on the \"any\" device",
1486
0
        PCAP_ERRBUF_SIZE);
1487
0
    return (-1);
1488
0
  }
1489
1490
0
  if (handlep->cooked) {
1491
    /*
1492
     * We don't support sending on cooked-mode sockets.
1493
     *
1494
     * XXX - how do you send on a bound cooked-mode
1495
     * socket?
1496
     * Is a "sendto()" required there?
1497
     */
1498
0
    pcapint_strlcpy(handle->errbuf,
1499
0
        "Sending packets isn't supported in cooked mode",
1500
0
        PCAP_ERRBUF_SIZE);
1501
0
    return (-1);
1502
0
  }
1503
1504
0
  ret = (int)send(handle->fd, buf, size, 0);
1505
0
  if (ret == -1) {
1506
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1507
0
        errno, "send");
1508
0
    return (-1);
1509
0
  }
1510
0
  return (ret);
1511
0
}
1512
1513
/*
1514
 *  Get the statistics for the given packet capture handle.
1515
 */
1516
static int
1517
pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
1518
0
{
1519
0
  struct pcap_linux *handlep = handle->priv;
1520
0
#ifdef HAVE_TPACKET3
1521
  /*
1522
   * For sockets using TPACKET_V2, the extra stuff at the end
1523
   * of a struct tpacket_stats_v3 will not be filled in, and
1524
   * we don't look at it so this is OK even for those sockets.
1525
   * In addition, the PF_PACKET socket code in the kernel only
1526
   * uses the length parameter to compute how much data to
1527
   * copy out and to indicate how much data was copied out, so
1528
   * it's OK to base it on the size of a struct tpacket_stats.
1529
   *
1530
   * XXX - it's probably OK, in fact, to just use a
1531
   * struct tpacket_stats for V3 sockets, as we don't
1532
   * care about the tp_freeze_q_cnt stat.
1533
   */
1534
0
  struct tpacket_stats_v3 kstats;
1535
#else /* HAVE_TPACKET3 */
1536
  struct tpacket_stats kstats;
1537
#endif /* HAVE_TPACKET3 */
1538
0
  socklen_t len = sizeof (struct tpacket_stats);
1539
1540
0
  long long if_dropped = 0;
1541
1542
  /*
1543
   * To fill in ps_ifdrop, we parse
1544
   * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1545
   * for the numbers
1546
   */
1547
0
  if (handle->opt.promisc)
1548
0
  {
1549
    /*
1550
     * XXX - is there any reason to do this by remembering
1551
     * the last counts value, subtracting it from the
1552
     * current counts value, and adding that to stat.ps_ifdrop,
1553
     * maintaining stat.ps_ifdrop as a count, rather than just
1554
     * saving the *initial* counts value and setting
1555
     * stat.ps_ifdrop to the difference between the current
1556
     * value and the initial value?
1557
     *
1558
     * One reason might be to handle the count wrapping
1559
     * around, on platforms where the count is 32 bits
1560
     * and where you might get more than 2^32 dropped
1561
     * packets; is there any other reason?
1562
     *
1563
     * (We maintain the count as a long long int so that,
1564
     * if the kernel maintains the counts as 64-bit even
1565
     * on 32-bit platforms, we can handle the real count.
1566
     *
1567
     * Unfortunately, we can't report 64-bit counts; we
1568
     * need a better API for reporting statistics, such as
1569
     * one that reports them in a style similar to the
1570
     * pcapng Interface Statistics Block, so that 1) the
1571
     * counts are 64-bit, 2) it's easier to add new statistics
1572
     * without breaking the ABI, and 3) it's easier to
1573
     * indicate to a caller that wants one particular
1574
     * statistic that it's not available by just not supplying
1575
     * it.)
1576
     */
1577
0
    if_dropped = handlep->sysfs_dropped;
1578
0
    handlep->sysfs_dropped = linux_if_drops(handlep->device);
1579
0
    handlep->stat.ps_ifdrop += (u_int)(handlep->sysfs_dropped - if_dropped);
1580
0
  }
1581
1582
  /*
1583
   * Try to get the packet counts from the kernel.
1584
   */
1585
0
  if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
1586
0
      &kstats, &len) > -1) {
1587
    /*
1588
     * "ps_recv" counts only packets that *passed* the
1589
     * filter, not packets that didn't pass the filter.
1590
     * This includes packets later dropped because we
1591
     * ran out of buffer space.
1592
     *
1593
     * "ps_drop" counts packets dropped because we ran
1594
     * out of buffer space.  It doesn't count packets
1595
     * dropped by the interface driver.  It counts only
1596
     * packets that passed the filter.
1597
     *
1598
     * See above for ps_ifdrop.
1599
     *
1600
     * Both statistics include packets not yet read from
1601
     * the kernel by libpcap, and thus not yet seen by
1602
     * the application.
1603
     *
1604
     * In "linux/net/packet/af_packet.c", at least in 2.6.27
1605
     * through 5.6 kernels, "tp_packets" is incremented for
1606
     * every packet that passes the packet filter *and* is
1607
     * successfully copied to the ring buffer; "tp_drops" is
1608
     * incremented for every packet dropped because there's
1609
     * not enough free space in the ring buffer.
1610
     *
1611
     * When the statistics are returned for a PACKET_STATISTICS
1612
     * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1613
     * so that "tp_packets" counts all packets handed to
1614
     * the PF_PACKET socket, including packets dropped because
1615
     * there wasn't room on the socket buffer - but not
1616
     * including packets that didn't pass the filter.
1617
     *
1618
     * In the BSD BPF, the count of received packets is
1619
     * incremented for every packet handed to BPF, regardless
1620
     * of whether it passed the filter.
1621
     *
1622
     * We can't make "pcap_stats()" work the same on both
1623
     * platforms, but the best approximation is to return
1624
     * "tp_packets" as the count of packets and "tp_drops"
1625
     * as the count of drops.
1626
     *
1627
     * Keep a running total because each call to
1628
     *    getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1629
     * resets the counters to zero.
1630
     */
1631
0
    handlep->stat.ps_recv += kstats.tp_packets;
1632
0
    handlep->stat.ps_drop += kstats.tp_drops;
1633
0
    *stats = handlep->stat;
1634
0
    return 0;
1635
0
  }
1636
1637
0
  pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE, errno,
1638
0
      "failed to get statistics from socket");
1639
0
  return -1;
1640
0
}
1641
1642
/*
1643
 * A PF_PACKET socket can be bound to any network interface.
1644
 */
1645
static int
1646
can_be_bound(const char *name _U_)
1647
0
{
1648
0
  return (1);
1649
0
}
1650
1651
/*
1652
 * Get a socket to use with various interface ioctls.
1653
 */
1654
static int
1655
get_if_ioctl_socket(void)
1656
0
{
1657
0
  int fd;
1658
1659
  /*
1660
   * This is a bit ugly.
1661
   *
1662
   * There isn't a socket type that's guaranteed to work.
1663
   *
1664
   * AF_NETLINK will work *if* you have Netlink configured into the
1665
   * kernel (can it be configured out if you have any networking
1666
   * support at all?) *and* if you're running a sufficiently recent
1667
   * kernel, but not all the kernels we support are sufficiently
1668
   * recent - that feature was introduced in Linux 4.6.
1669
   *
1670
   * AF_UNIX will work *if* you have UNIX-domain sockets configured
1671
   * into the kernel and *if* you're not on a system that doesn't
1672
   * allow them - some SELinux systems don't allow you create them.
1673
   * Most systems probably have them configured in, but not all systems
1674
   * have them configured in and allow them to be created.
1675
   *
1676
   * AF_INET will work *if* you have IPv4 configured into the kernel,
1677
   * but, apparently, some systems have network adapters but have
1678
   * kernels without IPv4 support.
1679
   *
1680
   * AF_INET6 will work *if* you have IPv6 configured into the
1681
   * kernel, but if you don't have AF_INET, you might not have
1682
   * AF_INET6, either (that is, independently on its own grounds).
1683
   *
1684
   * AF_PACKET would work, except that some of these calls should
1685
   * work even if you *don't* have capture permission (you should be
1686
   * able to enumerate interfaces and get information about them
1687
   * without capture permission; you shouldn't get a failure until
1688
   * you try pcap_activate()).  (If you don't allow programs to
1689
   * get as much information as possible about interfaces if you
1690
   * don't have permission to capture, you run the risk of users
1691
   * asking "why isn't it showing XXX" - or, worse, if you don't
1692
   * show interfaces *at all* if you don't have permission to
1693
   * capture on them, "why do no interfaces show up?" - when the
1694
   * real problem is a permissions problem.  Error reports of that
1695
   * type require a lot more back-and-forth to debug, as evidenced
1696
   * by many Wireshark bugs/mailing list questions/Q&A questions.)
1697
   *
1698
   * So:
1699
   *
1700
   * we first try an AF_NETLINK socket, where "try" includes
1701
   * "try to do a device ioctl on it", as, in the future, once
1702
   * pre-4.6 kernels are sufficiently rare, that will probably
1703
   * be the mechanism most likely to work;
1704
   *
1705
   * if that fails, we try an AF_UNIX socket, as that's less
1706
   * likely to be configured out on a networking-capable system
1707
   * than is IP;
1708
   *
1709
   * if that fails, we try an AF_INET6 socket;
1710
   *
1711
   * if that fails, we try an AF_INET socket.
1712
   */
1713
0
  fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
1714
0
  if (fd != -1) {
1715
    /*
1716
     * OK, let's make sure we can do an SIOCGIFNAME
1717
     * ioctl.
1718
     */
1719
0
    struct ifreq ifr;
1720
1721
0
    memset(&ifr, 0, sizeof(ifr));
1722
0
    if (ioctl(fd, SIOCGIFNAME, &ifr) == 0 ||
1723
0
        errno != EOPNOTSUPP) {
1724
      /*
1725
       * It succeeded, or failed for some reason
1726
       * other than "netlink sockets don't support
1727
       * device ioctls".  Go with the AF_NETLINK
1728
       * socket.
1729
       */
1730
0
      return (fd);
1731
0
    }
1732
1733
    /*
1734
     * OK, that didn't work, so it's as bad as "netlink
1735
     * sockets aren't available".  Close the socket and
1736
     * drive on.
1737
     */
1738
0
    close(fd);
1739
0
  }
1740
1741
  /*
1742
   * Now try an AF_UNIX socket.
1743
   */
1744
0
  fd = socket(AF_UNIX, SOCK_RAW, 0);
1745
0
  if (fd != -1) {
1746
    /*
1747
     * OK, we got it!
1748
     */
1749
0
    return (fd);
1750
0
  }
1751
1752
  /*
1753
   * Now try an AF_INET6 socket.
1754
   */
1755
0
  fd = socket(AF_INET6, SOCK_DGRAM, 0);
1756
0
  if (fd != -1) {
1757
0
    return (fd);
1758
0
  }
1759
1760
  /*
1761
   * Now try an AF_INET socket.
1762
   *
1763
   * XXX - if that fails, is there anything else we should try?
1764
   * AF_CAN, for embedded systems in vehicles, in case they're
1765
   * built without Internet protocol support?  Any other socket
1766
   * types popular in non-Internet embedded systems?
1767
   */
1768
0
  return (socket(AF_INET, SOCK_DGRAM, 0));
1769
0
}
1770
1771
/*
1772
 * Get additional flags for a device, using SIOCETHTOOL.
1773
 */
1774
static int
1775
get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
1776
0
{
1777
0
  int sock;
1778
0
  FILE *fh;
1779
0
  unsigned int arptype = ARPHRD_VOID;
1780
0
  struct ifreq ifr;
1781
0
  struct ethtool_value info;
1782
1783
0
  if (*flags & PCAP_IF_LOOPBACK) {
1784
    /*
1785
     * Loopback devices aren't wireless, and "connected"/
1786
     * "disconnected" doesn't apply to them.
1787
     */
1788
0
    *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1789
0
    return 0;
1790
0
  }
1791
1792
0
  sock = get_if_ioctl_socket();
1793
0
  if (sock == -1) {
1794
0
    pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno,
1795
0
        "Can't create socket to get ethtool information for %s",
1796
0
        name);
1797
0
    return -1;
1798
0
  }
1799
1800
  /*
1801
   * OK, what type of network is this?
1802
   * In particular, is it wired or wireless?
1803
   */
1804
0
  if (is_wifi(name)) {
1805
    /*
1806
     * Wi-Fi, hence wireless.
1807
     */
1808
0
    *flags |= PCAP_IF_WIRELESS;
1809
0
  } else {
1810
    /*
1811
     * OK, what does /sys/class/net/{if_name}/type contain?
1812
     * (We don't use that for Wi-Fi, as it'll report
1813
     * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
1814
     * mode devices.)
1815
     */
1816
0
    char *pathstr;
1817
1818
0
    if (asprintf(&pathstr, "/sys/class/net/%s/type", name) == -1) {
1819
0
      snprintf(errbuf, PCAP_ERRBUF_SIZE,
1820
0
          "%s: Can't generate path name string for /sys/class/net device",
1821
0
          name);
1822
0
      close(sock);
1823
0
      return -1;
1824
0
    }
1825
0
    fh = fopen(pathstr, "r");
1826
0
    if (fh != NULL) {
1827
0
      if (fscanf(fh, "%u", &arptype) == 1) {
1828
        /*
1829
         * OK, we got an ARPHRD_ type; what is it?
1830
         */
1831
0
        switch (arptype) {
1832
1833
0
        case ARPHRD_LOOPBACK:
1834
          /*
1835
           * These are types to which
1836
           * "connected" and "disconnected"
1837
           * don't apply, so don't bother
1838
           * asking about it.
1839
           *
1840
           * XXX - add other types?
1841
           */
1842
0
          close(sock);
1843
0
          fclose(fh);
1844
0
          free(pathstr);
1845
0
          return 0;
1846
1847
0
        case ARPHRD_IRDA:
1848
0
        case ARPHRD_IEEE80211:
1849
0
        case ARPHRD_IEEE80211_PRISM:
1850
0
        case ARPHRD_IEEE80211_RADIOTAP:
1851
0
        case ARPHRD_IEEE802154:
1852
0
        case ARPHRD_IEEE802154_MONITOR:
1853
0
        case ARPHRD_6LOWPAN:
1854
          /*
1855
           * Various wireless types.
1856
           */
1857
0
          *flags |= PCAP_IF_WIRELESS;
1858
0
          break;
1859
0
        }
1860
0
      }
1861
0
      fclose(fh);
1862
0
    }
1863
0
    free(pathstr);
1864
0
  }
1865
1866
0
#ifdef ETHTOOL_GLINK
1867
0
  memset(&ifr, 0, sizeof(ifr));
1868
0
  pcapint_strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1869
0
  info.cmd = ETHTOOL_GLINK;
1870
  /*
1871
   * XXX - while Valgrind handles SIOCETHTOOL and knows that
1872
   * the ETHTOOL_GLINK command sets the .data member of the
1873
   * structure, Memory Sanitizer doesn't yet do so:
1874
   *
1875
   *    https://bugs.llvm.org/show_bug.cgi?id=45814
1876
   *
1877
   * For now, we zero it out to squelch warnings; if the bug
1878
   * in question is fixed, we can remove this.
1879
   */
1880
0
  info.data = 0;
1881
0
  ifr.ifr_data = (caddr_t)&info;
1882
0
  if (ioctl(sock, SIOCETHTOOL, &ifr) == -1) {
1883
0
    int save_errno = errno;
1884
1885
0
    switch (save_errno) {
1886
1887
0
    case EOPNOTSUPP:
1888
0
    case EINVAL:
1889
      /*
1890
       * OK, this OS version or driver doesn't support
1891
       * asking for this information.
1892
       * XXX - distinguish between "this doesn't
1893
       * support ethtool at all because it's not
1894
       * that type of device" vs. "this doesn't
1895
       * support ethtool even though it's that
1896
       * type of device", and return "unknown".
1897
       */
1898
0
      *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1899
0
      close(sock);
1900
0
      return 0;
1901
1902
0
    case ENODEV:
1903
      /*
1904
       * OK, no such device.
1905
       * The user will find that out when they try to
1906
       * activate the device; just say "OK" and
1907
       * don't set anything.
1908
       */
1909
0
      close(sock);
1910
0
      return 0;
1911
1912
0
    case EPERM:
1913
      /*
1914
       * OK, this version of the kernel requires
1915
       * CAP_NET_ADMIN privileges for this, and
1916
       * we don't have those privileges.
1917
       *
1918
       * Just leave it as PCAP_IF_CONNECTION_STATUS_UNKNOWN,
1919
       * as we can't determine the status; just say "OK" and
1920
       * don't set anything.
1921
       */
1922
0
      close(sock);
1923
0
      return 0;
1924
1925
0
    default:
1926
      /*
1927
       * Other error.
1928
       */
1929
0
      pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1930
0
          save_errno,
1931
0
          "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
1932
0
          name);
1933
0
      close(sock);
1934
0
      return -1;
1935
0
    }
1936
0
  }
1937
1938
  /*
1939
   * Is it connected?
1940
   */
1941
0
  if (info.data) {
1942
    /*
1943
     * It's connected.
1944
     */
1945
0
    *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
1946
0
  } else {
1947
    /*
1948
     * It's disconnected.
1949
     */
1950
0
    *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
1951
0
  }
1952
0
#endif
1953
1954
0
  close(sock);
1955
1956
#ifdef HAVE_SNF_API
1957
  // For "down" SNF devices the SNF API makes the flags more relevant.
1958
  if (arptype == ARPHRD_ETHER &&
1959
      ! (*flags & PCAP_IF_UP) &&
1960
      snf_get_if_flags(name, flags, errbuf) < 0)
1961
    return PCAP_ERROR;
1962
#endif // HAVE_SNF_API
1963
1964
0
  return 0;
1965
0
}
1966
1967
int
1968
pcapint_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
1969
0
{
1970
  /*
1971
   * Get the list of regular interfaces first.
1972
   */
1973
0
  if (pcapint_findalldevs_interfaces(devlistp, errbuf, can_be_bound,
1974
0
      get_if_flags) == -1)
1975
0
    return (-1); /* failure */
1976
1977
  /*
1978
   * Add the "any" device.
1979
   */
1980
0
  if (pcapint_add_any_dev(devlistp, errbuf) == NULL)
1981
0
    return (-1);
1982
1983
0
  return (0);
1984
0
}
1985
1986
/*
1987
 * Set direction flag: Which packets do we accept on a forwarding
1988
 * single device? IN, OUT or both?
1989
 */
1990
static int
1991
pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
1992
0
{
1993
  /*
1994
   * It's guaranteed, at this point, that d is a valid
1995
   * direction value.
1996
   */
1997
0
  handle->direction = d;
1998
0
  return 0;
1999
0
}
2000
2001
static int
2002
is_wifi(const char *device)
2003
0
{
2004
0
  char *pathstr;
2005
0
  struct stat statb;
2006
2007
  /*
2008
   * See if there's a sysfs wireless directory for it.
2009
   * If so, it's a wireless interface.
2010
   */
2011
0
  if (asprintf(&pathstr, "/sys/class/net/%s/wireless", device) == -1) {
2012
    /*
2013
     * Just give up here.
2014
     */
2015
0
    return 0;
2016
0
  }
2017
0
  if (stat(pathstr, &statb) == 0) {
2018
0
    free(pathstr);
2019
0
    return 1;
2020
0
  }
2021
0
  free(pathstr);
2022
2023
0
  return 0;
2024
0
}
2025
2026
/*
2027
 *  Linux uses the ARP hardware type to identify the type of an
2028
 *  interface. pcap uses the DLT_xxx constants for this. This
2029
 *  function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2030
 *  constant, as arguments, and sets "handle->linktype" to the
2031
 *  appropriate DLT_XXX constant and sets "handle->offset" to
2032
 *  the appropriate value (to make "handle->offset" plus link-layer
2033
 *  header length be a multiple of 4, so that the link-layer payload
2034
 *  will be aligned on a 4-byte boundary when capturing packets).
2035
 *  (If the offset isn't set here, it'll be 0; add code as appropriate
2036
 *  for cases where it shouldn't be 0.)
2037
 *
2038
 *  If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2039
 *  in cooked mode; otherwise, we can't use cooked mode, so we have
2040
 *  to pick some type that works in raw mode, or fail.
2041
 *
2042
 *  Sets the link type to -1 if unable to map the type.
2043
 *
2044
 *  Returns 0 on success or a PCAP_ERROR_ value on error.
2045
 */
2046
static int map_arphrd_to_dlt(pcap_t *handle, int arptype,
2047
           const char *device, int cooked_ok)
2048
0
{
2049
0
  static const char cdma_rmnet[] = "cdma_rmnet";
2050
2051
0
  switch (arptype) {
2052
2053
0
  case ARPHRD_ETHER:
2054
    /*
2055
     * For various annoying reasons having to do with DHCP
2056
     * software, some versions of Android give the mobile-
2057
     * phone-network interface an ARPHRD_ value of
2058
     * ARPHRD_ETHER, even though the packets supplied by
2059
     * that interface have no link-layer header, and begin
2060
     * with an IP header, so that the ARPHRD_ value should
2061
     * be ARPHRD_NONE.
2062
     *
2063
     * Detect those devices by checking the device name, and
2064
     * use DLT_RAW for them.
2065
     */
2066
0
    if (strncmp(device, cdma_rmnet, sizeof cdma_rmnet - 1) == 0) {
2067
0
      handle->linktype = DLT_RAW;
2068
0
      return 0;
2069
0
    }
2070
2071
    /*
2072
     * Is this a real Ethernet device?  If so, give it a
2073
     * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2074
     * that an application can let you choose it, in case you're
2075
     * capturing DOCSIS traffic that a Cisco Cable Modem
2076
     * Termination System is putting out onto an Ethernet (it
2077
     * doesn't put an Ethernet header onto the wire, it puts raw
2078
     * DOCSIS frames out on the wire inside the low-level
2079
     * Ethernet framing).
2080
     *
2081
     * XXX - are there any other sorts of "fake Ethernet" that
2082
     * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
2083
     * a Cisco CMTS won't put traffic onto it or get traffic
2084
     * bridged onto it?  ISDN is handled in "setup_socket()",
2085
     * as we fall back on cooked mode there, and we use
2086
     * is_wifi() to check for 802.11 devices; are there any
2087
     * others?
2088
     */
2089
0
    if (!is_wifi(device)) {
2090
0
      int ret;
2091
2092
      /*
2093
       * This is not a Wi-Fi device but it could be
2094
       * a DSA master/management network device.
2095
       */
2096
0
      ret = iface_dsa_get_proto_info(device, handle);
2097
0
      if (ret < 0)
2098
0
        return ret;
2099
2100
0
      if (ret == 1) {
2101
        /*
2102
         * This is a DSA master/management network
2103
         * device, linktype is already set by
2104
         * iface_dsa_get_proto_info(), set an
2105
         * appropriate offset here.
2106
         */
2107
0
        handle->offset = 2;
2108
0
        break;
2109
0
      }
2110
2111
      /*
2112
       * It's not a Wi-Fi device; offer DOCSIS.
2113
       */
2114
0
      handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2115
0
      if (handle->dlt_list == NULL) {
2116
0
        pcapint_fmt_errmsg_for_errno(handle->errbuf,
2117
0
            PCAP_ERRBUF_SIZE, errno, "malloc");
2118
0
        return (PCAP_ERROR);
2119
0
      }
2120
0
      handle->dlt_list[0] = DLT_EN10MB;
2121
0
      handle->dlt_list[1] = DLT_DOCSIS;
2122
0
      handle->dlt_count = 2;
2123
0
    }
2124
    /* FALLTHROUGH */
2125
2126
0
  case ARPHRD_METRICOM:
2127
0
  case ARPHRD_LOOPBACK:
2128
0
    handle->linktype = DLT_EN10MB;
2129
0
    handle->offset = 2;
2130
0
    break;
2131
2132
0
  case ARPHRD_EETHER:
2133
0
    handle->linktype = DLT_EN3MB;
2134
0
    break;
2135
2136
0
  case ARPHRD_AX25:
2137
0
    handle->linktype = DLT_AX25_KISS;
2138
0
    break;
2139
2140
0
  case ARPHRD_PRONET:
2141
0
    handle->linktype = DLT_PRONET;
2142
0
    break;
2143
2144
0
  case ARPHRD_CHAOS:
2145
0
    handle->linktype = DLT_CHAOS;
2146
0
    break;
2147
2148
0
  case ARPHRD_CAN:
2149
0
    handle->linktype = DLT_CAN_SOCKETCAN;
2150
0
    break;
2151
2152
0
  case ARPHRD_IEEE802_TR:
2153
0
  case ARPHRD_IEEE802:
2154
0
    handle->linktype = DLT_IEEE802;
2155
0
    handle->offset = 2;
2156
0
    break;
2157
2158
0
  case ARPHRD_ARCNET:
2159
0
    handle->linktype = DLT_ARCNET_LINUX;
2160
0
    break;
2161
2162
0
  case ARPHRD_FDDI:
2163
0
    handle->linktype = DLT_FDDI;
2164
0
    handle->offset = 3;
2165
0
    break;
2166
2167
0
  case ARPHRD_ATM:
2168
    /*
2169
     * The Classical IP implementation in ATM for Linux
2170
     * supports both what RFC 1483 calls "LLC Encapsulation",
2171
     * in which each packet has an LLC header, possibly
2172
     * with a SNAP header as well, prepended to it, and
2173
     * what RFC 1483 calls "VC Based Multiplexing", in which
2174
     * different virtual circuits carry different network
2175
     * layer protocols, and no header is prepended to packets.
2176
     *
2177
     * They both have an ARPHRD_ type of ARPHRD_ATM, so
2178
     * you can't use the ARPHRD_ type to find out whether
2179
     * captured packets will have an LLC header, and,
2180
     * while there's a socket ioctl to *set* the encapsulation
2181
     * type, there's no ioctl to *get* the encapsulation type.
2182
     *
2183
     * This means that
2184
     *
2185
     *  programs that dissect Linux Classical IP frames
2186
     *  would have to check for an LLC header and,
2187
     *  depending on whether they see one or not, dissect
2188
     *  the frame as LLC-encapsulated or as raw IP (I
2189
     *  don't know whether there's any traffic other than
2190
     *  IP that would show up on the socket, or whether
2191
     *  there's any support for IPv6 in the Linux
2192
     *  Classical IP code);
2193
     *
2194
     *  filter expressions would have to compile into
2195
     *  code that checks for an LLC header and does
2196
     *  the right thing.
2197
     *
2198
     * Both of those are a nuisance - and, at least on systems
2199
     * that support PF_PACKET sockets, we don't have to put
2200
     * up with those nuisances; instead, we can just capture
2201
     * in cooked mode.  That's what we'll do, if we can.
2202
     * Otherwise, we'll just fail.
2203
     */
2204
0
    if (cooked_ok)
2205
0
      handle->linktype = DLT_LINUX_SLL;
2206
0
    else
2207
0
      handle->linktype = -1;
2208
0
    break;
2209
2210
0
  case ARPHRD_IEEE80211:
2211
0
    handle->linktype = DLT_IEEE802_11;
2212
0
    break;
2213
2214
0
  case ARPHRD_IEEE80211_PRISM:
2215
0
    handle->linktype = DLT_PRISM_HEADER;
2216
0
    break;
2217
2218
0
  case ARPHRD_IEEE80211_RADIOTAP:
2219
0
    handle->linktype = DLT_IEEE802_11_RADIO;
2220
0
    break;
2221
2222
0
  case ARPHRD_PPP:
2223
    /*
2224
     * Some PPP code in the kernel supplies no link-layer
2225
     * header whatsoever to PF_PACKET sockets; other PPP
2226
     * code supplies PPP link-layer headers ("syncppp.c");
2227
     * some PPP code might supply random link-layer
2228
     * headers (PPP over ISDN - there's code in Wireshark,
2229
     * for example, to cope with PPP-over-ISDN captures
2230
     * with which the Wireshark developers have had to cope,
2231
     * heuristically trying to determine which of the
2232
     * oddball link-layer headers particular packets have).
2233
     *
2234
     * As such, we just punt, and run all PPP interfaces
2235
     * in cooked mode, if we can; otherwise, we just treat
2236
     * it as DLT_RAW, for now - if somebody needs to capture,
2237
     * on a 2.0[.x] kernel, on PPP devices that supply a
2238
     * link-layer header, they'll have to add code here to
2239
     * map to the appropriate DLT_ type (possibly adding a
2240
     * new DLT_ type, if necessary).
2241
     */
2242
0
    if (cooked_ok)
2243
0
      handle->linktype = DLT_LINUX_SLL;
2244
0
    else {
2245
      /*
2246
       * XXX - handle ISDN types here?  We can't fall
2247
       * back on cooked sockets, so we'd have to
2248
       * figure out from the device name what type of
2249
       * link-layer encapsulation it's using, and map
2250
       * that to an appropriate DLT_ value, meaning
2251
       * we'd map "isdnN" devices to DLT_RAW (they
2252
       * supply raw IP packets with no link-layer
2253
       * header) and "isdY" devices to a new DLT_I4L_IP
2254
       * type that has only an Ethernet packet type as
2255
       * a link-layer header.
2256
       *
2257
       * But sometimes we seem to get random crap
2258
       * in the link-layer header when capturing on
2259
       * ISDN devices....
2260
       */
2261
0
      handle->linktype = DLT_RAW;
2262
0
    }
2263
0
    break;
2264
2265
0
  case ARPHRD_CISCO:
2266
0
    handle->linktype = DLT_C_HDLC;
2267
0
    break;
2268
2269
  /* Not sure if this is correct for all tunnels, but it
2270
   * works for CIPE */
2271
0
  case ARPHRD_TUNNEL:
2272
0
  case ARPHRD_SIT:
2273
0
  case ARPHRD_CSLIP:
2274
0
  case ARPHRD_SLIP6:
2275
0
  case ARPHRD_CSLIP6:
2276
0
  case ARPHRD_ADAPT:
2277
0
  case ARPHRD_SLIP:
2278
0
  case ARPHRD_RAWHDLC:
2279
0
  case ARPHRD_DLCI:
2280
    /*
2281
     * XXX - should some of those be mapped to DLT_LINUX_SLL
2282
     * instead?  Should we just map all of them to DLT_LINUX_SLL?
2283
     */
2284
0
    handle->linktype = DLT_RAW;
2285
0
    break;
2286
2287
0
  case ARPHRD_FRAD:
2288
0
    handle->linktype = DLT_FRELAY;
2289
0
    break;
2290
2291
0
  case ARPHRD_LOCALTLK:
2292
0
    handle->linktype = DLT_LTALK;
2293
0
    break;
2294
2295
0
  case 18:
2296
    /*
2297
     * RFC 4338 defines an encapsulation for IP and ARP
2298
     * packets that's compatible with the RFC 2625
2299
     * encapsulation, but that uses a different ARP
2300
     * hardware type and hardware addresses.  That
2301
     * ARP hardware type is 18; Linux doesn't define
2302
     * any ARPHRD_ value as 18, but if it ever officially
2303
     * supports RFC 4338-style IP-over-FC, it should define
2304
     * one.
2305
     *
2306
     * For now, we map it to DLT_IP_OVER_FC, in the hopes
2307
     * that this will encourage its use in the future,
2308
     * should Linux ever officially support RFC 4338-style
2309
     * IP-over-FC.
2310
     */
2311
0
    handle->linktype = DLT_IP_OVER_FC;
2312
0
    break;
2313
2314
0
  case ARPHRD_FCPP:
2315
0
  case ARPHRD_FCAL:
2316
0
  case ARPHRD_FCPL:
2317
0
  case ARPHRD_FCFABRIC:
2318
    /*
2319
     * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2320
     * IP-over-FC:
2321
     *
2322
     *  https://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2323
     *
2324
     * and one was assigned.
2325
     *
2326
     * In a later private discussion (spun off from a message
2327
     * on the ethereal-users list) on how to get that DLT_
2328
     * value in libpcap on Linux, I ended up deciding that
2329
     * the best thing to do would be to have him tweak the
2330
     * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2331
     * type, and map all those types to DLT_IP_OVER_FC:
2332
     *
2333
     *  I've checked into the libpcap and tcpdump CVS tree
2334
     *  support for DLT_IP_OVER_FC.  In order to use that,
2335
     *  you'd have to modify your modified driver to return
2336
     *  one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2337
     *  change it to set "dev->type" to ARPHRD_FCFABRIC, for
2338
     *  example (the exact value doesn't matter, it can be
2339
     *  any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2340
     *  ARPHRD_FCFABRIC).
2341
     *
2342
     * 11 years later, Christian Svensson wanted to map
2343
     * various ARPHRD_ values to DLT_FC_2 and
2344
     * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2345
     * frames:
2346
     *
2347
     *  https://github.com/mcr/libpcap/pull/29
2348
     *
2349
     * There don't seem to be any network drivers that use
2350
     * any of the ARPHRD_FC* values for IP-over-FC, and
2351
     * it's not exactly clear what the "Dummy types for non
2352
     * ARP hardware" are supposed to mean (link-layer
2353
     * header type?  Physical network type?), so it's
2354
     * not exactly clear why the ARPHRD_FC* types exist
2355
     * in the first place.
2356
     *
2357
     * For now, we map them to DLT_FC_2, and provide an
2358
     * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
2359
     * DLT_IP_OVER_FC just in case there's some old
2360
     * driver out there that uses one of those types for
2361
     * IP-over-FC on which somebody wants to capture
2362
     * packets.
2363
     */
2364
0
    handle->linktype = DLT_FC_2;
2365
0
    handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 3);
2366
0
    if (handle->dlt_list == NULL) {
2367
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
2368
0
          PCAP_ERRBUF_SIZE, errno, "malloc");
2369
0
      return (PCAP_ERROR);
2370
0
    }
2371
0
    handle->dlt_list[0] = DLT_FC_2;
2372
0
    handle->dlt_list[1] = DLT_FC_2_WITH_FRAME_DELIMS;
2373
0
    handle->dlt_list[2] = DLT_IP_OVER_FC;
2374
0
    handle->dlt_count = 3;
2375
0
    break;
2376
2377
0
  case ARPHRD_IRDA:
2378
    /* Don't expect IP packet out of this interfaces... */
2379
0
    handle->linktype = DLT_LINUX_IRDA;
2380
    /* We need to save packet direction for IrDA decoding,
2381
     * so let's use "Linux-cooked" mode. Jean II
2382
     *
2383
     * XXX - this is handled in setup_socket(). */
2384
    /* handlep->cooked = 1; */
2385
0
    break;
2386
2387
0
  case ARPHRD_LAPD:
2388
    /* Don't expect IP packet out of this interfaces... */
2389
0
    handle->linktype = DLT_LINUX_LAPD;
2390
0
    break;
2391
2392
0
  case ARPHRD_NONE:
2393
    /*
2394
     * No link-layer header; packets are just IP
2395
     * packets, so use DLT_RAW.
2396
     */
2397
0
    handle->linktype = DLT_RAW;
2398
0
    break;
2399
2400
0
  case ARPHRD_IEEE802154:
2401
0
    handle->linktype = DLT_IEEE802_15_4_NOFCS;
2402
0
    break;
2403
2404
0
  case ARPHRD_NETLINK:
2405
0
    handle->linktype = DLT_NETLINK;
2406
    /*
2407
     * We need to use cooked mode, so that in sll_protocol we
2408
     * pick up the netlink protocol type such as NETLINK_ROUTE,
2409
     * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
2410
     *
2411
     * XXX - this is handled in setup_socket().
2412
     */
2413
    /* handlep->cooked = 1; */
2414
0
    break;
2415
2416
0
  case ARPHRD_VSOCKMON:
2417
0
    handle->linktype = DLT_VSOCK;
2418
0
    break;
2419
2420
0
  default:
2421
0
    handle->linktype = -1;
2422
0
    break;
2423
0
  }
2424
0
  return (0);
2425
0
}
2426
2427
/*
2428
 * Try to set up a PF_PACKET socket.
2429
 * Returns 0 or a PCAP_WARNING_ value on success and a PCAP_ERROR_ value
2430
 * on failure.
2431
 */
2432
static int
2433
setup_socket(pcap_t *handle, int is_any_device)
2434
0
{
2435
0
  struct pcap_linux *handlep = handle->priv;
2436
0
  const char    *device = handle->opt.device;
2437
0
  int     status = 0;
2438
0
  int     sock_fd, arptype;
2439
0
  int     val;
2440
0
  int     err = 0;
2441
0
  struct packet_mreq  mr;
2442
2443
  /*
2444
   * Open a socket with protocol family packet. If cooked is true,
2445
   * we open a SOCK_DGRAM socket for the cooked interface, otherwise
2446
   * we open a SOCK_RAW socket for the raw interface.
2447
   *
2448
   * The protocol is set to 0.  This means we will receive no
2449
   * packets until we "bind" the socket with a non-zero
2450
   * protocol.  This allows us to setup the ring buffers without
2451
   * dropping any packets.
2452
   */
2453
0
  sock_fd = is_any_device ?
2454
0
    socket(PF_PACKET, SOCK_DGRAM, 0) :
2455
0
    socket(PF_PACKET, SOCK_RAW, 0);
2456
2457
0
  if (sock_fd == -1) {
2458
0
    if (errno == EPERM || errno == EACCES) {
2459
      /*
2460
       * You don't have permission to open the
2461
       * socket.
2462
       */
2463
0
      status = PCAP_ERROR_PERM_DENIED;
2464
0
      snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2465
0
          "Attempt to create packet socket failed - CAP_NET_RAW may be required");
2466
0
    } else if (errno == EAFNOSUPPORT) {
2467
      /*
2468
       * PF_PACKET sockets not supported.
2469
       * Perhaps we're running on the WSL1 module
2470
       * in the Windows NT kernel rather than on
2471
       * a real Linux kernel.
2472
       */
2473
0
      status = PCAP_ERROR_CAPTURE_NOTSUP;
2474
0
      snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2475
0
          "PF_PACKET sockets not supported - is this WSL1?");
2476
0
    } else {
2477
      /*
2478
       * Other error.
2479
       */
2480
0
      status = PCAP_ERROR;
2481
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
2482
0
          PCAP_ERRBUF_SIZE, errno, "socket");
2483
0
    }
2484
0
    return status;
2485
0
  }
2486
2487
  /*
2488
   * Get the interface index of the loopback device.
2489
   * If the attempt fails, don't fail, just set the
2490
   * "handlep->lo_ifindex" to -1.
2491
   *
2492
   * XXX - can there be more than one device that loops
2493
   * packets back, i.e. devices other than "lo"?  If so,
2494
   * we'd need to find them all, and have an array of
2495
   * indices for them, and check all of them in
2496
   * "pcap_read_packet()".
2497
   */
2498
0
  handlep->lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
2499
2500
  /*
2501
   * Default value for offset to align link-layer payload
2502
   * on a 4-byte boundary.
2503
   */
2504
0
  handle->offset   = 0;
2505
2506
  /*
2507
   * What kind of frames do we have to deal with? Fall back
2508
   * to cooked mode if we have an unknown interface type
2509
   * or a type we know doesn't work well in raw mode.
2510
   */
2511
0
  if (!is_any_device) {
2512
    /* Assume for now we don't need cooked mode. */
2513
0
    handlep->cooked = 0;
2514
2515
0
    if (handle->opt.rfmon) {
2516
      /*
2517
       * We were asked to turn on monitor mode.
2518
       * Do so before we get the link-layer type,
2519
       * because entering monitor mode could change
2520
       * the link-layer type.
2521
       */
2522
0
      err = enter_rfmon_mode(handle, sock_fd, device);
2523
0
      if (err < 0) {
2524
        /* Hard failure */
2525
0
        close(sock_fd);
2526
0
        return err;
2527
0
      }
2528
0
      if (err == 0) {
2529
        /*
2530
         * Nothing worked for turning monitor mode
2531
         * on.
2532
         */
2533
0
        close(sock_fd);
2534
2535
0
        return PCAP_ERROR_RFMON_NOTSUP;
2536
0
      }
2537
2538
      /*
2539
       * Either monitor mode has been turned on for
2540
       * the device, or we've been given a different
2541
       * device to open for monitor mode.  If we've
2542
       * been given a different device, use it.
2543
       */
2544
0
      if (handlep->mondevice != NULL)
2545
0
        device = handlep->mondevice;
2546
0
    }
2547
0
    arptype = iface_get_arptype(sock_fd, device, handle->errbuf);
2548
0
    if (arptype < 0) {
2549
0
      close(sock_fd);
2550
0
      return arptype;
2551
0
    }
2552
0
    status = map_arphrd_to_dlt(handle, arptype, device, 1);
2553
0
    if (status < 0) {
2554
0
      close(sock_fd);
2555
0
      return status;
2556
0
    }
2557
0
    if (handle->linktype == -1 ||
2558
0
        handle->linktype == DLT_LINUX_SLL ||
2559
0
        handle->linktype == DLT_LINUX_IRDA ||
2560
0
        handle->linktype == DLT_LINUX_LAPD ||
2561
0
        handle->linktype == DLT_NETLINK ||
2562
0
        (handle->linktype == DLT_EN10MB &&
2563
0
         (strncmp("isdn", device, 4) == 0 ||
2564
0
          strncmp("isdY", device, 4) == 0))) {
2565
      /*
2566
       * Unknown interface type (-1), or a
2567
       * device we explicitly chose to run
2568
       * in cooked mode (e.g., PPP devices),
2569
       * or an ISDN device (whose link-layer
2570
       * type we can only determine by using
2571
       * APIs that may be different on different
2572
       * kernels) - reopen in cooked mode.
2573
       *
2574
       * If the type is unknown, return a warning;
2575
       * map_arphrd_to_dlt() has already set the
2576
       * warning message.
2577
       */
2578
0
      if (close(sock_fd) == -1) {
2579
0
        pcapint_fmt_errmsg_for_errno(handle->errbuf,
2580
0
            PCAP_ERRBUF_SIZE, errno, "close");
2581
0
        return PCAP_ERROR;
2582
0
      }
2583
0
      sock_fd = socket(PF_PACKET, SOCK_DGRAM, 0);
2584
0
      if (sock_fd < 0) {
2585
        /*
2586
         * Fatal error.  We treat this as
2587
         * a generic error; we already know
2588
         * that we were able to open a
2589
         * PF_PACKET/SOCK_RAW socket, so
2590
         * any failure is a "this shouldn't
2591
         * happen" case.
2592
         */
2593
0
        pcapint_fmt_errmsg_for_errno(handle->errbuf,
2594
0
            PCAP_ERRBUF_SIZE, errno, "socket");
2595
0
        return PCAP_ERROR;
2596
0
      }
2597
0
      handlep->cooked = 1;
2598
2599
      /*
2600
       * Get rid of any link-layer type list
2601
       * we allocated - this only supports cooked
2602
       * capture.
2603
       */
2604
0
      if (handle->dlt_list != NULL) {
2605
0
        free(handle->dlt_list);
2606
0
        handle->dlt_list = NULL;
2607
0
        handle->dlt_count = 0;
2608
0
      }
2609
2610
0
      if (handle->linktype == -1) {
2611
        /*
2612
         * Warn that we're falling back on
2613
         * cooked mode; we may want to
2614
         * update "map_arphrd_to_dlt()"
2615
         * to handle the new type.
2616
         */
2617
0
        snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2618
0
          "arptype %d not "
2619
0
          "supported by libpcap - "
2620
0
          "falling back to cooked "
2621
0
          "socket",
2622
0
          arptype);
2623
0
        status = PCAP_WARNING;
2624
0
      }
2625
2626
      /*
2627
       * IrDA capture is not a real "cooked" capture,
2628
       * it's IrLAP frames, not IP packets.  The
2629
       * same applies to LAPD capture.
2630
       */
2631
0
      if (handle->linktype != DLT_LINUX_IRDA &&
2632
0
          handle->linktype != DLT_LINUX_LAPD &&
2633
0
          handle->linktype != DLT_NETLINK)
2634
0
        handle->linktype = DLT_LINUX_SLL;
2635
0
    }
2636
2637
0
    handlep->ifindex = iface_get_id(sock_fd, device,
2638
0
        handle->errbuf);
2639
0
    if (handlep->ifindex == -1) {
2640
0
      close(sock_fd);
2641
0
      return PCAP_ERROR;
2642
0
    }
2643
2644
0
    if ((err = iface_bind(sock_fd, handlep->ifindex,
2645
0
        handle->errbuf, 0)) != 0) {
2646
0
      close(sock_fd);
2647
0
      return err;
2648
0
    }
2649
0
  } else {
2650
    /*
2651
     * The "any" device.
2652
     */
2653
0
    if (handle->opt.rfmon) {
2654
      /*
2655
       * It doesn't support monitor mode.
2656
       */
2657
0
      close(sock_fd);
2658
0
      return PCAP_ERROR_RFMON_NOTSUP;
2659
0
    }
2660
2661
    /*
2662
     * It uses cooked mode.
2663
     * Support both DLT_LINUX_SLL and DLT_LINUX_SLL2.
2664
     */
2665
0
    handlep->cooked = 1;
2666
0
    handle->linktype = DLT_LINUX_SLL;
2667
0
    handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2668
0
    if (handle->dlt_list == NULL) {
2669
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
2670
0
          PCAP_ERRBUF_SIZE, errno, "malloc");
2671
0
      close(sock_fd);
2672
0
      return (PCAP_ERROR);
2673
0
    }
2674
0
    handle->dlt_list[0] = DLT_LINUX_SLL;
2675
0
    handle->dlt_list[1] = DLT_LINUX_SLL2;
2676
0
    handle->dlt_count = 2;
2677
2678
    /*
2679
     * We're not bound to a device.
2680
     * For now, we're using this as an indication
2681
     * that we can't transmit; stop doing that only
2682
     * if we figure out how to transmit in cooked
2683
     * mode.
2684
     */
2685
0
    handlep->ifindex = -1;
2686
0
  }
2687
2688
  /*
2689
   * Select promiscuous mode on if "promisc" is set.
2690
   *
2691
   * Do not turn allmulti mode on if we don't select
2692
   * promiscuous mode - on some devices (e.g., Orinoco
2693
   * wireless interfaces), allmulti mode isn't supported
2694
   * and the driver implements it by turning promiscuous
2695
   * mode on, and that screws up the operation of the
2696
   * card as a normal networking interface, and on no
2697
   * other platform I know of does starting a non-
2698
   * promiscuous capture affect which multicast packets
2699
   * are received by the interface.
2700
   */
2701
2702
  /*
2703
   * Hmm, how can we set promiscuous mode on all interfaces?
2704
   * I am not sure if that is possible at all.  For now, we
2705
   * silently ignore attempts to turn promiscuous mode on
2706
   * for the "any" device (so you don't have to explicitly
2707
   * disable it in programs such as tcpdump).
2708
   */
2709
2710
0
  if (!is_any_device && handle->opt.promisc) {
2711
0
    memset(&mr, 0, sizeof(mr));
2712
0
    mr.mr_ifindex = handlep->ifindex;
2713
0
    mr.mr_type    = PACKET_MR_PROMISC;
2714
0
    if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
2715
0
        &mr, sizeof(mr)) == -1) {
2716
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
2717
0
          PCAP_ERRBUF_SIZE, errno, "setsockopt (PACKET_ADD_MEMBERSHIP)");
2718
0
      close(sock_fd);
2719
0
      return PCAP_ERROR;
2720
0
    }
2721
0
  }
2722
2723
  /*
2724
   * Enable auxiliary data and reserve room for reconstructing
2725
   * VLAN headers.
2726
   *
2727
   * XXX - is enabling auxiliary data necessary, now that we
2728
   * only support memory-mapped capture?  The kernel's memory-mapped
2729
   * capture code doesn't seem to check whether auxiliary data
2730
   * is enabled, it seems to provide it whether it is or not.
2731
   */
2732
0
  val = 1;
2733
0
  if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
2734
0
           sizeof(val)) == -1 && errno != ENOPROTOOPT) {
2735
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
2736
0
        errno, "setsockopt (PACKET_AUXDATA)");
2737
0
    close(sock_fd);
2738
0
    return PCAP_ERROR;
2739
0
  }
2740
0
  handle->offset += VLAN_TAG_LEN;
2741
2742
  /*
2743
   * If we're in cooked mode, make the snapshot length
2744
   * large enough to hold a "cooked mode" header plus
2745
   * 1 byte of packet data (so we don't pass a byte
2746
   * count of 0 to "recvfrom()").
2747
   * XXX - we don't know whether this will be DLT_LINUX_SLL
2748
   * or DLT_LINUX_SLL2, so make sure it's big enough for
2749
   * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
2750
   * that small is silly anyway.
2751
   */
2752
0
  if (handlep->cooked) {
2753
0
    if (handle->snapshot < SLL2_HDR_LEN + 1)
2754
0
      handle->snapshot = SLL2_HDR_LEN + 1;
2755
0
  }
2756
0
  handle->bufsize = handle->snapshot;
2757
2758
  /*
2759
   * Set the offset at which to insert VLAN tags.
2760
   */
2761
0
  set_vlan_offset(handle);
2762
2763
0
  if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
2764
0
    int nsec_tstamps = 1;
2765
2766
0
    if (setsockopt(sock_fd, SOL_SOCKET, SO_TIMESTAMPNS, &nsec_tstamps, sizeof(nsec_tstamps)) < 0) {
2767
0
      snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "setsockopt: unable to set SO_TIMESTAMPNS");
2768
0
      close(sock_fd);
2769
0
      return PCAP_ERROR;
2770
0
    }
2771
0
  }
2772
2773
  /*
2774
   * We've succeeded. Save the socket FD in the pcap structure.
2775
   */
2776
0
  handle->fd = sock_fd;
2777
2778
  /*
2779
   * Any supported Linux version implements at least four auxiliary
2780
   * data items (SKF_AD_PROTOCOL, SKF_AD_PKTTYPE, SKF_AD_IFINDEX and
2781
   * SKF_AD_NLATTR).  Set a flag so the code generator can use these
2782
   * items if necessary.
2783
   */
2784
0
  handle->bpf_codegen_flags |= BPF_SPECIAL_BASIC_HANDLING;
2785
2786
  /*
2787
   * Can we generate special code for VLAN checks?
2788
   * (XXX - what if we need the special code but it's not supported
2789
   * by the OS?  Is that possible?)
2790
   *
2791
   * This depends on both a runtime condition (the running Linux kernel
2792
   * must support at least SKF_AD_VLAN_TAG_PRESENT in the auxiliary data
2793
   * and must support SO_BPF_EXTENSIONS in order to tell the userland
2794
   * process what it supports) and a compile-time condition (the OS
2795
   * headers must define both constants in order to compile libpcap code
2796
   * that asks the kernel about the support).
2797
   */
2798
0
#if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2799
0
  int bpf_extensions;
2800
0
  socklen_t len = sizeof(bpf_extensions);
2801
0
  if (getsockopt(sock_fd, SOL_SOCKET, SO_BPF_EXTENSIONS,
2802
0
      &bpf_extensions, &len) == 0) {
2803
0
    if (bpf_extensions >= SKF_AD_VLAN_TAG_PRESENT) {
2804
      /*
2805
       * Yes, we can.  Request that we do so.
2806
       */
2807
0
      handle->bpf_codegen_flags |= BPF_SPECIAL_VLAN_HANDLING;
2808
0
    }
2809
0
  }
2810
0
#endif // defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2811
2812
0
  return status;
2813
0
}
2814
2815
/*
2816
 * Attempt to setup memory-mapped access.
2817
 *
2818
 * On success, returns 0 if there are no warnings or a PCAP_WARNING_ code
2819
 * if there is a warning.
2820
 *
2821
 * On error, returns the appropriate error code; if that is PCAP_ERROR,
2822
 * sets handle->errbuf to the appropriate message.
2823
 */
2824
static int
2825
setup_mmapped(pcap_t *handle)
2826
0
{
2827
0
  struct pcap_linux *handlep = handle->priv;
2828
0
  int flags = MAP_ANONYMOUS | MAP_PRIVATE;
2829
0
  int status;
2830
2831
  /*
2832
   * Attempt to allocate a buffer to hold the contents of one
2833
   * packet, for use by the oneshot callback.
2834
   */
2835
0
#ifdef MAP_32BIT
2836
0
  if (pcapint_mmap_32bit) flags |= MAP_32BIT;
2837
0
#endif
2838
0
  handlep->oneshot_buffer = mmap(0, handle->snapshot, PROT_READ | PROT_WRITE, flags, -1, 0);
2839
0
  if (handlep->oneshot_buffer == MAP_FAILED) {
2840
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
2841
0
        errno, "can't allocate oneshot buffer");
2842
0
    return PCAP_ERROR;
2843
0
  }
2844
2845
0
  if (handle->opt.buffer_size == 0) {
2846
    /* by default request 2M for the ring buffer */
2847
0
    handle->opt.buffer_size = 2*1024*1024;
2848
0
  }
2849
0
  status = prepare_tpacket_socket(handle);
2850
0
  if (status == -1) {
2851
0
    munmap(handlep->oneshot_buffer, handle->snapshot);
2852
0
    handlep->oneshot_buffer = NULL;
2853
0
    return PCAP_ERROR;
2854
0
  }
2855
0
  status = create_ring(handle);
2856
0
  if (status < 0) {
2857
    /*
2858
     * Error attempting to enable memory-mapped capture;
2859
     * fail.  The return value is the status to return.
2860
     */
2861
0
    munmap(handlep->oneshot_buffer, handle->snapshot);
2862
0
    handlep->oneshot_buffer = NULL;
2863
0
    return status;
2864
0
  }
2865
2866
  /*
2867
   * Success.  status has been set either to 0 if there are no
2868
   * warnings or to a PCAP_WARNING_ value if there is a warning.
2869
   *
2870
   * handle->offset is used to get the current position into the rx ring.
2871
   * handle->cc is used to store the ring size.
2872
   */
2873
2874
  /*
2875
   * Set the timeout to use in poll() before returning.
2876
   */
2877
0
  set_poll_timeout(handlep);
2878
2879
0
  return status;
2880
0
}
2881
2882
/*
2883
 * Attempt to set the socket to the specified version of the memory-mapped
2884
 * header.
2885
 *
2886
 * Return 0 if we succeed; return 1 if we fail because that version isn't
2887
 * supported; return -1 on any other error, and set handle->errbuf.
2888
 */
2889
static int
2890
init_tpacket(pcap_t *handle, int version, const char *version_str)
2891
0
{
2892
0
  struct pcap_linux *handlep = handle->priv;
2893
0
  int val = version;
2894
0
  socklen_t len = sizeof(val);
2895
2896
  /*
2897
   * Probe whether kernel supports the specified TPACKET version;
2898
   * this also gets the length of the header for that version.
2899
   *
2900
   * This socket option was introduced in 2.6.27, which was
2901
   * also the first release with TPACKET_V2 support.
2902
   */
2903
0
  if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
2904
0
    if (errno == EINVAL) {
2905
      /*
2906
       * EINVAL means this specific version of TPACKET
2907
       * is not supported. Tell the caller they can try
2908
       * with a different one; if they've run out of
2909
       * others to try, let them set the error message
2910
       * appropriately.
2911
       */
2912
0
      return 1;
2913
0
    }
2914
2915
    /*
2916
     * All other errors are fatal.
2917
     */
2918
0
    if (errno == ENOPROTOOPT) {
2919
      /*
2920
       * PACKET_HDRLEN isn't supported, which means
2921
       * that memory-mapped capture isn't supported.
2922
       * Indicate that in the message.
2923
       */
2924
0
      snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2925
0
          "Kernel doesn't support memory-mapped capture; a 2.6.27 or later 2.x kernel is required, with CONFIG_PACKET_MMAP specified for 2.x kernels");
2926
0
    } else {
2927
      /*
2928
       * Some unexpected error.
2929
       */
2930
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
2931
0
          errno, "can't get %s header len on packet socket",
2932
0
          version_str);
2933
0
    }
2934
0
    return -1;
2935
0
  }
2936
0
  handlep->tp_hdrlen = val;
2937
2938
0
  val = version;
2939
0
  if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
2940
0
         sizeof(val)) < 0) {
2941
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
2942
0
        errno, "can't activate %s on packet socket", version_str);
2943
0
    return -1;
2944
0
  }
2945
0
  handlep->tp_version = version;
2946
2947
0
  return 0;
2948
0
}
2949
2950
/*
2951
 * Attempt to set the socket to version 3 of the memory-mapped header and,
2952
 * if that fails because version 3 isn't supported, attempt to fall
2953
 * back to version 2.  If version 2 isn't supported, just fail.
2954
 *
2955
 * Return 0 if we succeed and -1 on any other error, and set handle->errbuf.
2956
 */
2957
static int
2958
prepare_tpacket_socket(pcap_t *handle)
2959
0
{
2960
0
  int ret;
2961
2962
0
#ifdef HAVE_TPACKET3
2963
  /*
2964
   * Try setting the version to TPACKET_V3.
2965
   *
2966
   * The only mode in which buffering is done on PF_PACKET
2967
   * sockets, so that packets might not be delivered
2968
   * immediately, is TPACKET_V3 mode.
2969
   *
2970
   * The buffering cannot be disabled in that mode, so
2971
   * if the user has requested immediate mode, we don't
2972
   * use TPACKET_V3.
2973
   */
2974
0
  if (!handle->opt.immediate) {
2975
0
    ret = init_tpacket(handle, TPACKET_V3, "TPACKET_V3");
2976
0
    if (ret == 0) {
2977
      /*
2978
       * Success.
2979
       */
2980
0
      return 0;
2981
0
    }
2982
0
    if (ret == -1) {
2983
      /*
2984
       * We failed for some reason other than "the
2985
       * kernel doesn't support TPACKET_V3".
2986
       */
2987
0
      return -1;
2988
0
    }
2989
2990
    /*
2991
     * This means it returned 1, which means "the kernel
2992
     * doesn't support TPACKET_V3"; try TPACKET_V2.
2993
     */
2994
0
  }
2995
0
#endif /* HAVE_TPACKET3 */
2996
2997
  /*
2998
   * Try setting the version to TPACKET_V2.
2999
   */
3000
0
  ret = init_tpacket(handle, TPACKET_V2, "TPACKET_V2");
3001
0
  if (ret == 0) {
3002
    /*
3003
     * Success.
3004
     */
3005
0
    return 0;
3006
0
  }
3007
3008
0
  if (ret == 1) {
3009
    /*
3010
     * OK, the kernel supports memory-mapped capture, but
3011
     * not TPACKET_V2.  Set the error message appropriately.
3012
     */
3013
0
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3014
0
        "Kernel doesn't support TPACKET_V2; a 2.6.27 or later kernel is required");
3015
0
  }
3016
3017
  /*
3018
   * We failed.
3019
   */
3020
0
  return -1;
3021
0
}
3022
3023
/*
3024
 * Attempt to set up memory-mapped access.
3025
 *
3026
 * On success, returns 0 if there are no warnings or to a PCAP_WARNING_ code
3027
 * if there is a warning.
3028
 *
3029
 * On error, returns the appropriate error code; if that is PCAP_ERROR,
3030
 * sets handle->errbuf to the appropriate message.
3031
 */
3032
static int
3033
create_ring(pcap_t *handle)
3034
0
{
3035
0
  struct pcap_linux *handlep = handle->priv;
3036
0
  unsigned i, j, frames_per_block;
3037
0
  int flags = MAP_SHARED;
3038
0
#ifdef HAVE_TPACKET3
3039
  /*
3040
   * For sockets using TPACKET_V2, the extra stuff at the end of a
3041
   * struct tpacket_req3 will be ignored, so this is OK even for
3042
   * those sockets.
3043
   */
3044
0
  struct tpacket_req3 req;
3045
#else
3046
  struct tpacket_req req;
3047
#endif
3048
0
  socklen_t len;
3049
0
  unsigned int sk_type, tp_reserve, maclen, tp_hdrlen, netoff, macoff;
3050
0
  unsigned int frame_size;
3051
0
  int status;
3052
3053
  /*
3054
   * Start out assuming no warnings.
3055
   */
3056
0
  status = 0;
3057
3058
  /*
3059
   * Reserve space for VLAN tag reconstruction.
3060
   */
3061
0
  tp_reserve = VLAN_TAG_LEN;
3062
3063
  /*
3064
   * If we're capturing in cooked mode, reserve space for
3065
   * a DLT_LINUX_SLL2 header; we don't know yet whether
3066
   * we'll be using DLT_LINUX_SLL or DLT_LINUX_SLL2, as
3067
   * that can be changed on an open device, so we reserve
3068
   * space for the larger of the two.
3069
   *
3070
   * XXX - we assume that the kernel is still adding
3071
   * 16 bytes of extra space, so we subtract 16 from
3072
   * SLL2_HDR_LEN to get the additional space needed.
3073
   * (Are they doing that for DLT_LINUX_SLL, the link-
3074
   * layer header for which is 16 bytes?)
3075
   *
3076
   * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - 16)?
3077
   */
3078
0
  if (handlep->cooked)
3079
0
    tp_reserve += SLL2_HDR_LEN - 16;
3080
3081
  /*
3082
   * Try to request that amount of reserve space.
3083
   * This must be done before creating the ring buffer.
3084
   */
3085
0
  len = sizeof(tp_reserve);
3086
0
  if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE,
3087
0
      &tp_reserve, len) < 0) {
3088
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf,
3089
0
        PCAP_ERRBUF_SIZE, errno,
3090
0
        "setsockopt (PACKET_RESERVE)");
3091
0
    return PCAP_ERROR;
3092
0
  }
3093
3094
0
  switch (handlep->tp_version) {
3095
3096
0
  case TPACKET_V2:
3097
    /* Note that with large snapshot length (say 256K, which is
3098
     * the default for recent versions of tcpdump, Wireshark,
3099
     * TShark, dumpcap or 64K, the value that "-s 0" has given for
3100
     * a long time with tcpdump), if we use the snapshot
3101
     * length to calculate the frame length, only a few frames
3102
     * will be available in the ring even with pretty
3103
     * large ring size (and a lot of memory will be unused).
3104
     *
3105
     * Ideally, we should choose a frame length based on the
3106
     * minimum of the specified snapshot length and the maximum
3107
     * packet size.  That's not as easy as it sounds; consider,
3108
     * for example, an 802.11 interface in monitor mode, where
3109
     * the frame would include a radiotap header, where the
3110
     * maximum radiotap header length is device-dependent.
3111
     *
3112
     * So, for now, we just do this for Ethernet devices, where
3113
     * there's no metadata header, and the link-layer header is
3114
     * fixed length.  We can get the maximum packet size by
3115
     * adding 18, the Ethernet header length plus the CRC length
3116
     * (just in case we happen to get the CRC in the packet), to
3117
     * the MTU of the interface; we fetch the MTU in the hopes
3118
     * that it reflects support for jumbo frames.  (Even if the
3119
     * interface is just being used for passive snooping, the
3120
     * driver might set the size of buffers in the receive ring
3121
     * based on the MTU, so that the MTU limits the maximum size
3122
     * of packets that we can receive.)
3123
     *
3124
     * If segmentation/fragmentation or receive offload are
3125
     * enabled, we can get reassembled/aggregated packets larger
3126
     * than MTU, but bounded to 65535 plus the Ethernet overhead,
3127
     * due to kernel and protocol constraints */
3128
0
    frame_size = handle->snapshot;
3129
0
    if (handle->linktype == DLT_EN10MB) {
3130
0
      unsigned int max_frame_len;
3131
0
      int mtu;
3132
0
      int offload;
3133
3134
0
      mtu = iface_get_mtu(handle->fd, handle->opt.device,
3135
0
          handle->errbuf);
3136
0
      if (mtu == -1)
3137
0
        return PCAP_ERROR;
3138
0
      offload = iface_get_offload(handle);
3139
0
      if (offload == -1)
3140
0
        return PCAP_ERROR;
3141
0
      if (offload)
3142
0
        max_frame_len = max(mtu, 65535);
3143
0
      else
3144
0
        max_frame_len = mtu;
3145
0
      max_frame_len += 18;
3146
3147
0
      if (frame_size > max_frame_len)
3148
0
        frame_size = max_frame_len;
3149
0
    }
3150
3151
    /* NOTE: calculus matching those in tpacket_rcv()
3152
     * in linux-2.6/net/packet/af_packet.c
3153
     */
3154
0
    len = sizeof(sk_type);
3155
0
    if (getsockopt(handle->fd, SOL_SOCKET, SO_TYPE, &sk_type,
3156
0
        &len) < 0) {
3157
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
3158
0
          PCAP_ERRBUF_SIZE, errno, "getsockopt (SO_TYPE)");
3159
0
      return PCAP_ERROR;
3160
0
    }
3161
0
    maclen = (sk_type == SOCK_DGRAM) ? 0 : MAX_LINKHEADER_SIZE;
3162
      /* XXX: in the kernel maclen is calculated from
3163
       * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3164
       * in:  packet_snd()           in linux-2.6/net/packet/af_packet.c
3165
       * then packet_alloc_skb()     in linux-2.6/net/packet/af_packet.c
3166
       * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3167
       * but I see no way to get those sizes in userspace,
3168
       * like for instance with an ifreq ioctl();
3169
       * the best thing I've found so far is MAX_HEADER in
3170
       * the kernel part of linux-2.6/include/linux/netdevice.h
3171
       * which goes up to 128+48=176; since pcap-linux.c
3172
       * defines a MAX_LINKHEADER_SIZE of 256 which is
3173
       * greater than that, let's use it.. maybe is it even
3174
       * large enough to directly replace macoff..
3175
       */
3176
0
    tp_hdrlen = TPACKET_ALIGN(handlep->tp_hdrlen) + sizeof(struct sockaddr_ll) ;
3177
0
    netoff = TPACKET_ALIGN(tp_hdrlen + (maclen < 16 ? 16 : maclen)) + tp_reserve;
3178
      /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
3179
       * of netoff, which contradicts
3180
       * linux-2.6/Documentation/networking/packet_mmap.txt
3181
       * documenting that:
3182
       * "- Gap, chosen so that packet data (Start+tp_net)
3183
       * aligns to TPACKET_ALIGNMENT=16"
3184
       */
3185
      /* NOTE: in linux-2.6/include/linux/skbuff.h:
3186
       * "CPUs often take a performance hit
3187
       *  when accessing unaligned memory locations"
3188
       */
3189
0
    macoff = netoff - maclen;
3190
0
    req.tp_frame_size = TPACKET_ALIGN(macoff + frame_size);
3191
    /*
3192
     * Round the buffer size up to a multiple of the
3193
     * frame size (rather than rounding down, which
3194
     * would give a buffer smaller than our caller asked
3195
     * for, and possibly give zero frames if the requested
3196
     * buffer size is too small for one frame).
3197
     */
3198
0
    req.tp_frame_nr = (handle->opt.buffer_size + req.tp_frame_size - 1)/req.tp_frame_size;
3199
0
    break;
3200
3201
0
#ifdef HAVE_TPACKET3
3202
0
  case TPACKET_V3:
3203
    /* The "frames" for this are actually buffers that
3204
     * contain multiple variable-sized frames.
3205
     *
3206
     * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
3207
     * enough room for at least one reasonably-sized packet
3208
     * in the "frame". */
3209
0
    req.tp_frame_size = MAXIMUM_SNAPLEN;
3210
    /*
3211
     * Round the buffer size up to a multiple of the
3212
     * "frame" size (rather than rounding down, which
3213
     * would give a buffer smaller than our caller asked
3214
     * for, and possibly give zero "frames" if the requested
3215
     * buffer size is too small for one "frame").
3216
     */
3217
0
    req.tp_frame_nr = (handle->opt.buffer_size + req.tp_frame_size - 1)/req.tp_frame_size;
3218
0
    break;
3219
0
#endif
3220
0
  default:
3221
0
    snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3222
0
        "Internal error: unknown TPACKET_ value %u",
3223
0
        handlep->tp_version);
3224
0
    return PCAP_ERROR;
3225
0
  }
3226
3227
  /* compute the minimum block size that will handle this frame.
3228
   * The block has to be page size aligned.
3229
   * The max block size allowed by the kernel is arch-dependent and
3230
   * it's not explicitly checked here. */
3231
0
  req.tp_block_size = getpagesize();
3232
0
  while (req.tp_block_size < req.tp_frame_size)
3233
0
    req.tp_block_size <<= 1;
3234
3235
0
  frames_per_block = req.tp_block_size/req.tp_frame_size;
3236
3237
  /*
3238
   * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3239
   * so we check for PACKET_TIMESTAMP.  We check for
3240
   * linux/net_tstamp.h just in case a system somehow has
3241
   * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3242
   * be unnecessary.
3243
   *
3244
   * SIOCSHWTSTAMP was introduced in the patch that introduced
3245
   * linux/net_tstamp.h, so we don't bother checking whether
3246
   * SIOCSHWTSTAMP is defined (if your Linux system has
3247
   * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3248
   * Linux system is badly broken).
3249
   */
3250
0
#if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3251
  /*
3252
   * If we were told to do so, ask the kernel and the driver
3253
   * to use hardware timestamps.
3254
   *
3255
   * Hardware timestamps are only supported with mmapped
3256
   * captures.
3257
   */
3258
0
  if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER ||
3259
0
      handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER_UNSYNCED) {
3260
0
    struct hwtstamp_config hwconfig;
3261
0
    struct ifreq ifr;
3262
0
    int timesource;
3263
3264
    /*
3265
     * Ask for hardware time stamps on all packets,
3266
     * including transmitted packets.
3267
     */
3268
0
    memset(&hwconfig, 0, sizeof(hwconfig));
3269
0
    hwconfig.tx_type = HWTSTAMP_TX_ON;
3270
0
    hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
3271
3272
0
    memset(&ifr, 0, sizeof(ifr));
3273
0
    pcapint_strlcpy(ifr.ifr_name, handle->opt.device, sizeof(ifr.ifr_name));
3274
0
    ifr.ifr_data = (void *)&hwconfig;
3275
3276
    /*
3277
     * This may require CAP_NET_ADMIN.
3278
     */
3279
0
    if (ioctl(handle->fd, SIOCSHWTSTAMP, &ifr) < 0) {
3280
0
      switch (errno) {
3281
3282
0
      case EPERM:
3283
        /*
3284
         * Treat this as an error, as the
3285
         * user should try to run this
3286
         * with the appropriate privileges -
3287
         * and, if they can't, shouldn't
3288
         * try requesting hardware time stamps.
3289
         */
3290
0
        snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3291
0
            "Attempt to set hardware timestamp failed - CAP_NET_ADMIN may be required");
3292
0
        return PCAP_ERROR_PERM_DENIED;
3293
3294
0
      case EOPNOTSUPP:
3295
0
      case ERANGE:
3296
        /*
3297
         * Treat this as a warning, as the
3298
         * only way to fix the warning is to
3299
         * get an adapter that supports hardware
3300
         * time stamps for *all* packets.
3301
         * (ERANGE means "we support hardware
3302
         * time stamps, but for packets matching
3303
         * that particular filter", so it means
3304
         * "we don't support hardware time stamps
3305
         * for all incoming packets" here.)
3306
         *
3307
         * We'll just fall back on the standard
3308
         * host time stamps.
3309
         */
3310
0
        status = PCAP_WARNING_TSTAMP_TYPE_NOTSUP;
3311
0
        break;
3312
3313
0
      default:
3314
0
        pcapint_fmt_errmsg_for_errno(handle->errbuf,
3315
0
            PCAP_ERRBUF_SIZE, errno,
3316
0
            "SIOCSHWTSTAMP failed");
3317
0
        return PCAP_ERROR;
3318
0
      }
3319
0
    } else {
3320
      /*
3321
       * Well, that worked.  Now specify the type of
3322
       * hardware time stamp we want for this
3323
       * socket.
3324
       */
3325
0
      if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER) {
3326
        /*
3327
         * Hardware timestamp, synchronized
3328
         * with the system clock.
3329
         */
3330
0
        timesource = SOF_TIMESTAMPING_SYS_HARDWARE;
3331
0
      } else {
3332
        /*
3333
         * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3334
         * timestamp, not synchronized with the
3335
         * system clock.
3336
         */
3337
0
        timesource = SOF_TIMESTAMPING_RAW_HARDWARE;
3338
0
      }
3339
0
      if (setsockopt(handle->fd, SOL_PACKET, PACKET_TIMESTAMP,
3340
0
        (void *)&timesource, sizeof(timesource))) {
3341
0
        pcapint_fmt_errmsg_for_errno(handle->errbuf,
3342
0
            PCAP_ERRBUF_SIZE, errno,
3343
0
            "can't set PACKET_TIMESTAMP");
3344
0
        return PCAP_ERROR;
3345
0
      }
3346
0
    }
3347
0
  }
3348
0
#endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3349
3350
  /* ask the kernel to create the ring */
3351
0
retry:
3352
0
  req.tp_block_nr = req.tp_frame_nr / frames_per_block;
3353
3354
  /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3355
0
  req.tp_frame_nr = req.tp_block_nr * frames_per_block;
3356
3357
0
#ifdef HAVE_TPACKET3
3358
  /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
3359
0
  if (handlep->timeout > 0) {
3360
    /* Use the user specified timeout as the block timeout */
3361
0
    req.tp_retire_blk_tov = handlep->timeout;
3362
0
  } else if (handlep->timeout == 0) {
3363
    /*
3364
     * In pcap, this means "infinite timeout"; TPACKET_V3
3365
     * doesn't support that, so just set it to UINT_MAX
3366
     * milliseconds.  In the TPACKET_V3 loop, if the
3367
     * timeout is 0, and we haven't yet seen any packets,
3368
     * and we block and still don't have any packets, we
3369
     * keep blocking until we do.
3370
     */
3371
0
    req.tp_retire_blk_tov = UINT_MAX;
3372
0
  } else {
3373
    /*
3374
     * XXX - this is not valid; use 0, meaning "have the
3375
     * kernel pick a default", for now.
3376
     */
3377
0
    req.tp_retire_blk_tov = 0;
3378
0
  }
3379
  /* private data not used */
3380
0
  req.tp_sizeof_priv = 0;
3381
  /* Rx ring - feature request bits - none (rxhash will not be filled) */
3382
0
  req.tp_feature_req_word = 0;
3383
0
#endif
3384
3385
0
  if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3386
0
          (void *) &req, sizeof(req))) {
3387
0
    if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
3388
      /*
3389
       * Memory failure; try to reduce the requested ring
3390
       * size.
3391
       *
3392
       * We used to reduce this by half -- do 5% instead.
3393
       * That may result in more iterations and a longer
3394
       * startup, but the user will be much happier with
3395
       * the resulting buffer size.
3396
       */
3397
0
      if (req.tp_frame_nr < 20)
3398
0
        req.tp_frame_nr -= 1;
3399
0
      else
3400
0
        req.tp_frame_nr -= req.tp_frame_nr/20;
3401
0
      goto retry;
3402
0
    }
3403
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
3404
0
        errno, "can't create rx ring on packet socket");
3405
0
    return PCAP_ERROR;
3406
0
  }
3407
3408
  /* memory map the rx ring */
3409
0
  handlep->mmapbuflen = req.tp_block_nr * req.tp_block_size;
3410
0
#ifdef MAP_32BIT
3411
0
  if (pcapint_mmap_32bit) flags |= MAP_32BIT;
3412
0
#endif
3413
0
  handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ | PROT_WRITE, flags, handle->fd, 0);
3414
0
  if (handlep->mmapbuf == MAP_FAILED) {
3415
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
3416
0
        errno, "can't mmap rx ring");
3417
3418
    /* clear the allocated ring on error*/
3419
0
    destroy_ring(handle);
3420
0
    return PCAP_ERROR;
3421
0
  }
3422
3423
  /* allocate a ring for each frame header pointer*/
3424
0
  handle->cc = req.tp_frame_nr;
3425
0
  handle->buffer = malloc(handle->cc * sizeof(union thdr *));
3426
0
  if (!handle->buffer) {
3427
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
3428
0
        errno, "can't allocate ring of frame headers");
3429
3430
0
    destroy_ring(handle);
3431
0
    return PCAP_ERROR;
3432
0
  }
3433
3434
  /* fill the header ring with proper frame ptr*/
3435
0
  handle->offset = 0;
3436
0
  for (i=0; i<req.tp_block_nr; ++i) {
3437
0
    u_char *base = &handlep->mmapbuf[i*req.tp_block_size];
3438
0
    for (j=0; j<frames_per_block; ++j, ++handle->offset) {
3439
0
      RING_GET_CURRENT_FRAME(handle) = base;
3440
0
      base += req.tp_frame_size;
3441
0
    }
3442
0
  }
3443
3444
0
  handle->bufsize = req.tp_frame_size;
3445
0
  handle->offset = 0;
3446
0
  return status;
3447
0
}
3448
3449
/* free all ring related resources*/
3450
static void
3451
destroy_ring(pcap_t *handle)
3452
0
{
3453
0
  struct pcap_linux *handlep = handle->priv;
3454
3455
  /*
3456
   * Tell the kernel to destroy the ring.
3457
   * We don't check for setsockopt failure, as 1) we can't recover
3458
   * from an error and 2) we might not yet have set it up in the
3459
   * first place.
3460
   */
3461
0
  struct tpacket_req req;
3462
0
  memset(&req, 0, sizeof(req));
3463
0
  (void)setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3464
0
        (void *) &req, sizeof(req));
3465
3466
  /* if ring is mapped, unmap it*/
3467
0
  if (handlep->mmapbuf) {
3468
    /* do not test for mmap failure, as we can't recover from any error */
3469
0
    (void)munmap(handlep->mmapbuf, handlep->mmapbuflen);
3470
0
    handlep->mmapbuf = NULL;
3471
0
  }
3472
0
}
3473
3474
/*
3475
 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3476
 * for Linux mmapped capture.
3477
 *
3478
 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3479
 * data handed to the callback to be valid after the callback returns,
3480
 * but pcap_read_linux_mmap() has to release that packet as soon as
3481
 * the callback returns (otherwise, the kernel thinks there's still
3482
 * at least one unprocessed packet available in the ring, so a select()
3483
 * will immediately return indicating that there's data to process), so,
3484
 * in the callback, we have to make a copy of the packet.
3485
 *
3486
 * Yes, this means that, if the capture is using the ring buffer, using
3487
 * pcap_next() or pcap_next_ex() requires more copies than using
3488
 * pcap_loop() or pcap_dispatch().  If that bothers you, don't use
3489
 * pcap_next() or pcap_next_ex().
3490
 */
3491
static void
3492
pcapint_oneshot_linux(u_char *user, const struct pcap_pkthdr *h,
3493
    const u_char *bytes)
3494
0
{
3495
0
  struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
3496
0
  pcap_t *handle = sp->pd;
3497
0
  struct pcap_linux *handlep = handle->priv;
3498
3499
0
  *sp->hdr = *h;
3500
0
  memcpy(handlep->oneshot_buffer, bytes, h->caplen);
3501
0
  *sp->pkt = handlep->oneshot_buffer;
3502
0
}
3503
3504
static int
3505
pcap_getnonblock_linux(pcap_t *handle)
3506
0
{
3507
0
  struct pcap_linux *handlep = handle->priv;
3508
3509
  /* use negative value of timeout to indicate non blocking ops */
3510
0
  return (handlep->timeout<0);
3511
0
}
3512
3513
static int
3514
pcap_setnonblock_linux(pcap_t *handle, int nonblock)
3515
0
{
3516
0
  struct pcap_linux *handlep = handle->priv;
3517
3518
  /*
3519
   * Set the file descriptor to the requested mode, as we use
3520
   * it for sending packets.
3521
   */
3522
0
  if (pcapint_setnonblock_fd(handle, nonblock) == -1)
3523
0
    return -1;
3524
3525
  /*
3526
   * Map each value to their corresponding negation to
3527
   * preserve the timeout value provided with pcap_set_timeout.
3528
   */
3529
0
  if (nonblock) {
3530
    /*
3531
     * We're setting the mode to non-blocking mode.
3532
     */
3533
0
    if (handlep->timeout >= 0) {
3534
      /*
3535
       * Indicate that we're switching to
3536
       * non-blocking mode.
3537
       */
3538
0
      handlep->timeout = ~handlep->timeout;
3539
0
    }
3540
0
    if (handlep->poll_breakloop_fd != -1) {
3541
      /* Close the eventfd; we do not need it in nonblock mode. */
3542
0
      close(handlep->poll_breakloop_fd);
3543
0
      handlep->poll_breakloop_fd = -1;
3544
0
    }
3545
0
  } else {
3546
    /*
3547
     * We're setting the mode to blocking mode.
3548
     */
3549
0
    if (handlep->poll_breakloop_fd == -1) {
3550
      /* If we did not have an eventfd, open one now that we are blocking. */
3551
0
      if ( ( handlep->poll_breakloop_fd = eventfd(0, EFD_NONBLOCK) ) == -1 ) {
3552
0
        pcapint_fmt_errmsg_for_errno(handle->errbuf,
3553
0
            PCAP_ERRBUF_SIZE, errno,
3554
0
            "could not open eventfd");
3555
0
        return -1;
3556
0
      }
3557
0
    }
3558
0
    if (handlep->timeout < 0) {
3559
0
      handlep->timeout = ~handlep->timeout;
3560
0
    }
3561
0
  }
3562
  /* Update the timeout to use in poll(). */
3563
0
  set_poll_timeout(handlep);
3564
0
  return 0;
3565
0
}
3566
3567
/*
3568
 * Get the status field of the ring buffer frame at a specified offset.
3569
 */
3570
static inline u_int
3571
pcap_get_ring_frame_status(pcap_t *handle, u_int offset)
3572
0
{
3573
0
  struct pcap_linux *handlep = handle->priv;
3574
0
  union thdr h;
3575
3576
0
  h.raw = RING_GET_FRAME_AT(handle, offset);
3577
0
  switch (handlep->tp_version) {
3578
0
  case TPACKET_V2:
3579
0
    return __atomic_load_n(&h.h2->tp_status, __ATOMIC_ACQUIRE);
3580
0
#ifdef HAVE_TPACKET3
3581
0
  case TPACKET_V3:
3582
0
    return __atomic_load_n(&h.h3->hdr.bh1.block_status, __ATOMIC_ACQUIRE);
3583
0
#endif
3584
0
  }
3585
  /* This should not happen. */
3586
0
  return 0;
3587
0
}
3588
3589
/*
3590
 * Block waiting for frames to be available.
3591
 */
3592
static int pcap_wait_for_frames_mmap(pcap_t *handle)
3593
0
{
3594
0
  struct pcap_linux *handlep = handle->priv;
3595
0
  int timeout;
3596
0
  struct ifreq ifr;
3597
0
  int ret;
3598
0
  struct pollfd pollinfo[2];
3599
0
  int numpollinfo;
3600
0
  pollinfo[0].fd = handle->fd;
3601
0
  pollinfo[0].events = POLLIN;
3602
0
  if ( handlep->poll_breakloop_fd == -1 ) {
3603
0
    numpollinfo = 1;
3604
0
    pollinfo[1].revents = 0;
3605
    /*
3606
     * We set pollinfo[1].revents to zero, even though
3607
     * numpollinfo = 1 meaning that poll() doesn't see
3608
     * pollinfo[1], so that we do not have to add a
3609
     * conditional of numpollinfo > 1 below when we
3610
     * test pollinfo[1].revents.
3611
     */
3612
0
  } else {
3613
0
    pollinfo[1].fd = handlep->poll_breakloop_fd;
3614
0
    pollinfo[1].events = POLLIN;
3615
0
    numpollinfo = 2;
3616
0
  }
3617
3618
  /*
3619
   * Keep polling until we either get some packets to read, see
3620
   * that we got told to break out of the loop, get a fatal error,
3621
   * or discover that the device went away.
3622
   *
3623
   * In non-blocking mode, we must still do one poll() to catch
3624
   * any pending error indications, but the poll() has a timeout
3625
   * of 0, so that it doesn't block, and we quit after that one
3626
   * poll().
3627
   *
3628
   * If we've seen an ENETDOWN, it might be the first indication
3629
   * that the device went away, or it might just be that it was
3630
   * configured down.  Unfortunately, there's no guarantee that
3631
   * the device has actually been removed as an interface, because:
3632
   *
3633
   * 1) if, as appears to be the case at least some of the time,
3634
   * the PF_PACKET socket code first gets a NETDEV_DOWN indication
3635
   * for the device and then gets a NETDEV_UNREGISTER indication
3636
   * for it, the first indication will cause a wakeup with ENETDOWN
3637
   * but won't set the packet socket's field for the interface index
3638
   * to -1, and the second indication won't cause a wakeup (because
3639
   * the first indication also caused the protocol hook to be
3640
   * unregistered) but will set the packet socket's field for the
3641
   * interface index to -1;
3642
   *
3643
   * 2) even if just a NETDEV_UNREGISTER indication is registered,
3644
   * the packet socket's field for the interface index only gets
3645
   * set to -1 after the wakeup, so there's a small but non-zero
3646
   * risk that a thread blocked waiting for the wakeup will get
3647
   * to the "fetch the socket name" code before the interface index
3648
   * gets set to -1, so it'll get the old interface index.
3649
   *
3650
   * Therefore, if we got an ENETDOWN and haven't seen a packet
3651
   * since then, we assume that we might be waiting for the interface
3652
   * to disappear, and poll with a timeout to try again in a short
3653
   * period of time.  If we *do* see a packet, the interface has
3654
   * come back up again, and is *definitely* still there, so we
3655
   * don't need to poll.
3656
   */
3657
0
  for (;;) {
3658
    /*
3659
     * Yes, we do this even in non-blocking mode, as it's
3660
     * the only way to get error indications from a
3661
     * tpacket socket.
3662
     *
3663
     * The timeout is 0 in non-blocking mode, so poll()
3664
     * returns immediately.
3665
     */
3666
0
    timeout = handlep->poll_timeout;
3667
3668
    /*
3669
     * If we got an ENETDOWN and haven't gotten an indication
3670
     * that the device has gone away or that the device is up,
3671
     * we don't yet know for certain whether the device has
3672
     * gone away or not, do a poll() with a 1-millisecond timeout,
3673
     * as we have to poll indefinitely for "device went away"
3674
     * indications until we either get one or see that the
3675
     * device is up.
3676
     */
3677
0
    if (handlep->netdown) {
3678
0
      if (timeout != 0)
3679
0
        timeout = 1;
3680
0
    }
3681
0
    ret = poll(pollinfo, numpollinfo, timeout);
3682
0
    if (ret < 0) {
3683
      /*
3684
       * Error.  If it's not EINTR, report it.
3685
       */
3686
0
      if (errno != EINTR) {
3687
0
        pcapint_fmt_errmsg_for_errno(handle->errbuf,
3688
0
            PCAP_ERRBUF_SIZE, errno,
3689
0
            "can't poll on packet socket");
3690
0
        return PCAP_ERROR;
3691
0
      }
3692
3693
      /*
3694
       * It's EINTR; if we were told to break out of
3695
       * the loop, do so.
3696
       */
3697
0
      if (handle->break_loop) {
3698
0
        handle->break_loop = 0;
3699
0
        return PCAP_ERROR_BREAK;
3700
0
      }
3701
0
    } else if (ret > 0) {
3702
      /*
3703
       * OK, some descriptor is ready.
3704
       * Check the socket descriptor first.
3705
       *
3706
       * As I read the Linux man page, pollinfo[0].revents
3707
       * will either be POLLIN, POLLERR, POLLHUP, or POLLNVAL.
3708
       */
3709
0
      if (pollinfo[0].revents == POLLIN) {
3710
        /*
3711
         * OK, we may have packets to
3712
         * read.
3713
         */
3714
0
        break;
3715
0
      }
3716
0
      if (pollinfo[0].revents != 0) {
3717
        /*
3718
         * There's some indication other than
3719
         * "you can read on this descriptor" on
3720
         * the descriptor.
3721
         */
3722
0
        if (pollinfo[0].revents & POLLNVAL) {
3723
0
          snprintf(handle->errbuf,
3724
0
              PCAP_ERRBUF_SIZE,
3725
0
              "Invalid polling request on packet socket");
3726
0
          return PCAP_ERROR;
3727
0
        }
3728
0
        if (pollinfo[0].revents & (POLLHUP | POLLRDHUP)) {
3729
0
          snprintf(handle->errbuf,
3730
0
              PCAP_ERRBUF_SIZE,
3731
0
              "Hangup on packet socket");
3732
0
          return PCAP_ERROR;
3733
0
        }
3734
0
        if (pollinfo[0].revents & POLLERR) {
3735
          /*
3736
           * Get the error.
3737
           */
3738
0
          int err;
3739
0
          socklen_t errlen;
3740
3741
0
          errlen = sizeof(err);
3742
0
          if (getsockopt(handle->fd, SOL_SOCKET,
3743
0
              SO_ERROR, &err, &errlen) == -1) {
3744
            /*
3745
             * The call *itself* returned
3746
             * an error; make *that*
3747
             * the error.
3748
             */
3749
0
            err = errno;
3750
0
          }
3751
3752
          /*
3753
           * OK, we have the error.
3754
           */
3755
0
          if (err == ENETDOWN) {
3756
            /*
3757
             * The device on which we're
3758
             * capturing went away or the
3759
             * interface was taken down.
3760
             *
3761
             * We don't know for certain
3762
             * which happened, and the
3763
             * next poll() may indicate
3764
             * that there are packets
3765
             * to be read, so just set
3766
             * a flag to get us to do
3767
             * checks later, and set
3768
             * the required select
3769
             * timeout to 1 millisecond
3770
             * so that event loops that
3771
             * check our socket descriptor
3772
             * also time out so that
3773
             * they can call us and we
3774
             * can do the checks.
3775
             */
3776
0
            handlep->netdown = 1;
3777
0
            handle->required_select_timeout = &netdown_timeout;
3778
0
          } else if (err == 0) {
3779
            /*
3780
             * This shouldn't happen, so
3781
             * report a special indication
3782
             * that it did.
3783
             */
3784
0
            snprintf(handle->errbuf,
3785
0
                PCAP_ERRBUF_SIZE,
3786
0
                "Error condition on packet socket: Reported error was 0");
3787
0
            return PCAP_ERROR;
3788
0
          } else {
3789
0
            pcapint_fmt_errmsg_for_errno(handle->errbuf,
3790
0
                PCAP_ERRBUF_SIZE,
3791
0
                err,
3792
0
                "Error condition on packet socket");
3793
0
            return PCAP_ERROR;
3794
0
          }
3795
0
        }
3796
0
      }
3797
      /*
3798
       * Now check the event device.
3799
       */
3800
0
      if (pollinfo[1].revents & POLLIN) {
3801
0
        ssize_t nread;
3802
0
        uint64_t value;
3803
3804
        /*
3805
         * This should never fail, but, just
3806
         * in case....
3807
         */
3808
0
        nread = read(handlep->poll_breakloop_fd, &value,
3809
0
            sizeof(value));
3810
0
        if (nread == -1) {
3811
0
          pcapint_fmt_errmsg_for_errno(handle->errbuf,
3812
0
              PCAP_ERRBUF_SIZE,
3813
0
              errno,
3814
0
              "Error reading from event FD");
3815
0
          return PCAP_ERROR;
3816
0
        }
3817
3818
        /*
3819
         * According to the Linux read(2) man
3820
         * page, read() will transfer at most
3821
         * 2^31-1 bytes, so the return value is
3822
         * either -1 or a value between 0
3823
         * and 2^31-1, so it's non-negative.
3824
         *
3825
         * Cast it to size_t to squelch
3826
         * warnings from the compiler; add this
3827
         * comment to squelch warnings from
3828
         * humans reading the code. :-)
3829
         *
3830
         * Don't treat an EOF as an error, but
3831
         * *do* treat a short read as an error;
3832
         * that "shouldn't happen", but....
3833
         */
3834
0
        if (nread != 0 &&
3835
0
            (size_t)nread < sizeof(value)) {
3836
0
          snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3837
0
              "Short read from event FD: expected %zu, got %zd",
3838
0
              sizeof(value), nread);
3839
0
          return PCAP_ERROR;
3840
0
        }
3841
3842
        /*
3843
         * This event gets signaled by a
3844
         * pcap_breakloop() call; if we were told
3845
         * to break out of the loop, do so.
3846
         */
3847
0
        if (handle->break_loop) {
3848
0
          handle->break_loop = 0;
3849
0
          return PCAP_ERROR_BREAK;
3850
0
        }
3851
0
      }
3852
0
    }
3853
3854
    /*
3855
     * Either:
3856
     *
3857
     *   1) we got neither an error from poll() nor any
3858
     *      readable descriptors, in which case there
3859
     *      are no packets waiting to read
3860
     *
3861
     * or
3862
     *
3863
     *   2) We got readable descriptors but the PF_PACKET
3864
     *      socket wasn't one of them, in which case there
3865
     *      are no packets waiting to read
3866
     *
3867
     * so, if we got an ENETDOWN, we've drained whatever
3868
     * packets were available to read at the point of the
3869
     * ENETDOWN.
3870
     *
3871
     * So, if we got an ENETDOWN and haven't gotten an indication
3872
     * that the device has gone away or that the device is up,
3873
     * we don't yet know for certain whether the device has
3874
     * gone away or not, check whether the device exists and is
3875
     * up.
3876
     */
3877
0
    if (handlep->netdown) {
3878
0
      if (!device_still_exists(handle)) {
3879
        /*
3880
         * The device doesn't exist any more;
3881
         * report that.
3882
         *
3883
         * XXX - we should really return an
3884
         * appropriate error for that, but
3885
         * pcap_dispatch() etc. aren't documented
3886
         * as having error returns other than
3887
         * PCAP_ERROR or PCAP_ERROR_BREAK.
3888
         */
3889
0
        snprintf(handle->errbuf,  PCAP_ERRBUF_SIZE,
3890
0
            "The interface disappeared");
3891
0
        return PCAP_ERROR;
3892
0
      }
3893
3894
      /*
3895
       * The device still exists; try to see if it's up.
3896
       */
3897
0
      memset(&ifr, 0, sizeof(ifr));
3898
0
      pcapint_strlcpy(ifr.ifr_name, handlep->device,
3899
0
          sizeof(ifr.ifr_name));
3900
0
      if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
3901
0
        if (errno == ENXIO || errno == ENODEV) {
3902
          /*
3903
           * OK, *now* it's gone.
3904
           *
3905
           * XXX - see above comment.
3906
           */
3907
0
          snprintf(handle->errbuf,
3908
0
              PCAP_ERRBUF_SIZE,
3909
0
              "The interface disappeared");
3910
0
          return PCAP_ERROR;
3911
0
        } else {
3912
0
          pcapint_fmt_errmsg_for_errno(handle->errbuf,
3913
0
              PCAP_ERRBUF_SIZE, errno,
3914
0
              "%s: Can't get flags",
3915
0
              handlep->device);
3916
0
          return PCAP_ERROR;
3917
0
        }
3918
0
      }
3919
0
      if (ifr.ifr_flags & IFF_UP) {
3920
        /*
3921
         * It's up, so it definitely still exists.
3922
         * Cancel the ENETDOWN indication - we
3923
         * presumably got it due to the interface
3924
         * going down rather than the device going
3925
         * away - and revert to "no required select
3926
         * timeout.
3927
         */
3928
0
        handlep->netdown = 0;
3929
0
        handle->required_select_timeout = NULL;
3930
0
      }
3931
0
    }
3932
3933
    /*
3934
     * If we're in non-blocking mode, just quit now, rather
3935
     * than spinning in a loop doing poll()s that immediately
3936
     * time out if there's no indication on any descriptor.
3937
     */
3938
0
    if (handlep->poll_timeout == 0)
3939
0
      break;
3940
0
  }
3941
0
  return 0;
3942
0
}
3943
3944
/* handle a single memory mapped packet */
3945
static int pcap_handle_packet_mmap(
3946
    pcap_t *handle,
3947
    pcap_handler callback,
3948
    u_char *user,
3949
    unsigned char *frame,
3950
    unsigned int tp_len,
3951
    unsigned int tp_mac,
3952
    unsigned int tp_snaplen,
3953
    unsigned int tp_sec,
3954
    unsigned int tp_usec,
3955
    int tp_vlan_tci_valid,
3956
    __u16 tp_vlan_tci,
3957
    __u16 tp_vlan_tpid)
3958
0
{
3959
0
  struct pcap_linux *handlep = handle->priv;
3960
0
  unsigned char *bp;
3961
0
  struct sockaddr_ll *sll;
3962
0
  struct pcap_pkthdr pcaphdr;
3963
0
  unsigned int snaplen = tp_snaplen;
3964
0
  struct utsname utsname;
3965
3966
  /* perform sanity check on internal offset. */
3967
0
  if (tp_mac + tp_snaplen > handle->bufsize) {
3968
    /*
3969
     * Report some system information as a debugging aid.
3970
     */
3971
0
    if (uname(&utsname) != -1) {
3972
0
      snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3973
0
        "corrupted frame on kernel ring mac "
3974
0
        "offset %u + caplen %u > frame len %d "
3975
0
        "(kernel %.32s version %s, machine %.16s)",
3976
0
        tp_mac, tp_snaplen, handle->bufsize,
3977
0
        utsname.release, utsname.version,
3978
0
        utsname.machine);
3979
0
    } else {
3980
0
      snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3981
0
        "corrupted frame on kernel ring mac "
3982
0
        "offset %u + caplen %u > frame len %d",
3983
0
        tp_mac, tp_snaplen, handle->bufsize);
3984
0
    }
3985
0
    return -1;
3986
0
  }
3987
3988
  /* run filter on received packet
3989
   * If the kernel filtering is enabled we need to run the
3990
   * filter until all the frames present into the ring
3991
   * at filter creation time are processed.
3992
   * In this case, blocks_to_filter_in_userland is used
3993
   * as a counter for the packet we need to filter.
3994
   * Note: alternatively it could be possible to stop applying
3995
   * the filter when the ring became empty, but it can possibly
3996
   * happen a lot later... */
3997
0
  bp = frame + tp_mac;
3998
3999
  /* if required build in place the sll header*/
4000
0
  sll = (void *)(frame + TPACKET_ALIGN(handlep->tp_hdrlen));
4001
0
  if (handlep->cooked) {
4002
0
    if (handle->linktype == DLT_LINUX_SLL2) {
4003
0
      struct sll2_header *hdrp;
4004
4005
      /*
4006
       * The kernel should have left us with enough
4007
       * space for an sll header; back up the packet
4008
       * data pointer into that space, as that'll be
4009
       * the beginning of the packet we pass to the
4010
       * callback.
4011
       */
4012
0
      bp -= SLL2_HDR_LEN;
4013
4014
      /*
4015
       * Let's make sure that's past the end of
4016
       * the tpacket header, i.e. >=
4017
       * ((u_char *)thdr + TPACKET_HDRLEN), so we
4018
       * don't step on the header when we construct
4019
       * the sll header.
4020
       */
4021
0
      if (bp < (u_char *)frame +
4022
0
             TPACKET_ALIGN(handlep->tp_hdrlen) +
4023
0
             sizeof(struct sockaddr_ll)) {
4024
0
        snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4025
0
          "cooked-mode frame doesn't have room for sll header");
4026
0
        return -1;
4027
0
      }
4028
4029
      /*
4030
       * OK, that worked; construct the sll header.
4031
       */
4032
0
      hdrp = (struct sll2_header *)bp;
4033
0
      hdrp->sll2_protocol = sll->sll_protocol;
4034
0
      hdrp->sll2_reserved_mbz = 0;
4035
0
      hdrp->sll2_if_index = htonl(sll->sll_ifindex);
4036
0
      hdrp->sll2_hatype = htons(sll->sll_hatype);
4037
0
      hdrp->sll2_pkttype = sll->sll_pkttype;
4038
0
      hdrp->sll2_halen = sll->sll_halen;
4039
0
      memcpy(hdrp->sll2_addr, sll->sll_addr, SLL_ADDRLEN);
4040
4041
0
      snaplen += sizeof(struct sll2_header);
4042
0
    } else {
4043
0
      struct sll_header *hdrp;
4044
4045
      /*
4046
       * The kernel should have left us with enough
4047
       * space for an sll header; back up the packet
4048
       * data pointer into that space, as that'll be
4049
       * the beginning of the packet we pass to the
4050
       * callback.
4051
       */
4052
0
      bp -= SLL_HDR_LEN;
4053
4054
      /*
4055
       * Let's make sure that's past the end of
4056
       * the tpacket header, i.e. >=
4057
       * ((u_char *)thdr + TPACKET_HDRLEN), so we
4058
       * don't step on the header when we construct
4059
       * the sll header.
4060
       */
4061
0
      if (bp < (u_char *)frame +
4062
0
             TPACKET_ALIGN(handlep->tp_hdrlen) +
4063
0
             sizeof(struct sockaddr_ll)) {
4064
0
        snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4065
0
          "cooked-mode frame doesn't have room for sll header");
4066
0
        return -1;
4067
0
      }
4068
4069
      /*
4070
       * OK, that worked; construct the sll header.
4071
       */
4072
0
      hdrp = (struct sll_header *)bp;
4073
0
      hdrp->sll_pkttype = htons(sll->sll_pkttype);
4074
0
      hdrp->sll_hatype = htons(sll->sll_hatype);
4075
0
      hdrp->sll_halen = htons(sll->sll_halen);
4076
0
      memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
4077
0
      hdrp->sll_protocol = sll->sll_protocol;
4078
4079
0
      snaplen += sizeof(struct sll_header);
4080
0
    }
4081
0
  } else {
4082
    /*
4083
     * If this is a packet from a CAN device, so that
4084
     * sll->sll_hatype is ARPHRD_CAN, then, as we're
4085
     * not capturing in cooked mode, its link-layer
4086
     * type is DLT_CAN_SOCKETCAN.  Fix up the header
4087
     * provided by the code below us to match what
4088
     * DLT_CAN_SOCKETCAN is expected to provide.
4089
     */
4090
0
    if (sll->sll_hatype == ARPHRD_CAN) {
4091
0
      pcap_can_socketcan_hdr *canhdr = (pcap_can_socketcan_hdr *)bp;
4092
0
      pcap_can_socketcan_xl_hdr *canxl_hdr = (pcap_can_socketcan_xl_hdr *)bp;
4093
0
      uint16_t protocol = ntohs(sll->sll_protocol);
4094
4095
      /*
4096
       * Check the protocol field from the sll header.
4097
       * If it's one of the known CAN protocol types,
4098
       * make sure the appropriate flags are set, so
4099
       * that a program can tell what type of frame
4100
       * it is.
4101
       *
4102
       * These operations should not have any effect
4103
       * when reading proper CAN frames from Linux
4104
       * CAN interfaces. Enforcing these bit values
4105
       * ensures proper DLT_CAN_SOCKETCAN data even
4106
       * with malformed PF_PACKET content.
4107
       *
4108
       * The two flags are:
4109
       *
4110
       *   CANFD_FDF, which is in the fd_flags field
4111
       *   of the CAN CC/CAN FD header;
4112
       *
4113
       *   CANXL_XLF, which is in the flags field
4114
       *   of the CAN XL header, which overlaps
4115
       *   the payload_length field of the CAN CC/
4116
       *   CAN FD header. Setting CANXL_XLF in the
4117
       *   payload_length of CAN CC/FD frames would
4118
       *   intentionally break the payload length.
4119
       */
4120
0
      switch (protocol) {
4121
4122
0
      case LINUX_SLL_P_CAN:
4123
        /*
4124
         * CAN CC frame (aka Classical CAN, CAN 2.0B)
4125
         *
4126
         * Zero out the CAN FD and CAN XL flags
4127
         * so that this frame will be identified
4128
         * as a CAN CC frame.
4129
         */
4130
0
        canxl_hdr->flags &= ~CANXL_XLF;
4131
0
        canhdr->fd_flags &= ~CANFD_FDF;
4132
0
        break;
4133
4134
0
      case LINUX_SLL_P_CANFD:
4135
        /*
4136
         * CAN FD frame
4137
         *
4138
         * Set CANFD_FDF in the fd_flags field,
4139
         * and clear the CANXL_XLF bit in the
4140
         * CAN XL flags field, so that this frame
4141
         * will be identified as a CAN FD frame.
4142
         *
4143
         * The CANFD_FDF bit is not reliably
4144
         * set by the Linux kernel. But setting
4145
         * that bit for CAN FD is recommended.
4146
         */
4147
0
        canxl_hdr->flags &= ~CANXL_XLF;
4148
0
        canhdr->fd_flags |= CANFD_FDF;
4149
0
        break;
4150
4151
0
      case LINUX_SLL_P_CANXL:
4152
        /*
4153
         * CAN XL frame
4154
         *
4155
         * Set CANXL_XLF bit in the CAN XL flags
4156
         * field, so that this frame will appear
4157
         * to be a CAN XL frame.
4158
         */
4159
0
        canxl_hdr->flags |= CANXL_XLF;
4160
0
        break;
4161
0
      }
4162
4163
      /*
4164
       * Put multi-byte header fields in a byte-order
4165
       * -independent format.
4166
       */
4167
0
      if (canxl_hdr->flags & CANXL_XLF) {
4168
        /*
4169
         * This is a CAN XL frame.
4170
         *
4171
         * DLT_CAN_SOCKETCAN is specified as having
4172
         * the Priority ID/VCID field in big-
4173
         * endian byte order, and the payload length
4174
         * and Acceptance Field in little-endian byte
4175
         * order, but capturing on a CAN device
4176
         * provides them in host byte order.
4177
         * Convert them to the appropriate byte
4178
         * orders.
4179
         *
4180
         * The reason we put the first field
4181
         * into big-endian byte order is that
4182
         * older libpcap code, ignorant of
4183
         * CAN XL, treated it as the CAN ID
4184
         * field and put it into big-endian
4185
         * byte order, and we don't want to
4186
         * break code that understands CAN XL
4187
         * headers, and treats that field as
4188
         * being big-endian.
4189
         *
4190
         * The reason other fields are put in little-
4191
         * endian byte order is that older
4192
         * libpcap code, ignorant of CAN XL,
4193
         * left those fields alone, and the
4194
         * processors on which the CAN XL
4195
         * frames were captured are likely
4196
         * to be little-endian processors.
4197
         */
4198
4199
0
#if __BYTE_ORDER == __LITTLE_ENDIAN
4200
        /*
4201
         * We're capturing on a little-endian
4202
         * machine, so we put the priority/VCID
4203
         * field into big-endian byte order, and
4204
         * leave the payload length and acceptance
4205
         * field in little-endian byte order.
4206
         */
4207
        /* Byte-swap priority/VCID. */
4208
0
        canxl_hdr->priority_vcid = PCAP_BSWAP_32(canxl_hdr->priority_vcid);
4209
#elif __BYTE_ORDER == __BIG_ENDIAN
4210
        /*
4211
         * We're capturing on a big-endian
4212
         * machine, so we want to leave the
4213
         * priority/VCID field alone, and byte-swap
4214
         * the payload length and acceptance
4215
         * fields to little-endian.
4216
         */
4217
        /* Byte-swap the payload length */
4218
        canxl_hdr->payload_length = PCAP_BSWAP_16(canxl_hdr->payload_length);
4219
4220
        /*
4221
         * Byte-swap the acceptance field.
4222
         *
4223
         * XXX - is it just a 4-octet string,
4224
         * not in any byte order?
4225
         */
4226
        canxl_hdr->acceptance_field = PCAP_BSWAP_32(canxl_hdr->acceptance_field);
4227
#else
4228
#error "Unknown byte order"
4229
#endif
4230
0
      } else {
4231
        /*
4232
         * CAN CC or CAN FD frame.
4233
         *
4234
         * DLT_CAN_SOCKETCAN is specified as having
4235
         * the CAN ID and flags in network byte
4236
         * order, but capturing on a CAN device
4237
         * provides it in host byte order.  Convert
4238
         * it to network byte order.
4239
         */
4240
0
        canhdr->can_id = htonl(canhdr->can_id);
4241
0
      }
4242
0
    }
4243
0
  }
4244
4245
0
  if (handlep->filter_in_userland && handle->fcode.bf_insns) {
4246
0
    struct pcap_bpf_aux_data aux_data;
4247
4248
0
    aux_data.vlan_tag_present = tp_vlan_tci_valid;
4249
0
    aux_data.vlan_tag = tp_vlan_tci & 0x0fff;
4250
4251
0
    if (pcapint_filter_with_aux_data(handle->fcode.bf_insns,
4252
0
                handle->fcode.bf_len,
4253
0
                bp,
4254
0
                tp_len,
4255
0
                snaplen,
4256
0
                &aux_data) == 0)
4257
0
      return 0;
4258
0
  }
4259
4260
0
  if (!linux_check_direction(handle, sll))
4261
0
    return 0;
4262
4263
  /*
4264
   * Get required packet info from ring header.
4265
   *
4266
   * The seconds part of the time stamp is a 32-bit
4267
   * unsigned integer; this will have a problem in 2106,
4268
   * but not in 2038.
4269
   *
4270
   * ts.tv_sec is a time_t, which is signed, and which
4271
   * may be 32-bit or 64-bit.  Pass it through; if we
4272
   * have a 32-bit signed time_t, in which values >
4273
   * 2^31-1 won't fit, then:
4274
   *
4275
   *    Writing the packet to a file will pass the bits
4276
   *    through.  If the program reading the file can
4277
   *    handle 32-bit unsigned time stamps, including
4278
   *    any conversion to local time or UTC, it will
4279
   *    properly handle the time stamps.
4280
   *
4281
   *    Reporting the packet time stamp may give
4282
   *    an error or a pre-1970 time stamp on platforms
4283
   *    with signed 32-bit time stamps, but that
4284
   *    will happen even if it's captured on a
4285
   *    platform with a 64-bit time_t.
4286
   */
4287
0
  pcaphdr.ts.tv_sec = tp_sec;
4288
0
  pcaphdr.ts.tv_usec = tp_usec;
4289
0
  pcaphdr.caplen = tp_snaplen;
4290
0
  pcaphdr.len = tp_len;
4291
4292
  /* if required build in place the sll header*/
4293
0
  if (handlep->cooked) {
4294
    /* update packet len */
4295
0
    if (handle->linktype == DLT_LINUX_SLL2) {
4296
0
      pcaphdr.caplen += SLL2_HDR_LEN;
4297
0
      pcaphdr.len += SLL2_HDR_LEN;
4298
0
    } else {
4299
0
      pcaphdr.caplen += SLL_HDR_LEN;
4300
0
      pcaphdr.len += SLL_HDR_LEN;
4301
0
    }
4302
0
  }
4303
4304
0
  if (tp_vlan_tci_valid &&
4305
0
    handlep->vlan_offset != -1 &&
4306
0
    tp_snaplen >= (unsigned int) handlep->vlan_offset)
4307
0
  {
4308
0
    struct vlan_tag *tag;
4309
4310
    /*
4311
     * Move everything in the header, except the type field,
4312
     * down VLAN_TAG_LEN bytes, to allow us to insert the
4313
     * VLAN tag between that stuff and the type field.
4314
     */
4315
0
    bp -= VLAN_TAG_LEN;
4316
0
    memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
4317
4318
    /*
4319
     * Now insert the tag.
4320
     */
4321
0
    tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
4322
0
    tag->vlan_tpid = htons(tp_vlan_tpid);
4323
0
    tag->vlan_tci = htons(tp_vlan_tci);
4324
4325
    /*
4326
     * Add the tag to the packet lengths.
4327
     */
4328
0
    pcaphdr.caplen += VLAN_TAG_LEN;
4329
0
    pcaphdr.len += VLAN_TAG_LEN;
4330
0
  }
4331
4332
  /*
4333
   * The only way to tell the kernel to cut off the
4334
   * packet at a snapshot length is with a filter program;
4335
   * if there's no filter program, the kernel won't cut
4336
   * the packet off.
4337
   *
4338
   * Trim the snapshot length to be no longer than the
4339
   * specified snapshot length.
4340
   *
4341
   * XXX - an alternative is to put a filter, consisting
4342
   * of a "ret <snaplen>" instruction, on the socket
4343
   * in the activate routine, so that the truncation is
4344
   * done in the kernel even if nobody specified a filter;
4345
   * that means that less buffer space is consumed in
4346
   * the memory-mapped buffer.
4347
   */
4348
0
  if (pcaphdr.caplen > (bpf_u_int32)handle->snapshot)
4349
0
    pcaphdr.caplen = handle->snapshot;
4350
4351
  /* pass the packet to the user */
4352
0
  callback(user, &pcaphdr, bp);
4353
4354
0
  return 1;
4355
0
}
4356
4357
static int
4358
pcap_read_linux_mmap_v2(pcap_t *handle, int max_packets, pcap_handler callback,
4359
    u_char *user)
4360
0
{
4361
0
  struct pcap_linux *handlep = handle->priv;
4362
0
  union thdr h;
4363
0
  int pkts = 0;
4364
0
  int ret;
4365
4366
  /* wait for frames availability.*/
4367
0
  h.raw = RING_GET_CURRENT_FRAME(handle);
4368
0
  if (!packet_mmap_acquire(h.h2)) {
4369
    /*
4370
     * The current frame is owned by the kernel; wait for
4371
     * a frame to be handed to us.
4372
     */
4373
0
    ret = pcap_wait_for_frames_mmap(handle);
4374
0
    if (ret) {
4375
0
      return ret;
4376
0
    }
4377
0
  }
4378
4379
  /*
4380
   * This can conceivably process more than INT_MAX packets,
4381
   * which would overflow the packet count, causing it either
4382
   * to look like a negative number, and thus cause us to
4383
   * return a value that looks like an error, or overflow
4384
   * back into positive territory, and thus cause us to
4385
   * return a too-low count.
4386
   *
4387
   * Therefore, if the packet count is unlimited, we clip
4388
   * it at INT_MAX; this routine is not expected to
4389
   * process packets indefinitely, so that's not an issue.
4390
   */
4391
0
  if (PACKET_COUNT_IS_UNLIMITED(max_packets))
4392
0
    max_packets = INT_MAX;
4393
4394
0
  while (pkts < max_packets) {
4395
    /*
4396
     * Get the current ring buffer frame, and break if
4397
     * it's still owned by the kernel.
4398
     */
4399
0
    h.raw = RING_GET_CURRENT_FRAME(handle);
4400
0
    if (!packet_mmap_acquire(h.h2))
4401
0
      break;
4402
4403
0
    ret = pcap_handle_packet_mmap(
4404
0
        handle,
4405
0
        callback,
4406
0
        user,
4407
0
        h.raw,
4408
0
        h.h2->tp_len,
4409
0
        h.h2->tp_mac,
4410
0
        h.h2->tp_snaplen,
4411
0
        h.h2->tp_sec,
4412
0
        handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? h.h2->tp_nsec : h.h2->tp_nsec / 1000,
4413
0
        VLAN_VALID(h.h2, h.h2),
4414
0
        h.h2->tp_vlan_tci,
4415
0
        VLAN_TPID(h.h2, h.h2));
4416
0
    if (ret == 1) {
4417
0
      pkts++;
4418
0
    } else if (ret < 0) {
4419
0
      return ret;
4420
0
    }
4421
4422
    /*
4423
     * Hand this block back to the kernel, and, if we're
4424
     * counting blocks that need to be filtered in userland
4425
     * after having been filtered by the kernel, count
4426
     * the one we've just processed.
4427
     */
4428
0
    packet_mmap_release(h.h2);
4429
0
    if (handlep->blocks_to_filter_in_userland != 0) {
4430
0
      handlep->blocks_to_filter_in_userland--;
4431
0
      if (handlep->blocks_to_filter_in_userland == 0) {
4432
        /*
4433
         * No more blocks need to be filtered
4434
         * in userland.
4435
         */
4436
0
        handlep->filter_in_userland = 0;
4437
0
      }
4438
0
    }
4439
4440
    /* next block */
4441
0
    if (++handle->offset >= handle->cc)
4442
0
      handle->offset = 0;
4443
4444
    /* check for break loop condition*/
4445
0
    if (handle->break_loop) {
4446
0
      handle->break_loop = 0;
4447
0
      return PCAP_ERROR_BREAK;
4448
0
    }
4449
0
  }
4450
0
  return pkts;
4451
0
}
4452
4453
#ifdef HAVE_TPACKET3
4454
static int
4455
pcap_read_linux_mmap_v3(pcap_t *handle, int max_packets, pcap_handler callback,
4456
    u_char *user)
4457
0
{
4458
0
  struct pcap_linux *handlep = handle->priv;
4459
0
  union thdr h;
4460
0
  int pkts = 0;
4461
0
  int ret;
4462
4463
0
again:
4464
0
  if (handlep->current_packet == NULL) {
4465
    /* wait for frames availability.*/
4466
0
    h.raw = RING_GET_CURRENT_FRAME(handle);
4467
0
    if (!packet_mmap_v3_acquire(h.h3)) {
4468
      /*
4469
       * The current frame is owned by the kernel; wait
4470
       * for a frame to be handed to us.
4471
       */
4472
0
      ret = pcap_wait_for_frames_mmap(handle);
4473
0
      if (ret) {
4474
0
        return ret;
4475
0
      }
4476
0
    }
4477
0
  }
4478
0
  h.raw = RING_GET_CURRENT_FRAME(handle);
4479
0
  if (!packet_mmap_v3_acquire(h.h3)) {
4480
0
    if (pkts == 0 && handlep->timeout == 0) {
4481
      /* Block until we see a packet. */
4482
0
      goto again;
4483
0
    }
4484
0
    return pkts;
4485
0
  }
4486
4487
  /*
4488
   * This can conceivably process more than INT_MAX packets,
4489
   * which would overflow the packet count, causing it either
4490
   * to look like a negative number, and thus cause us to
4491
   * return a value that looks like an error, or overflow
4492
   * back into positive territory, and thus cause us to
4493
   * return a too-low count.
4494
   *
4495
   * Therefore, if the packet count is unlimited, we clip
4496
   * it at INT_MAX; this routine is not expected to
4497
   * process packets indefinitely, so that's not an issue.
4498
   */
4499
0
  if (PACKET_COUNT_IS_UNLIMITED(max_packets))
4500
0
    max_packets = INT_MAX;
4501
4502
0
  while (pkts < max_packets) {
4503
0
    int packets_to_read;
4504
4505
0
    if (handlep->current_packet == NULL) {
4506
0
      h.raw = RING_GET_CURRENT_FRAME(handle);
4507
0
      if (!packet_mmap_v3_acquire(h.h3))
4508
0
        break;
4509
4510
0
      handlep->current_packet = h.raw + h.h3->hdr.bh1.offset_to_first_pkt;
4511
0
      handlep->packets_left = h.h3->hdr.bh1.num_pkts;
4512
0
    }
4513
0
    packets_to_read = handlep->packets_left;
4514
4515
0
    if (packets_to_read > (max_packets - pkts)) {
4516
      /*
4517
       * There are more packets in the buffer than
4518
       * the number of packets we have left to
4519
       * process to get up to the maximum number
4520
       * of packets to process.  Only process enough
4521
       * of them to get us up to that maximum.
4522
       */
4523
0
      packets_to_read = max_packets - pkts;
4524
0
    }
4525
4526
0
    while (packets_to_read-- && !handle->break_loop) {
4527
0
      struct tpacket3_hdr* tp3_hdr = (struct tpacket3_hdr*) handlep->current_packet;
4528
0
      ret = pcap_handle_packet_mmap(
4529
0
          handle,
4530
0
          callback,
4531
0
          user,
4532
0
          handlep->current_packet,
4533
0
          tp3_hdr->tp_len,
4534
0
          tp3_hdr->tp_mac,
4535
0
          tp3_hdr->tp_snaplen,
4536
0
          tp3_hdr->tp_sec,
4537
0
          handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? tp3_hdr->tp_nsec : tp3_hdr->tp_nsec / 1000,
4538
0
          VLAN_VALID(tp3_hdr, &tp3_hdr->hv1),
4539
0
          tp3_hdr->hv1.tp_vlan_tci,
4540
0
          VLAN_TPID(tp3_hdr, &tp3_hdr->hv1));
4541
0
      if (ret == 1) {
4542
0
        pkts++;
4543
0
      } else if (ret < 0) {
4544
0
        handlep->current_packet = NULL;
4545
0
        return ret;
4546
0
      }
4547
0
      handlep->current_packet += tp3_hdr->tp_next_offset;
4548
0
      handlep->packets_left--;
4549
0
    }
4550
4551
0
    if (handlep->packets_left <= 0) {
4552
      /*
4553
       * Hand this block back to the kernel, and, if
4554
       * we're counting blocks that need to be
4555
       * filtered in userland after having been
4556
       * filtered by the kernel, count the one we've
4557
       * just processed.
4558
       */
4559
0
      packet_mmap_v3_release(h.h3);
4560
0
      if (handlep->blocks_to_filter_in_userland != 0) {
4561
0
        handlep->blocks_to_filter_in_userland--;
4562
0
        if (handlep->blocks_to_filter_in_userland == 0) {
4563
          /*
4564
           * No more blocks need to be filtered
4565
           * in userland.
4566
           */
4567
0
          handlep->filter_in_userland = 0;
4568
0
        }
4569
0
      }
4570
4571
      /* next block */
4572
0
      if (++handle->offset >= handle->cc)
4573
0
        handle->offset = 0;
4574
4575
0
      handlep->current_packet = NULL;
4576
0
    }
4577
4578
    /* check for break loop condition*/
4579
0
    if (handle->break_loop) {
4580
0
      handle->break_loop = 0;
4581
0
      return PCAP_ERROR_BREAK;
4582
0
    }
4583
0
  }
4584
0
  if (pkts == 0 && handlep->timeout == 0) {
4585
    /* Block until we see a packet. */
4586
0
    goto again;
4587
0
  }
4588
0
  return pkts;
4589
0
}
4590
#endif /* HAVE_TPACKET3 */
4591
4592
/*
4593
 *  Attach the given BPF code to the packet capture device.
4594
 */
4595
static int
4596
pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
4597
0
{
4598
0
  struct pcap_linux *handlep;
4599
0
  struct sock_fprog fcode;
4600
0
  int     can_filter_in_kernel;
4601
0
  int     err = 0;
4602
0
  u_int     n, offset;
4603
4604
0
  if (!handle)
4605
0
    return -1;
4606
0
  if (!filter) {
4607
0
          pcapint_strlcpy(handle->errbuf, "setfilter: No filter specified",
4608
0
      PCAP_ERRBUF_SIZE);
4609
0
    return -1;
4610
0
  }
4611
4612
0
  handlep = handle->priv;
4613
4614
  /* Make our private copy of the filter */
4615
4616
0
  if (pcapint_install_bpf_program(handle, filter) < 0)
4617
    /* pcapint_install_bpf_program() filled in errbuf */
4618
0
    return -1;
4619
4620
  /*
4621
   * Run user level packet filter by default. Will be overridden if
4622
   * installing a kernel filter succeeds.
4623
   */
4624
0
  handlep->filter_in_userland = 1;
4625
4626
  /* Install kernel level filter if possible */
4627
4628
0
  if (handle->fcode.bf_len > USHRT_MAX) {
4629
    /*
4630
     * fcode.len is an unsigned short for current kernel.
4631
     * I have yet to see BPF-Code with that much
4632
     * instructions but still it is possible. So for the
4633
     * sake of correctness I added this check.
4634
     */
4635
0
    fprintf(stderr, "Warning: Filter too complex for kernel\n");
4636
0
    fcode.len = 0;
4637
0
    fcode.filter = NULL;
4638
0
    can_filter_in_kernel = 0;
4639
0
  } else {
4640
    /*
4641
     * Oh joy, the Linux kernel uses struct sock_fprog instead
4642
     * of struct bpf_program and of course the length field is
4643
     * of different size. Pointed out by Sebastian
4644
     *
4645
     * Oh, and we also need to fix it up so that all "ret"
4646
     * instructions with non-zero operands have MAXIMUM_SNAPLEN
4647
     * as the operand if we're not capturing in memory-mapped
4648
     * mode, and so that, if we're in cooked mode, all memory-
4649
     * reference instructions use special magic offsets in
4650
     * references to the link-layer header and assume that the
4651
     * link-layer payload begins at 0; "fix_program()" will do
4652
     * that.
4653
     */
4654
0
    switch (fix_program(handle, &fcode)) {
4655
4656
0
    case -1:
4657
0
    default:
4658
      /*
4659
       * Fatal error; just quit.
4660
       * (The "default" case shouldn't happen; we
4661
       * return -1 for that reason.)
4662
       */
4663
0
      return -1;
4664
4665
0
    case 0:
4666
      /*
4667
       * The program performed checks that we can't make
4668
       * work in the kernel.
4669
       */
4670
0
      can_filter_in_kernel = 0;
4671
0
      break;
4672
4673
0
    case 1:
4674
      /*
4675
       * We have a filter that'll work in the kernel.
4676
       */
4677
0
      can_filter_in_kernel = 1;
4678
0
      break;
4679
0
    }
4680
0
  }
4681
4682
  /*
4683
   * NOTE: at this point, we've set both the "len" and "filter"
4684
   * fields of "fcode".  As of the 2.6.32.4 kernel, at least,
4685
   * those are the only members of the "sock_fprog" structure,
4686
   * so we initialize every member of that structure.
4687
   *
4688
   * If there is anything in "fcode" that is not initialized,
4689
   * it is either a field added in a later kernel, or it's
4690
   * padding.
4691
   *
4692
   * If a new field is added, this code needs to be updated
4693
   * to set it correctly.
4694
   *
4695
   * If there are no other fields, then:
4696
   *
4697
   *  if the Linux kernel looks at the padding, it's
4698
   *  buggy;
4699
   *
4700
   *  if the Linux kernel doesn't look at the padding,
4701
   *  then if some tool complains that we're passing
4702
   *  uninitialized data to the kernel, then the tool
4703
   *  is buggy and needs to understand that it's just
4704
   *  padding.
4705
   */
4706
0
  if (can_filter_in_kernel) {
4707
0
    if ((err = set_kernel_filter(handle, &fcode)) == 0)
4708
0
    {
4709
      /*
4710
       * Installation succeeded - using kernel filter,
4711
       * so userland filtering not needed.
4712
       */
4713
0
      handlep->filter_in_userland = 0;
4714
0
    }
4715
0
    else if (err == -1) /* Non-fatal error */
4716
0
    {
4717
      /*
4718
       * Print a warning if we weren't able to install
4719
       * the filter for a reason other than "this kernel
4720
       * isn't configured to support socket filters.
4721
       */
4722
0
      if (errno == ENOMEM) {
4723
        /*
4724
         * Either a kernel memory allocation
4725
         * failure occurred, or there's too
4726
         * much "other/option memory" allocated
4727
         * for this socket.  Suggest that they
4728
         * increase the "other/option memory"
4729
         * limit.
4730
         */
4731
0
        fprintf(stderr,
4732
0
            "Warning: Couldn't allocate kernel memory for filter: try increasing net.core.optmem_max with sysctl\n");
4733
0
      } else if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
4734
0
        fprintf(stderr,
4735
0
            "Warning: Kernel filter failed: %s\n",
4736
0
          pcap_strerror(errno));
4737
0
      }
4738
0
    }
4739
0
  }
4740
4741
  /*
4742
   * If we're not using the kernel filter, get rid of any kernel
4743
   * filter that might've been there before, e.g. because the
4744
   * previous filter could work in the kernel, or because some other
4745
   * code attached a filter to the socket by some means other than
4746
   * calling "pcap_setfilter()".  Otherwise, the kernel filter may
4747
   * filter out packets that would pass the new userland filter.
4748
   */
4749
0
  if (handlep->filter_in_userland) {
4750
0
    if (reset_kernel_filter(handle) == -1) {
4751
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
4752
0
          PCAP_ERRBUF_SIZE, errno,
4753
0
          "can't remove kernel filter");
4754
0
      err = -2; /* fatal error */
4755
0
    }
4756
0
  }
4757
4758
  /*
4759
   * Free up the copy of the filter that was made by "fix_program()".
4760
   */
4761
0
  if (fcode.filter != NULL)
4762
0
    free(fcode.filter);
4763
4764
0
  if (err == -2)
4765
    /* Fatal error */
4766
0
    return -1;
4767
4768
  /*
4769
   * If we're filtering in userland, there's nothing to do;
4770
   * the new filter will be used for the next packet.
4771
   */
4772
0
  if (handlep->filter_in_userland)
4773
0
    return 0;
4774
4775
  /*
4776
   * We're filtering in the kernel; the packets present in
4777
   * all blocks currently in the ring were already filtered
4778
   * by the old filter, and so will need to be filtered in
4779
   * userland by the new filter.
4780
   *
4781
   * Get an upper bound for the number of such blocks; first,
4782
   * walk the ring backward and count the free blocks.
4783
   */
4784
0
  offset = handle->offset;
4785
0
  if (offset == 0)
4786
0
    offset = handle->cc;
4787
0
  offset--;
4788
0
  for (n=0; n < handle->cc; ++n) {
4789
0
    if (offset == 0)
4790
0
      offset = handle->cc;
4791
0
    offset--;
4792
0
    if (pcap_get_ring_frame_status(handle, offset) != TP_STATUS_KERNEL)
4793
0
      break;
4794
0
  }
4795
4796
  /*
4797
   * If we found free blocks, decrement the count of free
4798
   * blocks by 1, just in case we lost a race with another
4799
   * thread of control that was adding a packet while
4800
   * we were counting and that had run the filter before
4801
   * we changed it.
4802
   *
4803
   * XXX - could there be more than one block added in
4804
   * this fashion?
4805
   *
4806
   * XXX - is there a way to avoid that race, e.g. somehow
4807
   * wait for all packets that passed the old filter to
4808
   * be added to the ring?
4809
   */
4810
0
  if (n != 0)
4811
0
    n--;
4812
4813
  /*
4814
   * Set the count of blocks worth of packets to filter
4815
   * in userland to the total number of blocks in the
4816
   * ring minus the number of free blocks we found, and
4817
   * turn on userland filtering.  (The count of blocks
4818
   * worth of packets to filter in userland is guaranteed
4819
   * not to be zero - n, above, couldn't be set to a
4820
   * value > handle->cc, and if it were equal to
4821
   * handle->cc, it wouldn't be zero, and thus would
4822
   * be decremented to handle->cc - 1.)
4823
   */
4824
0
  handlep->blocks_to_filter_in_userland = handle->cc - n;
4825
0
  handlep->filter_in_userland = 1;
4826
4827
0
  return 0;
4828
0
}
4829
4830
/*
4831
 *  Return the index of the given device name. Fill ebuf and return
4832
 *  -1 on failure.
4833
 */
4834
static int
4835
iface_get_id(int fd, const char *device, char *ebuf)
4836
0
{
4837
0
  struct ifreq  ifr;
4838
4839
0
  memset(&ifr, 0, sizeof(ifr));
4840
0
  pcapint_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
4841
4842
0
  if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
4843
0
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
4844
0
        errno, "SIOCGIFINDEX");
4845
0
    return -1;
4846
0
  }
4847
4848
0
  return ifr.ifr_ifindex;
4849
0
}
4850
4851
/*
4852
 *  Bind the socket associated with FD to the given device.
4853
 *  Return 0 on success or a PCAP_ERROR_ value on a hard error.
4854
 */
4855
static int
4856
iface_bind(int fd, int ifindex, char *ebuf, int protocol)
4857
0
{
4858
0
  struct sockaddr_ll  sll;
4859
0
  int     ret, err;
4860
0
  socklen_t   errlen = sizeof(err);
4861
4862
0
  memset(&sll, 0, sizeof(sll));
4863
0
  sll.sll_family    = AF_PACKET;
4864
0
  sll.sll_ifindex   = ifindex < 0 ? 0 : ifindex;
4865
0
  sll.sll_protocol  = protocol;
4866
4867
0
  if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
4868
0
    if (errno == ENETDOWN) {
4869
      /*
4870
       * Return a "network down" indication, so that
4871
       * the application can report that rather than
4872
       * saying we had a mysterious failure and
4873
       * suggest that they report a problem to the
4874
       * libpcap developers.
4875
       */
4876
0
      return PCAP_ERROR_IFACE_NOT_UP;
4877
0
    }
4878
0
    if (errno == ENODEV) {
4879
      /*
4880
       * There's nothing more to say, so clear the
4881
       * error message.
4882
       */
4883
0
      ebuf[0] = '\0';
4884
0
      ret = PCAP_ERROR_NO_SUCH_DEVICE;
4885
0
    } else {
4886
0
      ret = PCAP_ERROR;
4887
0
      pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
4888
0
          errno, "bind");
4889
0
    }
4890
0
    return ret;
4891
0
  }
4892
4893
  /* Any pending errors, e.g., network is down? */
4894
4895
0
  if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
4896
0
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
4897
0
        errno, "getsockopt (SO_ERROR)");
4898
0
    return PCAP_ERROR;
4899
0
  }
4900
4901
0
  if (err == ENETDOWN) {
4902
    /*
4903
     * Return a "network down" indication, so that
4904
     * the application can report that rather than
4905
     * saying we had a mysterious failure and
4906
     * suggest that they report a problem to the
4907
     * libpcap developers.
4908
     */
4909
0
    return PCAP_ERROR_IFACE_NOT_UP;
4910
0
  } else if (err > 0) {
4911
0
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
4912
0
        err, "bind");
4913
0
    return PCAP_ERROR;
4914
0
  }
4915
4916
0
  return 0;
4917
0
}
4918
4919
/*
4920
 * Try to enter monitor mode.
4921
 * If we have libnl, try to create a new monitor-mode device and
4922
 * capture on that; otherwise, just say "not supported".
4923
 */
4924
#ifdef HAVE_LIBNL
4925
static int
4926
enter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
4927
{
4928
  struct pcap_linux *handlep = handle->priv;
4929
  int ret;
4930
  char phydev_path[PATH_MAX+1];
4931
  struct nl80211_state nlstate;
4932
  struct ifreq ifr;
4933
  u_int n;
4934
4935
  /*
4936
   * Is this a mac80211 device?
4937
   */
4938
  ret = get_mac80211_phydev(handle, device, phydev_path, PATH_MAX);
4939
  if (ret < 0)
4940
    return ret; /* error */
4941
  if (ret == 0)
4942
    return 0; /* no error, but not mac80211 device */
4943
4944
  ret = nl80211_init(handle, &nlstate, device);
4945
  if (ret != 0)
4946
    return ret;
4947
4948
  /*
4949
   * Is this already a monN device?
4950
   * If so, we're done.
4951
   */
4952
  int type;
4953
  ret = get_if_type(handle, sock_fd, &nlstate, device, &type);
4954
  if (ret <= 0) {
4955
    /*
4956
     * < 0 is a Hard failure.  Just return ret; handle->errbuf
4957
     * has already been set.
4958
     *
4959
     * 0 is "device not available"; the caller should retry later.
4960
     */
4961
    nl80211_cleanup(&nlstate);
4962
    return ret;
4963
  }
4964
  if (type == NL80211_IFTYPE_MONITOR) {
4965
    /*
4966
     * OK, it's already a monitor mode device; just use it.
4967
     * There's no point in creating another monitor device
4968
     * that will have to be cleaned up.
4969
     */
4970
    nl80211_cleanup(&nlstate);
4971
    return ret;
4972
  }
4973
4974
  /*
4975
   * OK, it's apparently a mac80211 device but not a monitor device.
4976
   * Try to find an unused monN device for it.
4977
   */
4978
  for (n = 0; n < UINT_MAX; n++) {
4979
    /*
4980
     * Try mon{n}.
4981
     */
4982
    char mondevice[3+10+1]; /* mon{UINT_MAX}\0 */
4983
4984
    snprintf(mondevice, sizeof mondevice, "mon%u", n);
4985
    ret = add_mon_if(handle, sock_fd, &nlstate, device, mondevice);
4986
    if (ret == 1) {
4987
      /*
4988
       * Success.  We don't clean up the libnl state
4989
       * yet, as we'll be using it later.
4990
       */
4991
      goto added;
4992
    }
4993
    if (ret < 0) {
4994
      /*
4995
       * Hard failure.  Just return ret; handle->errbuf
4996
       * has already been set.
4997
       */
4998
      nl80211_cleanup(&nlstate);
4999
      return ret;
5000
    }
5001
  }
5002
5003
  snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5004
      "%s: No free monN interfaces", device);
5005
  nl80211_cleanup(&nlstate);
5006
  return PCAP_ERROR;
5007
5008
added:
5009
5010
#if 0
5011
  /*
5012
   * Sleep for .1 seconds.
5013
   */
5014
  delay.tv_sec = 0;
5015
  delay.tv_nsec = 500000000;
5016
  nanosleep(&delay, NULL);
5017
#endif
5018
5019
  /*
5020
   * If we haven't already done so, arrange to have
5021
   * "pcap_close_all()" called when we exit.
5022
   */
5023
  if (!pcapint_do_addexit(handle)) {
5024
    /*
5025
     * "atexit()" failed; don't put the interface
5026
     * in rfmon mode, just give up.
5027
     * handle->errbuf has already been filled.
5028
     */
5029
    del_mon_if(handle, sock_fd, &nlstate, device,
5030
        handlep->mondevice);
5031
    nl80211_cleanup(&nlstate);
5032
    return PCAP_ERROR;
5033
  }
5034
5035
  /*
5036
   * Now configure the monitor interface up.
5037
   */
5038
  memset(&ifr, 0, sizeof(ifr));
5039
  pcapint_strlcpy(ifr.ifr_name, handlep->mondevice, sizeof(ifr.ifr_name));
5040
  if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
5041
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
5042
        errno, "%s: Can't get flags for %s", device,
5043
        handlep->mondevice);
5044
    del_mon_if(handle, sock_fd, &nlstate, device,
5045
        handlep->mondevice);
5046
    nl80211_cleanup(&nlstate);
5047
    return PCAP_ERROR;
5048
  }
5049
  ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
5050
  if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
5051
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
5052
        errno, "%s: Can't set flags for %s", device,
5053
        handlep->mondevice);
5054
    del_mon_if(handle, sock_fd, &nlstate, device,
5055
        handlep->mondevice);
5056
    nl80211_cleanup(&nlstate);
5057
    return PCAP_ERROR;
5058
  }
5059
5060
  /*
5061
   * Success.  Clean up the libnl state.
5062
   */
5063
  nl80211_cleanup(&nlstate);
5064
5065
  /*
5066
   * Note that we have to delete the monitor device when we close
5067
   * the handle.
5068
   */
5069
  handlep->must_do_on_close |= MUST_DELETE_MONIF;
5070
5071
  /*
5072
   * Add this to the list of pcaps to close when we exit.
5073
   */
5074
  pcapint_add_to_pcaps_to_close(handle);
5075
5076
  return 1;
5077
}
5078
#else /* HAVE_LIBNL */
5079
static int
5080
enter_rfmon_mode(pcap_t *handle _U_, int sock_fd _U_, const char *device _U_)
5081
0
{
5082
  /*
5083
   * We don't have libnl, so we can't do monitor mode.
5084
   */
5085
0
  return 0;
5086
0
}
5087
#endif /* HAVE_LIBNL */
5088
5089
#if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
5090
/*
5091
 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
5092
 */
5093
static const struct {
5094
  int soft_timestamping_val;
5095
  int pcap_tstamp_val;
5096
} sof_ts_type_map[3] = {
5097
  { SOF_TIMESTAMPING_SOFTWARE, PCAP_TSTAMP_HOST },
5098
  { SOF_TIMESTAMPING_SYS_HARDWARE, PCAP_TSTAMP_ADAPTER },
5099
  { SOF_TIMESTAMPING_RAW_HARDWARE, PCAP_TSTAMP_ADAPTER_UNSYNCED }
5100
};
5101
0
#define NUM_SOF_TIMESTAMPING_TYPES  (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
5102
5103
/*
5104
 * Set the list of time stamping types to include all types.
5105
 */
5106
static int
5107
iface_set_all_ts_types(pcap_t *handle, char *ebuf)
5108
0
{
5109
0
  u_int i;
5110
5111
0
  handle->tstamp_type_list = malloc(NUM_SOF_TIMESTAMPING_TYPES * sizeof(u_int));
5112
0
  if (handle->tstamp_type_list == NULL) {
5113
0
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5114
0
        errno, "malloc");
5115
0
    return -1;
5116
0
  }
5117
0
  for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++)
5118
0
    handle->tstamp_type_list[i] = sof_ts_type_map[i].pcap_tstamp_val;
5119
0
  handle->tstamp_type_count = NUM_SOF_TIMESTAMPING_TYPES;
5120
0
  return 0;
5121
0
}
5122
5123
/*
5124
 * Get a list of time stamp types.
5125
 */
5126
#ifdef ETHTOOL_GET_TS_INFO
5127
static int
5128
iface_get_ts_types(const char *device, pcap_t *handle, char *ebuf)
5129
0
{
5130
0
  int fd;
5131
0
  struct ifreq ifr;
5132
0
  struct ethtool_ts_info info;
5133
0
  int num_ts_types;
5134
0
  u_int i, j;
5135
5136
  /*
5137
   * This doesn't apply to the "any" device; you can't say "turn on
5138
   * hardware time stamping for all devices that exist now and arrange
5139
   * that it be turned on for any device that appears in the future",
5140
   * and not all devices even necessarily *support* hardware time
5141
   * stamping, so don't report any time stamp types.
5142
   */
5143
0
  if (strcmp(device, "any") == 0) {
5144
0
    handle->tstamp_type_list = NULL;
5145
0
    return 0;
5146
0
  }
5147
5148
  /*
5149
   * Create a socket from which to fetch time stamping capabilities.
5150
   */
5151
0
  fd = get_if_ioctl_socket();
5152
0
  if (fd < 0) {
5153
0
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5154
0
        errno, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
5155
0
    return -1;
5156
0
  }
5157
5158
0
  memset(&ifr, 0, sizeof(ifr));
5159
0
  pcapint_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5160
0
  memset(&info, 0, sizeof(info));
5161
0
  info.cmd = ETHTOOL_GET_TS_INFO;
5162
0
  ifr.ifr_data = (caddr_t)&info;
5163
0
  if (ioctl(fd, SIOCETHTOOL, &ifr) == -1) {
5164
0
    int save_errno = errno;
5165
5166
0
    close(fd);
5167
0
    switch (save_errno) {
5168
5169
0
    case EOPNOTSUPP:
5170
0
    case EINVAL:
5171
      /*
5172
       * OK, this OS version or driver doesn't support
5173
       * asking for the time stamping types, so let's
5174
       * just return all the possible types.
5175
       */
5176
0
      if (iface_set_all_ts_types(handle, ebuf) == -1)
5177
0
        return -1;
5178
0
      return 0;
5179
5180
0
    case ENODEV:
5181
      /*
5182
       * OK, no such device.
5183
       * The user will find that out when they try to
5184
       * activate the device; just return an empty
5185
       * list of time stamp types.
5186
       */
5187
0
      handle->tstamp_type_list = NULL;
5188
0
      return 0;
5189
5190
0
    default:
5191
      /*
5192
       * Other error.
5193
       */
5194
0
      pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5195
0
          save_errno,
5196
0
          "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
5197
0
          device);
5198
0
      return -1;
5199
0
    }
5200
0
  }
5201
0
  close(fd);
5202
5203
  /*
5204
   * Do we support hardware time stamping of *all* packets?
5205
   */
5206
0
  if (!(info.rx_filters & (1 << HWTSTAMP_FILTER_ALL))) {
5207
    /*
5208
     * No, so don't report any time stamp types.
5209
     *
5210
     * XXX - some devices either don't report
5211
     * HWTSTAMP_FILTER_ALL when they do support it, or
5212
     * report HWTSTAMP_FILTER_ALL but map it to only
5213
     * time stamping a few PTP packets.  See
5214
     * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
5215
     *
5216
     * Maybe that got fixed later.
5217
     */
5218
0
    handle->tstamp_type_list = NULL;
5219
0
    return 0;
5220
0
  }
5221
5222
0
  num_ts_types = 0;
5223
0
  for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
5224
0
    if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val)
5225
0
      num_ts_types++;
5226
0
  }
5227
0
  if (num_ts_types != 0) {
5228
0
    handle->tstamp_type_list = malloc(num_ts_types * sizeof(u_int));
5229
0
    if (handle->tstamp_type_list == NULL) {
5230
0
      pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5231
0
          errno, "malloc");
5232
0
      return -1;
5233
0
    }
5234
0
    for (i = 0, j = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
5235
0
      if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val) {
5236
0
        handle->tstamp_type_list[j] = sof_ts_type_map[i].pcap_tstamp_val;
5237
0
        j++;
5238
0
      }
5239
0
    }
5240
0
    handle->tstamp_type_count = num_ts_types;
5241
0
  } else
5242
0
    handle->tstamp_type_list = NULL;
5243
5244
0
  return 0;
5245
0
}
5246
#else /* ETHTOOL_GET_TS_INFO */
5247
static int
5248
iface_get_ts_types(const char *device, pcap_t *handle, char *ebuf)
5249
{
5250
  /*
5251
   * This doesn't apply to the "any" device; you can't say "turn on
5252
   * hardware time stamping for all devices that exist now and arrange
5253
   * that it be turned on for any device that appears in the future",
5254
   * and not all devices even necessarily *support* hardware time
5255
   * stamping, so don't report any time stamp types.
5256
   */
5257
  if (strcmp(device, "any") == 0) {
5258
    handle->tstamp_type_list = NULL;
5259
    return 0;
5260
  }
5261
5262
  /*
5263
   * We don't have an ioctl to use to ask what's supported,
5264
   * so say we support everything.
5265
   */
5266
  if (iface_set_all_ts_types(handle, ebuf) == -1)
5267
    return -1;
5268
  return 0;
5269
}
5270
#endif /* ETHTOOL_GET_TS_INFO */
5271
#else  /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
5272
static int
5273
iface_get_ts_types(const char *device _U_, pcap_t *p _U_, char *ebuf _U_)
5274
{
5275
  /*
5276
   * Nothing to fetch, so it always "succeeds".
5277
   */
5278
  return 0;
5279
}
5280
#endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
5281
5282
/*
5283
 * Find out if we have any form of fragmentation/reassembly offloading.
5284
 *
5285
 * We do so using SIOCETHTOOL checking for various types of offloading;
5286
 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
5287
 * of the types of offloading, there's nothing we can do to check, so
5288
 * we just say "no, we don't".
5289
 *
5290
 * We treat EOPNOTSUPP, EINVAL and, if eperm_ok is true, EPERM as
5291
 * indications that the operation isn't supported.  We do EPERM
5292
 * weirdly because the SIOCETHTOOL code in later kernels 1) doesn't
5293
 * support ETHTOOL_GUFO, 2) also doesn't include it in the list
5294
 * of ethtool operations that don't require CAP_NET_ADMIN privileges,
5295
 * and 3) does the "is this permitted" check before doing the "is
5296
 * this even supported" check, so it fails with "this is not permitted"
5297
 * rather than "this is not even supported".  To work around this
5298
 * annoyance, we only treat EPERM as an error for the first feature,
5299
 * and assume that they all do the same permission checks, so if the
5300
 * first one is allowed all the others are allowed if supported.
5301
 */
5302
#if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
5303
static int
5304
iface_ethtool_flag_ioctl(pcap_t *handle, int cmd, const char *cmdname,
5305
    int eperm_ok)
5306
0
{
5307
0
  struct ifreq  ifr;
5308
0
  struct ethtool_value eval;
5309
5310
0
  memset(&ifr, 0, sizeof(ifr));
5311
0
  pcapint_strlcpy(ifr.ifr_name, handle->opt.device, sizeof(ifr.ifr_name));
5312
0
  eval.cmd = cmd;
5313
0
  eval.data = 0;
5314
0
  ifr.ifr_data = (caddr_t)&eval;
5315
0
  if (ioctl(handle->fd, SIOCETHTOOL, &ifr) == -1) {
5316
0
    if (errno == EOPNOTSUPP || errno == EINVAL ||
5317
0
        (errno == EPERM && eperm_ok)) {
5318
      /*
5319
       * OK, let's just return 0, which, in our
5320
       * case, either means "no, what we're asking
5321
       * about is not enabled" or "all the flags
5322
       * are clear (i.e., nothing is enabled)".
5323
       */
5324
0
      return 0;
5325
0
    }
5326
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
5327
0
        errno, "%s: SIOCETHTOOL(%s) ioctl failed",
5328
0
        handle->opt.device, cmdname);
5329
0
    return -1;
5330
0
  }
5331
0
  return eval.data;
5332
0
}
5333
5334
/*
5335
 * XXX - it's annoying that we have to check for offloading at all, but,
5336
 * given that we have to, it's still annoying that we have to check for
5337
 * particular types of offloading, especially that shiny new types of
5338
 * offloading may be added - and, worse, may not be checkable with
5339
 * a particular ETHTOOL_ operation; ETHTOOL_GFEATURES would, in
5340
 * theory, give those to you, but the actual flags being used are
5341
 * opaque (defined in a non-uapi header), and there doesn't seem to
5342
 * be any obvious way to ask the kernel what all the offloading flags
5343
 * are - at best, you can ask for a set of strings(!) to get *names*
5344
 * for various flags.  (That whole mechanism appears to have been
5345
 * designed for the sole purpose of letting ethtool report flags
5346
 * by name and set flags by name, with the names having no semantics
5347
 * ethtool understands.)
5348
 */
5349
static int
5350
iface_get_offload(pcap_t *handle)
5351
0
{
5352
0
  int ret;
5353
5354
0
#ifdef ETHTOOL_GTSO
5355
0
  ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GTSO, "ETHTOOL_GTSO", 0);
5356
0
  if (ret == -1)
5357
0
    return -1;
5358
0
  if (ret)
5359
0
    return 1; /* TCP segmentation offloading on */
5360
0
#endif
5361
5362
0
#ifdef ETHTOOL_GGSO
5363
  /*
5364
   * XXX - will this cause large unsegmented packets to be
5365
   * handed to PF_PACKET sockets on transmission?  If not,
5366
   * this need not be checked.
5367
   */
5368
0
  ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGSO, "ETHTOOL_GGSO", 0);
5369
0
  if (ret == -1)
5370
0
    return -1;
5371
0
  if (ret)
5372
0
    return 1; /* generic segmentation offloading on */
5373
0
#endif
5374
5375
0
#ifdef ETHTOOL_GFLAGS
5376
0
  ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GFLAGS, "ETHTOOL_GFLAGS", 0);
5377
0
  if (ret == -1)
5378
0
    return -1;
5379
0
  if (ret & ETH_FLAG_LRO)
5380
0
    return 1; /* large receive offloading on */
5381
0
#endif
5382
5383
0
#ifdef ETHTOOL_GGRO
5384
  /*
5385
   * XXX - will this cause large reassembled packets to be
5386
   * handed to PF_PACKET sockets on receipt?  If not,
5387
   * this need not be checked.
5388
   */
5389
0
  ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGRO, "ETHTOOL_GGRO", 0);
5390
0
  if (ret == -1)
5391
0
    return -1;
5392
0
  if (ret)
5393
0
    return 1; /* generic (large) receive offloading on */
5394
0
#endif
5395
5396
0
#ifdef ETHTOOL_GUFO
5397
  /*
5398
   * Do this one last, as support for it was removed in later
5399
   * kernels, and it fails with EPERM on those kernels rather
5400
   * than with EOPNOTSUPP (see explanation in comment for
5401
   * iface_ethtool_flag_ioctl()).
5402
   */
5403
0
  ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GUFO, "ETHTOOL_GUFO", 1);
5404
0
  if (ret == -1)
5405
0
    return -1;
5406
0
  if (ret)
5407
0
    return 1; /* UDP fragmentation offloading on */
5408
0
#endif
5409
5410
0
  return 0;
5411
0
}
5412
#else /* SIOCETHTOOL */
5413
static int
5414
iface_get_offload(pcap_t *handle _U_)
5415
{
5416
  /*
5417
   * XXX - do we need to get this information if we don't
5418
   * have the ethtool ioctls?  If so, how do we do that?
5419
   */
5420
  return 0;
5421
}
5422
#endif /* SIOCETHTOOL */
5423
5424
/*
5425
 * As per
5426
 *
5427
 *    https://www.kernel.org/doc/html/latest/networking/dsa/dsa.html#switch-tagging-protocols
5428
 *
5429
 * Type 1 means that the tag is prepended to the Ethernet packet.
5430
 *
5431
 * Type 2 means that the tag is inserted into the Ethernet header
5432
 * after the source address and before the type/length field.
5433
 *
5434
 * Type 3 means that tag is a packet trailer.
5435
 *
5436
 * Every element in the array below uses a DLT.  Because a DSA-tagged frame is
5437
 * not a standard IEEE 802.3 Ethernet frame, the array elements must not use
5438
 * DLT_EN10MB.  It is safe, albeit only barely useful, to use DLT_DEBUG_ONLY,
5439
 * which is also the implicit default for any DSA tag that is not present in
5440
 * the array.  To implement proper support for a particular DSA tag of
5441
 * interest, please do as much of the following as is reasonably practicable:
5442
 *
5443
 * 1. Using recent versions of tcpdump and libpcap on a Linux host with a
5444
 *    network interface that implements the required DSA tag, capture packets
5445
 *    on the interface and study the hex dumps.
5446
 * 2. Using the hex dumps and any other available supporting materials, produce
5447
 *    a sufficiently detailed description of the DSA tag structure, complete
5448
 *    with a full comment indicating whether it's type 1, 2, or 3, and, for
5449
 *    type 2, indicating whether it has an EtherType and, if so, what that type
5450
 *    is, and whether it's registered with the IEEE or not.  Refer to the
5451
 *    specification(s), existing implementation(s), or any other relevant
5452
 *    resources.
5453
 * 3. Using the description, request and obtain a new DLT for the DSA tag.
5454
 * 4. Associate the new DLT with the DSA tag in the array below.
5455
 * 5. Using the updated libpcap, capture packets again, produce a .pcap file
5456
 *    and confirm it uses the new DLT.
5457
 * 6. Using the .pcap file as a test, prepare additional changes to tcpdump to
5458
 *    enable decoding of packets for the new DLT.
5459
 * 7. Using the .pcap file as a test, prepare additional changes to libpcap to
5460
 *    enable filtering of packets for the new DLT.
5461
 *
5462
 * For working examples of such support, see the existing DLTs other than
5463
 * DLT_DEBUG_ONLY in the array below.
5464
 */
5465
static struct dsa_proto {
5466
  const char *name;
5467
  bpf_u_int32 linktype;
5468
} dsa_protos[] = {
5469
  /*
5470
   * Type 1. See
5471
   *
5472
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ar9331.c
5473
   */
5474
  { "ar9331", DLT_DEBUG_ONLY },
5475
5476
  /*
5477
   * Type 2, without an EtherType at the beginning.
5478
   */
5479
  { "brcm", DLT_DSA_TAG_BRCM },
5480
5481
  /*
5482
   * Type 2, with EtherType 0x8874, assigned to Broadcom.
5483
   */
5484
  { "brcm-legacy", DLT_DEBUG_ONLY },
5485
5486
  /*
5487
   * Type 1.
5488
   */
5489
  { "brcm-prepend", DLT_DSA_TAG_BRCM_PREPEND },
5490
5491
  /*
5492
   * Type 2, without an EtherType at the beginning.
5493
   */
5494
  { "dsa", DLT_DSA_TAG_DSA },
5495
5496
  /*
5497
   * Type 2, with an EtherType field, but without
5498
   * an assigned EtherType value that can be relied
5499
   * on.
5500
   */
5501
  { "edsa", DLT_DSA_TAG_EDSA },
5502
5503
  /*
5504
   * Type 1, with different transmit and receive headers,
5505
   * so can't really be handled well with the current
5506
   * libpcap API and with pcap files.
5507
   *
5508
   * See
5509
   *
5510
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_gswip.c
5511
   */
5512
  { "gswip", DLT_DEBUG_ONLY },
5513
5514
  /*
5515
   * Type 3. See
5516
   *
5517
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_hellcreek.c
5518
   */
5519
  { "hellcreek", DLT_DEBUG_ONLY },
5520
5521
  /*
5522
   * Type 3, with different transmit and receive headers,
5523
   * so can't really be handled well with the current
5524
   * libpcap API and with pcap files.
5525
   *
5526
   * See
5527
   *
5528
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ksz.c#L102
5529
   */
5530
  { "ksz8795", DLT_DEBUG_ONLY },
5531
5532
  /*
5533
   * Type 3, with different transmit and receive headers,
5534
   * so can't really be handled well with the current
5535
   * libpcap API and with pcap files.
5536
   *
5537
   * See
5538
   *
5539
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ksz.c#L160
5540
   */
5541
  { "ksz9477", DLT_DEBUG_ONLY },
5542
5543
  /*
5544
   * Type 3, with different transmit and receive headers,
5545
   * so can't really be handled well with the current
5546
   * libpcap API and with pcap files.
5547
   *
5548
   * See
5549
   *
5550
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ksz.c#L341
5551
   */
5552
  { "ksz9893", DLT_DEBUG_ONLY },
5553
5554
  /*
5555
   * Type 3, with different transmit and receive headers,
5556
   * so can't really be handled well with the current
5557
   * libpcap API and with pcap files.
5558
   *
5559
   * See
5560
   *
5561
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ksz.c#L386
5562
   */
5563
  { "lan937x", DLT_DEBUG_ONLY },
5564
5565
  /*
5566
   * Type 2, with EtherType 0x8100; the VID can be interpreted
5567
   * as per
5568
   *
5569
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_lan9303.c#L24
5570
   */
5571
  { "lan9303", DLT_DEBUG_ONLY },
5572
5573
  /*
5574
   * Type 2, without an EtherType at the beginning.
5575
   *
5576
   * See
5577
   *
5578
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_mtk.c#L15
5579
   *
5580
   * Linux kernel implements this tag so that it does not indicate the frame
5581
   * encoding reliably.  The matter is, some drivers use METADATA_HW_PORT_MUX,
5582
   * which (for the switch->CPU direction only, at the time of this writing)
5583
   * means that the frame does not have a DSA tag, the frame metadata is stored
5584
   * elsewhere and libpcap receives the frame only.  Specifically, this is the
5585
   * case for drivers/net/ethernet/mediatek/mtk_eth_soc.c, but the tag visible
5586
   * in sysfs is still "mtk" even though the wire encoding is different.
5587
   */
5588
  { "mtk", DLT_DEBUG_ONLY },
5589
5590
  /*
5591
   * Type 1.
5592
   *
5593
   * See
5594
   *
5595
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ocelot.c
5596
   */
5597
  { "ocelot", DLT_DEBUG_ONLY },
5598
5599
  /*
5600
   * Type 1.
5601
   *
5602
   * See
5603
   *
5604
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ocelot.c
5605
   */
5606
  { "seville", DLT_DEBUG_ONLY },
5607
5608
  /*
5609
   * Type 2, with EtherType 0x8100; the VID can be interpreted
5610
   * as per
5611
   *
5612
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_8021q.c#L15
5613
   */
5614
  { "ocelot-8021q", DLT_DEBUG_ONLY },
5615
5616
  /*
5617
   * Type 2, without an EtherType at the beginning.
5618
   *
5619
   * See
5620
   *
5621
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_qca.c
5622
   */
5623
  { "qca", DLT_DEBUG_ONLY },
5624
5625
  /*
5626
   * Type 2, with EtherType 0x8899, assigned to Realtek;
5627
   * they use it for several on-the-Ethernet protocols
5628
   * as well, but there are fields that allow the two
5629
   * tag formats, and all the protocols in question,
5630
   * to be distinguiished from one another.
5631
   *
5632
   * See
5633
   *
5634
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_rtl4_a.c
5635
   *
5636
   *    http://realtek.info/pdf/rtl8306sd%28m%29_datasheet_1.1.pdf
5637
   *
5638
   * and various pages in tcpdump's print-realtek.c and Wireshark's
5639
   * epan/dissectors/packet-realtek.c for the other protocols.
5640
   */
5641
  { "rtl4a", DLT_DEBUG_ONLY },
5642
5643
  /*
5644
   * Type 2, with EtherType 0x8899, assigned to Realtek;
5645
   * see above.
5646
   */
5647
  { "rtl8_4", DLT_DEBUG_ONLY },
5648
5649
  /*
5650
   * Type 3, with the same tag format as rtl8_4.
5651
   */
5652
  { "rtl8_4t", DLT_DEBUG_ONLY },
5653
5654
  /*
5655
   * Type 2, with EtherType 0xe001; that's probably
5656
   * self-assigned.
5657
   *
5658
   * See
5659
   *
5660
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_rzn1_a5psw.c
5661
   */
5662
  { "a5psw", DLT_DEBUG_ONLY },
5663
5664
  /*
5665
   * Type 2, with EtherType 0x8100 or the self-assigned
5666
   * 0xdadb, so this really should have its own
5667
   * LINKTYPE_/DLT_ value; that would also allow the
5668
   * VID of the tag to be dissected as per
5669
   *
5670
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_8021q.c#L15
5671
   */
5672
  { "sja1105", DLT_DEBUG_ONLY },
5673
5674
  /*
5675
   * Type "none of the above", with both a header and trailer,
5676
   * with different transmit and receive tags.  Has
5677
   * EtherType 0xdadc, which is probably self-assigned.
5678
   */
5679
  { "sja1110", DLT_DEBUG_ONLY },
5680
5681
  /*
5682
   * Type 3, as the name suggests.
5683
   *
5684
   * See
5685
   *
5686
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_trailer.c
5687
   */
5688
  { "trailer", DLT_DEBUG_ONLY },
5689
5690
  /*
5691
   * Type 2, with EtherType 0x8100; the VID can be interpreted
5692
   * as per
5693
   *
5694
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_8021q.c#L15
5695
   */
5696
  { "vsc73xx-8021q", DLT_DEBUG_ONLY },
5697
5698
  /*
5699
   * Type 3.
5700
   *
5701
   * See
5702
   *
5703
   *    https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_xrs700x.c
5704
   */
5705
  { "xrs700x", DLT_DEBUG_ONLY },
5706
};
5707
5708
/*
5709
 * Return 1 if the interface uses DSA tagging, 0 if the interface does not use
5710
 * DSA tagging, or PCAP_ERROR on error.
5711
 */
5712
static int
5713
iface_dsa_get_proto_info(const char *device, pcap_t *handle)
5714
0
{
5715
0
  char *pathstr;
5716
0
  unsigned int i;
5717
  /*
5718
   * Make this significantly smaller than PCAP_ERRBUF_SIZE;
5719
   * the tag *shouldn't* have some huge long name, and making
5720
   * it smaller keeps newer versions of GCC from whining that
5721
   * the error message if we don't support the tag could
5722
   * overflow the error message buffer.
5723
   */
5724
0
  char buf[128];
5725
0
  ssize_t r;
5726
0
  int fd;
5727
5728
0
  fd = asprintf(&pathstr, "/sys/class/net/%s/dsa/tagging", device);
5729
0
  if (fd < 0) {
5730
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
5731
0
            fd, "asprintf");
5732
0
    return PCAP_ERROR;
5733
0
  }
5734
5735
0
  fd = open(pathstr, O_RDONLY);
5736
0
  free(pathstr);
5737
  /*
5738
   * This could be not fatal: kernel >= 4.20 *might* expose this
5739
   * attribute.  However, if it exposes the attribute, but the read has
5740
   * failed due to another reason (ENFILE, EMFILE, ENOMEM...), propagate
5741
   * the failure.
5742
   */
5743
0
  if (fd < 0) {
5744
0
    if (errno == ENOENT)
5745
0
      return 0;
5746
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
5747
0
                                 errno, "open");
5748
0
    return PCAP_ERROR;
5749
0
  }
5750
5751
0
  r = read(fd, buf, sizeof(buf) - 1);
5752
0
  if (r <= 0) {
5753
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
5754
0
            errno, "read");
5755
0
    close(fd);
5756
0
    return PCAP_ERROR;
5757
0
  }
5758
0
  close(fd);
5759
5760
  /*
5761
   * Buffer should be LF terminated.
5762
   */
5763
0
  if (buf[r - 1] == '\n')
5764
0
    r--;
5765
0
  buf[r] = '\0';
5766
5767
  /*
5768
   * The string "none" indicates that the interface does not have
5769
   * any tagging protocol configured, and is therefore a standard
5770
   * Ethernet interface.
5771
   */
5772
0
  if (strcmp(buf, "none") == 0)
5773
0
    return 0;
5774
5775
  /*
5776
   * Every element in the array stands for a DSA-tagged interface.  Using
5777
   * DLT_EN10MB (the standard IEEE 802.3 Ethernet) for such an interface
5778
   * may seem a good idea at first, but doing so would certainly cause
5779
   * major problems in areas that are already complicated and depend on
5780
   * DLT_EN10MB meaning the standard IEEE 802.3 Ethernet only, namely:
5781
   *
5782
   * - live capturing of packets on Linux, and
5783
   * - live kernel filtering of packets on Linux, and
5784
   * - live userspace filtering of packets on Linux, and
5785
   * - offline filtering of packets on all supported OSes, and
5786
   * - identification of savefiles on all OSes.
5787
   *
5788
   * Therefore use a default DLT value that does not block capturing and
5789
   * hexdumping of unsupported DSA encodings (in case the tag is not in
5790
   * the array) and enforce the non-use of DLT_EN10MB (in case the tag is
5791
   * in the array, but is incorrectly declared).
5792
   */
5793
0
  handle->linktype = DLT_DEBUG_ONLY;
5794
0
  for (i = 0; i < sizeof(dsa_protos) / sizeof(dsa_protos[0]); i++) {
5795
0
    if (strcmp(buf, dsa_protos[i].name) == 0) {
5796
0
      if (dsa_protos[i].linktype != DLT_EN10MB)
5797
0
        handle->linktype = dsa_protos[i].linktype;
5798
0
      break;
5799
0
    }
5800
0
  }
5801
0
  return 1;
5802
0
}
5803
5804
/*
5805
 *  Query the kernel for the MTU of the given interface.
5806
 */
5807
static int
5808
iface_get_mtu(int fd, const char *device, char *ebuf)
5809
0
{
5810
0
  struct ifreq  ifr;
5811
5812
0
  if (!device)
5813
0
    return BIGGER_THAN_ALL_MTUS;
5814
5815
0
  memset(&ifr, 0, sizeof(ifr));
5816
0
  pcapint_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5817
5818
0
  if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
5819
0
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5820
0
        errno, "SIOCGIFMTU");
5821
0
    return -1;
5822
0
  }
5823
5824
0
  return ifr.ifr_mtu;
5825
0
}
5826
5827
/*
5828
 *  Get the hardware type of the given interface as ARPHRD_xxx constant.
5829
 */
5830
static int
5831
iface_get_arptype(int fd, const char *device, char *ebuf)
5832
0
{
5833
0
  struct ifreq  ifr;
5834
0
  int   ret;
5835
5836
0
  memset(&ifr, 0, sizeof(ifr));
5837
0
  pcapint_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5838
5839
0
  if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
5840
0
    if (errno == ENODEV) {
5841
      /*
5842
       * No such device.
5843
       *
5844
       * There's nothing more to say, so clear
5845
       * the error message.
5846
       */
5847
0
      ret = PCAP_ERROR_NO_SUCH_DEVICE;
5848
0
      ebuf[0] = '\0';
5849
0
    } else {
5850
0
      ret = PCAP_ERROR;
5851
0
      pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5852
0
          errno, "SIOCGIFHWADDR");
5853
0
    }
5854
0
    return ret;
5855
0
  }
5856
5857
0
  return ifr.ifr_hwaddr.sa_family;
5858
0
}
5859
5860
/*
5861
 * In a DLT_CAN_SOCKETCAN frame the first four bytes are a 32-bit integer
5862
 * value in host byte order if the filter program is running in the kernel and
5863
 * in network byte order if in userland.  This applies to both CC, FD and XL
5864
 * frames, see pcap_handle_packet_mmap() for the rationale.  Return 1 iff the
5865
 * [possibly modified] filter program can work correctly in the kernel.
5866
 */
5867
#if __BYTE_ORDER == __LITTLE_ENDIAN
5868
static int
5869
fix_dlt_can_socketcan(const u_int len, struct bpf_insn insn[])
5870
0
{
5871
0
  for (u_int i = 0; i < len; ++i) {
5872
0
    switch (insn[i].code) {
5873
0
    case BPF_LD|BPF_B|BPF_ABS: // ldb [k]
5874
0
    case BPF_LDX|BPF_MSH|BPF_B: // ldxb 4*([k]&0xf)
5875
0
      if (insn[i].k < 4)
5876
0
        insn[i].k = 3 - insn[i].k; // Fixed now.
5877
0
      break;
5878
0
    case BPF_LD|BPF_H|BPF_ABS: // ldh [k]
5879
0
    case BPF_LD|BPF_W|BPF_ABS: // ld [k]
5880
      /*
5881
       * A halfword or a word load cannot be fixed by just
5882
       * changing k, even if every required byte is within
5883
       * the byte-swapped part of the frame, even if the
5884
       * load is aligned.  The fix would require either
5885
       * rewriting the filter program extensively or
5886
       * generating it differently in the first place.
5887
       */
5888
0
    case BPF_LD|BPF_B|BPF_IND: // ldb [x + k]
5889
0
    case BPF_LD|BPF_H|BPF_IND: // ldh [x + k]
5890
0
    case BPF_LD|BPF_W|BPF_IND: // ld [x + k]
5891
      /*
5892
       * In addition to the above, a variable offset load
5893
       * cannot be fixed because x can have any value, thus
5894
       * x + k can have any value, but only the first four
5895
       * bytes are swapped.  An easy way to demonstrate it
5896
       * is to compile "link[link[4]] == 0", which will use
5897
       * "ldb [x + 0]" to access one of the first four bytes
5898
       * of the frame iff CAN CC/FD payload length is less
5899
       * than 4.
5900
       */
5901
0
      if (insn[i].k < 4)
5902
0
        return 0; // Userland filtering only.
5903
0
      break;
5904
0
    }
5905
0
  }
5906
0
  return 1;
5907
0
}
5908
#else
5909
static int
5910
fix_dlt_can_socketcan(const u_int len _U_, struct bpf_insn insn[] _U_)
5911
{
5912
  return 1;
5913
}
5914
#endif // __BYTE_ORDER == __LITTLE_ENDIAN
5915
5916
static int
5917
fix_program(pcap_t *handle, struct sock_fprog *fcode)
5918
0
{
5919
0
  struct pcap_linux *handlep = handle->priv;
5920
0
  size_t prog_size;
5921
0
  int i;
5922
0
  struct bpf_insn *p;
5923
0
  struct bpf_insn *f;
5924
0
  int len;
5925
5926
  /*
5927
   * Make a copy of the filter, and modify that copy if
5928
   * necessary.
5929
   */
5930
0
  prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
5931
0
  len = handle->fcode.bf_len;
5932
0
  f = (struct bpf_insn *)malloc(prog_size);
5933
0
  if (f == NULL) {
5934
0
    pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
5935
0
        errno, "malloc");
5936
0
    return -1;
5937
0
  }
5938
0
  memcpy(f, handle->fcode.bf_insns, prog_size);
5939
0
  fcode->len = len;
5940
0
  fcode->filter = (struct sock_filter *) f;
5941
5942
0
  switch (handle->linktype) {
5943
0
  case DLT_CAN_SOCKETCAN:
5944
    /*
5945
     * If a similar fix needs to be done for CAN frames that
5946
     * appear on the "any" pseudo-interface, it needs to be done
5947
     * differently because that would be within DLT_LINUX_SLL or
5948
     * DLT_LINUX_SLL2.
5949
     */
5950
0
    return fix_dlt_can_socketcan(len, f);
5951
0
  }
5952
5953
0
  for (i = 0; i < len; ++i) {
5954
0
    p = &f[i];
5955
    /*
5956
     * What type of instruction is this?
5957
     */
5958
0
    switch (BPF_CLASS(p->code)) {
5959
5960
0
    case BPF_LD:
5961
0
    case BPF_LDX:
5962
      /*
5963
       * It's a load instruction; is it loading
5964
       * from the packet?
5965
       */
5966
0
      switch (BPF_MODE(p->code)) {
5967
5968
0
      case BPF_ABS:
5969
0
      case BPF_IND:
5970
0
      case BPF_MSH:
5971
        /*
5972
         * Yes; are we in cooked mode?
5973
         */
5974
0
        if (handlep->cooked) {
5975
          /*
5976
           * Yes, so we need to fix this
5977
           * instruction.
5978
           */
5979
0
          if (fix_offset(handle, p) < 0) {
5980
            /*
5981
             * We failed to do so.
5982
             * Return 0, so our caller
5983
             * knows to punt to userland.
5984
             */
5985
0
            return 0;
5986
0
          }
5987
0
        }
5988
0
        break;
5989
0
      }
5990
0
      break;
5991
0
    }
5992
0
  }
5993
0
  return 1; /* we succeeded */
5994
0
}
5995
5996
static int
5997
fix_offset(pcap_t *handle, struct bpf_insn *p)
5998
0
{
5999
  /*
6000
   * Existing references to auxiliary data shouldn't be adjusted.
6001
   *
6002
   * Note that SKF_AD_OFF is negative, but p->k is unsigned, so
6003
   * we use >= and cast SKF_AD_OFF to unsigned.
6004
   */
6005
0
  if (p->k >= (bpf_u_int32)SKF_AD_OFF)
6006
0
    return 0;
6007
0
  if (handle->linktype == DLT_LINUX_SLL2) {
6008
    /*
6009
     * What's the offset?
6010
     */
6011
0
    if (p->k >= SLL2_HDR_LEN) {
6012
      /*
6013
       * It's within the link-layer payload; that starts
6014
       * at an offset of 0, as far as the kernel packet
6015
       * filter is concerned, so subtract the length of
6016
       * the link-layer header.
6017
       */
6018
0
      p->k -= SLL2_HDR_LEN;
6019
0
    } else if (p->k == 0) {
6020
      /*
6021
       * It's the protocol field; map it to the
6022
       * special magic kernel offset for that field.
6023
       */
6024
0
      p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
6025
0
    } else if (p->k == 4) {
6026
      /*
6027
       * It's the ifindex field; map it to the
6028
       * special magic kernel offset for that field.
6029
       */
6030
0
      p->k = SKF_AD_OFF + SKF_AD_IFINDEX;
6031
0
    } else if (p->k == 10) {
6032
      /*
6033
       * It's the packet type field; map it to the
6034
       * special magic kernel offset for that field.
6035
       */
6036
0
      p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
6037
0
    } else if ((bpf_int32)(p->k) > 0) {
6038
      /*
6039
       * It's within the header, but it's not one of
6040
       * those fields; we can't do that in the kernel,
6041
       * so punt to userland.
6042
       */
6043
0
      return -1;
6044
0
    }
6045
0
  } else {
6046
    /*
6047
     * What's the offset?
6048
     */
6049
0
    if (p->k >= SLL_HDR_LEN) {
6050
      /*
6051
       * It's within the link-layer payload; that starts
6052
       * at an offset of 0, as far as the kernel packet
6053
       * filter is concerned, so subtract the length of
6054
       * the link-layer header.
6055
       */
6056
0
      p->k -= SLL_HDR_LEN;
6057
0
    } else if (p->k == 0) {
6058
      /*
6059
       * It's the packet type field; map it to the
6060
       * special magic kernel offset for that field.
6061
       */
6062
0
      p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
6063
0
    } else if (p->k == 14) {
6064
      /*
6065
       * It's the protocol field; map it to the
6066
       * special magic kernel offset for that field.
6067
       */
6068
0
      p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
6069
0
    } else if ((bpf_int32)(p->k) > 0) {
6070
      /*
6071
       * It's within the header, but it's not one of
6072
       * those fields; we can't do that in the kernel,
6073
       * so punt to userland.
6074
       */
6075
0
      return -1;
6076
0
    }
6077
0
  }
6078
0
  return 0;
6079
0
}
6080
6081
static int
6082
set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
6083
0
{
6084
0
  int total_filter_on = 0;
6085
0
  int save_mode;
6086
0
  int ret;
6087
0
  int save_errno;
6088
6089
  /*
6090
   * The socket filter code doesn't discard all packets queued
6091
   * up on the socket when the filter is changed; this means
6092
   * that packets that don't match the new filter may show up
6093
   * after the new filter is put onto the socket, if those
6094
   * packets haven't yet been read.
6095
   *
6096
   * This means, for example, that if you do a tcpdump capture
6097
   * with a filter, the first few packets in the capture might
6098
   * be packets that wouldn't have passed the filter.
6099
   *
6100
   * We therefore discard all packets queued up on the socket
6101
   * when setting a kernel filter.  (This isn't an issue for
6102
   * userland filters, as the userland filtering is done after
6103
   * packets are queued up.)
6104
   *
6105
   * To flush those packets, we put the socket in read-only mode,
6106
   * and read packets from the socket until there are no more to
6107
   * read.
6108
   *
6109
   * In order to keep that from being an infinite loop - i.e.,
6110
   * to keep more packets from arriving while we're draining
6111
   * the queue - we put the "total filter", which is a filter
6112
   * that rejects all packets, onto the socket before draining
6113
   * the queue.
6114
   *
6115
   * This code deliberately ignores any errors, so that you may
6116
   * get bogus packets if an error occurs, rather than having
6117
   * the filtering done in userland even if it could have been
6118
   * done in the kernel.
6119
   */
6120
0
  if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
6121
0
           &total_fcode, sizeof(total_fcode)) == 0) {
6122
0
    char drain[1];
6123
6124
    /*
6125
     * Note that we've put the total filter onto the socket.
6126
     */
6127
0
    total_filter_on = 1;
6128
6129
    /*
6130
     * Save the socket's current mode, and put it in
6131
     * non-blocking mode; we drain it by reading packets
6132
     * until we get an error (which is normally a
6133
     * "nothing more to be read" error).
6134
     */
6135
0
    save_mode = fcntl(handle->fd, F_GETFL, 0);
6136
0
    if (save_mode == -1) {
6137
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
6138
0
          PCAP_ERRBUF_SIZE, errno,
6139
0
          "can't get FD flags when changing filter");
6140
0
      return -2;
6141
0
    }
6142
0
    if (fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) < 0) {
6143
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
6144
0
          PCAP_ERRBUF_SIZE, errno,
6145
0
          "can't set nonblocking mode when changing filter");
6146
0
      return -2;
6147
0
    }
6148
0
    while (recv(handle->fd, &drain, sizeof drain, MSG_TRUNC) >= 0)
6149
0
      ;
6150
0
    save_errno = errno;
6151
0
    if (save_errno != EAGAIN) {
6152
      /*
6153
       * Fatal error.
6154
       *
6155
       * If we can't restore the mode or reset the
6156
       * kernel filter, there's nothing we can do.
6157
       */
6158
0
      (void)fcntl(handle->fd, F_SETFL, save_mode);
6159
0
      (void)reset_kernel_filter(handle);
6160
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
6161
0
          PCAP_ERRBUF_SIZE, save_errno,
6162
0
          "recv failed when changing filter");
6163
0
      return -2;
6164
0
    }
6165
0
    if (fcntl(handle->fd, F_SETFL, save_mode) == -1) {
6166
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
6167
0
          PCAP_ERRBUF_SIZE, errno,
6168
0
          "can't restore FD flags when changing filter");
6169
0
      return -2;
6170
0
    }
6171
0
  }
6172
6173
  /*
6174
   * Now attach the new filter.
6175
   */
6176
0
  ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
6177
0
       fcode, sizeof(*fcode));
6178
0
  if (ret == -1 && total_filter_on) {
6179
    /*
6180
     * Well, we couldn't set that filter on the socket,
6181
     * but we could set the total filter on the socket.
6182
     *
6183
     * This could, for example, mean that the filter was
6184
     * too big to put into the kernel, so we'll have to
6185
     * filter in userland; in any case, we'll be doing
6186
     * filtering in userland, so we need to remove the
6187
     * total filter so we see packets.
6188
     */
6189
0
    save_errno = errno;
6190
6191
    /*
6192
     * If this fails, we're really screwed; we have the
6193
     * total filter on the socket, and it won't come off.
6194
     * Report it as a fatal error.
6195
     */
6196
0
    if (reset_kernel_filter(handle) == -1) {
6197
0
      pcapint_fmt_errmsg_for_errno(handle->errbuf,
6198
0
          PCAP_ERRBUF_SIZE, errno,
6199
0
          "can't remove kernel total filter");
6200
0
      return -2;  /* fatal error */
6201
0
    }
6202
6203
0
    errno = save_errno;
6204
0
  }
6205
0
  return ret;
6206
0
}
6207
6208
static int
6209
reset_kernel_filter(pcap_t *handle)
6210
0
{
6211
0
  int ret;
6212
  /*
6213
   * setsockopt() barfs unless it get a dummy parameter.
6214
   * valgrind whines unless the value is initialized,
6215
   * as it has no idea that setsockopt() ignores its
6216
   * parameter.
6217
   */
6218
0
  int dummy = 0;
6219
6220
0
  ret = setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
6221
0
           &dummy, sizeof(dummy));
6222
  /*
6223
   * Ignore ENOENT - it means "we don't have a filter", so there
6224
   * was no filter to remove, and there's still no filter.
6225
   *
6226
   * Also ignore ENONET, as a lot of kernel versions had a
6227
   * typo where ENONET, rather than ENOENT, was returned.
6228
   */
6229
0
  if (ret == -1 && errno != ENOENT && errno != ENONET)
6230
0
    return -1;
6231
0
  return 0;
6232
0
}
6233
6234
int
6235
pcap_set_protocol_linux(pcap_t *p, int protocol)
6236
0
{
6237
0
  if (pcapint_check_activated(p))
6238
0
    return (PCAP_ERROR_ACTIVATED);
6239
0
  p->opt.protocol = protocol;
6240
0
  return (0);
6241
0
}
6242
6243
/*
6244
 * Libpcap version string.
6245
 */
6246
#if defined(HAVE_TPACKET3) && defined(PCAP_SUPPORT_NETMAP)
6247
  #define ADDITIONAL_INFO_STRING  "with TPACKET_V3 and netmap"
6248
#elif defined(HAVE_TPACKET3)
6249
  #define ADDITIONAL_INFO_STRING  "with TPACKET_V3"
6250
#elif defined(PCAP_SUPPORT_NETMAP)
6251
  #define ADDITIONAL_INFO_STRING  "with TPACKET_V2 and netmap"
6252
#else
6253
  #define ADDITIONAL_INFO_STRING  "with TPACKET_V2"
6254
#endif
6255
6256
const char *
6257
pcap_lib_version(void)
6258
0
{
6259
0
  return (PCAP_VERSION_STRING_WITH_ADDITIONAL_INFO(ADDITIONAL_INFO_STRING));
6260
0
}