suricata
log-pcap.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-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  * \file
20  *
21  * \author William Metcalf <William.Metcalf@gmail.com>
22  * \author Victor Julien <victor@inliniac.net>
23  *
24  * Pcap packet logging module.
25  */
26 
27 #include "suricata-common.h"
28 #ifdef HAVE_LIBLZ4
29 #include <lz4frame.h>
30 #include "util-fmemopen.h"
31 #endif /* HAVE_LIBLZ4 */
32 
33 #if defined(HAVE_DIRENT_H) && defined(HAVE_FNMATCH_H)
34 #define INIT_RING_BUFFER
35 #include <dirent.h>
36 #include <fnmatch.h>
37 #endif
38 
39 #include "log-pcap.h"
40 
41 #include "threads.h"
42 #include "threadvars.h"
43 #include "decode.h"
44 #include "stream.h"
45 #include "stream-tcp-reassemble.h"
46 
47 #include "output.h"
48 
49 #include "util-buffer.h"
50 #include "util-byte.h"
51 #include "util-conf.h"
52 #include "util-cpu.h"
53 #include "util-datalink.h"
54 #include "util-misc.h"
55 #include "util-path.h"
56 #include "util-time.h"
57 
58 #define DEFAULT_LOG_FILENAME "pcaplog"
59 #define MODULE_NAME "PcapLog"
60 #define MIN_LIMIT 4 * 1024 * 1024
61 #define DEFAULT_LIMIT 100 * 1024 * 1024
62 #define DEFAULT_FILE_LIMIT 0
63 
64 #define LOGMODE_NORMAL 0
65 #define LOGMODE_MULTI 1
66 
72 
73 #define RING_BUFFER_MODE_DISABLED 0
74 #define RING_BUFFER_MODE_ENABLED 1
75 
76 #define TS_FORMAT_SEC 0
77 #define TS_FORMAT_USEC 1
78 
79 #define USE_STREAM_DEPTH_DISABLED 0
80 #define USE_STREAM_DEPTH_ENABLED 1
81 
82 #define HONOR_PASS_RULES_DISABLED 0
83 #define HONOR_PASS_RULES_ENABLED 1
84 
85 #define PCAP_SNAPLEN 262144
86 #define PCAP_BUFFER_TIMEOUT 1000000 // microseconds
87 #define PCAP_PKTHDR_SIZE 16
88 
89 SC_ATOMIC_DECLARE(uint32_t, thread_cnt);
90 
91 typedef struct PcapFileName_ {
92  char *filename;
93  char *dirname;
94 
95  /* Like a struct timeval, but with fixed size. This is only used when
96  * seeding the ring buffer on start. */
97  struct {
98  uint64_t secs;
99  uint32_t usecs;
100  };
101 
102  TAILQ_ENTRY(PcapFileName_) next; /**< Pointer to next Pcap File for tailq. */
104 
105 thread_local char *pcap_file_thread = NULL;
106 
107 typedef struct PcapLogProfileData_ {
108  uint64_t total;
109  uint64_t cnt;
111 
112 #define MAX_TOKS 9
113 #define MAX_FILENAMELEN 513
114 
118 };
119 
120 typedef struct PcapLogCompressionData_ {
122  uint8_t *buffer;
123  uint64_t buffer_size;
124 #ifdef HAVE_LIBLZ4
125  LZ4F_compressionContext_t lz4f_context;
126  LZ4F_preferences_t lz4f_prefs;
127 #endif /* HAVE_LIBLZ4 */
128  FILE *file;
129  uint8_t *pcap_buf;
130  uint64_t pcap_buf_size;
132  uint64_t bytes_in_block;
134 
135 /**
136  * PcapLog thread vars
137  *
138  * Used for storing file options.
139  */
140 typedef struct PcapLogData_ {
141  int use_stream_depth; /**< use stream depth i.e. ignore packets that reach limit */
142  int honor_pass_rules; /**< don't log if pass rules have matched */
144  uint64_t pkt_cnt; /**< total number of packets */
145  struct pcap_pkthdr *h; /**< pcap header struct */
146  char *filename; /**< current filename */
147  int mode; /**< normal or multi */
148  int prev_day; /**< last day, for finding out when */
149  uint64_t size_current; /**< file current size */
150  uint64_t size_limit; /**< file size limit */
151  pcap_t *pcap_dead_handle; /**< pcap_dumper_t needs a handle */
152  pcap_dumper_t *pcap_dumper; /**< actually writes the packets */
153  uint64_t profile_data_size; /**< track in bytes how many bytes we wrote */
154  uint32_t file_cnt; /**< count of pcap files we currently have */
155  uint32_t max_files; /**< maximum files to use in ring buffer mode */
156  bool is_private; /**< true if ctx is thread local */
158  conditional; /**< log all packets or just packets and flows with alerts */
159 
167 
168  TAILQ_HEAD(, PcapFileName_) pcap_file_list;
169 
170  uint32_t thread_number; /**< thread number, first thread is 1, second 2, etc */
171  int use_ringbuffer; /**< ring buffer mode enabled or disabled */
172  int timestamp_format; /**< timestamp format sec or usec */
173  char *prefix; /**< filename prefix */
174  const char *suffix; /**< filename suffix */
175  char dir[PATH_MAX]; /**< pcap log directory */
176  int reported;
177  int threads; /**< number of threads (only set in the global) */
178  char *filename_parts[MAX_TOKS];
179  int filename_part_cnt;
180  struct timeval last_pcap_dump;
181  int fopen_err; /**< set to the last fopen error */
182  bool pcap_open_err; /**< true if the last pcap open errored */
183 
184  PcapLogCompressionData compression;
186 
187 typedef struct PcapLogThreadData_ {
191 
192 /* Pattern for extracting timestamp from pcap log files. */
193 static const char timestamp_pattern[] = ".*?(\\d+)(\\.(\\d+))?";
194 static pcre2_code *pcre_timestamp_code = NULL;
195 static pcre2_match_data *pcre_timestamp_match = NULL;
196 
197 /* global pcap data for when we're using multi mode. At exit we'll
198  * merge counters into this one and then report counters. */
199 static PcapLogData *g_pcap_data = NULL;
200 
201 static int PcapLogOpenFileCtx(PcapLogData *);
202 static int PcapLog(ThreadVars *, void *, const Packet *);
203 static TmEcode PcapLogDataInit(ThreadVars *, const void *, void **);
204 static TmEcode PcapLogDataDeinit(ThreadVars *, void *);
205 static void PcapLogFileDeInitCtx(OutputCtx *);
206 static OutputInitResult PcapLogInitCtx(ConfNode *);
207 static void PcapLogProfilingDump(PcapLogData *);
208 static bool PcapLogCondition(ThreadVars *, void *, const Packet *);
209 
210 void PcapLogRegister(void)
211 {
212  OutputPacketLoggerFunctions output_logger_functions = {
213  .LogFunc = PcapLog,
214  .FlushFunc = NULL,
215  .ConditionFunc = PcapLogCondition,
216  .ThreadInitFunc = PcapLogDataInit,
217  .ThreadDeinitFunc = PcapLogDataDeinit,
218  .ThreadExitPrintStatsFunc = NULL,
219  };
221  LOGGER_PCAP, MODULE_NAME, "pcap-log", PcapLogInitCtx, &output_logger_functions);
223  SC_ATOMIC_INIT(thread_cnt);
224  SC_ATOMIC_SET(thread_cnt, 1); /* first id is 1 */
225 }
226 
227 #define PCAPLOG_PROFILE_START \
228  uint64_t pcaplog_profile_ticks = UtilCpuGetTicks()
229 
230 #define PCAPLOG_PROFILE_END(prof) \
231  (prof).total += (UtilCpuGetTicks() - pcaplog_profile_ticks); \
232  (prof).cnt++
233 
234 static bool PcapLogCondition(ThreadVars *tv, void *thread_data, const Packet *p)
235 {
236  PcapLogThreadData *ptd = (PcapLogThreadData *)thread_data;
237 
238  /* Log alerted flow or tagged flow */
239  switch (ptd->pcap_log->conditional) {
240  case LOGMODE_COND_ALL:
241  break;
242  case LOGMODE_COND_ALERTS:
243  return (p->alerts.cnt || (p->flow && FlowHasAlerts(p->flow)));
244  case LOGMODE_COND_TAG:
245  return (p->flags & (PKT_HAS_TAG | PKT_FIRST_TAG));
246  }
247 
248  if (p->flags & PKT_PSEUDO_STREAM_END) {
249  return false;
250  }
251 
252  if (p->ttype == PacketTunnelChild) {
253  return false;
254  }
255  return true;
256 }
257 
258 /**
259  * \brief Function to close pcaplog file
260  *
261  * \param t Thread Variable containing input/output queue, cpu affinity etc.
262  * \param pl PcapLog thread variable.
263  */
264 static int PcapLogCloseFile(ThreadVars *t, PcapLogData *pl)
265 {
266  if (pl != NULL) {
268 
269  if (pl->pcap_dumper != NULL) {
270  pcap_dump_close(pl->pcap_dumper);
271 #ifdef HAVE_LIBLZ4
272  PcapLogCompressionData *comp = &pl->compression;
274  /* pcap_dump_close() has closed its output ``file'',
275  * so we need to call fmemopen again. */
276 
277  comp->pcap_buf_wrapper = SCFmemopen(comp->pcap_buf,
278  comp->pcap_buf_size, "w");
279  if (comp->pcap_buf_wrapper == NULL) {
280  SCLogError("SCFmemopen failed: %s", strerror(errno));
281  return TM_ECODE_FAILED;
282  }
283  }
284 #endif /* HAVE_LIBLZ4 */
285  }
286  pl->size_current = 0;
287  pl->pcap_dumper = NULL;
288 
289  if (pl->pcap_dead_handle != NULL)
290  pcap_close(pl->pcap_dead_handle);
291  pl->pcap_dead_handle = NULL;
292 
293 #ifdef HAVE_LIBLZ4
294  PcapLogCompressionData *comp = &pl->compression;
296  /* pcap_dump_close did not write any data because we call
297  * pcap_dump_flush() after every write when writing
298  * compressed output. */
299  uint64_t bytes_written = LZ4F_compressEnd(comp->lz4f_context,
300  comp->buffer, comp->buffer_size, NULL);
301  if (LZ4F_isError(bytes_written)) {
302  SCLogError("LZ4F_compressEnd: %s", LZ4F_getErrorName(bytes_written));
303  return TM_ECODE_FAILED;
304  }
305  if (fwrite(comp->buffer, 1, bytes_written, comp->file) < bytes_written) {
306  SCLogError("fwrite failed: %s", strerror(errno));
307  return TM_ECODE_FAILED;
308  }
309  fclose(comp->file);
310  comp->bytes_in_block = 0;
311  }
312 #endif /* HAVE_LIBLZ4 */
313 
315  }
316 
317  return 0;
318 }
319 
320 static void PcapFileNameFree(PcapFileName *pf)
321 {
322  if (pf != NULL) {
323  if (pf->filename != NULL) {
324  SCFree(pf->filename);
325  }
326  if (pf->dirname != NULL) {
327  SCFree(pf->dirname);
328  }
329  SCFree(pf);
330  }
331 }
332 
333 /**
334  * \brief Function to rotate pcaplog file
335  *
336  * \param t Thread Variable containing input/output queue, cpu affinity etc.
337  * \param pl PcapLog thread variable.
338  *
339  * \retval 0 on success
340  * \retval -1 on failure
341  */
342 static int PcapLogRotateFile(ThreadVars *t, PcapLogData *pl)
343 {
344  PcapFileName *pf;
345 
347 
348  if (PcapLogCloseFile(t,pl) < 0) {
349  SCLogDebug("PcapLogCloseFile failed");
350  return -1;
351  }
352 
353  if (pl->use_ringbuffer == RING_BUFFER_MODE_ENABLED && pl->file_cnt >= pl->max_files) {
354  pf = TAILQ_FIRST(&pl->pcap_file_list);
355  SCLogDebug("Removing pcap file %s", pf->filename);
356 
357  if (remove(pf->filename) != 0) {
358  // VJ remove can fail because file is already gone
359  // SCLogWarning("failed to remove log file %s: %s",
360  // pf->filename, strerror( errno ));
361  }
362 
363  TAILQ_REMOVE(&pl->pcap_file_list, pf, next);
364  PcapFileNameFree(pf);
365  pl->file_cnt--;
366  }
367 
368  if (PcapLogOpenFileCtx(pl) < 0) {
369  SCLogError("opening new pcap log file failed");
370  return -1;
371  }
372  pl->file_cnt++;
373  SCLogDebug("file_cnt %u", pl->file_cnt);
374 
376  return 0;
377 }
378 
379 static int PcapLogOpenHandles(PcapLogData *pl, const Packet *p)
380 {
382 
383  int datalink = p->datalink;
384  if (p->ttype == PacketTunnelChild) {
385  Packet *real_p = p->root;
386  datalink = real_p->datalink;
387  }
388  if (pl->pcap_dead_handle == NULL) {
389  SCLogDebug("Setting pcap-log link type to %u", datalink);
390  if ((pl->pcap_dead_handle = pcap_open_dead(datalink, PCAP_SNAPLEN)) == NULL) {
391  SCLogDebug("Error opening dead pcap handle");
392  return TM_ECODE_FAILED;
393  }
394  }
395 
396  if (pl->pcap_dumper == NULL) {
397  if (pl->compression.format == PCAP_LOG_COMPRESSION_FORMAT_NONE) {
398  if ((pl->pcap_dumper = pcap_dump_open(pl->pcap_dead_handle,
399  pl->filename)) == NULL) {
400  if (!pl->pcap_open_err) {
401  SCLogError("Error opening dump file %s", pcap_geterr(pl->pcap_dead_handle));
402  pl->pcap_open_err = true;
403  }
404  return TM_ECODE_FAILED;
405  } else {
406  pl->pcap_open_err = false;
407  }
408  }
409 #ifdef HAVE_LIBLZ4
410  else if (pl->compression.format == PCAP_LOG_COMPRESSION_FORMAT_LZ4) {
411  PcapLogCompressionData *comp = &pl->compression;
412 
413  comp->file = fopen(pl->filename, "w");
414  if (comp->file == NULL) {
415  if (errno != pl->fopen_err) {
416  SCLogError("Error opening file for compressed output: %s", strerror(errno));
417  pl->fopen_err = errno;
418  }
419  return TM_ECODE_FAILED;
420  } else {
421  pl->fopen_err = 0;
422  }
423 
424  if ((pl->pcap_dumper = pcap_dump_fopen(pl->pcap_dead_handle, comp->pcap_buf_wrapper)) ==
425  NULL) {
426  if (!pl->pcap_open_err) {
427  SCLogError("Error opening dump file %s", pcap_geterr(pl->pcap_dead_handle));
428  pl->pcap_open_err = true;
429  }
430  fclose(comp->file);
431  comp->file = NULL;
432  return TM_ECODE_FAILED;
433  } else {
434  pl->pcap_open_err = false;
435  }
436 
437  uint64_t bytes_written = LZ4F_compressBegin(comp->lz4f_context,
438  comp->buffer, comp->buffer_size, NULL);
439  if (LZ4F_isError(bytes_written)) {
440  SCLogError("LZ4F_compressBegin: %s", LZ4F_getErrorName(bytes_written));
441  return TM_ECODE_FAILED;
442  }
443  if (fwrite(comp->buffer, 1, bytes_written, comp->file) < bytes_written) {
444  SCLogError("fwrite failed: %s", strerror(errno));
445  return TM_ECODE_FAILED;
446  }
447  }
448 #endif /* HAVE_LIBLZ4 */
449  }
450 
452  return TM_ECODE_OK;
453 }
454 
455 /** \internal
456  * \brief lock wrapper for main PcapLog() function
457  * NOTE: only meant for use in main PcapLog() function.
458  */
459 static void PcapLogLock(PcapLogData *pl)
460 {
461  if (!(pl->is_private)) {
463  SCMutexLock(&pl->plog_lock);
465  }
466 }
467 
468 /** \internal
469  * \brief unlock wrapper for main PcapLog() function
470  * NOTE: only meant for use in main PcapLog() function.
471  */
472 static void PcapLogUnlock(PcapLogData *pl)
473 {
474  if (!(pl->is_private)) {
476  SCMutexUnlock(&pl->plog_lock);
478  }
479 }
480 
481 static inline int PcapWrite(
482  PcapLogData *pl, PcapLogCompressionData *comp, const uint8_t *data, const size_t len)
483 {
484  struct timeval current_dump;
485  gettimeofday(&current_dump, NULL);
486  pcap_dump((u_char *)pl->pcap_dumper, pl->h, data);
487  if (pl->compression.format == PCAP_LOG_COMPRESSION_FORMAT_NONE) {
488  pl->size_current += len;
489  }
490 #ifdef HAVE_LIBLZ4
491  else if (comp->format == PCAP_LOG_COMPRESSION_FORMAT_LZ4) {
492  pcap_dump_flush(pl->pcap_dumper);
493  long in_size = ftell(comp->pcap_buf_wrapper);
494  if (in_size < 0) {
495  SCLogError("ftell failed with: %s", strerror(errno));
496  return TM_ECODE_FAILED;
497  }
498  uint64_t out_size = LZ4F_compressUpdate(comp->lz4f_context, comp->buffer, comp->buffer_size,
499  comp->pcap_buf, (uint64_t)in_size, NULL);
500  if (LZ4F_isError(len)) {
501  SCLogError("LZ4F_compressUpdate: %s", LZ4F_getErrorName(len));
502  return TM_ECODE_FAILED;
503  }
504  if (fseek(comp->pcap_buf_wrapper, 0, SEEK_SET) != 0) {
505  SCLogError("fseek failed: %s", strerror(errno));
506  return TM_ECODE_FAILED;
507  }
508  if (fwrite(comp->buffer, 1, out_size, comp->file) < out_size) {
509  SCLogError("fwrite failed: %s", strerror(errno));
510  return TM_ECODE_FAILED;
511  }
512  if (out_size > 0) {
513  pl->size_current += out_size;
514  comp->bytes_in_block = len;
515  } else {
516  comp->bytes_in_block += len;
517  }
518  }
519 #endif /* HAVE_LIBLZ4 */
520  if (TimeDifferenceMicros(pl->last_pcap_dump, current_dump) >= PCAP_BUFFER_TIMEOUT) {
521  pcap_dump_flush(pl->pcap_dumper);
522  }
523  pl->last_pcap_dump = current_dump;
524  return TM_ECODE_OK;
525 }
526 
531 };
532 
533 static int PcapLogSegmentCallback(
534  const Packet *p, TcpSegment *seg, void *data, const uint8_t *buf, uint32_t buflen)
535 {
536  struct PcapLogCallbackContext *pctx = (struct PcapLogCallbackContext *)data;
537 
538  if (seg->pcap_hdr_storage->pktlen) {
539  struct timeval tv;
541  pctx->pl->h->ts.tv_sec = tv.tv_sec;
542  pctx->pl->h->ts.tv_usec = tv.tv_usec;
543  pctx->pl->h->len = seg->pcap_hdr_storage->pktlen + buflen;
544  pctx->pl->h->caplen = seg->pcap_hdr_storage->pktlen + buflen;
545  MemBufferReset(pctx->buf);
547  MemBufferWriteRaw(pctx->buf, buf, buflen);
548 
549  PcapWrite(pctx->pl, pctx->comp, (uint8_t *)pctx->buf->buffer, pctx->pl->h->len);
550  }
551  return 1;
552 }
553 
554 static void PcapLogDumpSegments(
555  PcapLogThreadData *td, PcapLogCompressionData *comp, const Packet *p)
556 {
557  uint8_t flag = STREAM_DUMP_HEADERS;
558 
559  /* Loop on segment from this side */
560  struct PcapLogCallbackContext data = { td->pcap_log, comp, td->buf };
561  StreamSegmentForSession(p, flag, PcapLogSegmentCallback, (void *)&data);
562 }
563 
564 /**
565  * \brief Pcap logging main function
566  *
567  * \param t threadvar
568  * \param p packet
569  * \param thread_data thread module specific data
570  *
571  * \retval TM_ECODE_OK on succes
572  * \retval TM_ECODE_FAILED on serious error
573  */
574 static int PcapLog (ThreadVars *t, void *thread_data, const Packet *p)
575 {
576  size_t len;
577  int ret = 0;
578  Packet *rp = NULL;
579 
580  PcapLogThreadData *td = (PcapLogThreadData *)thread_data;
581  PcapLogData *pl = td->pcap_log;
582 
585  return TM_ECODE_OK;
586  }
587 
588  PcapLogLock(pl);
589 
590  pl->pkt_cnt++;
591  pl->h->ts.tv_sec = SCTIME_SECS(p->ts);
592  pl->h->ts.tv_usec = SCTIME_USECS(p->ts);
593  if (p->ttype == PacketTunnelChild) {
594  rp = p->root;
595  pl->h->caplen = GET_PKT_LEN(rp);
596  pl->h->len = GET_PKT_LEN(rp);
598  } else {
599  pl->h->caplen = GET_PKT_LEN(p);
600  pl->h->len = GET_PKT_LEN(p);
602  }
603 
604  if (pl->filename == NULL) {
605  ret = PcapLogOpenFileCtx(pl);
606  if (ret < 0) {
607  PcapLogUnlock(pl);
608  return TM_ECODE_FAILED;
609  }
610  SCLogDebug("Opening PCAP log file %s", pl->filename);
611  }
612 
613  PcapLogCompressionData *comp = &pl->compression;
615  if ((pl->size_current + len) > pl->size_limit) {
616  if (PcapLogRotateFile(t,pl) < 0) {
617  PcapLogUnlock(pl);
618  SCLogDebug("rotation of pcap failed");
619  return TM_ECODE_FAILED;
620  }
621  }
622  }
623 #ifdef HAVE_LIBLZ4
625  /* When writing compressed pcap logs, we have no way of knowing
626  * for sure whether adding this packet would cause the current
627  * file to exceed the size limit. Thus, we record the number of
628  * bytes that have been fed into lz4 since the last write, and
629  * act as if they would be written uncompressed. */
630 
632  if (PcapLogRotateFile(t,pl) < 0) {
633  PcapLogUnlock(pl);
634  SCLogDebug("rotation of pcap failed");
635  return TM_ECODE_FAILED;
636  }
637  }
638  }
639 #endif /* HAVE_LIBLZ4 */
640 
641  /* XXX pcap handles, nfq, pfring, can only have one link type ipfw? we do
642  * this here as we don't know the link type until we get our first packet */
643  if (pl->pcap_dead_handle == NULL || pl->pcap_dumper == NULL) {
644  if (PcapLogOpenHandles(pl, p) != TM_ECODE_OK) {
645  PcapLogUnlock(pl);
646  return TM_ECODE_FAILED;
647  }
648  }
649 
651 
652  /* if we are using alerted logging and if packet is first one with alert in flow
653  * then we need to dump in the pcap the stream acked by the packet */
654  if ((p->flags & PKT_FIRST_ALERTS) && (td->pcap_log->conditional != LOGMODE_COND_ALL)) {
655  if (PacketIsTCP(p)) {
656  /* dump fake packets for all segments we have on acked by packet */
657  PcapLogDumpSegments(td, comp, p);
658 
659  if (p->flags & PKT_PSEUDO_STREAM_END) {
660  PcapLogUnlock(pl);
661  return TM_ECODE_OK;
662  }
663 
664  /* PcapLogDumpSegment has written over the PcapLogData variables so need to update */
665  pl->h->ts.tv_sec = SCTIME_SECS(p->ts);
666  pl->h->ts.tv_usec = SCTIME_USECS(p->ts);
667  if (p->ttype == PacketTunnelChild) {
668  rp = p->root;
669  pl->h->caplen = GET_PKT_LEN(rp);
670  pl->h->len = GET_PKT_LEN(rp);
672  } else {
673  pl->h->caplen = GET_PKT_LEN(p);
674  pl->h->len = GET_PKT_LEN(p);
676  }
677  }
678  }
679 
680  if (p->ttype == PacketTunnelChild) {
681  rp = p->root;
682  ret = PcapWrite(pl, comp, GET_PKT_DATA(rp), len);
683  } else {
684  ret = PcapWrite(pl, comp, GET_PKT_DATA(p), len);
685  }
686  if (ret != TM_ECODE_OK) {
688  PcapLogUnlock(pl);
689  return ret;
690  }
691 
694 
695  SCLogDebug("pl->size_current %"PRIu64", pl->size_limit %"PRIu64,
697 
698  PcapLogUnlock(pl);
699  return TM_ECODE_OK;
700 }
701 
702 static PcapLogData *PcapLogDataCopy(const PcapLogData *pl)
703 {
705  PcapLogData *copy = SCCalloc(1, sizeof(*copy));
706  if (unlikely(copy == NULL)) {
707  return NULL;
708  }
709 
710  copy->h = SCCalloc(1, sizeof(*copy->h));
711  if (unlikely(copy->h == NULL)) {
712  SCFree(copy);
713  return NULL;
714  }
715 
716  copy->prefix = SCStrdup(pl->prefix);
717  if (unlikely(copy->prefix == NULL)) {
718  SCFree(copy->h);
719  SCFree(copy);
720  return NULL;
721  }
722 
723  copy->suffix = pl->suffix;
724 
725  /* settings TODO move to global cfg struct */
726  copy->is_private = true;
727  copy->mode = pl->mode;
728  copy->max_files = pl->max_files;
729  copy->use_ringbuffer = pl->use_ringbuffer;
730  copy->timestamp_format = pl->timestamp_format;
732  copy->size_limit = pl->size_limit;
733  copy->conditional = pl->conditional;
734 
735  const PcapLogCompressionData *comp = &pl->compression;
736  PcapLogCompressionData *copy_comp = &copy->compression;
737  copy_comp->format = comp->format;
738 #ifdef HAVE_LIBLZ4
740  /* We need to allocate a new compression context and buffers for
741  * the copy. First copy the things that can simply be copied. */
742 
743  copy_comp->buffer_size = comp->buffer_size;
744  copy_comp->pcap_buf_size = comp->pcap_buf_size;
745  copy_comp->lz4f_prefs = comp->lz4f_prefs;
746 
747  /* Allocate the buffers. */
748 
749  copy_comp->buffer = SCMalloc(copy_comp->buffer_size);
750  if (copy_comp->buffer == NULL) {
751  SCLogError("SCMalloc failed: %s", strerror(errno));
752  SCFree(copy->h);
753  SCFree(copy);
754  return NULL;
755  }
756  copy_comp->pcap_buf = SCMalloc(copy_comp->pcap_buf_size);
757  if (copy_comp->pcap_buf == NULL) {
758  SCLogError("SCMalloc failed: %s", strerror(errno));
759  SCFree(copy_comp->buffer);
760  SCFree(copy->h);
761  SCFree(copy);
762  return NULL;
763  }
764  copy_comp->pcap_buf_wrapper = SCFmemopen(copy_comp->pcap_buf,
765  copy_comp->pcap_buf_size, "w");
766  if (copy_comp->pcap_buf_wrapper == NULL) {
767  SCLogError("SCFmemopen failed: %s", strerror(errno));
768  SCFree(copy_comp->buffer);
769  SCFree(copy_comp->pcap_buf);
770  SCFree(copy->h);
771  SCFree(copy);
772  return NULL;
773  }
774 
775  /* Initialize a new compression context. */
776 
777  LZ4F_errorCode_t errcode =
778  LZ4F_createCompressionContext(&copy_comp->lz4f_context, 1);
779  if (LZ4F_isError(errcode)) {
780  SCLogError("LZ4F_createCompressionContext failed: %s", LZ4F_getErrorName(errcode));
781  fclose(copy_comp->pcap_buf_wrapper);
782  SCFree(copy_comp->buffer);
783  SCFree(copy_comp->pcap_buf);
784  SCFree(copy->h);
785  SCFree(copy);
786  return NULL;
787  }
788 
789  /* Initialize the rest. */
790 
791  copy_comp->file = NULL;
792  copy_comp->bytes_in_block = 0;
793  }
794 #endif /* HAVE_LIBLZ4 */
795 
796  TAILQ_INIT(&copy->pcap_file_list);
797  SCMutexInit(&copy->plog_lock, NULL);
798 
799  strlcpy(copy->dir, pl->dir, sizeof(copy->dir));
800 
801  for (int i = 0; i < pl->filename_part_cnt && i < MAX_TOKS; i++)
802  copy->filename_parts[i] = pl->filename_parts[i];
803  copy->filename_part_cnt = pl->filename_part_cnt;
804 
805  /* set thread number, first thread is 1 */
806  copy->thread_number = SC_ATOMIC_ADD(thread_cnt, 1);
807 
808  SCLogDebug("copied, returning %p", copy);
809  return copy;
810 }
811 
812 #ifdef INIT_RING_BUFFER
813 static int PcapLogGetTimeOfFile(const char *filename, uint64_t *secs,
814  uint32_t *usecs)
815 {
816  char buf[PATH_MAX];
817  size_t copylen;
818 
819  int n = pcre2_match(pcre_timestamp_code, (PCRE2_SPTR8)filename, strlen(filename), 0, 0,
820  pcre_timestamp_match, NULL);
821  if (n != 2 && n != 4) {
822  /* No match. */
823  return 0;
824  }
825 
826  if (n >= 2) {
827  /* Extract seconds. */
828  copylen = sizeof(buf);
829  if (pcre2_substring_copy_bynumber(pcre_timestamp_match, 1, (PCRE2_UCHAR8 *)buf, &copylen) <
830  0) {
831  return 0;
832  }
833  if (StringParseUint64(secs, 10, 0, buf) < 0) {
834  return 0;
835  }
836  }
837  if (n == 4) {
838  /* Extract microseconds. */
839  copylen = sizeof(buf);
840  if (pcre2_substring_copy_bynumber(pcre_timestamp_match, 3, (PCRE2_UCHAR8 *)buf, &copylen) <
841  0) {
842  return 0;
843  }
844  if (StringParseUint32(usecs, 10, 0, buf) < 0) {
845  return 0;
846  }
847  }
848 
849  return 1;
850 }
851 
852 static TmEcode PcapLogInitRingBuffer(PcapLogData *pl)
853 {
854  char pattern[PATH_MAX];
855 
856  SCLogInfo("Initializing PCAP ring buffer for %s/%s.",
857  pl->dir, pl->prefix);
858 
859  strlcpy(pattern, pl->dir, PATH_MAX);
860  if (pattern[strlen(pattern) - 1] != '/') {
861  strlcat(pattern, "/", PATH_MAX);
862  }
863  if (pl->mode == LOGMODE_MULTI) {
864  for (int i = 0; i < pl->filename_part_cnt; i++) {
865  char *part = pl->filename_parts[i];
866  if (part == NULL || strlen(part) == 0) {
867  continue;
868  }
869  if (part[0] != '%' || strlen(part) < 2) {
870  strlcat(pattern, part, PATH_MAX);
871  continue;
872  }
873  switch (part[1]) {
874  case 'i':
875  SCLogError("Thread ID not allowed in ring buffer mode.");
876  return TM_ECODE_FAILED;
877  case 'n': {
878  char tmp[PATH_MAX];
879  snprintf(tmp, PATH_MAX, "%"PRIu32, pl->thread_number);
880  strlcat(pattern, tmp, PATH_MAX);
881  break;
882  }
883  case 't':
884  strlcat(pattern, "*", PATH_MAX);
885  break;
886  default:
887  SCLogError("Unsupported format character: %%%s", part);
888  return TM_ECODE_FAILED;
889  }
890  }
891  } else {
892  strlcat(pattern, pl->prefix, PATH_MAX);
893  strlcat(pattern, ".*", PATH_MAX);
894  }
895  strlcat(pattern, pl->suffix, PATH_MAX);
896 
897  char *basename = strrchr(pattern, '/');
898  *basename++ = '\0';
899 
900  /* Pattern is now just the directory name. */
901  DIR *dir = opendir(pattern);
902  if (dir == NULL) {
903  SCLogWarning("Failed to open directory %s: %s", pattern, strerror(errno));
904  return TM_ECODE_FAILED;
905  }
906 
907  for (;;) {
908  struct dirent *entry = readdir(dir);
909  if (entry == NULL) {
910  break;
911  }
912  if (fnmatch(basename, entry->d_name, 0) != 0) {
913  continue;
914  }
915 
916  uint64_t secs = 0;
917  uint32_t usecs = 0;
918 
919  if (!PcapLogGetTimeOfFile(entry->d_name, &secs, &usecs)) {
920  /* Failed to get time stamp out of file name. Not necessarily a
921  * failure as the file might just not be a pcap log file. */
922  continue;
923  }
924 
925  PcapFileName *pf = SCCalloc(sizeof(*pf), 1);
926  if (unlikely(pf == NULL)) {
927  goto fail;
928  }
929  char path[PATH_MAX];
930  if (snprintf(path, PATH_MAX, "%s/%s", pattern, entry->d_name) == PATH_MAX)
931  goto fail;
932 
933  if ((pf->filename = SCStrdup(path)) == NULL) {
934  goto fail;
935  }
936  if ((pf->dirname = SCStrdup(pattern)) == NULL) {
937  goto fail;
938  }
939  pf->secs = secs;
940  pf->usecs = usecs;
941 
942  if (TAILQ_EMPTY(&pl->pcap_file_list)) {
943  TAILQ_INSERT_TAIL(&pl->pcap_file_list, pf, next);
944  } else {
945  /* Ordered insert. */
946  PcapFileName *it = NULL;
947  TAILQ_FOREACH(it, &pl->pcap_file_list, next) {
948  if (pf->secs < it->secs) {
949  break;
950  } else if (pf->secs == it->secs && pf->usecs < it->usecs) {
951  break;
952  }
953  }
954  if (it == NULL) {
955  TAILQ_INSERT_TAIL(&pl->pcap_file_list, pf, next);
956  } else {
957  TAILQ_INSERT_BEFORE(it, pf, next);
958  }
959  }
960  pl->file_cnt++;
961  continue;
962 
963  fail:
964  if (pf != NULL) {
965  if (pf->filename != NULL) {
966  SCFree(pf->filename);
967  }
968  if (pf->dirname != NULL) {
969  SCFree(pf->dirname);
970  }
971  SCFree(pf);
972  }
973  break;
974  }
975 
976  if (pl->file_cnt > pl->max_files) {
977  PcapFileName *pf = TAILQ_FIRST(&pl->pcap_file_list);
978  while (pf != NULL && pl->file_cnt > pl->max_files) {
979  TAILQ_REMOVE(&pl->pcap_file_list, pf, next);
980 
981  SCLogDebug("Removing PCAP file %s", pf->filename);
982  if (remove(pf->filename) != 0) {
983  SCLogWarning("Failed to remove PCAP file %s: %s", pf->filename, strerror(errno));
984  }
985  PcapFileNameFree(pf);
986  pl->file_cnt--;
987 
988  pf = TAILQ_FIRST(&pl->pcap_file_list);
989  }
990  }
991 
992  closedir(dir);
993 
994  /* For some reason file count is initialized at one, instead of 0. */
995  SCLogNotice("Ring buffer initialized with %d files.", pl->file_cnt - 1);
996 
997  return TM_ECODE_OK;
998 }
999 #endif /* INIT_RING_BUFFER */
1000 
1001 static TmEcode PcapLogDataInit(ThreadVars *t, const void *initdata, void **data)
1002 {
1003  if (initdata == NULL) {
1004  SCLogDebug("Error getting context for LogPcap. \"initdata\" argument NULL");
1005  return TM_ECODE_FAILED;
1006  }
1007 
1008  PcapLogData *pl = ((OutputCtx *)initdata)->data;
1009 
1010  PcapLogThreadData *td = SCCalloc(1, sizeof(*td));
1011  if (unlikely(td == NULL))
1012  return TM_ECODE_FAILED;
1013 
1014  if (pl->mode == LOGMODE_MULTI)
1015  td->pcap_log = PcapLogDataCopy(pl);
1016  else
1017  td->pcap_log = pl;
1018  BUG_ON(td->pcap_log == NULL);
1019 
1020  if (DatalinkHasMultipleValues()) {
1021  if (pl->mode != LOGMODE_MULTI) {
1022  FatalError("Pcap logging with multiple link type is not supported.");
1023  } else {
1024  /* In multi mode, only pcap conditional is not supported as a flow timeout
1025  * will trigger packet logging with potentially invalid datalink. In regular
1026  * pcap logging, the logging should be done in the same thread if we
1027  * have a proper load balancing. So no mix of datalink should occur. But we need a
1028  * proper load balancing so this needs at least a warning.
1029  */
1030  switch (pl->conditional) {
1031  case LOGMODE_COND_ALERTS:
1032  case LOGMODE_COND_TAG:
1033  FatalError("Can't have multiple link types in pcap conditional mode.");
1034  break;
1035  default:
1036  SCLogWarning("Using multiple link types can result in invalid pcap output");
1037  }
1038  }
1039  }
1040 
1041  PcapLogLock(td->pcap_log);
1042 
1043  /** Use the Output Context (file pointer and mutex) */
1044  td->pcap_log->pkt_cnt = 0;
1045  td->pcap_log->pcap_dead_handle = NULL;
1046  td->pcap_log->pcap_dumper = NULL;
1047  if (td->pcap_log->file_cnt < 1) {
1048  td->pcap_log->file_cnt = 1;
1049  }
1050 
1051  SCTime_t ts = TimeGet();
1052  struct tm local_tm;
1053  struct tm *tms = SCLocalTime(SCTIME_SECS(ts), &local_tm);
1054  td->pcap_log->prev_day = tms->tm_mday;
1055 
1056  PcapLogUnlock(td->pcap_log);
1057 
1058  /* count threads in the global structure */
1059  SCMutexLock(&pl->plog_lock);
1060  pl->threads++;
1061  SCMutexUnlock(&pl->plog_lock);
1062 
1063  *data = (void *)td;
1064 
1067  } else {
1068  td->buf = NULL;
1069  }
1070 
1071  if (pl->max_files && (pl->mode == LOGMODE_MULTI || pl->threads == 1)) {
1072 #ifdef INIT_RING_BUFFER
1073  if (PcapLogInitRingBuffer(td->pcap_log) == TM_ECODE_FAILED) {
1074  return TM_ECODE_FAILED;
1075  }
1076 #else
1077  SCLogInfo("Unable to initialize ring buffer on this platform.");
1078 #endif /* INIT_RING_BUFFER */
1079  }
1080 
1081  /* Don't early initialize output files if in a PCAP file (offline)
1082  * mode. */
1083  if (!IsRunModeOffline(SCRunmodeGet())) {
1084  if (pl->mode == LOGMODE_MULTI) {
1085  PcapLogOpenFileCtx(td->pcap_log);
1086  } else {
1087  if (pl->filename == NULL) {
1088  PcapLogOpenFileCtx(pl);
1089  }
1090  }
1091  }
1092 
1093  return TM_ECODE_OK;
1094 }
1095 
1096 static void StatsMerge(PcapLogData *dst, PcapLogData *src)
1097 {
1098  dst->profile_open.total += src->profile_open.total;
1099  dst->profile_open.cnt += src->profile_open.cnt;
1100 
1101  dst->profile_close.total += src->profile_close.total;
1102  dst->profile_close.cnt += src->profile_close.cnt;
1103 
1104  dst->profile_write.total += src->profile_write.total;
1105  dst->profile_write.cnt += src->profile_write.cnt;
1106 
1107  dst->profile_rotate.total += src->profile_rotate.total;
1108  dst->profile_rotate.cnt += src->profile_rotate.cnt;
1109 
1110  dst->profile_handles.total += src->profile_handles.total;
1111  dst->profile_handles.cnt += src->profile_handles.cnt;
1112 
1113  dst->profile_lock.total += src->profile_lock.total;
1114  dst->profile_lock.cnt += src->profile_lock.cnt;
1115 
1116  dst->profile_unlock.total += src->profile_unlock.total;
1117  dst->profile_unlock.cnt += src->profile_unlock.cnt;
1118 
1119  dst->profile_data_size += src->profile_data_size;
1120 }
1121 
1122 static void PcapLogDataFree(PcapLogData *pl)
1123 {
1124 
1125  PcapFileName *pf;
1126  while ((pf = TAILQ_FIRST(&pl->pcap_file_list)) != NULL) {
1127  TAILQ_REMOVE(&pl->pcap_file_list, pf, next);
1128  PcapFileNameFree(pf);
1129  }
1130  if (pl == g_pcap_data) {
1131  for (int i = 0; i < MAX_TOKS; i++) {
1132  if (pl->filename_parts[i] != NULL) {
1133  SCFree(pl->filename_parts[i]);
1134  }
1135  }
1136  }
1137  SCFree(pl->h);
1138  SCFree(pl->filename);
1139  SCFree(pl->prefix);
1140 
1141  if (pl->pcap_dead_handle) {
1142  pcap_close(pl->pcap_dead_handle);
1143  }
1144 
1145 #ifdef HAVE_LIBLZ4
1146  if (pl->compression.format == PCAP_LOG_COMPRESSION_FORMAT_LZ4) {
1147  SCFree(pl->compression.buffer);
1148  fclose(pl->compression.pcap_buf_wrapper);
1149  SCFree(pl->compression.pcap_buf);
1150  LZ4F_errorCode_t errcode =
1151  LZ4F_freeCompressionContext(pl->compression.lz4f_context);
1152  if (LZ4F_isError(errcode)) {
1153  SCLogWarning("Error freeing lz4 context.");
1154  }
1155  }
1156 #endif /* HAVE_LIBLZ4 */
1157  SCFree(pl);
1158 }
1159 
1160 /**
1161  * \brief Thread deinit function.
1162  *
1163  * \param t Thread Variable containing input/output queue, cpu affinity etc.
1164  * \param data PcapLog thread data.
1165  * \retval TM_ECODE_OK on success
1166  * \retval TM_ECODE_FAILED on failure
1167  */
1168 static TmEcode PcapLogDataDeinit(ThreadVars *t, void *thread_data)
1169 {
1170  PcapLogThreadData *td = (PcapLogThreadData *)thread_data;
1171  PcapLogData *pl = td->pcap_log;
1172 
1173  if (pl->pcap_dumper != NULL) {
1174  if (PcapLogCloseFile(t,pl) < 0) {
1175  SCLogDebug("PcapLogCloseFile failed");
1176  }
1177  }
1178 
1179  if (pl->mode == LOGMODE_MULTI) {
1180  SCMutexLock(&g_pcap_data->plog_lock);
1181  StatsMerge(g_pcap_data, pl);
1182  g_pcap_data->reported++;
1183  if (g_pcap_data->threads == g_pcap_data->reported)
1184  PcapLogProfilingDump(g_pcap_data);
1185  SCMutexUnlock(&g_pcap_data->plog_lock);
1186  } else {
1187  if (pl->reported == 0) {
1188  PcapLogProfilingDump(pl);
1189  pl->reported = 1;
1190  }
1191  }
1192 
1193  if (pl != g_pcap_data) {
1194  PcapLogDataFree(pl);
1195  }
1196 
1197  if (td->buf)
1198  MemBufferFree(td->buf);
1199 
1200  SCFree(td);
1201  return TM_ECODE_OK;
1202 }
1203 
1204 
1205 static int ParseFilename(PcapLogData *pl, const char *filename)
1206 {
1207  char *toks[MAX_TOKS] = { NULL };
1208  int tok = 0;
1209  char str[MAX_FILENAMELEN] = "";
1210  int s = 0;
1211  char *p = NULL;
1212  size_t filename_len = 0;
1213 
1214  if (filename) {
1215  filename_len = strlen(filename);
1216  if (filename_len > (MAX_FILENAMELEN-1)) {
1217  SCLogError("invalid filename option. Max filename-length: %d", MAX_FILENAMELEN - 1);
1218  goto error;
1219  }
1220 
1221  for (int i = 0; i < (int)strlen(filename); i++) {
1222  if (tok >= MAX_TOKS) {
1223  SCLogError("invalid filename option. Max 2 %%-sign options");
1224  goto error;
1225  }
1226 
1227  str[s++] = filename[i];
1228 
1229  if (filename[i] == '%') {
1230  str[s-1] = '\0';
1231  SCLogDebug("filename with %%-sign: %s", str);
1232 
1233  p = SCStrdup(str);
1234  if (p == NULL)
1235  goto error;
1236  toks[tok++] = p;
1237 
1238  s = 0;
1239 
1240  if (i+1 < (int)strlen(filename)) {
1241  if (tok >= MAX_TOKS) {
1242  SCLogError("invalid filename option. Max 2 %%-sign options");
1243  goto error;
1244  }
1245 
1246  if (filename[i+1] != 'n' && filename[i+1] != 't' && filename[i+1] != 'i') {
1247  SCLogError(
1248  "invalid filename option. Valid %%-sign options: %%n, %%i and %%t");
1249  goto error;
1250  }
1251  str[0] = '%';
1252  str[1] = filename[i+1];
1253  str[2] = '\0';
1254  p = SCStrdup(str);
1255  if (p == NULL)
1256  goto error;
1257  toks[tok++] = p;
1258  i++;
1259  }
1260  }
1261  }
1262 
1263  if ((tok == 0) && (pl->mode == LOGMODE_MULTI)) {
1264  SCLogError("Invalid filename for multimode. Need at least one %%-sign option");
1265  goto error;
1266  }
1267 
1268  if (s) {
1269  if (tok >= MAX_TOKS) {
1270  SCLogError("invalid filename option. Max 3 %%-sign options");
1271  goto error;
1272 
1273  }
1274  str[s++] = '\0';
1275  p = SCStrdup(str);
1276  if (p == NULL)
1277  goto error;
1278  toks[tok++] = p;
1279  }
1280 
1281  /* finally, store tokens in the pl */
1282  for (int i = 0; i < tok; i++) {
1283  if (toks[i] == NULL)
1284  goto error;
1285 
1286  SCLogDebug("toks[%d] %s", i, toks[i]);
1287  pl->filename_parts[i] = toks[i];
1288  }
1289  pl->filename_part_cnt = tok;
1290  }
1291  return 0;
1292 error:
1293  for (int x = 0; x < MAX_TOKS; x++) {
1294  if (toks[x] != NULL)
1295  SCFree(toks[x]);
1296  }
1297  return -1;
1298 }
1299 
1300 /** \brief Fill in pcap logging struct from the provided ConfNode.
1301  * \param conf The configuration node for this output.
1302  * \retval output_ctx
1303  * */
1304 static OutputInitResult PcapLogInitCtx(ConfNode *conf)
1305 {
1306  OutputInitResult result = { NULL, false };
1307  int en;
1308  PCRE2_SIZE eo = 0;
1309 
1310  PcapLogData *pl = SCCalloc(1, sizeof(PcapLogData));
1311  if (unlikely(pl == NULL)) {
1312  FatalError("Failed to allocate Memory for PcapLogData");
1313  }
1314 
1315  pl->h = SCMalloc(sizeof(*pl->h));
1316  if (pl->h == NULL) {
1317  FatalError("Failed to allocate Memory for pcap header struct");
1318  }
1319 
1320  /* Set the defaults */
1321  pl->mode = LOGMODE_NORMAL;
1323  pl->use_ringbuffer = RING_BUFFER_MODE_DISABLED;
1324  pl->timestamp_format = TS_FORMAT_SEC;
1328 
1329  TAILQ_INIT(&pl->pcap_file_list);
1330 
1331  SCMutexInit(&pl->plog_lock, NULL);
1332 
1333  /* Initialize PCREs. */
1334  pcre_timestamp_code =
1335  pcre2_compile((PCRE2_SPTR8)timestamp_pattern, PCRE2_ZERO_TERMINATED, 0, &en, &eo, NULL);
1336  if (pcre_timestamp_code == NULL) {
1337  PCRE2_UCHAR errbuffer[256];
1338  pcre2_get_error_message(en, errbuffer, sizeof(errbuffer));
1339  FatalError(
1340  "Failed to compile \"%s\" at offset %d: %s", timestamp_pattern, (int)eo, errbuffer);
1341  }
1342  pcre_timestamp_match = pcre2_match_data_create_from_pattern(pcre_timestamp_code, NULL);
1343 
1344  /* conf params */
1345 
1346  const char *filename = NULL;
1347 
1348  if (conf != NULL) { /* To facilitate unit tests. */
1349  filename = ConfNodeLookupChildValue(conf, "filename");
1350  }
1351 
1352  if (filename == NULL)
1353  filename = DEFAULT_LOG_FILENAME;
1354 
1355  if ((pl->prefix = SCStrdup(filename)) == NULL) {
1356  exit(EXIT_FAILURE);
1357  }
1358 
1359  pl->suffix = "";
1360 
1361  pl->size_limit = DEFAULT_LIMIT;
1362  if (conf != NULL) {
1363  const char *s_limit = NULL;
1364  s_limit = ConfNodeLookupChildValue(conf, "limit");
1365  if (s_limit != NULL) {
1366  if (ParseSizeStringU64(s_limit, &pl->size_limit) < 0) {
1367  SCLogError("Failed to initialize pcap output, invalid limit: %s", s_limit);
1368  exit(EXIT_FAILURE);
1369  }
1370  if (pl->size_limit < 4096) {
1371  SCLogInfo("pcap-log \"limit\" value of %"PRIu64" assumed to be pre-1.2 "
1372  "style: setting limit to %"PRIu64"mb", pl->size_limit, pl->size_limit);
1373  uint64_t size = pl->size_limit * 1024 * 1024;
1374  pl->size_limit = size;
1375  } else if (pl->size_limit < MIN_LIMIT) {
1376  FatalError("Fail to initialize pcap-log output, limit less than "
1377  "allowed minimum of %d bytes.",
1378  MIN_LIMIT);
1379  }
1380  }
1381  }
1382 
1383  if (conf != NULL) {
1384  const char *s_mode = NULL;
1385  s_mode = ConfNodeLookupChildValue(conf, "mode");
1386  if (s_mode != NULL) {
1387  if (strcasecmp(s_mode, "multi") == 0) {
1388  pl->mode = LOGMODE_MULTI;
1389  } else if (strcasecmp(s_mode, "normal") != 0) {
1390  FatalError("log-pcap: invalid mode \"%s\". Valid options: \"normal\""
1391  "or \"multi\" mode ",
1392  s_mode);
1393  }
1394  }
1395 
1396  const char *s_dir = NULL;
1397  s_dir = ConfNodeLookupChildValue(conf, "dir");
1398  if (s_dir == NULL) {
1399  const char *log_dir = NULL;
1400  log_dir = ConfigGetLogDirectory();
1401 
1402  strlcpy(pl->dir, log_dir, sizeof(pl->dir));
1403  SCLogInfo("Using log dir %s", pl->dir);
1404  } else {
1405  if (PathIsAbsolute(s_dir)) {
1406  strlcpy(pl->dir,
1407  s_dir, sizeof(pl->dir));
1408  } else {
1409  const char *log_dir = NULL;
1410  log_dir = ConfigGetLogDirectory();
1411 
1412  snprintf(pl->dir, sizeof(pl->dir), "%s/%s",
1413  log_dir, s_dir);
1414  }
1415 
1416  struct stat stat_buf;
1417  if (stat(pl->dir, &stat_buf) != 0) {
1418  FatalError("The dir directory \"%s\" "
1419  "supplied doesn't exist. Shutting down the engine",
1420  pl->dir);
1421  }
1422  SCLogInfo("Using log dir %s", pl->dir);
1423  }
1424 
1425  const char *compression_str = ConfNodeLookupChildValue(conf,
1426  "compression");
1427 
1428  PcapLogCompressionData *comp = &pl->compression;
1429  if (compression_str == NULL || strcmp(compression_str, "none") == 0) {
1431  comp->buffer = NULL;
1432  comp->buffer_size = 0;
1433  comp->file = NULL;
1434  comp->pcap_buf = NULL;
1435  comp->pcap_buf_size = 0;
1436  comp->pcap_buf_wrapper = NULL;
1437  } else if (strcmp(compression_str, "lz4") == 0) {
1438 #ifdef HAVE_LIBLZ4
1439  pl->compression.format = PCAP_LOG_COMPRESSION_FORMAT_LZ4;
1440 
1441  /* Use SCFmemopen so we can make pcap_dump write to a buffer. */
1442 
1443  comp->pcap_buf_size = sizeof(struct pcap_file_header) +
1444  sizeof(struct pcap_pkthdr) + PCAP_SNAPLEN;
1445  comp->pcap_buf = SCMalloc(comp->pcap_buf_size);
1446  if (comp->pcap_buf == NULL) {
1447  SCLogError("SCMalloc failed: %s", strerror(errno));
1448  exit(EXIT_FAILURE);
1449  }
1450  comp->pcap_buf_wrapper = SCFmemopen(comp->pcap_buf,
1451  comp->pcap_buf_size, "w");
1452  if (comp->pcap_buf_wrapper == NULL) {
1453  SCLogError("SCFmemopen failed: %s", strerror(errno));
1454  exit(EXIT_FAILURE);
1455  }
1456 
1457  /* Set lz4 preferences. */
1458 
1459  memset(&comp->lz4f_prefs, '\0', sizeof(comp->lz4f_prefs));
1460  comp->lz4f_prefs.frameInfo.blockSizeID = LZ4F_max4MB;
1461  comp->lz4f_prefs.frameInfo.blockMode = LZ4F_blockLinked;
1462  if (ConfNodeChildValueIsTrue(conf, "lz4-checksum")) {
1463  comp->lz4f_prefs.frameInfo.contentChecksumFlag = 1;
1464  }
1465  else {
1466  comp->lz4f_prefs.frameInfo.contentChecksumFlag = 0;
1467  }
1468  intmax_t lvl = 0;
1469  if (ConfGetChildValueInt(conf, "lz4-level", &lvl)) {
1470  if (lvl > 16) {
1471  lvl = 16;
1472  } else if (lvl < 0) {
1473  lvl = 0;
1474  }
1475  } else {
1476  lvl = 0;
1477  }
1478  comp->lz4f_prefs.compressionLevel = (int)lvl;
1479 
1480  /* Allocate resources for lz4. */
1481 
1482  LZ4F_errorCode_t errcode =
1483  LZ4F_createCompressionContext(&pl->compression.lz4f_context, 1);
1484 
1485  if (LZ4F_isError(errcode)) {
1486  SCLogError("LZ4F_createCompressionContext failed: %s", LZ4F_getErrorName(errcode));
1487  exit(EXIT_FAILURE);
1488  }
1489 
1490  /* Calculate the size of the lz4 output buffer. */
1491 
1492  comp->buffer_size = LZ4F_compressBound(comp->pcap_buf_size,
1493  &comp->lz4f_prefs);
1494 
1495  comp->buffer = SCMalloc(comp->buffer_size);
1496  if (unlikely(comp->buffer == NULL)) {
1497  FatalError("Failed to allocate memory for "
1498  "lz4 output buffer.");
1499  }
1500 
1501  comp->bytes_in_block = 0;
1502 
1503  /* Add the lz4 file extension to the log files. */
1504 
1505  pl->suffix = ".lz4";
1506 #else
1507  SCLogError("lz4 compression was selected "
1508  "in pcap-log, but suricata was not compiled with lz4 "
1509  "support.");
1510  PcapLogDataFree(pl);
1511  return result;
1512 #endif /* HAVE_LIBLZ4 */
1513  }
1514  else {
1515  SCLogError("Unsupported pcap-log "
1516  "compression format: %s",
1517  compression_str);
1518  PcapLogDataFree(pl);
1519  return result;
1520  }
1521 
1522  SCLogInfo("Selected pcap-log compression method: %s",
1523  compression_str ? compression_str : "none");
1524 
1525  const char *s_conditional = ConfNodeLookupChildValue(conf, "conditional");
1526  if (s_conditional != NULL) {
1527  if (strcasecmp(s_conditional, "alerts") == 0) {
1530  } else if (strcasecmp(s_conditional, "tag") == 0) {
1533  } else if (strcasecmp(s_conditional, "all") != 0) {
1534  FatalError("log-pcap: invalid conditional \"%s\". Valid options: \"all\", "
1535  "\"alerts\", or \"tag\" mode ",
1536  s_conditional);
1537  }
1538  }
1539 
1540  SCLogInfo(
1541  "Selected pcap-log conditional logging: %s", s_conditional ? s_conditional : "all");
1542  }
1543 
1544  if (ParseFilename(pl, filename) != 0)
1545  exit(EXIT_FAILURE);
1546 
1547  SCLogInfo("using %s logging", (pl->mode == LOGMODE_MULTI ? "multi" : "normal"));
1548 
1549  uint32_t max_file_limit = DEFAULT_FILE_LIMIT;
1550  if (conf != NULL) {
1551  const char *max_number_of_files_s = NULL;
1552  max_number_of_files_s = ConfNodeLookupChildValue(conf, "max-files");
1553  if (max_number_of_files_s != NULL) {
1554  if (StringParseUint32(&max_file_limit, 10, 0,
1555  max_number_of_files_s) == -1) {
1556  SCLogError("Failed to initialize "
1557  "pcap-log output, invalid number of files limit: %s",
1558  max_number_of_files_s);
1559  exit(EXIT_FAILURE);
1560  } else if (max_file_limit < 1) {
1561  FatalError("Failed to initialize pcap-log output, limit less than "
1562  "allowed minimum.");
1563  } else {
1564  pl->max_files = max_file_limit;
1565  pl->use_ringbuffer = RING_BUFFER_MODE_ENABLED;
1566  }
1567  }
1568  }
1569 
1570  const char *ts_format = NULL;
1571  if (conf != NULL) { /* To facilitate unit tests. */
1572  ts_format = ConfNodeLookupChildValue(conf, "ts-format");
1573  }
1574  if (ts_format != NULL) {
1575  if (strcasecmp(ts_format, "usec") == 0) {
1576  pl->timestamp_format = TS_FORMAT_USEC;
1577  } else if (strcasecmp(ts_format, "sec") != 0) {
1578  SCLogError("log-pcap ts_format specified %s is invalid must be"
1579  " \"sec\" or \"usec\"",
1580  ts_format);
1581  exit(EXIT_FAILURE);
1582  }
1583  }
1584 
1585  const char *use_stream_depth = NULL;
1586  if (conf != NULL) { /* To facilitate unit tests. */
1587  use_stream_depth = ConfNodeLookupChildValue(conf, "use-stream-depth");
1588  }
1589  if (use_stream_depth != NULL) {
1590  if (ConfValIsFalse(use_stream_depth)) {
1592  } else if (ConfValIsTrue(use_stream_depth)) {
1594  } else {
1595  FatalError("log-pcap use_stream_depth specified is invalid must be");
1596  }
1597  }
1598 
1599  const char *honor_pass_rules = NULL;
1600  if (conf != NULL) { /* To facilitate unit tests. */
1601  honor_pass_rules = ConfNodeLookupChildValue(conf, "honor-pass-rules");
1602  }
1603  if (honor_pass_rules != NULL) {
1604  if (ConfValIsFalse(honor_pass_rules)) {
1606  } else if (ConfValIsTrue(honor_pass_rules)) {
1608  } else {
1609  FatalError("log-pcap honor-pass-rules specified is invalid");
1610  }
1611  }
1612 
1613  /* create the output ctx and send it back */
1614 
1615  OutputCtx *output_ctx = SCCalloc(1, sizeof(OutputCtx));
1616  if (unlikely(output_ctx == NULL)) {
1617  FatalError("Failed to allocate memory for OutputCtx.");
1618  }
1619  output_ctx->data = pl;
1620  output_ctx->DeInit = PcapLogFileDeInitCtx;
1621  g_pcap_data = pl;
1622 
1623  result.ctx = output_ctx;
1624  result.ok = true;
1625  return result;
1626 }
1627 
1628 static void PcapLogFileDeInitCtx(OutputCtx *output_ctx)
1629 {
1630  if (output_ctx == NULL)
1631  return;
1632 
1633  PcapLogData *pl = output_ctx->data;
1634 
1635  PcapFileName *pf = NULL;
1636  TAILQ_FOREACH(pf, &pl->pcap_file_list, next) {
1637  SCLogDebug("PCAP files left at exit: %s\n", pf->filename);
1638  }
1639  PcapLogDataFree(pl);
1640  SCFree(output_ctx);
1641 
1642  pcre2_code_free(pcre_timestamp_code);
1643  pcre2_match_data_free(pcre_timestamp_match);
1644 }
1645 
1646 /**
1647  * \brief Read the config set the file pointer, open the file
1648  *
1649  * \param PcapLogData.
1650  *
1651  * \retval -1 if failure
1652  * \retval 0 if succesful
1653  */
1654 static int PcapLogOpenFileCtx(PcapLogData *pl)
1655 {
1656  char *filename = NULL;
1657 
1659 
1660  if (pl->filename != NULL)
1661  filename = pl->filename;
1662  else {
1663  filename = SCMalloc(PATH_MAX);
1664  if (unlikely(filename == NULL)) {
1665  return -1;
1666  }
1667  pl->filename = filename;
1668  }
1669 
1670  /** get the time so we can have a filename with seconds since epoch */
1671  SCTime_t ts = TimeGet();
1672 
1673  /* Place to store the name of our PCAP file */
1674  PcapFileName *pf = SCCalloc(1, sizeof(PcapFileName));
1675  if (unlikely(pf == NULL)) {
1676  return -1;
1677  }
1678 
1679  if (pl->mode == LOGMODE_NORMAL) {
1680  int ret;
1681  /* create the filename to use */
1682  if (pl->timestamp_format == TS_FORMAT_SEC) {
1683  ret = snprintf(filename, PATH_MAX, "%s/%s.%" PRIu32 "%s", pl->dir, pl->prefix,
1684  (uint32_t)SCTIME_SECS(ts), pl->suffix);
1685  } else {
1686  ret = snprintf(filename, PATH_MAX, "%s/%s.%" PRIu32 ".%" PRIu32 "%s", pl->dir,
1687  pl->prefix, (uint32_t)SCTIME_SECS(ts), (uint32_t)SCTIME_USECS(ts), pl->suffix);
1688  }
1689  if (ret < 0 || (size_t)ret >= PATH_MAX) {
1690  SCLogError("failed to construct path");
1691  goto error;
1692  }
1693  } else if (pl->mode == LOGMODE_MULTI) {
1694  if (pl->filename_part_cnt > 0) {
1695  /* assemble filename from stored tokens */
1696 
1697  strlcpy(filename, pl->dir, PATH_MAX);
1698  strlcat(filename, "/", PATH_MAX);
1699 
1700  for (int i = 0; i < pl->filename_part_cnt; i++) {
1701  if (pl->filename_parts[i] == NULL ||strlen(pl->filename_parts[i]) == 0)
1702  continue;
1703 
1704  /* handle variables */
1705  if (pl->filename_parts[i][0] == '%') {
1706  char str[64] = "";
1707  if (strlen(pl->filename_parts[i]) < 2)
1708  continue;
1709 
1710  switch(pl->filename_parts[i][1]) {
1711  case 'n':
1712  snprintf(str, sizeof(str), "%u", pl->thread_number);
1713  break;
1714  case 'i':
1715  {
1716  long thread_id = SCGetThreadIdLong();
1717  snprintf(str, sizeof(str), "%"PRIu64, (uint64_t)thread_id);
1718  break;
1719  }
1720  case 't':
1721  /* create the filename to use */
1722  if (pl->timestamp_format == TS_FORMAT_SEC) {
1723  snprintf(str, sizeof(str), "%" PRIu32, (uint32_t)SCTIME_SECS(ts));
1724  } else {
1725  snprintf(str, sizeof(str), "%" PRIu32 ".%" PRIu32,
1726  (uint32_t)SCTIME_SECS(ts), (uint32_t)SCTIME_USECS(ts));
1727  }
1728  }
1729  strlcat(filename, str, PATH_MAX);
1730 
1731  /* copy the rest over */
1732  } else {
1733  strlcat(filename, pl->filename_parts[i], PATH_MAX);
1734  }
1735  }
1736  strlcat(filename, pl->suffix, PATH_MAX);
1737  } else {
1738  int ret;
1739  /* create the filename to use */
1740  if (pl->timestamp_format == TS_FORMAT_SEC) {
1741  ret = snprintf(filename, PATH_MAX, "%s/%s.%u.%" PRIu32 "%s", pl->dir, pl->prefix,
1742  pl->thread_number, (uint32_t)SCTIME_SECS(ts), pl->suffix);
1743  } else {
1744  ret = snprintf(filename, PATH_MAX, "%s/%s.%u.%" PRIu32 ".%" PRIu32 "%s", pl->dir,
1745  pl->prefix, pl->thread_number, (uint32_t)SCTIME_SECS(ts),
1746  (uint32_t)SCTIME_USECS(ts), pl->suffix);
1747  }
1748  if (ret < 0 || (size_t)ret >= PATH_MAX) {
1749  SCLogError("failed to construct path");
1750  goto error;
1751  }
1752  }
1753  SCLogDebug("multi-mode: filename %s", filename);
1754  }
1755 
1756  if ((pf->filename = SCStrdup(pl->filename)) == NULL) {
1757  SCLogError("Error allocating memory. For filename");
1758  goto error;
1759  }
1760  SCLogDebug("Opening pcap file log %s", pf->filename);
1761  TAILQ_INSERT_TAIL(&pl->pcap_file_list, pf, next);
1762 
1763  if (pl->mode == LOGMODE_MULTI || pl->mode == LOGMODE_NORMAL) {
1764  pcap_file_thread = pl->filename;
1765  }
1767  return 0;
1768 
1769 error:
1770  PcapFileNameFree(pf);
1771  return -1;
1772 }
1773 
1775 {
1776  /* return pcap filename per thread */
1777  if (pcap_file_thread != NULL) {
1778  return pcap_file_thread;
1779  }
1780  return NULL;
1781 }
1782 
1783 static int profiling_pcaplog_enabled = 0;
1784 static int profiling_pcaplog_output_to_file = 0;
1785 static char *profiling_pcaplog_file_name = NULL;
1786 static const char *profiling_pcaplog_file_mode = "a";
1787 
1788 static void FormatNumber(uint64_t num, char *str, size_t size)
1789 {
1790  if (num < 1000UL)
1791  snprintf(str, size, "%"PRIu64, num);
1792  else if (num < 1000000UL)
1793  snprintf(str, size, "%3.1fk", (float)num/1000UL);
1794  else if (num < 1000000000UL)
1795  snprintf(str, size, "%3.1fm", (float)num/1000000UL);
1796  else
1797  snprintf(str, size, "%3.1fb", (float)num/1000000000UL);
1798 }
1799 
1800 static void ProfileReportPair(FILE *fp, const char *name, PcapLogProfileData *p)
1801 {
1802  char ticks_str[32] = "n/a";
1803  char cnt_str[32] = "n/a";
1804  char avg_str[32] = "n/a";
1805 
1806  FormatNumber((uint64_t)p->cnt, cnt_str, sizeof(cnt_str));
1807  FormatNumber((uint64_t)p->total, ticks_str, sizeof(ticks_str));
1808  if (p->cnt && p->total)
1809  FormatNumber((uint64_t)(p->total/p->cnt), avg_str, sizeof(avg_str));
1810 
1811  fprintf(fp, "%-28s %-10s %-10s %-10s\n", name, cnt_str, avg_str, ticks_str);
1812 }
1813 
1814 static void ProfileReport(FILE *fp, PcapLogData *pl)
1815 {
1816  ProfileReportPair(fp, "open", &pl->profile_open);
1817  ProfileReportPair(fp, "close", &pl->profile_close);
1818  ProfileReportPair(fp, "write", &pl->profile_write);
1819  ProfileReportPair(fp, "rotate (incl open/close)", &pl->profile_rotate);
1820  ProfileReportPair(fp, "handles", &pl->profile_handles);
1821  ProfileReportPair(fp, "lock", &pl->profile_lock);
1822  ProfileReportPair(fp, "unlock", &pl->profile_unlock);
1823 }
1824 
1825 static void FormatBytes(uint64_t num, char *str, size_t size)
1826 {
1827  if (num < 1000UL)
1828  snprintf(str, size, "%"PRIu64, num);
1829  else if (num < 1048576UL)
1830  snprintf(str, size, "%3.1fKiB", (float)num/1000UL);
1831  else if (num < 1073741824UL)
1832  snprintf(str, size, "%3.1fMiB", (float)num/1000000UL);
1833  else
1834  snprintf(str, size, "%3.1fGiB", (float)num/1000000000UL);
1835 }
1836 
1837 static void PcapLogProfilingDump(PcapLogData *pl)
1838 {
1839  FILE *fp = NULL;
1840 
1841  if (profiling_pcaplog_enabled == 0)
1842  return;
1843 
1844  if (profiling_pcaplog_output_to_file == 1) {
1845  fp = fopen(profiling_pcaplog_file_name, profiling_pcaplog_file_mode);
1846  if (fp == NULL) {
1847  SCLogError("failed to open %s: %s", profiling_pcaplog_file_name, strerror(errno));
1848  return;
1849  }
1850  } else {
1851  fp = stdout;
1852  }
1853 
1854  /* counters */
1855  fprintf(fp, "\n\nOperation Cnt Avg ticks Total ticks\n");
1856  fprintf(fp, "---------------------------- ---------- ---------- -----------\n");
1857 
1858  ProfileReport(fp, pl);
1859  uint64_t total = pl->profile_write.total + pl->profile_rotate.total +
1862  pl->profile_unlock.total;
1863 
1864  /* overall stats */
1865  fprintf(fp, "\nOverall: %"PRIu64" bytes written, average %d bytes per write.\n",
1867  (int)(pl->profile_data_size / pl->profile_write.cnt) : 0);
1868  fprintf(fp, " PCAP data structure overhead: %"PRIuMAX" per write.\n",
1869  (uintmax_t)sizeof(struct pcap_pkthdr));
1870 
1871  /* print total bytes written */
1872  char bytes_str[32];
1873  FormatBytes(pl->profile_data_size, bytes_str, sizeof(bytes_str));
1874  fprintf(fp, " Size written: %s\n", bytes_str);
1875 
1876  /* ticks per MiB and GiB */
1877  uint64_t ticks_per_mib = 0, ticks_per_gib = 0;
1878  uint64_t mib = pl->profile_data_size/(1024*1024);
1879  if (mib)
1880  ticks_per_mib = total/mib;
1881  char ticks_per_mib_str[32] = "n/a";
1882  if (ticks_per_mib > 0)
1883  FormatNumber(ticks_per_mib, ticks_per_mib_str, sizeof(ticks_per_mib_str));
1884  fprintf(fp, " Ticks per MiB: %s\n", ticks_per_mib_str);
1885 
1886  uint64_t gib = pl->profile_data_size/(1024*1024*1024);
1887  if (gib)
1888  ticks_per_gib = total/gib;
1889  char ticks_per_gib_str[32] = "n/a";
1890  if (ticks_per_gib > 0)
1891  FormatNumber(ticks_per_gib, ticks_per_gib_str, sizeof(ticks_per_gib_str));
1892  fprintf(fp, " Ticks per GiB: %s\n", ticks_per_gib_str);
1893 
1894  if (fp != stdout)
1895  fclose(fp);
1896 }
1897 
1899 {
1900  ConfNode *conf = ConfGetNode("profiling.pcap-log");
1901  if (conf != NULL && ConfNodeChildValueIsTrue(conf, "enabled")) {
1902  profiling_pcaplog_enabled = 1;
1903  SCLogInfo("pcap-log profiling enabled");
1904 
1905  const char *filename = ConfNodeLookupChildValue(conf, "filename");
1906  if (filename != NULL) {
1907  const char *log_dir;
1908  log_dir = ConfigGetLogDirectory();
1909 
1910  profiling_pcaplog_file_name = SCMalloc(PATH_MAX);
1911  if (unlikely(profiling_pcaplog_file_name == NULL)) {
1912  FatalError("can't duplicate file name");
1913  }
1914 
1915  snprintf(profiling_pcaplog_file_name, PATH_MAX, "%s/%s", log_dir, filename);
1916 
1917  const char *v = ConfNodeLookupChildValue(conf, "append");
1918  if (v == NULL || ConfValIsTrue(v)) {
1919  profiling_pcaplog_file_mode = "a";
1920  } else {
1921  profiling_pcaplog_file_mode = "w";
1922  }
1923 
1924  profiling_pcaplog_output_to_file = 1;
1925  SCLogInfo("pcap-log profiling output goes to %s (mode %s)",
1926  profiling_pcaplog_file_name, profiling_pcaplog_file_mode);
1927  }
1928  }
1929 }
util-byte.h
PcapLogCallbackContext::comp
PcapLogCompressionData * comp
Definition: log-pcap.c:529
PcapLogCompressionData_::pcap_buf_size
uint64_t pcap_buf_size
Definition: log-pcap.c:130
ConfGetChildValueInt
int ConfGetChildValueInt(const ConfNode *base, const char *name, intmax_t *val)
Definition: conf.c:434
PcapLogData
struct PcapLogData_ PcapLogData
PcapLogProfileData_
Definition: log-pcap.c:107
LOGMODE_COND_ALL
@ LOGMODE_COND_ALL
Definition: log-pcap.c:68
len
uint8_t len
Definition: app-layer-dnp3.h:2
ts
uint64_t ts
Definition: source-erf-file.c:55
PcapLogData_::conditional
LogModeConditionalType conditional
Definition: log-pcap.c:158
SCRunmodeGet
int SCRunmodeGet(void)
Get the current run mode.
Definition: suricata.c:264
PcapLogThreadData
struct PcapLogThreadData_ PcapLogThreadData
ConfNodeChildValueIsTrue
int ConfNodeChildValueIsTrue(const ConfNode *node, const char *key)
Test if a configuration node has a true value.
Definition: conf.c:854
MemBuffer_::buffer
uint8_t buffer[]
Definition: util-buffer.h:30
IsTcpSessionDumpingEnabled
bool IsTcpSessionDumpingEnabled(void)
Definition: stream-tcp-reassemble.c:91
util-fmemopen.h
TAILQ_INIT
#define TAILQ_INIT(head)
Definition: queue.h:262
SC_ATOMIC_INIT
#define SC_ATOMIC_INIT(name)
wrapper for initializing an atomic variable.
Definition: util-atomic.h:314
USE_STREAM_DEPTH_DISABLED
#define USE_STREAM_DEPTH_DISABLED
Definition: log-pcap.c:79
PcapFileName_::secs
uint64_t secs
Definition: log-pcap.c:98
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
PcapLogData_::pcap_dumper
pcap_dumper_t * pcap_dumper
Definition: log-pcap.c:152
TS_FORMAT_SEC
#define TS_FORMAT_SEC
Definition: log-pcap.c:76
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:269
ParseSizeStringU64
int ParseSizeStringU64(const char *size, uint64_t *res)
Definition: util-misc.c:190
PcapFileName_::usecs
uint32_t usecs
Definition: log-pcap.c:99
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
PcapLogData_::filename
char * filename
Definition: log-pcap.c:146
PacketAlerts_::cnt
uint16_t cnt
Definition: decode.h:267
HONOR_PASS_RULES_ENABLED
#define HONOR_PASS_RULES_ENABLED
Definition: log-pcap.c:83
Packet_::flags
uint32_t flags
Definition: decode.h:513
ConfGetNode
ConfNode * ConfGetNode(const char *name)
Get a ConfNode by name.
Definition: conf.c:181
DEFAULT_LOG_FILENAME
#define DEFAULT_LOG_FILENAME
Definition: log-pcap.c:58
threads.h
SC_ATOMIC_ADD
#define SC_ATOMIC_ADD(name, val)
add a value to our atomic variable
Definition: util-atomic.h:332
RING_BUFFER_MODE_ENABLED
#define RING_BUFFER_MODE_ENABLED
Definition: log-pcap.c:74
PcapLogData_::mode
int mode
Definition: log-pcap.c:147
TAILQ_EMPTY
#define TAILQ_EMPTY(head)
Definition: queue.h:248
PcapLogData_::pkt_cnt
uint64_t pkt_cnt
Definition: log-pcap.c:144
HONOR_PASS_RULES_DISABLED
#define HONOR_PASS_RULES_DISABLED
Definition: log-pcap.c:82
TAILQ_FOREACH
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:252
SCMutexLock
#define SCMutexLock(mut)
Definition: threads-debug.h:117
PcapLogData_::use_stream_depth
int use_stream_depth
Definition: log-pcap.c:141
PcapLogCompressionData_::format
enum PcapLogCompressionFormat format
Definition: log-pcap.c:121
PcapLogProfileData
struct PcapLogProfileData_ PcapLogProfileData
stream-tcp-reassemble.h
PcapLogData_::profile_handles
PcapLogProfileData profile_handles
Definition: log-pcap.c:163
LOGMODE_MULTI
#define LOGMODE_MULTI
Definition: log-pcap.c:65
TAILQ_INSERT_TAIL
#define TAILQ_INSERT_TAIL(head, elm, field)
Definition: queue.h:294
PcapLogRegister
void PcapLogRegister(void)
Definition: log-pcap.c:210
SCFmemopen
#define SCFmemopen
Definition: util-fmemopen.h:52
PcapLogCompressionData_::buffer
uint8_t * buffer
Definition: log-pcap.c:122
DEFAULT_LIMIT
#define DEFAULT_LIMIT
Definition: log-pcap.c:61
TM_ECODE_FAILED
@ TM_ECODE_FAILED
Definition: tm-threads-common.h:81
IsRunModeOffline
bool IsRunModeOffline(enum RunModes run_mode_to_check)
Definition: runmodes.c:544
PcapLogData_::pcap_dead_handle
pcap_t * pcap_dead_handle
Definition: log-pcap.c:151
Packet_::alerts
PacketAlerts alerts
Definition: decode.h:589
PacketTunnelChild
@ PacketTunnelChild
Definition: decode.h:383
TcpSegmentPcapHdrStorage_::pktlen
uint32_t pktlen
Definition: stream-tcp-private.h:67
PcapLogData_::size_current
uint64_t size_current
Definition: log-pcap.c:149
ConfValIsTrue
int ConfValIsTrue(const char *val)
Check if a value is true.
Definition: conf.c:536
PcapLogData_::profile_rotate
PcapLogProfileData profile_rotate
Definition: log-pcap.c:166
OutputCtx_::data
void * data
Definition: tm-modules.h:87
PcapLogCompressionData_
Definition: log-pcap.c:120
TM_ECODE_OK
@ TM_ECODE_OK
Definition: tm-threads-common.h:80
PCAPLOG_PROFILE_END
#define PCAPLOG_PROFILE_END(prof)
Definition: log-pcap.c:230
PcapLogGetFilename
char * PcapLogGetFilename(void)
Definition: log-pcap.c:1774
OutputCtx_
Definition: tm-modules.h:84
LogModeConditionalType_
LogModeConditionalType_
Definition: log-pcap.c:67
strlcpy
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: util-strlcpyu.c:43
PcapLogCompressionData_::bytes_in_block
uint64_t bytes_in_block
Definition: log-pcap.c:132
TAILQ_ENTRY
#define TAILQ_ENTRY(type)
Definition: queue.h:239
Packet_::datalink
int datalink
Definition: decode.h:608
PcapLogData_::is_private
bool is_private
Definition: log-pcap.c:156
PcapLogData_::size_limit
uint64_t size_limit
Definition: log-pcap.c:150
PcapLogProfileData_::cnt
uint64_t cnt
Definition: log-pcap.c:109
PcapLogData_::max_files
uint32_t max_files
Definition: log-pcap.c:155
PcapLogCompressionData_::file
FILE * file
Definition: log-pcap.c:128
TAILQ_REMOVE
#define TAILQ_REMOVE(head, elm, field)
Definition: queue.h:312
decode.h
TAILQ_FIRST
#define TAILQ_FIRST(head)
Definition: queue.h:250
OutputInitResult_::ctx
OutputCtx * ctx
Definition: output.h:47
PCAP_LOG_COMPRESSION_FORMAT_NONE
@ PCAP_LOG_COMPRESSION_FORMAT_NONE
Definition: log-pcap.c:116
strlcat
size_t strlcat(char *, const char *src, size_t siz)
Definition: util-strlcatu.c:45
util-cpu.h
Packet_::ts
SCTime_t ts
Definition: decode.h:524
SCMutexUnlock
#define SCMutexUnlock(mut)
Definition: threads-debug.h:119
TcpSegmentPcapHdrStorage_::ts
SCTime_t ts
Definition: stream-tcp-private.h:66
PKT_PSEUDO_STREAM_END
#define PKT_PSEUDO_STREAM_END
Definition: decode.h:1268
PCAP_LOG_COMPRESSION_FORMAT_LZ4
@ PCAP_LOG_COMPRESSION_FORMAT_LZ4
Definition: log-pcap.c:117
EnableTcpSessionDumping
void EnableTcpSessionDumping(void)
Definition: stream-tcp-reassemble.c:96
STREAM_DUMP_HEADERS
#define STREAM_DUMP_HEADERS
Definition: stream.h:34
GET_PKT_DATA
#define GET_PKT_DATA(p)
Definition: decode.h:205
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:58
PcapLogProfileData_::total
uint64_t total
Definition: log-pcap.c:108
PCAP_PKTHDR_SIZE
#define PCAP_PKTHDR_SIZE
Definition: log-pcap.c:87
StringParseUint32
int StringParseUint32(uint32_t *res, int base, size_t len, const char *str)
Definition: util-byte.c:313
util-time.h
OutputInitResult_::ok
bool ok
Definition: output.h:48
SCLogWarning
#define SCLogWarning(...)
Macro used to log WARNING messages.
Definition: util-debug.h:249
PcapFileName_::dirname
char * dirname
Definition: log-pcap.c:93
PcapLogData_::file_cnt
uint32_t file_cnt
Definition: log-pcap.c:154
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:309
SCTIME_TO_TIMEVAL
#define SCTIME_TO_TIMEVAL(tv, t)
Definition: util-time.h:97
PCAP_OUTPUT_BUFFER_SIZE
#define PCAP_OUTPUT_BUFFER_SIZE
Definition: log-pcap.h:31
stream.h
PcapLogCallbackContext::buf
MemBuffer * buf
Definition: log-pcap.c:530
TcpSegment
Definition: stream-tcp-private.h:72
Packet_
Definition: decode.h:476
SCLocalTime
struct tm * SCLocalTime(time_t timep, struct tm *result)
Definition: util-time.c:267
GET_PKT_LEN
#define GET_PKT_LEN(p)
Definition: decode.h:204
TimeGet
SCTime_t TimeGet(void)
Definition: util-time.c:152
DEFAULT_FILE_LIMIT
#define DEFAULT_FILE_LIMIT
Definition: log-pcap.c:62
SCTime_t
Definition: util-time.h:40
TmEcode
TmEcode
Definition: tm-threads-common.h:79
RING_BUFFER_MODE_DISABLED
#define RING_BUFFER_MODE_DISABLED
Definition: log-pcap.c:73
PcapLogThreadData_::buf
MemBuffer * buf
Definition: log-pcap.c:189
name
const char * name
Definition: tm-threads.c:2081
PCAP_SNAPLEN
#define PCAP_SNAPLEN
Definition: log-pcap.c:85
PcapLogData_::plog_lock
SCMutex plog_lock
Definition: log-pcap.c:143
PcapLogData_::h
struct pcap_pkthdr * h
Definition: log-pcap.c:145
PcapLogCompressionData_::pcap_buf
uint8_t * pcap_buf
Definition: log-pcap.c:129
MemBuffer_
Definition: util-buffer.h:27
LOGMODE_COND_TAG
@ LOGMODE_COND_TAG
Definition: log-pcap.c:70
SCLogInfo
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:224
StreamSegmentForSession
int StreamSegmentForSession(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
Run callback for all segments on both directions of the session.
Definition: stream.c:64
PcapLogCallbackContext::pl
PcapLogData * pl
Definition: log-pcap.c:528
PcapLogData_::prev_day
int prev_day
Definition: log-pcap.c:148
PKT_FIRST_TAG
#define PKT_FIRST_TAG
Definition: decode.h:1316
SCMutexInit
#define SCMutexInit(mut, mutattrs)
Definition: threads-debug.h:116
PCAPLOG_PROFILE_START
#define PCAPLOG_PROFILE_START
Definition: log-pcap.c:227
log-pcap.h
SCGetThreadIdLong
#define SCGetThreadIdLong(...)
Definition: threads.h:255
PcapLogData_::honor_pass_rules
int honor_pass_rules
Definition: log-pcap.c:142
pcap_file_thread
thread_local char * pcap_file_thread
Definition: log-pcap.c:105
PcapLogData_::profile_open
PcapLogProfileData profile_open
Definition: log-pcap.c:165
PcapLogData_::profile_lock
PcapLogProfileData profile_lock
Definition: log-pcap.c:160
OutputInitResult_
Definition: output.h:46
util-conf.h
Packet_::flow
struct Flow_ * flow
Definition: decode.h:515
StringParseUint64
int StringParseUint64(uint64_t *res, int base, size_t len, const char *str)
Definition: util-byte.c:308
TimeDifferenceMicros
uint64_t TimeDifferenceMicros(struct timeval t0, struct timeval t1)
Definition: util-time.c:644
LOGGER_PCAP
@ LOGGER_PCAP
Definition: suricata-common.h:499
suricata-common.h
OutputCtx_::DeInit
void(* DeInit)(struct OutputCtx_ *)
Definition: tm-modules.h:90
util-path.h
LOGMODE_NORMAL
#define LOGMODE_NORMAL
Definition: log-pcap.c:64
MemBufferFree
void MemBufferFree(MemBuffer *buffer)
Definition: util-buffer.c:86
PKT_STREAM_NOPCAPLOG
#define PKT_STREAM_NOPCAPLOG
Definition: decode.h:1277
PcapLogData_::profile_data_size
uint64_t profile_data_size
Definition: log-pcap.c:153
OutputPacketLoggerFunctions_::LogFunc
PacketLogger LogFunc
Definition: output.h:88
SCTIME_SECS
#define SCTIME_SECS(t)
Definition: util-time.h:57
OutputRegisterPacketModule
void OutputRegisterPacketModule(LoggerId id, const char *name, const char *conf_name, OutputInitFunc InitFunc, OutputPacketLoggerFunctions *output_module_functions)
Register a packet output module.
Definition: output.c:170
PathIsAbsolute
int PathIsAbsolute(const char *path)
Check if a path is absolute.
Definition: util-path.c:44
Packet_::ttype
enum PacketTunnelType ttype
Definition: decode.h:522
PcapLogProfileSetup
void PcapLogProfileSetup(void)
Definition: log-pcap.c:1898
SCStrdup
#define SCStrdup(s)
Definition: util-mem.h:56
FatalError
#define FatalError(...)
Definition: util-debug.h:502
PcapLogCallbackContext
Definition: log-pcap.c:527
PcapLogCompressionData_::buffer_size
uint64_t buffer_size
Definition: log-pcap.c:123
tv
ThreadVars * tv
Definition: fuzz_decodepcapfile.c:32
PcapLogThreadData_
Definition: log-pcap.c:187
threadvars.h
SCMalloc
#define SCMalloc(sz)
Definition: util-mem.h:47
ConfigGetLogDirectory
const char * ConfigGetLogDirectory(void)
Definition: util-conf.c:38
LOGMODE_COND_ALERTS
@ LOGMODE_COND_ALERTS
Definition: log-pcap.c:69
PcapFileName_::filename
char * filename
Definition: log-pcap.c:92
Packet_::root
struct Packet_ * root
Definition: decode.h:622
TcpSegmentPcapHdrStorage_::pkt_hdr
uint8_t * pkt_hdr
Definition: stream-tcp-private.h:69
str
#define str(s)
Definition: suricata-common.h:300
MAX_TOKS
#define MAX_TOKS
Definition: log-pcap.c:112
SCLogError
#define SCLogError(...)
Macro used to log ERROR messages.
Definition: util-debug.h:261
PcapLogCompressionData
struct PcapLogCompressionData_ PcapLogCompressionData
MODULE_NAME
#define MODULE_NAME
Definition: log-pcap.c:59
TcpSegment::pcap_hdr_storage
TcpSegmentPcapHdrStorage * pcap_hdr_storage
Definition: stream-tcp-private.h:78
SCFree
#define SCFree(p)
Definition: util-mem.h:61
ConfNode_
Definition: conf.h:32
SC_ATOMIC_DECLARE
SC_ATOMIC_DECLARE(uint32_t, thread_cnt)
PcapLogCompressionData_::pcap_buf_wrapper
FILE * pcap_buf_wrapper
Definition: log-pcap.c:131
src
uint16_t src
Definition: app-layer-dnp3.h:5
util-buffer.h
PcapFileName_
Definition: log-pcap.c:91
ConfValIsFalse
int ConfValIsFalse(const char *val)
Check if a value is false.
Definition: conf.c:561
TAILQ_HEAD
#define TAILQ_HEAD(name, type)
Definition: queue.h:230
PcapLogData_::profile_unlock
PcapLogProfileData profile_unlock
Definition: log-pcap.c:162
USE_STREAM_DEPTH_ENABLED
#define USE_STREAM_DEPTH_ENABLED
Definition: log-pcap.c:80
MemBufferWriteRaw
uint32_t MemBufferWriteRaw(MemBuffer *dst, const uint8_t *raw, const uint32_t raw_len)
Write a raw buffer to the MemBuffer dst.
Definition: util-buffer.c:115
PcapLogData_::profile_close
PcapLogProfileData profile_close
Definition: log-pcap.c:164
PKT_NOPACKET_INSPECTION
#define PKT_NOPACKET_INSPECTION
Definition: decode.h:1250
FlowHasAlerts
int FlowHasAlerts(const Flow *f)
Check if flow has alerts.
Definition: flow.c:162
PcapFileName
struct PcapFileName_ PcapFileName
PCAP_BUFFER_TIMEOUT
#define PCAP_BUFFER_TIMEOUT
Definition: log-pcap.c:86
MIN_LIMIT
#define MIN_LIMIT
Definition: log-pcap.c:60
dst
uint16_t dst
Definition: app-layer-dnp3.h:4
util-misc.h
PKT_HAS_TAG
#define PKT_HAS_TAG
Definition: decode.h:1259
PcapLogData_
Definition: log-pcap.c:140
PcapLogThreadData_::pcap_log
PcapLogData * pcap_log
Definition: log-pcap.c:188
PKT_FIRST_ALERTS
#define PKT_FIRST_ALERTS
Definition: decode.h:1315
SCLogNotice
#define SCLogNotice(...)
Macro used to log NOTICE messages.
Definition: util-debug.h:237
TAILQ_INSERT_BEFORE
#define TAILQ_INSERT_BEFORE(listelm, elm, field)
Definition: queue.h:277
PcapLogData_::profile_write
PcapLogProfileData profile_write
Definition: log-pcap.c:161
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
TS_FORMAT_USEC
#define TS_FORMAT_USEC
Definition: log-pcap.c:77
OutputPacketLoggerFunctions_
Definition: output.h:87
SCMutex
#define SCMutex
Definition: threads-debug.h:114
MAX_FILENAMELEN
#define MAX_FILENAMELEN
Definition: log-pcap.c:113
MemBufferCreateNew
MemBuffer * MemBufferCreateNew(uint32_t size)
Definition: util-buffer.c:32
output.h
LogModeConditionalType
enum LogModeConditionalType_ LogModeConditionalType
PcapLogCompressionFormat
PcapLogCompressionFormat
Definition: log-pcap.c:115
SCTIME_USECS
#define SCTIME_USECS(t)
Definition: util-time.h:56
ConfNodeLookupChildValue
const char * ConfNodeLookupChildValue(const ConfNode *node, const char *name)
Lookup the value of a child configuration node by name.
Definition: conf.c:809