From f377207cb896679b4eab9f6773d9d071700852ad Mon Sep 17 00:00:00 2001
From: Tobias Markmann <tm@ayena.de>
Date: Thu, 21 Jan 2016 09:43:00 +0100
Subject: Stop timer during clean up of WhitespacePingLayer

AddressSanitizer reported a heap-buffer-overflow in
WhitespacePingLayer::handleTimerTick() which happened during
multiple restarts of a XMPP server. Under the assumption
that it was caused by not correctly stopping the timer, the
timer is now explicitly stopped if still active at destruction.

Test-Information:

Unable to reproduce the ASAN report. Unit tests still pass.

Change-Id: Ia0b7c3b613688750c4ce0ad40d759a0db4a52791

diff --git a/Swiften/StreamStack/WhitespacePingLayer.cpp b/Swiften/StreamStack/WhitespacePingLayer.cpp
index 00b931b..5ea5423 100644
--- a/Swiften/StreamStack/WhitespacePingLayer.cpp
+++ b/Swiften/StreamStack/WhitespacePingLayer.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
  * All rights reserved.
  * See the COPYING file for more information.
  */
@@ -8,8 +8,9 @@
 
 #include <boost/bind.hpp>
 
-#include <Swiften/Network/TimerFactory.h>
+#include <Swiften/Base/Log.h>
 #include <Swiften/Network/Timer.h>
+#include <Swiften/Network/TimerFactory.h>
 
 namespace Swift {
 
@@ -20,6 +21,14 @@ WhitespacePingLayer::WhitespacePingLayer(TimerFactory* timerFactory) : isActive(
 	timer->onTick.connect(boost::bind(&WhitespacePingLayer::handleTimerTick, this));
 }
 
+WhitespacePingLayer::~WhitespacePingLayer() {
+	SWIFT_LOG_ASSERT(!isActive, debug) << "WhitespacePingLayer still active at destruction." << std::endl;
+	if (isActive) {
+		timer->stop();
+	}
+	timer->onTick.disconnect(boost::bind(&WhitespacePingLayer::handleTimerTick, this));
+}
+
 void WhitespacePingLayer::writeData(const SafeByteArray& data) {
 	writeDataToChildLayer(data);
 }
diff --git a/Swiften/StreamStack/WhitespacePingLayer.h b/Swiften/StreamStack/WhitespacePingLayer.h
index 17b0654..7ed56ca 100644
--- a/Swiften/StreamStack/WhitespacePingLayer.h
+++ b/Swiften/StreamStack/WhitespacePingLayer.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.
  */
@@ -19,6 +19,7 @@ namespace Swift {
 	class SWIFTEN_API WhitespacePingLayer : public StreamLayer, boost::noncopyable {
 		public:
 			WhitespacePingLayer(TimerFactory* timerFactory);
+			virtual ~WhitespacePingLayer();
 
 			void setActive();
 			void setInactive();
-- 
cgit v0.10.2-6-g49f6