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