Code

snort plugin: Improve error handling.
[collectd.git] / src / snort.c
index 6da5030296a83400d9c7181236d24d5eab075b7b..a49cb5fe52a0b1f4c7b061fba733d02a426a2a99 100644 (file)
@@ -94,13 +94,12 @@ static int snort_read(user_data_t *ud){
 
     int i;
     int fd;
-    int metrics_num;
 
     char **metrics;
-    char **metrics_t;
+    int metrics_num;
 
     struct stat sb;
-    char *buf, *buf_t;
+    char *buf, *buf_ptr;
 
     /* mmap, char pointers */
     char *p_start;
@@ -117,11 +116,13 @@ static int snort_read(user_data_t *ud){
 
     if ((fstat(fd, &sb) != 0) || (!S_ISREG(sb.st_mode))){
         ERROR("snort plugin: `%s' is not a file.", id->path);
+        close (fd);
         return (-1);
     }
 
     if (sb.st_size == 0){
         ERROR("snort plugin: `%s' is empty.", id->path);
+        close (fd);
         return (-1);
     }
 
@@ -129,6 +130,7 @@ static int snort_read(user_data_t *ud){
         /* offset = */ 0);
     if (p_start == MAP_FAILED){
         ERROR("snort plugin: mmap error");
+        close (fd);
         return (-1);
     }
 
@@ -148,16 +150,20 @@ static int snort_read(user_data_t *ud){
 
     if (metrics_num == 1){
         ERROR("snort plugin: last line of `%s' does not contain enough values.", id->path);
+        close (fd);
+        munmap(p_start, sb.st_size);
         return (-1);
     }
 
     if (*p_end == '#'){
         ERROR("snort plugin: last line of `%s' is a comment.", id->path);
+        close (fd);
+        munmap(p_start, sb.st_size);
         return (-1);
     }
 
     /* Copy the line to the buffer */
-    buf_t = buf = strdup(p_end);
+    buf = strdup(p_end);
 
     /* Done with mmap and file pointer */
     close(fd);
@@ -167,13 +173,23 @@ static int snort_read(user_data_t *ud){
     metrics = calloc (metrics_num, sizeof (*metrics));
     if (metrics == NULL) {
         ERROR ("snort plugin: calloc failed.");
+        sfree (buf);
         return (-1);
     }
 
-    for (metrics_t = metrics; (*metrics_t = strsep(&buf_t, ",")) != NULL;)
-        if (**metrics_t != '\0')
-            if (++metrics_t >= &metrics[metrics_num])
-                break;
+    buf_ptr = buf;
+    i = 0;
+    while (buf_ptr != NULL) {
+        char *next = strchr (buf_ptr, ',');
+        if (next != NULL) {
+            *next = 0;
+            next++;
+        }
+        metrics[i] = buf_ptr;
+        buf_ptr = next;
+        i++;
+    }
+    assert (i == metrics_num);
 
     /* Set last time */
     id->last = TIME_T_TO_CDTIME_T(strtol(*metrics, NULL, 0));