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