suricata
util-logopenfile.c
Go to the documentation of this file.
1 /* vi: set et ts=4: */
2 /* Copyright (C) 2007-2020 Open Information Security Foundation
3  *
4  * You can copy, redistribute or modify this Program under the terms of
5  * the GNU General Public License version 2 as published by the Free
6  * Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * version 2 along with this program; if not, write to the Free Software
15  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16  * 02110-1301, USA.
17  */
18 
19 /**
20  * \file
21  *
22  * \author Mike Pomraning <mpomraning@qualys.com>
23  *
24  * File-like output for logging: regular files and sockets.
25  */
26 
27 #include "suricata-common.h" /* errno.h, string.h, etc. */
28 #include "conf.h" /* ConfNode, etc. */
29 #include "output.h" /* DEFAULT_LOG_* */
30 #include "util-byte.h"
31 #include "util-logopenfile.h"
32 
33 #if defined(HAVE_SYS_UN_H) && defined(HAVE_SYS_SOCKET_H) && defined(HAVE_SYS_TYPES_H)
34 #define BUILD_WITH_UNIXSOCKET
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/un.h>
38 #endif
39 
40 #ifdef HAVE_LIBHIREDIS
41 #include "util-log-redis.h"
42 #endif /* HAVE_LIBHIREDIS */
43 
44 static bool LogFileNewThreadedCtx(LogFileCtx *parent_ctx, const char *log_path, const char *append, int i);
45 static bool SCLogOpenThreadedFileFp(const char *log_path, const char *append, LogFileCtx *parent_ctx, int slot_count);
46 
47 // Threaded eve.json suffixes
48 static SC_ATOMIC_DECL_AND_INIT_WITH_VAL(uint32_t, eve_file_suffix, 1);
49 
50 #ifdef BUILD_WITH_UNIXSOCKET
51 /** \brief connect to the indicated local stream socket, logging any errors
52  * \param path filesystem path to connect to
53  * \param log_err, non-zero if connect failure should be logged.
54  * \retval FILE* on success (fdopen'd wrapper of underlying socket)
55  * \retval NULL on error
56  */
57 static FILE *
58 SCLogOpenUnixSocketFp(const char *path, int sock_type, int log_err)
59 {
60  struct sockaddr_un saun;
61  int s = -1;
62  FILE * ret = NULL;
63 
64  memset(&saun, 0x00, sizeof(saun));
65 
66  s = socket(PF_UNIX, sock_type, 0);
67  if (s < 0) goto err;
68 
69  saun.sun_family = AF_UNIX;
70  strlcpy(saun.sun_path, path, sizeof(saun.sun_path));
71 
72  if (connect(s, (const struct sockaddr *)&saun, sizeof(saun)) < 0)
73  goto err;
74 
75  ret = fdopen(s, "w");
76  if (ret == NULL)
77  goto err;
78 
79  return ret;
80 
81 err:
82  if (log_err)
84  "Error connecting to socket \"%s\": %s (will keep trying)",
85  path, strerror(errno));
86 
87  if (s >= 0)
88  close(s);
89 
90  return NULL;
91 }
92 
93 /**
94  * \brief Attempt to reconnect a disconnected (or never-connected) Unix domain socket.
95  * \retval 1 if it is now connected; otherwise 0
96  */
97 static int SCLogUnixSocketReconnect(LogFileCtx *log_ctx)
98 {
99  int disconnected = 0;
100  if (log_ctx->fp) {
102  "Write error on Unix socket \"%s\": %s; reconnecting...",
103  log_ctx->filename, strerror(errno));
104  fclose(log_ctx->fp);
105  log_ctx->fp = NULL;
106  log_ctx->reconn_timer = 0;
107  disconnected = 1;
108  }
109 
110  struct timeval tv;
111  uint64_t now;
112  gettimeofday(&tv, NULL);
113  now = (uint64_t)tv.tv_sec * 1000;
114  now += tv.tv_usec / 1000; /* msec resolution */
115  if (log_ctx->reconn_timer != 0 &&
116  (now - log_ctx->reconn_timer) < LOGFILE_RECONN_MIN_TIME) {
117  /* Don't bother to try reconnecting too often. */
118  return 0;
119  }
120  log_ctx->reconn_timer = now;
121 
122  log_ctx->fp = SCLogOpenUnixSocketFp(log_ctx->filename, log_ctx->sock_type, 0);
123  if (log_ctx->fp) {
124  /* Connected at last (or reconnected) */
125  SCLogNotice("Reconnected socket \"%s\"", log_ctx->filename);
126  } else if (disconnected) {
127  SCLogWarning(SC_ERR_SOCKET, "Reconnect failed: %s (will keep trying)",
128  strerror(errno));
129  }
130 
131  return log_ctx->fp ? 1 : 0;
132 }
133 
134 static int SCLogFileWriteSocket(const char *buffer, int buffer_len,
135  LogFileCtx *ctx)
136 {
137  int tries = 0;
138  int ret = 0;
139  bool reopen = false;
140  if (ctx->fp == NULL && ctx->is_sock) {
141  SCLogUnixSocketReconnect(ctx);
142  }
143 tryagain:
144  ret = -1;
145  reopen = 0;
146  errno = 0;
147  if (ctx->fp != NULL) {
148  int fd = fileno(ctx->fp);
149  ssize_t size = send(fd, buffer, buffer_len, ctx->send_flags);
150  if (size > -1) {
151  ret = 0;
152  } else {
153  if (errno == EAGAIN || errno == EWOULDBLOCK) {
154  SCLogDebug("Socket would block, dropping event.");
155  } else if (errno == EINTR) {
156  if (tries++ == 0) {
157  SCLogDebug("Interrupted system call, trying again.");
158  goto tryagain;
159  }
160  SCLogDebug("Too many interrupted system calls, "
161  "dropping event.");
162  } else {
163  /* Some other error. Assume badness and reopen. */
164  SCLogDebug("Send failed: %s", strerror(errno));
165  reopen = true;
166  }
167  }
168  }
169 
170  if (reopen && tries++ == 0) {
171  if (SCLogUnixSocketReconnect(ctx)) {
172  goto tryagain;
173  }
174  }
175 
176  if (ret == -1) {
177  ctx->dropped++;
178  }
179 
180  return ret;
181 }
182 #endif /* BUILD_WITH_UNIXSOCKET */
183 static inline void OutputWriteLock(pthread_mutex_t *m)
184 {
185  SCMutexLock(m);
186 
187 }
188 
189 /**
190  * \brief Write buffer to log file.
191  * \retval 0 on failure; otherwise, the return value of fwrite_unlocked (number of
192  * characters successfully written).
193  */
194 static int SCLogFileWriteNoLock(const char *buffer, int buffer_len, LogFileCtx *log_ctx)
195 {
196  int ret = 0;
197 
198  BUG_ON(log_ctx->is_sock);
199 
200  /* Check for rotation. */
201  if (log_ctx->rotation_flag) {
202  log_ctx->rotation_flag = 0;
203  SCConfLogReopen(log_ctx);
204  }
205 
206  if (log_ctx->flags & LOGFILE_ROTATE_INTERVAL) {
207  time_t now = time(NULL);
208  if (now >= log_ctx->rotate_time) {
209  SCConfLogReopen(log_ctx);
210  log_ctx->rotate_time = now + log_ctx->rotate_interval;
211  }
212  }
213 
214  if (log_ctx->fp) {
215  SCClearErrUnlocked(log_ctx->fp);
216  if (1 != SCFwriteUnlocked(buffer, buffer_len, 1, log_ctx->fp)) {
217  /* Only the first error is logged */
218  if (!log_ctx->output_errors) {
219  SCLogError(SC_ERR_LOG_OUTPUT, "%s error while writing to %s",
220  SCFerrorUnlocked(log_ctx->fp) ? strerror(errno) : "unknown error",
221  log_ctx->filename);
222  }
223  log_ctx->output_errors++;
224  } else {
225  SCFflushUnlocked(log_ctx->fp);
226  }
227  }
228 
229  return ret;
230 }
231 
232 /**
233  * \brief Write buffer to log file.
234  * \retval 0 on failure; otherwise, the return value of fwrite (number of
235  * characters successfully written).
236  */
237 static int SCLogFileWrite(const char *buffer, int buffer_len, LogFileCtx *log_ctx)
238 {
239  OutputWriteLock(&log_ctx->fp_mutex);
240  int ret = 0;
241 
242 #ifdef BUILD_WITH_UNIXSOCKET
243  if (log_ctx->is_sock) {
244  ret = SCLogFileWriteSocket(buffer, buffer_len, log_ctx);
245  } else
246 #endif
247  {
248 
249  /* Check for rotation. */
250  if (log_ctx->rotation_flag) {
251  log_ctx->rotation_flag = 0;
252  SCConfLogReopen(log_ctx);
253  }
254 
255  if (log_ctx->flags & LOGFILE_ROTATE_INTERVAL) {
256  time_t now = time(NULL);
257  if (now >= log_ctx->rotate_time) {
258  SCConfLogReopen(log_ctx);
259  log_ctx->rotate_time = now + log_ctx->rotate_interval;
260  }
261  }
262 
263  if (log_ctx->fp) {
264  clearerr(log_ctx->fp);
265  if (1 != fwrite(buffer, buffer_len, 1, log_ctx->fp)) {
266  /* Only the first error is logged */
267  if (!log_ctx->output_errors) {
268  SCLogError(SC_ERR_LOG_OUTPUT, "%s error while writing to %s",
269  ferror(log_ctx->fp) ? strerror(errno) : "unknown error",
270  log_ctx->filename);
271  }
272  log_ctx->output_errors++;
273  } else {
274  fflush(log_ctx->fp);
275  }
276  }
277  }
278 
279  SCMutexUnlock(&log_ctx->fp_mutex);
280 
281  return ret;
282 }
283 
284 /** \brief generate filename based on pattern
285  * \param pattern pattern to use
286  * \retval char* on success
287  * \retval NULL on error
288  */
289 static char *SCLogFilenameFromPattern(const char *pattern)
290 {
291  char *filename = SCMalloc(PATH_MAX);
292  if (filename == NULL) {
293  return NULL;
294  }
295 
296  int rc = SCTimeToStringPattern(time(NULL), pattern, filename, PATH_MAX);
297  if (rc != 0) {
298  SCFree(filename);
299  return NULL;
300  }
301 
302  return filename;
303 }
304 
305 static void SCLogFileCloseNoLock(LogFileCtx *log_ctx)
306 {
307  if (log_ctx->fp)
308  fclose(log_ctx->fp);
309 
310  if (log_ctx->output_errors) {
311  SCLogError(SC_ERR_LOG_OUTPUT, "There were %" PRIu64 " output errors to %s",
312  log_ctx->output_errors, log_ctx->filename);
313  }
314 }
315 
316 static void SCLogFileClose(LogFileCtx *log_ctx)
317 {
318  SCMutexLock(&log_ctx->fp_mutex);
319  SCLogFileCloseNoLock(log_ctx);
320  SCMutexUnlock(&log_ctx->fp_mutex);
321 }
322 
323 static bool
324 SCLogOpenThreadedFileFp(const char *log_path, const char *append, LogFileCtx *parent_ctx, int slot_count)
325 {
326  parent_ctx->threads = SCCalloc(1, sizeof(LogThreadedFileCtx));
327  if (!parent_ctx->threads) {
328  SCLogError(SC_ERR_MEM_ALLOC, "Unable to allocate threads container");
329  return false;
330  }
331  parent_ctx->threads->append = SCStrdup(append);
332  if (!parent_ctx->threads->append) {
333  SCLogError(SC_ERR_MEM_ALLOC, "Unable to allocate threads append setting");
334  goto error_exit;
335  }
336 
337  parent_ctx->threads->slot_count = slot_count;
338  parent_ctx->threads->lf_slots = SCCalloc(slot_count, sizeof(LogFileCtx *));
339  if (!parent_ctx->threads->lf_slots) {
340  SCLogError(SC_ERR_MEM_ALLOC, "Unable to allocate thread slots");
341  goto error_exit;
342  }
343  SCLogDebug("Allocated %d file context pointers for threaded array",
344  parent_ctx->threads->slot_count);
345  int slot = 1;
346  for (; slot < parent_ctx->threads->slot_count; slot++) {
347  if (!LogFileNewThreadedCtx(parent_ctx, log_path, append, slot)) {
348  /* TODO: clear allocated entries [1, slot) */
349  goto error_exit;
350  }
351  }
352  SCMutexInit(&parent_ctx->threads->mutex, NULL);
353  return true;
354 
355 error_exit:
356 
357  if (parent_ctx->threads->lf_slots) {
358  SCFree(parent_ctx->threads->lf_slots);
359  }
360  if (parent_ctx->threads->append) {
361  SCFree(parent_ctx->threads->append);
362  }
363  SCFree(parent_ctx->threads);
364  parent_ctx->threads = NULL;
365  return false;
366 }
367 
368 /** \brief open the indicated file, logging any errors
369  * \param path filesystem path to open
370  * \param append_setting open file with O_APPEND: "yes" or "no"
371  * \param mode permissions to set on file
372  * \retval FILE* on success
373  * \retval NULL on error
374  */
375 static FILE *
376 SCLogOpenFileFp(const char *path, const char *append_setting, uint32_t mode)
377 {
378  FILE *ret = NULL;
379 
380  char *filename = SCLogFilenameFromPattern(path);
381  if (filename == NULL) {
382  return NULL;
383  }
384 
385  int rc = SCCreateDirectoryTree(filename, false);
386  if (rc < 0) {
387  SCFree(filename);
388  return NULL;
389  }
390 
391  if (ConfValIsTrue(append_setting)) {
392  ret = fopen(filename, "a");
393  } else {
394  ret = fopen(filename, "w");
395  }
396 
397  if (ret == NULL) {
398  SCLogError(SC_ERR_FOPEN, "Error opening file: \"%s\": %s",
399  filename, strerror(errno));
400  } else {
401  if (mode != 0) {
402  int r = chmod(filename, mode);
403  if (r < 0) {
404  SCLogWarning(SC_WARN_CHMOD, "Could not chmod %s to %o: %s",
405  filename, mode, strerror(errno));
406  }
407  }
408  }
409 
410  SCFree(filename);
411  return ret;
412 }
413 
414 /** \brief open a generic output "log file", which may be a regular file or a socket
415  * \param conf ConfNode structure for the output section in question
416  * \param log_ctx Log file context allocated by caller
417  * \param default_filename Default name of file to open, if not specified in ConfNode
418  * \param rotate Register the file for rotation in HUP.
419  * \retval 0 on success
420  * \retval -1 on error
421  */
422 int
424  LogFileCtx *log_ctx,
425  const char *default_filename,
426  int rotate)
427 {
428  char log_path[PATH_MAX];
429  const char *log_dir;
430  const char *filename, *filetype;
431 
432  // Arg check
433  if (conf == NULL || log_ctx == NULL || default_filename == NULL) {
435  "SCConfLogOpenGeneric(conf %p, ctx %p, default %p) "
436  "missing an argument",
437  conf, log_ctx, default_filename);
438  return -1;
439  }
440  if (log_ctx->fp != NULL) {
442  "SCConfLogOpenGeneric: previously initialized Log CTX "
443  "encountered");
444  return -1;
445  }
446 
447  // Resolve the given config
448  filename = ConfNodeLookupChildValue(conf, "filename");
449  if (filename == NULL)
450  filename = default_filename;
451 
452  log_dir = ConfigGetLogDirectory();
453 
454  if (PathIsAbsolute(filename)) {
455  snprintf(log_path, PATH_MAX, "%s", filename);
456  } else {
457  snprintf(log_path, PATH_MAX, "%s/%s", log_dir, filename);
458  }
459 
460  /* Rotate log file based on time */
461  const char *rotate_int = ConfNodeLookupChildValue(conf, "rotate-interval");
462  if (rotate_int != NULL) {
463  time_t now = time(NULL);
464  log_ctx->flags |= LOGFILE_ROTATE_INTERVAL;
465 
466  /* Use a specific time */
467  if (strcmp(rotate_int, "minute") == 0) {
468  log_ctx->rotate_time = now + SCGetSecondsUntil(rotate_int, now);
469  log_ctx->rotate_interval = 60;
470  } else if (strcmp(rotate_int, "hour") == 0) {
471  log_ctx->rotate_time = now + SCGetSecondsUntil(rotate_int, now);
472  log_ctx->rotate_interval = 3600;
473  } else if (strcmp(rotate_int, "day") == 0) {
474  log_ctx->rotate_time = now + SCGetSecondsUntil(rotate_int, now);
475  log_ctx->rotate_interval = 86400;
476  }
477 
478  /* Use a timer */
479  else {
480  log_ctx->rotate_interval = SCParseTimeSizeString(rotate_int);
481  if (log_ctx->rotate_interval == 0) {
483  "invalid rotate-interval value");
484  }
485  log_ctx->rotate_time = now + log_ctx->rotate_interval;
486  }
487  }
488 
489  filetype = ConfNodeLookupChildValue(conf, "filetype");
490  if (filetype == NULL)
491  filetype = DEFAULT_LOG_FILETYPE;
492 
493  const char *filemode = ConfNodeLookupChildValue(conf, "filemode");
494  uint32_t mode = 0;
495  if (filemode != NULL &&
496  StringParseUint32(&mode, 8, strlen(filemode),
497  filemode) > 0) {
498  log_ctx->filemode = mode;
499  }
500 
501  const char *append = ConfNodeLookupChildValue(conf, "append");
502  if (append == NULL)
503  append = DEFAULT_LOG_MODE_APPEND;
504 
505  /* JSON flags */
506  log_ctx->json_flags = JSON_PRESERVE_ORDER|JSON_COMPACT|
507  JSON_ENSURE_ASCII|JSON_ESCAPE_SLASH;
508 
509  ConfNode *json_flags = ConfNodeLookupChild(conf, "json");
510 
511  if (json_flags != 0) {
512  const char *preserve_order = ConfNodeLookupChildValue(json_flags,
513  "preserve-order");
514  if (preserve_order != NULL && ConfValIsFalse(preserve_order))
515  log_ctx->json_flags &= ~(JSON_PRESERVE_ORDER);
516 
517  const char *compact = ConfNodeLookupChildValue(json_flags, "compact");
518  if (compact != NULL && ConfValIsFalse(compact))
519  log_ctx->json_flags &= ~(JSON_COMPACT);
520 
521  const char *ensure_ascii = ConfNodeLookupChildValue(json_flags,
522  "ensure-ascii");
523  if (ensure_ascii != NULL && ConfValIsFalse(ensure_ascii))
524  log_ctx->json_flags &= ~(JSON_ENSURE_ASCII);
525 
526  const char *escape_slash = ConfNodeLookupChildValue(json_flags,
527  "escape-slash");
528  if (escape_slash != NULL && ConfValIsFalse(escape_slash))
529  log_ctx->json_flags &= ~(JSON_ESCAPE_SLASH);
530  }
531 
532  // Now, what have we been asked to open?
533  if (strcasecmp(filetype, "unix_stream") == 0) {
534 #ifdef BUILD_WITH_UNIXSOCKET
535  /* Don't bail. May be able to connect later. */
536  log_ctx->is_sock = 1;
537  log_ctx->sock_type = SOCK_STREAM;
538  log_ctx->fp = SCLogOpenUnixSocketFp(log_path, SOCK_STREAM, 1);
539 #else
540  return -1;
541 #endif
542  } else if (strcasecmp(filetype, "unix_dgram") == 0) {
543 #ifdef BUILD_WITH_UNIXSOCKET
544  /* Don't bail. May be able to connect later. */
545  log_ctx->is_sock = 1;
546  log_ctx->sock_type = SOCK_DGRAM;
547  log_ctx->fp = SCLogOpenUnixSocketFp(log_path, SOCK_DGRAM, 1);
548 #else
549  return -1;
550 #endif
551  } else if (strcasecmp(filetype, DEFAULT_LOG_FILETYPE) == 0 ||
552  strcasecmp(filetype, "file") == 0) {
553  log_ctx->is_regular = 1;
554  if (!log_ctx->threaded) {
555  log_ctx->fp = SCLogOpenFileFp(log_path, append, log_ctx->filemode);
556  if (log_ctx->fp == NULL)
557  return -1; // Error already logged by Open...Fp routine
558  } else {
559  if (!SCLogOpenThreadedFileFp(log_path, append, log_ctx, 1)) {
560  return -1;
561  }
562  }
563  if (rotate) {
565  }
566 #ifdef HAVE_LIBHIREDIS
567  } else if (strcasecmp(filetype, "redis") == 0) {
568  ConfNode *redis_node = ConfNodeLookupChild(conf, "redis");
569  if (SCConfLogOpenRedis(redis_node, log_ctx) < 0) {
570  SCLogError(SC_ERR_REDIS, "failed to open redis output");
571  return -1;
572  }
573  log_ctx->type = LOGFILE_TYPE_REDIS;
574 #endif
575  } else {
576  SCLogError(SC_ERR_INVALID_YAML_CONF_ENTRY, "Invalid entry for "
577  "%s.filetype. Expected \"regular\" (default), \"unix_stream\", "
578  "\"pcie\" "
579  "or \"unix_dgram\"",
580  conf->name);
581  }
582  log_ctx->filename = SCStrdup(log_path);
583  if (unlikely(log_ctx->filename == NULL)) {
585  "Failed to allocate memory for filename");
586  return -1;
587  }
588 
589 #ifdef BUILD_WITH_UNIXSOCKET
590  /* If a socket and running live, do non-blocking writes. */
591  if (log_ctx->is_sock && !IsRunModeOffline(RunmodeGetCurrent())) {
592  SCLogInfo("Setting logging socket of non-blocking in live mode.");
593  log_ctx->send_flags |= MSG_DONTWAIT;
594  }
595 #endif
596  SCLogInfo("%s output device (%s) initialized: %s", conf->name, filetype,
597  filename);
598 
599  return 0;
600 }
601 
602 /**
603  * \brief Reopen a regular log file with the side-affect of truncating it.
604  *
605  * This is useful to clear the log file and start a new one, or to
606  * re-open the file after its been moved by something external
607  * (eg. logrotate).
608  */
610 {
611  if (!log_ctx->is_regular) {
612  /* Not supported and not needed on non-regular files. */
613  return 0;
614  }
615 
616  if (log_ctx->filename == NULL) {
618  "Can't re-open LogFileCtx without a filename.");
619  return -1;
620  }
621 
622  if (log_ctx->fp != NULL) {
623  fclose(log_ctx->fp);
624  }
625 
626  /* Reopen the file. Append is forced in case the file was not
627  * moved as part of a rotation process. */
628  SCLogDebug("Reopening log file %s.", log_ctx->filename);
629  log_ctx->fp = SCLogOpenFileFp(log_ctx->filename, "yes", log_ctx->filemode);
630  if (log_ctx->fp == NULL) {
631  return -1; // Already logged by Open..Fp routine.
632  }
633 
634  return 0;
635 }
636 
637 /** \brief LogFileNewCtx() Get a new LogFileCtx
638  * \retval LogFileCtx * pointer if successful, NULL if error
639  * */
641 {
642  LogFileCtx* lf_ctx;
643  lf_ctx = (LogFileCtx*)SCCalloc(1, sizeof(LogFileCtx));
644 
645  if (lf_ctx == NULL)
646  return NULL;
647 
648  lf_ctx->Write = SCLogFileWrite;
649  lf_ctx->Close = SCLogFileClose;
650 
651  return lf_ctx;
652 }
653 
654 /** \brief LogFileEnsureExists() Ensure a log file context for the thread exists
655  * \param parent_ctx
656  * \param thread_id
657  * \retval LogFileCtx * pointer if successful; NULL otherwise
658  */
659 LogFileCtx *LogFileEnsureExists(LogFileCtx *parent_ctx, int thread_id)
660 {
661  /* threaded output disabled */
662  if (!parent_ctx->threaded)
663  return parent_ctx;
664 
665  SCLogDebug("Adding reference %d to file ctx %p", thread_id, parent_ctx);
666  SCMutexLock(&parent_ctx->threads->mutex);
667  /* are there enough context slots already */
668  if (thread_id < parent_ctx->threads->slot_count) {
669  /* has it been opened yet? */
670  if (!parent_ctx->threads->lf_slots[thread_id]) {
671  SCLogDebug("Opening new file for %d reference to file ctx %p", thread_id, parent_ctx);
672  LogFileNewThreadedCtx(parent_ctx, parent_ctx->filename, parent_ctx->threads->append, thread_id);
673  }
674  SCLogDebug("Existing file for %d reference to file ctx %p", thread_id, parent_ctx);
675  SCMutexUnlock(&parent_ctx->threads->mutex);
676  return parent_ctx->threads->lf_slots[thread_id];
677  }
678 
679  /* ensure there's a slot for the caller */
680  int new_size = MAX(parent_ctx->threads->slot_count << 1, thread_id + 1);
681  SCLogDebug("Increasing slot count; current %d, trying %d",
682  parent_ctx->threads->slot_count, new_size);
683  LogFileCtx **new_array = SCRealloc(parent_ctx->threads->lf_slots, new_size * sizeof(LogFileCtx *));
684  if (new_array == NULL) {
685  /* Try one more time */
686  SCLogDebug("Unable to increase file context array size to %d; trying %d",
687  new_size, thread_id + 1);
688  new_size = thread_id + 1;
689  new_array = SCRealloc(parent_ctx->threads->lf_slots, new_size * sizeof(LogFileCtx *));
690  }
691 
692  if (new_array == NULL) {
693  SCLogError(SC_ERR_MEM_ALLOC, "Unable to increase file context array size to %d", new_size);
694  SCMutexUnlock(&parent_ctx->threads->mutex);
695  return NULL;
696  }
697 
698  parent_ctx->threads->lf_slots = new_array;
699  /* initialize newly added slots */
700  for (int i = parent_ctx->threads->slot_count; i < new_size; i++) {
701  parent_ctx->threads->lf_slots[i] = NULL;
702  }
703  parent_ctx->threads->slot_count = new_size;
704  LogFileNewThreadedCtx(parent_ctx, parent_ctx->filename, parent_ctx->threads->append, thread_id);
705 
706  SCMutexUnlock(&parent_ctx->threads->mutex);
707 
708  return parent_ctx->threads->lf_slots[thread_id];
709 }
710 
711 /** \brief LogFileNewThreadedCtx() Create file context for threaded output
712  * \param parent_ctx
713  * \param log_path
714  * \param append
715  * \param thread_id
716  */
717 static bool LogFileNewThreadedCtx(LogFileCtx *parent_ctx, const char *log_path, const char *append, int thread_id)
718 {
719  LogFileCtx *thread = SCCalloc(1, sizeof(LogFileCtx));
720  if (!thread) {
721  SCLogError(SC_ERR_MEM_ALLOC, "Unable to allocate thread file context slot %d", thread_id);
722  return false;
723  }
724 
725  *thread = *parent_ctx;
726  char fname[NAME_MAX];
727  snprintf(fname, sizeof(fname), "%s.%d", log_path, SC_ATOMIC_ADD(eve_file_suffix, 1));
728  SCLogDebug("Thread open -- using name %s [replaces %s]", fname, log_path);
729  thread->fp = SCLogOpenFileFp(fname, append, thread->filemode);
730  if (thread->fp == NULL) {
731  goto error;
732  }
733  thread->filename = SCStrdup(fname);
734  if (!thread->filename) {
735  SCLogError(SC_ERR_MEM_ALLOC, "Unable to duplicate filename for context slot %d", thread_id);
736  goto error;
737  }
738 
739  thread->threaded = false;
740  thread->parent = parent_ctx;
741  thread->id = thread_id;
742  thread->is_regular = true;
743  thread->Write = SCLogFileWriteNoLock;
744  thread->Close = SCLogFileCloseNoLock;
746 
747  parent_ctx->threads->lf_slots[thread_id] = thread;
748  return true;
749 
750 error:
751  SC_ATOMIC_SUB(eve_file_suffix, 1);
752  if (thread->fp) {
753  thread->Close(thread);
754  }
755  if (thread) {
756  SCFree(thread);
757  }
758  parent_ctx->threads->lf_slots[thread_id] = NULL;
759  return false;
760 }
761 
762 /** \brief LogFileFreeCtx() Destroy a LogFileCtx (Close the file and free memory)
763  * \param lf_ctx pointer to the OutputCtx
764  * \retval int 1 if successful, 0 if error
765  * */
767 {
768  if (lf_ctx == NULL) {
769  SCReturnInt(0);
770  }
771 
772  if (lf_ctx->threaded) {
773  SCMutexDestroy(&lf_ctx->threads->mutex);
774  for(int i = 0; i < lf_ctx->threads->slot_count; i++) {
775  if (lf_ctx->threads->lf_slots[i]) {
777  SCFree(lf_ctx->threads->lf_slots[i]->filename);
778  SCFree(lf_ctx->threads->lf_slots[i]);
779  }
780  }
781  SCFree(lf_ctx->threads->lf_slots);
782  SCFree(lf_ctx->threads->append);
783  SCFree(lf_ctx->threads);
784  } else {
785  if (lf_ctx->type == LOGFILE_TYPE_PLUGIN) {
786  if (lf_ctx->plugin->Close != NULL) {
787  lf_ctx->plugin->Close(lf_ctx->plugin_data);
788  }
789  } else if (lf_ctx->fp != NULL) {
790  lf_ctx->Close(lf_ctx);
791  }
792  if (lf_ctx->parent) {
793  SCMutexLock(&lf_ctx->parent->threads->mutex);
794  lf_ctx->parent->threads->lf_slots[lf_ctx->id] = NULL;
795  SCMutexUnlock(&lf_ctx->parent->threads->mutex);
796  }
797  SCMutexDestroy(&lf_ctx->fp_mutex);
798  }
799 
800  if (lf_ctx->prefix != NULL) {
801  SCFree(lf_ctx->prefix);
802  lf_ctx->prefix_len = 0;
803  }
804 
805  if(lf_ctx->filename != NULL)
806  SCFree(lf_ctx->filename);
807 
808  if (lf_ctx->sensor_name)
809  SCFree(lf_ctx->sensor_name);
810 
811  if (!lf_ctx->threaded) {
813  }
814 
815  SCFree(lf_ctx);
816 
817  SCReturnInt(1);
818 }
819 
820 int LogFileWrite(LogFileCtx *file_ctx, MemBuffer *buffer)
821 {
822  if (file_ctx->type == LOGFILE_TYPE_SYSLOG) {
823  syslog(file_ctx->syslog_setup.alert_syslog_level, "%s",
824  (const char *)MEMBUFFER_BUFFER(buffer));
825  } else if (file_ctx->type == LOGFILE_TYPE_FILE ||
826  file_ctx->type == LOGFILE_TYPE_UNIX_DGRAM ||
827  file_ctx->type == LOGFILE_TYPE_UNIX_STREAM)
828  {
829  /* append \n for files only */
830  MemBufferWriteString(buffer, "\n");
831  file_ctx->Write((const char *)MEMBUFFER_BUFFER(buffer),
832  MEMBUFFER_OFFSET(buffer), file_ctx);
833  }
834 #ifdef HAVE_LIBHIREDIS
835  else if (file_ctx->type == LOGFILE_TYPE_REDIS) {
836  SCMutexLock(&file_ctx->fp_mutex);
837  LogFileWriteRedis(file_ctx, (const char *)MEMBUFFER_BUFFER(buffer),
838  MEMBUFFER_OFFSET(buffer));
839  SCMutexUnlock(&file_ctx->fp_mutex);
840  }
841 #endif
842  else if (file_ctx->type == LOGFILE_TYPE_PLUGIN) {
843  file_ctx->plugin->Write((const char *)MEMBUFFER_BUFFER(buffer),
844  MEMBUFFER_OFFSET(buffer), file_ctx->plugin_data);
845  }
846 
847  return 0;
848 }
SCParseTimeSizeString
uint64_t SCParseTimeSizeString(const char *str)
Parse string containing time size (1m, 1h, etc).
Definition: util-time.c:576
LogFileCtx_::rotation_flag
int rotation_flag
Definition: util-logopenfile.h:140
util-byte.h
LogFileCtx_::prefix_len
size_t prefix_len
Definition: util-logopenfile.h:119
SyslogSetup_::alert_syslog_level
int alert_syslog_level
Definition: util-logopenfile.h:48
LogThreadedFileCtx_::append
char * append
Definition: util-logopenfile.h:56
SCFerrorUnlocked
#define SCFerrorUnlocked
Definition: suricata-common.h:533
LOGFILE_TYPE_REDIS
@ LOGFILE_TYPE_REDIS
Definition: util-logopenfile.h:44
LogFileCtx_::sensor_name
char * sensor_name
Definition: util-logopenfile.h:102
LogFileCtx_::reconn_timer
uint64_t reconn_timer
Definition: util-logopenfile.h:107
syslog
#define syslog(__pri, __fmt, __param)
Definition: win32-syslog.h:78
SC_ERR_SOCKET
@ SC_ERR_SOCKET
Definition: util-error.h:232
LogFileCtx_::fp_mutex
SCMutex fp_mutex
Definition: util-logopenfile.h:85
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
SC_ATOMIC_DECL_AND_INIT_WITH_VAL
#define SC_ATOMIC_DECL_AND_INIT_WITH_VAL(type, name, val)
wrapper for declaring an atomic variable and initializing it to a specific value
Definition: util-atomic.h:304
LogFileNewCtx
LogFileCtx * LogFileNewCtx(void)
LogFileNewCtx() Get a new LogFileCtx.
Definition: util-logopenfile.c:640
SCGetSecondsUntil
uint64_t SCGetSecondsUntil(const char *str, time_t epoch)
Get seconds until a time unit changes.
Definition: util-time.c:627
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:298
SCPluginFileType_::Close
void(* Close)(void *ctx)
Definition: suricata-plugin.h:53
LogThreadedFileCtx_::lf_slots
struct LogFileCtx_ ** lf_slots
Definition: util-logopenfile.h:55
LogFileCtx_::json_flags
size_t json_flags
Definition: util-logopenfile.h:137
LogFileCtx_::id
int id
Definition: util-logopenfile.h:90
SC_ATOMIC_ADD
#define SC_ATOMIC_ADD(name, val)
add a value to our atomic variable
Definition: util-atomic.h:333
LogFileCtx_
Definition: util-logopenfile.h:60
LOGFILE_TYPE_SYSLOG
@ LOGFILE_TYPE_SYSLOG
Definition: util-logopenfile.h:41
LOGFILE_RECONN_MIN_TIME
#define LOGFILE_RECONN_MIN_TIME
Definition: util-logopenfile.h:156
DEFAULT_LOG_MODE_APPEND
#define DEFAULT_LOG_MODE_APPEND
Definition: output.h:30
SCMutexLock
#define SCMutexLock(mut)
Definition: threads-debug.h:117
util-log-redis.h
LogFileCtx_::Write
int(* Write)(const char *buffer, int buffer_len, struct LogFileCtx_ *fp)
Definition: util-logopenfile.h:78
LogFileCtx_::filename
char * filename
Definition: util-logopenfile.h:96
JSON_ESCAPE_SLASH
#define JSON_ESCAPE_SLASH
Definition: suricata-common.h:258
m
SCMutex m
Definition: flow-hash.h:6
LogFileCtx_::plugin
SCPluginFileType * plugin
Definition: util-logopenfile.h:81
LogFileCtx_::send_flags
uint8_t send_flags
Definition: util-logopenfile.h:130
MAX
#define MAX(x, y)
Definition: suricata-common.h:381
SCConfLogReopen
int SCConfLogReopen(LogFileCtx *log_ctx)
Reopen a regular log file with the side-affect of truncating it.
Definition: util-logopenfile.c:609
IsRunModeOffline
bool IsRunModeOffline(enum RunModes run_mode_to_check)
Definition: runmodes.c:518
SCClearErrUnlocked
#define SCClearErrUnlocked
Definition: suricata-common.h:532
ConfValIsTrue
int ConfValIsTrue(const char *val)
Check if a value is true.
Definition: conf.c:565
SCConfLogOpenGeneric
int SCConfLogOpenGeneric(ConfNode *conf, LogFileCtx *log_ctx, const char *default_filename, int rotate)
open a generic output "log file", which may be a regular file or a socket
Definition: util-logopenfile.c:423
strlcpy
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: util-strlcpyu.c:43
LogFileCtx_::sock_type
int sock_type
Definition: util-logopenfile.h:106
OutputRegisterFileRotationFlag
void OutputRegisterFileRotationFlag(int *flag)
Register a flag for file rotation notification.
Definition: output.c:830
SCTimeToStringPattern
int SCTimeToStringPattern(time_t epoch, const char *pattern, char *str, size_t size)
Convert epoch time to string pattern.
Definition: util-time.c:547
LogFileWrite
int LogFileWrite(LogFileCtx *file_ctx, MemBuffer *buffer)
Definition: util-logopenfile.c:820
SCPluginFileType_::Write
int(* Write)(const char *buffer, int buffer_len, void *ctx)
Definition: suricata-plugin.h:52
SC_WARN_CHMOD
@ SC_WARN_CHMOD
Definition: util-error.h:330
LogFileCtx_::rotate_interval
uint64_t rotate_interval
Definition: util-logopenfile.h:114
DEFAULT_LOG_FILETYPE
#define DEFAULT_LOG_FILETYPE
Definition: output.h:31
LogFileCtx_::is_sock
int is_sock
Definition: util-logopenfile.h:105
SCFwriteUnlocked
#define SCFwriteUnlocked
Definition: suricata-common.h:530
LogFileCtx_::dropped
uint64_t dropped
Definition: util-logopenfile.h:150
SCFflushUnlocked
#define SCFflushUnlocked
Definition: suricata-common.h:531
SCMutexUnlock
#define SCMutexUnlock(mut)
Definition: threads-debug.h:119
LogFileEnsureExists
LogFileCtx * LogFileEnsureExists(LogFileCtx *parent_ctx, int thread_id)
LogFileEnsureExists() Ensure a log file context for the thread exists.
Definition: util-logopenfile.c:659
LogFileCtx_::type
enum LogFileType type
Definition: util-logopenfile.h:93
SC_ERR_INVALID_ARGUMENT
@ SC_ERR_INVALID_ARGUMENT
Definition: util-error.h:43
LOGFILE_TYPE_FILE
@ LOGFILE_TYPE_FILE
Definition: util-logopenfile.h:40
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:282
LogFileCtx_::threads
LogThreadedFileCtx * threads
Definition: util-logopenfile.h:64
SC_ATOMIC_SUB
#define SC_ATOMIC_SUB(name, val)
sub a value from our atomic variable
Definition: util-atomic.h:342
SC_ERR_FOPEN
@ SC_ERR_FOPEN
Definition: util-error.h:74
LOGFILE_TYPE_PLUGIN
@ LOGFILE_TYPE_PLUGIN
Definition: util-logopenfile.h:45
conf.h
LogFileCtx_::syslog_setup
SyslogSetup syslog_setup
Definition: util-logopenfile.h:72
LOGFILE_TYPE_UNIX_DGRAM
@ LOGFILE_TYPE_UNIX_DGRAM
Definition: util-logopenfile.h:42
LOGFILE_TYPE_UNIX_STREAM
@ LOGFILE_TYPE_UNIX_STREAM
Definition: util-logopenfile.h:43
MemBuffer_
Definition: util-buffer.h:27
LogFileCtx_::is_regular
uint8_t is_regular
Definition: util-logopenfile.h:134
SCLogInfo
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:217
SC_ERR_INVALID_YAML_CONF_ENTRY
@ SC_ERR_INVALID_YAML_CONF_ENTRY
Definition: util-error.h:169
SCMutexInit
#define SCMutexInit(mut, mutattrs)
Definition: threads-debug.h:116
SCRealloc
#define SCRealloc(ptr, sz)
Definition: util-mem.h:50
ConfNodeLookupChild
ConfNode * ConfNodeLookupChild(const ConfNode *node, const char *name)
Lookup a child configuration node by name.
Definition: conf.c:814
LogFileCtx_::parent
struct LogFileCtx_ * parent
Definition: util-logopenfile.h:89
StringParseUint32
int StringParseUint32(uint32_t *res, int base, uint16_t len, const char *str)
Definition: util-byte.c:313
LogThreadedFileCtx_
Definition: util-logopenfile.h:52
suricata-common.h
LogFileCtx_::output_errors
uint64_t output_errors
Definition: util-logopenfile.h:152
LogThreadedFileCtx_::slot_count
int slot_count
Definition: util-logopenfile.h:53
ConfNode_::name
char * name
Definition: conf.h:33
MemBufferWriteString
#define MemBufferWriteString(dst,...)
Write a string buffer to the Membuffer dst.
Definition: util-buffer.h:162
PathIsAbsolute
int PathIsAbsolute(const char *path)
Check if a path is absolute.
Definition: util-path.c:39
SCLogError
#define SCLogError(err_code,...)
Macro used to log ERROR messages.
Definition: util-debug.h:257
LogFileFreeCtx
int LogFileFreeCtx(LogFileCtx *lf_ctx)
LogFileFreeCtx() Destroy a LogFileCtx (Close the file and free memory)
Definition: util-logopenfile.c:766
SC_ERR_REDIS
@ SC_ERR_REDIS
Definition: util-error.h:327
SCStrdup
#define SCStrdup(s)
Definition: util-mem.h:56
FatalError
#define FatalError(x,...)
Definition: util-debug.h:532
LogFileCtx_::rotate_time
time_t rotate_time
Definition: util-logopenfile.h:111
tv
ThreadVars * tv
Definition: fuzz_decodepcapfile.c:29
RunmodeGetCurrent
int RunmodeGetCurrent(void)
Definition: suricata.c:272
SCMalloc
#define SCMalloc(sz)
Definition: util-mem.h:47
ConfigGetLogDirectory
const char * ConfigGetLogDirectory()
Definition: util-conf.c:35
SCLogWarning
#define SCLogWarning(err_code,...)
Macro used to log WARNING messages.
Definition: util-debug.h:244
SCFree
#define SCFree(p)
Definition: util-mem.h:61
ConfNode_
Definition: conf.h:32
util-logopenfile.h
SC_ERR_FATAL
@ SC_ERR_FATAL
Definition: util-error.h:203
LOGFILE_ROTATE_INTERVAL
#define LOGFILE_ROTATE_INTERVAL
Definition: util-logopenfile.h:161
ConfValIsFalse
int ConfValIsFalse(const char *val)
Check if a value is false.
Definition: conf.c:590
LogThreadedFileCtx_::mutex
SCMutex mutex
Definition: util-logopenfile.h:54
LogFileCtx_::prefix
char * prefix
Definition: util-logopenfile.h:118
SC_ERR_MEM_ALLOC
@ SC_ERR_MEM_ALLOC
Definition: util-error.h:31
SC_ERR_LOG_OUTPUT
@ SC_ERR_LOG_OUTPUT
Definition: util-error.h:368
LogFileCtx_::flags
uint8_t flags
Definition: util-logopenfile.h:127
LogFileCtx_::Close
void(* Close)(struct LogFileCtx_ *fp)
Definition: util-logopenfile.h:79
MEMBUFFER_BUFFER
#define MEMBUFFER_BUFFER(mem_buffer)
Get the MemBuffers underlying buffer.
Definition: util-buffer.h:50
SCLogNotice
#define SCLogNotice(...)
Macro used to log NOTICE messages.
Definition: util-debug.h:232
OutputUnregisterFileRotationFlag
void OutputUnregisterFileRotationFlag(int *flag)
Unregister a file rotation flag.
Definition: output.c:852
MEMBUFFER_OFFSET
#define MEMBUFFER_OFFSET(mem_buffer)
Get the MemBuffers current offset.
Definition: util-buffer.h:55
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
SCReturnInt
#define SCReturnInt(x)
Definition: util-debug.h:304
SCMutexDestroy
#define SCMutexDestroy
Definition: threads-debug.h:120
LogFileCtx_::fp
FILE * fp
Definition: util-logopenfile.h:62
LogFileCtx_::plugin_data
void * plugin_data
Definition: util-logopenfile.h:65
output.h
LogFileCtx_::threaded
bool threaded
Definition: util-logopenfile.h:88
SCCreateDirectoryTree
int SCCreateDirectoryTree(const char *path, const bool final)
Recursively create a directory.
Definition: util-path.c:123
LogFileCtx_::filemode
uint32_t filemode
Definition: util-logopenfile.h:99
ConfNodeLookupChildValue
const char * ConfNodeLookupChildValue(const ConfNode *node, const char *name)
Lookup the value of a child configuration node by name.
Definition: conf.c:842