From 3020f63bd17cf1a4f0450e6c39a95d210f5ad976 Mon Sep 17 00:00:00 2001
From: Marc Hoersken <info@marc-hoersken.de>
Date: Sun, 7 Apr 2013 10:34:32 +0200
Subject: [PATCH] cookie.c: Made cookie sort function more deterministic

Since qsort implementations vary with regards to handling the order
of similiar elements, this change makes the internal sort function
more deterministic by comparing path length first, then domain length
and finally the cookie name. Spotted with testcase 62 on Windows.
---
 lib/cookie.c | 27 ++++++++++++++++++++++++---
 1 file changed, 24 insertions(+), 3 deletions(-)

diff --git a/lib/cookie.c b/lib/cookie.c
index c111976..72c8412 100644
--- a/lib/cookie.c
+++ b/lib/cookie.c
@@ -777,11 +777,32 @@ static int cookie_sort(const void *p1, const void *p2)
 {
   struct Cookie *c1 = *(struct Cookie **)p1;
   struct Cookie *c2 = *(struct Cookie **)p2;
+  size_t l1, l2;
+  int cmp;
 
-  size_t l1 = c1->path?strlen(c1->path):0;
-  size_t l2 = c2->path?strlen(c2->path):0;
+  /* compare cooke path */
+  l1 = c1->path ? strlen(c1->path) : 0;
+  l2 = c2->path ? strlen(c2->path) : 0;
 
-  return (l2 > l1) ? 1 : (l2 < l1) ? -1 : 0 ;
+  if(l1 != l2)
+    return l2 - l1;
+
+  /* fallback 1: compare cookie domain */
+  l1 = c1->domain ? strlen(c1->domain) : 0;
+  l2 = c2->domain ? strlen(c2->domain) : 0;
+
+  if(l1 != l2)
+    return l2 - l1;
+
+  /* fallback 2: compare cookie name */
+  if(c1->name && c2->name) {
+    cmp = strcmp(c1->name, c2->name);
+    if(cmp)
+      return cmp;
+  }
+
+  /* sorry, can't be more deterministic */
+  return 0;
 }
 
 /*****************************************************************************
-- 
1.8.0.msysgit.0

