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