From 78682c15df5f808ee906010e0107500412b174f0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Henrik=20Grubbstr=C3=B6m=20=28Grubba=29?=
 <grubba@grubba.org>
Date: Wed, 27 Feb 2013 15:12:21 +0100
Subject: [PATCH] Mysql: Potential workaround for race-condition in create().

It seems mysql_real_connect() and/or mysql_close() aren't
fully thread-safe. When there's a high reconnect contention,
create() sometimes failed with ECONNREFUSED. A network scan
of the client could observe that a new connection was closed
by the client before the server had sent its greeting.

The bug has been observed as recently as in MySQL 5.5.30.
---
 src/modules/Mysql/mysql.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/modules/Mysql/mysql.c b/src/modules/Mysql/mysql.c
index 0e7166fafb..9c12f88636 100644
--- a/src/modules/Mysql/mysql.c
+++ b/src/modules/Mysql/mysql.c
@@ -482,13 +482,13 @@ static void pike_mysql_reconnect (int reconnect)
 
   MYSQL_ALLOW();
 
+#if defined(HAVE_MYSQL_PORT) || defined(HAVE_MYSQL_UNIX_PORT)
+  STUPID_PORT_LOCK();
+#endif /* HAVE_MYSQL_PORT || HAVE_MYSQL_UNIX_PORT */
 #ifdef HAVE_MYSQL_REAL_CONNECT
   socket = mysql_real_connect(mysql, host, user, password,
                               NULL, port, portptr, options);
 #else
-#if defined(HAVE_MYSQL_PORT) || defined(HAVE_MYSQL_UNIX_PORT)
-  STUPID_PORT_LOCK();
-#endif /* HAVE_MYSQL_PORT || HAVE_MYSQL_UNIX_PORT */
 
 #ifdef HAVE_MYSQL_PORT
   if (port) {
@@ -516,10 +516,10 @@ static void pike_mysql_reconnect (int reconnect)
   }
 #endif /* HAVE_MYSQL_UNIX_PORT */
 
+#endif /* HAVE_MYSQL_REAL_CONNECT */
 #if defined(HAVE_MYSQL_PORT) || defined(HAVE_MYSQL_UNIX_PORT)
   STUPID_PORT_UNLOCK();
 #endif /* HAVE_MYSQL_PORT || MAVE_MYSQL_UNIX_PORT*/
-#endif /* HAVE_MYSQL_REAL_CONNECT */
 
   MYSQL_DISALLOW();
 
-- 
GitLab