]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
Introduce BytesToString utility
authorVictor Julien <victor@inliniac.net>
Fri, 31 Jan 2014 11:21:47 +0000 (12:21 +0100)
committerVictor Julien <victor@inliniac.net>
Fri, 31 Jan 2014 12:30:12 +0000 (13:30 +0100)
Introduce a utility function to convert an array of bytes into a
null-terminated string:

 char *BytesToString(const uint8_t *bytes, size_t nbytes);

All non-printables are copied over, except for '\0', which is
turned into literal '\' '0' in the string. So the resulting string
may be bigger than the input.

src/util-byte.c
src/util-byte.h

index e3d276b2a264d72f0d5ddc730fee5a1756c01bff..65bf35baa13446cc9a488572a7e0fb0865a5de66 100644 (file)
 #include "util-unittest.h"
 #include "util-debug.h"
 
+/** \brief Turn byte array into string.
+ *
+ *  All non-printables are copied over, except for '\0', which is
+ *  turned into literal \0 in the string.
+ *
+ *  \param bytes byte array
+ *  \param nbytes number of bytes
+ *  \return string nul-terminated string or NULL on error
+ */
+char *BytesToString(const uint8_t *bytes, size_t nbytes)
+{
+    size_t n = nbytes + 1;
+    size_t nulls = 0;
+
+    size_t u;
+    for (u = 0; u < nbytes; u++) {
+        if (bytes[u] == '\0')
+            nulls++;
+    }
+    n += nulls;
+
+    char *string = SCCalloc(1, n);
+    if (string == NULL)
+        return NULL;
+
+    if (nulls == 0) {
+        /* no nulls */
+        memcpy(string, bytes, nbytes);
+    } else {
+        /* no nulls present */
+        char *dst = string;
+        for (u = 0; u < n; u++) {
+            if (bytes[u] == '\0') {
+                *dst++ = '\\';
+                *dst++ = '0';
+            } else {
+                *dst++ = bytes[u];
+            }
+        }
+    }
+    return string;
+}
+
 int ByteExtractUint64(uint64_t *res, int e, uint16_t len, const uint8_t *bytes)
 {
     uint64_t i64;
index 8175e5ca63adc11758e7f7606edbab5a576585a2..82c16a4d1c502f7938489f740ff4d08de1743bad 100644 (file)
 #define SCByteSwap64(x) bswap_64(x)
 #endif /* OS_FREEBSD */
 
+/** \brief Turn byte array into string.
+ *
+ *  All non-printables are copied over, except for '\0', which is
+ *  turned into literal \0 in the string.
+ *
+ *  \param bytes byte array
+ *  \param nbytes number of bytes
+ *  \return string nul-terminated string or NULL on error
+ */
+char *BytesToString(const uint8_t *bytes, size_t nbytes);
+
 /**
  * Extract bytes from a byte string and convert to a unint64_t.
  *