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