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