From 8472194d716e0e3b95a66bf5be45c246ee79d0af Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Remko=20Tron=C3=A7on?= <git@el-tramo.be>
Date: Wed, 18 May 2011 18:22:06 +0200
Subject: Propagate use of SafeByteArray down to the connection.


diff --git a/QA/Checker/IO.cpp b/QA/Checker/IO.cpp
index 2e14589..0e402f7 100644
--- a/QA/Checker/IO.cpp
+++ b/QA/Checker/IO.cpp
@@ -35,3 +35,8 @@ std::ostream& operator<<(std::ostream& os, const Swift::SafeByteArray& s) {
 	os.flags(oldFlags);
 	return os;
 }
+
+std::ostream& operator<<(std::ostream& os, const Swift::SafeString& s) {
+	os << s.toString();
+	return os;
+}
diff --git a/QA/Checker/IO.h b/QA/Checker/IO.h
index a369b56..79ec878 100644
--- a/QA/Checker/IO.h
+++ b/QA/Checker/IO.h
@@ -8,6 +8,8 @@
 
 #include <Swiften/Base/ByteArray.h>
 #include <Swiften/Base/SafeByteArray.h>
+#include <Swiften/Base/SafeString.h>
 
 std::ostream& operator<<(std::ostream& os, const Swift::ByteArray& s);
 std::ostream& operator<<(std::ostream& os, const Swift::SafeByteArray& s);
+std::ostream& operator<<(std::ostream& os, const Swift::SafeString& s);
diff --git a/Swiften/Base/SafeByteArray.h b/Swiften/Base/SafeByteArray.h
index c80a2c0..1ef850f 100644
--- a/Swiften/Base/SafeByteArray.h
+++ b/Swiften/Base/SafeByteArray.h
@@ -34,6 +34,10 @@ namespace Swift {
 		return SafeByteArray(c, c + n);
 	}
 
+	inline SafeByteArray createSafeByteArray(const unsigned char* c, size_t n) {
+		return SafeByteArray(c, c + n);
+	}
+
 	SafeByteArray createSafeByteArray(const SafeString& s);
 }
 
diff --git a/Swiften/Base/SafeString.h b/Swiften/Base/SafeString.h
index 0bd898d..44b0316 100644
--- a/Swiften/Base/SafeString.h
+++ b/Swiften/Base/SafeString.h
@@ -59,6 +59,10 @@ namespace Swift {
 				return data.size();
 			}
 
+			bool operator==(const SafeString& o) const {
+				return data == o.data;
+			}
+
 		private:
 			std::vector<char, SafeAllocator<char> > data;
 	};
diff --git a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
index 22b8016..1b2a36b 100644
--- a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
+++ b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
@@ -174,7 +174,7 @@ class ComponentConnectorTest : public CppUnit::TestFixture {
 				}
 
 				void disconnect() { assert(false); }
-				void write(const ByteArray&) { assert(false); }
+				void write(const SafeByteArray&) { assert(false); }
 				HostAddressPort getLocalAddress() const { return HostAddressPort(); }
 
 				EventLoop* eventLoop;
diff --git a/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp b/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp
index 9320ae1..3f22690 100644
--- a/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp
+++ b/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp
@@ -4,7 +4,7 @@
  * See Documentation/Licenses/GPLv3.txt for more information.
  */
 
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 
 #include <cppunit/extensions/HelperMacros.h>
 #include <cppunit/extensions/TestFactoryRegistry.h>
@@ -27,17 +27,17 @@ class ZLibCompressorTest : public CppUnit::TestFixture
 
 		void testProcess() {
 			ZLibCompressor testling;
-			ByteArray result = testling.process(createByteArray("foo"));
+			SafeByteArray result = testling.process(createSafeByteArray("foo"));
 
-			CPPUNIT_ASSERT_EQUAL(createByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11), result);
+			CPPUNIT_ASSERT_EQUAL(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11), result);
 		}
 
 		void testProcess_Twice() {
 			ZLibCompressor testling;
-			testling.process(createByteArray("foo"));
-			ByteArray result = testling.process(createByteArray("bar"));
+			testling.process(createSafeByteArray("foo"));
+			SafeByteArray result = testling.process(createSafeByteArray("bar"));
 
-			CPPUNIT_ASSERT_EQUAL(createByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff",9), result); 
+			CPPUNIT_ASSERT_EQUAL(createSafeByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff",9), result);
 		}
 };
 
diff --git a/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp b/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp
index 00aae6e..5dd8630 100644
--- a/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp
+++ b/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp
@@ -32,22 +32,22 @@ class ZLibDecompressorTest : public CppUnit::TestFixture
 
 		void testProcess() {
 			ZLibDecompressor testling;
-			ByteArray result = testling.process(createByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11));
+			SafeByteArray result = testling.process(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11));
 
-			CPPUNIT_ASSERT_EQUAL(createByteArray("foo"), result);
+			CPPUNIT_ASSERT_EQUAL(createSafeByteArray("foo"), result);
 		}
 
 		void testProcess_Twice() {
 			ZLibDecompressor testling;
-			testling.process(createByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11));
-			ByteArray result = testling.process(createByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff", 9)); 
+			testling.process(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11));
+			SafeByteArray result = testling.process(createSafeByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff", 9));
 
-			CPPUNIT_ASSERT_EQUAL(createByteArray("bar"), result);
+			CPPUNIT_ASSERT_EQUAL(createSafeByteArray("bar"), result);
 		}
 
 		void testProcess_Invalid() {
 			ZLibDecompressor testling;
-			CPPUNIT_ASSERT_THROW(testling.process(createByteArray("invalid")), ZLibException);
+			CPPUNIT_ASSERT_THROW(testling.process(createSafeByteArray("invalid")), ZLibException);
 		}
 
 		void testProcess_Huge() {
@@ -56,9 +56,9 @@ class ZLibDecompressorTest : public CppUnit::TestFixture
 			for (unsigned int i = 0; i < 2048; ++i) {
 				data.push_back(static_cast<char>(i));
 			}
-			ByteArray original(createByteArray(&data[0], data.size()));
-			ByteArray compressed = ZLibCompressor().process(original);
-			ByteArray decompressed = ZLibDecompressor().process(compressed);
+			SafeByteArray original(createSafeByteArray(&data[0], data.size()));
+			SafeByteArray compressed = ZLibCompressor().process(original);
+			SafeByteArray decompressed = ZLibDecompressor().process(compressed);
 
 			CPPUNIT_ASSERT_EQUAL(original, decompressed);
 		}
@@ -69,9 +69,9 @@ class ZLibDecompressorTest : public CppUnit::TestFixture
 			for (unsigned int i = 0; i < 1024; ++i) {
 				data.push_back(static_cast<char>(i));
 			}
-			ByteArray original(createByteArray(&data[0], data.size()));
-			ByteArray compressed = ZLibCompressor().process(original);
-			ByteArray decompressed = ZLibDecompressor().process(compressed);
+			SafeByteArray original(createSafeByteArray(&data[0], data.size()));
+			SafeByteArray compressed = ZLibCompressor().process(original);
+			SafeByteArray decompressed = ZLibDecompressor().process(compressed);
 
 			CPPUNIT_ASSERT_EQUAL(original, decompressed);
 		}
diff --git a/Swiften/Compress/ZLibCodecompressor.cpp b/Swiften/Compress/ZLibCodecompressor.cpp
index 872c154..0869d6b 100644
--- a/Swiften/Compress/ZLibCodecompressor.cpp
+++ b/Swiften/Compress/ZLibCodecompressor.cpp
@@ -25,8 +25,8 @@ ZLibCodecompressor::ZLibCodecompressor() {
 ZLibCodecompressor::~ZLibCodecompressor() {
 }
 
-ByteArray ZLibCodecompressor::process(const ByteArray& input) {
-	ByteArray output;
+SafeByteArray ZLibCodecompressor::process(const SafeByteArray& input) {
+	SafeByteArray output;
 	stream_.avail_in = input.size();
 	stream_.next_in = reinterpret_cast<Bytef*>(const_cast<unsigned char*>(vecptr(input)));
 	int outputPosition = 0;
diff --git a/Swiften/Compress/ZLibCodecompressor.h b/Swiften/Compress/ZLibCodecompressor.h
index c23f2d2..93babf0 100644
--- a/Swiften/Compress/ZLibCodecompressor.h
+++ b/Swiften/Compress/ZLibCodecompressor.h
@@ -8,7 +8,7 @@
 
 #include <zlib.h>
 
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 
 namespace Swift {
 	class ZLibCodecompressor {
@@ -16,7 +16,7 @@ namespace Swift {
 			ZLibCodecompressor();
 			virtual ~ZLibCodecompressor();
 
-			ByteArray process(const ByteArray& data);
+			SafeByteArray process(const SafeByteArray& data);
 			virtual int processZStream() = 0;
 
 		protected:
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
index fadfd46..477af4b 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
@@ -10,6 +10,7 @@
 #include <iostream>
 
 #include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 #include <Swiften/Base/Algorithm.h>
 #include <Swiften/Base/Concat.h>
 #include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
@@ -36,7 +37,7 @@ void SOCKS5BytestreamServerSession::stop() {
 	finish(false);
 }
 
-void SOCKS5BytestreamServerSession::handleDataRead(const ByteArray& data) {
+void SOCKS5BytestreamServerSession::handleDataRead(const SafeByteArray& data) {
 	append(unprocessedData, data);
 	process();
 }
@@ -56,7 +57,7 @@ void SOCKS5BytestreamServerSession::process() {
 					std::cerr << "SOCKS5BytestreamServerSession: Junk after authentication mechanism";
 				}
 				unprocessedData.clear();
-				connection->write(createByteArray("\x05\x00", 2));
+				connection->write(createSafeByteArray("\x05\x00", 2));
 				state = WaitingForRequest;
 			}
 		}
@@ -77,7 +78,7 @@ void SOCKS5BytestreamServerSession::process() {
 					std::cerr << "SOCKS5BytestreamServerSession: Junk after authentication mechanism";
 				}
 				bytestream = bytestreams->getBytestream(byteArrayToString(requestID));
-				ByteArray result = createByteArray("\x05", 1);
+				SafeByteArray result = createSafeByteArray("\x05", 1);
 				result.push_back(bytestream ? 0x0 : 0x4);
 				append(result, createByteArray("\x00\x03", 2));
 				result.push_back(static_cast<char>(requestID.size()));
@@ -99,7 +100,7 @@ void SOCKS5BytestreamServerSession::process() {
 void SOCKS5BytestreamServerSession::sendData() {
 	if (!bytestream->isFinished()) {
 		try {
-			connection->write(bytestream->read(chunkSize));
+			connection->write(createSafeByteArray(bytestream->read(chunkSize)));
 		}
 		catch (const BytestreamException&) {
 			finish(true);
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
index 80965fb..761a365 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
@@ -40,7 +40,7 @@ namespace Swift {
 		private:
 			void finish(bool error);
 			void process();
-			void handleDataRead(const ByteArray&);
+			void handleDataRead(const SafeByteArray&);
 			void sendData();
 
 		private:
diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
index d4c31c5..06bc98f 100644
--- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
@@ -48,7 +48,7 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
 			boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
 			StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
 
-			receive(createByteArray("\x05\x02\x01\x02"));
+			receive(createSafeByteArray("\x05\x02\x01\x02"));
 
 			CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData);
 		}
@@ -57,10 +57,10 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
 			boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
 			StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
 
-			receive(createByteArray("\x05\x02\x01"));
+			receive(createSafeByteArray("\x05\x02\x01"));
 
 			CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedData.size()));
-			receive(createByteArray("\x01"));
+			receive(createSafeByteArray("\x01"));
 			CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData);
 		}
 
@@ -71,7 +71,7 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
 			authenticate();
 
 			ByteArray hostname(createByteArray("abcdef"));
-			receive(concat(createByteArray("\x05\x01\x00\x03", 4), createByteArray(hostname.size()), hostname, createByteArray("\x00\x00", 2)));
+			receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(hostname.size()), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2)));
 			CPPUNIT_ASSERT(createByteArray("\x05\x00\x00\x03\x06\x61\x62\x63\x64\x65\x66\x00\x00", 13) == createByteArray(&receivedData[0], 13));
 		}
 
