suricata
flow-hash.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2026 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  * \file
20  *
21  * \author Victor Julien <victor@inliniac.net>
22  * \author Pablo Rincon Crespo <pablo.rincon.crespo@gmail.com>
23  *
24  * Flow Hashing functions.
25  */
26 
27 #include "suricata-common.h"
28 #include "threads.h"
29 
30 #include "decode.h"
31 #include "detect-engine-state.h"
32 
33 #include "flow.h"
34 #include "flow-hash.h"
35 #include "flow-util.h"
36 #include "flow-private.h"
37 #include "flow-manager.h"
38 #include "flow-storage.h"
39 #include "flow-timeout.h"
40 #include "flow-spare-pool.h"
41 #include "flow-callbacks.h"
42 #include "app-layer-parser.h"
43 
44 #include "util-time.h"
45 #include "util-debug.h"
46 #include "util-device-private.h"
47 
48 #include "util-hash-lookup3.h"
49 
50 #include "conf.h"
51 #include "output.h"
52 #include "output-flow.h"
53 #include "stream-tcp.h"
54 #include "util-exception-policy.h"
55 
57 
58 
59 FlowBucket *flow_hash;
60 SC_ATOMIC_EXTERN(unsigned int, flow_prune_idx);
61 SC_ATOMIC_EXTERN(unsigned int, flow_flags);
62 
63 static Flow *FlowGetUsedFlow(ThreadVars *tv, DecodeThreadVars *dtv, const SCTime_t ts);
64 
65 /** \brief compare two raw ipv6 addrs
66  *
67  * \note we don't care about the real ipv6 ip's, this is just
68  * to consistently fill the FlowHashKey6 struct, without all
69  * the SCNtohl calls.
70  *
71  * \warning do not use elsewhere unless you know what you're doing.
72  * detect-engine-address-ipv6.c's AddressIPv6GtU32 is likely
73  * what you are looking for.
74  */
75 static inline int FlowHashRawAddressIPv6GtU32(const uint32_t *a, const uint32_t *b)
76 {
77  for (uint8_t i = 0; i < 4; i++) {
78  if (a[i] > b[i])
79  return 1;
80  if (a[i] < b[i])
81  break;
82  }
83 
84  return 0;
85 }
86 
87 typedef struct FlowHashKey4_ {
88  union {
89  struct {
90  uint32_t addrs[2];
91  uint16_t ports[2];
92  uint8_t proto; /**< u8 so proto and recur and livedev add up to u32 */
93  uint8_t recur;
94  uint16_t livedev;
96  uint16_t pad[1];
97  };
98  const uint32_t u32[6];
99  };
101 
102 typedef struct FlowHashKey6_ {
103  union {
104  struct {
105  uint32_t src[4], dst[4];
106  uint16_t ports[2];
107  uint8_t proto; /**< u8 so proto and recur and livedev add up to u32 */
108  uint8_t recur;
109  uint16_t livedev;
111  uint16_t pad[1];
112  };
113  const uint32_t u32[12];
114  };
116 
118 {
119  uint32_t hash = 0;
120  if (PacketIsIPv4(p)) {
121  FlowHashKey4 fhk = {
122  .pad[0] = 0,
123  };
124 
125  int ai = (p->src.addr_data32[0] > p->dst.addr_data32[0]);
126  fhk.addrs[1 - ai] = p->src.addr_data32[0];
127  fhk.addrs[ai] = p->dst.addr_data32[0];
128 
129  fhk.ports[0] = 0xfedc;
130  fhk.ports[1] = 0xba98;
131 
132  fhk.proto = (uint8_t)p->proto;
133  /* g_recurlvl_mask sets the recursion_level to 0 if
134  * decoder.recursion-level.use-for-tracking is disabled.
135  */
136  fhk.recur = (uint8_t)p->recursion_level & g_recurlvl_mask;
137  /* g_vlan_mask sets the vlan_ids to 0 if vlan.use-for-tracking
138  * is disabled. */
139  fhk.vlan_id[0] = p->vlan_id[0] & g_vlan_mask;
140  fhk.vlan_id[1] = p->vlan_id[1] & g_vlan_mask;
141  fhk.vlan_id[2] = p->vlan_id[2] & g_vlan_mask;
142 
143  hash = hashword(fhk.u32, ARRAY_SIZE(fhk.u32), flow_config.hash_rand);
144  } else if (PacketIsIPv6(p)) {
145  FlowHashKey6 fhk = {
146  .pad[0] = 0,
147  };
148  if (FlowHashRawAddressIPv6GtU32(p->src.addr_data32, p->dst.addr_data32)) {
149  fhk.src[0] = p->src.addr_data32[0];
150  fhk.src[1] = p->src.addr_data32[1];
151  fhk.src[2] = p->src.addr_data32[2];
152  fhk.src[3] = p->src.addr_data32[3];
153  fhk.dst[0] = p->dst.addr_data32[0];
154  fhk.dst[1] = p->dst.addr_data32[1];
155  fhk.dst[2] = p->dst.addr_data32[2];
156  fhk.dst[3] = p->dst.addr_data32[3];
157  } else {
158  fhk.src[0] = p->dst.addr_data32[0];
159  fhk.src[1] = p->dst.addr_data32[1];
160  fhk.src[2] = p->dst.addr_data32[2];
161  fhk.src[3] = p->dst.addr_data32[3];
162  fhk.dst[0] = p->src.addr_data32[0];
163  fhk.dst[1] = p->src.addr_data32[1];
164  fhk.dst[2] = p->src.addr_data32[2];
165  fhk.dst[3] = p->src.addr_data32[3];
166  }
167 
168  fhk.ports[0] = 0xfedc;
169  fhk.ports[1] = 0xba98;
170  fhk.proto = (uint8_t)p->proto;
171  fhk.recur = (uint8_t)p->recursion_level & g_recurlvl_mask;
172  fhk.vlan_id[0] = p->vlan_id[0] & g_vlan_mask;
173  fhk.vlan_id[1] = p->vlan_id[1] & g_vlan_mask;
174  fhk.vlan_id[2] = p->vlan_id[2] & g_vlan_mask;
175 
176  hash = hashword(fhk.u32, ARRAY_SIZE(fhk.u32), flow_config.hash_rand);
177  }
178  return hash;
179 }
180 
181 /* calculate the hash key for this packet
182  *
183  * we're using:
184  * hash_rand -- set at init time
185  * source port
186  * destination port
187  * source address
188  * destination address
189  * recursion level -- for tunnels, make sure different tunnel layers can
190  * never get mixed up.
191  *
192  * For ICMP we only consider UNREACHABLE errors atm.
193  */
194 static inline uint32_t FlowGetHash(const Packet *p)
195 {
196  uint32_t hash = 0;
197 
198  if (PacketIsIPv4(p)) {
199  if (PacketIsTCP(p) || PacketIsUDP(p)) {
200  FlowHashKey4 fhk = { .pad[0] = 0 };
201 
202  int ai = (p->src.addr_data32[0] > p->dst.addr_data32[0]);
203  fhk.addrs[1-ai] = p->src.addr_data32[0];
204  fhk.addrs[ai] = p->dst.addr_data32[0];
205 
206  const int pi = (p->sp > p->dp);
207  fhk.ports[1-pi] = p->sp;
208  fhk.ports[pi] = p->dp;
209 
210  fhk.proto = p->proto;
211  /* g_recurlvl_mask sets the recursion_level to 0 if
212  * decoder.recursion-level.use-for-tracking is disabled.
213  */
215  /* g_livedev_mask sets the livedev ids to 0 if livedev.use-for-tracking
216  * is disabled. */
217  uint16_t devid = p->livedev_id;
218  fhk.livedev = devid & g_livedev_mask;
219  /* g_vlan_mask sets the vlan_ids to 0 if vlan.use-for-tracking
220  * is disabled. */
221  fhk.vlan_id[0] = p->vlan_id[0] & g_vlan_mask;
222  fhk.vlan_id[1] = p->vlan_id[1] & g_vlan_mask;
223  fhk.vlan_id[2] = p->vlan_id[2] & g_vlan_mask;
224 
225  hash = hashword(fhk.u32, ARRAY_SIZE(fhk.u32), flow_config.hash_rand);
226 
227  } else if (ICMPV4_DEST_UNREACH_IS_VALID(p)) {
228  uint32_t psrc = IPV4_GET_RAW_IPSRC_U32(PacketGetICMPv4EmbIPv4(p));
229  uint32_t pdst = IPV4_GET_RAW_IPDST_U32(PacketGetICMPv4EmbIPv4(p));
230  FlowHashKey4 fhk = { .pad[0] = 0 };
231 
232  const int ai = (psrc > pdst);
233  fhk.addrs[1-ai] = psrc;
234  fhk.addrs[ai] = pdst;
235 
236  const int pi = (p->l4.vars.icmpv4.emb_sport > p->l4.vars.icmpv4.emb_dport);
237  fhk.ports[1 - pi] = p->l4.vars.icmpv4.emb_sport;
238  fhk.ports[pi] = p->l4.vars.icmpv4.emb_dport;
239 
242  uint16_t devid = p->livedev_id;
243  fhk.livedev = devid & g_livedev_mask;
244  fhk.vlan_id[0] = p->vlan_id[0] & g_vlan_mask;
245  fhk.vlan_id[1] = p->vlan_id[1] & g_vlan_mask;
246  fhk.vlan_id[2] = p->vlan_id[2] & g_vlan_mask;
247 
248  hash = hashword(fhk.u32, ARRAY_SIZE(fhk.u32), flow_config.hash_rand);
249 
250  } else {
251  FlowHashKey4 fhk = { .pad[0] = 0 };
252  const int ai = (p->src.addr_data32[0] > p->dst.addr_data32[0]);
253  fhk.addrs[1-ai] = p->src.addr_data32[0];
254  fhk.addrs[ai] = p->dst.addr_data32[0];
255  fhk.ports[0] = 0xfeed;
256  fhk.ports[1] = 0xbeef;
257  fhk.proto = p->proto;
259  uint16_t devid = p->livedev_id;
260  fhk.livedev = devid & g_livedev_mask;
261  fhk.vlan_id[0] = p->vlan_id[0] & g_vlan_mask;
262  fhk.vlan_id[1] = p->vlan_id[1] & g_vlan_mask;
263  fhk.vlan_id[2] = p->vlan_id[2] & g_vlan_mask;
264 
265  hash = hashword(fhk.u32, ARRAY_SIZE(fhk.u32), flow_config.hash_rand);
266  }
267  } else if (PacketIsIPv6(p)) {
268  FlowHashKey6 fhk = { .pad[0] = 0 };
269  if (FlowHashRawAddressIPv6GtU32(p->src.addr_data32, p->dst.addr_data32)) {
270  fhk.src[0] = p->src.addr_data32[0];
271  fhk.src[1] = p->src.addr_data32[1];
272  fhk.src[2] = p->src.addr_data32[2];
273  fhk.src[3] = p->src.addr_data32[3];
274  fhk.dst[0] = p->dst.addr_data32[0];
275  fhk.dst[1] = p->dst.addr_data32[1];
276  fhk.dst[2] = p->dst.addr_data32[2];
277  fhk.dst[3] = p->dst.addr_data32[3];
278  } else {
279  fhk.src[0] = p->dst.addr_data32[0];
280  fhk.src[1] = p->dst.addr_data32[1];
281  fhk.src[2] = p->dst.addr_data32[2];
282  fhk.src[3] = p->dst.addr_data32[3];
283  fhk.dst[0] = p->src.addr_data32[0];
284  fhk.dst[1] = p->src.addr_data32[1];
285  fhk.dst[2] = p->src.addr_data32[2];
286  fhk.dst[3] = p->src.addr_data32[3];
287  }
288 
289  const int pi = (p->sp > p->dp);
290  fhk.ports[1-pi] = p->sp;
291  fhk.ports[pi] = p->dp;
292  fhk.proto = p->proto;
294  uint16_t devid = p->livedev_id;
295  fhk.livedev = devid & g_livedev_mask;
296  fhk.vlan_id[0] = p->vlan_id[0] & g_vlan_mask;
297  fhk.vlan_id[1] = p->vlan_id[1] & g_vlan_mask;
298  fhk.vlan_id[2] = p->vlan_id[2] & g_vlan_mask;
299 
300  hash = hashword(fhk.u32, ARRAY_SIZE(fhk.u32), flow_config.hash_rand);
301  }
302 
303  return hash;
304 }
305 
306 /**
307  * Basic hashing function for FlowKey
308  *
309  * \note Function only used for bypass and TCP or UDP flows
310  *
311  * \note this is only used at start to create Flow from pinned maps
312  * so fairness is not an issue
313  */
314 uint32_t FlowKeyGetHash(FlowKey *fk)
315 {
316  uint32_t hash = 0;
317 
318  if (fk->src.family == AF_INET) {
319  FlowHashKey4 fhk = {
320  .pad[0] = 0,
321  };
322  int ai = (fk->src.address.address_un_data32[0] > fk->dst.address.address_un_data32[0]);
323  fhk.addrs[1-ai] = fk->src.address.address_un_data32[0];
324  fhk.addrs[ai] = fk->dst.address.address_un_data32[0];
325 
326  const int pi = (fk->sp > fk->dp);
327  fhk.ports[1-pi] = fk->sp;
328  fhk.ports[pi] = fk->dp;
329 
330  fhk.proto = fk->proto;
332  fhk.livedev = fk->livedev_id & g_livedev_mask;
333  fhk.vlan_id[0] = fk->vlan_id[0] & g_vlan_mask;
334  fhk.vlan_id[1] = fk->vlan_id[1] & g_vlan_mask;
335  fhk.vlan_id[2] = fk->vlan_id[2] & g_vlan_mask;
336 
337  hash = hashword(fhk.u32, ARRAY_SIZE(fhk.u32), flow_config.hash_rand);
338  } else {
339  FlowHashKey6 fhk = {
340  .pad[0] = 0,
341  };
342  if (FlowHashRawAddressIPv6GtU32(fk->src.address.address_un_data32,
344  fhk.src[0] = fk->src.address.address_un_data32[0];
345  fhk.src[1] = fk->src.address.address_un_data32[1];
346  fhk.src[2] = fk->src.address.address_un_data32[2];
347  fhk.src[3] = fk->src.address.address_un_data32[3];
348  fhk.dst[0] = fk->dst.address.address_un_data32[0];
349  fhk.dst[1] = fk->dst.address.address_un_data32[1];
350  fhk.dst[2] = fk->dst.address.address_un_data32[2];
351  fhk.dst[3] = fk->dst.address.address_un_data32[3];
352  } else {
353  fhk.src[0] = fk->dst.address.address_un_data32[0];
354  fhk.src[1] = fk->dst.address.address_un_data32[1];
355  fhk.src[2] = fk->dst.address.address_un_data32[2];
356  fhk.src[3] = fk->dst.address.address_un_data32[3];
357  fhk.dst[0] = fk->src.address.address_un_data32[0];
358  fhk.dst[1] = fk->src.address.address_un_data32[1];
359  fhk.dst[2] = fk->src.address.address_un_data32[2];
360  fhk.dst[3] = fk->src.address.address_un_data32[3];
361  }
362 
363  const int pi = (fk->sp > fk->dp);
364  fhk.ports[1-pi] = fk->sp;
365  fhk.ports[pi] = fk->dp;
366  fhk.proto = fk->proto;
368  fhk.livedev = fk->livedev_id & g_livedev_mask;
369  fhk.vlan_id[0] = fk->vlan_id[0] & g_vlan_mask;
370  fhk.vlan_id[1] = fk->vlan_id[1] & g_vlan_mask;
371  fhk.vlan_id[2] = fk->vlan_id[2] & g_vlan_mask;
372 
373  hash = hashword(fhk.u32, ARRAY_SIZE(fhk.u32), flow_config.hash_rand);
374  }
375  return hash;
376 }
377 
378 static inline bool CmpAddrs(const uint32_t addr1[4], const uint32_t addr2[4])
379 {
380  return addr1[0] == addr2[0] && addr1[1] == addr2[1] &&
381  addr1[2] == addr2[2] && addr1[3] == addr2[3];
382 }
383 
384 static inline bool CmpAddrsAndPorts(const uint32_t src1[4],
385  const uint32_t dst1[4], Port src_port1, Port dst_port1,
386  const uint32_t src2[4], const uint32_t dst2[4], Port src_port2,
387  Port dst_port2)
388 {
389  /* Compare the source and destination addresses. If they are not equal,
390  * compare the first source address with the second destination address,
391  * and vice versa. Likewise for ports. */
392  return (CmpAddrs(src1, src2) && CmpAddrs(dst1, dst2) &&
393  src_port1 == src_port2 && dst_port1 == dst_port2) ||
394  (CmpAddrs(src1, dst2) && CmpAddrs(dst1, src2) &&
395  src_port1 == dst_port2 && dst_port1 == src_port2);
396 }
397 
398 static inline bool CmpVlanIds(
399  const uint16_t vlan_id1[VLAN_MAX_LAYERS], const uint16_t vlan_id2[VLAN_MAX_LAYERS])
400 {
401  return ((vlan_id1[0] ^ vlan_id2[0]) & g_vlan_mask) == 0 &&
402  ((vlan_id1[1] ^ vlan_id2[1]) & g_vlan_mask) == 0 &&
403  ((vlan_id1[2] ^ vlan_id2[2]) & g_vlan_mask) == 0;
404 }
405 
406 static inline bool CmpLiveDevIds(const uint16_t id1, const uint16_t id2)
407 {
408  return (((id1 ^ id2) & g_livedev_mask) == 0);
409 }
410 
411 /* Since two or more flows can have the same hash key, we need to compare
412  * the flow with the current packet or flow key. */
413 static inline bool CmpFlowPacket(const Flow *f, const Packet *p)
414 {
415  const uint32_t *f_src = f->src.address.address_un_data32;
416  const uint32_t *f_dst = f->dst.address.address_un_data32;
417  const uint32_t *p_src = p->src.address.address_un_data32;
418  const uint32_t *p_dst = p->dst.address.address_un_data32;
419  return CmpAddrsAndPorts(f_src, f_dst, f->sp, f->dp, p_src, p_dst, p->sp, p->dp) &&
420  f->proto == p->proto &&
422  CmpVlanIds(f->vlan_id, p->vlan_id) && CmpLiveDevIds(p->livedev_id, f->livedev_id);
423 }
424 
425 static inline bool CmpFlowKey(const Flow *f, const FlowKey *k)
426 {
427  const uint32_t *f_src = f->src.address.address_un_data32;
428  const uint32_t *f_dst = f->dst.address.address_un_data32;
429  const uint32_t *k_src = k->src.address.address_un_data32;
430  const uint32_t *k_dst = k->dst.address.address_un_data32;
431  return CmpAddrsAndPorts(f_src, f_dst, f->sp, f->dp, k_src, k_dst, k->sp, k->dp) &&
432  f->proto == k->proto &&
433  (f->recursion_level == k->recursion_level || g_recurlvl_mask == 0) &&
434  CmpVlanIds(f->vlan_id, k->vlan_id) && CmpLiveDevIds(f->livedev_id, k->livedev_id);
435 }
436 
437 static inline bool CmpAddrsAndICMPTypes(const uint32_t src1[4],
438  const uint32_t dst1[4], uint8_t icmp_s_type1, uint8_t icmp_d_type1,
439  const uint32_t src2[4], const uint32_t dst2[4], uint8_t icmp_s_type2,
440  uint8_t icmp_d_type2)
441 {
442  /* Compare the source and destination addresses. If they are not equal,
443  * compare the first source address with the second destination address,
444  * and vice versa. Likewise for icmp types. */
445  return (CmpAddrs(src1, src2) && CmpAddrs(dst1, dst2) &&
446  icmp_s_type1 == icmp_s_type2 && icmp_d_type1 == icmp_d_type2) ||
447  (CmpAddrs(src1, dst2) && CmpAddrs(dst1, src2) &&
448  icmp_s_type1 == icmp_d_type2 && icmp_d_type1 == icmp_s_type2);
449 }
450 
451 static inline bool CmpFlowICMPPacket(const Flow *f, const Packet *p)
452 {
453  const uint32_t *f_src = f->src.address.address_un_data32;
454  const uint32_t *f_dst = f->dst.address.address_un_data32;
455  const uint32_t *p_src = p->src.address.address_un_data32;
456  const uint32_t *p_dst = p->dst.address.address_un_data32;
457  return CmpAddrsAndICMPTypes(f_src, f_dst, f->icmp_s.type, f->icmp_d.type, p_src, p_dst,
458  p->icmp_s.type, p->icmp_d.type) &&
459  f->proto == p->proto &&
461  CmpVlanIds(f->vlan_id, p->vlan_id) && CmpLiveDevIds(p->livedev_id, f->livedev_id);
462 }
463 
464 /**
465  * \brief See if a ICMP packet belongs to a flow by comparing the embedded
466  * packet in the ICMP error packet to the flow.
467  *
468  * \param f flow
469  * \param p ICMP packet
470  *
471  * \retval 1 match
472  * \retval 0 no match
473  */
474 static inline int FlowCompareICMPv4(Flow *f, const Packet *p)
475 {
477  /* first check the direction of the flow, in other words, the client ->
478  * server direction as it's most likely the ICMP error will be a
479  * response to the clients traffic */
480  if ((f->src.addr_data32[0] == IPV4_GET_RAW_IPSRC_U32(PacketGetICMPv4EmbIPv4(p))) &&
481  (f->dst.addr_data32[0] == IPV4_GET_RAW_IPDST_U32(PacketGetICMPv4EmbIPv4(p))) &&
482  f->sp == p->l4.vars.icmpv4.emb_sport && f->dp == p->l4.vars.icmpv4.emb_dport &&
483  f->proto == ICMPV4_GET_EMB_PROTO(p) &&
485  CmpVlanIds(f->vlan_id, p->vlan_id) && CmpLiveDevIds(p->livedev_id, f->livedev_id)) {
486  return 1;
487 
488  /* check the less likely case where the ICMP error was a response to
489  * a packet from the server. */
490  } else if ((f->dst.addr_data32[0] == IPV4_GET_RAW_IPSRC_U32(PacketGetICMPv4EmbIPv4(p))) &&
491  (f->src.addr_data32[0] == IPV4_GET_RAW_IPDST_U32(PacketGetICMPv4EmbIPv4(p))) &&
492  f->dp == p->l4.vars.icmpv4.emb_sport && f->sp == p->l4.vars.icmpv4.emb_dport &&
493  f->proto == ICMPV4_GET_EMB_PROTO(p) &&
495  CmpVlanIds(f->vlan_id, p->vlan_id) &&
496  CmpLiveDevIds(p->livedev_id, f->livedev_id)) {
497  return 1;
498  }
499 
500  /* no match, fall through */
501  } else {
502  /* just treat ICMP as a normal proto for now */
503  return CmpFlowICMPPacket(f, p);
504  }
505 
506  return 0;
507 }
508 
509 /**
510  * \brief See if a IP-ESP packet belongs to a flow by comparing the SPI
511  *
512  * \param f flow
513  * \param p ESP packet
514  *
515  * \retval 1 match
516  * \retval 0 no match
517  */
518 static inline int FlowCompareESP(Flow *f, const Packet *p)
519 {
520  const uint32_t *f_src = f->src.address.address_un_data32;
521  const uint32_t *f_dst = f->dst.address.address_un_data32;
522  const uint32_t *p_src = p->src.address.address_un_data32;
523  const uint32_t *p_dst = p->dst.address.address_un_data32;
524 
525  return CmpAddrs(f_src, p_src) && CmpAddrs(f_dst, p_dst) && f->proto == p->proto &&
527  CmpVlanIds(f->vlan_id, p->vlan_id) && f->esp.spi == ESP_GET_SPI(PacketGetESP(p)) &&
528  CmpLiveDevIds(p->livedev_id, f->livedev_id);
529 }
530 
532 {
533  p->flags |= PKT_WANTS_FLOW;
534  p->flow_hash = FlowGetHash(p);
535 }
536 
537 static inline int FlowCompare(Flow *f, const Packet *p)
538 {
539  if (p->proto == IPPROTO_ICMP) {
540  return FlowCompareICMPv4(f, p);
541  } else if (PacketIsESP(p)) {
542  return FlowCompareESP(f, p);
543  }
544  return CmpFlowPacket(f, p);
545 }
546 
547 /**
548  * \brief Check if we should create a flow based on a packet
549  *
550  * We use this check to filter out flow creation based on:
551  * - ICMP error messages
552  * - TCP flags (emergency mode only)
553  *
554  * \param p packet
555  * \retval true
556  * \retval false
557  */
558 static inline bool FlowCreateCheck(const Packet *p, const bool emerg)
559 {
560  /* if we're in emergency mode, don't try to create a flow for a TCP
561  * that is not a TCP SYN packet. */
562  if (emerg) {
563  if (PacketIsTCP(p)) {
564  const TCPHdr *tcph = PacketGetTCP(p);
565  if (((tcph->th_flags & (TH_SYN | TH_ACK | TH_RST | TH_FIN)) == TH_SYN) ||
567  ;
568  } else {
569  return false;
570  }
571  }
572  }
573 
574  if (PacketIsICMPv4(p)) {
575  if (ICMPV4_IS_ERROR_MSG(p->icmp_s.type)) {
576  return false;
577  }
578  }
579 
580  return true;
581 }
582 
583 static inline void FlowUpdateCounter(ThreadVars *tv, DecodeThreadVars *dtv,
584  uint8_t proto)
585 {
586 #ifdef UNITTESTS
587  if (tv && dtv) {
588 #endif
591  switch (proto){
592  case IPPROTO_UDP:
594  break;
595  case IPPROTO_TCP:
597  break;
598  case IPPROTO_ICMP:
600  break;
601  case IPPROTO_ICMPV6:
603  break;
604  }
605 #ifdef UNITTESTS
606  }
607 #endif
608 }
609 
610 /** \internal
611  * \brief try to fetch a new set of flows from the master flow pool.
612  *
613  * If in emergency mode, do this only once a second at max to avoid trying
614  * to synchronise per packet in the worse case. */
615 static inline Flow *FlowSpareSync(ThreadVars *tv, FlowLookupStruct *fls,
616  const Packet *p, const bool emerg)
617 {
618  Flow *f = NULL;
619  bool spare_sync = false;
620  if (emerg) {
621  if ((uint32_t)SCTIME_SECS(p->ts) > fls->emerg_spare_sync_stamp) {
622  fls->spare_queue = FlowSpareGetFromPool(); /* local empty, (re)populate and try again */
623  spare_sync = true;
625  if (f == NULL) {
626  /* wait till next full sec before retrying */
627  fls->emerg_spare_sync_stamp = (uint32_t)SCTIME_SECS(p->ts);
628  }
629  }
630  } else {
631  fls->spare_queue = FlowSpareGetFromPool(); /* local empty, (re)populate and try again */
633  spare_sync = true;
634  }
635 #ifdef UNITTESTS
636  if (tv && fls->dtv) {
637 #endif
638  if (spare_sync) {
639  if (f != NULL) {
641  fls->spare_queue.len + 1);
642  if (fls->spare_queue.len < 99) {
643  /* When a new flow pool is fetched it has 100 flows in sync,
644  * so there should be 99 left if we're in full sync.
645  * If len is below 99, means the spare sync is incomplete */
646  /* Track these instances */
648  }
649  } else if (fls->spare_queue.len == 0) {
651  }
653  }
654 #ifdef UNITTESTS
655  }
656 #endif
657  return f;
658 }
659 
660 static void FlowExceptionPolicyStatsIncr(
661  ThreadVars *tv, FlowLookupStruct *fls, enum ExceptionPolicy policy)
662 {
663 #ifdef UNITTESTS
664  if (tv == NULL || fls->dtv == NULL) {
665  return;
666  }
667 #endif
669  if (likely(id.id > 0)) {
670  StatsCounterIncr(&tv->stats, id);
671  }
672 }
673 
674 static inline void NoFlowHandleIPS(ThreadVars *tv, FlowLookupStruct *fls, Packet *p)
675 {
677  FlowExceptionPolicyStatsIncr(tv, fls, flow_config.memcap_policy);
678 }
679 
680 /**
681  * \brief Get a new flow
682  *
683  * Get a new flow. We're checking memcap first and will try to make room
684  * if the memcap is reached.
685  *
686  * \param tv thread vars
687  * \param fls lookup support vars
688  *
689  * \retval f *LOCKED* flow on success, NULL on error or if we should not create
690  * a new flow.
691  */
692 static Flow *FlowGetNew(ThreadVars *tv, FlowLookupStruct *fls, Packet *p)
693 {
694  const bool emerg = ((SC_ATOMIC_GET(flow_flags) & FLOW_EMERGENCY) != 0);
695 #ifdef QA_SIMULATION
696  if (g_eps_flow_memcap != UINT64_MAX && g_eps_flow_memcap == PcapPacketCntGet(p)) {
697  NoFlowHandleIPS(tv, fls, p);
699  return NULL;
700  }
701 #endif
702  if (!FlowCreateCheck(p, emerg)) {
703  return NULL;
704  }
705 
706  /* get a flow from the spare queue */
708  if (f == NULL) {
709  f = FlowSpareSync(tv, fls, p, emerg);
710  }
711  if (f == NULL) {
712  /* If we reached the max memcap, we get a used flow */
713  if (!(FLOW_CHECK_MEMCAP(sizeof(Flow) + SCFlowStorageSize()))) {
714  /* declare state of emergency */
715  if (!(SC_ATOMIC_GET(flow_flags) & FLOW_EMERGENCY)) {
716  SC_ATOMIC_OR(flow_flags, FLOW_EMERGENCY);
719  }
720 
721  f = FlowGetUsedFlow(tv, fls->dtv, p->ts);
722  if (f == NULL) {
723  NoFlowHandleIPS(tv, fls, p);
724 #ifdef UNITTESTS
725  if (tv != NULL && fls->dtv != NULL) {
726 #endif
728 #ifdef UNITTESTS
729  }
730 #endif
731  return NULL;
732  }
733 #ifdef UNITTESTS
734  if (tv != NULL && fls->dtv != NULL) {
735 #endif
737 #ifdef UNITTESTS
738  }
739 #endif
740  /* flow is still locked from FlowGetUsedFlow() */
741  FlowUpdateCounter(tv, fls->dtv, p->proto);
742  return f;
743  }
744 
745  /* now see if we can alloc a new flow */
746  f = FlowAlloc();
747  if (f == NULL) {
748 #ifdef UNITTESTS
749  if (tv != NULL && fls->dtv != NULL) {
750 #endif
752 #ifdef UNITTESTS
753  }
754 #endif
755  NoFlowHandleIPS(tv, fls, p);
756  return NULL;
757  }
758 
759  /* flow is initialized but *unlocked* */
760  } else {
761  /* flow has been recycled before it went into the spare queue */
762 
763  /* flow is initialized (recycled) but *unlocked* */
764  }
765 
766  FLOWLOCK_WRLOCK(f);
767  FlowUpdateCounter(tv, fls->dtv, p->proto);
768  return f;
769 }
770 
771 static Flow *TcpReuseReplace(ThreadVars *tv, FlowLookupStruct *fls, FlowBucket *fb, Flow *old_f,
772  const uint32_t hash, Packet *p)
773 {
774 #ifdef UNITTESTS
775  if (tv != NULL && fls->dtv != NULL) {
776 #endif
778 #ifdef UNITTESTS
779  }
780 #endif
781  /* get some settings that we move over to the new flow */
782  FlowThreadId thread_id[2] = { old_f->thread_id[0], old_f->thread_id[1] };
784 
785  /* flow is unlocked by caller */
786 
787  /* Get a new flow. It will be either a locked flow or NULL */
788  Flow *f = FlowGetNew(tv, fls, p);
789  if (f == NULL) {
790  return NULL;
791  }
792 
793  /* put at the start of the list */
794  f->next = fb->head;
795  fb->head = f;
796 
797  /* initialize and return */
798  FlowInit(tv, f, p);
799  f->flow_hash = hash;
800  f->fb = fb;
802 
803  f->thread_id[0] = thread_id[0];
804  f->thread_id[1] = thread_id[1];
805 
807  return f;
808 }
809 
810 static inline bool FlowBelongsToUs(const ThreadVars *tv, const Flow *f)
811 {
812 #ifdef UNITTESTS
813  if (RunmodeIsUnittests()) {
814  return true;
815  }
816 #endif
817  return f->thread_id[0] == tv->id;
818 }
819 
820 static inline void MoveToWorkQueue(ThreadVars *tv, FlowLookupStruct *fls,
821  FlowBucket *fb, Flow *f, Flow *prev_f)
822 {
824 
825  /* remove from hash... */
826  if (prev_f) {
827  prev_f->next = f->next;
828  }
829  if (f == fb->head) {
830  fb->head = f->next;
831  }
832 
833  if (f->proto != IPPROTO_TCP || FlowBelongsToUs(tv, f)) { // TODO thread_id[] direction
834  f->fb = NULL;
835  f->next = NULL;
837  } else {
838  /* implied: TCP but our thread does not own it. So set it
839  * aside for the Flow Manager to pick it up. */
840  f->next = fb->evicted;
841  fb->evicted = f;
842  if (SC_ATOMIC_GET(f->fb->next_ts) != 0) {
843  SC_ATOMIC_SET(f->fb->next_ts, 0);
844  }
845  }
846 }
847 
848 static inline bool FlowIsTimedOut(
849  const FlowThreadId ftid, const Flow *f, const SCTime_t pktts, const bool emerg)
850 {
851  SCTime_t timesout_at;
852  if (emerg) {
854  timesout_at = SCTIME_ADD_SECS(f->lastts,
855  FlowGetFlowTimeoutDirect(flow_timeouts_emerg, f->flow_state, f->protomap));
856  } else {
857  timesout_at = SCTIME_ADD_SECS(f->lastts, f->timeout_policy);
858  }
859  /* if time is live, we just use the pktts */
860  if (TimeModeIsLive() || ftid == f->thread_id[0] || f->thread_id[0] == 0) {
861  if (SCTIME_CMP_LT(pktts, timesout_at)) {
862  return false;
863  }
864  } else {
865  SCTime_t checkts = TmThreadsGetThreadTime(f->thread_id[0]);
866  /* do the timeout check */
867  if (SCTIME_CMP_LT(checkts, timesout_at)) {
868  return false;
869  }
870  }
871  return true;
872 }
873 
874 static inline uint16_t GetTvId(const ThreadVars *tv)
875 {
876  uint16_t tv_id;
877 #ifdef UNITTESTS
878  if (RunmodeIsUnittests()) {
879  tv_id = 0;
880  } else {
881  tv_id = (uint16_t)tv->id;
882  }
883 #else
884  tv_id = (uint16_t)tv->id;
885 #endif
886  return tv_id;
887 }
888 
889 /** \brief Get Flow for packet
890  *
891  * Hash retrieval function for flows. Looks up the hash bucket containing the
892  * flow pointer. Then compares the packet with the found flow to see if it is
893  * the flow we need. If it isn't, walk the list until the right flow is found.
894  *
895  * If the flow is not found or the bucket was empty, a new flow is taken from
896  * the spare pool. The pool will alloc new flows as long as we stay within our
897  * memcap limit.
898  *
899  * The p->flow pointer is updated to point to the flow.
900  *
901  * \param tv thread vars
902  * \param dtv decode thread vars (for flow log api thread data)
903  *
904  * \retval f *LOCKED* flow or NULL
905  */
907 {
908  Flow *f = NULL;
909 
910  /* get our hash bucket and lock it */
911  const uint32_t hash = p->flow_hash;
912  FlowBucket *fb = &flow_hash[hash % flow_config.hash_size];
913  FBLOCK_LOCK(fb);
914 
915  SCLogDebug("fb %p fb->head %p", fb, fb->head);
916 
917  /* see if the bucket already has a flow */
918  if (fb->head == NULL) {
919  f = FlowGetNew(tv, fls, p);
920  if (f == NULL) {
921  FBLOCK_UNLOCK(fb);
922  return NULL;
923  }
924 
925  /* flow is locked */
926  fb->head = f;
927 
928  /* got one, now lock, initialize and return */
929  FlowInit(tv, f, p);
930  f->flow_hash = hash;
931  f->fb = fb;
933 
934  FlowReference(dest, f);
935 
936  FBLOCK_UNLOCK(fb);
937  return f;
938  }
939 
940  const uint16_t tv_id = GetTvId(tv);
941  const bool emerg = (SC_ATOMIC_GET(flow_flags) & FLOW_EMERGENCY) != 0;
942  const uint32_t fb_nextts = !emerg ? SC_ATOMIC_GET(fb->next_ts) : 0;
943  const bool timeout_check = (fb_nextts <= (uint32_t)SCTIME_SECS(p->ts));
944  /* ok, we have a flow in the bucket. Let's find out if it is our flow */
945  Flow *prev_f = NULL; /* previous flow */
946  f = fb->head;
947  do {
948  Flow *next_f = NULL;
949  const bool our_flow = FlowCompare(f, p) != 0;
950  if (our_flow || timeout_check) {
951  FLOWLOCK_WRLOCK(f);
952  const bool timedout = (timeout_check && FlowIsTimedOut(tv_id, f, p->ts, emerg));
953  if (timedout) {
954  next_f = f->next;
955  MoveToWorkQueue(tv, fls, fb, f, prev_f);
956  FLOWLOCK_UNLOCK(f);
957  goto flow_removed;
958  } else if (our_flow) {
959  /* found a matching flow that is not timed out */
961  Flow *new_f = TcpReuseReplace(tv, fls, fb, f, hash, p);
962  if (prev_f == NULL) /* if we have no prev it means new_f is now our prev */
963  prev_f = new_f;
964  MoveToWorkQueue(tv, fls, fb, f, prev_f); /* evict old flow */
965  FLOWLOCK_UNLOCK(f); /* unlock old replaced flow */
966 
967  if (new_f == NULL) {
968  FBLOCK_UNLOCK(fb);
969  return NULL;
970  }
971  f = new_f;
972  }
973  FlowReference(dest, f);
974  FBLOCK_UNLOCK(fb);
975  return f; /* return w/o releasing flow lock */
976  } else {
977  FLOWLOCK_UNLOCK(f);
978  }
979  }
980  /* unless we removed 'f', prev_f needs to point to
981  * current 'f' when adding a new flow below. */
982  prev_f = f;
983  next_f = f->next;
984 
985 flow_removed:
986  if (next_f == NULL) {
987  f = FlowGetNew(tv, fls, p);
988  if (f == NULL) {
989  FBLOCK_UNLOCK(fb);
990  return NULL;
991  }
992 
993  /* flow is locked */
994 
995  f->next = fb->head;
996  fb->head = f;
997 
998  /* initialize and return */
999  FlowInit(tv, f, p);
1000  f->flow_hash = hash;
1001  f->fb = fb;
1003  FlowReference(dest, f);
1004  FBLOCK_UNLOCK(fb);
1005  return f;
1006  }
1007  f = next_f;
1008  } while (f != NULL);
1009 
1010  /* should be unreachable */
1011  BUG_ON(1);
1012  return NULL;
1013 }
1014 
1015 /** \internal
1016  * \retval true if flow matches key
1017  * \retval false if flow does not match key, or unsupported protocol
1018  * \note only supports TCP & UDP
1019  */
1020 static inline bool FlowCompareKey(Flow *f, FlowKey *key)
1021 {
1022  if ((f->proto != IPPROTO_TCP) && (f->proto != IPPROTO_UDP))
1023  return false;
1024  return CmpFlowKey(f, key);
1025 }
1026 
1027 /** \brief Look for existing Flow using a flow id value
1028  *
1029  * Hash retrieval function for flows. Looks up the hash bucket containing the
1030  * flow pointer. Then compares the flow_id with the found flow's flow_id to see
1031  * if it is the flow we need.
1032  *
1033  * \param flow_id Flow ID of the flow to look for
1034  * \retval f *LOCKED* flow or NULL
1035  */
1037 {
1038  uint32_t hash = flow_id & 0x0000FFFF;
1039  FlowBucket *fb = &flow_hash[hash % flow_config.hash_size];
1040  FBLOCK_LOCK(fb);
1041  SCLogDebug("fb %p fb->head %p", fb, fb->head);
1042 
1043  for (Flow *f = fb->head; f != NULL; f = f->next) {
1044  if (FlowGetId(f) == flow_id) {
1045  /* found our flow, lock & return */
1046  FLOWLOCK_WRLOCK(f);
1047  FBLOCK_UNLOCK(fb);
1048  return f;
1049  }
1050  }
1051  FBLOCK_UNLOCK(fb);
1052  return NULL;
1053 }
1054 
1055 /** \brief Look for existing Flow using a FlowKey
1056  *
1057  * Hash retrieval function for flows. Looks up the hash bucket containing the
1058  * flow pointer. Then compares the key with the found flow to see if it is
1059  * the flow we need. If it isn't, walk the list until the right flow is found.
1060  *
1061  * \param key Pointer to FlowKey build using flow to look for
1062  * \param hash Value of the flow hash
1063  * \retval f *LOCKED* flow or NULL
1064  */
1065 static Flow *FlowGetExistingFlowFromHash(FlowKey *key, const uint32_t hash)
1066 {
1067  /* get our hash bucket and lock it */
1068  FlowBucket *fb = &flow_hash[hash % flow_config.hash_size];
1069  FBLOCK_LOCK(fb);
1070  SCLogDebug("fb %p fb->head %p", fb, fb->head);
1071 
1072  for (Flow *f = fb->head; f != NULL; f = f->next) {
1073  /* see if this is the flow we are looking for */
1074  if (FlowCompareKey(f, key)) {
1075  /* found our flow, lock & return */
1076  FLOWLOCK_WRLOCK(f);
1077  FBLOCK_UNLOCK(fb);
1078  return f;
1079  }
1080  }
1081 
1082  FBLOCK_UNLOCK(fb);
1083  return NULL;
1084 }
1085 
1086 /** \brief Get or create a Flow using a FlowKey
1087  *
1088  * Hash retrieval function for flows. Looks up the hash bucket containing the
1089  * flow pointer. Then compares the packet with the found flow to see if it is
1090  * the flow we need. If it isn't, walk the list until the right flow is found.
1091  * Return a new Flow if ever no Flow was found.
1092  *
1093  *
1094  * \param key Pointer to FlowKey build using flow to look for
1095  * \param ttime time to use for flow creation
1096  * \param hash Value of the flow hash
1097  * \retval f *LOCKED* flow or NULL
1098  */
1099 
1100 Flow *FlowGetFromFlowKey(FlowKey *key, struct timespec *ttime, const uint32_t hash)
1101 {
1102  Flow *f = FlowGetExistingFlowFromHash(key, hash);
1103 
1104  if (f != NULL) {
1105  return f;
1106  }
1107  /* TODO use spare pool */
1108  /* now see if we can alloc a new flow */
1109  f = FlowAlloc();
1110  if (f == NULL) {
1111  SCLogDebug("Can't get a spare flow at start");
1112  return NULL;
1113  }
1114  f->proto = key->proto;
1115  memcpy(&f->vlan_id[0], &key->vlan_id[0], sizeof(f->vlan_id));
1116  ;
1117  f->src.addr_data32[0] = key->src.addr_data32[0];
1118  f->src.addr_data32[1] = key->src.addr_data32[1];
1119  f->src.addr_data32[2] = key->src.addr_data32[2];
1120  f->src.addr_data32[3] = key->src.addr_data32[3];
1121  f->dst.addr_data32[0] = key->dst.addr_data32[0];
1122  f->dst.addr_data32[1] = key->dst.addr_data32[1];
1123  f->dst.addr_data32[2] = key->dst.addr_data32[2];
1124  f->dst.addr_data32[3] = key->dst.addr_data32[3];
1125  f->sp = key->sp;
1126  f->dp = key->dp;
1127  f->recursion_level = 0;
1128  // f->livedev is set by caller EBPFCreateFlowForKey
1129  f->flow_hash = hash;
1130  if (key->src.family == AF_INET) {
1131  f->flags |= FLOW_IPV4;
1132  } else if (key->src.family == AF_INET6) {
1133  f->flags |= FLOW_IPV6;
1134  }
1135 
1137  /* set timestamp to now */
1138  f->startts = SCTIME_FROM_TIMESPEC(ttime);
1139  f->lastts = f->startts;
1140 
1141  FlowBucket *fb = &flow_hash[hash % flow_config.hash_size];
1142  FBLOCK_LOCK(fb);
1143  f->fb = fb;
1144  f->next = fb->head;
1145  fb->head = f;
1146  FLOWLOCK_WRLOCK(f);
1147  FBLOCK_UNLOCK(fb);
1148  return f;
1149 }
1150 
1151 #define FLOW_GET_NEW_TRIES 5
1153 /* inline locking wrappers to make profiling easier */
1154 
1155 static inline int GetUsedTryLockBucket(FlowBucket *fb)
1156 {
1157  int r = FBLOCK_TRYLOCK(fb);
1158  return r;
1159 }
1160 static inline int GetUsedTryLockFlow(Flow *f)
1161 {
1162  int r = FLOWLOCK_TRYWRLOCK(f);
1163  return r;
1164 }
1165 static inline uint32_t GetUsedAtomicUpdate(const uint32_t val)
1166 {
1167  uint32_t r = SC_ATOMIC_ADD(flow_prune_idx, val);
1168  return r;
1169 }
1170 
1171 /** \internal
1172  * \brief check if flow has just seen an update.
1173  */
1174 static inline bool StillAlive(const Flow *f, const SCTime_t ts)
1175 {
1176  switch (f->flow_state) {
1177  case FLOW_STATE_NEW:
1178  if (SCTIME_SECS(ts) - SCTIME_SECS(f->lastts) <= 1) {
1179  return true;
1180  }
1181  break;
1183  if (SCTIME_SECS(ts) - SCTIME_SECS(f->lastts) <= 5) {
1184  return true;
1185  }
1186  break;
1187  case FLOW_STATE_CLOSED:
1188  if (SCTIME_SECS(ts) - SCTIME_SECS(f->lastts) <= 3) {
1189  return true;
1190  }
1191  break;
1192  default:
1193  if (SCTIME_SECS(ts) - SCTIME_SECS(f->lastts) < 30) {
1194  return true;
1195  }
1196  break;
1197  }
1198  return false;
1199 }
1200 
1201 #ifdef UNITTESTS
1202 #define STATSADDUI64(cnt, value) \
1203  if (tv && dtv) { \
1204  StatsCounterAddI64(&tv->stats, dtv->cnt, (value)); \
1205  }
1206 #else
1207 #define STATSADDUI64(cnt, value) StatsCounterAddI64(&tv->stats, dtv->cnt, (value));
1208 #endif
1209 
1210 /** \internal
1211  * \brief Get a flow from the hash directly.
1212  *
1213  * Called in conditions where the spare queue is empty and memcap is reached.
1214  *
1215  * Walks the hash until a flow can be freed. Timeouts are disregarded.
1216  * "flow_prune_idx" atomic int makes sure we don't start at the
1217  * top each time since that would clear the top of the hash leading to longer
1218  * and longer search times under high pressure (observed).
1219  *
1220  * \param tv thread vars
1221  * \param dtv decode thread vars (for flow log api thread data)
1222  *
1223  * \retval f flow or NULL
1224  */
1225 static Flow *FlowGetUsedFlow(ThreadVars *tv, DecodeThreadVars *dtv, const SCTime_t ts)
1226 {
1227  uint32_t idx = GetUsedAtomicUpdate(FLOW_GET_NEW_TRIES) % flow_config.hash_size;
1228  uint32_t tried = 0;
1229 
1230  while (1) {
1231  if (tried++ > FLOW_GET_NEW_TRIES) {
1232  STATSADDUI64(counter_flow_get_used_eval, tried);
1233  break;
1234  }
1235  if (++idx >= flow_config.hash_size)
1236  idx = 0;
1237 
1238  FlowBucket *fb = &flow_hash[idx];
1239 
1240  if (SC_ATOMIC_GET(fb->next_ts) == UINT_MAX)
1241  continue;
1242 
1243  if (GetUsedTryLockBucket(fb) != 0) {
1244  STATSADDUI64(counter_flow_get_used_eval_busy, 1);
1245  continue;
1246  }
1247 
1248  Flow *f = fb->head;
1249  if (f == NULL) {
1250  FBLOCK_UNLOCK(fb);
1251  continue;
1252  }
1253 
1254  if (GetUsedTryLockFlow(f) != 0) {
1255  STATSADDUI64(counter_flow_get_used_eval_busy, 1);
1256  FBLOCK_UNLOCK(fb);
1257  continue;
1258  }
1259 
1260  if (StillAlive(f, ts)) {
1261  STATSADDUI64(counter_flow_get_used_eval_reject, 1);
1262  FBLOCK_UNLOCK(fb);
1263  FLOWLOCK_UNLOCK(f);
1264  continue;
1265  }
1266 
1267  /* remove from the hash */
1268  fb->head = f->next;
1269  f->next = NULL;
1270  f->fb = NULL;
1271  FBLOCK_UNLOCK(fb);
1272 
1273  /* rest of the flags is updated on-demand in output */
1275  if (SC_ATOMIC_GET(flow_flags) & FLOW_EMERGENCY)
1277 
1278  /* invoke flow log api */
1279 #ifdef UNITTESTS
1280  if (dtv) {
1281 #endif
1284  }
1285 #ifdef UNITTESTS
1286  }
1287 #endif
1288 
1290  FlowClearMemory(f, f->protomap);
1291 
1292  /* leave locked */
1293 
1294  STATSADDUI64(counter_flow_get_used_eval, tried);
1295  return f;
1296  }
1297 
1298  STATSADDUI64(counter_flow_get_used_failed, 1);
1299  return NULL;
1300 }
FlowHashKey4_::ports
uint16_t ports[2]
Definition: flow-hash.c:91
ESP_GET_SPI
#define ESP_GET_SPI(esph)
Get the spi field off a packet.
Definition: decode-esp.h:29
FlowLookupStruct_::work_queue
FlowQueuePrivate work_queue
Definition: flow.h:546
util-device-private.h
DecodeThreadVars_::counter_flow_icmp6
StatsCounterId counter_flow_icmp6
Definition: decode.h:1071
OutputFlowLog
TmEcode OutputFlowLog(ThreadVars *tv, void *thread_data, Flow *f)
Run flow logger(s)
Definition: output-flow.c:87
Packet_::proto
uint8_t proto
Definition: decode.h:536
ts
uint64_t ts
Definition: source-erf-file.c:55
ExceptionPolicyApply
void ExceptionPolicyApply(Packet *p, enum ExceptionPolicy policy, enum PacketDropReason drop_reason)
Definition: util-exception-policy.c:138
g_livedev_mask
uint16_t g_livedev_mask
Definition: suricata.c:210
ICMPV4_GET_EMB_PROTO
#define ICMPV4_GET_EMB_PROTO(p)
Definition: decode-icmpv4.h:243
Flow_::recursion_level
uint8_t recursion_level
Definition: flow.h:377
IPV4_GET_RAW_IPDST_U32
#define IPV4_GET_RAW_IPDST_U32(ip4h)
Definition: decode-ipv4.h:110
Flow_::flags
uint64_t flags
Definition: flow.h:403
hashword
uint32_t hashword(const uint32_t *k, size_t length, uint32_t initval)
Definition: util-hash-lookup3.c:172
FLOW_STATE_ESTABLISHED
@ FLOW_STATE_ESTABLISHED
Definition: flow.h:505
flow-util.h
FBLOCK_LOCK
#define FBLOCK_LOCK(fb)
Definition: flow-hash.h:73
FlowLookupStruct_::dtv
DecodeThreadVars * dtv
Definition: flow.h:545
Flow_::startts
SCTime_t startts
Definition: flow.h:493
TcpSessionPacketSsnReuse
bool TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
Definition: stream-tcp.c:6098
stream-tcp.h
Packet_::icmp_d
struct Packet_::@34::@40 icmp_d
FlowKey_::src
Address src
Definition: flow.h:308
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
PKT_DROP_REASON_FLOW_MEMCAP
@ PKT_DROP_REASON_FLOW_MEMCAP
Definition: decode.h:387
FlowCnf_::hash_size
uint32_t hash_size
Definition: flow.h:292
FlowAddress_::address_un_data32
uint32_t address_un_data32[4]
Definition: flow.h:318
FlowSpareGetFromPool
FlowQueuePrivate FlowSpareGetFromPool(void)
Definition: flow-spare-pool.c:173
PcapPacketCntGet
uint64_t PcapPacketCntGet(const Packet *p)
Definition: decode.c:1175
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:282
Flow_::esp
struct Flow_::@121::@128 esp
DecodeThreadVars_::counter_flow_spare_sync_empty
StatsCounterId counter_flow_spare_sync_empty
Definition: decode.h:1083
Flow_::proto
uint8_t proto
Definition: flow.h:376
Packet_::flags
uint32_t flags
Definition: decode.h:560
FlowKeyGetHash
uint32_t FlowKeyGetHash(FlowKey *fk)
Definition: flow-hash.c:314
threads.h
ICMPV4_DEST_UNREACH_IS_VALID
#define ICMPV4_DEST_UNREACH_IS_VALID(p)
Definition: decode-icmpv4.h:253
TH_RST
#define TH_RST
Definition: decode-tcp.h:36
flow-private.h
Flow_
Flow data structure.
Definition: flow.h:354
FlowHashKey4_::vlan_id
uint16_t vlan_id[VLAN_MAX_LAYERS]
Definition: flow-hash.c:95
SCFlowStorageSize
unsigned int SCFlowStorageSize(void)
Definition: flow-storage.c:35
TH_FIN
#define TH_FIN
Definition: decode-tcp.h:34
Flow_::protomap
uint8_t protomap
Definition: flow.h:445
SC_ATOMIC_ADD
#define SC_ATOMIC_ADD(name, val)
add a value to our atomic variable
Definition: util-atomic.h:332
FlowProtoTimeout_
Definition: flow.h:518
FLOWLOCK_TRYWRLOCK
#define FLOWLOCK_TRYWRLOCK(fb)
Definition: flow.h:270
PKT_WANTS_FLOW
#define PKT_WANTS_FLOW
Definition: decode.h:1334
flow-hash.h
FlowLookupStruct_
Definition: flow.h:542
DecodeThreadVars_::counter_flow_get_used
StatsCounterId counter_flow_get_used
Definition: decode.h:1076
FlowHashKey4
struct FlowHashKey4_ FlowHashKey4
FBLOCK_TRYLOCK
#define FBLOCK_TRYLOCK(fb)
Definition: flow-hash.h:74
TcpStreamCnf_
Definition: stream-tcp.h:54
StatsCounterId
Definition: counters.h:30
Address_::address_un_data32
uint32_t address_un_data32[4]
Definition: decode.h:116
proto
uint8_t proto
Definition: decode-template.h:0
Flow_::livedev_id
uint16_t livedev_id
Definition: flow.h:399
p
Packet * p
Definition: fuzz_iprep.c:21
FlowHashKey6_::recur
uint8_t recur
Definition: flow-hash.c:108
Flow_::dp
Port dp
Definition: flow.h:370
stream_config
TcpStreamCnf stream_config
Definition: stream-tcp.c:229
DecodeThreadVars_::counter_flow_spare_sync
StatsCounterId counter_flow_spare_sync
Definition: decode.h:1082
FlowQueuePrivate_::len
uint32_t len
Definition: flow-queue.h:43
Flow_::protoctx
void * protoctx
Definition: flow.h:433
FLOW_IPV4
#define FLOW_IPV4
Definition: flow.h:99
g_recurlvl_mask
uint8_t g_recurlvl_mask
Definition: suricata.c:214
TmThreadsGetThreadTime
SCTime_t TmThreadsGetThreadTime(const int idx)
Definition: tm-threads.c:2339
FLOWLOCK_UNLOCK
#define FLOWLOCK_UNLOCK(fb)
Definition: flow.h:271
Flow_::flow_state
FlowStateType flow_state
Definition: flow.h:420
FlowWakeupFlowManagerThread
void FlowWakeupFlowManagerThread(void)
Definition: flow-manager.c:85
Packet_::icmp_s
struct Packet_::@32::@39 icmp_s
Address_::address
union Address_::@29 address
FLOW_CHECK_MEMCAP
#define FLOW_CHECK_MEMCAP(size)
check if a memory alloc would fit in the memcap
Definition: flow-util.h:134
FlowLookupStruct_::emerg_spare_sync_stamp
uint32_t emerg_spare_sync_stamp
Definition: flow.h:547
StatsCounterAvgAddI64
void StatsCounterAvgAddI64(StatsThreadContext *stats, StatsCounterAvgId id, int64_t x)
Definition: counters.c:239
DecodeThreadVars_::counter_flow_memcap
StatsCounterId counter_flow_memcap
Definition: decode.h:1062
flow-spare-pool.h
Flow_::dst
FlowAddress dst
Definition: flow.h:357
Flow_::fb
struct FlowBucket_ * fb
Definition: flow.h:491
FlowHashKey6_::ports
uint16_t ports[2]
Definition: flow-hash.c:106
FlowHashKey4_::u32
const uint32_t u32[6]
Definition: flow-hash.c:98
TCPHdr_::th_flags
uint8_t th_flags
Definition: decode-tcp.h:155
decode.h
util-debug.h
SCFlowRunFinishCallbacks
void SCFlowRunFinishCallbacks(ThreadVars *tv, Flow *f)
Definition: flow-callbacks.c:122
FLOW_GET_NEW_TRIES
#define FLOW_GET_NEW_TRIES
Definition: flow-hash.c:1151
STATSADDUI64
#define STATSADDUI64(cnt, value)
Definition: flow-hash.c:1202
SCTIME_FROM_TIMESPEC
#define SCTIME_FROM_TIMESPEC(ts)
Definition: util-time.h:91
PacketL4::L4Vars::icmpv4
ICMPV4Vars icmpv4
Definition: decode.h:491
Packet_::ts
SCTime_t ts
Definition: decode.h:568
FlowHashKey4_::livedev
uint16_t livedev
Definition: flow-hash.c:94
util-exception-policy.h
FlowHashKey6_::proto
uint8_t proto
Definition: flow-hash.c:107
Flow_::lastts
SCTime_t lastts
Definition: flow.h:418
FLOWLOCK_WRLOCK
#define FLOWLOCK_WRLOCK(fb)
Definition: flow.h:268
SC_ATOMIC_EXTERN
SC_ATOMIC_EXTERN(unsigned int, flow_prune_idx)
FlowKey_::recursion_level
uint8_t recursion_level
Definition: flow.h:311
ICMPV4Vars_::emb_dport
uint16_t emb_dport
Definition: decode-icmpv4.h:197
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:58
DecodeThreadVars_::counter_flow_active
StatsCounterId counter_flow_active
Definition: decode.h:1067
Flow_::flow_end_flags
uint8_t flow_end_flags
Definition: flow.h:447
Packet_::sp
Port sp
Definition: decode.h:521
StatsCounterIncr
void StatsCounterIncr(StatsThreadContext *stats, StatsCounterId id)
Increments the local counter.
Definition: counters.c:164
FlowHashKey6
struct FlowHashKey6_ FlowHashKey6
FlowHashKey4_::pad
uint16_t pad[1]
Definition: flow-hash.c:96
TH_ACK
#define TH_ACK
Definition: decode-tcp.h:38
util-time.h
FlowQueuePrivateGetFromTop
Flow * FlowQueuePrivateGetFromTop(FlowQueuePrivate *fqc)
Definition: flow-queue.c:151
app-layer-parser.h
FlowKey_::livedev_id
uint16_t livedev_id
Definition: flow.h:312
ThreadVars_::id
int id
Definition: threadvars.h:86
FlowHashKey6_::livedev
uint16_t livedev
Definition: flow-hash.c:109
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:325
DecodeThreadVars_::counter_flow_spare_sync_avg
StatsCounterAvgId counter_flow_spare_sync_avg
Definition: decode.h:1085
flow_timeouts_emerg
FlowProtoTimeout flow_timeouts_emerg[FLOW_PROTO_MAX]
Definition: flow.c:90
FlowThreadId
uint16_t FlowThreadId
Definition: flow.h:331
DecodeThreadVars_::counter_flow_icmp4
StatsCounterId counter_flow_icmp4
Definition: decode.h:1070
FlowKey_::sp
Port sp
Definition: flow.h:309
TimeModeIsLive
bool TimeModeIsLive(void)
Definition: util-time.c:112
FlowTimeoutsEmergency
void FlowTimeoutsEmergency(void)
Definition: flow-manager.c:104
FlowGetProtoMapping
uint8_t FlowGetProtoMapping(uint8_t proto)
Function to map the protocol to the defined FLOW_PROTO_* enumeration.
Definition: flow-util.c:100
Packet_
Definition: decode.h:514
FlowHashKey6_::pad
uint16_t pad[1]
Definition: flow-hash.c:111
FLOW_END_FLAG_TCPREUSE
#define FLOW_END_FLAG_TCPREUSE
Definition: flow.h:244
conf.h
Packet_::l4
struct PacketL4 l4
Definition: decode.h:614
Port
uint16_t Port
Definition: decode.h:219
FLOW_END_FLAG_EMERGENCY
#define FLOW_END_FLAG_EMERGENCY
Definition: flow.h:240
FBLOCK_UNLOCK
#define FBLOCK_UNLOCK(fb)
Definition: flow-hash.h:75
SCTime_t
Definition: util-time.h:40
FlowHashKey4_
Definition: flow-hash.c:87
FlowClearMemory
int FlowClearMemory(Flow *f, uint8_t proto_map)
Function clear the flow memory before queueing it to spare flow queue.
Definition: flow.c:1127
STREAM_PKT_FLAG_TCP_SESSION_REUSE
#define STREAM_PKT_FLAG_TCP_SESSION_REUSE
Definition: stream-tcp-private.h:322
FlowCnf_::hash_rand
uint32_t hash_rand
Definition: flow.h:291
FlowHashKey4_::addrs
uint32_t addrs[2]
Definition: flow-hash.c:90
output-flow.h
detect-engine-state.h
Data structures and function prototypes for keeping state for the detection engine.
FlowHashKey6_
Definition: flow-hash.c:102
flow-timeout.h
Flow_::flow_hash
uint32_t flow_hash
Definition: flow.h:396
RunmodeIsUnittests
int RunmodeIsUnittests(void)
Definition: suricata.c:292
FlowUpdateState
void FlowUpdateState(Flow *f, const enum FlowState s)
Definition: flow.c:1192
Flow_::src
FlowAddress src
Definition: flow.h:357
Flow_::next
struct Flow_ * next
Definition: flow.h:401
dtv
DecodeThreadVars * dtv
Definition: fuzz_decodepcapfile.c:34
FlowHashKey6_::src
uint32_t src[4]
Definition: flow-hash.c:105
FlowLookupStruct_::spare_queue
FlowQueuePrivate spare_queue
Definition: flow.h:544
FlowGetIpPairProtoHash
uint32_t FlowGetIpPairProtoHash(const Packet *p)
Definition: flow-hash.c:117
SCTIME_CMP_LT
#define SCTIME_CMP_LT(a, b)
Definition: util-time.h:105
ARRAY_SIZE
#define ARRAY_SIZE(arr)
Definition: suricata-common.h:569
flow_hash
FlowBucket * flow_hash
Definition: flow-hash.c:59
flow-storage.h
TH_SYN
#define TH_SYN
Definition: decode-tcp.h:35
FLOW_STATE_NEW
@ FLOW_STATE_NEW
Definition: flow.h:504
flow-manager.h
suricata-common.h
IPV4_GET_RAW_IPSRC_U32
#define IPV4_GET_RAW_IPSRC_U32(ip4h)
Definition: decode-ipv4.h:108
FLOW_IPV6
#define FLOW_IPV6
Definition: flow.h:101
Flow_::icmp_d
struct Flow_::@123::@129 icmp_d
DecodeThreadVars_::counter_flow_udp
StatsCounterId counter_flow_udp
Definition: decode.h:1069
flow_config
FlowConfig flow_config
Definition: flow.c:94
FlowKey_::dst
Address dst
Definition: flow.h:308
Packet_::livedev_id
uint16_t livedev_id
Definition: decode.h:631
SCTIME_SECS
#define SCTIME_SECS(t)
Definition: util-time.h:57
VLAN_MAX_LAYERS
#define VLAN_MAX_LAYERS
Definition: decode-vlan.h:51
DecodeThreadVars_::counter_flow_memcap_eps
ExceptionPolicyCounters counter_flow_memcap_eps
Definition: decode.h:1063
util-hash-lookup3.h
FlowGetFlowFromHash
Flow * FlowGetFlowFromHash(ThreadVars *tv, FlowLookupStruct *fls, Packet *p, Flow **dest)
Get Flow for packet.
Definition: flow-hash.c:906
Flow_::timeout_policy
uint32_t timeout_policy
Definition: flow.h:413
tv
ThreadVars * tv
Definition: fuzz_decodepcapfile.c:33
FlowHashKey6_::dst
uint32_t dst[4]
Definition: flow-hash.c:105
TcpStreamCnf_::midstream
bool midstream
Definition: stream-tcp.h:70
FlowCnf_::memcap_policy
enum ExceptionPolicy memcap_policy
Definition: flow.h:300
g_vlan_mask
uint16_t g_vlan_mask
Definition: suricata.c:206
Packet_::flow_hash
uint32_t flow_hash
Definition: decode.h:566
FlowKey_::proto
uint8_t proto
Definition: flow.h:310
FLOW_STATE_CLOSED
@ FLOW_STATE_CLOSED
Definition: flow.h:506
flow-callbacks.h
FlowAddress_::address
union FlowAddress_::@120 address
DecodeThreadVars_::counter_flow_spare_sync_incomplete
StatsCounterId counter_flow_spare_sync_incomplete
Definition: decode.h:1084
DecodeThreadVars_
Structure to hold thread specific data for all decode modules.
Definition: decode.h:993
FlowGetFromFlowKey
Flow * FlowGetFromFlowKey(FlowKey *key, struct timespec *ttime, const uint32_t hash)
Get or create a Flow using a FlowKey.
Definition: flow-hash.c:1100
Packet_::recursion_level
uint8_t recursion_level
Definition: decode.h:539
DecodeThreadVars_::output_flow_thread_data
void * output_flow_thread_data
Definition: decode.h:1091
FlowInit
void FlowInit(ThreadVars *tv, Flow *f, const Packet *p)
Definition: flow-util.c:148
FlowKey_
Definition: flow.h:307
FlowHashKey6_::vlan_id
uint16_t vlan_id[VLAN_MAX_LAYERS]
Definition: flow-hash.c:110
FlowHashKey4_::proto
uint8_t proto
Definition: flow-hash.c:92
FLOW_EMERGENCY
#define FLOW_EMERGENCY
Definition: flow-private.h:37
STREAM_PKT_FLAG_SET
#define STREAM_PKT_FLAG_SET(p, f)
Definition: stream-tcp-private.h:326
Address_::family
char family
Definition: decode.h:114
Packet_::dst
Address dst
Definition: decode.h:519
Flow_::vlan_id
uint16_t vlan_id[VLAN_MAX_LAYERS]
Definition: flow.h:378
FLOW_END_FLAG_TIMEOUT
#define FLOW_END_FLAG_TIMEOUT
Definition: flow.h:241
FlowHashKey6_::u32
const uint32_t u32[12]
Definition: flow-hash.c:113
Packet_::vlan_id
uint16_t vlan_id[VLAN_MAX_LAYERS]
Definition: decode.h:541
DecodeThreadVars_::counter_flow_total
StatsCounterId counter_flow_total
Definition: decode.h:1066
likely
#define likely(expr)
Definition: util-optimize.h:32
Flow_::icmp_s
struct Flow_::@121::@127 icmp_s
Flow_::sp
Port sp
Definition: flow.h:359
ICMPV4Vars_::emb_sport
uint16_t emb_sport
Definition: decode-icmpv4.h:196
SC_ATOMIC_GET
#define SC_ATOMIC_GET(name)
Get the value from the atomic variable.
Definition: util-atomic.h:375
FlowKey_::vlan_id
uint16_t vlan_id[VLAN_MAX_LAYERS]
Definition: flow.h:313
flow.h
FlowQueuePrivateAppendFlow
void FlowQueuePrivateAppendFlow(FlowQueuePrivate *fqc, Flow *f)
Definition: flow-queue.c:65
FlowAlloc
Flow * FlowAlloc(void)
allocate a flow
Definition: flow-util.c:57
SCTIME_ADD_SECS
#define SCTIME_ADD_SECS(ts, s)
Definition: util-time.h:64
FlowGetExistingFlowFromFlowId
Flow * FlowGetExistingFlowFromFlowId(uint64_t flow_id)
Look for existing Flow using a flow id value.
Definition: flow-hash.c:1036
Packet_::dp
Port dp
Definition: decode.h:529
ExceptionPolicy
ExceptionPolicy
Definition: util-exception-policy-types.h:26
FLOW_END_FLAG_FORCED
#define FLOW_END_FLAG_FORCED
Definition: flow.h:242
ICMPV4_IS_ERROR_MSG
#define ICMPV4_IS_ERROR_MSG(type)
Definition: decode-icmpv4.h:267
FlowKey_::dp
Port dp
Definition: flow.h:309
ThreadVars_::stats
StatsThreadContext stats
Definition: threadvars.h:121
ExceptionPolicyCounters_::eps_id
StatsCounterId eps_id[EXCEPTION_POLICY_MAX]
Definition: util-exception-policy-types.h:56
FlowSetupPacket
void FlowSetupPacket(Packet *p)
prepare packet for a life with flow Set PKT_WANTS_FLOW flag to indicate workers should do a flow look...
Definition: flow-hash.c:531
TCPHdr_
Definition: decode-tcp.h:149
Packet_::src
Address src
Definition: decode.h:518
PacketL4::vars
union PacketL4::L4Vars vars
FLOW_PROTO_MAX
@ FLOW_PROTO_MAX
Definition: flow-private.h:72
FlowHashKey4_::recur
uint8_t recur
Definition: flow-hash.c:93
output.h
Flow_::thread_id
FlowThreadId thread_id[2]
Definition: flow.h:392
SC_ATOMIC_OR
#define SC_ATOMIC_OR(name, val)
Bitwise OR a value to our atomic variable.
Definition: util-atomic.h:350
DecodeThreadVars_::counter_flow_tcp_reuse
StatsCounterId counter_flow_tcp_reuse
Definition: decode.h:1072
DecodeThreadVars_::counter_flow_tcp
StatsCounterId counter_flow_tcp
Definition: decode.h:1068