From cee4eabdff5bc56813ea32fa211e2451623eb13e Mon Sep 17 00:00:00 2001
From: Joe Mason <jmason@rim.com>
Date: Fri, 24 Aug 2012 12:48:17 -0400
Subject: [PATCH] Deal with writing to a socket before it's detected

---
 tests/libtest/libntlmconnect.c |   38 +++++++++++++++++++++++++++++++-------
 1 files changed, 31 insertions(+), 7 deletions(-)

diff --git a/tests/libtest/libntlmconnect.c b/tests/libtest/libntlmconnect.c
index cabd26f..da7cec6 100644
--- a/tests/libtest/libntlmconnect.c
+++ b/tests/libtest/libntlmconnect.c
@@ -21,6 +21,7 @@
  ***************************************************************************/
 #include "test.h"
 
+#include <assert.h>
 #include "testutil.h"
 #include "memdebug.h"
 
@@ -44,10 +45,18 @@ static size_t callback(char* ptr, size_t size, size_t nmemb, void* data)
     return 0;
   }
   /* sock will only be set for NTLM requests; for others it is -1 */
-  if (sock != -1 && sock != sockets[idx]) {
-    fprintf(stderr, "Handle %d started on socket %d and moved to %d\n", idx, sockets[idx], sock);
-    res = TEST_ERR_MAJOR_BAD;
-    return 0;
+  if (sock != -1) {
+    if (sockets[idx] == -1) {
+      /* Data was written for this request before the socket was detected by
+         multi_fdset. Record the socket now. */
+      sockets[idx] = sock;
+    }
+    else if (sock != sockets[idx]) {
+      fprintf(stderr, "Handle %d started on socket %d and moved to %d\n", idx,
+              sockets[idx], sock);
+      res = TEST_ERR_MAJOR_BAD;
+      return 0;
+    }
   }
   return size * nmemb;
 }
@@ -144,6 +153,9 @@ int test(char *url)
       if (!FD_ISSET(i, &fdread)) {
         continue;
       }
+
+      /* Check if this socket was already detected for an earlier handle (or
+         for this handle, num_handles-1, in the callback */
       for (j = 0; j < num_handles; ++j) {
         if (sockets[j] == i) {
           socket_exists = TRUE;
@@ -160,9 +172,21 @@ int test(char *url)
         goto test_cleanup;
       }
 
-      sockets[num_handles-1] = i;
-      found_new_socket = TRUE;
-      /* continue to make sure there's only one new handle */
+      /* Now we know the socket is for the most recent handle, num_handles-1 */
+      if (sockets[num_handles-1] != -1) {
+        /* A socket for this handle was already detected in the callback; if it
+           matched socket_exists should be true and we would never get here */
+        assert(i != sockets[num_handles-1]);
+        fprintf(stderr, "Handle %d wrote to socket %d then detected on %d\n",
+                num_handles-1, sockets[num_handles-1], i);
+        res = TEST_ERR_MAJOR_BAD;
+        goto test_cleanup;
+      }
+      else {
+        sockets[num_handles-1] = i;
+        found_new_socket = TRUE;
+        /* continue to make sure there's only one new handle */
+      }
     }
 
     if (state == NeedSocketForNewHandle) {
-- 
1.7.5.4

