]> The Tcpdump Group git mirrors - tcpdump/commitdiff
fix bittok2str_internal() w/o separator (GH #391)
authorDenis Ovsienko <[email protected]>
Thu, 5 Jun 2014 20:56:05 +0000 (00:56 +0400)
committerDenis Ovsienko <[email protected]>
Thu, 5 Jun 2014 20:56:05 +0000 (00:56 +0400)
Simplify separator string handling in bittok2str_internal(): use empty
value for the first snprintf() call and set new value after each use.
This makes the terminating null char management unnecessary, especially
that it missed the case where there was no separator and no match (it
would return the previous content of the static buffer unchanged).

This change may affect the output of tcpdump in that before it could
print either "[]" or "[none]" or a string like "[S.]" for TCP flags
value 0. Now it prints "[none]" as that is exactly the value passed to
bittok2str_nosep() in tcp_print().

util.c

diff --git a/util.c b/util.c
index 12a15023e6d2a6145aa22f508585e11eb624da26..1ce46530cb3efd496cd7d33cae02ff60be6d9c25 100644 (file)
--- a/util.c
+++ b/util.c
@@ -320,6 +320,7 @@ bittok2str_internal(register const struct tok *lp, register const char *fmt,
         int buflen=0;
         register int rotbit; /* this is the bit we rotate through all bitpositions */
         register int tokval;
+        const char * sepstr = "";
 
        while (lp != NULL && lp->s != NULL) {
             tokval=lp->v;   /* load our first value */
@@ -332,7 +333,8 @@ bittok2str_internal(register const struct tok *lp, register const char *fmt,
                if (tokval == (v&rotbit)) {
                     /* ok we have found something */
                     buflen+=snprintf(buf+buflen, sizeof(buf)-buflen, "%s%s",
-                                     lp->s, sep ? ", " : "");
+                                     sepstr, lp->s);
+                    sepstr = sep ? ", " : "";
                     break;
                 }
                 rotbit=rotbit<<1; /* no match - lets shift and try again */
@@ -340,23 +342,10 @@ bittok2str_internal(register const struct tok *lp, register const char *fmt,
             lp++;
        }
 
-        /* user didn't want string seperation - no need to cut off trailing seperators */
-        if (!sep) {
-            return (buf);
-        }
-
-        if (buflen != 0) { /* did we find anything */
-            /* yep, set the trailing zero 2 bytes before to eliminate the last comma & whitespace */
-            buf[buflen-2] = '\0';
-            return (buf);
-        }
-        else {
+        if (buflen == 0)
             /* bummer - lets print the "unknown" message as advised in the fmt string if we got one */
-            if (fmt == NULL)
-               fmt = "#%d";
-            (void)snprintf(buf, sizeof(buf), fmt, v);
-            return (buf);
-        }
+            (void)snprintf(buf, sizeof(buf), fmt == NULL ? "#%d" : fmt, v);
+        return (buf);
 }
 
 /*