suricata
source-af-packet.c
Go to the documentation of this file.
1 /* Copyright (C) 2011-2021 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \defgroup afppacket AF_PACKET running mode
20  *
21  * @{
22  */
23 
24 /**
25  * \file
26  *
27  * \author Eric Leblond <eric@regit.org>
28  *
29  * AF_PACKET socket acquisition support
30  *
31  */
32 
33 #define SC_PCAP_DONT_INCLUDE_PCAP_H 1
35 #include "suricata.h"
36 #include "packet.h"
37 #include "decode.h"
38 #include "packet-queue.h"
39 #include "threads.h"
40 #include "threadvars.h"
41 #include "tm-queuehandlers.h"
42 #include "tm-modules.h"
43 #include "tm-threads.h"
44 #include "tm-threads-common.h"
45 #include "conf.h"
46 #include "util-cpu.h"
47 #include "util-datalink.h"
48 #include "util-debug.h"
49 #include "util-device-private.h"
50 #include "util-ebpf.h"
51 #include "util-error.h"
52 #include "util-privs.h"
53 #include "util-optimize.h"
54 #include "util-checksum.h"
55 #include "util-ioctl.h"
56 #include "util-host-info.h"
57 #include "tmqh-packetpool.h"
58 #include "source-af-packet.h"
59 #include "runmodes.h"
60 #include "flow-storage.h"
61 #include "util-validate.h"
62 #include "action-globals.h"
63 
64 #ifdef HAVE_AF_PACKET
65 
66 #if HAVE_SYS_IOCTL_H
67 #include <sys/ioctl.h>
68 #endif
69 
70 #if HAVE_LINUX_SOCKIOS_H
71 #include <linux/sockios.h>
72 #endif
73 
74 #ifdef HAVE_PACKET_EBPF
75 #define PCAP_DONT_INCLUDE_PCAP_BPF_H 1
76 #include <bpf/libbpf.h>
77 #include <bpf/bpf.h>
78 
79 struct bpf_program {
80  unsigned int bf_len;
81  struct bpf_insn *bf_insns;
82 };
83 #endif
84 
85 #ifdef HAVE_PCAP_H
86 #include <pcap.h>
87 #endif
88 
89 #ifdef HAVE_PCAP_PCAP_H
90 #include <pcap/pcap.h>
91 #endif
92 
93 #include "util-bpf.h"
94 
95 #if HAVE_LINUX_IF_ETHER_H
96 #include <linux/if_ether.h>
97 #endif
98 
99 #if HAVE_LINUX_IF_PACKET_H
100 #include <linux/if_packet.h>
101 #endif
102 
103 #if HAVE_LINUX_IF_ARP_H
104 #include <linux/if_arp.h>
105 #endif
106 
107 #if HAVE_LINUX_FILTER_H
108 #include <linux/filter.h>
109 #endif
110 
111 #if HAVE_SYS_MMAN_H
112 #include <sys/mman.h>
113 #endif
114 
115 #ifdef HAVE_HW_TIMESTAMPING
116 #include <linux/net_tstamp.h>
117 #endif
118 
119 #endif /* HAVE_AF_PACKET */
120 
121 extern uint32_t max_pending_packets;
122 
123 #ifndef HAVE_AF_PACKET
124 
125 TmEcode NoAFPSupportExit(ThreadVars *, const void *, void **);
126 
127 void TmModuleReceiveAFPRegister (void)
128 {
129  tmm_modules[TMM_RECEIVEAFP].name = "ReceiveAFP";
130  tmm_modules[TMM_RECEIVEAFP].ThreadInit = NoAFPSupportExit;
136 }
137 
138 /**
139  * \brief Registration Function for DecodeAFP.
140  */
141 void TmModuleDecodeAFPRegister (void)
142 {
143  tmm_modules[TMM_DECODEAFP].name = "DecodeAFP";
144  tmm_modules[TMM_DECODEAFP].ThreadInit = NoAFPSupportExit;
150 }
151 
152 /**
153  * \brief this function prints an error message and exits.
154  */
155 TmEcode NoAFPSupportExit(ThreadVars *tv, const void *initdata, void **data)
156 {
157  SCLogError("Error creating thread %s: you do not have "
158  "support for AF_PACKET enabled, on Linux host please recompile "
159  "with --enable-af-packet",
160  tv->name);
161  exit(EXIT_FAILURE);
162 }
163 
164 #else /* We have AF_PACKET support */
165 
166 #define AFP_IFACE_NAME_LENGTH 48
167 
168 #define AFP_STATE_DOWN 0
169 #define AFP_STATE_UP 1
170 
171 #define AFP_RECONNECT_TIMEOUT 500000
172 #define AFP_DOWN_COUNTER_INTERVAL 40
173 
174 #define POLL_TIMEOUT 100
175 
176 /* kernel flags defined for RX ring tp_status */
177 #ifndef TP_STATUS_KERNEL
178 #define TP_STATUS_KERNEL 0
179 #endif
180 #ifndef TP_STATUS_USER
181 #define TP_STATUS_USER BIT_U32(0)
182 #endif
183 #ifndef TP_STATUS_COPY
184 #define TP_STATUS_COPY BIT_U32(1)
185 #endif
186 #ifndef TP_STATUS_LOSING
187 #define TP_STATUS_LOSING BIT_U32(2)
188 #endif
189 #ifndef TP_STATUS_CSUMNOTREADY
190 #define TP_STATUS_CSUMNOTREADY BIT_U32(3)
191 #endif
192 #ifndef TP_STATUS_VLAN_VALID
193 #define TP_STATUS_VLAN_VALID BIT_U32(4)
194 #endif
195 #ifndef TP_STATUS_BLK_TMO
196 #define TP_STATUS_BLK_TMO BIT_U32(5)
197 #endif
198 #ifndef TP_STATUS_VLAN_TPID_VALID
199 #define TP_STATUS_VLAN_TPID_VALID BIT_U32(6)
200 #endif
201 #ifndef TP_STATUS_CSUM_VALID
202 #define TP_STATUS_CSUM_VALID BIT_U32(7)
203 #endif
204 
205 #ifndef TP_STATUS_TS_SOFTWARE
206 #define TP_STATUS_TS_SOFTWARE BIT_U32(29)
207 #endif
208 #ifndef TP_STATUS_TS_SYS_HARDWARE
209 #define TP_STATUS_TS_SYS_HARDWARE BIT_U32(30) /* kernel comment says: "deprecated, never set" */
210 #endif
211 #ifndef TP_STATUS_TS_RAW_HARDWARE
212 #define TP_STATUS_TS_RAW_HARDWARE BIT_U32(31)
213 #endif
214 
215 #ifndef TP_STATUS_USER_BUSY
216 /* HACK special setting in the tp_status field for frames we are
217  * still working on. This can happen in autofp mode where the
218  * capture thread goes around the ring and finds a frame that still
219  * hasn't been released by a worker thread.
220  *
221  * We use bits 29, 30, 31. 29 and 31 are software and hardware
222  * timestamps. 30 should not be set by the kernel at all. Combined
223  * they should never be set on the rx-ring together.
224  *
225  * The excessive casting is for handling the fact that the kernel
226  * defines almost all of these as int flags, not unsigned ints. */
227 #define TP_STATUS_USER_BUSY \
228  (uint32_t)((uint32_t)TP_STATUS_TS_SOFTWARE | (uint32_t)TP_STATUS_TS_SYS_HARDWARE | \
229  (uint32_t)TP_STATUS_TS_RAW_HARDWARE)
230 #endif
231 #define FRAME_BUSY(tp_status) \
232  (((uint32_t)(tp_status) & (uint32_t)TP_STATUS_USER_BUSY) == (uint32_t)TP_STATUS_USER_BUSY)
233 
234 enum {
237  /** Error during treatment by other functions of Suricata */
240 };
241 
242 enum {
245 };
246 
247 union thdr {
248  struct tpacket2_hdr *h2;
249  struct tpacket3_hdr *h3;
250  void *raw;
251 };
252 
253 #ifdef HAVE_PACKET_EBPF
254 static int AFPBypassCallback(Packet *p);
255 static int AFPXDPBypassCallback(Packet *p);
256 #endif
257 
258 /**
259  * \brief Structure to hold thread specific variables.
260  */
261 typedef struct AFPThreadVars_
262 {
263  union AFPRing {
264  union thdr **v2;
265  struct iovec *v3;
266  } ring;
267 
268  /* counters */
269  uint64_t pkts;
270 
274  /* data link type for the thread */
275  uint32_t datalink;
276 
277 #ifdef HAVE_PACKET_EBPF
278  /* File descriptor of the IPv4 flow bypass table maps */
279  int v4_map_fd;
280  /* File descriptor of the IPv6 flow bypass table maps */
281  int v6_map_fd;
282 #endif
283 
284  unsigned int frame_offset;
285 
287 
288  /* references to packet and drop counters */
299 
300  int64_t send_errors_logged; /**< snapshot of send errors logged. */
301 
302  /* handle state */
303  uint8_t afp_state;
304  uint8_t copy_mode;
305  unsigned int flags;
306 
307  /* IPS peer */
309 
310  /*
311  * Init related members
312  */
313 
314  /* thread specific socket */
315  int socket;
316 
321  /* socket buffer size */
323  /* Filter */
324  const char *bpf_filter;
325 
326  int promisc;
327 
328  /* bitmask of ignored ssl_pkttypes */
330 
332 
333  uint16_t cluster_id;
335 
336  int threads;
337 
339  struct tpacket_req v2;
340  struct tpacket_req3 v3;
341  } req;
342 
344  /* IPS output iface */
346 
347  /* mmap'ed ring buffer */
348  unsigned int ring_buflen;
349  uint8_t *ring_buf;
350 
351  int snaplen; /**< snaplen in use for passing on to bpf */
352 #ifdef HAVE_PACKET_EBPF
353  uint8_t xdp_mode;
354  int ebpf_lb_fd;
355  int ebpf_filter_fd;
356  struct ebpf_timeout_config ebpf_t_config;
357 #endif
358 
360 
361 static TmEcode ReceiveAFPThreadInit(ThreadVars *, const void *, void **);
362 static void ReceiveAFPThreadExitStats(ThreadVars *, void *);
363 static TmEcode ReceiveAFPThreadDeinit(ThreadVars *, void *);
364 static TmEcode ReceiveAFPLoop(ThreadVars *tv, void *data, void *slot);
365 
366 static TmEcode DecodeAFPThreadInit(ThreadVars *, const void *, void **);
367 static TmEcode DecodeAFPThreadDeinit(ThreadVars *tv, void *data);
368 static TmEcode DecodeAFP(ThreadVars *, Packet *, void *);
369 
370 static TmEcode AFPSetBPFFilter(AFPThreadVars *ptv);
371 static int AFPGetIfnumByDev(int fd, const char *ifname, int verbose);
372 static int AFPGetDevFlags(int fd, const char *ifname);
373 static int AFPDerefSocket(AFPPeer* peer);
374 static int AFPRefSocket(AFPPeer* peer);
375 
376 
377 /**
378  * \brief Registration Function for RecieveAFP.
379  * \todo Unit tests are needed for this module.
380  */
382 {
383  tmm_modules[TMM_RECEIVEAFP].name = "ReceiveAFP";
384  tmm_modules[TMM_RECEIVEAFP].ThreadInit = ReceiveAFPThreadInit;
386  tmm_modules[TMM_RECEIVEAFP].PktAcqLoop = ReceiveAFPLoop;
388  tmm_modules[TMM_RECEIVEAFP].ThreadExitPrintStats = ReceiveAFPThreadExitStats;
389  tmm_modules[TMM_RECEIVEAFP].ThreadDeinit = ReceiveAFPThreadDeinit;
392 
393 }
394 
395 /**
396  * \defgroup afppeers AFP peers list
397  *
398  * AF_PACKET has an IPS mode were interface are peered: packet from
399  * on interface are sent the peered interface and the other way. The ::AFPPeer
400  * list is maintaining the list of peers. Each ::AFPPeer is storing the needed
401  * information to be able to send packet on the interface.
402  * A element of the list must not be destroyed during the run of Suricata as it
403  * is used by ::Packet and other threads.
404  *
405  * @{
406  */
407 
408 typedef struct AFPPeersList_ {
409  TAILQ_HEAD(, AFPPeer_) peers; /**< Head of list of fragments. */
410  int cnt;
411  int peered;
412  int turn; /**< Next value for initialisation order */
413  SC_ATOMIC_DECLARE(int, reached); /**< Counter used to synchronize start */
415 
416 /**
417  * \brief Update the peer.
418  *
419  * Update the AFPPeer of a thread ie set new state, socket number
420  * or iface index.
421  *
422  */
423 static void AFPPeerUpdate(AFPThreadVars *ptv)
424 {
425  if (ptv->mpeer == NULL) {
426  return;
427  }
428  (void)SC_ATOMIC_SET(ptv->mpeer->if_idx, AFPGetIfnumByDev(ptv->socket, ptv->iface, 0));
429  (void)SC_ATOMIC_SET(ptv->mpeer->socket, ptv->socket);
430  (void)SC_ATOMIC_SET(ptv->mpeer->state, ptv->afp_state);
431 }
432 
433 /**
434  * \brief Clean and free ressource used by an ::AFPPeer
435  */
436 static void AFPPeerClean(AFPPeer *peer)
437 {
438  if (peer->flags & AFP_SOCK_PROTECT)
440  SCFree(peer);
441 }
442 
444 
445 
446 /**
447  * \brief Init the global list of ::AFPPeer
448  */
450 {
451  SCEnter();
452  TAILQ_INIT(&peerslist.peers);
453  peerslist.peered = 0;
454  peerslist.cnt = 0;
455  peerslist.turn = 0;
456  SC_ATOMIC_INIT(peerslist.reached);
457  (void) SC_ATOMIC_SET(peerslist.reached, 0);
459 }
460 
461 /**
462  * \brief Check that all ::AFPPeer got a peer
463  *
464  * \retval TM_ECODE_FAILED if some threads are not peered or TM_ECODE_OK else.
465  */
467 {
468 #define AFP_PEERS_MAX_TRY 4
469 #define AFP_PEERS_WAIT 20000
470  int try = 0;
471  SCEnter();
472  while (try < AFP_PEERS_MAX_TRY) {
473  if (peerslist.cnt != peerslist.peered) {
474  usleep(AFP_PEERS_WAIT);
475  } else {
477  }
478  try++;
479  }
480  SCLogError("thread number not equal");
482 }
483 
484 /**
485  * \brief Declare a new AFP thread to AFP peers list.
486  */
487 static TmEcode AFPPeersListAdd(AFPThreadVars *ptv)
488 {
489  SCEnter();
490  AFPPeer *peer = SCCalloc(1, sizeof(AFPPeer));
491  AFPPeer *pitem;
492 
493  if (unlikely(peer == NULL)) {
495  }
496  SC_ATOMIC_INIT(peer->socket);
497  SC_ATOMIC_INIT(peer->sock_usage);
498  SC_ATOMIC_INIT(peer->if_idx);
499  SC_ATOMIC_INIT(peer->state);
500  peer->flags = ptv->flags;
501  peer->turn = peerslist.turn++;
502 
503  if (peer->flags & AFP_SOCK_PROTECT) {
504  SCMutexInit(&peer->sock_protect, NULL);
505  }
506 
507  (void)SC_ATOMIC_SET(peer->sock_usage, 0);
508  (void)SC_ATOMIC_SET(peer->state, AFP_STATE_DOWN);
510 
511  peer->livedev_id = LiveDeviceGetId(ptv->livedev);
512  SCLogDebug("mpeer livedev id %u (%s)", peer->livedev_id, peer->iface);
513 
514  ptv->mpeer = peer;
515  /* add element to iface list */
516  TAILQ_INSERT_TAIL(&peerslist.peers, peer, next);
517 
518  if (ptv->copy_mode != AFP_COPY_MODE_NONE) {
519  peerslist.cnt++;
520 
521  /* Iter to find a peer */
522  TAILQ_FOREACH(pitem, &peerslist.peers, next) {
523  if (pitem->peer)
524  continue;
525  if (strcmp(pitem->iface, ptv->out_iface))
526  continue;
527  peer->peer = pitem;
528  pitem->peer = peer;
529 
530  LiveDevice *iface = ptv->livedev;
531  DEBUG_VALIDATE_BUG_ON(iface == NULL);
532  DEBUG_VALIDATE_BUG_ON(strcmp(iface->dev, ptv->iface) != 0);
533  LiveDevice *out_iface = LiveGetDevice(ptv->out_iface);
534  if (out_iface == NULL)
535  FatalError("AF_PACKET device %s not found. Aborting..", ptv->out_iface);
536  if (iface->mtu != out_iface->mtu) {
537  SCLogWarning("MTU on %s (%d) and %s (%d) are not equal, transmission of packets "
538  "bigger than %d will fail.",
539  iface->dev, iface->mtu, out_iface->dev, out_iface->mtu,
540  MIN(out_iface->mtu, iface->mtu));
541  }
542  peerslist.peered += 2;
543  break;
544  }
545  }
546 
547  AFPPeerUpdate(ptv);
548 
550 }
551 
552 static int AFPPeersListWaitTurn(AFPPeer *peer)
553 {
554  /* If turn is zero, we already have started threads once */
555  if (peerslist.turn == 0)
556  return 0;
557 
558  if (peer->turn == SC_ATOMIC_GET(peerslist.reached))
559  return 0;
560  return 1;
561 }
562 
563 static void AFPPeersListReachedInc(void)
564 {
565  if (peerslist.turn == 0)
566  return;
567 
568  if ((SC_ATOMIC_ADD(peerslist.reached, 1) + 1) == peerslist.turn) {
569  (void)SC_ATOMIC_SET(peerslist.reached, 0);
570  /* Set turn to 0 to skip synchronization when ReceiveAFPLoop is
571  * restarted.
572  */
573  peerslist.turn = 0;
574  }
575 }
576 
577 static int AFPPeersListStarted(void)
578 {
579  return !peerslist.turn;
580 }
581 
582 /**
583  * \brief Clean the global peers list.
584  */
586 {
587  AFPPeer *pitem;
588 
589  while ((pitem = TAILQ_FIRST(&peerslist.peers))) {
590  TAILQ_REMOVE(&peerslist.peers, pitem, next);
591  AFPPeerClean(pitem);
592  }
593 }
594 
595 /**
596  * @}
597  */
598 
599 /**
600  * \brief Registration Function for DecodeAFP.
601  * \todo Unit tests are needed for this module.
602  */
604 {
605  tmm_modules[TMM_DECODEAFP].name = "DecodeAFP";
606  tmm_modules[TMM_DECODEAFP].ThreadInit = DecodeAFPThreadInit;
607  tmm_modules[TMM_DECODEAFP].Func = DecodeAFP;
609  tmm_modules[TMM_DECODEAFP].ThreadDeinit = DecodeAFPThreadDeinit;
612 }
613 
614 static int AFPCreateSocket(AFPThreadVars *ptv, char *devname, int verbose);
615 
616 static inline void AFPDumpCounters(AFPThreadVars *ptv)
617 {
618 #ifdef PACKET_STATISTICS
619  struct tpacket_stats kstats;
620  socklen_t len = sizeof (struct tpacket_stats);
621  if (getsockopt(ptv->socket, SOL_PACKET, PACKET_STATISTICS,
622  &kstats, &len) > -1) {
623  SCLogDebug("(%s) Kernel: Packets %" PRIu32 ", dropped %" PRIu32 "",
624  ptv->tv->name,
625  kstats.tp_packets, kstats.tp_drops);
626  StatsCounterAddI64(&ptv->tv->stats, ptv->capture_kernel_packets, kstats.tp_packets);
627  StatsCounterAddI64(&ptv->tv->stats, ptv->capture_kernel_drops, kstats.tp_drops);
628  (void) SC_ATOMIC_ADD(ptv->livedev->drop, (uint64_t) kstats.tp_drops);
629  (void) SC_ATOMIC_ADD(ptv->livedev->pkts, (uint64_t) kstats.tp_packets);
630 
631  const int64_t value = SC_ATOMIC_GET(ptv->mpeer->send_errors);
632  if (value > ptv->send_errors_logged) {
634  &ptv->tv->stats, ptv->capture_afp_send_err, value - ptv->send_errors_logged);
635  ptv->send_errors_logged = value;
636  }
637  }
638 #endif
639 }
640 
641 /**
642  * \brief AF packet write function.
643  *
644  * This function has to be called before the memory
645  * related to Packet in ring buffer is released.
646  *
647  * \param pointer to Packet
648  * \param version of capture: TPACKET_V2 or TPACKET_V3
649  * \retval TM_ECODE_FAILED on failure and TM_ECODE_OK on success
650  *
651  */
652 static void AFPWritePacket(Packet *p, int version)
653 {
654  struct sockaddr_ll socket_address;
655  int socket;
656 
657  if (p->afp_v.copy_mode == AFP_COPY_MODE_IPS) {
659  return;
660  }
661  }
662 
663  if (!PacketIsEthernet(p)) {
664  SCLogWarning("packet should have an ethernet header");
665  return;
666  }
667 
668  const EthernetHdr *ethh = PacketGetEthernet(p);
669  /* Index of the network device */
670  socket_address.sll_ifindex = SC_ATOMIC_GET(p->afp_v.peer->if_idx);
671  /* Address length*/
672  socket_address.sll_halen = ETH_ALEN;
673  /* Destination MAC */
674  memcpy(socket_address.sll_addr, ethh, 6);
675 
676  /* Send packet, locking the socket if necessary */
677  if (p->afp_v.peer->flags & AFP_SOCK_PROTECT)
678  SCMutexLock(&p->afp_v.peer->sock_protect);
679  socket = SC_ATOMIC_GET(p->afp_v.peer->socket);
680 
681  if (sendto(socket, GET_PKT_DATA(p), GET_PKT_LEN(p), 0, (struct sockaddr *)&socket_address,
682  sizeof(struct sockaddr_ll)) < 0) {
683  if (SC_ATOMIC_ADD(p->afp_v.peer->send_errors, 1) == 0) {
684  SCLogWarning("%s: sending packet failed on socket %d: %s", p->afp_v.peer->iface, socket,
685  strerror(errno));
686  }
687  }
688  if (p->afp_v.peer->flags & AFP_SOCK_PROTECT)
689  SCMutexUnlock(&p->afp_v.peer->sock_protect);
690 }
691 
692 static void AFPReleaseDataFromRing(Packet *p)
693 {
695 
696  /* Need to be in copy mode and need to detect early release
697  where Ethernet header could not be set (and pseudo packet) */
698  if (p->afp_v.copy_mode != AFP_COPY_MODE_NONE) {
699  AFPWritePacket(p, TPACKET_V2);
700  }
701 
702  BUG_ON(p->afp_v.relptr == NULL);
703 
704  union thdr h;
705  h.raw = p->afp_v.relptr;
706  h.h2->tp_status = TP_STATUS_KERNEL;
707 
708  (void)AFPDerefSocket(p->afp_v.mpeer);
709 
710  AFPV_CLEANUP(&p->afp_v);
711 }
712 
713 static void AFPReleasePacketV3(Packet *p)
714 {
716 
717  /* Need to be in copy mode and need to detect early release
718  where Ethernet header could not be set (and pseudo packet) */
719  if (p->afp_v.copy_mode != AFP_COPY_MODE_NONE) {
720  AFPWritePacket(p, TPACKET_V3);
721  }
723 }
724 
725 static void AFPReleasePacket(Packet *p)
726 {
727  AFPReleaseDataFromRing(p);
729 }
730 
731 /** \internal
732  * \brief recoverable error - release packet and
733  * return AFP_SURI_FAILURE
734  */
735 static inline int AFPSuriFailure(AFPThreadVars *ptv, union thdr h)
736 {
737  h.h2->tp_status = TP_STATUS_KERNEL;
738  if (++ptv->frame_offset >= ptv->req.v2.tp_frame_nr) {
739  ptv->frame_offset = 0;
740  }
742 }
743 
744 static inline void AFPReadApplyBypass(const AFPThreadVars *ptv, Packet *p)
745 {
746 #ifdef HAVE_PACKET_EBPF
747  if (ptv->flags & AFP_BYPASS) {
748  p->BypassPacketsFlow = AFPBypassCallback;
749  p->afp_v.v4_map_fd = ptv->v4_map_fd;
750  p->afp_v.v6_map_fd = ptv->v6_map_fd;
751  p->afp_v.nr_cpus = ptv->ebpf_t_config.cpus_count;
752  }
753  if (ptv->flags & AFP_XDPBYPASS) {
754  p->BypassPacketsFlow = AFPXDPBypassCallback;
755  p->afp_v.v4_map_fd = ptv->v4_map_fd;
756  p->afp_v.v6_map_fd = ptv->v6_map_fd;
757  p->afp_v.nr_cpus = ptv->ebpf_t_config.cpus_count;
758  }
759 #endif
760 }
761 
762 /** \internal
763  * \brief setup packet for AFPReadFromRing
764  */
765 static void AFPReadFromRingSetupPacket(
766  AFPThreadVars *ptv, union thdr h, const unsigned int tp_status, Packet *p)
767 {
769 
770  /* flag the packet as TP_STATUS_USER_BUSY, which is ignore by the kernel, but
771  * acts as an indicator that we've reached a frame that is not yet released by
772  * us in autofp mode. It will be cleared when the frame gets released to the kernel. */
773  h.h2->tp_status |= TP_STATUS_USER_BUSY;
774  p->livedev_id = ptv->livedev->id;
775  p->datalink = ptv->datalink;
776  ptv->pkts++;
777 
778  AFPReadApplyBypass(ptv, p);
779 
780  if (h.h2->tp_len > h.h2->tp_snaplen) {
781  SCLogDebug("Packet length (%d) > snaplen (%d), truncating", h.h2->tp_len, h.h2->tp_snaplen);
783  }
784 
785  /* get vlan id from header */
786  if ((ptv->flags & AFP_VLAN_IN_HEADER) &&
787  (tp_status & TP_STATUS_VLAN_VALID || h.h2->tp_vlan_tci)) {
788  p->vlan_id[0] = h.h2->tp_vlan_tci & 0x0fff;
789  p->vlan_idx = 1;
790  p->afp_v.vlan_tci = h.h2->tp_vlan_tci;
791  }
792 
793  (void)PacketSetData(p, (unsigned char *)h.raw + h.h2->tp_mac, h.h2->tp_snaplen);
794 
795  p->ReleasePacket = AFPReleasePacket;
796  p->afp_v.relptr = h.raw;
797  if (ptv->flags & AFP_NEED_PEER) {
798  p->afp_v.mpeer = ptv->mpeer;
799  AFPRefSocket(ptv->mpeer);
800  } else {
801  p->afp_v.mpeer = NULL;
802  }
803  p->afp_v.copy_mode = ptv->copy_mode;
804  p->afp_v.peer = (p->afp_v.copy_mode == AFP_COPY_MODE_NONE) ? NULL : ptv->mpeer->peer;
805 
806  if (p->afp_v.copy_mode != AFP_COPY_MODE_NONE) {
807  p->afp_v.peer = ptv->mpeer->peer;
809  }
810 
811  /* Timestamp */
812  p->ts = (SCTime_t){ .secs = h.h2->tp_sec, .usecs = h.h2->tp_nsec / 1000 };
813  SCLogDebug("pktlen: %" PRIu32 " (pkt %p, pkt data %p)", GET_PKT_LEN(p), p, GET_PKT_DATA(p));
814 
815  /* We only check for checksum disable */
818  } else if (ptv->checksum_mode == CHECKSUM_VALIDATION_AUTO) {
819  if (ChecksumAutoModeCheck(ptv->pkts, SC_ATOMIC_GET(ptv->livedev->pkts),
820  SC_ATOMIC_GET(ptv->livedev->invalid_checksums))) {
823  }
824  } else {
825  if (tp_status & TP_STATUS_CSUMNOTREADY) {
827  }
828  }
829 }
830 
831 static inline int AFPReadFromRingWaitForPacket(AFPThreadVars *ptv)
832 {
833  union thdr h;
834  struct timeval start_time;
835  gettimeofday(&start_time, NULL);
836  int64_t busy_loop_iter = 0;
837 
838  /* busy wait loop until we have packets available */
839  while (1) {
840  if (unlikely(suricata_ctl_flags != 0)) {
841  break;
842  }
843  h.raw = (((union thdr **)ptv->ring.v2)[ptv->frame_offset]);
844  if (unlikely(h.raw == NULL)) {
845  return AFP_READ_FAILURE;
846  }
847  const unsigned int tp_status = h.h2->tp_status;
848  if (tp_status == TP_STATUS_KERNEL) {
849  busy_loop_iter++;
850 
851  struct timeval cur_time;
852  memset(&cur_time, 0, sizeof(cur_time));
853  uint64_t milliseconds =
854  ((cur_time.tv_sec - start_time.tv_sec) * 1000) +
855  (((1000000 + cur_time.tv_usec - start_time.tv_usec) / 1000) - 1000);
856  if (milliseconds > 1000) {
857  break;
858  }
859  continue;
860  }
861  break;
862  }
863  if (busy_loop_iter) {
864  StatsCounterAvgAddI64(&ptv->tv->stats, ptv->afpacket_spin, busy_loop_iter);
865  }
866  return AFP_READ_OK;
867 }
868 
869 /**
870  * \brief AF packet frame ignore logic
871  *
872  * Given a sockaddr_ll of a frame, use the pkttype_filter_mask to decide if the
873  * frame should be ignored. Protect from undefined behavior if there's ever
874  * a sll_pkttype that would shift by too much. At this point, only outgoing
875  * packets (4) are ignored. The highest value in if_linux.h is PACKET_KERNEL (7),
876  * this extra check is being overly cautious.
877  *
878  * \retval true if the frame should be ignored
879  */
880 static inline bool AFPShouldIgnoreFrame(AFPThreadVars *ptv, const struct sockaddr_ll *sll)
881 {
882  if (unlikely(sll->sll_pkttype > 31))
883  return false;
884 
885  return (ptv->pkttype_filter_mask & BIT_U32(sll->sll_pkttype)) != 0;
886 }
887 
888 /**
889  * \brief AF packet read function for ring
890  *
891  * This function fills
892  * From here the packets are picked up by the DecodeAFP thread.
893  *
894  * \param user pointer to AFPThreadVars
895  * \retval TM_ECODE_FAILED on failure and TM_ECODE_OK on success
896  */
897 static int AFPReadFromRing(AFPThreadVars *ptv)
898 {
899  union thdr h;
900  bool emergency_flush = false;
901  const unsigned int start_pos = ptv->frame_offset;
902 
903  /* poll() told us there are frames, so lets wait for at least
904  * one frame to become available. */
905  if (AFPReadFromRingWaitForPacket(ptv) != AFP_READ_OK)
906  return AFP_READ_FAILURE;
907 
908  /* process the frames in the ring */
909  while (1) {
910  if (unlikely(suricata_ctl_flags != 0)) {
911  break;
912  }
913  h.raw = (((union thdr **)ptv->ring.v2)[ptv->frame_offset]);
914  if (unlikely(h.raw == NULL)) {
915  return AFP_READ_FAILURE;
916  }
917  const unsigned int tp_status = h.h2->tp_status;
918  /* if we find a kernel frame we are done */
919  if (unlikely(tp_status == TP_STATUS_KERNEL)) {
920  break;
921  }
922  /* if in autofp mode the frame is still busy, return to poll */
923  if (unlikely(FRAME_BUSY(tp_status))) {
924  break;
925  }
926  emergency_flush |= ((tp_status & TP_STATUS_LOSING) != 0);
927 
928  if ((ptv->flags & AFP_EMERGENCY_MODE) && emergency_flush) {
929  h.h2->tp_status = TP_STATUS_KERNEL;
930  goto next_frame;
931  }
932 
933  const struct sockaddr_ll *sll =
934  (const struct sockaddr_ll *)((uint8_t *)h.h2 +
935  TPACKET_ALIGN(sizeof(struct tpacket2_hdr)));
936  if (unlikely(AFPShouldIgnoreFrame(ptv, sll)))
937  goto next_frame;
938 
940  if (p == NULL) {
941  return AFPSuriFailure(ptv, h);
942  }
943  AFPReadFromRingSetupPacket(ptv, h, tp_status, p);
944 
945  if (TmThreadsSlotProcessPkt(ptv->tv, ptv->slot, p) != TM_ECODE_OK) {
946  return AFPSuriFailure(ptv, h);
947  }
948 next_frame:
949  if (++ptv->frame_offset >= ptv->req.v2.tp_frame_nr) {
950  ptv->frame_offset = 0;
951  /* Get out of loop to be sure we will reach maintenance tasks */
952  if (ptv->frame_offset == start_pos)
953  break;
954  }
955  }
956  if (emergency_flush) {
957  AFPDumpCounters(ptv);
958  }
960 }
961 
962 static inline void AFPFlushBlock(struct tpacket_block_desc *pbd)
963 {
964  pbd->hdr.bh1.block_status = TP_STATUS_KERNEL;
965 }
966 
967 static inline int AFPParsePacketV3(AFPThreadVars *ptv, struct tpacket_block_desc *pbd, struct tpacket3_hdr *ppd)
968 {
970  if (p == NULL) {
972  }
974 
975  AFPReadApplyBypass(ptv, p);
976 
977  ptv->pkts++;
978  p->livedev_id = ptv->livedev->id;
979  p->datalink = ptv->datalink;
980 
981  if ((ptv->flags & AFP_VLAN_IN_HEADER) &&
982  (ppd->tp_status & TP_STATUS_VLAN_VALID || ppd->hv1.tp_vlan_tci)) {
983  p->vlan_id[0] = ppd->hv1.tp_vlan_tci & 0x0fff;
984  p->vlan_idx = 1;
985  p->afp_v.vlan_tci = (uint16_t)ppd->hv1.tp_vlan_tci;
986  }
987 
988  if (ppd->tp_len > ppd->tp_snaplen) {
989  SCLogDebug("Packet length (%d) > snaplen (%d), truncating", ppd->tp_len, ppd->tp_snaplen);
991  }
992 
993  (void)PacketSetData(p, (unsigned char *)ppd + ppd->tp_mac, ppd->tp_snaplen);
994 
995  p->ReleasePacket = AFPReleasePacketV3;
996  p->afp_v.relptr = NULL;
997  p->afp_v.mpeer = NULL;
998  p->afp_v.copy_mode = ptv->copy_mode;
999  p->afp_v.peer = (p->afp_v.copy_mode == AFP_COPY_MODE_NONE) ? NULL : ptv->mpeer->peer;
1000 
1001  /* Timestamp */
1002  p->ts = (SCTime_t){ .secs = ppd->tp_sec, .usecs = ppd->tp_nsec / 1000 };
1003  SCLogDebug("pktlen: %" PRIu32 " (pkt %p, pkt data %p)",
1004  GET_PKT_LEN(p), p, GET_PKT_DATA(p));
1005 
1006  /* We only check for checksum disable */
1009  } else if (ptv->checksum_mode == CHECKSUM_VALIDATION_AUTO) {
1010  if (ChecksumAutoModeCheck(ptv->pkts,
1011  SC_ATOMIC_GET(ptv->livedev->pkts),
1012  SC_ATOMIC_GET(ptv->livedev->invalid_checksums))) {
1015  }
1016  } else {
1017  if (ppd->tp_status & TP_STATUS_CSUMNOTREADY) {
1019  }
1020  }
1021 
1022  if (TmThreadsSlotProcessPkt(ptv->tv, ptv->slot, p) != TM_ECODE_OK) {
1024  }
1025 
1027 }
1028 
1029 static inline int AFPWalkBlock(AFPThreadVars *ptv, struct tpacket_block_desc *pbd)
1030 {
1031  const int num_pkts = pbd->hdr.bh1.num_pkts;
1032  uint8_t *ppd = (uint8_t *)pbd + pbd->hdr.bh1.offset_to_first_pkt;
1033 
1034  for (int i = 0; i < num_pkts; ++i) {
1035  const struct sockaddr_ll *sll =
1036  (const struct sockaddr_ll *)(ppd + TPACKET_ALIGN(sizeof(struct tpacket3_hdr)));
1037  if (unlikely(AFPShouldIgnoreFrame(ptv, sll))) {
1038  ppd = ppd + ((struct tpacket3_hdr *)ppd)->tp_next_offset;
1039  continue;
1040  }
1041  int ret = AFPParsePacketV3(ptv, pbd, (struct tpacket3_hdr *)ppd);
1042  switch (ret) {
1043  case AFP_READ_OK:
1044  break;
1045  case AFP_SURI_FAILURE:
1046  /* Internal error but let's just continue and
1047  * treat thenext packet */
1048  break;
1049  case AFP_READ_FAILURE:
1051  default:
1052  SCReturnInt(ret);
1053  }
1054  ppd = ppd + ((struct tpacket3_hdr *)ppd)->tp_next_offset;
1055  }
1056 
1058 }
1059 
1060 /**
1061  * \brief AF packet read function for ring
1062  *
1063  * This function fills
1064  * From here the packets are picked up by the DecodeAFP thread.
1065  *
1066  * \param user pointer to AFPThreadVars
1067  * \retval TM_ECODE_FAILED on failure and TM_ECODE_OK on success
1068  */
1069 static int AFPReadFromRingV3(AFPThreadVars *ptv)
1070 {
1071  /* Loop till we have packets available */
1072  while (1) {
1073  if (unlikely(suricata_ctl_flags != 0)) {
1074  SCLogDebug("Exiting AFP V3 read loop");
1075  break;
1076  }
1077 
1078  struct tpacket_block_desc *pbd =
1079  (struct tpacket_block_desc *)ptv->ring.v3[ptv->frame_offset].iov_base;
1080 
1081  /* block is not ready to be read */
1082  if ((pbd->hdr.bh1.block_status & TP_STATUS_USER) == 0) {
1084  }
1085 
1086  int ret = AFPWalkBlock(ptv, pbd);
1087  if (unlikely(ret != AFP_READ_OK)) {
1088  AFPFlushBlock(pbd);
1089  SCReturnInt(ret);
1090  }
1091 
1092  AFPFlushBlock(pbd);
1093  ptv->frame_offset = (ptv->frame_offset + 1) % ptv->req.v3.tp_block_nr;
1094  /* return to maintenance task after one loop on the ring */
1095  if (ptv->frame_offset == 0) {
1097  }
1098  }
1100 }
1101 
1102 /**
1103  * \brief Reference socket
1104  *
1105  * \retval O in case of failure, 1 in case of success
1106  */
1107 static int AFPRefSocket(AFPPeer* peer)
1108 {
1109  if (unlikely(peer == NULL))
1110  return 0;
1111 
1112  (void)SC_ATOMIC_ADD(peer->sock_usage, 1);
1113  return 1;
1114 }
1115 
1116 
1117 /**
1118  * \brief Dereference socket
1119  *
1120  * \retval 1 if socket is still alive, 0 if not
1121  */
1122 static int AFPDerefSocket(AFPPeer* peer)
1123 {
1124  if (peer == NULL)
1125  return 1;
1126 
1127  if (SC_ATOMIC_SUB(peer->sock_usage, 1) == 1) {
1128  return 0;
1129  }
1130  return 1;
1131 }
1132 
1133 static void AFPCloseSocket(AFPThreadVars *ptv)
1134 {
1135  if (ptv->mpeer != NULL)
1136  BUG_ON(SC_ATOMIC_GET(ptv->mpeer->sock_usage) != 0);
1137 
1138  if (ptv->flags & AFP_TPACKET_V3) {
1139  if (ptv->ring.v3) {
1140  SCFree(ptv->ring.v3);
1141  ptv->ring.v3 = NULL;
1142  }
1143  } else {
1144  if (ptv->ring.v2) {
1145  /* only used in reading phase, we can free it */
1146  SCFree(ptv->ring.v2);
1147  ptv->ring.v2 = NULL;
1148  }
1149  }
1150  if (ptv->socket != -1) {
1151  SCLogDebug("Cleaning socket connected to '%s'", ptv->iface);
1152  munmap(ptv->ring_buf, ptv->ring_buflen);
1153  close(ptv->socket);
1154  ptv->socket = -1;
1155  }
1156 }
1157 
1158 static void AFPSwitchState(AFPThreadVars *ptv, uint8_t state)
1159 {
1160  ptv->afp_state = state;
1161  ptv->down_count = 0;
1162 
1163  if (state == AFP_STATE_DOWN) {
1164  /* cleanup is done on thread cleanup or try reopen
1165  * as there may still be packets in autofp that
1166  * are referencing us */
1167  (void)SC_ATOMIC_SUB(ptv->mpeer->sock_usage, 1);
1168  }
1169  if (state == AFP_STATE_UP) {
1170  AFPPeerUpdate(ptv);
1171  (void)SC_ATOMIC_SET(ptv->mpeer->sock_usage, 1);
1172  }
1173 }
1174 
1175 static int AFPReadAndDiscardFromRing(AFPThreadVars *ptv, struct timeval *synctv,
1176  uint64_t *discarded_pkts)
1177 {
1178  if (unlikely(suricata_ctl_flags != 0)) {
1179  return 1;
1180  }
1181 
1182  if (ptv->flags & AFP_TPACKET_V3) {
1183  int ret = 0;
1184  struct tpacket_block_desc *pbd =
1185  (struct tpacket_block_desc *)ptv->ring.v3[ptv->frame_offset].iov_base;
1186  *discarded_pkts += pbd->hdr.bh1.num_pkts;
1187  struct tpacket3_hdr *ppd =
1188  (struct tpacket3_hdr *)((uint8_t *)pbd + pbd->hdr.bh1.offset_to_first_pkt);
1189  if (((time_t)ppd->tp_sec > synctv->tv_sec) ||
1190  ((time_t)ppd->tp_sec == synctv->tv_sec &&
1191  (suseconds_t) (ppd->tp_nsec / 1000) > (suseconds_t)synctv->tv_usec)) {
1192  ret = 1;
1193  }
1194  AFPFlushBlock(pbd);
1195  ptv->frame_offset = (ptv->frame_offset + 1) % ptv->req.v3.tp_block_nr;
1196  return ret;
1197 
1198  } else {
1199  /* Read packet from ring */
1200  union thdr h;
1201  h.raw = (((union thdr **)ptv->ring.v2)[ptv->frame_offset]);
1202  if (h.raw == NULL) {
1203  return -1;
1204  }
1205  if (h.h2->tp_status == TP_STATUS_KERNEL)
1206  return 0;
1207 
1208  if (((time_t)h.h2->tp_sec > synctv->tv_sec) ||
1209  ((time_t)h.h2->tp_sec == synctv->tv_sec &&
1210  (suseconds_t) (h.h2->tp_nsec / 1000) > synctv->tv_usec)) {
1211  return 1;
1212  }
1213 
1214  (*discarded_pkts)++;
1215  h.h2->tp_status = TP_STATUS_KERNEL;
1216  if (++ptv->frame_offset >= ptv->req.v2.tp_frame_nr) {
1217  ptv->frame_offset = 0;
1218  }
1219  }
1220 
1221  return 0;
1222 }
1223 
1224 /** \brief wait for all afpacket threads to fully init
1225  *
1226  * Discard packets before all threads are ready, as the cluster
1227  * setup is not complete yet.
1228  *
1229  * if AFPPeersListStarted() returns true init is complete
1230  *
1231  * \retval r 1 = happy, otherwise unhappy
1232  */
1233 static int AFPSynchronizeStart(AFPThreadVars *ptv, uint64_t *discarded_pkts)
1234 {
1235  struct timeval synctv;
1236  struct pollfd fds;
1237 
1238  fds.fd = ptv->socket;
1239  fds.events = POLLIN;
1240 
1241  /* Set timeval to end of the world */
1242  synctv.tv_sec = 0xffffffff;
1243  synctv.tv_usec = 0xffffffff;
1244 
1245  while (1) {
1246  int r = poll(&fds, 1, POLL_TIMEOUT);
1247  if (r > 0 &&
1248  (fds.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
1249  SCLogWarning("%s: poll failed %02x", ptv->iface,
1250  fds.revents & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL));
1251  return 0;
1252  } else if (r > 0) {
1253  if (AFPPeersListStarted() && synctv.tv_sec == (time_t) 0xffffffff) {
1254  gettimeofday(&synctv, NULL);
1255  }
1256  r = AFPReadAndDiscardFromRing(ptv, &synctv, discarded_pkts);
1257  SCLogDebug("Discarding on %s", ptv->tv->name);
1258  switch (r) {
1259  case 1:
1260  SCLogDebug("Starting to read on %s", ptv->tv->name);
1261  return 1;
1262  case -1:
1263  return r;
1264  }
1265  /* no packets */
1266  } else if (r == 0 && AFPPeersListStarted()) {
1267  SCLogDebug("Starting to read on %s", ptv->tv->name);
1268  return 1;
1269  } else if (r < 0) { /* only exit on error */
1270  SCLogWarning("poll failed with retval %d", r);
1271  return 0;
1272  }
1273  }
1274  return 1;
1275 }
1276 
1277 /**
1278  * \brief Try to reopen socket
1279  *
1280  * \retval 0 in case of success, negative if error occurs or a condition
1281  * is not met.
1282  */
1283 static int AFPTryReopen(AFPThreadVars *ptv)
1284 {
1285  ptv->down_count++;
1286 
1287  /* Don't reconnect till we have packet that did not release data */
1288  if (SC_ATOMIC_GET(ptv->mpeer->sock_usage) != 0) {
1289  return -1;
1290  }
1291 
1292  /* ref cnt 0, we can close the old socket */
1293  AFPCloseSocket(ptv);
1294 
1295  int afp_activate_r = AFPCreateSocket(ptv, ptv->iface, 0);
1296  if (afp_activate_r != 0) {
1297  if (ptv->down_count % AFP_DOWN_COUNTER_INTERVAL == 0) {
1298  SCLogWarning("%s: can't reopen interface", ptv->iface);
1299  }
1300  return afp_activate_r;
1301  }
1302 
1303  SCLogInfo("%s: interface is back up", ptv->iface);
1304  return 0;
1305 }
1306 
1307 /**
1308  * \brief Main AF_PACKET reading Loop function
1309  */
1310 TmEcode ReceiveAFPLoop(ThreadVars *tv, void *data, void *slot)
1311 {
1312  SCEnter();
1313 
1314  AFPThreadVars *ptv = (AFPThreadVars *)data;
1315  struct pollfd fds;
1316  int r;
1317  TmSlot *s = (TmSlot *)slot;
1318  time_t last_dump = 0;
1319  time_t current_time;
1320  int (*AFPReadFunc) (AFPThreadVars *);
1321  uint64_t discarded_pkts = 0;
1322 
1323  ptv->slot = s->slot_next;
1324 
1325  if (ptv->flags & AFP_TPACKET_V3) {
1326  AFPReadFunc = AFPReadFromRingV3;
1327  } else {
1328  AFPReadFunc = AFPReadFromRing;
1329  }
1330 
1331  if (ptv->afp_state == AFP_STATE_DOWN) {
1332  /* Wait for our turn, threads before us must have opened the socket */
1333  while (AFPPeersListWaitTurn(ptv->mpeer)) {
1334  usleep(1000);
1335  if (suricata_ctl_flags != 0) {
1336  break;
1337  }
1338  }
1339  r = AFPCreateSocket(ptv, ptv->iface, 1);
1340  if (r < 0) {
1341  switch (-r) {
1342  case AFP_FATAL_ERROR:
1343  SCLogError("%s: failed to init socket for interface", ptv->iface);
1345  case AFP_RECOVERABLE_ERROR:
1346  SCLogWarning(
1347  "%s: failed to init socket for interface, retrying soon", ptv->iface);
1348  }
1349  }
1350  AFPPeersListReachedInc();
1351  }
1352  if (ptv->afp_state == AFP_STATE_UP) {
1353  SCLogDebug("Thread %s using socket %d", tv->name, ptv->socket);
1354  AFPSynchronizeStart(ptv, &discarded_pkts);
1355  /* let's reset counter as we will start the capture at the
1356  * next function call */
1357 #ifdef PACKET_STATISTICS
1358  struct tpacket_stats kstats;
1359  socklen_t len = sizeof (struct tpacket_stats);
1360  if (getsockopt(ptv->socket, SOL_PACKET, PACKET_STATISTICS,
1361  &kstats, &len) > -1) {
1362  int64_t pkts = 0;
1363  SCLogDebug("(%s) Kernel socket startup: Packets %" PRIu32
1364  ", dropped %" PRIu32 "",
1365  ptv->tv->name,
1366  kstats.tp_packets, kstats.tp_drops);
1367  pkts = kstats.tp_packets - discarded_pkts - kstats.tp_drops;
1368  StatsCounterAddI64(&ptv->tv->stats, ptv->capture_kernel_packets, pkts);
1369  (void) SC_ATOMIC_ADD(ptv->livedev->pkts, pkts);
1370  }
1371 #endif
1372  }
1373 
1374  fds.fd = ptv->socket;
1375  fds.events = POLLIN;
1376 
1377  // Indicate that the thread is actually running its application level code (i.e., it can poll
1378  // packets)
1380 
1381  while (1) {
1382  /* Start by checking the state of our interface */
1383  if (unlikely(ptv->afp_state == AFP_STATE_DOWN)) {
1384  int dbreak = 0;
1385 
1386  do {
1387  usleep(AFP_RECONNECT_TIMEOUT);
1388  if (suricata_ctl_flags != 0) {
1389  dbreak = 1;
1390  break;
1391  }
1392  r = AFPTryReopen(ptv);
1393  fds.fd = ptv->socket;
1394  } while (r < 0);
1395  if (dbreak == 1)
1396  break;
1397  }
1398 
1399  /* make sure we have at least one packet in the packet pool, to prevent
1400  * us from alloc'ing packets at line rate */
1401  PacketPoolWait();
1402 
1403  StatsCounterIncr(&ptv->tv->stats, ptv->capture_afp_poll);
1404 
1405  r = poll(&fds, 1, POLL_TIMEOUT);
1406 
1407  if (suricata_ctl_flags != 0) {
1408  break;
1409  }
1410 
1411  if (r > 0 &&
1412  (fds.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
1414  if (fds.revents & (POLLHUP | POLLRDHUP)) {
1415  AFPSwitchState(ptv, AFP_STATE_DOWN);
1416  continue;
1417  } else if (fds.revents & POLLERR) {
1418  char c;
1419  /* Do a recv to get errno */
1420  if (recv(ptv->socket, &c, sizeof c, MSG_PEEK) != -1)
1421  continue; /* what, no error? */
1422  SCLogWarning("%s: failed to poll interface: %s", ptv->iface, strerror(errno));
1423  AFPSwitchState(ptv, AFP_STATE_DOWN);
1424  continue;
1425  } else if (fds.revents & POLLNVAL) {
1426  SCLogWarning("%s: invalid poll request: %s", ptv->iface, strerror(errno));
1427  AFPSwitchState(ptv, AFP_STATE_DOWN);
1428  continue;
1429  }
1430  } else if (r > 0) {
1432  r = AFPReadFunc(ptv);
1433  switch (r) {
1434  case AFP_READ_OK:
1435  /* Trigger one dump of stats every second */
1436  current_time = time(NULL);
1437  if (current_time != last_dump) {
1438  AFPDumpCounters(ptv);
1439  last_dump = current_time;
1440  }
1441  break;
1442  case AFP_READ_FAILURE:
1443  /* AFPRead in error: best to reset the socket */
1444  SCLogWarning("%s: read failure: %s", ptv->iface, strerror(errno));
1445  AFPSwitchState(ptv, AFP_STATE_DOWN);
1446  continue;
1447  case AFP_SURI_FAILURE:
1448  StatsCounterIncr(&ptv->tv->stats, ptv->capture_errors);
1449  break;
1450  case AFP_KERNEL_DROP:
1451  AFPDumpCounters(ptv);
1452  break;
1453  }
1454  } else if (unlikely(r == 0)) {
1456  /* Trigger one dump of stats every second */
1457  current_time = time(NULL);
1458  if (current_time != last_dump) {
1459  AFPDumpCounters(ptv);
1460  last_dump = current_time;
1461  }
1462  /* poll timed out, lets see handle our timeout path */
1463  TmThreadsCaptureHandleTimeout(tv, NULL);
1464 
1465  } else if ((r < 0) && (errno != EINTR)) {
1467  SCLogWarning("%s: poll failure: %s", ptv->iface, strerror(errno));
1468  AFPSwitchState(ptv, AFP_STATE_DOWN);
1469  continue;
1470  }
1472  }
1473 
1474  AFPDumpCounters(ptv);
1477 }
1478 
1479 static int AFPGetDevFlags(int fd, const char *ifname)
1480 {
1481  struct ifreq ifr;
1482 
1483  memset(&ifr, 0, sizeof(ifr));
1484  strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
1485 
1486  if (ioctl(fd, SIOCGIFFLAGS, &ifr) == -1) {
1487  SCLogError("%s: failed to get interface flags: %s", ifname, strerror(errno));
1488  return -1;
1489  }
1490 
1491  return ifr.ifr_flags;
1492 }
1493 
1494 
1495 static int AFPGetIfnumByDev(int fd, const char *ifname, int verbose)
1496 {
1497  struct ifreq ifr;
1498 
1499  memset(&ifr, 0, sizeof(ifr));
1500  strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
1501 
1502  if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
1503  if (verbose)
1504  SCLogError("%s: failed to find interface: %s", ifname, strerror(errno));
1505  return -1;
1506  }
1507 
1508  return ifr.ifr_ifindex;
1509 }
1510 
1511 static int AFPGetDevLinktype(int fd, const char *ifname)
1512 {
1513  struct ifreq ifr;
1514 
1515  memset(&ifr, 0, sizeof(ifr));
1516  strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
1517 
1518  if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
1519  SCLogError("%s: failed to find interface type: %s", ifname, strerror(errno));
1520  return -1;
1521  }
1522 
1523  switch (ifr.ifr_hwaddr.sa_family) {
1524  case ARPHRD_LOOPBACK:
1525  return LINKTYPE_ETHERNET;
1526  case ARPHRD_PPP:
1527  case ARPHRD_NONE:
1528  return LINKTYPE_RAW;
1529  default:
1530  return ifr.ifr_hwaddr.sa_family;
1531  }
1532 }
1533 
1534 int AFPGetLinkType(const char *ifname)
1535 {
1536  int ltype;
1537 
1538  int fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
1539  if (fd == -1) {
1540  SCLogError("%s: failed to create AF_PACKET socket: %s", ifname, strerror(errno));
1541  return LINKTYPE_RAW;
1542  }
1543 
1544  ltype = AFPGetDevLinktype(fd, ifname);
1545  close(fd);
1546 
1547  DatalinkSetGlobalType(ltype);
1548 
1549  return ltype;
1550 }
1551 
1552 static int AFPComputeRingParams(AFPThreadVars *ptv, int order)
1553 {
1554  /* Compute structure:
1555  Target is to store all pending packets
1556  with a size equal to MTU + auxdata
1557  And we keep a decent number of block
1558 
1559  To do so:
1560  Compute frame_size (aligned to be able to fit in block
1561  Check which block size we need. Blocksize is a 2^n * pagesize
1562  We then need to get order, big enough to have
1563  frame_size < block size
1564  Find number of frame per block (divide)
1565  Fill in packet_req
1566 
1567  Compute frame size:
1568  described in packet_mmap.txt
1569  dependent on snaplen (need to use a variable ?)
1570 snaplen: MTU ?
1571 tp_hdrlen determine_version in daq_afpacket
1572 in V1: sizeof(struct tpacket_hdr);
1573 in V2: val in getsockopt(instance->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len)
1574 frame size: TPACKET_ALIGN(snaplen + TPACKET_ALIGN(TPACKET_ALIGN(tp_hdrlen) + sizeof(struct
1575 sockaddr_ll) + ETH_HLEN) - ETH_HLEN);
1576 
1577  */
1578  int tp_hdrlen = sizeof(struct tpacket_hdr);
1579  int snaplen = default_packet_size;
1580 
1581  if (snaplen == 0) {
1583  SCLogConfig("%s: defrag enabled, setting snaplen to %d", ptv->iface,
1586  } else {
1587  snaplen = GetIfaceMaxPacketSize(ptv->livedev);
1588  if (snaplen <= 0) {
1589  SCLogWarning("%s: unable to get MTU, setting snaplen default of 1514", ptv->iface);
1590  snaplen = 1514;
1591  }
1592  }
1593  }
1594  ptv->snaplen = snaplen;
1595 
1596  ptv->req.v2.tp_frame_size = TPACKET_ALIGN(snaplen +TPACKET_ALIGN(TPACKET_ALIGN(tp_hdrlen) + sizeof(struct sockaddr_ll) + ETH_HLEN) - ETH_HLEN);
1597  ptv->req.v2.tp_block_size = getpagesize() << order;
1598  int frames_per_block = ptv->req.v2.tp_block_size / ptv->req.v2.tp_frame_size;
1599  if (frames_per_block == 0) {
1600  SCLogError("%s: Frame size bigger than block size", ptv->iface);
1601  return -1;
1602  }
1603  ptv->req.v2.tp_frame_nr = ptv->ring_size;
1604  ptv->req.v2.tp_block_nr = ptv->req.v2.tp_frame_nr / frames_per_block + 1;
1605  /* exact division */
1606  ptv->req.v2.tp_frame_nr = ptv->req.v2.tp_block_nr * frames_per_block;
1607  SCLogPerf("%s: rx ring: block_size=%d block_nr=%d frame_size=%d frame_nr=%d", ptv->iface,
1608  ptv->req.v2.tp_block_size, ptv->req.v2.tp_block_nr, ptv->req.v2.tp_frame_size,
1609  ptv->req.v2.tp_frame_nr);
1610  return 1;
1611 }
1612 
1613 static int AFPComputeRingParamsWithBlockSize(AFPThreadVars *ptv, unsigned int block_size)
1614 {
1615  /* Compute structure:
1616  Target is to store all pending packets
1617  with a size equal to MTU + auxdata
1618  And we keep a decent number of block
1619 
1620  To do so:
1621  Compute frame_size (aligned to be able to fit in block
1622  Check which block size we need. Blocksize is a 2^n * pagesize
1623  We then need to get order, big enough to have
1624  frame_size < block size
1625  Find number of frame per block (divide)
1626  Fill in packet_req
1627 
1628  Compute frame size:
1629  described in packet_mmap.txt
1630  dependent on snaplen (need to use a variable ?)
1631 snaplen: MTU ?
1632 tp_hdrlen determine_version in daq_afpacket
1633 in V1: sizeof(struct tpacket_hdr);
1634 in V2: val in getsockopt(instance->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len)
1635 frame size: TPACKET_ALIGN(snaplen + TPACKET_ALIGN(TPACKET_ALIGN(tp_hdrlen) + sizeof(struct
1636 sockaddr_ll) + ETH_HLEN) - ETH_HLEN);
1637 
1638  */
1639  int tp_hdrlen = sizeof(struct tpacket_hdr);
1640  int snaplen = default_packet_size;
1641 
1642  if (snaplen == 0) {
1644  SCLogConfig("%s: defrag enabled, setting snaplen to %d", ptv->iface,
1647  } else {
1648  snaplen = GetIfaceMaxPacketSize(ptv->livedev);
1649  if (snaplen <= 0) {
1650  SCLogWarning("%s: unable to get MTU, setting snaplen default of 1514", ptv->iface);
1651  snaplen = 1514;
1652  }
1653  }
1654  }
1655  ptv->snaplen = snaplen;
1656 
1657  ptv->req.v2.tp_frame_size = TPACKET_ALIGN(
1658  snaplen +
1659  TPACKET_ALIGN(TPACKET_ALIGN(tp_hdrlen) + sizeof(struct sockaddr_ll) + ETH_HLEN) -
1660  ETH_HLEN);
1661  ptv->req.v2.tp_block_size = block_size;
1662  int frames_per_block = ptv->req.v2.tp_block_size / ptv->req.v2.tp_frame_size;
1663  if (frames_per_block == 0) {
1664  SCLogError("%s: Frame size bigger than block size", ptv->iface);
1665  return -1;
1666  }
1667  ptv->req.v2.tp_frame_nr = ptv->ring_size;
1668  ptv->req.v2.tp_block_nr = ptv->req.v2.tp_frame_nr / frames_per_block + 1;
1669  /* exact division */
1670  ptv->req.v2.tp_frame_nr = ptv->req.v2.tp_block_nr * frames_per_block;
1671  SCLogPerf("%s: rx ring: block_size=%d block_nr=%d frame_size=%d frame_nr=%d", ptv->iface,
1672  ptv->req.v2.tp_block_size, ptv->req.v2.tp_block_nr, ptv->req.v2.tp_frame_size,
1673  ptv->req.v2.tp_frame_nr);
1674  return 1;
1675 }
1676 
1677 static int AFPComputeRingParamsV3(AFPThreadVars *ptv)
1678 {
1679  ptv->req.v3.tp_block_size = ptv->block_size;
1680  ptv->req.v3.tp_frame_size = 2048;
1681  int frames_per_block = 0;
1682  int tp_hdrlen = sizeof(struct tpacket3_hdr);
1683  int snaplen = default_packet_size;
1684 
1685  if (snaplen == 0) {
1686  snaplen = GetIfaceMaxPacketSize(ptv->livedev);
1687  if (snaplen <= 0) {
1688  SCLogWarning("%s: unable to get MTU, setting snaplen default of 1514", ptv->iface);
1689  snaplen = 1514;
1690  }
1691  }
1692  ptv->snaplen = snaplen;
1693 
1694  ptv->req.v3.tp_frame_size = TPACKET_ALIGN(snaplen +TPACKET_ALIGN(TPACKET_ALIGN(tp_hdrlen) + sizeof(struct sockaddr_ll) + ETH_HLEN) - ETH_HLEN);
1695  frames_per_block = ptv->req.v3.tp_block_size / ptv->req.v3.tp_frame_size;
1696 
1697  if (frames_per_block == 0) {
1698  SCLogError("%s: block size is too small, it should be at least %d", ptv->iface,
1699  ptv->req.v3.tp_frame_size);
1700  return -1;
1701  }
1702  ptv->req.v3.tp_block_nr = ptv->ring_size / frames_per_block + 1;
1703  /* exact division */
1704  ptv->req.v3.tp_frame_nr = ptv->req.v3.tp_block_nr * frames_per_block;
1705  ptv->req.v3.tp_retire_blk_tov = ptv->block_timeout;
1706  ptv->req.v3.tp_feature_req_word = TP_FT_REQ_FILL_RXHASH;
1707  SCLogPerf("%s: rx ring params: block_size=%d block_nr=%d frame_size=%d frame_nr=%d (mem: %d)",
1708  ptv->iface, ptv->req.v3.tp_block_size, ptv->req.v3.tp_block_nr,
1709  ptv->req.v3.tp_frame_size, ptv->req.v3.tp_frame_nr,
1710  ptv->req.v3.tp_block_size * ptv->req.v3.tp_block_nr);
1711  return 1;
1712 }
1713 
1714 static int AFPSetupRing(AFPThreadVars *ptv, char *devname)
1715 {
1716  int val;
1717  unsigned int len = sizeof(val), i;
1718  int order;
1719  int r, mmap_flag;
1720 
1721  if (ptv->flags & AFP_TPACKET_V3) {
1722  val = TPACKET_V3;
1723  } else {
1724  val = TPACKET_V2;
1725  }
1726  if (getsockopt(ptv->socket, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
1727  if (errno == ENOPROTOOPT) {
1728  if (ptv->flags & AFP_TPACKET_V3) {
1729  SCLogError("%s: kernel too old for TPACKET_V3 (need 3.2+)", devname);
1730  } else {
1731  SCLogError("%s: kernel too old (need 2.6.27+)", devname);
1732  }
1733  }
1734  SCLogError("%s: failed to retrieve packet header len", devname);
1735  return AFP_FATAL_ERROR;
1736  }
1737 
1738  val = TPACKET_V2;
1739  if (ptv->flags & AFP_TPACKET_V3) {
1740  val = TPACKET_V3;
1741  }
1742  if (setsockopt(ptv->socket, SOL_PACKET, PACKET_VERSION, &val,
1743  sizeof(val)) < 0) {
1744  SCLogError("%s: failed to activate TPACKET_V2/TPACKET_V3 on packet socket: %s", devname,
1745  strerror(errno));
1746  return AFP_FATAL_ERROR;
1747  }
1748 
1749 #ifdef HAVE_HW_TIMESTAMPING
1750  if (ptv->flags & AFP_ENABLE_HWTIMESTAMP) {
1751  int req = SOF_TIMESTAMPING_RAW_HARDWARE;
1752  if (setsockopt(ptv->socket, SOL_PACKET, PACKET_TIMESTAMP, (void *)&req, sizeof(req)) < 0) {
1753  SCLogWarning("%s: failed to activate hardware timestamping on packet socket: %s",
1754  devname, strerror(errno));
1755  } else {
1756  SCLogConfig("%s: hardware timestamping enabled", devname);
1757  }
1758  } else {
1759  SCLogConfig("%s: hardware timestamping disabled", devname);
1760  }
1761 #endif
1762 
1763  /* Reserve head room for a VLAN header. One vlan is extracted from AFP header
1764  * so one VLAN header length is enough. */
1765  int reserve = VLAN_HEADER_LEN;
1766  if (setsockopt(ptv->socket, SOL_PACKET, PACKET_RESERVE, (void *)&reserve, sizeof(reserve)) <
1767  0) {
1768  SCLogError("%s: failed to activate reserve on packet socket: %s", devname, strerror(errno));
1769  return AFP_FATAL_ERROR;
1770  }
1771 
1772  /* Allocate RX ring */
1773  if (ptv->flags & AFP_TPACKET_V3) {
1774  if (AFPComputeRingParamsV3(ptv) != 1) {
1775  return AFP_FATAL_ERROR;
1776  }
1777  r = setsockopt(ptv->socket, SOL_PACKET, PACKET_RX_RING,
1778  (void *) &ptv->req.v3, sizeof(ptv->req.v3));
1779  if (r < 0) {
1780  SCLogError("%s: failed to allocate RX Ring: %s", devname, strerror(errno));
1781  return AFP_FATAL_ERROR;
1782  }
1783  } else {
1784  if (ptv->v2_block_size) {
1785 
1786  if (AFPComputeRingParamsWithBlockSize(ptv, ptv->v2_block_size) != 1) {
1787  SCLogError("%s: ring parameters are incorrect. Please file a bug report", devname);
1788  return AFP_FATAL_ERROR;
1789  }
1790 
1791  r = setsockopt(
1792  ptv->socket, SOL_PACKET, PACKET_RX_RING, (void *)&ptv->req, sizeof(ptv->req));
1793 
1794  if (r < 0) {
1795  if (errno == ENOMEM) {
1796  SCLogError("%s: memory issue with ring parameters", devname);
1797  return AFP_FATAL_ERROR;
1798  }
1799  SCLogError("%s: failed to setup RX Ring: %s", devname, strerror(errno));
1800  return AFP_FATAL_ERROR;
1801  }
1802 
1803  } else {
1804  for (order = AFP_BLOCK_SIZE_DEFAULT_ORDER; order >= 0; order--) {
1805  if (AFPComputeRingParams(ptv, order) != 1) {
1806  SCLogError(
1807  "%s: ring parameters are incorrect. Please file a bug report", devname);
1808  return AFP_FATAL_ERROR;
1809  }
1810 
1811  r = setsockopt(ptv->socket, SOL_PACKET, PACKET_RX_RING, (void *)&ptv->req,
1812  sizeof(ptv->req));
1813 
1814  if (r < 0) {
1815  if (errno == ENOMEM) {
1816  SCLogWarning("%s: memory issue with ring parameters. Retrying", devname);
1817  continue;
1818  }
1819  SCLogError("%s: failed to setup RX Ring: %s", devname, strerror(errno));
1820  return AFP_FATAL_ERROR;
1821  } else {
1822  break;
1823  }
1824  }
1825  if (order < 0) {
1826  SCLogError("%s: failed to setup RX Ring (order 0 failed)", devname);
1827  return AFP_FATAL_ERROR;
1828  }
1829  }
1830  }
1831 
1832  /* Allocate the Ring */
1833  if (ptv->flags & AFP_TPACKET_V3) {
1834  ptv->ring_buflen = ptv->req.v3.tp_block_nr * ptv->req.v3.tp_block_size;
1835  } else {
1836  ptv->ring_buflen = ptv->req.v2.tp_block_nr * ptv->req.v2.tp_block_size;
1837  }
1838  mmap_flag = MAP_SHARED;
1839  if (ptv->flags & AFP_MMAP_LOCKED)
1840  mmap_flag |= MAP_LOCKED;
1841  ptv->ring_buf = mmap(0, ptv->ring_buflen, PROT_READ|PROT_WRITE,
1842  mmap_flag, ptv->socket, 0);
1843  if (ptv->ring_buf == MAP_FAILED) {
1844  SCLogError("%s: failed to mmap: %s", devname, strerror(errno));
1845  goto mmap_err;
1846  }
1847  if (ptv->flags & AFP_TPACKET_V3) {
1848  ptv->ring.v3 = SCMalloc(ptv->req.v3.tp_block_nr * sizeof(*ptv->ring.v3));
1849  if (!ptv->ring.v3) {
1850  SCLogError("%s: failed to alloc ring: %s", devname, strerror(errno));
1851  goto postmmap_err;
1852  }
1853  for (i = 0; i < ptv->req.v3.tp_block_nr; ++i) {
1854  ptv->ring.v3[i].iov_base = ptv->ring_buf + (i * ptv->req.v3.tp_block_size);
1855  ptv->ring.v3[i].iov_len = ptv->req.v3.tp_block_size;
1856  }
1857  } else {
1858  /* allocate a ring for each frame header pointer*/
1859  ptv->ring.v2 = SCCalloc(ptv->req.v2.tp_frame_nr, sizeof(union thdr *));
1860  if (ptv->ring.v2 == NULL) {
1861  SCLogError("%s: failed to alloc ring: %s", devname, strerror(errno));
1862  goto postmmap_err;
1863  }
1864  /* fill the header ring with proper frame ptr*/
1865  ptv->frame_offset = 0;
1866  for (i = 0; i < ptv->req.v2.tp_block_nr; ++i) {
1867  void *base = &(ptv->ring_buf[i * ptv->req.v2.tp_block_size]);
1868  unsigned int j;
1869  for (j = 0; j < ptv->req.v2.tp_block_size / ptv->req.v2.tp_frame_size; ++j, ++ptv->frame_offset) {
1870  (((union thdr **)ptv->ring.v2)[ptv->frame_offset]) = base;
1871  base += ptv->req.v2.tp_frame_size;
1872  }
1873  }
1874  ptv->frame_offset = 0;
1875  }
1876 
1877  return 0;
1878 
1879 postmmap_err:
1880  munmap(ptv->ring_buf, ptv->ring_buflen);
1881  if (ptv->ring.v2)
1882  SCFree(ptv->ring.v2);
1883  if (ptv->ring.v3)
1884  SCFree(ptv->ring.v3);
1885 mmap_err:
1886  /* Packet mmap does the cleaning when socket is closed */
1887  return AFP_FATAL_ERROR;
1888 }
1889 
1890 /** \brief test if we can use FANOUT. Older kernels like those in
1891  * CentOS6 have HAVE_PACKET_FANOUT defined but fail to work
1892  */
1893 int AFPIsFanoutSupported(uint16_t cluster_id)
1894 {
1895 #ifdef HAVE_PACKET_FANOUT
1896  int fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
1897  if (fd < 0)
1898  return 0;
1899 
1901  uint32_t option = (mode << 16) | cluster_id;
1902  int r = setsockopt(fd, SOL_PACKET, PACKET_FANOUT,(void *)&option, sizeof(option));
1903  close(fd);
1904 
1905  if (r < 0) {
1906  SCLogError("fanout not supported by kernel: "
1907  "Kernel too old or cluster-id %d already in use.",
1908  cluster_id);
1909  return 0;
1910  }
1911  return 1;
1912 #else
1913  return 0;
1914 #endif
1915 }
1916 
1917 #ifdef HAVE_PACKET_EBPF
1918 
1919 static int SockFanoutSeteBPF(AFPThreadVars *ptv)
1920 {
1921  int pfd = ptv->ebpf_lb_fd;
1922  if (pfd == -1) {
1923  SCLogError("Fanout file descriptor is invalid");
1924  return -1;
1925  }
1926 
1927  if (setsockopt(ptv->socket, SOL_PACKET, PACKET_FANOUT_DATA, &pfd, sizeof(pfd))) {
1928  SCLogError("Error setting ebpf");
1929  return -1;
1930  }
1931  SCLogInfo("Activated eBPF on socket");
1932 
1933  return 0;
1934 }
1935 
1936 static TmEcode SetEbpfFilter(AFPThreadVars *ptv)
1937 {
1938  int pfd = ptv->ebpf_filter_fd;
1939  if (pfd == -1) {
1940  SCLogError("Filter file descriptor is invalid");
1941  return TM_ECODE_FAILED;
1942  }
1943 
1944  if (setsockopt(ptv->socket, SOL_SOCKET, SO_ATTACH_BPF, &pfd, sizeof(pfd))) {
1945  SCLogError("Error setting ebpf: %s", strerror(errno));
1946  return TM_ECODE_FAILED;
1947  }
1948  SCLogInfo("Activated eBPF filter on socket");
1949 
1950  return TM_ECODE_OK;
1951 }
1952 #endif
1953 
1954 static int AFPCreateSocket(AFPThreadVars *ptv, char *devname, int verbose)
1955 {
1956  int r;
1957  int ret = AFP_FATAL_ERROR;
1958  struct packet_mreq sock_params;
1959  struct sockaddr_ll bind_address;
1960  int if_idx;
1961 
1962  /* open socket */
1963  ptv->socket = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
1964  if (ptv->socket == -1) {
1965  SCLogError("%s: failed to create socket: %s", devname, strerror(errno));
1966  goto error;
1967  }
1968 
1969  if_idx = AFPGetIfnumByDev(ptv->socket, devname, verbose);
1970  if (if_idx == -1) {
1971  goto socket_err;
1972  }
1973 
1974  /* bind socket */
1975  memset(&bind_address, 0, sizeof(bind_address));
1976  bind_address.sll_family = AF_PACKET;
1977  bind_address.sll_protocol = htons(ETH_P_ALL);
1978  bind_address.sll_ifindex = if_idx;
1979  if (bind_address.sll_ifindex == -1) {
1980  if (verbose)
1981  SCLogWarning("%s: device for found", devname);
1982  ret = AFP_RECOVERABLE_ERROR;
1983  goto socket_err;
1984  }
1985 
1986  int if_flags = AFPGetDevFlags(ptv->socket, ptv->iface);
1987  if (if_flags == -1) {
1988  if (verbose) {
1989  SCLogWarning("%s: failed to get interface flags", ptv->iface);
1990  }
1991  ret = AFP_RECOVERABLE_ERROR;
1992  goto socket_err;
1993  } else if ((if_flags & (IFF_UP | IFF_RUNNING)) == 0) {
1994  if (verbose) {
1995  SCLogWarning("%s: interface is down", ptv->iface);
1996  }
1997  ret = AFP_RECOVERABLE_ERROR;
1998  goto socket_err;
1999  }
2000 
2001  /* ignore outgoing packets on loopback interfaces */
2002  if (if_flags & IFF_LOOPBACK)
2003  ptv->pkttype_filter_mask |= BIT_U32(PACKET_OUTGOING);
2004 
2005  if (ptv->promisc != 0) {
2006  /* Force promiscuous mode */
2007  memset(&sock_params, 0, sizeof(sock_params));
2008  sock_params.mr_type = PACKET_MR_PROMISC;
2009  sock_params.mr_ifindex = bind_address.sll_ifindex;
2010  r = setsockopt(ptv->socket, SOL_PACKET, PACKET_ADD_MEMBERSHIP,(void *)&sock_params, sizeof(sock_params));
2011  if (r < 0) {
2012  SCLogError("%s: failed to set promisc mode: %s", devname, strerror(errno));
2013  goto socket_err;
2014  }
2015  }
2016 
2018  int val = 1;
2019  if (setsockopt(ptv->socket, SOL_PACKET, PACKET_AUXDATA, &val,
2020  sizeof(val)) == -1 && errno != ENOPROTOOPT) {
2021  SCLogWarning(
2022  "%s: 'kernel' checksum mode not supported, falling back to full mode", devname);
2024  }
2025  }
2026 
2027  /* set socket recv buffer size */
2028  if (ptv->buffer_size != 0) {
2029  /*
2030  * Set the socket buffer size to the specified value.
2031  */
2032  SCLogPerf("%s: setting socket buffer to %d", devname, ptv->buffer_size);
2033  if (setsockopt(ptv->socket, SOL_SOCKET, SO_RCVBUF,
2034  &ptv->buffer_size,
2035  sizeof(ptv->buffer_size)) == -1) {
2036  SCLogError("%s: failed to set buffer size to %d: %s", devname, ptv->buffer_size,
2037  strerror(errno));
2038  goto socket_err;
2039  }
2040  }
2041 
2042  r = bind(ptv->socket, (struct sockaddr *)&bind_address, sizeof(bind_address));
2043  if (r < 0) {
2044  if (verbose) {
2045  if (errno == ENETDOWN) {
2046  SCLogWarning("%s: failed to bind socket, iface is down", devname);
2047  } else {
2048  SCLogWarning("%s: failed to bind socket: %s", devname, strerror(errno));
2049  }
2050  }
2051  ret = AFP_RECOVERABLE_ERROR;
2052  goto socket_err;
2053  }
2054 
2055 
2056 #ifdef HAVE_PACKET_FANOUT
2057  /* add bound socket to fanout group */
2058  if (ptv->threads > 1) {
2059  uint32_t mode = ptv->cluster_type;
2060  uint16_t id = ptv->cluster_id;
2061  uint32_t option = (mode << 16) | (id & 0xffff);
2062  r = setsockopt(ptv->socket, SOL_PACKET, PACKET_FANOUT,(void *)&option, sizeof(option));
2063  if (r < 0) {
2064  SCLogError("%s: failed to set fanout mode: %s", devname, strerror(errno));
2065  goto socket_err;
2066  }
2067  }
2068 #endif
2069 
2070 #ifdef HAVE_PACKET_EBPF
2071  if (ptv->cluster_type == PACKET_FANOUT_EBPF) {
2072  r = SockFanoutSeteBPF(ptv);
2073  if (r < 0) {
2074  SCLogError("%s: failed to set eBPF: %s", devname, strerror(errno));
2075  goto socket_err;
2076  }
2077  }
2078 #endif
2079 
2080  ret = AFPSetupRing(ptv, devname);
2081  if (ret != 0)
2082  goto socket_err;
2083 
2084  SCLogDebug("Using interface '%s' via socket %d", (char *)devname, ptv->socket);
2085 
2086  ptv->datalink = AFPGetDevLinktype(ptv->socket, ptv->iface);
2087 
2088  TmEcode rc = AFPSetBPFFilter(ptv);
2089  if (rc == TM_ECODE_FAILED) {
2090  ret = AFP_FATAL_ERROR;
2091  goto socket_err;
2092  }
2093 
2094  /* Init is ok */
2095  AFPSwitchState(ptv, AFP_STATE_UP);
2096  return 0;
2097 
2098 socket_err:
2099  close(ptv->socket);
2100  ptv->socket = -1;
2101  if (ptv->flags & AFP_TPACKET_V3) {
2102  if (ptv->ring.v3) {
2103  SCFree(ptv->ring.v3);
2104  ptv->ring.v3 = NULL;
2105  }
2106  } else {
2107  if (ptv->ring.v2) {
2108  SCFree(ptv->ring.v2);
2109  ptv->ring.v2 = NULL;
2110  }
2111  }
2112 
2113 error:
2114  return -ret;
2115 }
2116 
2117 TmEcode AFPSetBPFFilter(AFPThreadVars *ptv)
2118 {
2119  struct bpf_program filter;
2120  struct sock_fprog fcode;
2121  int rc;
2122 
2123 #ifdef HAVE_PACKET_EBPF
2124  if (ptv->ebpf_filter_fd != -1) {
2125  return SetEbpfFilter(ptv);
2126  }
2127 #endif
2128 
2129  if (!ptv->bpf_filter)
2130  return TM_ECODE_OK;
2131 
2132  SCLogInfo("%s: using BPF '%s'", ptv->iface, ptv->bpf_filter);
2133 
2134  char errbuf[PCAP_ERRBUF_SIZE];
2135  if (SCBPFCompile(ptv->snaplen, /* snaplen_arg */
2136  ptv->datalink, /* linktype_arg */
2137  &filter, /* program */
2138  ptv->bpf_filter, /* const char *buf */
2139  1, /* optimize */
2140  0, /* mask */
2141  errbuf, sizeof(errbuf)) == -1) {
2142  SCLogError("%s: failed to compile BPF \"%s\": %s", ptv->iface, ptv->bpf_filter, errbuf);
2143  return TM_ECODE_FAILED;
2144  }
2145 
2146  if (filter.bf_len > USHRT_MAX) {
2147  return TM_ECODE_FAILED;
2148  }
2149  fcode.len = (unsigned short)filter.bf_len;
2150  fcode.filter = (struct sock_filter*)filter.bf_insns;
2151 
2152  rc = setsockopt(ptv->socket, SOL_SOCKET, SO_ATTACH_FILTER, &fcode, sizeof(fcode));
2153 
2154  SCBPFFree(&filter);
2155  if(rc == -1) {
2156  SCLogError("%s: failed to attach filter: %s", ptv->iface, strerror(errno));
2157  return TM_ECODE_FAILED;
2158  }
2159 
2160  return TM_ECODE_OK;
2161 }
2162 
2163 #ifdef HAVE_PACKET_EBPF
2164 /**
2165  * Insert a half flow in the kernel bypass table
2166  *
2167  * \param mapfd file descriptor of the protocol bypass table
2168  * \param key data to use as key in the table
2169  * \return 0 in case of error, 1 if success
2170  */
2171 static int AFPInsertHalfFlow(int mapd, void *key, unsigned int nr_cpus)
2172 {
2173  BPF_DECLARE_PERCPU(struct pair, value, nr_cpus);
2174  unsigned int i;
2175 
2176  if (mapd == -1) {
2177  return 0;
2178  }
2179 
2180  /* We use a per CPU structure so we have to set an array of values as the kernel
2181  * is not duplicating the data on each CPU by itself. */
2182  for (i = 0; i < nr_cpus; i++) {
2183  BPF_PERCPU(value, i).packets = 0;
2184  BPF_PERCPU(value, i).bytes = 0;
2185  }
2186  if (bpf_map_update_elem(mapd, key, value, BPF_NOEXIST) != 0) {
2187  switch (errno) {
2188  /* no more place in the hash */
2189  case E2BIG:
2190  return 0;
2191  /* no more place in the hash for some hardware bypass */
2192  case EAGAIN:
2193  return 0;
2194  /* if we already have the key then bypass is a success */
2195  case EEXIST:
2196  return 1;
2197  /* Not supposed to be there so issue a error */
2198  default:
2199  SCLogError("Can't update eBPF map: %s (%d)", strerror(errno), errno);
2200  return 0;
2201  }
2202  }
2203  return 1;
2204 }
2205 
2206 static int AFPSetFlowStorage(Packet *p, int map_fd, void *key0, void* key1,
2207  int family)
2208 {
2211  if (fc) {
2212  if (fc->bypass_data != NULL) {
2213  // bypass already activated
2214  SCFree(key0);
2215  SCFree(key1);
2216  return 1;
2217  }
2218  EBPFBypassData *eb = SCCalloc(1, sizeof(EBPFBypassData));
2219  if (eb == NULL) {
2220  EBPFDeleteKey(map_fd, key0);
2221  EBPFDeleteKey(map_fd, key1);
2222  LiveDevAddBypassFail(dev, 1, family);
2223  SCFree(key0);
2224  SCFree(key1);
2225  return 0;
2226  }
2227  eb->key[0] = key0;
2228  eb->key[1] = key1;
2229  eb->mapfd = map_fd;
2230  eb->cpus_count = p->afp_v.nr_cpus;
2231  fc->BypassUpdate = EBPFBypassUpdate;
2232  fc->BypassFree = EBPFBypassFree;
2233  fc->bypass_data = eb;
2234  } else {
2235  EBPFDeleteKey(map_fd, key0);
2236  EBPFDeleteKey(map_fd, key1);
2237  LiveDevAddBypassFail(dev, 1, family);
2238  SCFree(key0);
2239  SCFree(key1);
2240  return 0;
2241  }
2242 
2243  LiveDevAddBypassStats(dev, 1, family);
2244  LiveDevAddBypassSuccess(dev, 1, family);
2245  return 1;
2246 }
2247 
2248 #define FlowKeyIpFill(k, p) \
2249  { \
2250  (k)->ip_proto = ((p)->proto == IPPROTO_TCP) ? 1 : 0; \
2251  (k)->vlan0 = (p)->vlan_id[0]; \
2252  (k)->vlan1 = (p)->vlan_id[1]; \
2253  }
2254 
2255 /**
2256  * Bypass function for AF_PACKET capture in eBPF mode
2257  *
2258  * This function creates two half flows in the map shared with the kernel
2259  * to trigger bypass.
2260  *
2261  * The implementation of bypass is done via an IPv4 and an IPv6 flow table.
2262  * This table contains the list of half flows to bypass. The in-kernel filter
2263  * will skip/drop the packet if they belong to a flow in one of the flows
2264  * table.
2265  *
2266  * \param p the packet belonging to the flow to bypass
2267  * \return 0 if unable to bypass, 1 if success
2268  */
2269 static int AFPBypassCallback(Packet *p)
2270 {
2271  SCLogDebug("Calling af_packet callback function");
2272  /* Only bypass TCP and UDP */
2273  if (!(PacketIsTCP(p) || PacketIsUDP(p))) {
2274  return 0;
2275  }
2276 
2277  /* If we don't have a flow attached to packet the eBPF map entries
2278  * will be destroyed at first flow bypass manager pass as we won't
2279  * find any associated entry */
2280  if (p->flow == NULL) {
2281  return 0;
2282  }
2283  /* Bypassing tunneled packets is currently not supported
2284  * because we can't discard the inner packet only due to
2285  * primitive parsing in eBPF */
2286  if (PacketIsTunnel(p)) {
2287  return 0;
2288  }
2290  if (PacketIsIPv4(p)) {
2291  SCLogDebug("add an IPv4");
2292  if (p->afp_v.v4_map_fd == -1) {
2293  return 0;
2294  }
2295  struct flowv4_keys *keys[2];
2296  keys[0] = SCCalloc(1, sizeof(struct flowv4_keys));
2297  if (keys[0] == NULL) {
2298  return 0;
2299  }
2300  keys[0]->src = htonl(GET_IPV4_SRC_ADDR_U32(p));
2301  keys[0]->dst = htonl(GET_IPV4_DST_ADDR_U32(p));
2302  FlowKeyIpFill(keys[0], p);
2303  keys[0]->port16[0] = p->sp;
2304  keys[0]->port16[1] = p->dp;
2305  if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[0],
2306  p->afp_v.nr_cpus) == 0) {
2307  LiveDevAddBypassFail(dev, 1, AF_INET);
2308  SCFree(keys[0]);
2309  return 0;
2310  }
2311  keys[1]= SCCalloc(1, sizeof(struct flowv4_keys));
2312  if (keys[1] == NULL) {
2313  EBPFDeleteKey(p->afp_v.v4_map_fd, keys[0]);
2314  LiveDevAddBypassFail(dev, 1, AF_INET);
2315  SCFree(keys[0]);
2316  return 0;
2317  }
2318  keys[1]->src = htonl(GET_IPV4_DST_ADDR_U32(p));
2319  keys[1]->dst = htonl(GET_IPV4_SRC_ADDR_U32(p));
2320  keys[1]->port16[0] = p->dp;
2321  keys[1]->port16[1] = p->sp;
2322  FlowKeyIpFill(keys[1], p);
2323  if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[1],
2324  p->afp_v.nr_cpus) == 0) {
2325  EBPFDeleteKey(p->afp_v.v4_map_fd, keys[0]);
2326  LiveDevAddBypassFail(dev, 1, AF_INET);
2327  SCFree(keys[0]);
2328  SCFree(keys[1]);
2329  return 0;
2330  }
2331  EBPFUpdateFlow(p->flow, p, NULL);
2332  return AFPSetFlowStorage(p, p->afp_v.v4_map_fd, keys[0], keys[1], AF_INET);
2333  }
2334  /* For IPv6 case we don't handle extended header in eBPF */
2335  if (PacketIsIPv6(p) && ((p->proto == IPPROTO_TCP) || (p->proto == IPPROTO_UDP))) {
2336  int i;
2337  if (p->afp_v.v6_map_fd == -1) {
2338  return 0;
2339  }
2340  SCLogDebug("add an IPv6");
2341  struct flowv6_keys *keys[2];
2342  keys[0] = SCCalloc(1, sizeof(struct flowv6_keys));
2343  if (keys[0] == NULL) {
2344  LiveDevAddBypassFail(dev, 1, AF_INET6);
2345  return 0;
2346  }
2347  for (i = 0; i < 4; i++) {
2348  keys[0]->src[i] = ntohl(GET_IPV6_SRC_ADDR(p)[i]);
2349  keys[0]->dst[i] = ntohl(GET_IPV6_DST_ADDR(p)[i]);
2350  }
2351  keys[0]->port16[0] = p->sp;
2352  keys[0]->port16[1] = p->dp;
2353  FlowKeyIpFill(keys[0], p);
2354  if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[0],
2355  p->afp_v.nr_cpus) == 0) {
2356  LiveDevAddBypassFail(dev, 1, AF_INET6);
2357  SCFree(keys[0]);
2358  return 0;
2359  }
2360  keys[1]= SCCalloc(1, sizeof(struct flowv6_keys));
2361  if (keys[1] == NULL) {
2362  EBPFDeleteKey(p->afp_v.v6_map_fd, keys[0]);
2363  LiveDevAddBypassFail(dev, 1, AF_INET6);
2364  SCFree(keys[0]);
2365  return 0;
2366  }
2367  for (i = 0; i < 4; i++) {
2368  keys[1]->src[i] = ntohl(GET_IPV6_DST_ADDR(p)[i]);
2369  keys[1]->dst[i] = ntohl(GET_IPV6_SRC_ADDR(p)[i]);
2370  }
2371  keys[1]->port16[0] = p->dp;
2372  keys[1]->port16[1] = p->sp;
2373  FlowKeyIpFill(keys[1], p);
2374  if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[1],
2375  p->afp_v.nr_cpus) == 0) {
2376  EBPFDeleteKey(p->afp_v.v6_map_fd, keys[0]);
2377  LiveDevAddBypassFail(dev, 1, AF_INET6);
2378  SCFree(keys[0]);
2379  SCFree(keys[1]);
2380  return 0;
2381  }
2382  if (p->flow)
2383  EBPFUpdateFlow(p->flow, p, NULL);
2384  return AFPSetFlowStorage(p, p->afp_v.v6_map_fd, keys[0], keys[1], AF_INET6);
2385  }
2386  return 0;
2387 }
2388 
2389 /**
2390  * Bypass function for AF_PACKET capture in XDP mode
2391  *
2392  * This function creates two half flows in the map shared with the kernel
2393  * to trigger bypass. This function is similar to AFPBypassCallback() but
2394  * the bytes order is changed for some data due to the way we get the data
2395  * in the XDP case.
2396  *
2397  * \param p the packet belonging to the flow to bypass
2398  * \return 0 if unable to bypass, 1 if success
2399  */
2400 static int AFPXDPBypassCallback(Packet *p)
2401 {
2402  SCLogDebug("Calling af_packet callback function");
2403  /* Only bypass TCP and UDP */
2404  if (!(PacketIsTCP(p) || PacketIsUDP(p))) {
2405  return 0;
2406  }
2407 
2408  /* If we don't have a flow attached to packet the eBPF map entries
2409  * will be destroyed at first flow bypass manager pass as we won't
2410  * find any associated entry */
2411  if (p->flow == NULL) {
2412  return 0;
2413  }
2414  /* Bypassing tunneled packets is currently not supported
2415  * because we can't discard the inner packet only due to
2416  * primitive parsing in eBPF */
2417  if (PacketIsTunnel(p)) {
2418  return 0;
2419  }
2421  if (PacketIsIPv4(p)) {
2422  struct flowv4_keys *keys[2];
2423  keys[0]= SCCalloc(1, sizeof(struct flowv4_keys));
2424  if (keys[0] == NULL) {
2425  LiveDevAddBypassFail(dev, 1, AF_INET);
2426  return 0;
2427  }
2428  if (p->afp_v.v4_map_fd == -1) {
2429  SCFree(keys[0]);
2430  return 0;
2431  }
2432  keys[0]->src = p->src.addr_data32[0];
2433  keys[0]->dst = p->dst.addr_data32[0];
2434  /* In the XDP filter we get port from parsing of packet and not from skb
2435  * (as in eBPF filter) so we need to pass from host to network order */
2436  keys[0]->port16[0] = htons(p->sp);
2437  keys[0]->port16[1] = htons(p->dp);
2438  FlowKeyIpFill(keys[0], p);
2439  if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[0],
2440  p->afp_v.nr_cpus) == 0) {
2441  LiveDevAddBypassFail(dev, 1, AF_INET);
2442  SCFree(keys[0]);
2443  return 0;
2444  }
2445  keys[1]= SCCalloc(1, sizeof(struct flowv4_keys));
2446  if (keys[1] == NULL) {
2447  EBPFDeleteKey(p->afp_v.v4_map_fd, keys[0]);
2448  LiveDevAddBypassFail(dev, 1, AF_INET);
2449  SCFree(keys[0]);
2450  return 0;
2451  }
2452  keys[1]->src = p->dst.addr_data32[0];
2453  keys[1]->dst = p->src.addr_data32[0];
2454  keys[1]->port16[0] = htons(p->dp);
2455  keys[1]->port16[1] = htons(p->sp);
2456  FlowKeyIpFill(keys[1], p);
2457  if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[1],
2458  p->afp_v.nr_cpus) == 0) {
2459  EBPFDeleteKey(p->afp_v.v4_map_fd, keys[0]);
2460  LiveDevAddBypassFail(dev, 1, AF_INET);
2461  SCFree(keys[0]);
2462  SCFree(keys[1]);
2463  return 0;
2464  }
2465  return AFPSetFlowStorage(p, p->afp_v.v4_map_fd, keys[0], keys[1], AF_INET);
2466  }
2467  /* For IPv6 case we don't handle extended header in eBPF */
2468  if (PacketIsIPv6(p) && ((p->proto == IPPROTO_TCP) || (p->proto == IPPROTO_UDP))) {
2469  SCLogDebug("add an IPv6");
2470  if (p->afp_v.v6_map_fd == -1) {
2471  return 0;
2472  }
2473  int i;
2474  struct flowv6_keys *keys[2];
2475  keys[0] = SCCalloc(1, sizeof(struct flowv6_keys));
2476  if (keys[0] == NULL) {
2477  return 0;
2478  }
2479 
2480  for (i = 0; i < 4; i++) {
2481  keys[0]->src[i] = GET_IPV6_SRC_ADDR(p)[i];
2482  keys[0]->dst[i] = GET_IPV6_DST_ADDR(p)[i];
2483  }
2484  keys[0]->port16[0] = htons(p->sp);
2485  keys[0]->port16[1] = htons(p->dp);
2486  FlowKeyIpFill(keys[0], p);
2487  if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[0],
2488  p->afp_v.nr_cpus) == 0) {
2489  LiveDevAddBypassFail(dev, 1, AF_INET6);
2490  SCFree(keys[0]);
2491  return 0;
2492  }
2493  keys[1]= SCCalloc(1, sizeof(struct flowv6_keys));
2494  if (keys[1] == NULL) {
2495  EBPFDeleteKey(p->afp_v.v6_map_fd, keys[0]);
2496  LiveDevAddBypassFail(dev, 1, AF_INET6);
2497  SCFree(keys[0]);
2498  return 0;
2499  }
2500  for (i = 0; i < 4; i++) {
2501  keys[1]->src[i] = GET_IPV6_DST_ADDR(p)[i];
2502  keys[1]->dst[i] = GET_IPV6_SRC_ADDR(p)[i];
2503  }
2504  keys[1]->port16[0] = htons(p->dp);
2505  keys[1]->port16[1] = htons(p->sp);
2506  FlowKeyIpFill(keys[1], p);
2507  if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[1],
2508  p->afp_v.nr_cpus) == 0) {
2509  EBPFDeleteKey(p->afp_v.v6_map_fd, keys[0]);
2510  LiveDevAddBypassFail(dev, 1, AF_INET6);
2511  SCFree(keys[0]);
2512  SCFree(keys[1]);
2513  return 0;
2514  }
2515  return AFPSetFlowStorage(p, p->afp_v.v6_map_fd, keys[0], keys[1], AF_INET6);
2516  }
2517  return 0;
2518 }
2519 
2520 bool g_flowv4_ok = true;
2521 bool g_flowv6_ok = true;
2522 
2523 #endif /* HAVE_PACKET_EBPF */
2524 
2525 /**
2526  * \brief Init function for ReceiveAFP.
2527  *
2528  * \param tv pointer to ThreadVars
2529  * \param initdata pointer to the interface passed from the user
2530  * \param data pointer gets populated with AFPThreadVars
2531  *
2532  * \todo Create a general AFP setup function.
2533  */
2534 TmEcode ReceiveAFPThreadInit(ThreadVars *tv, const void *initdata, void **data)
2535 {
2536  SCEnter();
2537  AFPIfaceConfig *afpconfig = (AFPIfaceConfig *)initdata;
2538 
2539  if (initdata == NULL) {
2540  SCLogError("initdata == NULL");
2542  }
2543 
2544  AFPThreadVars *ptv = SCCalloc(1, sizeof(AFPThreadVars));
2545  if (unlikely(ptv == NULL)) {
2546  afpconfig->DerefFunc(afpconfig);
2548  }
2549 
2550  ptv->tv = tv;
2551 
2552  strlcpy(ptv->iface, afpconfig->iface, AFP_IFACE_NAME_LENGTH);
2553  ptv->iface[AFP_IFACE_NAME_LENGTH - 1]= '\0';
2554 
2555  ptv->livedev = LiveGetDevice(ptv->iface);
2556  if (ptv->livedev == NULL) {
2557  SCLogError("Unable to find Live device");
2558  SCFree(ptv);
2560  }
2561 
2562  ptv->buffer_size = afpconfig->buffer_size;
2563  ptv->ring_size = afpconfig->ring_size;
2564  ptv->v2_block_size = afpconfig->v2_block_size;
2565  ptv->block_size = afpconfig->block_size;
2566  ptv->block_timeout = afpconfig->block_timeout;
2567 
2568  ptv->promisc = afpconfig->promisc;
2569  ptv->checksum_mode = afpconfig->checksum_mode;
2570  ptv->bpf_filter = NULL;
2571 
2572  ptv->threads = 1;
2573 #ifdef HAVE_PACKET_FANOUT
2575  ptv->cluster_id = 1;
2576  /* We only set cluster info if the number of reader threads is greater than 1 */
2577  if (afpconfig->threads > 1) {
2578  ptv->cluster_id = afpconfig->cluster_id;
2579  ptv->cluster_type = afpconfig->cluster_type;
2580  ptv->threads = afpconfig->threads;
2581  }
2582 #endif
2583  ptv->flags = afpconfig->flags;
2584 
2585  if (afpconfig->bpf_filter) {
2586  ptv->bpf_filter = afpconfig->bpf_filter;
2587  }
2588 #ifdef HAVE_PACKET_EBPF
2589  ptv->ebpf_lb_fd = afpconfig->ebpf_lb_fd;
2590  ptv->ebpf_filter_fd = afpconfig->ebpf_filter_fd;
2591  ptv->xdp_mode = afpconfig->xdp_mode;
2592  ptv->ebpf_t_config.cpus_count = UtilCpuGetNumProcessorsConfigured();
2593 
2594  if (ptv->flags & (AFP_BYPASS|AFP_XDPBYPASS)) {
2595  ptv->v4_map_fd = EBPFGetMapFDByName(ptv->iface, "flow_table_v4");
2596  if (ptv->v4_map_fd == -1) {
2597  if (g_flowv4_ok) {
2598  SCLogError("Can't find eBPF map fd for '%s'", "flow_table_v4");
2599  g_flowv4_ok = false;
2600  }
2601  }
2602  ptv->v6_map_fd = EBPFGetMapFDByName(ptv->iface, "flow_table_v6");
2603  if (ptv->v6_map_fd == -1) {
2604  if (g_flowv6_ok) {
2605  SCLogError("Can't find eBPF map fd for '%s'", "flow_table_v6");
2606  g_flowv6_ok = false;
2607  }
2608  }
2609  }
2610  ptv->ebpf_t_config = afpconfig->ebpf_t_config;
2611 #endif
2612 
2613 #ifdef PACKET_STATISTICS
2614  ptv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", &ptv->tv->stats);
2615  ptv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", &ptv->tv->stats);
2616  ptv->capture_errors = StatsRegisterCounter("capture.errors", &ptv->tv->stats);
2617 
2618  ptv->afpacket_spin = StatsRegisterAvgCounter("capture.afpacket.busy_loop_avg", &ptv->tv->stats);
2619 
2620  ptv->capture_afp_poll = StatsRegisterCounter("capture.afpacket.polls", &ptv->tv->stats);
2622  StatsRegisterCounter("capture.afpacket.poll_signal", &ptv->tv->stats);
2624  StatsRegisterCounter("capture.afpacket.poll_timeout", &ptv->tv->stats);
2625  ptv->capture_afp_poll_data =
2626  StatsRegisterCounter("capture.afpacket.poll_data", &ptv->tv->stats);
2627  ptv->capture_afp_poll_err =
2628  StatsRegisterCounter("capture.afpacket.poll_errors", &ptv->tv->stats);
2629  ptv->capture_afp_send_err =
2630  StatsRegisterCounter("capture.afpacket.send_errors", &ptv->tv->stats);
2631 #endif
2632 
2633  ptv->copy_mode = afpconfig->copy_mode;
2634  if (ptv->copy_mode != AFP_COPY_MODE_NONE) {
2635  strlcpy(ptv->out_iface, afpconfig->out_iface, AFP_IFACE_NAME_LENGTH);
2636  ptv->out_iface[AFP_IFACE_NAME_LENGTH - 1]= '\0';
2637  /* Warn about BPF filter consequence */
2638  if (ptv->bpf_filter) {
2639  SCLogWarning("Enabling a BPF filter in IPS mode result"
2640  " in dropping all non matching packets.");
2641  }
2642  }
2643 
2644 
2645  if (AFPPeersListAdd(ptv) == TM_ECODE_FAILED) {
2646  SCFree(ptv);
2647  afpconfig->DerefFunc(afpconfig);
2649  }
2650 
2651  *data = (void *)ptv;
2652 
2653  afpconfig->DerefFunc(afpconfig);
2654 
2655  /* If kernel is older than 3.0, VLAN is not stripped so we don't
2656  * get the info from packet extended header but we will use a standard
2657  * parsing of packet data (See Linux commit bcc6d47903612c3861201cc3a866fb604f26b8b2) */
2658  if (SCKernelVersionIsAtLeast(3, 0)) {
2659  ptv->flags |= AFP_VLAN_IN_HEADER;
2660  }
2661 
2663 }
2664 
2665 /**
2666  * \brief This function prints stats to the screen at exit.
2667  * \param tv pointer to ThreadVars
2668  * \param data pointer that gets cast into AFPThreadVars for ptv
2669  */
2670 void ReceiveAFPThreadExitStats(ThreadVars *tv, void *data)
2671 {
2672  SCEnter();
2673  AFPThreadVars *ptv = (AFPThreadVars *)data;
2674 
2675 #ifdef PACKET_STATISTICS
2676  AFPDumpCounters(ptv);
2677  SCLogPerf("%s: (%s) kernel: Packets %" PRIu64 ", dropped %" PRIu64 "", ptv->iface, tv->name,
2680 #endif
2681 }
2682 
2683 /**
2684  * \brief DeInit function closes af packet socket at exit.
2685  * \param tv pointer to ThreadVars
2686  * \param data pointer that gets cast into AFPThreadVars for ptv
2687  */
2688 TmEcode ReceiveAFPThreadDeinit(ThreadVars *tv, void *data)
2689 {
2690  AFPThreadVars *ptv = (AFPThreadVars *)data;
2691 
2692  AFPSwitchState(ptv, AFP_STATE_DOWN);
2693 
2694 #ifdef HAVE_PACKET_XDP
2695  if ((ptv->ebpf_t_config.flags & EBPF_XDP_CODE) &&
2696  (!(ptv->ebpf_t_config.flags & EBPF_PINNED_MAPS))) {
2697  EBPFSetupXDP(ptv->iface, -1, ptv->xdp_mode);
2698  }
2699 #endif
2700 
2701  ptv->bpf_filter = NULL;
2702  if ((ptv->flags & AFP_TPACKET_V3) && ptv->ring.v3) {
2703  SCFree(ptv->ring.v3);
2704  } else {
2705  if (ptv->ring.v2)
2706  SCFree(ptv->ring.v2);
2707  }
2708 
2709  SCFree(ptv);
2711 }
2712 
2713 /** \internal
2714  * \brief add a VLAN header into the raw data for inspection, logging
2715  * and sending out in IPS mode
2716  *
2717  * The kernel doesn't provide the first VLAN header the raw packet data,
2718  * but instead feeds it to us through meta data. For logging and IPS
2719  * we need to put it back into the raw data. Luckily there is some head
2720  * room in the original data so its enough to move the ethernet header
2721  * a bit to make space for the VLAN header.
2722  */
2723 static void UpdateRawDataForVLANHdr(Packet *p)
2724 {
2725  if (p->afp_v.vlan_tci != 0) {
2726  uint8_t *pstart = GET_PKT_DATA(p) - VLAN_HEADER_LEN;
2727  uint32_t plen = GET_PKT_LEN(p) + VLAN_HEADER_LEN;
2728  /* move ethernet addresses */
2729  memmove(pstart, GET_PKT_DATA(p), 2 * ETH_ALEN);
2730  /* write vlan info */
2731  *(uint16_t *)(pstart + 2 * ETH_ALEN) = htons(0x8100);
2732  *(uint16_t *)(pstart + 2 * ETH_ALEN + 2) = htons(p->afp_v.vlan_tci);
2733 
2734  /* update the packet raw data pointer to start at the new offset */
2735  (void)PacketSetData(p, pstart, plen);
2736  /* update ethernet header pointer to point to the new start of the data */
2737  p->l2.hdrs.ethh = (void *)pstart;
2738  }
2739 }
2740 
2741 /**
2742  * \brief This function passes off to link type decoders.
2743  *
2744  * DecodeAFP decodes packets from AF_PACKET and passes
2745  * them off to the proper link type decoder.
2746  *
2747  * \param t pointer to ThreadVars
2748  * \param p pointer to the current packet
2749  * \param data pointer that gets cast into AFPThreadVars for ptv
2750  */
2751 TmEcode DecodeAFP(ThreadVars *tv, Packet *p, void *data)
2752 {
2753  SCEnter();
2754 
2755  const bool afp_vlan_hdr = p->vlan_idx != 0;
2757 
2759 
2760  /* update counters */
2762 
2763  /* call the decoder */
2764  DecodeLinkLayer(tv, dtv, p->datalink, p, GET_PKT_DATA(p), GET_PKT_LEN(p));
2765  /* post-decoding put vlan hdr back into the raw data) */
2766  if (afp_vlan_hdr) {
2768  UpdateRawDataForVLANHdr(p);
2769  }
2770 
2772 
2774 }
2775 
2776 TmEcode DecodeAFPThreadInit(ThreadVars *tv, const void *initdata, void **data)
2777 {
2778  SCEnter();
2780  if (dtv == NULL)
2782 
2784 
2785  *data = (void *)dtv;
2786 
2788 }
2789 
2790 TmEcode DecodeAFPThreadDeinit(ThreadVars *tv, void *data)
2791 {
2792  if (data != NULL)
2793  DecodeThreadVarsFree(tv, data);
2795 }
2796 
2797 #endif /* HAVE_AF_PACKET */
2798 /* eof */
2799 /**
2800  * @}
2801  */
TmModule_::cap_flags
uint8_t cap_flags
Definition: tm-modules.h:77
AFPThreadVars_::capture_afp_send_err
StatsCounterId capture_afp_send_err
Definition: source-af-packet.c:298
PacketCheckAction
bool PacketCheckAction(const Packet *p, const uint8_t a)
Definition: packet.c:50
util-device-private.h
AFPIfaceConfig_::promisc
int promisc
Definition: source-af-packet.h:107
tm-threads.h
Packet_::proto
uint8_t proto
Definition: decode.h:537
AFPThreadVars_::promisc
int promisc
Definition: source-af-packet.c:326
AFPIfaceConfig_::checksum_mode
ChecksumValidationMode checksum_mode
Definition: source-af-packet.h:111
PACKET_FANOUT_FLAG_DEFRAG
#define PACKET_FANOUT_FLAG_DEFRAG
Definition: source-af-packet.h:40
len
uint8_t len
Definition: app-layer-dnp3.h:2
peerslist
AFPPeersList peerslist
Definition: source-af-packet.c:443
AFPIfaceConfig_::xdp_mode
uint8_t xdp_mode
Definition: source-af-packet.h:119
AFPV_CLEANUP
#define AFPV_CLEANUP(afpv)
Definition: source-af-packet.h:183
AFP_BYPASS
#define AFP_BYPASS
Definition: source-af-packet.h:65
AFPThreadVars_::pkts
uint64_t pkts
Definition: source-af-packet.c:269
TP_STATUS_VLAN_VALID
#define TP_STATUS_VLAN_VALID
Definition: source-af-packet.c:193
AFPThreadVars_::capture_afp_poll
StatsCounterId capture_afp_poll
Definition: source-af-packet.c:293
AFPThreadVars_::checksum_mode
ChecksumValidationMode checksum_mode
Definition: source-af-packet.c:286
ThreadVars_::name
char name[16]
Definition: threadvars.h:65
PacketFreeOrRelease
void PacketFreeOrRelease(Packet *p)
Return a packet to where it was allocated.
Definition: decode.c:282
StatsSyncCountersIfSignalled
void StatsSyncCountersIfSignalled(StatsThreadContext *stats)
Definition: counters.c:482
TAILQ_INIT
#define TAILQ_INIT(head)
Definition: queue.h:262
AFPPeer_::turn
int turn
Definition: source-af-packet.h:139
AFPThreadVars_::AFPRing::v2
union thdr ** v2
Definition: source-af-packet.c:264
AFP_SURI_FAILURE
@ AFP_SURI_FAILURE
Definition: source-af-packet.c:238
SC_ATOMIC_INIT
#define SC_ATOMIC_INIT(name)
wrapper for initializing an atomic variable.
Definition: util-atomic.h:314
AFP_COPY_MODE_NONE
#define AFP_COPY_MODE_NONE
Definition: source-af-packet.h:68
PKT_IS_PSEUDOPKT
#define PKT_IS_PSEUDOPKT(p)
return 1 if the packet is a pseudo packet
Definition: decode.h:1363
util-bpf.h
AFPThreadVars_::block_size
int block_size
Definition: source-af-packet.c:319
FlowBypassInfo_
Definition: flow.h:529
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
SC_ATOMIC_SET
#define SC_ATOMIC_SET(name, val)
Set the value for the atomic variable.
Definition: util-atomic.h:386
SCFlowGetStorageById
void * SCFlowGetStorageById(const Flow *f, SCFlowStorageId id)
Definition: flow-storage.c:40
AFPThreadVars_
Structure to hold thread specific variables.
Definition: source-af-packet.c:262
AFPPeer_::peer
struct AFPPeer_ * peer
Definition: source-af-packet.h:142
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:282
AFPThreadVars_::capture_afp_poll_signal
StatsCounterId capture_afp_poll_signal
Definition: source-af-packet.c:294
StatsRegisterCounter
StatsCounterId StatsRegisterCounter(const char *name, StatsThreadContext *stats)
Registers a normal, unqualified counter.
Definition: counters.c:1039
TmThreadsSetFlag
void TmThreadsSetFlag(ThreadVars *tv, uint32_t flag)
Set a thread flag.
Definition: tm-threads.c:103
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
AFPIfaceConfig_::ebpf_filter_fd
int ebpf_filter_fd
Definition: source-af-packet.h:116
Packet_::livedev_dst_id
uint16_t livedev_dst_id
Definition: decode.h:634
util-checksum.h
AFPThreadVars_::AFPTpacketReq
Definition: source-af-packet.c:338
AFPThreadVars_::block_timeout
int block_timeout
Definition: source-af-packet.c:320
action-globals.h
Packet_::flags
uint32_t flags
Definition: decode.h:561
threads.h
thdr::raw
void * raw
Definition: source-af-packet.c:250
Packet_::vlan_idx
uint8_t vlan_idx
Definition: decode.h:543
AFPThreadVars_::buffer_size
int buffer_size
Definition: source-af-packet.c:322
UtilCpuGetNumProcessorsConfigured
uint16_t UtilCpuGetNumProcessorsConfigured(void)
Get the number of cpus configured in the system.
Definition: util-cpu.c:59
AFP_SOCK_PROTECT
#define AFP_SOCK_PROTECT
Definition: source-af-packet.h:60
PACKET_FANOUT_HASH
#define PACKET_FANOUT_HASH
Definition: source-af-packet.h:32
LiveDevice_
Definition: util-device-private.h:32
AFPPeersListInit
TmEcode AFPPeersListInit(void)
Init the global list of AFPPeer.
Definition: source-af-packet.c:449
AFPThreadVars
struct AFPThreadVars_ AFPThreadVars
Structure to hold thread specific variables.
SC_ATOMIC_ADD
#define SC_ATOMIC_ADD(name, val)
add a value to our atomic variable
Definition: util-atomic.h:332
AFP_DOWN_COUNTER_INTERVAL
#define AFP_DOWN_COUNTER_INTERVAL
Definition: source-af-packet.c:172
AFPThreadVars_::ring_size
int ring_size
Definition: source-af-packet.c:317
LiveDevice_::id
uint16_t id
Definition: util-device-private.h:38
THV_RUNNING
#define THV_RUNNING
Definition: threadvars.h:55
packet-queue.h
AFPIfaceConfig_::ring_size
int ring_size
Definition: source-af-packet.h:96
TAILQ_FOREACH
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:252
LiveDeviceGetById
LiveDevice * LiveDeviceGetById(const int id)
Definition: util-device.c:460
TmModuleDecodeAFPRegister
void TmModuleDecodeAFPRegister(void)
Registration Function for DecodeAFP.
Definition: source-af-packet.c:603
AFP_RECOVERABLE_ERROR
@ AFP_RECOVERABLE_ERROR
Definition: source-af-packet.c:244
AFPIfaceConfig_::block_timeout
int block_timeout
Definition: source-af-packet.h:100
SCKernelVersionIsAtLeast
int SCKernelVersionIsAtLeast(int major, int minor)
Definition: util-host-info.c:37
AFPThreadVars_::ring
union AFPThreadVars_::AFPRing ring
tm-threads-common.h
SCMutexLock
#define SCMutexLock(mut)
Definition: threads-debug.h:117
MIN
#define MIN(x, y)
Definition: suricata-common.h:416
tm-modules.h
util-privs.h
AFP_PEERS_MAX_TRY
#define AFP_PEERS_MAX_TRY
CHECKSUM_VALIDATION_DISABLE
@ CHECKSUM_VALIDATION_DISABLE
Definition: decode.h:43
AFP_IFACE_NAME_LENGTH
#define AFP_IFACE_NAME_LENGTH
Definition: source-af-packet.c:166
AFPIfaceConfig_::out_iface
const char * out_iface
Definition: source-af-packet.h:120
AFPThreadVars_::AFPTpacketReq::v3
struct tpacket_req3 v3
Definition: source-af-packet.c:340
CHECKSUM_VALIDATION_KERNEL
@ CHECKSUM_VALIDATION_KERNEL
Definition: decode.h:47
TAILQ_INSERT_TAIL
#define TAILQ_INSERT_TAIL(head, elm, field)
Definition: queue.h:294
StatsCounterId
Definition: counters.h:30
AFP_XDPBYPASS
#define AFP_XDPBYPASS
Definition: source-af-packet.h:66
PacketDecodeFinalize
void PacketDecodeFinalize(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p)
Finalize decoding of a packet.
Definition: decode.c:235
AFPIfaceConfig_::flags
unsigned int flags
Definition: source-af-packet.h:109
p
Packet * p
Definition: fuzz_iprep.c:21
AFPThreadVars_::ring_buf
uint8_t * ring_buf
Definition: source-af-packet.c:349
AFP_STATE_UP
#define AFP_STATE_UP
Definition: source-af-packet.c:169
Packet_::BypassPacketsFlow
int(* BypassPacketsFlow)(struct Packet_ *)
Definition: decode.h:608
TM_ECODE_FAILED
@ TM_ECODE_FAILED
Definition: tm-threads-common.h:82
AFPPeersListClean
void AFPPeersListClean(void)
Clean the global peers list.
Definition: source-af-packet.c:585
GetFlowBypassInfoID
SCFlowStorageId GetFlowBypassInfoID(void)
Definition: flow-util.c:223
AFPGetLinkType
int AFPGetLinkType(const char *ifname)
Definition: source-af-packet.c:1534
StatsRegisterAvgCounter
StatsCounterAvgId StatsRegisterAvgCounter(const char *name, StatsThreadContext *stats)
Registers a counter, whose value holds the average of all the values assigned to it.
Definition: counters.c:1058
GET_IPV6_DST_ADDR
#define GET_IPV6_DST_ADDR(p)
Definition: decode.h:205
ChecksumAutoModeCheck
int ChecksumAutoModeCheck(uint64_t thread_count, uint64_t iface_count, uint64_t iface_fail)
Check if the number of invalid checksums indicate checksum offloading in place.
Definition: util-checksum.c:69
tmqh-packetpool.h
AFPPeer_::sock_protect
SCMutex sock_protect
Definition: source-af-packet.h:145
AFPPeersListCheck
TmEcode AFPPeersListCheck(void)
Check that all AFPPeer got a peer.
Definition: source-af-packet.c:466
TmModule_::PktAcqLoop
TmEcode(* PktAcqLoop)(ThreadVars *, void *, void *)
Definition: tm-modules.h:58
AFP_PEERS_WAIT
#define AFP_PEERS_WAIT
AFPThreadVars_::capture_afp_poll_err
StatsCounterId capture_afp_poll_err
Definition: source-af-packet.c:297
TM_ECODE_OK
@ TM_ECODE_OK
Definition: tm-threads-common.h:81
AFPPeersList
struct AFPPeersList_ AFPPeersList
AFP_BLOCK_SIZE_DEFAULT_ORDER
#define AFP_BLOCK_SIZE_DEFAULT_ORDER
Definition: source-af-packet.h:78
AFPIfaceConfig_::cluster_type
int cluster_type
Definition: source-af-packet.h:105
AFPIfaceConfig_::cluster_id
uint16_t cluster_id
Definition: source-af-packet.h:104
strlcpy
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: util-strlcpyu.c:43
TmModule_::ThreadDeinit
TmEcode(* ThreadDeinit)(ThreadVars *, void *)
Definition: tm-modules.h:53
Packet_::datalink
int datalink
Definition: decode.h:651
AFPThreadVars_::socket
int socket
Definition: source-af-packet.c:315
AFP_VLAN_IN_HEADER
#define AFP_VLAN_IN_HEADER
Definition: source-af-packet.h:63
AFPIfaceConfig_::block_size
int block_size
Definition: source-af-packet.h:98
PKT_SET_SRC
#define PKT_SET_SRC(p, src_val)
Definition: decode.h:1365
StatsCounterAvgAddI64
void StatsCounterAvgAddI64(StatsThreadContext *stats, StatsCounterAvgId id, int64_t x)
Definition: counters.c:239
CHECKSUM_VALIDATION_ENABLE
@ CHECKSUM_VALIDATION_ENABLE
Definition: decode.h:44
AFPPeersList_
Definition: source-af-packet.c:408
DecodeRegisterPerfCounters
void DecodeRegisterPerfCounters(DecodeThreadVars *dtv, ThreadVars *tv)
Definition: decode.c:634
CHECKSUM_VALIDATION_AUTO
@ CHECKSUM_VALIDATION_AUTO
Definition: decode.h:45
AFPThreadVars_::frame_offset
unsigned int frame_offset
Definition: source-af-packet.c:284
GetIfaceMaxPacketSize
int GetIfaceMaxPacketSize(LiveDevice *ld)
output max packet size for a link
Definition: util-ioctl.c:121
TAILQ_REMOVE
#define TAILQ_REMOVE(head, elm, field)
Definition: queue.h:312
decode.h
TMM_DECODEAFP
@ TMM_DECODEAFP
Definition: tm-threads-common.h:54
util-debug.h
PKT_SRC_WIRE
@ PKT_SRC_WIRE
Definition: decode.h:52
TAILQ_FIRST
#define TAILQ_FIRST(head)
Definition: queue.h:250
AFPIfaceConfig_::ebpf_lb_fd
int ebpf_lb_fd
Definition: source-af-packet.h:114
util-error.h
AFPThreadVars_::datalink
uint32_t datalink
Definition: source-af-packet.c:275
VLAN_HEADER_LEN
#define VLAN_HEADER_LEN
Definition: decode-vlan.h:46
TmModule_::PktAcqBreakLoop
TmEcode(* PktAcqBreakLoop)(ThreadVars *, void *)
Definition: tm-modules.h:61
FlowBypassInfo_::BypassUpdate
bool(* BypassUpdate)(Flow *f, void *data, time_t tsec)
Definition: flow.h:530
TP_STATUS_CSUMNOTREADY
#define TP_STATUS_CSUMNOTREADY
Definition: source-af-packet.c:190
AFP_MMAP_LOCKED
#define AFP_MMAP_LOCKED
Definition: source-af-packet.h:64
util-cpu.h
FlowBypassInfo_::BypassFree
void(* BypassFree)(void *data)
Definition: flow.h:531
Packet_::ts
SCTime_t ts
Definition: decode.h:569
AFPThreadVars_::capture_kernel_drops
StatsCounterId capture_kernel_drops
Definition: source-af-packet.c:290
BIT_U32
#define BIT_U32(n)
Definition: suricata-common.h:425
TmModuleReceiveAFPRegister
void TmModuleReceiveAFPRegister(void)
Registration Function for RecieveAFP.
Definition: source-af-packet.c:381
SCMutexUnlock
#define SCMutexUnlock(mut)
Definition: threads-debug.h:120
PACKET_FANOUT_LB
#define PACKET_FANOUT_LB
Definition: source-af-packet.h:33
SCTime_t::secs
uint64_t secs
Definition: util-time.h:41
LiveGetDevice
LiveDevice * LiveGetDevice(const char *name)
Get a pointer to the device at idx.
Definition: util-device.c:269
TP_STATUS_USER
#define TP_STATUS_USER
Definition: source-af-packet.c:181
SCEnter
#define SCEnter(...)
Definition: util-debug.h:284
GET_PKT_DATA
#define GET_PKT_DATA(p)
Definition: decode.h:210
AFPThreadVars_::threads
int threads
Definition: source-af-packet.c:336
util-ebpf.h
AFPThreadVars_::capture_afp_poll_timeout
StatsCounterId capture_afp_poll_timeout
Definition: source-af-packet.c:295
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:58
AFPPeer_::livedev_id
uint16_t livedev_id
Definition: source-af-packet.h:141
TmModule_::Func
TmEcode(* Func)(ThreadVars *, Packet *, void *)
Definition: tm-modules.h:56
Packet_::sp
Port sp
Definition: decode.h:522
StatsCounterIncr
void StatsCounterIncr(StatsThreadContext *stats, StatsCounterId id)
Increments the local counter.
Definition: counters.c:164
AFPThreadVars_::afpacket_spin
StatsCounterAvgId afpacket_spin
Definition: source-af-packet.c:292
AFPThreadVars_::ring_buflen
unsigned int ring_buflen
Definition: source-af-packet.c:348
LiveDevice_::dev
char * dev
Definition: util-device-private.h:33
FlowBypassInfo_::bypass_data
void * bypass_data
Definition: flow.h:532
AFPIfaceConfig_::DerefFunc
void(* DerefFunc)(void *)
Definition: source-af-packet.h:125
SCLogWarning
#define SCLogWarning(...)
Macro used to log WARNING messages.
Definition: util-debug.h:262
AFPThreadVars_::afp_state
uint8_t afp_state
Definition: source-af-packet.c:303
TP_STATUS_USER_BUSY
#define TP_STATUS_USER_BUSY
Definition: source-af-packet.c:227
AFPThreadVars_::iface
char iface[AFP_IFACE_NAME_LENGTH]
Definition: source-af-packet.c:343
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:325
AFP_STATE_DOWN
#define AFP_STATE_DOWN
Definition: source-af-packet.c:168
SC_ATOMIC_SUB
#define SC_ATOMIC_SUB(name, val)
sub a value from our atomic variable
Definition: util-atomic.h:341
SC_ATOMIC_DECLARE
#define SC_ATOMIC_DECLARE(type, name)
wrapper for declaring atomic variables.
Definition: util-atomic.h:280
PacketPoolWait
void PacketPoolWait(void)
Definition: tmqh-packetpool.c:71
AFPThreadVars_::AFPRing::v3
struct iovec * v3
Definition: source-af-packet.c:265
AFPThreadVars_::capture_afp_poll_data
StatsCounterId capture_afp_poll_data
Definition: source-af-packet.c:296
Packet_
Definition: decode.h:515
LiveDeviceGetId
uint16_t LiveDeviceGetId(const LiveDevice *dev)
Definition: util-device.c:452
TM_FLAG_DECODE_TM
#define TM_FLAG_DECODE_TM
Definition: tm-modules.h:33
tmm_modules
TmModule tmm_modules[TMM_SIZE]
Definition: tm-modules.c:29
AFPIfaceConfig_::threads
uint16_t threads
Definition: source-af-packet.h:92
GET_PKT_LEN
#define GET_PKT_LEN(p)
Definition: decode.h:209
AFPPeer_::flags
int flags
Definition: source-af-packet.h:137
AFP_KERNEL_DROP
@ AFP_KERNEL_DROP
Definition: source-af-packet.c:239
conf.h
TmSlot_
Definition: tm-threads.h:53
PKT_IGNORE_CHECKSUM
#define PKT_IGNORE_CHECKSUM
Definition: decode.h:1326
SCTime_t
Definition: util-time.h:40
TmEcode
TmEcode
Definition: tm-threads-common.h:80
max_pending_packets
uint32_t max_pending_packets
Definition: suricata.c:187
util-host-info.h
LiveDevice_::mtu
int mtu
Definition: util-device-private.h:35
AFP_READ_FAILURE
@ AFP_READ_FAILURE
Definition: source-af-packet.c:236
TmModule_::name
const char * name
Definition: tm-modules.h:48
AFPThreadVars_::pkttype_filter_mask
uint32_t pkttype_filter_mask
Definition: source-af-packet.c:329
AFP_ENABLE_HWTIMESTAMP
#define AFP_ENABLE_HWTIMESTAMP
Definition: source-af-packet.h:59
LiveDevAddBypassStats
void LiveDevAddBypassStats(LiveDevice *dev, uint64_t cnt, int family)
Definition: util-device.c:563
PacketL2::L2Hdrs::ethh
EthernetHdr * ethh
Definition: decode.h:432
runmodes.h
LiveDevAddBypassSuccess
void LiveDevAddBypassSuccess(LiveDevice *dev, uint64_t cnt, int family)
Definition: util-device.c:620
SCLogInfo
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:232
SCMutexInit
#define SCMutexInit(mut, mutattrs)
Definition: threads-debug.h:116
TM_FLAG_RECEIVE_TM
#define TM_FLAG_RECEIVE_TM
Definition: tm-modules.h:32
AFP_NEED_PEER
#define AFP_NEED_PEER
Definition: source-af-packet.h:58
AFPThreadVars_::down_count
int down_count
Definition: source-af-packet.c:331
dtv
DecodeThreadVars * dtv
Definition: fuzz_decodepcapfile.c:34
AFPThreadVars_::cluster_type
int cluster_type
Definition: source-af-packet.c:334
AFPThreadVars_::livedev
LiveDevice * livedev
Definition: source-af-packet.c:273
AFP_FATAL_ERROR
@ AFP_FATAL_ERROR
Definition: source-af-packet.c:243
default_packet_size
uint32_t default_packet_size
Definition: decode.c:77
tm-queuehandlers.h
Packet_::l2
struct PacketL2 l2
Definition: decode.h:613
AFPThreadVars_::cluster_id
uint16_t cluster_id
Definition: source-af-packet.c:333
AFPThreadVars_::slot
TmSlot * slot
Definition: source-af-packet.c:272
Packet_::ReleasePacket
void(* ReleasePacket)(struct Packet_ *)
Definition: decode.h:605
flow-storage.h
cnt
uint32_t cnt
Definition: tmqh-packetpool.h:7
TMM_RECEIVEAFP
@ TMM_RECEIVEAFP
Definition: tm-threads-common.h:52
Packet_::flow
struct Flow_ * flow
Definition: decode.h:563
AFPPeer_
Definition: source-af-packet.h:133
DecodeThreadVarsFree
void DecodeThreadVarsFree(ThreadVars *tv, DecodeThreadVars *dtv)
Definition: decode.c:848
ChecksumValidationMode
ChecksumValidationMode
Definition: decode.h:42
suricata-common.h
packet.h
Packet_::livedev_id
uint16_t livedev_id
Definition: decode.h:632
AFPThreadVars_::flags
unsigned int flags
Definition: source-af-packet.c:305
ACTION_DROP
#define ACTION_DROP
Definition: action-globals.h:30
SCLogPerf
#define SCLogPerf(...)
Definition: util-debug.h:241
StatsCounterGetLocalValue
int64_t StatsCounterGetLocalValue(StatsThreadContext *stats, StatsCounterId id)
Get the value of the local copy of the counter that hold this id.
Definition: counters.c:1376
version
uint8_t version
Definition: decode-gre.h:1
SCBPFFree
void SCBPFFree(struct bpf_program *program)
Definition: util-bpf.c:56
TmModule_::ThreadInit
TmEcode(* ThreadInit)(ThreadVars *, const void *, void **)
Definition: tm-modules.h:51
thdr::h2
struct tpacket2_hdr * h2
Definition: source-af-packet.c:248
AFP_TPACKET_V3
#define AFP_TPACKET_V3
Definition: source-af-packet.h:62
AFP_READ_OK
@ AFP_READ_OK
Definition: source-af-packet.c:235
LiveDevAddBypassFail
void LiveDevAddBypassFail(LiveDevice *dev, uint64_t cnt, int family)
Definition: util-device.c:601
FatalError
#define FatalError(...)
Definition: util-debug.h:517
AFPIfaceConfig_::v2_block_size
int v2_block_size
Definition: source-af-packet.h:102
thdr
Definition: source-af-packet.c:247
tv
ThreadVars * tv
Definition: fuzz_decodepcapfile.c:33
util-optimize.h
TmModule_::ThreadExitPrintStats
void(* ThreadExitPrintStats)(ThreadVars *, void *)
Definition: tm-modules.h:52
threadvars.h
util-validate.h
source-af-packet.h
SCMalloc
#define SCMalloc(sz)
Definition: util-mem.h:47
SCLogConfig
struct SCLogConfig_ SCLogConfig
Holds the config state used by the logging api.
FRAME_BUSY
#define FRAME_BUSY(tp_status)
Definition: source-af-packet.c:231
AFPThreadVars_::snaplen
int snaplen
Definition: source-af-packet.c:351
POLL_TIMEOUT
#define POLL_TIMEOUT
Definition: source-af-packet.c:174
SCLogError
#define SCLogError(...)
Macro used to log ERROR messages.
Definition: util-debug.h:274
GET_IPV6_SRC_ADDR
#define GET_IPV6_SRC_ADDR(p)
Definition: decode.h:204
StatsCounterAvgId
Definition: counters.h:34
SCFree
#define SCFree(p)
Definition: util-mem.h:61
AFP_COPY_MODE_IPS
#define AFP_COPY_MODE_IPS
Definition: source-af-packet.h:70
DecodeThreadVars_
Structure to hold thread specific data for all decode modules.
Definition: decode.h:994
AFPThreadVars_::v2_block_size
int v2_block_size
Definition: source-af-packet.c:318
AFPThreadVars_::tv
ThreadVars * tv
Definition: source-af-packet.c:271
AFPIfaceConfig_::buffer_size
int buffer_size
Definition: source-af-packet.h:94
AFPThreadVars_::req
union AFPThreadVars_::AFPTpacketReq req
util-ioctl.h
AFP_RECONNECT_TIMEOUT
#define AFP_RECONNECT_TIMEOUT
Definition: source-af-packet.c:171
DecodeThreadVarsAlloc
DecodeThreadVars * DecodeThreadVarsAlloc(ThreadVars *tv)
Alloc and setup DecodeThreadVars.
Definition: decode.c:830
TAILQ_HEAD
#define TAILQ_HEAD(name, type)
Definition: queue.h:230
PacketSetData
int PacketSetData(Packet *p, const uint8_t *pktdata, uint32_t pktlen)
Set data for Packet and set length when zero copy is used.
Definition: decode.c:868
AFP_TRUNC_PKT
@ AFP_TRUNC_PKT
Definition: decode-events.h:31
PacketL2::hdrs
union PacketL2::L2Hdrs hdrs
AFPThreadVars_::out_iface
char out_iface[AFP_IFACE_NAME_LENGTH]
Definition: source-af-packet.c:345
TP_STATUS_KERNEL
#define TP_STATUS_KERNEL
Definition: source-af-packet.c:178
AFPIfaceConfig_::iface
char iface[AFP_IFACE_NAME_LENGTH]
Definition: source-af-packet.h:90
SCBPFCompile
int SCBPFCompile(int snaplen_arg, int linktype_arg, struct bpf_program *program, const char *buf, int optimize, uint32_t mask, char *errbuf, size_t errbuf_len)
Definition: util-bpf.c:62
suricata.h
Packet_::dst
Address dst
Definition: decode.h:520
AFPThreadVars_::copy_mode
uint8_t copy_mode
Definition: source-af-packet.c:304
ENGINE_SET_INVALID_EVENT
#define ENGINE_SET_INVALID_EVENT(p, e)
Definition: decode.h:1238
DEFAULT_TPACKET_DEFRAG_SNAPLEN
#define DEFAULT_TPACKET_DEFRAG_SNAPLEN
Definition: source-af-packet.h:86
AFPIfaceConfig_::copy_mode
uint8_t copy_mode
Definition: source-af-packet.h:110
Packet_::vlan_id
uint16_t vlan_id[VLAN_MAX_LAYERS]
Definition: decode.h:542
TmSlot_::slot_next
struct TmSlot_ * slot_next
Definition: tm-threads.h:62
thdr::h3
struct tpacket3_hdr * h3
Definition: source-af-packet.c:249
AFPIfaceConfig_
Definition: source-af-packet.h:89
DecodeThreadVars_::counter_vlan
StatsCounterId counter_vlan
Definition: decode.h:1038
AFPIfaceConfig_::bpf_filter
const char * bpf_filter
Definition: source-af-packet.h:112
GET_IPV4_SRC_ADDR_U32
#define GET_IPV4_SRC_ADDR_U32(p)
Definition: decode.h:197
PACKET_FANOUT
#define PACKET_FANOUT
Definition: source-af-packet.h:30
AFPThreadVars_::AFPRing
Definition: source-af-packet.c:263
GET_IPV4_DST_ADDR_U32
#define GET_IPV4_DST_ADDR_U32(p)
Definition: decode.h:198
AFPPeer_::iface
char iface[AFP_IFACE_NAME_LENGTH]
Definition: source-af-packet.h:144
SC_ATOMIC_GET
#define SC_ATOMIC_GET(name)
Get the value from the atomic variable.
Definition: util-atomic.h:375
Packet_::dp
Port dp
Definition: decode.h:530
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
ThreadVars_::stats
StatsThreadContext stats
Definition: threadvars.h:121
SCReturnInt
#define SCReturnInt(x)
Definition: util-debug.h:288
SCMutexDestroy
#define SCMutexDestroy
Definition: threads-debug.h:121
AFPThreadVars_::AFPTpacketReq::v2
struct tpacket_req v2
Definition: source-af-packet.c:339
StatsCounterAddI64
void StatsCounterAddI64(StatsThreadContext *stats, StatsCounterId id, int64_t x)
Adds a value of type uint64_t to the local counter.
Definition: counters.c:145
AFPThreadVars_::capture_kernel_packets
StatsCounterId capture_kernel_packets
Definition: source-af-packet.c:289
AFPThreadVars_::bpf_filter
const char * bpf_filter
Definition: source-af-packet.c:324
AFPThreadVars_::capture_errors
StatsCounterId capture_errors
Definition: source-af-packet.c:291
AFPThreadVars_::mpeer
AFPPeer * mpeer
Definition: source-af-packet.c:308
PacketGetFromQueueOrAlloc
Packet * PacketGetFromQueueOrAlloc(void)
Get a packet. We try to get a packet from the packetpool first, but if that is empty we alloc a packe...
Definition: decode.c:299
SC_CAP_NET_RAW
#define SC_CAP_NET_RAW
Definition: util-privs.h:32
DEBUG_VALIDATE_BUG_ON
#define DEBUG_VALIDATE_BUG_ON(exp)
Definition: util-validate.h:109
Packet_::src
Address src
Definition: decode.h:519
TP_STATUS_LOSING
#define TP_STATUS_LOSING
Definition: source-af-packet.c:187
TmModule_::flags
uint8_t flags
Definition: tm-modules.h:80
AFPIsFanoutSupported
int AFPIsFanoutSupported(uint16_t cluster_id)
test if we can use FANOUT. Older kernels like those in CentOS6 have HAVE_PACKET_FANOUT defined but fa...
Definition: source-af-packet.c:1893
DecodeUpdatePacketCounters
void DecodeUpdatePacketCounters(ThreadVars *tv, const DecodeThreadVars *dtv, const Packet *p)
Definition: decode.c:798
AFPThreadVars_::send_errors_logged
int64_t send_errors_logged
Definition: source-af-packet.c:300
suricata_ctl_flags
volatile uint8_t suricata_ctl_flags
Definition: suricata.c:176
AFP_EMERGENCY_MODE
#define AFP_EMERGENCY_MODE
Definition: source-af-packet.h:61