@@ -81,7 +81,7 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
 			authenticate();
 
 			ByteArray hostname(createByteArray("abcdef"));
-			receive(concat(createByteArray("\x05\x01\x00\x03", 4), createByteArray(hostname.size()), hostname, createByteArray("\x00\x00", 2)));
+			receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(hostname.size()), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2)));
 			CPPUNIT_ASSERT(createByteArray("\x05\x04\x00\x03\x06\x61\x62\x63\x64\x65\x66\x00\x00", 13) == receivedData);
 		}
 
@@ -113,19 +113,19 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
 		}
 
 	private:
-		void receive(const ByteArray& data) {
+		void receive(const SafeByteArray& data) {
 			connection->receive(data);
 			eventLoop->processEvents();
 		}
 
 		void authenticate() {
-			receive(createByteArray("\x05\x02\x01\x02"));
+			receive(createSafeByteArray("\x05\x02\x01\x02"));
 			receivedData.clear();
 			receivedDataChunks = 0;
 		}
 
 		void request(const std::string& hostname) {
-			receive(concat(createByteArray("\x05\x01\x00\x03", 4), createByteArray(hostname.size()), createByteArray(hostname), createByteArray("\x00\x00", 2)));
+			receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(hostname.size()), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2)));
 		}
 
 		void skipHeader(const std::string& hostname) {
@@ -134,7 +134,7 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
 		}
 
 
