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