]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
output-json: don't alloc for JSON to string
authorVictor Julien <victor@inliniac.net>
Sun, 1 Nov 2015 22:43:59 +0000 (23:43 +0100)
committerVictor Julien <victor@inliniac.net>
Sun, 22 Nov 2015 10:35:47 +0000 (11:35 +0100)
src/output-json.c
src/util-logopenfile.c

index f80120d47e68fa8f20877f5c50e33a9e9147703a..ed54d0df313dbcfc7d3d2f3ce72022be99354746 100644 (file)
@@ -335,16 +335,28 @@ json_t *CreateJSONHeaderWithTxId(Packet *p, int direction_sensitive, char *event
     return js;
 }
 
-int OutputJSONBuffer(json_t *js, LogFileCtx *file_ctx, MemBuffer *buffer)
+static int MemBufferCallback(const char *str, size_t size, void *data)
 {
-    char *js_s = NULL;
+    MemBuffer *memb = data;
+#if 0 // can't expand, need a MemBuffer **
+    /* since we can have many threads, the buffer might not be big enough.
+     *              * Expand if necessary. */
+    if (MEMBUFFER_OFFSET(memb) + size > MEMBUFFER_SIZE(memb)) {
+        MemBufferExpand(&memb, OUTPUT_BUFFER_SIZE);
+    }
+#endif
+    MemBufferWriteString(memb, "%s", str);
+    return 0;
+}
 
+int OutputJSONBuffer(json_t *js, LogFileCtx *file_ctx, MemBuffer *buffer)
+{
     if (file_ctx->sensor_name) {
         json_object_set_new(js, "host",
                             json_string(file_ctx->sensor_name));
     }
 
-    js_s = json_dumps(js,
+    int r = json_dump_callback(js, MemBufferCallback, buffer,
             JSON_PRESERVE_ORDER|JSON_COMPACT|JSON_ENSURE_ASCII|
 #ifdef JSON_ESCAPE_SLASH
                             JSON_ESCAPE_SLASH
@@ -352,12 +364,12 @@ int OutputJSONBuffer(json_t *js, LogFileCtx *file_ctx, MemBuffer *buffer)
                             0
 #endif
                             );
-    if (unlikely(js_s == NULL))
+    if (r != 0)
         return TM_ECODE_OK;
 
-    LogFileWrite(file_ctx, buffer, js_s, strlen(js_s));
-
-    free(js_s);
+    LogFileWrite(file_ctx, buffer,
+           (char *)MEMBUFFER_BUFFER(buffer),
+                   MEMBUFFER_OFFSET(buffer));
     return 0;
 }
 
index c91e039c32dd2ae34f013179e993fe42d51c74b1..d2bc61b4e88e7daa93682b23fdc621131c33b380 100644 (file)
@@ -623,10 +623,11 @@ int LogFileWrite(LogFileCtx *file_ctx, MemBuffer *buffer, char *string, size_t s
                file_ctx->type == LOGFILE_TYPE_UNIX_DGRAM ||
                file_ctx->type == LOGFILE_TYPE_UNIX_STREAM)
     {
+        /* append \n for files only */
+        MemBufferWriteString(buffer, "\n");
         SCMutexLock(&file_ctx->fp_mutex);
-        MemBufferWriteString(buffer, "%s\n", string);
         file_ctx->Write((const char *)MEMBUFFER_BUFFER(buffer),
-            MEMBUFFER_OFFSET(buffer), file_ctx);
+                        MEMBUFFER_OFFSET(buffer), file_ctx);
         SCMutexUnlock(&file_ctx->fp_mutex);
     }
 #ifdef HAVE_LIBHIREDIS