From c2b80af83f9ac19fefc21493c5a21ca232662ee2 Mon Sep 17 00:00:00 2001
From: Tobias Markmann <tm@ayena.de>
Date: Thu, 25 Feb 2016 10:10:19 +0100
Subject: Fix data race in BoostConnection reported by TSAN

ThreadSanitizer reported a data-race between Boost's socket
close() and async_read_some().

Test-Information:

Verified all tests still pass and that TSAN does not report
an error anymore in a scenario where a Client connects/dis-
connects randomly.

Tested on Debian 8 and OS X 10.11.3.

Change-Id: I5e705efb15bee767dd5a55539854b5e488b3bf64

diff --git a/Swiften/Network/BoostConnection.cpp b/Swiften/Network/BoostConnection.cpp
index f495795..a88a739 100644
--- a/Swiften/Network/BoostConnection.cpp
+++ b/Swiften/Network/BoostConnection.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
  * All rights reserved.
  * See the COPYING file for more information.
  */
@@ -7,7 +7,6 @@
 #include <Swiften/Network/BoostConnection.h>
 
 #include <algorithm>
-#include <iostream>
 #include <string>
 
 #include <boost/asio/placeholders.hpp>
@@ -86,6 +85,7 @@ void BoostConnection::disconnect() {
 }
 
 void BoostConnection::closeSocket() {
+	boost::lock_guard<boost::mutex> lock(readCloseMutex_);
 	boost::system::error_code errorCode;
 	socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, errorCode);
 	socket_.close();
@@ -120,6 +120,7 @@ void BoostConnection::handleConnectFinished(const boost::system::error_code& err
 
 void BoostConnection::doRead() {
 	readBuffer_ = boost::make_shared<SafeByteArray>(BUFFER_SIZE);
+	boost::lock_guard<boost::mutex> lock(readCloseMutex_);
 	socket_.async_read_some(
 			boost::asio::buffer(*readBuffer_),
 			boost::bind(&BoostConnection::handleSocketRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
diff --git a/Swiften/Network/BoostConnection.h b/Swiften/Network/BoostConnection.h
index f933cd8..be44d51 100644
--- a/Swiften/Network/BoostConnection.h
+++ b/Swiften/Network/BoostConnection.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
  * All rights reserved.
  * See the COPYING file for more information.
  */
@@ -76,5 +76,6 @@ namespace Swift {
 			bool writing_;
 			SafeByteArray writeQueue_;
 			bool closeSocketAfterNextWrite_;
+			boost::mutex readCloseMutex_;
 	};
 }
-- 
cgit v0.10.2-6-g49f6