-		void handleDataWritten(const ByteArray& data) {
+		void handleDataWritten(const SafeByteArray& data) {
 			receivedData.insert(receivedData.end(), data.begin(), data.end());
 			receivedDataChunks++;
 		}
diff --git a/Swiften/Network/BoostConnection.cpp b/Swiften/Network/BoostConnection.cpp
index b56ad38..ac3b444 100644
--- a/Swiften/Network/BoostConnection.cpp
+++ b/Swiften/Network/BoostConnection.cpp
@@ -8,6 +8,7 @@
 
 #include <iostream>
 #include <string>
+#include <algorithm>
 #include <boost/bind.hpp>
 #include <boost/thread.hpp>
 #include <boost/asio/placeholders.hpp>
@@ -19,6 +20,7 @@
 #include <Swiften/Base/ByteArray.h>
 #include <Swiften/Network/HostAddressPort.h>
 #include <Swiften/Base/sleep.h>
+#include <Swiften/Base/SafeAllocator.h>
 
 namespace Swift {
 
@@ -29,8 +31,8 @@ static const size_t BUFFER_SIZE = 4096;
 // A reference-counted non-modifiable buffer class.
 class SharedBuffer {
 	public:
-		SharedBuffer(const ByteArray& data) : 
-				data_(new std::vector<char>(data.begin(), data.end())),
+		SharedBuffer(const SafeByteArray& data) :
+				data_(new std::vector<char, SafeAllocator<char> >(data.begin(), data.end())),
 				buffer_(boost::asio::buffer(*data_)) {
 		}
 
@@ -41,7 +43,7 @@ class SharedBuffer {
 		const boost::asio::const_buffer* end() const { return &buffer_ + 1; }
 
 	private:
-		boost::shared_ptr< std::vector<char> > data_;
+		boost::shared_ptr< std::vector<char, SafeAllocator<char> > > data_;
 		boost::asio::const_buffer buffer_;
 };
 
@@ -78,7 +80,7 @@ void BoostConnection::disconnect() {
 	socket_.close();
 }
 
-void BoostConnection::write(const ByteArray& data) {
+void BoostConnection::write(const SafeByteArray& data) {
 	boost::lock_guard<boost::mutex> lock(writeMutex_);
 	if (!writing_) {
 		writing_ = true;
@@ -89,7 +91,7 @@ void BoostConnection::write(const ByteArray& data) {
 	}
 }
 
-void BoostConnection::doWrite(const ByteArray& data) {
+void BoostConnection::doWrite(const SafeByteArray& data) {
 	boost::asio::async_write(socket_, SharedBuffer(data),
 			boost::bind(&BoostConnection::handleDataWritten, shared_from_this(), boost::asio::placeholders::error));
 }
@@ -114,7 +116,8 @@ void BoostConnection::doRead() {
 void BoostConnection::handleSocketRead(const boost::system::error_code& error, size_t bytesTransferred) {
 	SWIFT_LOG(debug) << "Socket read " << error << std::endl;
 	if (!error) {
-		eventLoop->postEvent(boost::bind(boost::ref(onDataRead), createByteArray(&readBuffer_[0], bytesTransferred)), shared_from_this());
+		eventLoop->postEvent(boost::bind(boost::ref(onDataRead), createSafeByteArray(&readBuffer_[0], bytesTransferred)), shared_from_this());
+		std::fill(readBuffer_.begin(), readBuffer_.end(), 0);
 		doRead();
 	}
 	else if (/*error == boost::asio::error::eof ||*/ error == boost::asio::error::operation_aborted) {
diff --git a/Swiften/Network/BoostConnection.h b/Swiften/Network/BoostConnection.h
index 0e7624d..259fcec 100644
--- a/Swiften/Network/BoostConnection.h
+++ b/Swiften/Network/BoostConnection.h
@@ -13,6 +13,7 @@
 
 #include <Swiften/Network/Connection.h>
 #include <Swiften/EventLoop/EventOwner.h>
+#include <Swiften/Base/SafeByteArray.h>
 
 namespace boost {
 	class thread;
@@ -37,7 +38,7 @@ namespace Swift {
 			virtual void listen();
 			virtual void connect(const HostAddressPort& address);
 			virtual void disconnect();
-			virtual void write(const ByteArray& data);
+			virtual void write(const SafeByteArray& data);
 
 			boost::asio::ip::tcp::socket& getSocket() {
 				return socket_;
@@ -52,15 +53,15 @@ namespace Swift {
 			void handleSocketRead(const boost::system::error_code& error, size_t bytesTransferred);
 			void handleDataWritten(const boost::system::error_code& error);
 			void doRead();
-			void doWrite(const ByteArray& data);
+			void doWrite(const SafeByteArray& data);
 
 		private:
 			EventLoop* eventLoop;
 			boost::shared_ptr<boost::asio::io_service> ioService;
 			boost::asio::ip::tcp::socket socket_;
-			std::vector<char> readBuffer_;
+			SafeByteArray readBuffer_;
 			boost::mutex writeMutex_;
 			bool writing_;
-			ByteArray writeQueue_;
+			SafeByteArray writeQueue_;
 	};
 }
diff --git a/Swiften/Network/Connection.h b/Swiften/Network/Connection.h
index 74d25aa..1b9977f 100644
--- a/Swiften/Network/Connection.h
+++ b/Swiften/Network/Connection.h
@@ -9,7 +9,7 @@
 #include <boost/shared_ptr.hpp>
 #include <Swiften/Base/boost_bsignals.h>
 
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 
 namespace Swift {
 	class HostAddressPort;
@@ -29,14 +29,14 @@ namespace Swift {
 			virtual void listen() = 0;
 			virtual void connect(const HostAddressPort& address) = 0;
 			virtual void disconnect() = 0;
-			virtual void write(const ByteArray& data) = 0;
+			virtual void write(const SafeByteArray& data) = 0;
 
 			virtual HostAddressPort getLocalAddress() const = 0;
 
 		public:
 			boost::signal<void (bool /* error */)> onConnectFinished;
 			boost::signal<void (const boost::optional<Error>&)> onDisconnected;
-			boost::signal<void (const ByteArray&)> onDataRead;
+			boost::signal<void (const SafeByteArray&)> onDataRead;
 			boost::signal<void ()> onDataWritten;
 	};
 }
diff --git a/Swiften/Network/DummyConnection.cpp b/Swiften/Network/DummyConnection.cpp
index ffc6dc2..9a9d138 100644
--- a/Swiften/Network/DummyConnection.cpp
+++ b/Swiften/Network/DummyConnection.cpp
@@ -14,8 +14,8 @@ namespace Swift {
 DummyConnection::DummyConnection(EventLoop* eventLoop) : eventLoop(eventLoop) {
 }
 
-void DummyConnection::receive(const ByteArray& data) {
-	eventLoop->postEvent(boost::bind(boost::ref(onDataRead), ByteArray(data)), shared_from_this());
+void DummyConnection::receive(const SafeByteArray& data) {
+	eventLoop->postEvent(boost::bind(boost::ref(onDataRead), SafeByteArray(data)), shared_from_this());
 }
 
 void DummyConnection::listen() {
diff --git a/Swiften/Network/DummyConnection.h b/Swiften/Network/DummyConnection.h
index 3024302..5191e30 100644
--- a/Swiften/Network/DummyConnection.h
+++ b/Swiften/Network/DummyConnection.h
@@ -25,18 +25,18 @@ namespace Swift {
 				//assert(false);
 			}
 
-			void write(const ByteArray& data) {
+			void write(const SafeByteArray& data) {
 				eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this());
 				onDataSent(data);
 			}
 
-			void receive(const ByteArray& data);
+			void receive(const SafeByteArray& data);
 
 			HostAddressPort getLocalAddress() const {
 				return localAddress;
 			}
 
-			boost::signal<void (const ByteArray&)> onDataSent;
+			boost::signal<void (const SafeByteArray&)> onDataSent;
 
 			EventLoop* eventLoop;
 			HostAddressPort localAddress;
diff --git a/Swiften/Network/FakeConnection.h b/Swiften/Network/FakeConnection.h
index 65f6650..99cb584 100644
--- a/Swiften/Network/FakeConnection.h
+++ b/Swiften/Network/FakeConnection.h
@@ -41,7 +41,7 @@ namespace Swift {
 			virtual void connect(const HostAddressPort& address);
 			virtual void disconnect();
 
-			virtual void write(const ByteArray& data) {
+			virtual void write(const SafeByteArray& data) {
 				dataWritten.push_back(data);
 			}
 
@@ -51,7 +51,7 @@ namespace Swift {
 
 			EventLoop* eventLoop;
 			boost::optional<HostAddressPort> connectedTo;
-			std::vector<ByteArray> dataWritten;
+			std::vector<SafeByteArray> dataWritten;
 			boost::optional<Error> error;
 			State state;
 			bool delayConnect;
diff --git a/Swiften/Network/HTTPConnectProxiedConnection.cpp b/Swiften/Network/HTTPConnectProxiedConnection.cpp
index 61fe597..20819ff 100644
--- a/Swiften/Network/HTTPConnectProxiedConnection.cpp
+++ b/Swiften/Network/HTTPConnectProxiedConnection.cpp
@@ -57,7 +57,7 @@ void HTTPConnectProxiedConnection::handleDisconnected(const boost::optional<Erro
 	onDisconnected(error);
 }
 
-void HTTPConnectProxiedConnection::write(const ByteArray& data) {
+void HTTPConnectProxiedConnection::write(const SafeByteArray& data) {
 	connection_->write(data);
 }
 
@@ -66,17 +66,17 @@ void HTTPConnectProxiedConnection::handleConnectionConnectFinished(bool error) {
 	if (!error) {
 		std::stringstream connect;
 		connect << "CONNECT " << server_.getAddress().toString() << ":" << server_.getPort() << " HTTP/1.1\r\n\r\n";
-		connection_->write(createByteArray(connect.str()));
+		connection_->write(createSafeByteArray(connect.str()));
 	}
 	else {
 		onConnectFinished(true);
 	}
 }
 
-void HTTPConnectProxiedConnection::handleDataRead(const ByteArray& data) {
+void HTTPConnectProxiedConnection::handleDataRead(const SafeByteArray& data) {
 	if (!connected_) {
-		SWIFT_LOG(debug) << byteArrayToString(data) << std::endl;
-		std::vector<std::string> tmp = String::split(byteArrayToString(data), ' ');
+		SWIFT_LOG(debug) << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl;
+		std::vector<std::string> tmp = String::split(byteArrayToString(ByteArray(data.begin(), data.end())), ' ');
 		if(tmp.size() > 1) {
 			int status = boost::lexical_cast<int> (tmp[1].c_str()); 
 			SWIFT_LOG(debug) << "Proxy Status: " << status << std::endl;
@@ -85,7 +85,7 @@ void HTTPConnectProxiedConnection::handleDataRead(const ByteArray& data) {
 				onConnectFinished(false);
 				return;
 			}
-			SWIFT_LOG(debug) << "HTTP Proxy returned an error: " << byteArrayToString(data) << std::endl;
+			SWIFT_LOG(debug) << "HTTP Proxy returned an error: " << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl;
 		}
 		disconnect();
 		onConnectFinished(true);
diff --git a/Swiften/Network/HTTPConnectProxiedConnection.h b/Swiften/Network/HTTPConnectProxiedConnection.h
index 4719267..96c6be8 100644
--- a/Swiften/Network/HTTPConnectProxiedConnection.h
+++ b/Swiften/Network/HTTPConnectProxiedConnection.h
@@ -34,14 +34,14 @@ namespace Swift {
 			virtual void listen();
 			virtual void connect(const HostAddressPort& address);
 			virtual void disconnect();
-			virtual void write(const ByteArray& data);
+			virtual void write(const SafeByteArray& data);
 
 			virtual HostAddressPort getLocalAddress() const;
 		private:
 			HTTPConnectProxiedConnection(ConnectionFactory* connectionFactory, HostAddressPort proxy);
 
 			void handleConnectionConnectFinished(bool error);
-			void handleDataRead(const ByteArray& data);
+			void handleDataRead(const SafeByteArray& data);
 			void handleDisconnected(const boost::optional<Error>& error);
 
 		private:
diff --git a/Swiften/Network/SOCKS5ProxiedConnection.cpp b/Swiften/Network/SOCKS5ProxiedConnection.cpp
index cf531e5..f8084ab 100644
--- a/Swiften/Network/SOCKS5ProxiedConnection.cpp
+++ b/Swiften/Network/SOCKS5ProxiedConnection.cpp
@@ -60,7 +60,7 @@ void SOCKS5ProxiedConnection::handleDisconnected(const boost::optional<Error>& e
 	onDisconnected(error);
 }
 
-void SOCKS5ProxiedConnection::write(const ByteArray& data) {
+void SOCKS5ProxiedConnection::write(const SafeByteArray& data) {
 	if (connection_) {
 		connection_->write(data);
 	}
@@ -72,7 +72,7 @@ void SOCKS5ProxiedConnection::handleConnectionConnectFinished(bool error) {
 		SWIFT_LOG(debug) << "Connection to proxy established, now connect to the server via it." << std::endl;
 		
 		proxyState_ = ProxyAuthenticating;
-		ByteArray socksConnect;
+		SafeByteArray socksConnect;
 		socksConnect.push_back(0x05); // VER = SOCKS5 = 0x05
 		socksConnect.push_back(0x01); // Number of authentication methods after this byte.
 		socksConnect.push_back(0x00); // 0x00 == no authentication
@@ -86,8 +86,8 @@ void SOCKS5ProxiedConnection::handleConnectionConnectFinished(bool error) {
 	}
 }
 
-void SOCKS5ProxiedConnection::handleDataRead(const ByteArray& data) {
-	ByteArray socksConnect;
+void SOCKS5ProxiedConnection::handleDataRead(const SafeByteArray& data) {
+	SafeByteArray socksConnect;
 	boost::asio::ip::address rawAddress = server_.getAddress().getRawAddress();
 	assert(rawAddress.is_v4() || rawAddress.is_v6());
 	if (!connected_) {
diff --git a/Swiften/Network/SOCKS5ProxiedConnection.h b/Swiften/Network/SOCKS5ProxiedConnection.h
index e594e0f..942b6ce 100644
--- a/Swiften/Network/SOCKS5ProxiedConnection.h
+++ b/Swiften/Network/SOCKS5ProxiedConnection.h
@@ -34,7 +34,7 @@ namespace Swift {
 			virtual void listen();
 			virtual void connect(const HostAddressPort& address);
 			virtual void disconnect();
-			virtual void write(const ByteArray& data);
+			virtual void write(const SafeByteArray& data);
 
 			virtual HostAddressPort getLocalAddress() const;
 
@@ -42,7 +42,7 @@ namespace Swift {
 			SOCKS5ProxiedConnection(ConnectionFactory* connectionFactory, const HostAddressPort& proxy);
 
 			void handleConnectionConnectFinished(bool error);
-			void handleDataRead(const ByteArray& data);
+			void handleDataRead(const SafeByteArray& data);
 			void handleDisconnected(const boost::optional<Error>& error);
 
 		private:
diff --git a/Swiften/Network/UnitTest/ChainedConnectorTest.cpp b/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
index 9c4c99d..c7d23da 100644
--- a/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
+++ b/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
@@ -128,7 +128,7 @@ class ChainedConnectorTest : public CppUnit::TestFixture {
 
 				HostAddressPort getLocalAddress() const { return HostAddressPort(); }
 				void disconnect() { assert(false); }
-				void write(const ByteArray&) { assert(false); }
+				void write(const SafeByteArray&) { assert(false); }
 
 				bool connects;
 				int id;
diff --git a/Swiften/Network/UnitTest/ConnectorTest.cpp b/Swiften/Network/UnitTest/ConnectorTest.cpp
index 6151b5c..6488e67 100644
--- a/Swiften/Network/UnitTest/ConnectorTest.cpp
+++ b/Swiften/Network/UnitTest/ConnectorTest.cpp
@@ -269,7 +269,7 @@ class ConnectorTest : public CppUnit::TestFixture {
 
 				HostAddressPort getLocalAddress() const { return HostAddressPort(); }
 				void disconnect() { assert(false); }
-				void write(const ByteArray&) { assert(false); }
+				void write(const SafeByteArray&) { assert(false); }
 
 				EventLoop* eventLoop;
 				boost::optional<HostAddressPort> hostAddressPort;
diff --git a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
index d33c988..90be27e 100644
--- a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
+++ b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
@@ -76,7 +76,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 			testling->connect(HostAddressPort(HostAddress("2.2.2.2"), 2345));
 			eventLoop->processEvents();
 
-			connectionFactory->connections[0]->onDataRead(createByteArray("HTTP/1.0 200 Connection established\r\n\r\n"));
+			connectionFactory->connections[0]->onDataRead(createSafeByteArray("HTTP/1.0 200 Connection established\r\n\r\n"));
 			eventLoop->processEvents();
 
 			CPPUNIT_ASSERT(connectFinished);
@@ -89,7 +89,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 			testling->connect(HostAddressPort(HostAddress("2.2.2.2"), 2345));
 			eventLoop->processEvents();
 
-			connectionFactory->connections[0]->onDataRead(createByteArray("FLOOP"));
+			connectionFactory->connections[0]->onDataRead(createSafeByteArray("FLOOP"));
 			eventLoop->processEvents();
 
 			CPPUNIT_ASSERT(connectFinished);
@@ -102,7 +102,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 			testling->connect(HostAddressPort(HostAddress("2.2.2.2"), 2345));
 			eventLoop->processEvents();
 
-			connectionFactory->connections[0]->onDataRead(createByteArray("HTTP/1.0 401 Unauthorized\r\n\r\n"));
+			connectionFactory->connections[0]->onDataRead(createSafeByteArray("HTTP/1.0 401 Unauthorized\r\n\r\n"));
 			eventLoop->processEvents();
 
 			CPPUNIT_ASSERT(connectFinished);
@@ -114,10 +114,10 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 			HTTPConnectProxiedConnection::ref testling(createTestling());
 			testling->connect(HostAddressPort(HostAddress("2.2.2.2"), 2345));
 			eventLoop->processEvents();
-			connectionFactory->connections[0]->onDataRead(createByteArray("HTTP/1.0 200 Connection established\r\n\r\n"));
+			connectionFactory->connections[0]->onDataRead(createSafeByteArray("HTTP/1.0 200 Connection established\r\n\r\n"));
 			eventLoop->processEvents();
 
-			connectionFactory->connections[0]->onDataRead(createByteArray("abcdef"));
+			connectionFactory->connections[0]->onDataRead(createSafeByteArray("abcdef"));
 
 			CPPUNIT_ASSERT_EQUAL(createByteArray("abcdef"), dataRead);
 		}
@@ -126,11 +126,11 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 			HTTPConnectProxiedConnection::ref testling(createTestling());
 			testling->connect(HostAddressPort(HostAddress("2.2.2.2"), 2345));
 			eventLoop->processEvents();
-			connectionFactory->connections[0]->onDataRead(createByteArray("HTTP/1.0 200 Connection established\r\n\r\n"));
+			connectionFactory->connections[0]->onDataRead(createSafeByteArray("HTTP/1.0 200 Connection established\r\n\r\n"));
 			eventLoop->processEvents();
 			connectionFactory->connections[0]->dataWritten.clear();
 
-			testling->write(createByteArray("abcdef"));
+			testling->write(createSafeByteArray("abcdef"));
 
 			CPPUNIT_ASSERT_EQUAL(createByteArray("abcdef"), connectionFactory->connections[0]->dataWritten);
 		}
@@ -151,7 +151,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 			HTTPConnectProxiedConnection::ref testling(createTestling());
 			testling->connect(HostAddressPort(HostAddress("2.2.2.2"), 2345));
 			eventLoop->processEvents();
-			connectionFactory->connections[0]->onDataRead(createByteArray("HTTP/1.0 200 Connection established\r\n\r\n"));
+			connectionFactory->connections[0]->onDataRead(createSafeByteArray("HTTP/1.0 200 Connection established\r\n\r\n"));
 			eventLoop->processEvents();
 
 			testling->disconnect();
@@ -180,7 +180,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 			disconnectedError = e;
 		}
 
-		void handleDataRead(const ByteArray& d) {
+		void handleDataRead(const SafeByteArray& d) {
 			append(dataRead, d);
 		}
 
@@ -204,7 +204,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 					onDisconnected(boost::optional<Connection::Error>());
 				}
 				
-				void write(const ByteArray& d) { 
+				void write(const SafeByteArray& d) {
 					append(dataWritten, d);
 				}
 
diff --git a/Swiften/QA/NetworkTest/BoostConnectionTest.cpp b/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
index 3d3c3c4..31d5d82 100644
--- a/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
+++ b/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
@@ -103,9 +103,9 @@ class BoostConnectionTest : public CppUnit::TestFixture {
 				eventLoop_->processEvents();
 			}
 
-			testling->write(createByteArray("<stream:strea"));
-			testling->write(createByteArray("m"));
-			testling->write(createByteArray(">"));
+			testling->write(createSafeByteArray("<stream:strea"));
+			testling->write(createSafeByteArray("m"));
+			testling->write(createSafeByteArray(">"));
 
 			 // Check that we only did one write event, the others are queued
 			/*int runHandlers = */boostIOService->poll();
@@ -127,11 +127,11 @@ class BoostConnectionTest : public CppUnit::TestFixture {
 		}
 
 		void doWrite(BoostConnection* connection) {
-			connection->write(createByteArray("<stream:stream>"));
-			connection->write(createByteArray("\r\n\r\n")); // Temporarily, while we don't have an xmpp server running on ipv6
+			connection->write(createSafeByteArray("<stream:stream>"));
+			connection->write(createSafeByteArray("\r\n\r\n")); // Temporarily, while we don't have an xmpp server running on ipv6
 		}
 
-		void handleDataRead(const ByteArray& data) {
+		void handleDataRead(const SafeByteArray& data) {
 			append(receivedData, data);
 		}
 
diff --git a/Swiften/Serializer/AuthChallengeSerializer.cpp b/Swiften/Serializer/AuthChallengeSerializer.cpp
index 6848ad1..445059d 100644
--- a/Swiften/Serializer/AuthChallengeSerializer.cpp
+++ b/Swiften/Serializer/AuthChallengeSerializer.cpp
@@ -15,7 +15,7 @@ namespace Swift {
 AuthChallengeSerializer::AuthChallengeSerializer() {
 }
 
-std::string AuthChallengeSerializer::serialize(boost::shared_ptr<Element> element)  const {
+SafeString AuthChallengeSerializer::serialize(boost::shared_ptr<Element> element)  const {
 	boost::shared_ptr<AuthChallenge> authChallenge(boost::dynamic_pointer_cast<AuthChallenge>(element));
 	std::string value;
 	boost::optional<std::vector<unsigned char> > message = authChallenge->getValue();
diff --git a/Swiften/Serializer/AuthChallengeSerializer.h b/Swiften/Serializer/AuthChallengeSerializer.h
index 5f04c4c..6254fac 100644
--- a/Swiften/Serializer/AuthChallengeSerializer.h
+++ b/Swiften/Serializer/AuthChallengeSerializer.h
@@ -16,6 +16,6 @@ namespace Swift {
 		public:
 			AuthChallengeSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element> element)  const;
+			virtual SafeString serialize(boost::shared_ptr<Element> element)  const;
 	};
 }
diff --git a/Swiften/Serializer/AuthFailureSerializer.h b/Swiften/Serializer/AuthFailureSerializer.h
index ef63697..5f01f09 100644
--- a/Swiften/Serializer/AuthFailureSerializer.h
+++ b/Swiften/Serializer/AuthFailureSerializer.h
@@ -18,7 +18,7 @@ namespace Swift {
 			AuthFailureSerializer() : GenericElementSerializer<AuthFailure>() {
 			}
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const {
+			virtual SafeString serialize(boost::shared_ptr<Element>) const {
 				return XMLElement("failure", "urn:ietf:params:xml:ns:xmpp-sasl").serialize();
 			}
 	};
diff --git a/Swiften/Serializer/AuthRequestSerializer.cpp b/Swiften/Serializer/AuthRequestSerializer.cpp
index 33bdd77..e38dc85 100644
--- a/Swiften/Serializer/AuthRequestSerializer.cpp
+++ b/Swiften/Serializer/AuthRequestSerializer.cpp
@@ -8,15 +8,16 @@
 
 #include <Swiften/Elements/AuthRequest.h>
 #include <Swiften/StringCodecs/Base64.h>
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 #include <Swiften/Base/SafeString.h>
+#include <Swiften/Base/Concat.h>
 
 namespace Swift {
 
 AuthRequestSerializer::AuthRequestSerializer() {
 }
 
-std::string AuthRequestSerializer::serialize(boost::shared_ptr<Element> element)  const {
+SafeString AuthRequestSerializer::serialize(boost::shared_ptr<Element> element)  const {
 	boost::shared_ptr<AuthRequest> authRequest(boost::dynamic_pointer_cast<AuthRequest>(element));
 	SafeString value;
 	boost::optional<SafeByteArray> message = authRequest->getMessage();
@@ -28,7 +29,7 @@ std::string AuthRequestSerializer::serialize(boost::shared_ptr<Element> element)
 			value = Base64::encode(*message);
 		}
 	}
-	return "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"" + authRequest->getMechanism() + "\">" + value.toString() + "</auth>";
+	return concat(SafeString("<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"" + authRequest->getMechanism() + "\">"), value, SafeString("</auth>"));
 }
 
 }
diff --git a/Swiften/Serializer/AuthRequestSerializer.h b/Swiften/Serializer/AuthRequestSerializer.h
index d817b0c..0d812d6 100644
--- a/Swiften/Serializer/AuthRequestSerializer.h
+++ b/Swiften/Serializer/AuthRequestSerializer.h
@@ -16,6 +16,6 @@ namespace Swift {
 		public:
 			AuthRequestSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element> element)  const;
+			virtual SafeString serialize(boost::shared_ptr<Element> element)  const;
 	};
 }
diff --git a/Swiften/Serializer/AuthResponseSerializer.cpp b/Swiften/Serializer/AuthResponseSerializer.cpp
index cfdcc99..5b166b7 100644
--- a/Swiften/Serializer/AuthResponseSerializer.cpp
+++ b/Swiften/Serializer/AuthResponseSerializer.cpp
@@ -8,15 +8,16 @@
 
 #include <Swiften/Elements/AuthResponse.h>
 #include <Swiften/StringCodecs/Base64.h>
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 #include <Swiften/Base/SafeString.h>
+#include <Swiften/Base/Concat.h>
 
 namespace Swift {
 
 AuthResponseSerializer::AuthResponseSerializer() {
 }
 
-std::string AuthResponseSerializer::serialize(boost::shared_ptr<Element> element)	const {
+SafeString AuthResponseSerializer::serialize(boost::shared_ptr<Element> element)	const {
 	boost::shared_ptr<AuthResponse> authResponse(boost::dynamic_pointer_cast<AuthResponse>(element));
 	SafeString value;
 	boost::optional<SafeByteArray> message = authResponse->getValue();
@@ -28,7 +29,7 @@ std::string AuthResponseSerializer::serialize(boost::shared_ptr<Element> element
 			value = Base64::encode(*message);
 		}
 	}
-	return "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">" + value.toString() + "</response>";
+	return concat(SafeString("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"), value, SafeString("</response>"));
 }
 
 }
diff --git a/Swiften/Serializer/AuthResponseSerializer.h b/Swiften/Serializer/AuthResponseSerializer.h
index f3734c0..bb4866f 100644
--- a/Swiften/Serializer/AuthResponseSerializer.h
+++ b/Swiften/Serializer/AuthResponseSerializer.h
@@ -16,6 +16,6 @@ namespace Swift {
 		public:
 			AuthResponseSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element> element)  const;
+			virtual SafeString serialize(boost::shared_ptr<Element> element)  const;
 	};
 }
diff --git a/Swiften/Serializer/AuthSuccessSerializer.cpp b/Swiften/Serializer/AuthSuccessSerializer.cpp
index 12aab8f..b7cae47 100644
--- a/Swiften/Serializer/AuthSuccessSerializer.cpp
+++ b/Swiften/Serializer/AuthSuccessSerializer.cpp
@@ -15,7 +15,7 @@ namespace Swift {
 AuthSuccessSerializer::AuthSuccessSerializer() {
 }
 
-std::string AuthSuccessSerializer::serialize(boost::shared_ptr<Element> element)  const {
+SafeString AuthSuccessSerializer::serialize(boost::shared_ptr<Element> element)  const {
 	boost::shared_ptr<AuthSuccess> authSuccess(boost::dynamic_pointer_cast<AuthSuccess>(element));
 	std::string value;
 	boost::optional<std::vector<unsigned char> > message = authSuccess->getValue();
diff --git a/Swiften/Serializer/AuthSuccessSerializer.h b/Swiften/Serializer/AuthSuccessSerializer.h
index d681f5a..5516c0d 100644
--- a/Swiften/Serializer/AuthSuccessSerializer.h
+++ b/Swiften/Serializer/AuthSuccessSerializer.h
@@ -16,6 +16,6 @@ namespace Swift {
 		public:
 			AuthSuccessSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element> element)  const;
+			virtual SafeString serialize(boost::shared_ptr<Element> element)  const;
 	};
 }
diff --git a/Swiften/Serializer/ComponentHandshakeSerializer.cpp b/Swiften/Serializer/ComponentHandshakeSerializer.cpp
index 4eef395..c60492d 100644
--- a/Swiften/Serializer/ComponentHandshakeSerializer.cpp
+++ b/Swiften/Serializer/ComponentHandshakeSerializer.cpp
@@ -13,7 +13,7 @@ namespace Swift {
 ComponentHandshakeSerializer::ComponentHandshakeSerializer() {
 }
 
-std::string ComponentHandshakeSerializer::serialize(boost::shared_ptr<Element> element)  const {
+SafeString ComponentHandshakeSerializer::serialize(boost::shared_ptr<Element> element)  const {
 	boost::shared_ptr<ComponentHandshake> handshake(boost::dynamic_pointer_cast<ComponentHandshake>(element));
 	return "<handshake>" + handshake->getData() + "</handshake>";
 }
diff --git a/Swiften/Serializer/ComponentHandshakeSerializer.h b/Swiften/Serializer/ComponentHandshakeSerializer.h
index fe79962..2d5970e 100644
--- a/Swiften/Serializer/ComponentHandshakeSerializer.h
+++ b/Swiften/Serializer/ComponentHandshakeSerializer.h
@@ -16,6 +16,6 @@ namespace Swift {
 		public:
 			ComponentHandshakeSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element> element)  const;
+			virtual SafeString serialize(boost::shared_ptr<Element> element)  const;
 	};
 }
diff --git a/Swiften/Serializer/CompressFailureSerializer.h b/Swiften/Serializer/CompressFailureSerializer.h
index a5272df..3446670 100644
--- a/Swiften/Serializer/CompressFailureSerializer.h
+++ b/Swiften/Serializer/CompressFailureSerializer.h
@@ -18,7 +18,7 @@ namespace Swift {
 			CompressFailureSerializer() : GenericElementSerializer<CompressFailure>() {
 			}
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const {
+			virtual SafeString serialize(boost::shared_ptr<Element>) const {
 				return XMLElement("failure", "http://jabber.org/protocol/compress").serialize();
 			}
 	};
diff --git a/Swiften/Serializer/CompressRequestSerializer.cpp b/Swiften/Serializer/CompressRequestSerializer.cpp
index 0c7a4ee..8dc4e50 100644
--- a/Swiften/Serializer/CompressRequestSerializer.cpp
+++ b/Swiften/Serializer/CompressRequestSerializer.cpp
@@ -13,7 +13,7 @@ namespace Swift {
 CompressRequestSerializer::CompressRequestSerializer() {
 }
 
-std::string CompressRequestSerializer::serialize(boost::shared_ptr<Element> element)  const {
+SafeString CompressRequestSerializer::serialize(boost::shared_ptr<Element> element)  const {
 	boost::shared_ptr<CompressRequest> compressRequest(boost::dynamic_pointer_cast<CompressRequest>(element));
 	return "<compress xmlns='http://jabber.org/protocol/compress'><method>" + compressRequest->getMethod() + "</method></compress>";
 }
diff --git a/Swiften/Serializer/CompressRequestSerializer.h b/Swiften/Serializer/CompressRequestSerializer.h
index 7cbca68..cd06e1a 100644
--- a/Swiften/Serializer/CompressRequestSerializer.h
+++ b/Swiften/Serializer/CompressRequestSerializer.h
@@ -15,7 +15,7 @@ namespace Swift {
 		public:
 			CompressRequestSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element> element)  const;
+			virtual SafeString serialize(boost::shared_ptr<Element> element)  const;
 			virtual bool canSerialize(boost::shared_ptr<Element> element) const;
 	};
 }
diff --git a/Swiften/Serializer/ElementSerializer.h b/Swiften/Serializer/ElementSerializer.h
index ed9c781..7109f96 100644
--- a/Swiften/Serializer/ElementSerializer.h
+++ b/Swiften/Serializer/ElementSerializer.h
@@ -8,7 +8,7 @@
 
 #include <boost/shared_ptr.hpp>
 
-#include <string>
+#include <Swiften/Base/SafeString.h>
 #include <Swiften/Elements/Element.h>
 
 namespace Swift {
@@ -16,7 +16,7 @@ namespace Swift {
 		public:
 			virtual ~ElementSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element> element) const = 0;
+			virtual SafeString serialize(boost::shared_ptr<Element> element) const = 0;
 			virtual bool canSerialize(boost::shared_ptr<Element> element) const = 0;
 	};
 }
diff --git a/Swiften/Serializer/EnableStreamManagementSerializer.h b/Swiften/Serializer/EnableStreamManagementSerializer.h
index dc9710e..35df0c1 100644
--- a/Swiften/Serializer/EnableStreamManagementSerializer.h
+++ b/Swiften/Serializer/EnableStreamManagementSerializer.h
@@ -18,7 +18,7 @@ namespace Swift {
 			EnableStreamManagementSerializer() : GenericElementSerializer<EnableStreamManagement>() {
 			}
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const {
+			virtual SafeString serialize(boost::shared_ptr<Element>) const {
 				return XMLElement("enable", "urn:xmpp:sm:2").serialize();
 			}
 	};
diff --git a/Swiften/Serializer/GenericElementSerializer.h b/Swiften/Serializer/GenericElementSerializer.h
index 903c205..c8abdf3 100644
--- a/Swiften/Serializer/GenericElementSerializer.h
+++ b/Swiften/Serializer/GenericElementSerializer.h
@@ -14,7 +14,7 @@ namespace Swift {
 	template<typename T>
 	class GenericElementSerializer : public ElementSerializer {
 		public:
-			virtual std::string serialize(boost::shared_ptr<Element> element) const = 0;
+			virtual SafeString serialize(boost::shared_ptr<Element> element) const = 0;
 
 			virtual bool canSerialize(boost::shared_ptr<Element> element) const {
 				return boost::dynamic_pointer_cast<T>(element);
diff --git a/Swiften/Serializer/StanzaAckRequestSerializer.h b/Swiften/Serializer/StanzaAckRequestSerializer.h
index 96598e9..dbcb27a 100644
--- a/Swiften/Serializer/StanzaAckRequestSerializer.h
+++ b/Swiften/Serializer/StanzaAckRequestSerializer.h
@@ -18,7 +18,7 @@ namespace Swift {
 			StanzaAckRequestSerializer() : GenericElementSerializer<StanzaAckRequest>() {
 			}
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const {
+			virtual SafeString serialize(boost::shared_ptr<Element>) const {
 				return XMLElement("r", "urn:xmpp:sm:2").serialize();
 			}
 	};
diff --git a/Swiften/Serializer/StanzaAckSerializer.h b/Swiften/Serializer/StanzaAckSerializer.h
index b417789..91bbb8d 100644
--- a/Swiften/Serializer/StanzaAckSerializer.h
+++ b/Swiften/Serializer/StanzaAckSerializer.h
@@ -19,7 +19,7 @@ namespace Swift {
 			StanzaAckSerializer() : GenericElementSerializer<StanzaAck>() {
 			}
 
-			virtual std::string serialize(boost::shared_ptr<Element> element) const {
+			virtual SafeString serialize(boost::shared_ptr<Element> element) const {
 				StanzaAck::ref stanzaAck(boost::dynamic_pointer_cast<StanzaAck>(element));
 				assert(stanzaAck->isValid());
 				XMLElement result("a", "urn:xmpp:sm:2");
diff --git a/Swiften/Serializer/StanzaSerializer.cpp b/Swiften/Serializer/StanzaSerializer.cpp
index ab87416..c34ecae 100644
--- a/Swiften/Serializer/StanzaSerializer.cpp
+++ b/Swiften/Serializer/StanzaSerializer.cpp
@@ -22,7 +22,7 @@ namespace Swift {
 StanzaSerializer::StanzaSerializer(const std::string& tag, PayloadSerializerCollection* payloadSerializers) : tag_(tag), payloadSerializers_(payloadSerializers) {
 }
 
-std::string StanzaSerializer::serialize(boost::shared_ptr<Element> element) const {
+SafeString StanzaSerializer::serialize(boost::shared_ptr<Element> element) const {
 	boost::shared_ptr<Stanza> stanza(boost::dynamic_pointer_cast<Stanza>(element));
 
 	XMLElement stanzaElement(tag_);
diff --git a/Swiften/Serializer/StanzaSerializer.h b/Swiften/Serializer/StanzaSerializer.h
index e273651..5726562 100644
--- a/Swiften/Serializer/StanzaSerializer.h
+++ b/Swiften/Serializer/StanzaSerializer.h
@@ -18,7 +18,7 @@ namespace Swift {
 		public:
 			StanzaSerializer(const std::string& tag, PayloadSerializerCollection* payloadSerializers);
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const;
+			virtual SafeString serialize(boost::shared_ptr<Element>) const;
 			virtual void setStanzaSpecificAttributes(boost::shared_ptr<Element>, XMLElement&) const = 0;
 
 		private:
diff --git a/Swiften/Serializer/StartTLSFailureSerializer.h b/Swiften/Serializer/StartTLSFailureSerializer.h
index 1844bca..6f3f24c 100644
--- a/Swiften/Serializer/StartTLSFailureSerializer.h
+++ b/Swiften/Serializer/StartTLSFailureSerializer.h
@@ -18,7 +18,7 @@ namespace Swift {
 			StartTLSFailureSerializer() : GenericElementSerializer<StartTLSFailure>() {
 			}
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const {
+			virtual SafeString serialize(boost::shared_ptr<Element>) const {
 				return XMLElement("failure", "urn:ietf:params:xml:ns:xmpp-tls").serialize();
 			}
 	};
diff --git a/Swiften/Serializer/StartTLSRequestSerializer.h b/Swiften/Serializer/StartTLSRequestSerializer.h
index 1e1d54c..d5fa046 100644
--- a/Swiften/Serializer/StartTLSRequestSerializer.h
+++ b/Swiften/Serializer/StartTLSRequestSerializer.h
@@ -18,7 +18,7 @@ namespace Swift {
 			StartTLSRequestSerializer() : GenericElementSerializer<StartTLSRequest>() {
 			}
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const {
+			virtual SafeString serialize(boost::shared_ptr<Element>) const {
 				return XMLElement("starttls", "urn:ietf:params:xml:ns:xmpp-tls").serialize();
 			}
 	};
diff --git a/Swiften/Serializer/StreamErrorSerializer.cpp b/Swiften/Serializer/StreamErrorSerializer.cpp
index 11f8a30..e95ee37 100644
--- a/Swiften/Serializer/StreamErrorSerializer.cpp
+++ b/Swiften/Serializer/StreamErrorSerializer.cpp
@@ -15,7 +15,7 @@ namespace Swift {
 StreamErrorSerializer::StreamErrorSerializer() : GenericElementSerializer<StreamError>() {
 }
 
-std::string StreamErrorSerializer::serialize(boost::shared_ptr<Element> element)  const {
+SafeString StreamErrorSerializer::serialize(boost::shared_ptr<Element> element)  const {
 	StreamError::ref error = boost::dynamic_pointer_cast<StreamError>(element);
 	XMLElement errorElement("error", "http://etherx.jabber.org/streams");
 
diff --git a/Swiften/Serializer/StreamErrorSerializer.h b/Swiften/Serializer/StreamErrorSerializer.h
index 9d4f60c..2115324 100644
--- a/Swiften/Serializer/StreamErrorSerializer.h
+++ b/Swiften/Serializer/StreamErrorSerializer.h
@@ -14,6 +14,6 @@ namespace Swift {
 		public:
 			StreamErrorSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element> error) const;
+			virtual SafeString serialize(boost::shared_ptr<Element> error) const;
 	};
 }
diff --git a/Swiften/Serializer/StreamFeaturesSerializer.cpp b/Swiften/Serializer/StreamFeaturesSerializer.cpp
index c42d262..3c500e3 100644
--- a/Swiften/Serializer/StreamFeaturesSerializer.cpp
+++ b/Swiften/Serializer/StreamFeaturesSerializer.cpp
@@ -17,7 +17,7 @@ namespace Swift {
 StreamFeaturesSerializer::StreamFeaturesSerializer() {
 }
 
-std::string StreamFeaturesSerializer::serialize(boost::shared_ptr<Element> element)  const {
+SafeString StreamFeaturesSerializer::serialize(boost::shared_ptr<Element> element)  const {
 	boost::shared_ptr<StreamFeatures> streamFeatures(boost::dynamic_pointer_cast<StreamFeatures>(element));
 
 	XMLElement streamFeaturesElement("stream:features");
diff --git a/Swiften/Serializer/StreamFeaturesSerializer.h b/Swiften/Serializer/StreamFeaturesSerializer.h
index fafc92b..0e8a6d2 100644
--- a/Swiften/Serializer/StreamFeaturesSerializer.h
+++ b/Swiften/Serializer/StreamFeaturesSerializer.h
@@ -16,6 +16,6 @@ namespace Swift {
 		public:
 			StreamFeaturesSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element> element)  const;
+			virtual SafeString serialize(boost::shared_ptr<Element> element)  const;
 	};
 }
diff --git a/Swiften/Serializer/StreamManagementEnabledSerializer.cpp b/Swiften/Serializer/StreamManagementEnabledSerializer.cpp
index 02cf948..c19b86f 100644
--- a/Swiften/Serializer/StreamManagementEnabledSerializer.cpp
+++ b/Swiften/Serializer/StreamManagementEnabledSerializer.cpp
@@ -16,7 +16,7 @@ using namespace Swift;
 StreamManagementEnabledSerializer::StreamManagementEnabledSerializer() : GenericElementSerializer<StreamManagementEnabled>() {
 }
 
-std::string StreamManagementEnabledSerializer::serialize(boost::shared_ptr<Element> el) const {
+SafeString StreamManagementEnabledSerializer::serialize(boost::shared_ptr<Element> el) const {
 	boost::shared_ptr<StreamManagementEnabled> e(boost::dynamic_pointer_cast<StreamManagementEnabled>(el));
 	XMLElement element("enabled", "urn:xmpp:sm:2");
 	if (!e->getResumeID().empty()) {
diff --git a/Swiften/Serializer/StreamManagementEnabledSerializer.h b/Swiften/Serializer/StreamManagementEnabledSerializer.h
index 6a27457..0ea976a 100644
--- a/Swiften/Serializer/StreamManagementEnabledSerializer.h
+++ b/Swiften/Serializer/StreamManagementEnabledSerializer.h
@@ -16,6 +16,6 @@ namespace Swift {
 		public:
 			StreamManagementEnabledSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const;
+			virtual SafeString serialize(boost::shared_ptr<Element>) const;
 	};
 }
diff --git a/Swiften/Serializer/StreamManagementFailedSerializer.h b/Swiften/Serializer/StreamManagementFailedSerializer.h
index 731cf4b..034366e 100644
--- a/Swiften/Serializer/StreamManagementFailedSerializer.h
+++ b/Swiften/Serializer/StreamManagementFailedSerializer.h
@@ -18,7 +18,7 @@ namespace Swift {
 			StreamManagementFailedSerializer() : GenericElementSerializer<StreamManagementFailed>() {
 			}
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const {
+			virtual SafeString serialize(boost::shared_ptr<Element>) const {
 				return XMLElement("failed", "urn:xmpp:sm:2").serialize();
 			}
 	};
diff --git a/Swiften/Serializer/StreamResumeSerializer.cpp b/Swiften/Serializer/StreamResumeSerializer.cpp
index a7a2e3b..01877a9 100644
--- a/Swiften/Serializer/StreamResumeSerializer.cpp
+++ b/Swiften/Serializer/StreamResumeSerializer.cpp
@@ -17,7 +17,7 @@ using namespace Swift;
 StreamResumeSerializer::StreamResumeSerializer() : GenericElementSerializer<StreamResume>() {
 }
 
-std::string StreamResumeSerializer::serialize(boost::shared_ptr<Element> el) const {
+SafeString StreamResumeSerializer::serialize(boost::shared_ptr<Element> el) const {
 	boost::shared_ptr<StreamResume> e(boost::dynamic_pointer_cast<StreamResume>(el));
 	XMLElement element("resume", "urn:xmpp:sm:2");
 	element.setAttribute("previd", e->getResumeID());
diff --git a/Swiften/Serializer/StreamResumeSerializer.h b/Swiften/Serializer/StreamResumeSerializer.h
index 6ea7365..965485f 100644
--- a/Swiften/Serializer/StreamResumeSerializer.h
+++ b/Swiften/Serializer/StreamResumeSerializer.h
@@ -16,6 +16,6 @@ namespace Swift {
 		public:
 			StreamResumeSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const;
+			virtual SafeString serialize(boost::shared_ptr<Element>) const;
 	};
 }
diff --git a/Swiften/Serializer/StreamResumedSerializer.cpp b/Swiften/Serializer/StreamResumedSerializer.cpp
index d3beafb..06006b8 100644
--- a/Swiften/Serializer/StreamResumedSerializer.cpp
+++ b/Swiften/Serializer/StreamResumedSerializer.cpp
@@ -17,7 +17,7 @@ using namespace Swift;
 StreamResumedSerializer::StreamResumedSerializer() : GenericElementSerializer<StreamResumed>() {
 }
 
-std::string StreamResumedSerializer::serialize(boost::shared_ptr<Element> el) const {
+SafeString StreamResumedSerializer::serialize(boost::shared_ptr<Element> el) const {
 	boost::shared_ptr<StreamResumed> e(boost::dynamic_pointer_cast<StreamResumed>(el));
 	XMLElement element("resumed", "urn:xmpp:sm:2");
 	element.setAttribute("previd", e->getResumeID());
diff --git a/Swiften/Serializer/StreamResumedSerializer.h b/Swiften/Serializer/StreamResumedSerializer.h
index 38d846f..24d5f86 100644
--- a/Swiften/Serializer/StreamResumedSerializer.h
+++ b/Swiften/Serializer/StreamResumedSerializer.h
@@ -16,6 +16,6 @@ namespace Swift {
 		public:
 			StreamResumedSerializer();
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const;
+			virtual SafeString serialize(boost::shared_ptr<Element>) const;
 	};
 }
diff --git a/Swiften/Serializer/TLSProceedSerializer.h b/Swiften/Serializer/TLSProceedSerializer.h
index d6ca99f..95ee211 100644
--- a/Swiften/Serializer/TLSProceedSerializer.h
+++ b/Swiften/Serializer/TLSProceedSerializer.h
@@ -18,7 +18,7 @@ namespace Swift {
 			TLSProceedSerializer() : GenericElementSerializer<TLSProceed>() {
 			}
 
-			virtual std::string serialize(boost::shared_ptr<Element>) const {
+			virtual SafeString serialize(boost::shared_ptr<Element>) const {
 				return XMLElement("proceed", "urn:ietf:params:xml:ns:xmpp-tls").serialize();
 			}
 	};
diff --git a/Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp b/Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp
index a81620d..2dcadcd 100644
--- a/Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp
@@ -10,6 +10,7 @@
 #include <Swiften/Serializer/AuthChallengeSerializer.h>
 #include <Swiften/Elements/AuthChallenge.h>
 #include <Swiften/Base/ByteArray.h>
+#include <QA/Checker/IO.h>
 
 using namespace Swift;
 
@@ -26,7 +27,7 @@ class AuthChallengeSerializerTest : public CppUnit::TestFixture {
 			boost::shared_ptr<AuthChallenge> authChallenge(new AuthChallenge());
 			authChallenge->setValue(createByteArray("foo"));
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
 					"Zm9v"
 				"</challenge>"), testling.serialize(authChallenge));
@@ -36,7 +37,7 @@ class AuthChallengeSerializerTest : public CppUnit::TestFixture {
 			AuthChallengeSerializer testling;
 			boost::shared_ptr<AuthChallenge> authChallenge(new AuthChallenge());
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
 				"</challenge>"), testling.serialize(authChallenge));
 		}
@@ -46,7 +47,7 @@ class AuthChallengeSerializerTest : public CppUnit::TestFixture {
 			boost::shared_ptr<AuthChallenge> authChallenge(new AuthChallenge());
 			authChallenge->setValue(std::vector<unsigned char>());
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
 					"="
 				"</challenge>"), testling.serialize(authChallenge));
diff --git a/Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp b/Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp
index d5c0a09..7d7b1be 100644
--- a/Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp
@@ -10,6 +10,7 @@
 #include <Swiften/Serializer/AuthRequestSerializer.h>
 #include <Swiften/Elements/AuthRequest.h>
 #include <Swiften/Base/ByteArray.h>
+#include <QA/Checker/IO.h>
 
 using namespace Swift;
 
@@ -26,7 +27,7 @@ class AuthRequestSerializerTest : public CppUnit::TestFixture {
 			boost::shared_ptr<AuthRequest> authRequest(new AuthRequest("PLAIN"));
 			authRequest->setMessage(createSafeByteArray("foo"));
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"PLAIN\">"
 					"Zm9v"
 				"</auth>"), testling.serialize(authRequest));
@@ -36,7 +37,7 @@ class AuthRequestSerializerTest : public CppUnit::TestFixture {
 			AuthRequestSerializer testling;
 			boost::shared_ptr<AuthRequest> authRequest(new AuthRequest("PLAIN"));
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"PLAIN\">"
 				"</auth>"), testling.serialize(authRequest));
 		}
@@ -46,7 +47,7 @@ class AuthRequestSerializerTest : public CppUnit::TestFixture {
 			boost::shared_ptr<AuthRequest> authRequest(new AuthRequest("PLAIN"));
 			authRequest->setMessage(SafeByteArray());
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"PLAIN\">"
 					"="
 				"</auth>"), testling.serialize(authRequest));
diff --git a/Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp b/Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp
index 8887b27..3be1185 100644
--- a/Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp
@@ -10,6 +10,7 @@
 #include <Swiften/Serializer/AuthResponseSerializer.h>
 #include <Swiften/Elements/AuthResponse.h>
 #include <Swiften/Base/ByteArray.h>
+#include <QA/Checker/IO.h>
 
 using namespace Swift;
 
@@ -26,7 +27,7 @@ class AuthResponseSerializerTest : public CppUnit::TestFixture {
 			boost::shared_ptr<AuthResponse> authResponse(new AuthResponse());
 			authResponse->setValue(createSafeByteArray("foo"));
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
 					"Zm9v"
 				"</response>"), testling.serialize(authResponse));
@@ -36,7 +37,7 @@ class AuthResponseSerializerTest : public CppUnit::TestFixture {
 			AuthResponseSerializer testling;
 			boost::shared_ptr<AuthResponse> authResponse(new AuthResponse());
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
 				"</response>"), testling.serialize(authResponse));
 		}
@@ -46,7 +47,7 @@ class AuthResponseSerializerTest : public CppUnit::TestFixture {
 			boost::shared_ptr<AuthResponse> authResponse(new AuthResponse());
 			authResponse->setValue(SafeByteArray());
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
 					"="
 				"</response>"), testling.serialize(authResponse));
diff --git a/Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp b/Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp
index a9f6de2..b8646c0 100644
--- a/Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp
@@ -10,6 +10,7 @@
 #include <Swiften/Serializer/AuthSuccessSerializer.h>
 #include <Swiften/Elements/AuthSuccess.h>
 #include <Swiften/Base/ByteArray.h>
+#include <QA/Checker/IO.h>
 
 using namespace Swift;
 
@@ -26,7 +27,7 @@ class AuthSuccessSerializerTest : public CppUnit::TestFixture {
 			boost::shared_ptr<AuthSuccess> authSuccess(new AuthSuccess());
 			authSuccess->setValue(createByteArray("foo"));
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
 					"Zm9v"
 				"</success>"), testling.serialize(authSuccess));
@@ -36,7 +37,7 @@ class AuthSuccessSerializerTest : public CppUnit::TestFixture {
 			AuthSuccessSerializer testling;
 			boost::shared_ptr<AuthSuccess> authSuccess(new AuthSuccess());
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
 				"</success>"), testling.serialize(authSuccess));
 		}
@@ -46,7 +47,7 @@ class AuthSuccessSerializerTest : public CppUnit::TestFixture {
 			boost::shared_ptr<AuthSuccess> authSuccess(new AuthSuccess());
 			authSuccess->setValue(std::vector<unsigned char>());
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
 					"="
 				"</success>"), testling.serialize(authSuccess));
diff --git a/Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp b/Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp
index 5b9412b..b30a774 100644
--- a/Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp
@@ -9,6 +9,8 @@
 
 #include <Swiften/Serializer/StreamFeaturesSerializer.h>
 #include <Swiften/Elements/StreamFeatures.h>
+#include <QA/Checker/IO.h>
+
 
 using namespace Swift;
 
@@ -34,7 +36,7 @@ class StreamFeaturesSerializerTest : public CppUnit::TestFixture
 			streamFeatures->setHasStreamManagement();
 			streamFeatures->setHasRosterVersioning();
 
-			CPPUNIT_ASSERT_EQUAL(std::string(
+			CPPUNIT_ASSERT_EQUAL(SafeString(
 				"<stream:features>"
 					"<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>"
 					"<compression xmlns=\"http://jabber.org/features/compress\">"
diff --git a/Swiften/Serializer/XMPPSerializer.cpp b/Swiften/Serializer/XMPPSerializer.cpp
index 19a30ce..054175d 100644
--- a/Swiften/Serializer/XMPPSerializer.cpp
+++ b/Swiften/Serializer/XMPPSerializer.cpp
@@ -83,10 +83,8 @@ std::string XMPPSerializer::serializeHeader(const ProtocolHeader& header) const
 	return result;
 }
 
-std::string XMPPSerializer::serializeElement(boost::shared_ptr<Element> element) const {
-	std::vector< boost::shared_ptr<ElementSerializer> >::const_iterator i = std::find_if(
-			serializers_.begin(), serializers_.end(), 
-			boost::bind(&ElementSerializer::canSerialize, _1, element));
+SafeString XMPPSerializer::serializeElement(boost::shared_ptr<Element> element) const {
+	std::vector< boost::shared_ptr<ElementSerializer> >::const_iterator i = std::find_if(serializers_.begin(), serializers_.end(), boost::bind(&ElementSerializer::canSerialize, _1, element));
 	if (i != serializers_.end()) {
 		return (*i)->serialize(element);
 	}
diff --git a/Swiften/Serializer/XMPPSerializer.h b/Swiften/Serializer/XMPPSerializer.h
index 003d33b..58274a8 100644
--- a/Swiften/Serializer/XMPPSerializer.h
+++ b/Swiften/Serializer/XMPPSerializer.h
@@ -24,7 +24,7 @@ namespace Swift {
 			XMPPSerializer(PayloadSerializerCollection*, StreamType type);
 
 			std::string serializeHeader(const ProtocolHeader&) const;
-			std::string serializeElement(boost::shared_ptr<Element> stanza) const;
+			SafeString serializeElement(boost::shared_ptr<Element> stanza) const;
 			std::string serializeFooter() const;
 		
 		private:
diff --git a/Swiften/Session/BasicSessionStream.cpp b/Swiften/Session/BasicSessionStream.cpp
index 579631f..a1ec907 100644
--- a/Swiften/Session/BasicSessionStream.cpp
+++ b/Swiften/Session/BasicSessionStream.cpp
@@ -192,12 +192,12 @@ void BasicSessionStream::handleConnectionFinished(const boost::optional<Connecti
 	}
 }
 
-void BasicSessionStream::handleDataRead(const ByteArray& data) {
-	onDataRead(byteArrayToString(data));
+void BasicSessionStream::handleDataRead(const SafeByteArray& data) {
+	onDataRead(byteArrayToString(ByteArray(data.begin(), data.end())));
 }
 
-void BasicSessionStream::handleDataWritten(const ByteArray& data) {
-	onDataWritten(byteArrayToString(data));
+void BasicSessionStream::handleDataWritten(const SafeByteArray& data) {
+	onDataWritten(byteArrayToString(ByteArray(data.begin(), data.end())));
 }
 
 };
diff --git a/Swiften/Session/BasicSessionStream.h b/Swiften/Session/BasicSessionStream.h
index d2be2d3..2a1ed8a 100644
--- a/Swiften/Session/BasicSessionStream.h
+++ b/Swiften/Session/BasicSessionStream.h
@@ -8,6 +8,7 @@
 
 #include <boost/shared_ptr.hpp>
 
+#include <Swiften/Base/SafeByteArray.h>
 #include <Swiften/Network/Connection.h>
 #include <Swiften/Session/SessionStream.h>
 #include <Swiften/Elements/StreamType.h>
@@ -64,8 +65,8 @@ namespace Swift {
 			void handleTLSError();
 			void handleStreamStartReceived(const ProtocolHeader&);
 			void handleElementReceived(boost::shared_ptr<Element>);
-			void handleDataRead(const ByteArray& data);
-			void handleDataWritten(const ByteArray& data);
+			void handleDataRead(const SafeByteArray& data);
+			void handleDataWritten(const SafeByteArray& data);
 
 		private:
 			bool available;
diff --git a/Swiften/Session/Session.h b/Swiften/Session/Session.h
index 04ae8d5..9e954c7 100644
--- a/Swiften/Session/Session.h
+++ b/Swiften/Session/Session.h
@@ -15,7 +15,7 @@
 #include <Swiften/Elements/Element.h>
 #include <Swiften/Network/Connection.h>
 #include <Swiften/StreamStack/ConnectionLayer.h>
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 
 namespace Swift {
 	class ProtocolHeader;
@@ -63,8 +63,8 @@ namespace Swift {
 
 			boost::signal<void (boost::shared_ptr<Element>)> onElementReceived;
 			boost::signal<void (const boost::optional<SessionError>&)> onSessionFinished;
-			boost::signal<void (const ByteArray&)> onDataWritten;
-			boost::signal<void (const ByteArray&)> onDataRead;
+			boost::signal<void (const SafeByteArray&)> onDataWritten;
+			boost::signal<void (const SafeByteArray&)> onDataRead;
 
 		protected:
 			void setRemoteJID(const JID& j) {
diff --git a/Swiften/Session/SessionTracer.cpp b/Swiften/Session/SessionTracer.cpp
index 060109b..e0a39bf 100644
--- a/Swiften/Session/SessionTracer.cpp
+++ b/Swiften/Session/SessionTracer.cpp
@@ -16,13 +16,13 @@ SessionTracer::SessionTracer(boost::shared_ptr<Session> session) : session(sessi
 	session->onDataWritten.connect(boost::bind(&SessionTracer::printData, this, '>', _1));
 }
 
-void SessionTracer::printData(char direction, const ByteArray& data) {
+void SessionTracer::printData(char direction, const SafeByteArray& data) {
 	std::cerr << direction << direction << " " << session->getLocalJID() << " ";
 	for (unsigned int i = 0; i < 72 - session->getLocalJID().toString().size() - session->getRemoteJID().toString().size(); ++i) {
 		std::cerr << direction;
 	}
 	std::cerr << " " << session->getRemoteJID()<< " " << direction << direction << std::endl;
-	std::cerr << byteArrayToString(data) << std::endl;
+	std::cerr << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl;
 }
 
 }
diff --git a/Swiften/Session/SessionTracer.h b/Swiften/Session/SessionTracer.h
index 4e45957..72c93b4 100644
--- a/Swiften/Session/SessionTracer.h
+++ b/Swiften/Session/SessionTracer.h
@@ -9,7 +9,7 @@
 #include <string>
 
 #include <Swiften/Session/Session.h>
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 
 namespace Swift {
 	class SessionTracer {
@@ -17,7 +17,7 @@ namespace Swift {
 			SessionTracer(boost::shared_ptr<Session> session);
 
 		private:
-			void printData(char direction, const ByteArray& data);
+			void printData(char direction, const SafeByteArray& data);
 
 			boost::shared_ptr<Session> session;
 	};
diff --git a/Swiften/StreamStack/CompressionLayer.h b/Swiften/StreamStack/CompressionLayer.h
index b10ee52..783cfca 100644
--- a/Swiften/StreamStack/CompressionLayer.h
+++ b/Swiften/StreamStack/CompressionLayer.h
@@ -9,7 +9,7 @@
 #include <boost/noncopyable.hpp>
 #include <Swiften/Base/boost_bsignals.h>
 
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 #include <Swiften/StreamStack/StreamLayer.h>
 #include <Swiften/Compress/ZLibException.h>
 #include <Swiften/Compress/ZLibCompressor.h>
@@ -23,7 +23,7 @@ namespace Swift {
 		public:
 			CompressionLayer() {}
 
-			virtual void writeData(const ByteArray& data) {
+			virtual void writeData(const SafeByteArray& data) {
 				try {
 					writeDataToChildLayer(compressor_.process(data));
 				}
@@ -32,7 +32,7 @@ namespace Swift {
 				}
 			}
 
-			virtual void handleDataRead(const ByteArray& data) {
+			virtual void handleDataRead(const SafeByteArray& data) {
 				try {
 					writeDataToParentLayer(decompressor_.process(data));
 				}
diff --git a/Swiften/StreamStack/ConnectionLayer.h b/Swiften/StreamStack/ConnectionLayer.h
index fc33e48..8ccd33c 100644
--- a/Swiften/StreamStack/ConnectionLayer.h
+++ b/Swiften/StreamStack/ConnectionLayer.h
@@ -17,7 +17,7 @@ namespace Swift {
 			ConnectionLayer(boost::shared_ptr<Connection> connection);
 			~ConnectionLayer();
 
-			void writeData(const ByteArray& data) {
+			void writeData(const SafeByteArray& data) {
 				connection->write(data);
 			}
 
diff --git a/Swiften/StreamStack/HighLayer.cpp b/Swiften/StreamStack/HighLayer.cpp
index 7203b7f..dc17c2a 100644
--- a/Swiften/StreamStack/HighLayer.cpp
+++ b/Swiften/StreamStack/HighLayer.cpp
@@ -18,7 +18,7 @@ HighLayer::HighLayer() : childLayer(NULL) {
 HighLayer::~HighLayer() {
 }
 
-void HighLayer::writeDataToChildLayer(const ByteArray& data) {
+void HighLayer::writeDataToChildLayer(const SafeByteArray& data) {
 	assert(childLayer);
 	childLayer->writeData(data);
 }
diff --git a/Swiften/StreamStack/HighLayer.h b/Swiften/StreamStack/HighLayer.h
index b96458f..06b1d25 100644
--- a/Swiften/StreamStack/HighLayer.h
+++ b/Swiften/StreamStack/HighLayer.h
@@ -6,7 +6,7 @@
 
 #pragma once
 
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 
 namespace Swift {
 	class LowLayer;
@@ -18,7 +18,7 @@ namespace Swift {
 			HighLayer();
 			virtual ~HighLayer();
 
-			virtual void handleDataRead(const ByteArray& data) = 0;
+			virtual void handleDataRead(const SafeByteArray& data) = 0;
 	
 		protected:
 			LowLayer* getChildLayer() {
@@ -29,7 +29,7 @@ namespace Swift {
 				this->childLayer = childLayer;
 			}
 
-			void writeDataToChildLayer(const ByteArray& data);
+			void writeDataToChildLayer(const SafeByteArray& data);
 
 		private:
 			LowLayer* childLayer;
diff --git a/Swiften/StreamStack/LowLayer.cpp b/Swiften/StreamStack/LowLayer.cpp
index ed93cd2..ff4ca17 100644
--- a/Swiften/StreamStack/LowLayer.cpp
+++ b/Swiften/StreamStack/LowLayer.cpp
@@ -18,7 +18,7 @@ LowLayer::LowLayer() : parentLayer(NULL) {
 LowLayer::~LowLayer() {
 }
 
-void LowLayer::writeDataToParentLayer(const ByteArray& data) {
+void LowLayer::writeDataToParentLayer(const SafeByteArray& data) {
 	assert(parentLayer);
 	parentLayer->handleDataRead(data);
 }
diff --git a/Swiften/StreamStack/LowLayer.h b/Swiften/StreamStack/LowLayer.h
index 87eb3de..00960ea 100644
--- a/Swiften/StreamStack/LowLayer.h
+++ b/Swiften/StreamStack/LowLayer.h
@@ -6,7 +6,7 @@
 
 #pragma once
 
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 
 namespace Swift {
 	class HighLayer;
@@ -18,7 +18,7 @@ namespace Swift {
 			LowLayer();
 			virtual ~LowLayer();
 
-			virtual void writeData(const ByteArray& data) = 0;
+			virtual void writeData(const SafeByteArray& data) = 0;
 	
 		protected:
 			HighLayer* getParentLayer() {
@@ -29,7 +29,7 @@ namespace Swift {
 				this->parentLayer = parentLayer;
 			}
 
-			void writeDataToParentLayer(const ByteArray& data);
+			void writeDataToParentLayer(const SafeByteArray& data);
 
 		private:
 			HighLayer* parentLayer;
diff --git a/Swiften/StreamStack/TLSLayer.cpp b/Swiften/StreamStack/TLSLayer.cpp
index 707b700..6f2223d 100644
--- a/Swiften/StreamStack/TLSLayer.cpp
+++ b/Swiften/StreamStack/TLSLayer.cpp
@@ -29,11 +29,11 @@ void TLSLayer::connect() {
 	context->connect();
 }
 
-void TLSLayer::writeData(const ByteArray& data) {
+void TLSLayer::writeData(const SafeByteArray& data) {
 	context->handleDataFromApplication(data);
 }
 
-void TLSLayer::handleDataRead(const ByteArray& data) {
+void TLSLayer::handleDataRead(const SafeByteArray& data) {
 	context->handleDataFromNetwork(data);
 }
 
diff --git a/Swiften/StreamStack/TLSLayer.h b/Swiften/StreamStack/TLSLayer.h
index bec63ee..a8693d5 100644
--- a/Swiften/StreamStack/TLSLayer.h
+++ b/Swiften/StreamStack/TLSLayer.h
@@ -6,7 +6,7 @@
 
 #include <Swiften/Base/boost_bsignals.h>
 
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 #include <Swiften/StreamStack/StreamLayer.h>
 #include <Swiften/TLS/Certificate.h>
 #include <Swiften/TLS/CertificateVerificationError.h>
@@ -27,8 +27,8 @@ namespace Swift {
 			Certificate::ref getPeerCertificate() const;
 			boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
 
-			void writeData(const ByteArray& data);
-			void handleDataRead(const ByteArray& data);
+			void writeData(const SafeByteArray& data);
+			void handleDataRead(const SafeByteArray& data);
 
 			TLSContext* getContext() const {
 				return context;
diff --git a/Swiften/StreamStack/UnitTest/StreamStackTest.cpp b/Swiften/StreamStack/UnitTest/StreamStackTest.cpp
index 19dd37c..cf6b035 100644
--- a/Swiften/StreamStack/UnitTest/StreamStackTest.cpp
+++ b/Swiften/StreamStack/UnitTest/StreamStackTest.cpp
@@ -54,7 +54,7 @@ class StreamStackTest : public CppUnit::TestFixture {
 			xmppStream_->writeData("foo");
 
 			CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size());
-			CPPUNIT_ASSERT_EQUAL(createByteArray("foo"), physicalStream_->data_[0]);
+			CPPUNIT_ASSERT_EQUAL(createSafeByteArray("foo"), physicalStream_->data_[0]);
 		}
 
 		void testWriteData_OneIntermediateStream() {
@@ -65,7 +65,7 @@ class StreamStackTest : public CppUnit::TestFixture {
 			xmppStream_->writeData("foo");
 
 			CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size());
-			CPPUNIT_ASSERT_EQUAL(createByteArray("Xfoo"), physicalStream_->data_[0]);
+			CPPUNIT_ASSERT_EQUAL(createSafeByteArray("Xfoo"), physicalStream_->data_[0]);
 		}
 
 		void testWriteData_TwoIntermediateStreamStack() {
@@ -78,14 +78,14 @@ class StreamStackTest : public CppUnit::TestFixture {
 			xmppStream_->writeData("foo");
 
 			CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size());
-			CPPUNIT_ASSERT_EQUAL(createByteArray("XYfoo"), physicalStream_->data_[0]);
+			CPPUNIT_ASSERT_EQUAL(createSafeByteArray("XYfoo"), physicalStream_->data_[0]);
 		}
 
 		void testReadData_NoIntermediateStreamStack() {
 			StreamStack testling(xmppStream_, physicalStream_);
 			xmppStream_->onElement.connect(boost::bind(&StreamStackTest::handleElement, this, _1));
 			
-			physicalStream_->onDataRead(createByteArray("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
+			physicalStream_->onDataRead(createSafeByteArray("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
 
 			CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
 		}
@@ -96,7 +96,7 @@ class StreamStackTest : public CppUnit::TestFixture {
 			boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("<"));
 			testling.addLayer(xStream.get());
 
-			physicalStream_->onDataRead(createByteArray("stream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
+			physicalStream_->onDataRead(createSafeByteArray("stream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
 
 			CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
 		}
@@ -109,7 +109,7 @@ class StreamStackTest : public CppUnit::TestFixture {
 			testling.addLayer(xStream.get());
 			testling.addLayer(yStream.get());
 
-			physicalStream_->onDataRead(createByteArray("tream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
+			physicalStream_->onDataRead(createSafeByteArray("tream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
 
 			CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
 		}
@@ -129,7 +129,7 @@ class StreamStackTest : public CppUnit::TestFixture {
 			++elementsReceived_;
 		}
 
-		void handleWriteData(ByteArray) {
+		void handleWriteData(const SafeByteArray&) {
 			++dataWriteReceived_;
 		}
 
@@ -139,12 +139,12 @@ class StreamStackTest : public CppUnit::TestFixture {
 				MyStreamLayer(const std::string& prepend) : prepend_(prepend) {
 				}
 
-				virtual void writeData(const ByteArray& data) {
-					writeDataToChildLayer(concat(createByteArray(prepend_), data));
+				virtual void writeData(const SafeByteArray& data) {
+					writeDataToChildLayer(concat(createSafeByteArray(prepend_), data));
 				}
 
-				virtual void handleDataRead(const ByteArray& data) {
-					writeDataToParentLayer(concat(createByteArray(prepend_), data));
+				virtual void handleDataRead(const SafeByteArray& data) {
+					writeDataToParentLayer(concat(createSafeByteArray(prepend_), data));
 				}
 
 			private:
@@ -156,15 +156,15 @@ class StreamStackTest : public CppUnit::TestFixture {
 				TestLowLayer() {
 				}
 
-				virtual void writeData(const ByteArray& data) {
+				virtual void writeData(const SafeByteArray& data) {
 					data_.push_back(data);
 				}
 
-				void onDataRead(const ByteArray& data) {
+				void onDataRead(const SafeByteArray& data) {
 					writeDataToParentLayer(data);
 				}
 
-				std::vector<ByteArray> data_;
+				std::vector<SafeByteArray> data_;
 		};
 
 
diff --git a/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp b/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
index 602699d..bb0ce61 100644
--- a/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
+++ b/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
@@ -46,7 +46,7 @@ class XMPPLayerTest : public CppUnit::TestFixture {
 		void testParseData_Error() {
 			testling_->onError.connect(boost::bind(&XMPPLayerTest::handleError, this));
 
-			testling_->handleDataRead(createByteArray("<iq>"));
+			testling_->handleDataRead(createSafeByteArray("<iq>"));
 			
 			CPPUNIT_ASSERT_EQUAL(1, errorReceived_);
 		}
@@ -55,10 +55,10 @@ class XMPPLayerTest : public CppUnit::TestFixture {
 			testling_->onElement.connect(boost::bind(&XMPPLayerTest::handleElement, this, _1));
 			testling_->onError.connect(boost::bind(&XMPPLayerTest::handleError, this));
 
-			testling_->handleDataRead(createByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" >"));
+			testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" >"));
 			testling_->resetParser();
-			testling_->handleDataRead(createByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" >"));
-			testling_->handleDataRead(createByteArray("<presence/>"));
+			testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" >"));
+			testling_->handleDataRead(createSafeByteArray("<presence/>"));
 
 			CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
 			CPPUNIT_ASSERT_EQUAL(0, errorReceived_);
@@ -66,8 +66,8 @@ class XMPPLayerTest : public CppUnit::TestFixture {
 
 		void testResetParser_FromSlot() {
 			testling_->onElement.connect(boost::bind(&XMPPLayerTest::handleElementAndReset, this, _1));
-			testling_->handleDataRead(createByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" ><presence/>"));
-			testling_->handleDataRead(createByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" ><presence/>"));
+			testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" ><presence/>"));
+			testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" ><presence/>"));
 
 			CPPUNIT_ASSERT_EQUAL(2, elementsReceived_);
 			CPPUNIT_ASSERT_EQUAL(0, errorReceived_);
@@ -120,8 +120,8 @@ class XMPPLayerTest : public CppUnit::TestFixture {
 
 		class DummyLowLayer : public LowLayer {
 			public:
-				virtual void writeData(const ByteArray& data) {
-					writtenData += byteArrayToString(data);
+				virtual void writeData(const SafeByteArray& data) {
+					writtenData += byteArrayToString(ByteArray(data.begin(), data.end()));
 				}
 				
 				std::string writtenData;
diff --git a/Swiften/StreamStack/WhitespacePingLayer.cpp b/Swiften/StreamStack/WhitespacePingLayer.cpp
index 6a95899..b14f3a2 100644
--- a/Swiften/StreamStack/WhitespacePingLayer.cpp
+++ b/Swiften/StreamStack/WhitespacePingLayer.cpp
@@ -20,17 +20,17 @@ WhitespacePingLayer::WhitespacePingLayer(TimerFactory* timerFactory) : isActive(
 	timer->onTick.connect(boost::bind(&WhitespacePingLayer::handleTimerTick, this));
 }
 
-void WhitespacePingLayer::writeData(const ByteArray& data) {
+void WhitespacePingLayer::writeData(const SafeByteArray& data) {
 	writeDataToChildLayer(data);
 }
 
-void WhitespacePingLayer::handleDataRead(const ByteArray& data) {
+void WhitespacePingLayer::handleDataRead(const SafeByteArray& data) {
 	writeDataToParentLayer(data);
 }
 
 void WhitespacePingLayer::handleTimerTick() {
 	timer->stop();
-	writeDataToChildLayer(createByteArray(" "));
+	writeDataToChildLayer(createSafeByteArray(" "));
 	timer->start();
 }
 
diff --git a/Swiften/StreamStack/WhitespacePingLayer.h b/Swiften/StreamStack/WhitespacePingLayer.h
index 7c42c29..1435842 100644
--- a/Swiften/StreamStack/WhitespacePingLayer.h
+++ b/Swiften/StreamStack/WhitespacePingLayer.h
@@ -21,8 +21,8 @@ namespace Swift {
 
 			void setActive();
 			void setInactive();
-			void writeData(const ByteArray& data);
-			void handleDataRead(const ByteArray& data);
+			void writeData(const SafeByteArray& data);
+			void handleDataRead(const SafeByteArray& data);
 
 			bool getIsActive() const {
 				return isActive;
diff --git a/Swiften/StreamStack/XMPPLayer.cpp b/Swiften/StreamStack/XMPPLayer.cpp
index 37cda65..1de3a2a 100644
--- a/Swiften/StreamStack/XMPPLayer.cpp
+++ b/Swiften/StreamStack/XMPPLayer.cpp
@@ -29,30 +29,33 @@ XMPPLayer::~XMPPLayer() {
 }
 
 void XMPPLayer::writeHeader(const ProtocolHeader& header) {
-	writeDataInternal(createByteArray(xmppSerializer_->serializeHeader(header)));
+	writeDataInternal(createSafeByteArray(xmppSerializer_->serializeHeader(header)));
 }
 
 void XMPPLayer::writeFooter() {
-	writeDataInternal(createByteArray(xmppSerializer_->serializeFooter()));
+	writeDataInternal(createSafeByteArray(xmppSerializer_->serializeFooter()));
 }
 
 void XMPPLayer::writeElement(boost::shared_ptr<Element> element) {
-	writeDataInternal(createByteArray(xmppSerializer_->serializeElement(element)));
+	writeDataInternal(createSafeByteArray(xmppSerializer_->serializeElement(element)));
 }
 
 void XMPPLayer::writeData(const std::string& data) {
-	writeDataInternal(createByteArray(data));
+	writeDataInternal(createSafeByteArray(data));
 }
 
-void XMPPLayer::writeDataInternal(const ByteArray& data) {
+void XMPPLayer::writeDataInternal(const SafeByteArray& data) {
 	onWriteData(data);
 	writeDataToChildLayer(data);
 }
 
-void XMPPLayer::handleDataRead(const ByteArray& data) {
+void XMPPLayer::handleDataRead(const SafeByteArray& data) {
 	onDataRead(data);
 	inParser_ = true;
-	if (!xmppParser_->parse(byteArrayToString(data))) {
+	// FIXME: Converting to unsafe string. Should be ok, since we don't take passwords
+	// from the stream in clients. If servers start using this, and require safe storage,
+	// we need to fix this.
+	if (!xmppParser_->parse(byteArrayToString(ByteArray(data.begin(), data.end())))) {
 		inParser_ = false;
 		onError();
 		return;
diff --git a/Swiften/StreamStack/XMPPLayer.h b/Swiften/StreamStack/XMPPLayer.h
index 72d0e7e..54bdd42 100644
--- a/Swiften/StreamStack/XMPPLayer.h
+++ b/Swiften/StreamStack/XMPPLayer.h
@@ -11,7 +11,7 @@
 #include <boost/noncopyable.hpp>
 
 #include <Swiften/StreamStack/HighLayer.h>
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 #include <Swiften/Elements/Element.h>
 #include <Swiften/Elements/StreamType.h>
 #include <Swiften/Parser/XMPPParserClient.h>
@@ -39,14 +39,14 @@ namespace Swift {
 			void resetParser();
 
 		protected:
-			void handleDataRead(const ByteArray& data);
-			void writeDataInternal(const ByteArray& data);
+			void handleDataRead(const SafeByteArray& data);
+			void writeDataInternal(const SafeByteArray& data);
 
 		public:
 			boost::signal<void (const ProtocolHeader&)> onStreamStart;
 			boost::signal<void (boost::shared_ptr<Element>)> onElement;
-			boost::signal<void (const ByteArray&)> onWriteData;
-			boost::signal<void (const ByteArray&)> onDataRead;
+			boost::signal<void (const SafeByteArray&)> onWriteData;
+			boost::signal<void (const SafeByteArray&)> onDataRead;
 			boost::signal<void ()> onError;
 
 		private:
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
index 97094bf..8d3970e 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
@@ -138,14 +138,14 @@ void OpenSSLContext::doConnect() {
 void OpenSSLContext::sendPendingDataToNetwork() {
 	int size = BIO_pending(writeBIO_);
 	if (size > 0) {
-		ByteArray data;
+		SafeByteArray data;
 		data.resize(size);
 		BIO_read(writeBIO_, vecptr(data), size);
 		onDataForNetwork(data);
 	}
 }
 
-void OpenSSLContext::handleDataFromNetwork(const ByteArray& data) {
+void OpenSSLContext::handleDataFromNetwork(const SafeByteArray& data) {
 	BIO_write(readBIO_, vecptr(data), data.size());
 	switch (state_) {
 		case Connecting:
@@ -159,7 +159,7 @@ void OpenSSLContext::handleDataFromNetwork(const ByteArray& data) {
 	}
 }
 
-void OpenSSLContext::handleDataFromApplication(const ByteArray& data) {
+void OpenSSLContext::handleDataFromApplication(const SafeByteArray& data) {
 	if (SSL_write(handle_, vecptr(data), data.size()) >= 0) {
 		sendPendingDataToNetwork();
 	}
@@ -170,7 +170,7 @@ void OpenSSLContext::handleDataFromApplication(const ByteArray& data) {
 }
 
 void OpenSSLContext::sendPendingDataToApplication() {
-	ByteArray data;
+	SafeByteArray data;
 	data.resize(SSL_READ_BUFFERSIZE);
 	int ret = SSL_read(handle_, vecptr(data), data.size());
 	while (ret > 0) {
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.h b/Swiften/TLS/OpenSSL/OpenSSLContext.h
index 30ac917..04693a3 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContext.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLContext.h
@@ -24,8 +24,8 @@ namespace Swift {
 			void connect();
 			bool setClientCertificate(const PKCS12Certificate& cert);
 
-			void handleDataFromNetwork(const ByteArray&);
-			void handleDataFromApplication(const ByteArray&);
+			void handleDataFromNetwork(const SafeByteArray&);
+			void handleDataFromApplication(const SafeByteArray&);
 
 			Certificate::ref getPeerCertificate() const;
 			boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
diff --git a/Swiften/TLS/TLSContext.h b/Swiften/TLS/TLSContext.h
index 68926c2..1538863 100644
--- a/Swiften/TLS/TLSContext.h
+++ b/Swiften/TLS/TLSContext.h
@@ -9,7 +9,7 @@
 #include <Swiften/Base/boost_bsignals.h>
 #include <boost/shared_ptr.hpp>
 
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
 #include <Swiften/TLS/Certificate.h>
 #include <Swiften/TLS/CertificateVerificationError.h>
 
@@ -24,8 +24,8 @@ namespace Swift {
 
 			virtual bool setClientCertificate(const PKCS12Certificate& cert) = 0;
 
-			virtual void handleDataFromNetwork(const ByteArray&) = 0;
-			virtual void handleDataFromApplication(const ByteArray&) = 0;
+			virtual void handleDataFromNetwork(const SafeByteArray&) = 0;
+			virtual void handleDataFromApplication(const SafeByteArray&) = 0;
 
 			virtual Certificate::ref getPeerCertificate() const = 0;
 			virtual CertificateVerificationError::ref getPeerCertificateVerificationError() const = 0;
@@ -33,8 +33,8 @@ namespace Swift {
 			virtual ByteArray getFinishMessage() const = 0;
 
 		public:
-			boost::signal<void (const ByteArray&)> onDataForNetwork;
-			boost::signal<void (const ByteArray&)> onDataForApplication;
+			boost::signal<void (const SafeByteArray&)> onDataForNetwork;
+			boost::signal<void (const SafeByteArray&)> onDataForApplication;
 			boost::signal<void ()> onError;
 			boost::signal<void ()> onConnected;
 	};
-- 
cgit v0.10.2-6-g49f6