From 2c6f1075474f6b8086cc6abf7978aee9421761c8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Remko=20Tron=C3=A7on?= <git@el-tramo.be>
Date: Sat, 8 Oct 2011 09:40:01 +0200
Subject: Protect JID cache access with mutex.

The overhead appears to be neglectible.

Using TSS had a similar overhead, with the disadvantages that it uses
more storage (one cache per thread vs one cache), has less cache reuse,
and that Windows/MSVC doesn't support automatic TSS cleanup, so it
requires manual cleanup work (which is non-trivial).

Note that the mutex approach may yield more overhead in multi-threaded
applications (in case of contention). Currently, the mutex also locks
during the whole nameprep sequence, which is not strictly necessary.

diff --git a/Swiften/JID/JID.cpp b/Swiften/JID/JID.cpp
index 66d6ff6..9b47ef7 100644
--- a/Swiften/JID/JID.cpp
+++ b/Swiften/JID/JID.cpp
@@ -12,6 +12,7 @@
 
 #include <string>
 #ifdef SWIFTEN_CACHE_JID_PREP
+#include <boost/thread/mutex.hpp>
 #include <boost/unordered_map.hpp>
 #endif
 #include <boost/assign/list_of.hpp>
@@ -29,6 +30,7 @@ using namespace Swift;
 #ifdef SWIFTEN_CACHE_JID_PREP
 typedef boost::unordered_map<std::string, std::string> PrepCache;
 
+static boost::mutex namePrepCacheMutex;
 static PrepCache nodePrepCache;
 static PrepCache domainPrepCache;
 static PrepCache resourcePrepCache;
@@ -154,12 +156,18 @@ void JID::initializeFromString(const std::string& jid) {
 
 
 void JID::nameprepAndSetComponents(const std::string& node, const std::string& domain, const std::string& resource) {
+	if (domain.empty()) {
+		valid_ = false;
+		return;
+	}
 	try {
 #ifndef SWIFTEN_CACHE_JID_PREP
 		node_ = StringPrep::getPrepared(node, StringPrep::NamePrep);
 		domain_ = StringPrep::getPrepared(domain, StringPrep::XMPPNodePrep);
 		resource_ = StringPrep::getPrepared(resource, StringPrep::XMPPResourcePrep);
 #else
+		boost::mutex::scoped_lock lock(namePrepCacheMutex);
+
 		std::pair<PrepCache::iterator, bool> r;
 
 		r = nodePrepCache.insert(std::make_pair(node, std::string()));
-- 
cgit v0.10.2-6-g49f6