From 87a2f26dde834652abcb1c358579c018422a6a8d Mon Sep 17 00:00:00 2001
From: Dave McCaldon <davem@intersys.com>
Date: Thu, 21 Jan 2010 09:06:34 -0500
Subject: [PATCH] Fix trace context lookup in libssh2_debug()

The trace context is actually a bitmask so that tracing output can be controlled by setting a bitmask using libssh2_trace().  However, the logic in libssh2_debug() that converted the context to a string was using the context value as an array index.  Because the code used a bounds check on the array, there was never a danger of a crash, but you would certainly either get the wrong string, or "unknown".

This patch adds a lookup that iterates over the context strings and uses it's index to check for the corresponding bit in the context.
---
 src/misc.c |   16 ++++++++++++----
 1 files changed, 12 insertions(+), 4 deletions(-)

diff --git a/src/misc.c b/src/misc.c
index ea6859e..44e68e1 100644
--- a/src/misc.c
+++ b/src/misc.c
@@ -340,14 +340,22 @@ _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format, ...)
         "Publickey",
         "Socket",
     };
+    const char* contexttext = contexts[0];
+    unsigned int contextindex;
 
-    if (context < 1 || context >= (int)ARRAY_SIZE(contexts)) {
-        context = 0;
-    }
     if (!(session->showmask & context)) {
         /* no such output asked for */
         return;
     }
+
+    /* Find the first matching context string for this message */
+    for (contextindex = 0; contextindex < ARRAY_SIZE(contexts); contextindex++) {
+        if ((context & (1 << contextindex)) != 0) {
+            contexttext = contexts[contextindex];
+            break;
+        }
+    }
+
     gettimeofday(&now, NULL);
     if(!firstsec) {
         firstsec = now.tv_sec;
@@ -355,7 +363,7 @@ _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format, ...)
     now.tv_sec -= firstsec;
 
     len = snprintf(buffer, sizeof(buffer), "[libssh2] %d.%06d %s: ",
-                   (int)now.tv_sec, (int)now.tv_usec, contexts[context]);
+                   (int)now.tv_sec, (int)now.tv_usec, contexttext);
 
     va_start(vargs, format);
     len += vsnprintf(buffer + len, 1535 - len, format, vargs);
-- 
1.6.4.4


