]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
logging: create log directories when needed
authorMats Klepsland <mats.klepsland@gmail.com>
Tue, 14 Feb 2017 09:32:33 +0000 (10:32 +0100)
committerVictor Julien <victor@inliniac.net>
Thu, 6 Apr 2017 14:19:45 +0000 (16:19 +0200)
Recursively create new log directories when needed. This makes it
possible to use date modifiers in the file path to create
directories based on date, e.g.:

  /var/log/suricata/2017/02/14/

src/util-logopenfile.c

index cc1f0b1fb96e4ee3a3532c10447a744a9d46699f..873df9c8357085cf0b524850d2370403d28235f6 100644 (file)
@@ -188,6 +188,41 @@ static char *SCLogFilenameFromPattern(const char *pattern)
     return filename;
 }
 
+/** \brief recursively create missing log directories
+ *  \param path path to log file
+ *  \retval 0 on success
+ *  \retval -1 on error
+ */
+static int SCLogCreateDirectoryTree(const char *filepath)
+{
+    char pathbuf[PATH_MAX];
+    char *p;
+    size_t len = strlen(filepath);
+
+    if (len > PATH_MAX - 1) {
+        return -1;
+    }
+
+    strlcpy(pathbuf, filepath, len);
+
+    for (p = pathbuf + 1; *p; p++) {
+        if (*p == '/') {
+            /* Truncate, while creating directory */
+            *p = '\0';
+
+            if (mkdir(pathbuf, S_IRWXU | S_IRGRP | S_IXGRP) != 0) {
+                if (errno != EEXIST) {
+                    return -1;
+                }
+            }
+
+            *p = '/';
+        }
+    }
+
+    return 0;
+}
+
 static void SCLogFileClose(LogFileCtx *log_ctx)
 {
     if (log_ctx->fp)
@@ -211,6 +246,12 @@ SCLogOpenFileFp(const char *path, const char *append_setting, uint32_t mode)
         return NULL;
     }
 
+    int rc = SCLogCreateDirectoryTree(filename);
+    if (rc < 0) {
+        SCFree(filename);
+        return NULL;
+    }
+
     if (ConfValIsTrue(append_setting)) {
         ret = fopen(filename, "a");
     } else {