Changeset - 6d2f8c192761
[Not reviewed]
! ! !
Vladimir Matena - 9 years ago 2016-09-12 18:20:58
vlada.matena@gmail.com
Switch from boost shared pointers to stl shared pointers (#162)

* Swiften 4 support
* using standard shared pointers when compiling with Swiften 4
84 files changed:
Changeset was too big and was cut off... Show full diff anyway
0 comments (0 inline, 0 general)
.travis.yml
Show inline comments
 
@@ -2,19 +2,19 @@ language: cpp
 
python:
 
  - "2.7_with_system_site_packages"
 
virtualenv:
 
  system_site_packages: true
 
sudo: required
 
dist: trusty
 
before_script:
 
          - curl -k https://swift.im/keys/packages.key | sudo apt-key add -
 
          - echo "deb http://swift.im/packages/ubuntu/trusty development main" | sudo tee -a /etc/apt/sources.list
 
          - echo "deb http://packages.spectrum.im/spectrum2/ trusty main" | sudo tee -a /etc/apt/sources.list
 
          - echo " deb http://packages.prosody.im/debian trusty main" | sudo tee -a /etc/apt/sources.list
 
          - sudo apt-get update -qq
 
          - sudo apt-get install -y --force-yes prosody ngircd python-sleekxmpp libswiften-dev libprotobuf-dev protobuf-compiler pidgin-dev liblog4cxx10-dev libpopt-dev libboost-dev libboost-signals-dev libboost-system-dev libboost-thread-dev libboost-locale-dev libboost-filesystem-dev libboost-program-options-dev libboost-regex-dev libboost-date-time-dev libcppunit-dev libcommuni-dev
 
          - sudo apt-get install -y --force-yes prosody ngircd python-sleekxmpp libswiften-dev libprotobuf-dev protobuf-compiler pidgin-dev liblog4cxx10-dev libpopt-dev libboost-dev libboost-signals-dev libboost-system-dev libboost-thread-dev libboost-locale-dev libboost-filesystem-dev libboost-program-options-dev libboost-regex-dev libboost-date-time-dev libcppunit-dev libcommuni-dev libminiupnpc-dev libnatpmp-dev
 
          - sudo killall lua5.1
 
install: "pip install --user sleekxmpp"
 
script:
 
          - cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_TESTS=ON . && make && make extended_test
 
notifications:
 
  slack: spectrum2:CIlYHtxGMAaxs3qVHfwBzCuy
CMakeLists.txt
Show inline comments
 
@@ -66,25 +66,26 @@ if(NOT SWIFTEN_FOUND)
 
	endif()
 
	if (LIBIDN_LIBRARY)
 
		set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} ${LIBIDN_LIBRARY})
 
	endif()
 
	if (LIBXML_LIBRARY)
 
		set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} ${LIBXML_LIBRARY})
 
	endif()
 
	set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} "Dnsapi")
 
	set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} "Crypt32")
 
	set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} "Secur32")
 
	set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} "Iphlpapi")
 
	set(SWIFTEN_LIBRARY ${SWIFTEN_LIBRARY} "Winscard")
 
	message(STATUS "Using swiften: ${SWIFTEN_INCLUDE_DIR} ${SWIFTEN_LIBRARY}")
 
	message(STATUS "XXXUsing swiften: ${SWIFTEN_INCLUDE_DIR} ${SWIFTEN_LIBRARY}
 
	Version: ${SWIFTEN_VERSION}")
 
endif()
 

	
 
# FIND BOOST
 
if (WIN32)
 
	set(Boost_USE_STATIC_LIBS      ON)
 
	set(Boost_USE_MULTITHREADED      ON)
 
	set(Boost_USE_STATIC_RUNTIME    OFF)
 
	find_package(Boost COMPONENTS program_options date_time system filesystem regex thread signals locale REQUIRED)
 
else(WIN32)
 
	LIST_CONTAINS(contains -lboost_program_options ${SWIFTEN_LIBRARY})
 
	if(contains)
 
		message(STATUS "Using non-multithreaded boost")
 
@@ -475,13 +476,12 @@ else(DOXYGEN_FOUND)
 
	endif()
 
endif(DOXYGEN_FOUND)
 

	
 
message("----------------------")
 

	
 
if(NOT SQLITE3_FOUND AND NOT MYSQL_FOUND AND NOT PQXX_FOUND)
 
	if(ENABLE_SQLITE3 OR ENABLE_MYSQL OR ENABLE_PQXX)
 
		message("Could not find any database - Please install at least one of sqlite3-devel, mysql-devel or pqxx-devel if you want to use transport mode.")
 
	else(ENABLE_SQLITE3 OR ENABLE_MYSQL OR ENABLE_PQXX)
 
		message("Please enable at least one of SQLITE3, MYSQL, PQXX databases to use transport mode.")
 
	endif()
 
endif()
 

	
backends/frotz/main.cpp
Show inline comments
 
@@ -2,24 +2,25 @@
 
 * Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
 
 *
 
 * This example is free, and not covered by LGPL license. There is no
 
 * restriction applied to their modification, redistribution, using and so on.
 
 * You can study them, modify them, use them in your own program - either
 
 * completely or partially. By using it you may give me some credits in your
 
 * program, but you don't have to.
 
 */
 

	
 
#include "transport/Config.h"
 
#include "transport/NetworkPlugin.h"
 
#include "Swiften/Swiften.h"
 
#include "Swiften/SwiftenCompat.h"
 
#include <boost/filesystem.hpp>
 
#include "unistd.h"
 
#include "signal.h"
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
Swift::SimpleEventLoop *loop_;
 

	
 
using namespace boost::program_options;
 
using namespace Transport;
 

	
 
class FrotzNetworkPlugin;
 
FrotzNetworkPlugin * np = NULL;
 
@@ -139,41 +140,41 @@ static void start_dfrotz(dfrotz &p, const std::string &game) {
 

	
 
	}
 
	else {
 
		close(CHILD_READ);
 
		close(CHILD_WRITE);
 
	}
 
}
 

	
 
class FrotzNetworkPlugin : public NetworkPlugin {
 
	public:
 
		Swift::BoostNetworkFactories *m_factories;
 
		Swift::BoostIOServiceThread m_boostIOServiceThread;
 
		boost::shared_ptr<Swift::Connection> m_conn;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> m_conn;
 

	
 
		FrotzNetworkPlugin(Config *config, Swift::SimpleEventLoop *loop, const std::string &host, int port) : NetworkPlugin() {
 
			this->config = config;
 
			m_factories = new Swift::BoostNetworkFactories(loop);
 
			m_conn = m_factories->getConnectionFactory()->createConnection();
 
			m_conn->onDataRead.connect(boost::bind(&FrotzNetworkPlugin::_handleDataRead, this, _1));
 
			m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(host), port));
 
// 			m_conn->onConnectFinished.connect(boost::bind(&FrotzNetworkPlugin::_handleConnected, this, _1));
 
// 			m_conn->onDisconnected.connect(boost::bind(&FrotzNetworkPlugin::handleDisconnected, this));
 
		}
 

	
 
		void sendData(const std::string &string) {
 
			m_conn->write(Swift::createSafeByteArray(string));
 
		}
 

	
 
		void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
 
		void _handleDataRead(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::SafeByteArray> data) {
 
			std::string d(data->begin(), data->end());
 
			handleDataRead(d);
 
		}
 

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
			np->handleConnected(user);
 
			std::vector<std::string> groups;
 
			groups.push_back("ZCode");
 
			np->handleBuddyChanged(user, "zcode", "ZCode", groups, pbnetwork::STATUS_ONLINE);
 
// 			sleep(1);
 
// 			np->handleMessage(np->m_user, "zork", first_msg);
 
		}
backends/libpurple/main.cpp
Show inline comments
 
@@ -7,24 +7,25 @@
 
#define _LIBC_INTERFACE_H_ 1
 

	
 
#include "purple.h"
 
#include <algorithm>
 
#include <iostream>
 
#include <fstream> 
 

	
 
#include "transport/NetworkPlugin.h"
 
#include "transport/Logging.h"
 
#include "transport/Config.h"
 
#include "transport/StorageBackend.h"
 
#include "geventloop.h"
 
#include "Swiften/SwiftenCompat.h"
 

	
 
// #include "valgrind/memcheck.h"
 
#if !defined(__FreeBSD__) && !defined(__APPLE__)
 
#include "malloc.h"
 
#endif
 
#include "errno.h"
 
#include <boost/make_shared.hpp>
 
#include <boost/locale.hpp>
 
#include <boost/locale/conversion.hpp>
 
#include <boost/thread/mutex.hpp>
 

	
 
#ifdef WITH_LIBEVENT
 
@@ -73,25 +74,25 @@ static std::vector<std::string> &split(const std::string &s, char delim, std::ve
 
}
 

	
 

	
 
static std::vector<std::string> split(const std::string &s, char delim) {
 
    std::vector<std::string> elems;
 
    return split(s, delim, elems);
 
}
 

	
 
static void transportDataReceived(gpointer data, gint source, PurpleInputCondition cond);
 

	
 
class SpectrumNetworkPlugin;
 

	
 
boost::shared_ptr<Config> config;
 
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Config> config;
 
SpectrumNetworkPlugin *np;
 
StorageBackend *storagebackend;
 

	
 
static std::string host;
 
static int port = 10000;
 

	
 
struct FTData {
 
	unsigned long id;
 
	unsigned long timer;
 
	bool paused;
 
};
 

	
 
@@ -2251,25 +2252,25 @@ int main(int argc, char **argv) {
 
			std::cout << "SIGCHLD handler can't be set\n";
 
			return -1;
 
		}
 
#endif
 

	
 
	std::string error;
 
	Config *cfg = Config::createFromArgs(argc, argv, error, host, port);
 
	if (cfg == NULL) {
 
		std::cerr << error;
 
		return 1;
 
	}
 

	
 
	config = boost::shared_ptr<Config>(cfg);
 
	config = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Config>(cfg);
 
 
 
	Logging::initBackendLogging(config.get());
 
	if (CONFIG_STRING(config, "service.protocol") == "prpl-hangouts") {
 
		storagebackend = StorageBackend::createBackend(config.get(), error);
 
		if (storagebackend == NULL) {
 
			LOG4CXX_ERROR(logger, "Error creating StorageBackend! " << error);
 
			LOG4CXX_ERROR(logger, "Hangouts backend needs storage backend configured to work! " << error);
 
			return NetworkPlugin::StorageBackendNeeded;
 
		}
 
		else if (!storagebackend->connect()) {
 
			LOG4CXX_ERROR(logger, "Can't connect to database!")
 
				return -1;
backends/smstools3/main.cpp
Show inline comments
 
@@ -7,24 +7,25 @@
 
 * completely or partially. By using it you may give me some credits in your
 
 * program, but you don't have to.
 
 */
 

	
 
#include "transport/Config.h"
 
#include "transport/Logging.h"
 
#include "transport/NetworkPlugin.h"
 
#include "transport/SQLite3Backend.h"
 
#include "transport/MySQLBackend.h"
 
#include "transport/PQXXBackend.h"
 
#include "transport/StorageBackend.h"
 
#include "Swiften/Swiften.h"
 
#include "Swiften/SwiftenCompat.h"
 
#include <boost/filesystem.hpp>
 
#include "unistd.h"
 
#include "signal.h"
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
#include <fstream>
 
#include <streambuf>
 

	
 
Swift::SimpleEventLoop *loop_;
 

	
 
#include <boost/filesystem.hpp>
 
#include <boost/algorithm/string.hpp>
 
@@ -36,25 +37,25 @@ using namespace Transport;
 

	
 
DEFINE_LOGGER(logger, "SMSNetworkPlugin");
 

	
 
#define INTERNAL_USER "/sms@backend@internal@user"
 

	
 
class SMSNetworkPlugin;
 
SMSNetworkPlugin * np = NULL;
 

	
 
class SMSNetworkPlugin : public NetworkPlugin {
 
	public:
 
		Swift::BoostNetworkFactories *m_factories;
 
		Swift::BoostIOServiceThread m_boostIOServiceThread;
 
		boost::shared_ptr<Swift::Connection> m_conn;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> m_conn;
 
		Swift::Timer::ref m_timer;
 
		int m_internalUser;
 
		StorageBackend *storageBackend;
 

	
 
		SMSNetworkPlugin(Config *config, Swift::SimpleEventLoop *loop, StorageBackend *storagebackend, const std::string &host, int port) : NetworkPlugin() {
 
			this->config = config;
 
			this->storageBackend = storagebackend;
 
			m_factories = new Swift::BoostNetworkFactories(loop);
 
			m_conn = m_factories->getConnectionFactory()->createConnection();
 
			m_conn->onDataRead.connect(boost::bind(&SMSNetworkPlugin::_handleDataRead, this, _1));
 
			m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(host), port));
 
// 			m_conn->onConnectFinished.connect(boost::bind(&FrotzNetworkPlugin::_handleConnected, this, _1));
 
@@ -160,25 +161,25 @@ class SMSNetworkPlugin : public NetworkPlugin {
 
				uuid += bucket[rand() % bucket.size()];
 
			}
 
			std::ofstream myfile;
 
			myfile.open (std::string("/var/spool/sms/outgoing/spectrum." + uuid).c_str());
 
			myfile << data;
 
			myfile.close();
 
		}
 

	
 
		void sendData(const std::string &string) {
 
			m_conn->write(Swift::createSafeByteArray(string));
 
		}
 

	
 
		void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
 
		void _handleDataRead(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::SafeByteArray> data) {
 
			std::string d(data->begin(), data->end());
 
			handleDataRead(d);
 
		}
 

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
			UserInfo info;
 
			if (!storageBackend->getUser(user, info)) {
 
				handleDisconnected(user, 0, "Not registered user.");
 
				return;
 
			}
 
			std::list<BuddyInfo> roster;
 
			storageBackend->getBuddies(info.id, roster);
backends/swiften/main.cpp
Show inline comments
 
// Transport includes
 
#include "transport/Config.h"
 
#include "transport/NetworkPlugin.h"
 
#include "transport/Logging.h"
 

	
 
#include "boost/date_time/posix_time/posix_time.hpp"
 

	
 
// Swiften
 
#include "Swiften/Swiften.h"
 
#include "Swiften/SwiftenCompat.h"
 
#include <Swiften/Version.h>
 
#define HAVE_SWIFTEN_3  (SWIFTEN_VERSION >= 0x030000)
 

	
 
#ifndef WIN32
 
// for signal handler
 
#include "unistd.h"
 
#include "signal.h"
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
#endif
 

	
 
#ifndef __FreeBSD__
 
@@ -42,49 +43,49 @@ class SwiftenPlugin;
 
NetworkPlugin *np = NULL;
 
Swift::XMPPSerializer *serializer;
 

	
 
class ForwardIQHandler : public Swift::IQHandler {
 
	public:
 
		std::map <std::string, std::string> m_id2resource;
 

	
 
		ForwardIQHandler(NetworkPlugin *np, const std::string &user) {
 
			m_np = np;
 
			m_user = user;
 
		}
 

	
 
		bool handleIQ(boost::shared_ptr<Swift::IQ> iq) {
 
		bool handleIQ(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::IQ> iq) {
 
			if (iq->getPayload<Swift::RosterPayload>() != NULL) {
 
				return false;
 
			}
 
			if (iq->getType() == Swift::IQ::Get) {
 
				m_id2resource[iq->getID()] = iq->getFrom().getResource();
 
			}
 

	
 
			iq->setTo(m_user);
 
			std::string xml = safeByteArrayToString(serializer->serializeElement(iq));
 
			m_np->sendRawXML(xml);
 
			return true;
 
		}
 

	
 
	private:
 
		NetworkPlugin *m_np;
 
		std::string m_user;
 
		
 
};
 

	
 
class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
 
	public:
 
		Swift::BoostNetworkFactories *m_factories;
 
		Swift::BoostIOServiceThread m_boostIOServiceThread;
 
		boost::shared_ptr<Swift::Connection> m_conn;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> m_conn;
 
		bool m_firstPing;
 
		
 
		Swift::FullPayloadSerializerCollection collection;
 
		Swift::XMPPParser *m_xmppParser;
 
		Swift::FullPayloadParserFactoryCollection m_collection2;
 

	
 
		SwiftenPlugin(Config *config, Swift::SimpleEventLoop *loop, const std::string &host, int port) : NetworkPlugin() {
 
			this->config = config;
 
			m_firstPing = true;
 
			m_factories = new Swift::BoostNetworkFactories(loop);
 
			m_conn = m_factories->getConnectionFactory()->createConnection();
 
			m_conn->onDataRead.connect(boost::bind(&SwiftenPlugin::_handleDataRead, this, _1));
 
@@ -97,68 +98,68 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
 
			m_xmppParser = new Swift::XMPPParser(this, &m_collection2, m_factories->getXMLParserFactory());
 
			m_xmppParser->parse("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='localhost' version='1.0'>");
 

	
 
			LOG4CXX_INFO(logger, "Starting the plugin.");
 
		}
 

	
 
		// NetworkPlugin uses this method to send the data to networkplugin server
 
		void sendData(const std::string &string) {
 
			m_conn->write(Swift::createSafeByteArray(string));
 
		}
 

	
 
		// This method has to call handleDataRead with all received data from network plugin server
 
		void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
 
		void _handleDataRead(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::SafeByteArray> data) {
 
			if (m_firstPing) {
 
				m_firstPing = false;
 
				NetworkPlugin::PluginConfig cfg;
 
				cfg.setRawXML(true);
 
				cfg.setNeedRegistration(false);
 
				sendConfig(cfg);
 
			}
 
			std::string d(data->begin(), data->end());
 
			handleDataRead(d);
 
		}
 

	
 
		void handleStreamStart(const Swift::ProtocolHeader&) {}
 
#if HAVE_SWIFTEN_3
 
		void handleElement(boost::shared_ptr<Swift::ToplevelElement> element) {
 
		void handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::ToplevelElement> element) {
 
#else
 
		void handleElement(boost::shared_ptr<Swift::Element> element) {
 
		void handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Element> element) {
 
#endif
 
			boost::shared_ptr<Swift::Stanza> stanza = boost::dynamic_pointer_cast<Swift::Stanza>(element);
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Stanza> stanza = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Swift::Stanza>(element);
 
			if (!stanza) {
 
				return;
 
			}
 

	
 
			std::string user = stanza->getFrom().toBare();
 

	
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> client = m_users[user];
 
			if (!client)
 
				return;
 

	
 
			stanza->setFrom(client->getJID());
 

	
 
			boost::shared_ptr<Swift::Message> message = boost::dynamic_pointer_cast<Swift::Message>(stanza);
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> message = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Swift::Message>(stanza);
 
			if (message) {
 
				client->sendMessage(message);
 
				return;
 
			}
 

	
 
			boost::shared_ptr<Swift::Presence> presence = boost::dynamic_pointer_cast<Swift::Presence>(stanza);
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Presence> presence = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Swift::Presence>(stanza);
 
			if (presence) {
 
				client->sendPresence(presence);
 
				return;
 
			}
 

	
 
			boost::shared_ptr<Swift::IQ> iq = boost::dynamic_pointer_cast<Swift::IQ>(stanza);
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::IQ> iq = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Swift::IQ>(stanza);
 
			if (iq) {
 
				if (m_handlers[user]->m_id2resource.find(stanza->getID()) != m_handlers[user]->m_id2resource.end()) {
 
					std::string resource = m_handlers[user]->m_id2resource[stanza->getID()];
 
					if (resource.empty()) {
 
						iq->setTo(Swift::JID(iq->getTo().getNode(), iq->getTo().getDomain()));					
 
					} else {
 
						iq->setTo(Swift::JID(iq->getTo().getNode(), iq->getTo().getDomain(), resource));					
 
					}
 
					
 
					m_handlers[user]->m_id2resource.erase(stanza->getID());
 
				}
 
				client->getIQRouter()->sendIQ(iq);
 
@@ -202,25 +203,25 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
 
					case Swift::ClientError::CertificateRejectedError: message = ("Certificate has been rejected"); break;
 
					case Swift::ClientError::CertificateUntrustedError: message = ("Certificate is not trusted"); break;
 
					case Swift::ClientError::InvalidCertificatePurposeError: message = ("Certificate cannot be used for encrypting your connection"); break;
 
					case Swift::ClientError::CertificatePathLengthExceededError: message = ("Certificate path length constraint exceeded"); break;
 
					case Swift::ClientError::InvalidCertificateSignatureError: message = ("Invalid certificate signature"); break;
 
					case Swift::ClientError::InvalidCAError: message = ("Invalid Certificate Authority"); break;
 
					case Swift::ClientError::InvalidServerIdentityError: message = ("Certificate does not match the host identity"); break;
 
				}
 
			}
 
			LOG4CXX_INFO(logger, user << ": Disconnected " << message);
 
			handleDisconnected(user, reconnect ? 0 : 3, message);
 

	
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				client->onConnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftConnected, this, user));
 
				client->onDisconnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftDisconnected, this, user, _1));
 
				client->onMessageReceived.disconnect(boost::bind(&SwiftenPlugin::handleSwiftMessageReceived, this, user, _1));
 
				m_users.erase(user);
 
				m_handlers.erase(user);
 
			}
 

	
 
#ifndef WIN32
 
#ifndef __FreeBSD__
 
#ifndef __MACH__
 
			// force returning of memory chunks allocated by libxml2 to kernel
 
@@ -241,39 +242,39 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
 

	
 
		void handleSwiftRosterReceived(const std::string &user) {
 
			Swift::PresenceOracle *oracle = m_users[user]->getPresenceOracle();
 
			BOOST_FOREACH(const Swift::XMPPRosterItem &item, m_users[user]->getRoster()->getItems()) {
 
				Swift::Presence::ref lastPresence = oracle->getLastPresence(item.getJID());
 
				pbnetwork::StatusType status = lastPresence ? ((pbnetwork::StatusType) lastPresence->getShow()) : pbnetwork::STATUS_NONE;
 
				handleBuddyChanged(user, item.getJID().toBare().toString(),
 
								   item.getName(), item.getGroups(), status);
 
			}
 
		}
 

	
 
		void handleSwiftPresenceChanged(const std::string &user, Swift::Presence::ref presence) {
 
// 			boost::shared_ptr<Swift::Client> client = m_users[user];
 
// 			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> client = m_users[user];
 
// 			if (client->getMUCRegistry()->isMUC(presence->getFrom().toBare())) {
 
// 				return;
 
// 			}
 
// 
 
// 			if (presence->getPayload<Swift::MUCUserPayload>() != NULL || presence->getPayload<Swift::MUCPayload>() != NULL) {
 
// 				return;
 
// 			}
 
// 
 
// 			LOG4CXX_INFO(logger, user << ": " << presence->getFrom().toBare().toString() << " presence changed");
 
// 
 
// 			std::string message = presence->getStatus();
 
// 			std::string photo = "";
 
// 
 
// 			boost::shared_ptr<Swift::VCardUpdate> update = presence->getPayload<Swift::VCardUpdate>();
 
// 			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::VCardUpdate> update = presence->getPayload<Swift::VCardUpdate>();
 
// 			if (update) {
 
// 				photo = update->getPhotoHash();
 
// 			}
 
// 
 
// 			boost::optional<Swift::XMPPRosterItem> item = m_users[user]->getRoster()->getItem(presence->getFrom());
 
// 			if (item) {
 
// 				handleBuddyChanged(user, presence->getFrom().toBare().toString(), item->getName(), item->getGroups(), (pbnetwork::StatusType) presence->getShow(), message, photo);
 
// 			}
 
// 			else {
 
// 				std::vector<std::string> groups;
 
// 				handleBuddyChanged(user, presence->getFrom().toBare().toString(), presence->getFrom().toBare(), groups, (pbnetwork::StatusType) presence->getShow(), message, photo);
 
// 			}
 
@@ -296,129 +297,129 @@ class SwiftenPlugin : public NetworkPlugin, Swift::XMPPParserClient {
 
		}
 

	
 
		void handleSwiftenDataWritten(const Swift::SafeByteArray &data) {
 
			LOG4CXX_INFO(logger_xml, "XML OUT " << safeByteArrayToString(data));
 
		}
 

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
			LOG4CXX_INFO(logger, user << ": connecting as " << legacyName);
 
			Swift::JID jid(legacyName);
 
			if (legacyName.find("/") == std::string::npos) {
 
				jid = Swift::JID(legacyName + "/Spectrum");
 
			}
 
			boost::shared_ptr<Swift::Client> client = boost::make_shared<Swift::Client>(jid, password, m_factories);
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> client = SWIFTEN_SHRPTR_NAMESPACE::make_shared<Swift::Client>(jid, password, m_factories);
 
			m_users[user] = client;
 
			client->setAlwaysTrustCertificates();
 
			client->onConnected.connect(boost::bind(&SwiftenPlugin::handleSwiftConnected, this, user));
 
			client->onDisconnected.connect(boost::bind(&SwiftenPlugin::handleSwiftDisconnected, this, user, _1));
 
			client->onMessageReceived.connect(boost::bind(&SwiftenPlugin::handleSwiftMessageReceived, this, user, _1));
 
			client->getRoster()->onInitialRosterPopulated.connect(boost::bind(&SwiftenPlugin::handleSwiftRosterReceived, this, user));
 
			client->getPresenceOracle()->onPresenceChange.connect(boost::bind(&SwiftenPlugin::handleSwiftPresenceChanged, this, user, _1));
 
			client->onDataRead.connect(boost::bind(&SwiftenPlugin::handleSwiftenDataRead, this, _1));
 
			client->onDataWritten.connect(boost::bind(&SwiftenPlugin::handleSwiftenDataWritten, this, _1));
 
			client->getSubscriptionManager()->onPresenceSubscriptionRequest.connect(boost::bind(&SwiftenPlugin::handleSubscriptionRequest, this, user, _1, _2, _3));
 
			client->getSubscriptionManager()->onPresenceSubscriptionRevoked.connect(boost::bind(&SwiftenPlugin::handleSubscriptionRevoked, this, user, _1, _2));
 
			Swift::ClientOptions opt;
 
			opt.allowPLAINWithoutTLS = true;
 
			client->connect(opt);
 

	
 
			boost::shared_ptr<ForwardIQHandler> handler = boost::make_shared<ForwardIQHandler>(this, user);
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ForwardIQHandler> handler = SWIFTEN_SHRPTR_NAMESPACE::make_shared<ForwardIQHandler>(this, user);
 
			client->getIQRouter()->addHandler(handler);
 
			m_handlers[user] = handler;
 
		}
 

	
 
		void handleSubscriptionRequest(const std::string &user, const Swift::JID& jid, const std::string& message, Swift::Presence::ref presence) {
 
			handleSwiftPresenceChanged(user, presence);
 
		}
 

	
 
		void handleSubscriptionRevoked(const std::string &user, const Swift::JID& jid, const std::string& message) {
 
			Swift::Presence::ref presence = Swift::Presence::create();
 
			presence->setTo(user);
 
			presence->setFrom(jid);
 
			presence->setType(Swift::Presence::Unsubscribe);
 
			handleSwiftPresenceChanged(user, presence);
 
		}
 

	
 
		void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				client->onConnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftConnected, this, user));
 
// 				client->onDisconnected.disconnect(boost::bind(&SwiftenPlugin::handleSwiftDisconnected, this, user, _1));
 
				client->onMessageReceived.disconnect(boost::bind(&SwiftenPlugin::handleSwiftMessageReceived, this, user, _1));
 
				client->getRoster()->onInitialRosterPopulated.disconnect(boost::bind(&SwiftenPlugin::handleSwiftRosterReceived, this, user));
 
				client->getPresenceOracle()->onPresenceChange.disconnect(boost::bind(&SwiftenPlugin::handleSwiftPresenceChanged, this, user, _1));
 
				client->disconnect();
 
			}
 
		}
 

	
 
		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &msg, const std::string &xhtml = "", const std::string &id = "") {
 
		}
 

	
 
		void handleVCardRequest(const std::string &user, const std::string &legacyName, unsigned int id) {
 
		}
 

	
 
		void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups) {
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				LOG4CXX_INFO(logger, user << ": Added/Updated buddy " << buddyName << ".");
 
				if (!client->getRoster()->containsJID(buddyName) || client->getRoster()->getSubscriptionStateForJID(buddyName) != Swift::RosterItemPayload::Both) {
 
					Swift::RosterItemPayload item;
 
					item.setName(alias);
 
					item.setJID(buddyName);
 
					item.setGroups(groups);
 
					boost::shared_ptr<Swift::RosterPayload> roster(new Swift::RosterPayload());
 
					SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::RosterPayload> roster(new Swift::RosterPayload());
 
					roster->addItem(item);
 
					Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(roster, client->getIQRouter());
 
// 					request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
 
					request->send();
 
					client->getSubscriptionManager()->requestSubscription(buddyName);
 
				}
 
				else {
 
					Swift::JID contact(buddyName);
 
					Swift::RosterItemPayload item(contact, alias, client->getRoster()->getSubscriptionStateForJID(contact));
 
					item.setGroups(groups);
 
					boost::shared_ptr<Swift::RosterPayload> roster(new Swift::RosterPayload());
 
					SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::RosterPayload> roster(new Swift::RosterPayload());
 
					roster->addItem(item);
 
					Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(roster, client->getIQRouter());
 
// 					request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
 
					request->send();
 
				}
 

	
 
			}
 
		}
 

	
 
		void handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups) {
 
			boost::shared_ptr<Swift::Client> client = m_users[user];
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> client = m_users[user];
 
			if (client) {
 
				Swift::RosterItemPayload item(buddyName, "", Swift::RosterItemPayload::Remove);
 
				boost::shared_ptr<Swift::RosterPayload> roster(new Swift::RosterPayload());
 
				SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::RosterPayload> roster(new Swift::RosterPayload());
 
				roster->addItem(item);
 
				Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(roster, client->getIQRouter());
 
// 				request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
 
				request->send();
 
			}
 
		}
 

	
 
		void handleJoinRoomRequest(const std::string &user, const std::string &room, const std::string &nickname, const std::string &password) {
 

	
 
		}
 

	
 
		void handleLeaveRoomRequest(const std::string &user, const std::string &room) {
 

	
 
		}
 

	
 
	private:
 
		Config *config;
 
		std::map<std::string, boost::shared_ptr<Swift::Client> > m_users;
 
		std::map<std::string, boost::shared_ptr<ForwardIQHandler> > m_handlers;
 
		std::map<std::string, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Client> > m_users;
 
		std::map<std::string, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ForwardIQHandler> > m_handlers;
 
};
 

	
 
#ifndef WIN32
 
static void spectrum_sigchld_handler(int sig)
 
{
 
	int status;
 
	pid_t pid;
 

	
 
	do {
 
		pid = waitpid(-1, &status, WNOHANG);
 
	} while (pid != 0 && pid != (pid_t)-1);
 

	
backends/template/plugin.cpp
Show inline comments
 
@@ -22,25 +22,25 @@ Plugin::Plugin(Config *config, Swift::SimpleEventLoop *loop, const std::string &
 
	m_conn->onDataRead.connect(boost::bind(&Plugin::_handleDataRead, this, _1));
 
	m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(host), port));
 

	
 
	LOG4CXX_INFO(logger, "Starting the plugin.");
 
}
 

	
 
// NetworkPlugin uses this method to send the data to networkplugin server
 
void Plugin::sendData(const std::string &string) {
 
	m_conn->write(Swift::createSafeByteArray(string));
 
}
 

	
 
// This method has to call handleDataRead with all received data from network plugin server
 
void Plugin::_handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
 
void Plugin::_handleDataRead(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::SafeByteArray> data) {
 
	std::string d(data->begin(), data->end());
 
	handleDataRead(d);
 
}
 

	
 
void Plugin::handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
	handleConnected(user);
 
	LOG4CXX_INFO(logger, user << ": Added buddy - Echo.");
 
	handleBuddyChanged(user, "echo", "Echo", std::vector<std::string>(), pbnetwork::STATUS_ONLINE);
 
}
 

	
 
void Plugin::handleLogoutRequest(const std::string &user, const std::string &legacyName) {
 
}
backends/template/plugin.h
Show inline comments
 
#pragma once
 

	
 
#include "Swiften/Swiften.h"
 
#include "Swiften/SwiftenCompat.h"
 

	
 
#include "transport/Config.h"
 
#include "transport/NetworkPlugin.h"
 

	
 
class Plugin : public Transport::NetworkPlugin {
 
	public:
 
		Plugin(Transport::Config *config, Swift::SimpleEventLoop *loop, const std::string &host, int port);
 

	
 
		// NetworkPlugin uses this method to send the data to networkplugin server
 
		void sendData(const std::string &string);
 

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password);
 

	
 
		void handleLogoutRequest(const std::string &user, const std::string &legacyName);
 

	
 
		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml = "", const std::string &id = "");
 

	
 
		void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups);
 

	
 
		void handleBuddyRemovedRequest(const std::string &user, const std::string &buddyName, const std::vector<std::string> &groups);
 

	
 
	private:
 
		// This method has to call handleDataRead with all received data from network plugin server
 
		void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data);
 
		void _handleDataRead(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::SafeByteArray> data);
 

	
 
	private:
 
		Swift::BoostNetworkFactories *m_factories;
 
		Swift::BoostIOServiceThread m_boostIOServiceThread;
 
		boost::shared_ptr<Swift::Connection> m_conn;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> m_conn;
 
		Transport::Config *config;
 
};
backends/twitter/TwitterPlugin.cpp
Show inline comments
 
@@ -78,47 +78,47 @@ TwitterPlugin::TwitterPlugin(Config *config, Swift::SimpleEventLoop *loop, Stora
 

	
 
	LOG4CXX_INFO(logger, "Fetch timeout is set to " << CONFIG_INT_DEFAULTED(config, "twitter.fetch_timeout", 90000));
 
	tweet_timer = m_factories->getTimerFactory()->createTimer(CONFIG_INT_DEFAULTED(config, "twitter.fetch_timeout", 90000));
 
	message_timer = m_factories->getTimerFactory()->createTimer(CONFIG_INT_DEFAULTED(config, "twitter.fetch_timeout", 90000));
 

	
 
	tweet_timer->onTick.connect(boost::bind(&TwitterPlugin::pollForTweets, this));
 
	message_timer->onTick.connect(boost::bind(&TwitterPlugin::pollForDirectMessages, this));
 

	
 
	tweet_timer->start();
 
	message_timer->start();
 

	
 
#if HAVE_SWIFTEN_3
 
		cryptoProvider = boost::shared_ptr<Swift::CryptoProvider>(Swift::PlatformCryptoProvider::create());
 
		cryptoProvider = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::CryptoProvider>(Swift::PlatformCryptoProvider::create());
 
#endif
 
	
 
	
 
	LOG4CXX_INFO(logger, "Starting the plugin.");
 
}
 

	
 
TwitterPlugin::~TwitterPlugin() 
 
{
 
	delete storagebackend;
 
	std::set<std::string>::iterator it;
 
	for(it = onlineUsers.begin() ; it != onlineUsers.end() ; it++) delete userdb[*it].sessions;
 
	delete tp;
 
}
 

	
 
// Send data to NetworkPlugin server
 
void TwitterPlugin::sendData(const std::string &string) 
 
{
 
	m_conn->write(Swift::createSafeByteArray(string));
 
}
 

	
 
// Receive date from the NetworkPlugin server and invoke the appropirate payload handler (implement in the NetworkPlugin class)
 
void TwitterPlugin::_handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) 
 
void TwitterPlugin::_handleDataRead(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::SafeByteArray> data)
 
{
 
	if (m_firstPing) {
 
		m_firstPing = false;
 
		// Users can join the network without registering if we allow
 
		// one user to connect multiple IRC networks.
 
		NetworkPlugin::PluginConfig cfg;
 
		cfg.setNeedPassword(false);
 
		sendConfig(cfg);
 
	}
 

	
 
	std::string d(data->begin(), data->end());
 
	handleDataRead(d);
backends/twitter/TwitterPlugin.h
Show inline comments
 
@@ -2,24 +2,25 @@
 
#define TWITTER_PLUGIN
 

	
 
#include "transport/Config.h"
 
#include "transport/NetworkPlugin.h"
 
#include "transport/Logging.h"
 
#include "transport/SQLite3Backend.h"
 
#include "transport/MySQLBackend.h"
 
#include "transport/PQXXBackend.h"
 
#include "transport/StorageBackend.h"
 
#include "transport/ThreadPool.h"
 

	
 
#include "Swiften/Swiften.h"
 
#include "Swiften/SwiftenCompat.h"
 
#ifndef _WIN32
 
#include "unistd.h"
 
#include "signal.h"
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
#endif
 
#include <boost/algorithm/string.hpp>
 
#include <boost/signal.hpp>
 
#include <boost/thread.hpp>
 
#include <boost/thread/mutex.hpp>
 

	
 
#include "twitcurl.h"
 
@@ -46,40 +47,40 @@ using namespace Transport;
 

	
 
#define STR(x) (std::string("(") + x.from + ", " + x.to + ", " + x.message + ")")
 

	
 
class TwitterPlugin;
 
extern TwitterPlugin *np;
 
extern Swift::SimpleEventLoop *loop_; // Event Loop
 

	
 

	
 
class TwitterPlugin : public NetworkPlugin {
 
	public:
 
		Swift::BoostNetworkFactories *m_factories;
 
		Swift::BoostIOServiceThread m_boostIOServiceThread;
 
		boost::shared_ptr<Swift::Connection> m_conn;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> m_conn;
 
#if HAVE_SWIFTEN_3
 
		boost::shared_ptr<Swift::CryptoProvider> cryptoProvider;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::CryptoProvider> cryptoProvider;
 
#endif
 
		Swift::Timer::ref tweet_timer;
 
		Swift::Timer::ref message_timer;
 
		StorageBackend *storagebackend;
 

	
 
		TwitterPlugin(Config *config, Swift::SimpleEventLoop *loop, StorageBackend *storagebackend, const std::string &host, int port);
 
		~TwitterPlugin();
 

	
 
		// Send data to NetworkPlugin server
 
		void sendData(const std::string &string);
 

	
 
		// Receive date from the NetworkPlugin server and invoke the appropirate payload handler (implement in the NetworkPlugin class)
 
		void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data);
 
		void _handleDataRead(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::SafeByteArray> data);
 
	
 
		// User trying to login into his twitter account
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password);
 
		
 
		// User logging out
 
		void handleLogoutRequest(const std::string &user, const std::string &legacyName);
 
		
 
		void handleJoinRoomRequest(const std::string &/*user*/, const std::string &/*room*/, const std::string &/*nickname*/, const std::string &/*pasword*/);
 

	
 
		void handleLeaveRoomRequest(const std::string &/*user*/, const std::string &/*room*/);
 

	
 
		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml = "", const std::string &id = "");
cmake_modules/SwiftenConfig.cmake
Show inline comments
 
FIND_LIBRARY(SWIFTEN_LIBRARY NAMES Swiften Swiften3 HINTS ../lib)
 
FIND_PATH(SWIFTEN_INCLUDE_DIR NAMES "Swiften/Swiften.h" PATH_SUFFIXES libSwiften Swiften HINTS ../include)
 

	
 
if( SWIFTEN_LIBRARY AND SWIFTEN_INCLUDE_DIR )
 
	find_program(SWIFTEN_CONFIG_EXECUTABLE NAMES swiften-config DOC "swiften-config executable" HINTS ../bin)
 
	set( SWIFTEN_CFLAGS "" )
 
	if (SWIFTEN_CONFIG_EXECUTABLE)
 
		# Libs
 
		execute_process(
 
			COMMAND ${SWIFTEN_CONFIG_EXECUTABLE} --libs
 
			OUTPUT_VARIABLE SWIFTEN_LIB)
 
		string(REGEX REPLACE "[\r\n]"                  " " SWIFTEN_LIB "${SWIFTEN_LIB}")
 
		string(REGEX REPLACE " +$"                     ""  SWIFTEN_LIB "${SWIFTEN_LIB}")
 
		set(SWIFTEN_LIBRARY "")
 
		if (APPLE)
 
			string(REGEX MATCHALL "-framework [A-Za-z]+" APPLE_FRAMEWORKS "${SWIFTEN_LIB}")
 
			foreach(framework ${APPLE_FRAMEWORKS})
 
				list(APPEND SWIFTEN_LIBRARY ${framework} )
 
			endforeach(framework)
 
			string(REGEX REPLACE "-framework [A-Za-z]+" "" SWIFTEN_LIB "${SWIFTEN_LIB}")
 
		endif(APPLE)
 
		string(REGEX REPLACE " " ";" SWIFTEN_LIB "${SWIFTEN_LIB}")
 
		foreach(f ${SWIFTEN_LIB})
 
			STRING(SUBSTRING ${f} 0 2 f_out)
 
			STRING(COMPARE EQUAL ${f_out} "/L" IS_PATH)
 
			if(${IS_PATH})
 
				string(REGEX REPLACE "/LIBPATH:" ""  f_replaced "${f}")
 
				message("Added link directory: ${f_replaced}")
 
				link_directories(${f_replaced})
 
			else()
 
				list(APPEND SWIFTEN_LIBRARY ${f})
 
			endif()
 
		endforeach(f) 
 
		endforeach(f)
 
		
 
		# Version
 
		execute_process(
 
			COMMAND ${SWIFTEN_CONFIG_EXECUTABLE} --version
 
			OUTPUT_VARIABLE SWIFTEN_VERSION)
 
		string(REGEX REPLACE "[\r\n]"                  " " SWIFTEN_VERSION "${SWIFTEN_VERSION}")
 
		string(REGEX REPLACE " +$"                     ""  SWIFTEN_VERSION "${SWIFTEN_VERSION}")
 
		string(REGEX REPLACE "swiften-config "          ""  SWIFTEN_VERSION "${SWIFTEN_VERSION}")
 

	
 
		if("${SWIFTEN_VERSION}" STRGREATER "4")
 
			message( STATUS "Found Swiften > 4 requesting C++11")
 
			add_definitions(-std=c++11)
 
		endif()
 
		
 
		set( SWIFTEN_FOUND 1 )
 
	else()
 
		message( STATUS "Could NOT find swiften-config" )
 
	endif()
 

	
 
	if (SWIFTEN_FOUND)
 
		set( SWIFTEN_INCLUDE_DIR ${SWIFTEN_INCLUDE_DIR} )
 
		message( STATUS "Found libSwiften: ${SWIFTEN_LIBRARY}, ${SWIFTEN_INCLUDE_DIR}")
 
	endif()
 

	
 
else( SWIFTEN_LIBRARY AND SWIFTEN_INCLUDE_DIR )
 
    message( STATUS "Could NOT find libSwiften" )
include/Swiften/Elements/AttentionPayload.h
Show inline comments
 
@@ -3,21 +3,23 @@
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include <string>
 
#include <boost/shared_ptr.hpp>
 

	
 
#include <Swiften/Elements/Payload.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class AttentionPayload : public Payload {
 
		public:
 
			typedef boost::shared_ptr<AttentionPayload> ref;
 
			typedef SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<AttentionPayload> ref;
 

	
 
		public:
 
			AttentionPayload();
 
	};
 
}
include/Swiften/Elements/InvisiblePayload.h
Show inline comments
 
@@ -3,23 +3,25 @@
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include <string>
 
#include <boost/shared_ptr.hpp>
 

	
 
#include <Swiften/Elements/Payload.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
// This payload is NOT part of ANY XEP and it is only
 
// libtransport related extension.
 
namespace Swift {
 
	class InvisiblePayload : public Payload {
 
		public:
 
			typedef boost::shared_ptr<InvisiblePayload> ref;
 
			typedef SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<InvisiblePayload> ref;
 

	
 
		public:
 
			InvisiblePayload();
 
	};
 
}
include/Swiften/FileTransfer/CombinedOutgoingFileTransferManager.cpp
Show inline comments
 
@@ -22,48 +22,48 @@
 

	
 

	
 
namespace Swift {
 

	
 
CombinedOutgoingFileTransferManager::CombinedOutgoingFileTransferManager(JingleSessionManager* jingleSessionManager, IQRouter* router, EntityCapsProvider* capsProvider, RemoteJingleTransportCandidateSelectorFactory* remoteFactory, LocalJingleTransportCandidateGeneratorFactory* localFactory, SOCKS5BytestreamRegistry* bytestreamRegistry, SOCKS5BytestreamProxy* bytestreamProxy, Transport::PresenceOracle *presOracle, SOCKS5BytestreamServer *bytestreamServer) : jsManager(jingleSessionManager), iqRouter(router), capsProvider(capsProvider), remoteFactory(remoteFactory), localFactory(localFactory), bytestreamRegistry(bytestreamRegistry), bytestreamProxy(bytestreamProxy), presenceOracle(presOracle), bytestreamServer(bytestreamServer) {
 
	idGenerator = new IDGenerator();
 
}
 

	
 
CombinedOutgoingFileTransferManager::~CombinedOutgoingFileTransferManager() {
 
	delete idGenerator;
 
}
 

	
 
boost::shared_ptr<OutgoingFileTransfer> CombinedOutgoingFileTransferManager::createOutgoingFileTransfer(const JID& from, const JID& receipient, boost::shared_ptr<ReadBytestream> readBytestream, const StreamInitiationFileInfo& fileInfo) {
 
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<OutgoingFileTransfer> CombinedOutgoingFileTransferManager::createOutgoingFileTransfer(const JID& from, const JID& receipient, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ReadBytestream> readBytestream, const StreamInitiationFileInfo& fileInfo) {
 
	// check if receipient support Jingle FT
 
	boost::optional<JID> fullJID = highestPriorityJIDSupportingJingle(receipient);
 
	if (!fullJID.is_initialized()) {
 
		fullJID = highestPriorityJIDSupportingSI(receipient);
 
	}
 
	else {
 
		JingleSessionImpl::ref jingleSession = boost::make_shared<JingleSessionImpl>(from, receipient, idGenerator->generateID(), iqRouter);
 
		JingleSessionImpl::ref jingleSession = SWIFTEN_SHRPTR_NAMESPACE::make_shared<JingleSessionImpl>(from, receipient, idGenerator->generateID(), iqRouter);
 

	
 
		//jsManager->getSession(receipient, idGenerator->generateID());
 
		assert(jingleSession);
 
		jsManager->registerOutgoingSession(from, jingleSession);
 
#if !HAVE_SWIFTEN_3
 
		boost::shared_ptr<OutgoingJingleFileTransfer> jingleFT =  boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer(jingleSession, remoteFactory, localFactory, iqRouter, idGenerator, from, receipient, readBytestream, fileInfo, bytestreamRegistry, bytestreamProxy));
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<OutgoingJingleFileTransfer> jingleFT =  SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer(jingleSession, remoteFactory, localFactory, iqRouter, idGenerator, from, receipient, readBytestream, fileInfo, bytestreamRegistry, bytestreamProxy));
 
		return jingleFT;
 
#endif
 
	}
 

	
 
	if (!fullJID.is_initialized()) {
 
		return boost::shared_ptr<OutgoingFileTransfer>();
 
		return SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<OutgoingFileTransfer>();
 
	}
 
	
 
	// otherwise try SI
 
	boost::shared_ptr<MyOutgoingSIFileTransfer> jingleFT =  boost::shared_ptr<MyOutgoingSIFileTransfer>(new MyOutgoingSIFileTransfer(idGenerator->generateID(), from, fullJID.get(), fileInfo.getName(), fileInfo.getSize(), fileInfo.getDescription(), readBytestream, iqRouter, bytestreamServer, bytestreamRegistry));
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<MyOutgoingSIFileTransfer> jingleFT =  SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<MyOutgoingSIFileTransfer>(new MyOutgoingSIFileTransfer(idGenerator->generateID(), from, fullJID.get(), fileInfo.getName(), fileInfo.getSize(), fileInfo.getDescription(), readBytestream, iqRouter, bytestreamServer, bytestreamRegistry));
 
	// else fail
 
	
 
	return jingleFT;
 
}
 

	
 
boost::optional<JID> CombinedOutgoingFileTransferManager::highestPriorityJIDSupportingJingle(const JID& bareJID) {
 
	JID fullReceipientJID;
 
	int priority = INT_MIN;
 
	
 
	//getAllPresence(bareJID) gives you all presences for the bare JID (i.e. all resources) Remko Tronçon @ 11:11
 
	std::vector<Presence::ref> presences = presenceOracle->getAllPresence(bareJID);
 

	
include/Swiften/FileTransfer/CombinedOutgoingFileTransferManager.h
Show inline comments
 
@@ -3,24 +3,27 @@
 
 * Licensed under the simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/shared_ptr.hpp>
 
#include <boost/optional.hpp>
 

	
 
#include <Swiften/JID/JID.h>
 

	
 
#include "transport/PresenceOracle.h"
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
 
#include <Swiften/Version.h>
 
#define HAVE_SWIFTEN_3  (SWIFTEN_VERSION >= 0x030000)
 

	
 
namespace Swift {
 

	
 
class JingleSessionManager;
 
class IQRouter;
 
class EntityCapsProvider;
 
class RemoteJingleTransportCandidateSelectorFactory;
 
class LocalJingleTransportCandidateGeneratorFactory;
 
class OutgoingFileTransfer;
 
@@ -29,25 +32,25 @@ class IDGenerator;
 
class ReadBytestream;
 
class StreamInitiationFileInfo;
 
class SOCKS5BytestreamRegistry;
 
class SOCKS5BytestreamProxy;
 
class SOCKS5BytestreamServer;
 
class PresenceOracle;
 

	
 
class CombinedOutgoingFileTransferManager {
 
public:
 
	CombinedOutgoingFileTransferManager(JingleSessionManager* jingleSessionManager, IQRouter* router, EntityCapsProvider* capsProvider, RemoteJingleTransportCandidateSelectorFactory* remoteFactory, LocalJingleTransportCandidateGeneratorFactory* localFactory, SOCKS5BytestreamRegistry* bytestreamRegistry, SOCKS5BytestreamProxy* bytestreamProxy, Transport::PresenceOracle* presOracle, SOCKS5BytestreamServer *server);
 
	~CombinedOutgoingFileTransferManager();
 
	
 
	boost::shared_ptr<OutgoingFileTransfer> createOutgoingFileTransfer(const JID& from, const JID& to, boost::shared_ptr<ReadBytestream>, const StreamInitiationFileInfo&);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<OutgoingFileTransfer> createOutgoingFileTransfer(const JID& from, const JID& to, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ReadBytestream>, const StreamInitiationFileInfo&);
 

	
 
private:
 
	boost::optional<JID> highestPriorityJIDSupportingJingle(const JID& bareJID);
 
	boost::optional<JID> highestPriorityJIDSupportingSI(const JID& bareJID);
 
	JingleSessionManager* jsManager;
 
	IQRouter* iqRouter;
 
	EntityCapsProvider* capsProvider;
 
	RemoteJingleTransportCandidateSelectorFactory* remoteFactory;
 
	LocalJingleTransportCandidateGeneratorFactory* localFactory;
 
	IDGenerator *idGenerator;
 
	SOCKS5BytestreamRegistry* bytestreamRegistry;
 
	SOCKS5BytestreamProxy* bytestreamProxy;
include/Swiften/FileTransfer/MyOutgoingSIFileTransfer.cpp
Show inline comments
 
@@ -5,27 +5,29 @@
 
 */
 

	
 
#include <Swiften/FileTransfer/MyOutgoingSIFileTransfer.h>
 

	
 
#include <boost/bind.hpp>
 

	
 
#include <Swiften/FileTransfer/StreamInitiationRequest.h>
 
#include <Swiften/FileTransfer/BytestreamsRequest.h>
 
#include <Swiften/FileTransfer/SOCKS5BytestreamServer.h>
 
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
 
#include <Swiften/FileTransfer/IBBSendSession.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 

	
 
MyOutgoingSIFileTransfer::MyOutgoingSIFileTransfer(const std::string& id, const JID& from, const JID& to, const std::string& name, int size, const std::string& description, boost::shared_ptr<ReadBytestream> bytestream, IQRouter* iqRouter, SOCKS5BytestreamServer* socksServer, SOCKS5BytestreamRegistry* registry) : id(id), from(from), to(to), name(name), size(size), description(description), bytestream(bytestream), iqRouter(iqRouter), socksServer(socksServer), registry(registry) {
 
MyOutgoingSIFileTransfer::MyOutgoingSIFileTransfer(const std::string& id, const JID& from, const JID& to, const std::string& name, int size, const std::string& description, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ReadBytestream> bytestream, IQRouter* iqRouter, SOCKS5BytestreamServer* socksServer, SOCKS5BytestreamRegistry* registry) : id(id), from(from), to(to), name(name), size(size), description(description), bytestream(bytestream), iqRouter(iqRouter), socksServer(socksServer), registry(registry) {
 
}
 

	
 
void MyOutgoingSIFileTransfer::start() {
 
	StreamInitiation::ref streamInitiation(new StreamInitiation());
 
	streamInitiation->setID(id);
 
	streamInitiation->setFileInfo(StreamInitiationFileInfo(name, description, size));
 
	streamInitiation->addProvidedMethod("http://jabber.org/protocol/bytestreams");
 
	streamInitiation->addProvidedMethod("http://jabber.org/protocol/ibb");
 
	StreamInitiationRequest::ref request = StreamInitiationRequest::create(from, to, streamInitiation, iqRouter);
 
	request->onResponse.connect(boost::bind(&MyOutgoingSIFileTransfer::handleStreamInitiationRequestResponse, this, _1, _2));
 
	request->send();
 
}
 
@@ -60,25 +62,25 @@ void MyOutgoingSIFileTransfer::handleStreamInitiationRequestResponse(StreamIniti
 
			registry->addReadBytestream(SOCKS5BytestreamRegistry::getHostname(id, from, to), bytestream);
 
			socksServer->addReadBytestream(id, from, to, bytestream);
 
#endif
 
			Bytestreams::ref bytestreams(new Bytestreams());
 
			bytestreams->setStreamID(id);
 
			HostAddressPort addressPort = socksServer->getAddressPort();
 
			bytestreams->addStreamHost(Bytestreams::StreamHost(addressPort.getAddress().toString(), from, addressPort.getPort()));
 
			BytestreamsRequest::ref request = BytestreamsRequest::create(from, to, bytestreams, iqRouter);
 
			request->onResponse.connect(boost::bind(&MyOutgoingSIFileTransfer::handleBytestreamsRequestResponse, this, _1, _2));
 
			request->send();
 
		}
 
		else if (response->getRequestedMethod() == "http://jabber.org/protocol/ibb") {
 
			ibbSession = boost::shared_ptr<IBBSendSession>(new IBBSendSession(id, from, to, bytestream, iqRouter));
 
			ibbSession = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<IBBSendSession>(new IBBSendSession(id, from, to, bytestream, iqRouter));
 
			ibbSession->onFinished.connect(boost::bind(&MyOutgoingSIFileTransfer::handleIBBSessionFinished, this, _1));
 
			ibbSession->start();
 
#if !HAVE_SWIFTEN_3
 
			onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
 
#endif
 
		}
 
	}
 
}
 

	
 
void MyOutgoingSIFileTransfer::handleBytestreamsRequestResponse(Bytestreams::ref, ErrorPayload::ref error) {
 
	if (error) {
 
		finish(FileTransferError());
include/Swiften/FileTransfer/MyOutgoingSIFileTransfer.h
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/shared_ptr.hpp>
 
#include <boost/signals.hpp>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
 
#include <Swiften/FileTransfer/ReadBytestream.h>
 
#include <Swiften/Base/boost_bsignals.h>
 
#include <Swiften/FileTransfer/FileTransferError.h>
 
#include <Swiften/FileTransfer/SOCKS5BytestreamServer.h>
 
#include <Swiften/JID/JID.h>
 
#include <Swiften/Elements/StreamInitiation.h>
 
#include <Swiften/Elements/Bytestreams.h>
 
#include <Swiften/Elements/ErrorPayload.h>
 
#include <Swiften/FileTransfer/IBBSendSession.h>
 
#include <Swiften/Version.h>
 
#define HAVE_SWIFTEN_3  (SWIFTEN_VERSION >= 0x030000)
 

	
 
namespace Swift {
 
	class IQRouter;
 
	class SOCKS5BytestreamServer;
 
	class SOCKS5BytestreamRegistry;
 

	
 
	class MyOutgoingSIFileTransfer : public OutgoingFileTransfer {
 
		public:
 
			MyOutgoingSIFileTransfer(const std::string& id, const JID& from, const JID& to, const std::string& name, int size, const std::string& description, boost::shared_ptr<ReadBytestream> bytestream, IQRouter* iqRouter, SOCKS5BytestreamServer* socksServer, SOCKS5BytestreamRegistry* registry);
 
			MyOutgoingSIFileTransfer(const std::string& id, const JID& from, const JID& to, const std::string& name, int size, const std::string& description, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ReadBytestream> bytestream, IQRouter* iqRouter, SOCKS5BytestreamServer* socksServer, SOCKS5BytestreamRegistry* registry);
 

	
 
			virtual void start();
 
			virtual void stop();
 
			virtual void cancel();
 

	
 
			boost::signal<void (const boost::optional<FileTransferError>&)> onFinished;
 

	
 
		private:
 
			void handleStreamInitiationRequestResponse(StreamInitiation::ref, ErrorPayload::ref);
 
			void handleBytestreamsRequestResponse(Bytestreams::ref, ErrorPayload::ref);
 
			void finish(boost::optional<FileTransferError> error);
 
			void handleIBBSessionFinished(boost::optional<FileTransferError> error);
 

	
 
		private:
 
			std::string id;
 
			JID from;
 
			JID to;
 
			std::string name;
 
			int size;
 
			std::string description;
 
			boost::shared_ptr<ReadBytestream> bytestream;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ReadBytestream> bytestream;
 
			IQRouter* iqRouter;
 
			SOCKS5BytestreamServer* socksServer;
 
			boost::shared_ptr<IBBSendSession> ibbSession;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<IBBSendSession> ibbSession;
 
			SOCKS5BytestreamRegistry *registry;
 
	};
 
}
include/Swiften/Network/DummyConnectionServer.cpp
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#include <Swiften/Network/DummyConnectionServer.h>
 

	
 
#include <boost/signal.hpp>
 
#include <boost/bind.hpp>
 
#include <boost/system/system_error.hpp>
 
#include <boost/asio/placeholders.hpp>
 

	
 
#include <Swiften/EventLoop/EventLoop.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 

	
 
DummyConnectionServer::DummyConnectionServer(EventLoop* eventLoop) : eventLoop(eventLoop) {
 
}
 

	
 
void DummyConnectionServer::start() {
 
}
 

	
 

	
 
void DummyConnectionServer::stop() {
 
	
 
}
 

	
 
void DummyConnectionServer::acceptConnection(boost::shared_ptr<Swift::Connection> connection) {
 
void DummyConnectionServer::acceptConnection(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> connection) {
 
		eventLoop->postEvent(
 
				boost::bind(boost::ref(onNewConnection), connection), 
 
				shared_from_this());
 
				SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<DummyConnectionServer>(this));
 
// 		connection->listen();
 
}
 

	
 

	
 
HostAddressPort DummyConnectionServer::getAddressPort() const {
 
	return HostAddressPort();
 
}
 

	
 
}
include/Swiften/Network/DummyConnectionServer.h
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/shared_ptr.hpp>
 
#include <boost/asio/io_service.hpp>
 
#include <boost/asio/ip/tcp.hpp>
 
#include <boost/enable_shared_from_this.hpp>
 
#include <Swiften/Base/boost_bsignals.h>
 

	
 
#include <Swiften/Network/DummyConnection.h>
 
#include <Swiften/Network/ConnectionServer.h>
 
#include <Swiften/EventLoop/EventOwner.h>
 
#include <Swiften/Version.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class DummyConnectionServer : public ConnectionServer, public EventOwner, public boost::enable_shared_from_this<DummyConnectionServer> {
 
		public:
 
			typedef boost::shared_ptr<DummyConnectionServer> ref;
 
			typedef SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<DummyConnectionServer> ref;
 

	
 
			enum Error {
 
				Conflict,
 
				UnknownError
 
			};
 

	
 
			static ref create(EventLoop* eventLoop) {
 
				return ref(new DummyConnectionServer(eventLoop));
 
			static SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::DummyConnectionServer> create(EventLoop* eventLoop) {
 
				return SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::DummyConnectionServer>(new DummyConnectionServer(eventLoop));
 
			}
 

	
 
			void acceptConnection(boost::shared_ptr<Swift::Connection> connection);
 
			void acceptConnection(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> connection);
 

	
 
#if (SWIFTEN_VERSION >= 0x030000)
 
			virtual boost::optional<ConnectionServer::Error> tryStart() {
 
				return boost::optional<ConnectionServer::Error>();
 
			}
 
#endif
 

	
 
			virtual void start();
 
			virtual void stop();
 

	
 
			virtual HostAddressPort getAddressPort() const;
 

	
include/Swiften/Network/DummyConnectionServerFactory.cpp
Show inline comments
 
@@ -3,21 +3,21 @@
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#include <Swiften/Network/DummyConnectionServerFactory.h>
 
#include <Swiften/Network/DummyConnectionServer.h>
 

	
 
namespace Swift {
 

	
 
DummyConnectionServerFactory::DummyConnectionServerFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {
 
}
 

	
 
boost::shared_ptr<ConnectionServer> DummyConnectionServerFactory::createConnectionServer(int port) {
 
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ConnectionServer> DummyConnectionServerFactory::createConnectionServer(int port) {
 
	return DummyConnectionServer::create(eventLoop);
 
}
 

	
 
boost::shared_ptr<ConnectionServer> DummyConnectionServerFactory::createConnectionServer(const Swift::HostAddress &hostAddress, int port) {
 
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ConnectionServer> DummyConnectionServerFactory::createConnectionServer(const Swift::HostAddress &hostAddress, int port) {
 
	return DummyConnectionServer::create(eventLoop);
 
}
 

	
 
}
include/Swiften/Network/DummyConnectionServerFactory.h
Show inline comments
 
@@ -2,27 +2,29 @@
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/asio/io_service.hpp>
 

	
 
#include <Swiften/Network/ConnectionServerFactory.h>
 
#include <Swiften/Network/DummyConnectionServer.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class ConnectionServer;
 

	
 
	class DummyConnectionServerFactory : public ConnectionServerFactory {
 
		public:
 
			DummyConnectionServerFactory(EventLoop* eventLoop);
 

	
 
			virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port);
 
			virtual SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ConnectionServer> createConnectionServer(int port);
 

	
 
			virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress &hostAddress, int port);
 
			virtual SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress &hostAddress, int port);
 

	
 
		private:
 
			EventLoop* eventLoop;
 
	};
 
}
include/Swiften/Network/DummyNetworkFactories.cpp
Show inline comments
 
@@ -13,25 +13,25 @@
 
#include <Swiften/Crypto/CryptoProvider.h>
 
#include <Swiften/Crypto/PlatformCryptoProvider.h>
 
#include <Swiften/Network/NetworkEnvironment.h>
 
#include <Swiften/Network/PlatformNetworkEnvironment.h>
 
#endif
 

	
 
namespace Swift {
 

	
 
DummyNetworkFactories::DummyNetworkFactories(EventLoop* eventLoop) {
 
	timerFactory = new DummyTimerFactory();
 
	connectionFactory = new DummyConnectionFactory(eventLoop);
 
#if HAVE_SWIFTEN_3
 
	idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
 
	idnConverter = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
 
	domainNameResolver = new PlatformDomainNameResolver(idnConverter.get(), eventLoop);
 
	cryptoProvider = PlatformCryptoProvider::create();
 
	networkEnvironment = new PlatformNetworkEnvironment();
 
#else
 
	domainNameResolver = new PlatformDomainNameResolver(eventLoop);
 
#endif
 
	connectionServerFactory = new DummyConnectionServerFactory(eventLoop);
 
	m_platformXMLParserFactory =  new PlatformXMLParserFactory();
 
	this->eventLoop = eventLoop;
 
}
 

	
 
DummyNetworkFactories::~DummyNetworkFactories() {
include/Swiften/Network/DummyNetworkFactories.h
Show inline comments
 
@@ -7,24 +7,26 @@
 
#pragma once
 

	
 
#include <Swiften/Version.h>
 
#define HAVE_SWIFTEN_3  (SWIFTEN_VERSION >= 0x030000)
 

	
 
#include <Swiften/Network/NetworkFactories.h>
 
#include <Swiften/Parser/PlatformXMLParserFactory.h>
 
#if HAVE_SWIFTEN_3
 
#include <Swiften/IDN/IDNConverter.h>
 
#include <Swiften/IDN/PlatformIDNConverter.h>
 
#endif
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class EventLoop;
 

	
 
	class DummyNetworkFactories : public NetworkFactories {
 
		public:
 
			DummyNetworkFactories(EventLoop *eventLoop);
 
			~DummyNetworkFactories();
 

	
 
			virtual TimerFactory* getTimerFactory() const {
 
				return timerFactory;
 
			}
 

	
 
@@ -68,21 +70,21 @@ namespace Swift {
 
            Swift::TLSContextFactory* getTLSContextFactory() const {
 
                return 0;
 
            }
 

	
 
            Swift::ProxyProvider* getProxyProvider() const {
 
                return 0;
 
            }
 
		private:
 
			PlatformXMLParserFactory *m_platformXMLParserFactory;
 
			TimerFactory* timerFactory;
 
			ConnectionFactory* connectionFactory;
 
#if HAVE_SWIFTEN_3
 
			boost::shared_ptr<IDNConverter> idnConverter;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<IDNConverter> idnConverter;
 
			CryptoProvider* cryptoProvider;
 
			NetworkEnvironment* networkEnvironment;
 
#endif
 
			DomainNameResolver* domainNameResolver;
 
			ConnectionServerFactory* connectionServerFactory;
 
			EventLoop *eventLoop;
 
	};
 
}
include/Swiften/Parser/PayloadParsers/XHTMLIMParser.cpp
Show inline comments
 
/*
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#include <cassert>
 
#include <Swiften/Parser/PayloadParsers/XHTMLIMParser.h>
 
#include <Swiften/Parser/SerializingParser.h>
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 

	
 
XHTMLIMParser::XHTMLIMParser() : level_(TopLevel), bodyParser_(0) {
 
}
 

	
 
void XHTMLIMParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
 
	++level_;
 
	if (level_ == BodyLevel) {
 
		if (element == "body") {
 
			assert(!bodyParser_);
 
			bodyParser_ = new SerializingParser();
 
@@ -41,17 +43,17 @@ void XHTMLIMParser::handleEndElement(const std::string& element, const std::stri
 
	--level_;
 
}
 

	
 
void XHTMLIMParser::handleCharacterData(const std::string& data) {
 
	if (bodyParser_) {
 
		bodyParser_->handleCharacterData(data);
 
	}
 
	else {
 
		currentText_ += data;
 
	}
 
}
 

	
 
boost::shared_ptr<XHTMLIMPayload> XHTMLIMParser::getLabelPayload() const {
 
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<XHTMLIMPayload> XHTMLIMParser::getLabelPayload() const {
 
	return getPayloadInternal();
 
}
 

	
 
}
include/Swiften/Parser/PayloadParsers/XHTMLIMParser.h
Show inline comments
 
/*
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <Swiften/Elements/XHTMLIMPayload.h>
 
#include <Swiften/Parser/GenericPayloadParser.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class SerializingParser;
 

	
 
	class XHTMLIMParser : public GenericPayloadParser<XHTMLIMPayload> {
 
		public:
 
			XHTMLIMParser();
 

	
 
			virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
 
			virtual void handleEndElement(const std::string& element, const std::string&);
 
			virtual void handleCharacterData(const std::string& data);
 
			boost::shared_ptr<XHTMLIMPayload> getLabelPayload() const;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<XHTMLIMPayload> getLabelPayload() const;
 
		private:
 
			enum Level { 
 
				TopLevel = 0, 
 
				PayloadLevel = 1,
 
				BodyLevel = 2,
 
				InsideBodyLevel = 3
 
			};
 
			int level_;
 
			SerializingParser* bodyParser_;
 
			std::string currentText_;
 
	};
 
}
include/Swiften/Parser/StringTreeParser.h
Show inline comments
 
@@ -5,35 +5,37 @@
 
 */
 

	
 
#pragma once
 

	
 
#include <deque>
 

	
 
#include <boost/shared_ptr.hpp>
 
#include <boost/smart_ptr/make_shared.hpp>
 

	
 
#include <Swiften/Parser/Tree/ParserElement.h>
 
#include <Swiften/Parser/XMLParserClient.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	/**
 
	 * Generics parser offering something a bit like a DOM to work with.
 
	 */
 
	class StringTreeParser : public XMLParserClient {
 
		public:
 
			StringTreeParser() : XMLParserClient() {}
 
			
 
			virtual void handleStartElement(const std::string& element, const std::string& xmlns, const AttributeMap& attributes) {
 
				if (!root_) {
 
					root_ = boost::make_shared<ParserElement>(element, xmlns, attributes);
 
					root_ = SWIFTEN_SHRPTR_NAMESPACE::make_shared<ParserElement>(element, xmlns, attributes);
 
					elementStack_.push_back(root_);
 
				}
 
				else {
 
					ParserElement::ref current = *elementStack_.rbegin();
 
					elementStack_.push_back(current->addChild(element, xmlns, attributes));
 
				}
 
			}
 

	
 
			virtual void handleEndElement(const std::string& /*element*/, const std::string&) {
 
				elementStack_.pop_back();
 
				if (elementStack_.empty()) {
 
					handleTree(root_);
include/Swiften/Serializer/PayloadSerializers/AttentionSerializer.cpp
Show inline comments
 
@@ -8,19 +8,19 @@
 

	
 
#include <boost/shared_ptr.hpp>
 

	
 
#include <Swiften/Serializer/XML/XMLTextNode.h>
 
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
 
#include <Swiften/Serializer/XML/XMLElement.h>
 

	
 
namespace Swift {
 

	
 
AttentionSerializer::AttentionSerializer() : GenericPayloadSerializer<AttentionPayload>() {
 
}
 

	
 
std::string AttentionSerializer::serializePayload(boost::shared_ptr<AttentionPayload> attention)  const {
 
std::string AttentionSerializer::serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<AttentionPayload> attention)  const {
 
	XMLElement attentionElement("attention", "urn:xmpp:attention:0");
 

	
 
	return attentionElement.serialize();
 
}
 

	
 
}
include/Swiften/Serializer/PayloadSerializers/AttentionSerializer.h
Show inline comments
 
/*
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <Swiften/Serializer/GenericPayloadSerializer.h>
 
#include <Swiften/Elements/AttentionPayload.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class AttentionSerializer : public GenericPayloadSerializer<AttentionPayload> {
 
		public:
 
			AttentionSerializer();
 

	
 
			virtual std::string serializePayload(boost::shared_ptr<AttentionPayload>)  const;
 
			virtual std::string serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<AttentionPayload>)  const;
 
	};
 
}
include/Swiften/Serializer/PayloadSerializers/GatewayPayloadSerializer.cpp
Show inline comments
 
@@ -2,40 +2,42 @@
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#include <Swiften/Serializer/PayloadSerializers/GatewayPayloadSerializer.h>
 
#include <Swiften/Base/foreach.h>
 
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
 
#include <Swiften/Serializer/XML/XMLTextNode.h>
 
#include <Swiften/Serializer/XML/XMLElement.h>
 
#include <Swiften/Serializer/PayloadSerializerCollection.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 

	
 
GatewayPayloadSerializer::GatewayPayloadSerializer()
 
	: GenericPayloadSerializer<GatewayPayload>() {
 
}
 

	
 
std::string GatewayPayloadSerializer::serializePayload(boost::shared_ptr<GatewayPayload> payload)  const {
 
std::string GatewayPayloadSerializer::serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<GatewayPayload> payload)  const {
 
	XMLElement query("query", "jabber:iq:gateway");
 

	
 
	if (payload->getJID().isValid()) {
 
		boost::shared_ptr<XMLElement> jid(new XMLElement("jid", "", payload->getJID().toBare().toString()));
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<XMLElement> jid(new XMLElement("jid", "", payload->getJID().toBare().toString()));
 
		query.addNode(jid);
 
	}
 

	
 
	if (!payload->getDesc().empty()) {
 
		boost::shared_ptr<XMLElement> desc(new XMLElement("desc", "", payload->getDesc()));
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<XMLElement> desc(new XMLElement("desc", "", payload->getDesc()));
 
		query.addNode(desc);
 
	}
 

	
 
	if (!payload->getPrompt().empty()) {
 
		boost::shared_ptr<XMLElement> prompt(new XMLElement("prompt", "", payload->getPrompt()));
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<XMLElement> prompt(new XMLElement("prompt", "", payload->getPrompt()));
 
		query.addNode(prompt);
 
	}
 

	
 
	return query.serialize();
 
}
 

	
 
}
include/Swiften/Serializer/PayloadSerializers/GatewayPayloadSerializer.h
Show inline comments
 
/*
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <Swiften/Serializer/GenericPayloadSerializer.h>
 
#include <Swiften/Elements/GatewayPayload.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class GatewayPayloadSerializer : public GenericPayloadSerializer<GatewayPayload> {
 
		public:
 
			GatewayPayloadSerializer();
 

	
 
			virtual std::string serializePayload(boost::shared_ptr<GatewayPayload> item)  const;
 
			virtual std::string serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<GatewayPayload> item)  const;
 
	};
 
}
include/Swiften/Serializer/PayloadSerializers/InvisibleSerializer.cpp
Show inline comments
 
@@ -10,19 +10,19 @@
 

	
 
#include <Swiften/Serializer/XML/XMLTextNode.h>
 
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
 
#include <Swiften/Serializer/XML/XMLElement.h>
 

	
 
namespace Swift {
 

	
 
// This payload is NOT part of ANY XEP and it is only
 
// libtransport related extension.
 
InvisibleSerializer::InvisibleSerializer() : GenericPayloadSerializer<InvisiblePayload>() {
 
}
 

	
 
std::string InvisibleSerializer::serializePayload(boost::shared_ptr<InvisiblePayload> attention)  const {
 
std::string InvisibleSerializer::serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<InvisiblePayload> attention)  const {
 
	XMLElement attentionElement("invisible", "urn:xmpp:invisible:0");
 

	
 
	return attentionElement.serialize();
 
}
 

	
 
}
include/Swiften/Serializer/PayloadSerializers/InvisibleSerializer.h
Show inline comments
 
/*
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <Swiften/Serializer/GenericPayloadSerializer.h>
 
#include <Swiften/Elements/InvisiblePayload.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
// This payload is NOT part of ANY XEP and it is only
 
// libtransport related extension.
 
namespace Swift {
 
	class InvisibleSerializer : public GenericPayloadSerializer<InvisiblePayload> {
 
		public:
 
			InvisibleSerializer();
 

	
 
			virtual std::string serializePayload(boost::shared_ptr<InvisiblePayload>)  const;
 
			virtual std::string serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<InvisiblePayload>)  const;
 
	};
 
}
include/Swiften/Serializer/PayloadSerializers/SpectrumErrorSerializer.cpp
Show inline comments
 
@@ -10,25 +10,25 @@
 

	
 
#include <Swiften/Base/foreach.h>
 
#include <Swiften/Serializer/XML/XMLTextNode.h>
 
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
 
#include <Swiften/Serializer/XML/XMLElement.h>
 
#include <boost/lexical_cast.hpp>
 

	
 
namespace Swift {
 

	
 
SpectrumErrorSerializer::SpectrumErrorSerializer() : GenericPayloadSerializer<SpectrumErrorPayload>() {
 
}
 

	
 
std::string SpectrumErrorSerializer::serializePayload(boost::shared_ptr<SpectrumErrorPayload> error)  const {
 
std::string SpectrumErrorSerializer::serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<SpectrumErrorPayload> error)  const {
 
	std::string data;
 
	switch (error->getError()) {
 
		case SpectrumErrorPayload::CONNECTION_ERROR_NETWORK_ERROR: data = "CONNECTION_ERROR_NETWORK_ERROR"; break;
 
		case SpectrumErrorPayload::CONNECTION_ERROR_INVALID_USERNAME: data = "CONNECTION_ERROR_INVALID_USERNAME"; break;
 
		case SpectrumErrorPayload::CONNECTION_ERROR_AUTHENTICATION_FAILED: data = "CONNECTION_ERROR_AUTHENTICATION_FAILED"; break;
 
		case SpectrumErrorPayload::CONNECTION_ERROR_AUTHENTICATION_IMPOSSIBLE: data = "CONNECTION_ERROR_AUTHENTICATION_IMPOSSIBLE"; break;
 
		case SpectrumErrorPayload::CONNECTION_ERROR_NO_SSL_SUPPORT: data = "CONNECTION_ERROR_NO_SSL_SUPPORT"; break;
 
		case SpectrumErrorPayload::CONNECTION_ERROR_ENCRYPTION_ERROR: data = "CONNECTION_ERROR_ENCRYPTION_ERROR"; break;
 
		case SpectrumErrorPayload::CONNECTION_ERROR_NAME_IN_USE: data = "CONNECTION_ERROR_NAME_IN_USE"; break;
 
		case SpectrumErrorPayload::CONNECTION_ERROR_INVALID_SETTINGS: data = "CONNECTION_ERROR_INVALID_SETTINGS"; break;
 
		case SpectrumErrorPayload::CONNECTION_ERROR_CERT_NOT_PROVIDED: data = "CONNECTION_ERROR_CERT_NOT_PROVIDED"; break;
 
		case SpectrumErrorPayload::CONNECTION_ERROR_CERT_UNTRUSTED: data = "CONNECTION_ERROR_CERT_UNTRUSTED"; break;
include/Swiften/Serializer/PayloadSerializers/SpectrumErrorSerializer.h
Show inline comments
 
/*
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <Swiften/Serializer/GenericPayloadSerializer.h>
 
#include <Swiften/Elements/SpectrumErrorPayload.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class SpectrumErrorSerializer : public GenericPayloadSerializer<SpectrumErrorPayload> {
 
		public:
 
			SpectrumErrorSerializer();
 

	
 
			virtual std::string serializePayload(boost::shared_ptr<SpectrumErrorPayload>)  const;
 
			virtual std::string serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<SpectrumErrorPayload>)  const;
 
	};
 
}
include/Swiften/Serializer/PayloadSerializers/StatsSerializer.cpp
Show inline comments
 
@@ -4,33 +4,35 @@
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#include <Swiften/Serializer/PayloadSerializers/StatsSerializer.h>
 

	
 
#include <boost/shared_ptr.hpp>
 

	
 
#include <Swiften/Base/foreach.h>
 
#include <Swiften/Serializer/XML/XMLTextNode.h>
 
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
 
#include <Swiften/Serializer/XML/XMLElement.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 

	
 
StatsSerializer::StatsSerializer() : GenericPayloadSerializer<StatsPayload>() {
 
}
 

	
 
std::string StatsSerializer::serializePayload(boost::shared_ptr<StatsPayload> stats)  const {
 
std::string StatsSerializer::serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<StatsPayload> stats)  const {
 
	XMLElement queryElement("query", "http://jabber.org/protocol/stats");
 
	foreach(const StatsPayload::Item& item, stats->getItems()) {
 
		boost::shared_ptr<XMLElement> statElement(new XMLElement("stat"));
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<XMLElement> statElement(new XMLElement("stat"));
 
		statElement->setAttribute("name", item.getName());
 
		if (!item.getUnits().empty()) {
 
			statElement->setAttribute("units", item.getUnits());
 
		}
 
		if (!item.getValue().empty()) {
 
			statElement->setAttribute("value", item.getValue());
 
		}
 

	
 
		queryElement.addNode(statElement);
 
	}
 

	
 
	return queryElement.serialize();
include/Swiften/Serializer/PayloadSerializers/StatsSerializer.h
Show inline comments
 
/*
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <Swiften/Serializer/GenericPayloadSerializer.h>
 
#include <Swiften/Elements/StatsPayload.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class StatsSerializer : public GenericPayloadSerializer<StatsPayload> {
 
		public:
 
			StatsSerializer();
 

	
 
			virtual std::string serializePayload(boost::shared_ptr<StatsPayload>)  const;
 
			virtual std::string serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<StatsPayload>)  const;
 
	};
 
}
include/Swiften/Serializer/PayloadSerializers/XHTMLIMSerializer.cpp
Show inline comments
 
/*
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#include <Swiften/Serializer/PayloadSerializers/XHTMLIMSerializer.h>
 
#include <Swiften/Base/foreach.h>
 
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
 
#include <Swiften/Serializer/XML/XMLTextNode.h>
 
#include <Swiften/Serializer/XML/XMLElement.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 

	
 
XHTMLIMSerializer::XHTMLIMSerializer() : GenericPayloadSerializer<XHTMLIMPayload>() {
 
}
 

	
 
std::string XHTMLIMSerializer::serializePayload(boost::shared_ptr<XHTMLIMPayload> payload)  const {
 
std::string XHTMLIMSerializer::serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<XHTMLIMPayload> payload)  const {
 
	XMLElement html("html", "http://jabber.org/protocol/xhtml-im");
 

	
 
	boost::shared_ptr<XMLElement> body(new XMLElement("body", "http://www.w3.org/1999/xhtml"));
 
	body->addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(payload->getBody())));
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<XMLElement> body(new XMLElement("body", "http://www.w3.org/1999/xhtml"));
 
	body->addNode(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(payload->getBody())));
 
	html.addNode(body);
 

	
 
	return html.serialize();
 
}
 

	
 
}
include/Swiften/Serializer/PayloadSerializers/XHTMLIMSerializer.h
Show inline comments
 
/*
 
 * Copyright (c) 2011 Jan Kaluza
 
 * Licensed under the Simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <Swiften/Serializer/GenericPayloadSerializer.h>
 
#include <Swiften/Elements/XHTMLIMPayload.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class XHTMLIMSerializer : public GenericPayloadSerializer<XHTMLIMPayload> {
 
		public:
 
			XHTMLIMSerializer();
 

	
 
			virtual std::string serializePayload(boost::shared_ptr<XHTMLIMPayload> xhtml)  const;
 
			virtual std::string serializePayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<XHTMLIMPayload> xhtml)  const;
 
	};
 
}
include/Swiften/Server/Server.cpp
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#include "Swiften/Server/Server.h"
 

	
 
#include <string>
 
#include <boost/bind.hpp>
 
#include <boost/signal.hpp>
 

	
 
#include "Swiften/Base/String.h"
 
#include "Swiften/Base/foreach.h"
 
#include "Swiften/Network/Connection.h"
 
#include "Swiften/Network/ConnectionServer.h"
 
#include "Swiften/Network/ConnectionServerFactory.h"
 
#include "Swiften/Elements/Element.h"
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/Elements/RosterPayload.h"
 
#include "Swiften/Network/NetworkFactories.h"
 
#include "Swiften/Session/SessionTracer.h"
 
#include "Swiften/Elements/IQ.h"
 
@@ -79,45 +80,45 @@ void Server::start() {
 
// 				boost::bind(&Server::handleClientConnectionServerStopped, this, _1)));
 

	
 
	serverFromClientConnectionServer->start();
 
}
 

	
 
void Server::stop() {
 
	if (stopping) {
 
		return;
 
	}
 

	
 
	stopping = true;
 

	
 
// 	foreach(boost::shared_ptr<ServerFromClientSession> session, serverFromClientSessions) {
 
// 	foreach(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> session, serverFromClientSessions) {
 
// 		session->finishSession();
 
// 	}
 
	serverFromClientSessions.clear();
 

	
 
	if (serverFromClientConnectionServer) {
 
		serverFromClientConnectionServer->stop();
 
		foreach(boost::bsignals::connection& connection, serverFromClientConnectionServerSignalConnections) {
 
		foreach(SWIFTEN_SIGNAL_NAMESPACE::connection& connection, serverFromClientConnectionServerSignalConnections) {
 
			connection.disconnect();
 
		}
 
		serverFromClientConnectionServerSignalConnections.clear();
 
		serverFromClientConnectionServer.reset();
 
	}
 

	
 
	stopping = false;
 
// 	onStopped(e);
 
}
 

	
 
void Server::handleNewClientConnection(boost::shared_ptr<Connection> connection) {
 
void Server::handleNewClientConnection(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Connection> connection) {
 

	
 
	boost::shared_ptr<ServerFromClientSession> serverFromClientSession = boost::shared_ptr<ServerFromClientSession>(
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> serverFromClientSession = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession>(
 
			new ServerFromClientSession(idGenerator.generateID(), connection, 
 
					getPayloadParserFactories(), getPayloadSerializers(), userRegistry_, parserFactory_));
 
	//serverFromClientSession->setAllowSASLEXTERNAL();
 

	
 
	serverFromClientSession->onSessionStarted.connect(
 
			boost::bind(&Server::handleSessionStarted, this, serverFromClientSession));
 
	serverFromClientSession->onSessionFinished.connect(
 
			boost::bind(&Server::handleSessionFinished, this, 
 
			serverFromClientSession));
 
	serverFromClientSession->onDataRead.connect(boost::bind(&Server::handleDataRead, this, _1));
 
	serverFromClientSession->onDataWritten.connect(boost::bind(&Server::handleDataWritten, this, _1));
 

	
 
@@ -129,29 +130,29 @@ void Server::handleNewClientConnection(boost::shared_ptr<Connection> connection)
 

	
 
	serverFromClientSessions.push_back(serverFromClientSession);
 
}
 

	
 
void Server::handleDataRead(const SafeByteArray& data) {
 
	onDataRead(data);
 
}
 

	
 
void Server::handleDataWritten(const SafeByteArray& data) {
 
	onDataWritten(data);
 
}
 

	
 
void Server::handleSessionStarted(boost::shared_ptr<ServerFromClientSession> session) {
 
void Server::handleSessionStarted(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> session) {
 
	dynamic_cast<ServerStanzaChannel *>(stanzaChannel_)->addSession(session);
 
}
 

	
 
void Server::handleSessionFinished(boost::shared_ptr<ServerFromClientSession> session) {
 
void Server::handleSessionFinished(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> session) {
 
// 	if (!session->getRemoteJID().isValid()) {
 
// 		Swift::Presence::ref presence = Swift::Presence::create();
 
// 		presence->setFrom(session->getBareJID());
 
// 		presence->setType(Swift::Presence::Unavailable);
 
// 		dynamic_cast<ServerStanzaChannel *>(stanzaChannel_)->onPresenceReceived(presence);
 
// 	}
 
	serverFromClientSessions.erase(std::remove(serverFromClientSessions.begin(), serverFromClientSessions.end(), session), serverFromClientSessions.end());
 
	session->onSessionStarted.disconnect(
 
			boost::bind(&Server::handleSessionStarted, this, session));
 
	session->onSessionFinished.disconnect(
 
			boost::bind(&Server::handleSessionFinished, this, session));
 
}
include/Swiften/Server/Server.h
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/shared_ptr.hpp>
 
#include <boost/optional.hpp>
 
#include <boost/signals2.hpp>
 
#include <vector>
 

	
 
#include "Swiften/Network/BoostIOServiceThread.h"
 
#include "Swiften/Network/ConnectionServer.h"
 
#include "Swiften/Server/UserRegistry.h"
 
#include "Swiften/Server/ServerSession.h"
 
#include "Swiften/Base/IDGenerator.h"
 
#include "Swiften/Server/ServerFromClientSession.h"
 
#include "Swiften/JID/JID.h"
 
#include "Swiften/Base/ByteArray.h"
 
#include "Swiften/Entity/Entity.h"
 
#include "Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h"
 
#include "Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h"
 
#include "Swiften/SwiftenCompat.h"
 
#include <Swiften/TLS/CertificateWithKey.h>
 
#include <Swiften/Parser/PlatformXMLParserFactory.h>
 

	
 
namespace Swift {
 
	class ConnectionServer;
 
	class SessionTracer;
 
	class EventLoop;
 
	class NetworkFactories;
 
	class StanzaChannel;
 
	class IQRouter;
 
	class TLSServerContextFactory;
 

	
 
@@ -44,48 +46,48 @@ namespace Swift {
 
			int getPort() const {
 
				return port_;
 
			}
 

	
 
			StanzaChannel* getStanzaChannel() const {
 
				return stanzaChannel_;
 
			}
 

	
 
			IQRouter* getIQRouter() const {
 
				return iqRouter_;
 
			}
 

	
 
			boost::shared_ptr<ConnectionServer> getConnectionServer() const {
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ConnectionServer> getConnectionServer() const {
 
				return serverFromClientConnectionServer;
 
			}
 

	
 
			boost::signal<void (const SafeByteArray&)> onDataRead;
 
			boost::signal<void (const SafeByteArray&)> onDataWritten;
 

	
 
			void addTLSEncryption(TLSServerContextFactory* tlsContextFactory, CertificateWithKey::ref cert);
 

	
 
		private:
 
			void handleNewClientConnection(boost::shared_ptr<Connection> c);
 
			void handleSessionStarted(boost::shared_ptr<ServerFromClientSession>);
 
			void handleSessionFinished(boost::shared_ptr<ServerFromClientSession>);
 
			void handleElementReceived(boost::shared_ptr<Element> element, boost::shared_ptr<ServerFromClientSession> session);
 
			void handleNewClientConnection(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Connection> c);
 
			void handleSessionStarted(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession>);
 
			void handleSessionFinished(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession>);
 
			void handleElementReceived(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Element> element, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> session);
 
			void handleDataRead(const SafeByteArray&);
 
			void handleDataWritten(const SafeByteArray&);
 

	
 
		private:
 
			IDGenerator idGenerator;
 
			UserRegistry *userRegistry_;
 
			int port_;
 
			EventLoop* eventLoop;
 
			NetworkFactories* networkFactories_;
 
			bool stopping;
 
			boost::shared_ptr<ConnectionServer> serverFromClientConnectionServer;
 
			std::vector<boost::bsignals::connection> serverFromClientConnectionServerSignalConnections;
 
			std::list<boost::shared_ptr<ServerFromClientSession> > serverFromClientSessions;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ConnectionServer> serverFromClientConnectionServer;
 
			std::vector<SWIFTEN_SIGNAL_NAMESPACE::connection> serverFromClientConnectionServerSignalConnections;
 
			std::list<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> > serverFromClientSessions;
 
			JID selfJID;
 
			StanzaChannel *stanzaChannel_;
 
			IQRouter *iqRouter_;
 
			TLSServerContextFactory *tlsFactory;
 
			CertificateWithKey::ref cert;
 
			PlatformXMLParserFactory *parserFactory_;
 
			std::string address_;
 
	};
 
}
include/Swiften/Server/ServerFromClientSession.cpp
Show inline comments
 
@@ -20,137 +20,139 @@
 
#include <Swiften/Elements/IQ.h>
 
#include <Swiften/Elements/AuthSuccess.h>
 
#include <Swiften/Elements/AuthFailure.h>
 
#include <Swiften/Elements/AuthRequest.h>
 
#include <Swiften/SASL/PLAINMessage.h>
 
#include <Swiften/StreamStack/StreamStack.h>
 
#include <Swiften/StreamStack/TLSServerLayer.h>
 
#include <Swiften/Elements/StartTLSRequest.h>
 
#include <Swiften/Elements/TLSProceed.h>
 
#include <iostream>
 
#include <Swiften/TLS/CertificateWithKey.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
#include <Swiften/Version.h>
 
#if (SWIFTEN_VERSION >= 0x030000)
 
#include <Swiften/Elements/ToplevelElement.h>
 
#endif
 

	
 
namespace Swift {
 

	
 
ServerFromClientSession::ServerFromClientSession(
 
		const std::string& id,
 
		boost::shared_ptr<Connection> connection, 
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Connection> connection,
 
		PayloadParserFactoryCollection* payloadParserFactories, 
 
		PayloadSerializerCollection* payloadSerializers,
 
		UserRegistry* userRegistry,
 
		XMLParserFactory* factory,
 
		Swift::JID remoteJID) : 
 
			Session(connection, payloadParserFactories, payloadSerializers, factory),
 
			id_(id),
 
			userRegistry_(userRegistry),
 
			authenticated_(false),
 
			initialized(false),
 
			allowSASLEXTERNAL(false),
 
			tlsLayer(0),
 
			tlsConnected(false) {
 
				setRemoteJID(remoteJID);
 
}
 

	
 
ServerFromClientSession::~ServerFromClientSession() {
 
	if (tlsLayer) {
 
		delete tlsLayer;
 
	}
 
}
 

	
 
void ServerFromClientSession::handlePasswordValid() {
 
	if (!isInitialized()) {
 
		getXMPPLayer()->writeElement(boost::shared_ptr<AuthSuccess>(new AuthSuccess()));
 
		getXMPPLayer()->writeElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<AuthSuccess>(new AuthSuccess()));
 
		authenticated_ = true;
 
		getXMPPLayer()->resetParser();
 
	}
 
}
 

	
 
void ServerFromClientSession::handlePasswordInvalid(const std::string &error) {
 
	if (!isInitialized()) {
 
		getXMPPLayer()->writeElement(boost::shared_ptr<AuthFailure>(new AuthFailure));
 
		getXMPPLayer()->writeElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<AuthFailure>(new AuthFailure));
 
		if (!error.empty()) {
 
			boost::shared_ptr<StreamError> msg(new StreamError(StreamError::UndefinedCondition, error));
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<StreamError> msg(new StreamError(StreamError::UndefinedCondition, error));
 
			getXMPPLayer()->writeElement(msg);
 
		}
 
		
 
		finishSession(AuthenticationFailedError);
 
	}
 
}
 

	
 
#if (SWIFTEN_VERSION >= 0x030000)
 
void ServerFromClientSession::handleElement(boost::shared_ptr<ToplevelElement> element) {
 
void ServerFromClientSession::handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ToplevelElement> element) {
 
#else
 
void ServerFromClientSession::handleElement(boost::shared_ptr<Element> element) {	
 
void ServerFromClientSession::handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Element> element) {
 
#endif
 
	if (isInitialized()) {
 
		onElementReceived(element);
 
	}
 
	else {
 
		if (AuthRequest* authRequest = dynamic_cast<AuthRequest*>(element.get())) {
 
			if (authRequest->getMechanism() == "PLAIN" || (allowSASLEXTERNAL && authRequest->getMechanism() == "EXTERNAL")) {
 
				if (authRequest->getMechanism() == "EXTERNAL") {
 
						getXMPPLayer()->writeElement(boost::shared_ptr<AuthSuccess>(new AuthSuccess()));
 
						getXMPPLayer()->writeElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<AuthSuccess>(new AuthSuccess()));
 
						authenticated_ = true;
 
						getXMPPLayer()->resetParser();
 
				}
 
				else {
 
					PLAINMessage plainMessage(authRequest->getMessage() ? *authRequest->getMessage() : createSafeByteArray(""));
 
					user_ = plainMessage.getAuthenticationID();
 
					userRegistry_->isValidUserPassword(JID(plainMessage.getAuthenticationID(), getLocalJID().getDomain()), this, plainMessage.getPassword());
 
				}
 
			}
 
			else {
 
				getXMPPLayer()->writeElement(boost::shared_ptr<AuthFailure>(new AuthFailure));
 
				getXMPPLayer()->writeElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<AuthFailure>(new AuthFailure));
 
				finishSession(NoSupportedAuthMechanismsError);
 
			}
 
		}
 
		else if (dynamic_cast<StartTLSRequest*>(element.get()) != NULL) {
 
			getXMPPLayer()->writeElement(boost::shared_ptr<TLSProceed>(new TLSProceed));
 
			getXMPPLayer()->writeElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<TLSProceed>(new TLSProceed));
 
			getStreamStack()->addLayer(tlsLayer);
 
			tlsLayer->connect();
 
			getXMPPLayer()->resetParser();
 
		}
 
		else if (IQ* iq = dynamic_cast<IQ*>(element.get())) {
 
			if (boost::shared_ptr<ResourceBind> resourceBind = iq->getPayload<ResourceBind>()) {
 
			if (SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ResourceBind> resourceBind = iq->getPayload<ResourceBind>()) {
 
				std::string bucket = "abcdefghijklmnopqrstuvwxyz";
 
				std::string uuid;
 
				for (int i = 0; i < 10; i++) {
 
					uuid += bucket[rand() % bucket.size()];
 
				}
 
				setRemoteJID(JID(user_, getLocalJID().getDomain(), uuid));
 
				boost::shared_ptr<ResourceBind> resultResourceBind(new ResourceBind());
 
				SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ResourceBind> resultResourceBind(new ResourceBind());
 
				resultResourceBind->setJID(getRemoteJID());
 
				getXMPPLayer()->writeElement(IQ::createResult(JID(), iq->getID(), resultResourceBind));
 
			}
 
			else if (iq->getPayload<StartSession>()) {
 
				getXMPPLayer()->writeElement(IQ::createResult(getRemoteJID(), iq->getID()));
 
				setInitialized();
 
			}
 
		}
 
	}
 
}
 

	
 
void ServerFromClientSession::handleStreamStart(const ProtocolHeader& incomingHeader) {
 
	setLocalJID(JID(incomingHeader.getTo()));
 
	ProtocolHeader header;
 
	header.setFrom(incomingHeader.getTo());
 
	header.setID(id_);
 
	getXMPPLayer()->writeHeader(header);
 

	
 
	boost::shared_ptr<StreamFeatures> features(new StreamFeatures());
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<StreamFeatures> features(new StreamFeatures());
 

	
 
	if (!authenticated_) {
 
		if (tlsLayer && !tlsConnected) {
 
			features->setHasStartTLS();
 
		}
 
		features->addAuthenticationMechanism("PLAIN");
 
		if (allowSASLEXTERNAL) {
 
			features->addAuthenticationMechanism("EXTERNAL");
 
		}
 
	}
 
	else {
 
		features->setHasResourceBind();
 
@@ -168,25 +170,25 @@ void ServerFromClientSession::setAllowSASLEXTERNAL() {
 
	allowSASLEXTERNAL = true;
 
}
 

	
 
void ServerFromClientSession::handleSessionFinished(const boost::optional<SessionError>&) {
 
	userRegistry_->stopLogin(JID(user_, getLocalJID().getDomain()), this);
 
}
 

	
 
void ServerFromClientSession::addTLSEncryption(TLSServerContextFactory* tlsContextFactory, CertificateWithKey::ref cert) {
 
	tlsLayer = new TLSServerLayer(tlsContextFactory);
 
	if (!tlsLayer->setServerCertificate(cert)) {
 
// 		std::cout << "error\n";
 
		// TODO:
 
// 		onClosed(boost::shared_ptr<Error>(new Error(Error::InvalidTLSCertificateError)));
 
// 		onClosed(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Error>(new Error(Error::InvalidTLSCertificateError)));
 
	}
 
	else {
 
		tlsLayer->onError.connect(boost::bind(&ServerFromClientSession::handleTLSError, this));
 
		tlsLayer->onConnected.connect(boost::bind(&ServerFromClientSession::handleTLSConnected, this));
 
// 		getStreamStack()->addLayer(tlsLayer);
 
// 		tlsLayer->onError.connect(boost::bind(&BasicSessionStream::handleTLSError, this));
 
// 		tlsLayer->onConnected.connect(boost::bind(&BasicSessionStream::handleTLSConnected, this));
 
// 		tlsLayer->connect();
 
	}
 
}
 

	
 
}
include/Swiften/Server/ServerFromClientSession.h
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/shared_ptr.hpp>
 
#include <Swiften/Base/boost_bsignals.h>
 
#include <boost/enable_shared_from_this.hpp>
 
#include <boost/signals.hpp>
 

	
 
#include <string>
 
#include <Swiften/Session/Session.h>
 
#include <Swiften/JID/JID.h>
 
#include <Swiften/Network/Connection.h>
 
#include <Swiften/Base/ByteArray.h>
 
#include <Swiften/TLS/CertificateWithKey.h>
 
#include <Swiften/Version.h>
 
#define HAVE_SWIFTEN_3  (SWIFTEN_VERSION >= 0x030000)
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class ProtocolHeader;
 
	class Element;
 
	class Stanza;
 
	class PayloadParserFactoryCollection;
 
	class PayloadSerializerCollection;
 
	class StreamStack;
 
	class UserRegistry;
 
	class XMPPLayer;
 
	class ConnectionLayer;
 
	class Connection;
 
	class TLSServerLayer;
 
	class TLSServerContextFactory;
 
	class PKCS12Certificate;
 

	
 
	class ServerFromClientSession : public Session {
 
		public:
 
			ServerFromClientSession(
 
					const std::string& id,
 
					boost::shared_ptr<Connection> connection, 
 
					SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Connection> connection,
 
					PayloadParserFactoryCollection* payloadParserFactories, 
 
					PayloadSerializerCollection* payloadSerializers,
 
					UserRegistry* userRegistry,
 
					XMLParserFactory* factory,
 
					Swift::JID remoteJID = Swift::JID());
 
			~ServerFromClientSession();
 

	
 
			boost::signal<void ()> onSessionStarted;
 
			void setAllowSASLEXTERNAL();
 
			const std::string &getUser() {
 
				return user_;
 
			}
 

	
 
			void addTLSEncryption(TLSServerContextFactory* tlsContextFactory, CertificateWithKey::ref cert);
 

	
 
			Swift::JID getBareJID() {
 
				return Swift::JID(user_, getLocalJID().getDomain());
 
			}
 

	
 
			void handlePasswordValid();
 
			void handlePasswordInvalid(const std::string &error = "");
 

	
 
		private:
 
#if HAVE_SWIFTEN_3
 
			void handleElement(boost::shared_ptr<ToplevelElement>);
 
			void handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ToplevelElement>);
 
#else		
 
			void handleElement(boost::shared_ptr<Element>);
 
			void handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Element>);
 
#endif
 
			void handleStreamStart(const ProtocolHeader& header);
 
			void handleSessionFinished(const boost::optional<SessionError>&);
 

	
 
			void setInitialized();
 
			bool isInitialized() const { 
 
				return initialized; 
 
			}
 

	
 
			void handleTLSError() { }
 
			void handleTLSConnected() { tlsConnected = true; }
 

	
include/Swiften/Server/ServerSession.h
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/shared_ptr.hpp>
 

	
 
#include <Swiften/Elements/Stanza.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class ServerSession {
 
		public:
 
			virtual ~ServerSession();
 

	
 
			virtual const JID& getJID() const = 0;
 
			virtual int getPriority() const = 0;
 

	
 
			virtual void sendStanza(boost::shared_ptr<Stanza>) = 0;
 
			virtual void sendStanza(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Stanza>) = 0;
 
	};
 
}
include/Swiften/Server/ServerStanzaChannel.cpp
Show inline comments
 
@@ -12,172 +12,172 @@
 

	
 
namespace Swift {
 

	
 
namespace {
 
// 	struct PriorityLessThan {
 
// 		bool operator()(const ServerSession* s1, const ServerSession* s2) const {
 
// 			return s1->getPriority() < s2->getPriority();
 
// 		}
 
// 	};
 

	
 
	struct HasJID {
 
		HasJID(const JID& jid) : jid(jid) {}
 
		bool operator()(const boost::shared_ptr<ServerFromClientSession> session) const {
 
		bool operator()(const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> session) const {
 
			return session->getRemoteJID().equals(jid, JID::WithResource);
 
		}
 
		JID jid;
 
	};
 
}
 

	
 
void ServerStanzaChannel::addSession(boost::shared_ptr<ServerFromClientSession> session) {
 
void ServerStanzaChannel::addSession(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> session) {
 
	sessions[session->getRemoteJID().toBare().toString()].push_back(session);
 
	session->onSessionFinished.connect(boost::bind(&ServerStanzaChannel::handleSessionFinished, this, _1, session));
 
	session->onElementReceived.connect(boost::bind(&ServerStanzaChannel::handleElement, this, _1, session));
 
	session->onDataRead.connect(boost::bind(&ServerStanzaChannel::handleDataRead, this, _1, session));
 
}
 

	
 
void ServerStanzaChannel::removeSession(boost::shared_ptr<ServerFromClientSession> session) {
 
void ServerStanzaChannel::removeSession(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> session) {
 
	session->onSessionFinished.disconnect(boost::bind(&ServerStanzaChannel::handleSessionFinished, this, _1, session));
 
	session->onElementReceived.disconnect(boost::bind(&ServerStanzaChannel::handleElement, this, _1, session));
 
	session->onDataRead.disconnect(boost::bind(&ServerStanzaChannel::handleDataRead, this, _1, session));
 
	std::list<boost::shared_ptr<ServerFromClientSession> > &lst = sessions[session->getRemoteJID().toBare().toString()];
 
	std::list<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> > &lst = sessions[session->getRemoteJID().toBare().toString()];
 
	lst.erase(std::remove(lst.begin(), lst.end(), session), lst.end());
 
}
 

	
 
void ServerStanzaChannel::sendIQ(boost::shared_ptr<IQ> iq) {
 
void ServerStanzaChannel::sendIQ(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<IQ> iq) {
 
	send(iq);
 
}
 

	
 
void ServerStanzaChannel::sendMessage(boost::shared_ptr<Message> message) {
 
void ServerStanzaChannel::sendMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Message> message) {
 
	send(message);
 
}
 

	
 
void ServerStanzaChannel::sendPresence(boost::shared_ptr<Presence> presence) {
 
void ServerStanzaChannel::sendPresence(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Presence> presence) {
 
	send(presence);
 
}
 

	
 
void ServerStanzaChannel::handleDataRead(const SafeByteArray &data, const boost::shared_ptr<ServerFromClientSession> &session) {
 
void ServerStanzaChannel::handleDataRead(const SafeByteArray &data, const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> &session) {
 
	if (safeByteArrayToString(data).find("</stream:stream>") != std::string::npos) {
 
		Swift::Presence::ref presence = Swift::Presence::create();
 
		presence->setFrom(session->getRemoteJID());
 
		presence->setType(Swift::Presence::Unavailable);
 
		onPresenceReceived(presence);
 
	}
 
}
 
#if HAVE_SWIFTEN_3
 
void ServerStanzaChannel::finishSession(const JID& to, boost::shared_ptr<ToplevelElement> element, bool last) {
 
void ServerStanzaChannel::finishSession(const JID& to, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ToplevelElement> element, bool last) {
 
#else
 
void ServerStanzaChannel::finishSession(const JID& to, boost::shared_ptr<Element> element, bool last) {
 
void ServerStanzaChannel::finishSession(const JID& to, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Element> element, bool last) {
 
#endif
 
	std::vector<boost::shared_ptr<ServerFromClientSession> > candidateSessions;
 
	for (std::list<boost::shared_ptr<ServerFromClientSession> >::const_iterator i = sessions[to.toBare().toString()].begin(); i != sessions[to.toBare().toString()].end(); ++i) {
 
	std::vector<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> > candidateSessions;
 
	for (std::list<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> >::const_iterator i = sessions[to.toBare().toString()].begin(); i != sessions[to.toBare().toString()].end(); ++i) {
 
		candidateSessions.push_back(*i);
 
	}
 

	
 
	for (std::vector<boost::shared_ptr<ServerFromClientSession> >::const_iterator i = candidateSessions.begin(); i != candidateSessions.end(); ++i) {
 
	for (std::vector<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> >::const_iterator i = candidateSessions.begin(); i != candidateSessions.end(); ++i) {
 
		removeSession(*i);
 
		if (element) {
 
			(*i)->sendElement(element);
 
		}
 

	
 
		if (last && (*i)->getRemoteJID().isValid()) {
 
			Swift::Presence::ref presence = Swift::Presence::create();
 
			presence->setFrom((*i)->getRemoteJID());
 
			presence->setType(Swift::Presence::Unavailable);
 
			onPresenceReceived(presence);
 
		}
 

	
 
		(*i)->finishSession();
 
// 		std::cout << "FINISH SESSION " << sessions[to.toBare().toString()].size() << "\n";
 
		if (last) {
 
			break;
 
		}
 
	}
 
}
 

	
 
std::string ServerStanzaChannel::getNewIQID() {
 
	return idGenerator.generateID();
 
}
 

	
 
void ServerStanzaChannel::send(boost::shared_ptr<Stanza> stanza) {
 
void ServerStanzaChannel::send(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Stanza> stanza) {
 
	JID to = stanza->getTo();
 
	assert(to.isValid());
 

	
 
	if (!stanza->getFrom().isValid()) {
 
		stanza->setFrom(m_jid);
 
	}
 

	
 
	// For a full JID, first try to route to a session with the full JID
 
	if (!to.isBare()) {
 
		std::list<boost::shared_ptr<ServerFromClientSession> >::const_iterator i = std::find_if(sessions[stanza->getTo().toBare().toString()].begin(), sessions[stanza->getTo().toBare().toString()].end(), HasJID(to));
 
		std::list<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> >::const_iterator i = std::find_if(sessions[stanza->getTo().toBare().toString()].begin(), sessions[stanza->getTo().toBare().toString()].end(), HasJID(to));
 
		if (i != sessions[stanza->getTo().toBare().toString()].end()) {
 
			(*i)->sendElement(stanza);
 
			return;
 
		}
 
	}
 

	
 
	// Look for candidate sessions
 
	to = to.toBare();
 
	std::vector<boost::shared_ptr<ServerFromClientSession> > candidateSessions;
 
	for (std::list<boost::shared_ptr<ServerFromClientSession> >::const_iterator i = sessions[stanza->getTo().toBare().toString()].begin(); i != sessions[stanza->getTo().toBare().toString()].end(); ++i) {
 
	std::vector<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> > candidateSessions;
 
	for (std::list<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> >::const_iterator i = sessions[stanza->getTo().toBare().toString()].begin(); i != sessions[stanza->getTo().toBare().toString()].end(); ++i) {
 
		if ((*i)->getRemoteJID().equals(to, JID::WithoutResource)) {
 
			candidateSessions.push_back(*i);
 
			(*i)->sendElement(stanza);
 
		}
 
	}
 
	if (candidateSessions.empty()) {
 
		return;
 
	}
 

	
 
	// Find the session with the highest priority
 
// 	std::vector<ServerSession*>::const_iterator i = std::max_element(sessions.begin(), sessions.end(), PriorityLessThan());
 
// 	(*i)->sendStanza(stanza);
 
	return;
 
}
 

	
 
void ServerStanzaChannel::handleSessionFinished(const boost::optional<Session::SessionError>&, const boost::shared_ptr<ServerFromClientSession>& session) {
 
void ServerStanzaChannel::handleSessionFinished(const boost::optional<Session::SessionError>&, const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession>& session) {
 
	removeSession(session);
 

	
 
// 	if (!session->initiatedFinish()) {
 
		Swift::Presence::ref presence = Swift::Presence::create();
 
		presence->setFrom(session->getRemoteJID());
 
		presence->setType(Swift::Presence::Unavailable);
 
		onPresenceReceived(presence);
 
// 	}
 
}
 

	
 
void ServerStanzaChannel::handleElement(boost::shared_ptr<Element> element, const boost::shared_ptr<ServerFromClientSession>& session) {
 
	boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element);
 
void ServerStanzaChannel::handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Element> element, const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession>& session) {
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Stanza> stanza = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Stanza>(element);
 
	if (!stanza) {
 
		return;
 
	}
 

	
 
	stanza->setFrom(session->getRemoteJID());
 

	
 
	if (!stanza->getFrom().isValid())
 
		return;
 
	
 

	
 
	boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(stanza);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Message> message = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Message>(stanza);
 
	if (message) {
 
		onMessageReceived(message);
 
		return;
 
	}
 

	
 
	boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(stanza);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Presence> presence = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Presence>(stanza);
 
	if (presence) {
 
		onPresenceReceived(presence);
 
		return;
 
	}
 

	
 
	boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<IQ> iq = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<IQ>(stanza);
 
	if (iq) {
 
		onIQReceived(iq);
 
		return;
 
	}
 
}
 

	
 
void ServerStanzaChannel::handleSessionInitialized() {
 
	onAvailableChanged(true);
 
}
 

	
 
}
include/Swiften/Server/ServerStanzaChannel.h
Show inline comments
 
@@ -16,51 +16,51 @@
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/TLS/Certificate.h"
 
#include <Swiften/Version.h>
 
#define HAVE_SWIFTEN_3  (SWIFTEN_VERSION >= 0x030000)
 

	
 
namespace Swift {
 
	class Error;
 
	class ServerStanzaChannel : public StanzaChannel {
 
		public:
 
			ServerStanzaChannel(const JID &selfJID) : StanzaChannel() {
 
				m_jid = selfJID;
 
			}
 
			void addSession(boost::shared_ptr<ServerFromClientSession> session);
 
			void removeSession(boost::shared_ptr<ServerFromClientSession> session);
 
			void addSession(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> session);
 
			void removeSession(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> session);
 

	
 
			void sendIQ(boost::shared_ptr<IQ> iq);
 
			void sendMessage(boost::shared_ptr<Message> message);
 
			void sendPresence(boost::shared_ptr<Presence> presence);
 
			void sendIQ(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<IQ> iq);
 
			void sendMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Message> message);
 
			void sendPresence(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Presence> presence);
 
#if HAVE_SWIFTEN_3
 
			void finishSession(const JID& to, boost::shared_ptr<ToplevelElement> element, bool last = false);
 
			void finishSession(const JID& to, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ToplevelElement> element, bool last = false);
 
#else
 
			void finishSession(const JID& to, boost::shared_ptr<Element> element, bool last = false);
 
			void finishSession(const JID& to, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Element> element, bool last = false);
 
#endif
 
			bool getStreamManagementEnabled() const {
 
				return false;
 
			}
 
	
 
			bool isAvailable() const {
 
				return true;
 
			}
 
			
 
			std::vector<Certificate::ref> getPeerCertificateChain() const {
 
				return std::vector<Certificate::ref>();
 
			}
 

	
 
		private:
 
			std::string getNewIQID();
 
			void send(boost::shared_ptr<Stanza> stanza);
 
			void handleSessionFinished(const boost::optional<Session::SessionError>&, const boost::shared_ptr<ServerFromClientSession> &session);
 
			void handleElement(boost::shared_ptr<Element> element, const boost::shared_ptr<ServerFromClientSession> &session);
 
			void handleDataRead(const SafeByteArray &data, const boost::shared_ptr<ServerFromClientSession> &session);
 
			void send(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Stanza> stanza);
 
			void handleSessionFinished(const boost::optional<Session::SessionError>&, const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> &session);
 
			void handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Element> element, const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> &session);
 
			void handleDataRead(const SafeByteArray &data, const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> &session);
 
			void handleSessionInitialized();
 

	
 
		private:
 
			JID m_jid;
 
			IDGenerator idGenerator;
 
			// [JID][resources][ServerFromClientSession]
 
			std::map<std::string, std::list<boost::shared_ptr<ServerFromClientSession> > > sessions;
 
			std::map<std::string, std::list<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<ServerFromClientSession> > > sessions;
 
	};
 

	
 
}
include/Swiften/Server/ServerStanzaRouter.cpp
Show inline comments
 
@@ -23,25 +23,25 @@ namespace {
 
	struct HasJID {
 
		HasJID(const JID& jid) : jid(jid) {}
 
		bool operator()(const ServerSession* session) const {
 
			return session->getJID().equals(jid, JID::WithResource);
 
		}
 
		JID jid;
 
	};
 
}
 

	
 
ServerStanzaRouter::ServerStanzaRouter() {
 
}
 

	
 
bool ServerStanzaRouter::routeStanza(boost::shared_ptr<Stanza> stanza) {
 
bool ServerStanzaRouter::routeStanza(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Stanza> stanza) {
 
	JID to = stanza->getTo();
 
	assert(to.isValid());
 

	
 
	// For a full JID, first try to route to a session with the full JID
 
	if (!to.isBare()) {
 
		std::vector<ServerSession*>::const_iterator i = std::find_if(clientSessions_.begin(), clientSessions_.end(), HasJID(to));
 
		if (i != clientSessions_.end()) {
 
			(*i)->sendStanza(stanza);
 
			return true;
 
		}
 
	}
 

	
include/Swiften/Server/ServerStanzaRouter.h
Show inline comments
 
@@ -3,28 +3,30 @@
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/shared_ptr.hpp>
 
#include <map>
 

	
 
#include <Swiften/JID/JID.h>
 
#include <Swiften/Elements/Stanza.h>
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class ServerSession;
 

	
 
	class ServerStanzaRouter {
 
		public:
 
			ServerStanzaRouter();
 

	
 
			bool routeStanza(boost::shared_ptr<Stanza>);
 
			bool routeStanza(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Stanza>);
 

	
 
			void addClientSession(ServerSession*);
 
			void removeClientSession(ServerSession*);
 

	
 
		private:
 
			std::vector<ServerSession*> clientSessions_;
 
	};
 
}
include/Swiften/StreamStack/TLSServerLayer.cpp
Show inline comments
 
@@ -36,17 +36,17 @@ void TLSServerLayer::writeData(const SafeByteArray& data) {
 
void TLSServerLayer::handleDataRead(const SafeByteArray& data) {
 
	context->handleDataFromNetwork(data);
 
}
 

	
 
bool TLSServerLayer::setServerCertificate(CertificateWithKey::ref certificate) {
 
	return context->setServerCertificate(certificate);
 
}
 

	
 
Certificate::ref TLSServerLayer::getPeerCertificate() const {
 
	return context->getPeerCertificate();
 
}
 

	
 
boost::shared_ptr<CertificateVerificationError> TLSServerLayer::getPeerCertificateVerificationError() const {
 
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError> TLSServerLayer::getPeerCertificateVerificationError() const {
 
	return context->getPeerCertificateVerificationError();
 
}
 

	
 
}
include/Swiften/StreamStack/TLSServerLayer.h
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#include "Swiften/Base/boost_bsignals.h"
 
#include <boost/signals.hpp>
 

	
 
#include "Swiften/Base/SafeByteArray.h"
 
#include "Swiften/StreamStack/StreamLayer.h"
 
#include "Swiften/TLS/Certificate.h"
 
#include <Swiften/TLS/CertificateWithKey.h>
 
#include "Swiften/TLS/CertificateVerificationError.h"
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Swift {
 
	class TLSServerContext;
 
	class TLSServerContextFactory;
 
	class PKCS12Certificate;
 

	
 
	class TLSServerLayer : public StreamLayer {
 
		public:
 
			TLSServerLayer(TLSServerContextFactory*);
 
			~TLSServerLayer();
 

	
 
			void connect();
 
			bool setServerCertificate(CertificateWithKey::ref cert);
 

	
 
			Certificate::ref getPeerCertificate() const;
 
			boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
 

	
 
			void writeData(const SafeByteArray& data);
 
			void handleDataRead(const SafeByteArray& data);
 

	
 
			TLSServerContext* getContext() const {
 
				return context;
 
			}
 

	
 
		public:
 
			boost::signal<void ()> onError;
 
			boost::signal<void ()> onConnected;
 

	
include/Swiften/SwiftenCompat.h
Show inline comments
 
new file 100644
 
/*
 
 * Swift compatibility
 
 * 
 
 * Copyright (c) 2016, Vladimir Matena <vlada.matena@gmail.com>
 
 * 
 
 * This program is free software; you can redistribute it and/or
 
 * modify it under the terms of the GNU General Public License
 
 * as published by the Free Software Foundation; either version 2
 
 * of the License, or (at your option) any later version.
 
 * 
 
 * This program is distributed in the hope that it will be useful,
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 * 
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
 

	
 
#include <Swiften/Version.h>
 

	
 
/*
 
 * Define macros for Swiften compatible shared pointer and signal namespaces.
 
 *
 
 * Using these it is possible to declare shared pointers and signals like this:
 
 *
 
 * SWIFTEN_SIGNAL_NAMESPACE::signal signal;
 
 * SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Type> ptr;
 
 *
 
 * These are guaranteed to be the same implementation as Swift uses internally,
 
 * thus can be used when passign/retrieveing data from/to swiften.
 
 *
 
 * This is due to Swift 4 moved from boost::shared_ptr to SWIFTEN_SHRPTR_NAMESPACE::shared_ptr
 
 * and from boost::signals to boost::signals2 .
 
 */
 

	
 
#if (SWIFTEN_VERSION >= 0x040000)
 
#define SWIFTEN_SHRPTR_NAMESPACE std
 
#define SWIFTEN_SIGNAL_NAMESPACE boost::signals2
 
#else
 
#define SWIFTEN_SHRPTR_NAMESPACE boost
 
#define SWIFTEN_SIGNAL_NAMESPACE boost::signals
 
#endif
include/Swiften/TLS/OpenSSL/OpenSSLServerContext.cpp
Show inline comments
 
@@ -172,82 +172,82 @@ void OpenSSLServerContext::sendPendingDataToApplication() {
 
		onDataForApplication(data);
 
		data.resize(SSL_READ_BUFFERSIZE);
 
		ret = SSL_read(handle_, vecptr(data), data.size());
 
	}
 
	if (ret < 0 && SSL_get_error(handle_, ret) != SSL_ERROR_WANT_READ) {
 
		state_ = Error;
 
// 		std::cout << "AAAAAAAA 3\n";
 
		onError();
 
	}
 
}
 

	
 
bool OpenSSLServerContext::setServerCertificate(CertificateWithKey::ref certref) {
 
	boost::shared_ptr<PKCS12Certificate> certificate = boost::dynamic_pointer_cast<PKCS12Certificate>(certref);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<PKCS12Certificate> certificate = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<PKCS12Certificate>(certref);
 
	if (certificate->isNull()) {
 
		LOG4CXX_ERROR(logger, "TLS WILL NOT WORK: Certificate can't be loaded.");
 
		return false;
 
	}
 

	
 
	// Create a PKCS12 structure
 
	BIO* bio = BIO_new(BIO_s_mem());
 
	BIO_write(bio, vecptr(certificate->getData()), certificate->getData().size());
 
	boost::shared_ptr<PKCS12> pkcs12(d2i_PKCS12_bio(bio, NULL), PKCS12_free);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<PKCS12> pkcs12(d2i_PKCS12_bio(bio, NULL), PKCS12_free);
 
	BIO_free(bio);
 
	if (!pkcs12) {
 
		LOG4CXX_ERROR(logger, "TLS WILL NOT WORK: Certificate is not in PKCS#12 format.");
 
		return false;
 
	}
 

	
 
	// Parse PKCS12
 
	X509 *certPtr = 0;
 
	EVP_PKEY* privateKeyPtr = 0;
 
	STACK_OF(X509)* caCertsPtr = 0;
 
	int result = PKCS12_parse(pkcs12.get(), reinterpret_cast<const char*>(vecptr(certificate->getPassword())), &privateKeyPtr, &certPtr, &caCertsPtr);
 
	if (result != 1) { 
 
		LOG4CXX_ERROR(logger, "TLS WILL NOT WORK: Certificate is not in PKCS#12 format.");
 
		return false;
 
	}
 
	boost::shared_ptr<X509> cert(certPtr, X509_free);
 
	boost::shared_ptr<EVP_PKEY> privateKey(privateKeyPtr, EVP_PKEY_free);
 
	boost::shared_ptr<STACK_OF(X509)> caCerts(caCertsPtr, freeX509Stack);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<X509> cert(certPtr, X509_free);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<EVP_PKEY> privateKey(privateKeyPtr, EVP_PKEY_free);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<STACK_OF(X509)> caCerts(caCertsPtr, freeX509Stack);
 

	
 
	// Use the key & certificates
 
	if (SSL_CTX_use_certificate(context_, cert.get()) != 1) {
 
		LOG4CXX_ERROR(logger, "TLS WILL NOT WORK: Can't use this certificate");
 
		return false;
 
	}
 
	if (SSL_CTX_use_PrivateKey(context_, privateKey.get()) != 1) {
 
		LOG4CXX_ERROR(logger, "TLS WILL NOT WORK: Can't use this private key");
 
		return false;
 
	}
 
	return true;
 
}
 

	
 
Certificate::ref OpenSSLServerContext::getPeerCertificate() const {
 
	boost::shared_ptr<X509> x509Cert(SSL_get_peer_certificate(handle_), X509_free);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<X509> x509Cert(SSL_get_peer_certificate(handle_), X509_free);
 
	if (x509Cert) {
 
		return Certificate::ref(new OpenSSLCertificate(x509Cert));
 
	}
 
	else {
 
		return Certificate::ref();
 
	}
 
}
 

	
 
boost::shared_ptr<CertificateVerificationError> OpenSSLServerContext::getPeerCertificateVerificationError() const {
 
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError> OpenSSLServerContext::getPeerCertificateVerificationError() const {
 
	int verifyResult = SSL_get_verify_result(handle_);
 
	if (verifyResult != X509_V_OK) {
 
		return boost::shared_ptr<CertificateVerificationError>(new CertificateVerificationError(getVerificationErrorTypeForResult(verifyResult)));
 
		return SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError>(new CertificateVerificationError(getVerificationErrorTypeForResult(verifyResult)));
 
	}
 
	else {
 
		return boost::shared_ptr<CertificateVerificationError>();
 
		return SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError>();
 
	}
 
}
 

	
 
ByteArray OpenSSLServerContext::getFinishMessage() const {
 
	ByteArray data;
 
	data.resize(MAX_FINISHED_SIZE);
 
	size_t size = SSL_get_finished(handle_, vecptr(data), data.size());
 
	data.resize(size);
 
	return data;
 
}
 

	
 
CertificateVerificationError::Type OpenSSLServerContext::getVerificationErrorTypeForResult(int result) {
include/Swiften/TLS/OpenSSL/OpenSSLServerContext.h
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include <openssl/ssl.h>
 
#include "Swiften/Base/boost_bsignals.h"
 
#include <boost/noncopyable.hpp>
 

	
 
#include "Swiften/TLS/TLSServerContext.h"
 
#include "Swiften/Base/ByteArray.h"
 
#include "Swiften/SwiftenCompat.h"
 
#include <Swiften/TLS/CertificateWithKey.h>
 

	
 
namespace Swift {
 
	class PKCS12Certificate;
 

	
 
	class OpenSSLServerContext : public TLSServerContext, boost::noncopyable {
 
		public:
 
			OpenSSLServerContext();
 
			~OpenSSLServerContext();
 

	
 
			void connect();
 
			bool setServerCertificate(CertificateWithKey::ref cert);
 

	
 
			void handleDataFromNetwork(const SafeByteArray&);
 
			void handleDataFromApplication(const SafeByteArray&);
 

	
 
			Certificate::ref getPeerCertificate() const;
 
			boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
 

	
 
			virtual ByteArray getFinishMessage() const;
 

	
 
		private:
 
			static void ensureLibraryInitialized();	
 

	
 
			static CertificateVerificationError::Type getVerificationErrorTypeForResult(int);
 

	
 
			void doConnect();
 
			void sendPendingDataToNetwork();
 
			void sendPendingDataToApplication();
 

	
include/Swiften/TLS/Schannel/SchannelServerContext.cpp
Show inline comments
 
@@ -511,25 +511,25 @@ void SchannelServerContext::encryptAndSendData(const SafeByteArray& data)
 
		}
 

	
 
		sendDataOnNetwork(&sendBuffer[0], outBuffers[0].cbBuffer + outBuffers[1].cbBuffer + outBuffers[2].cbBuffer);
 
		bytesSent += bytesToSend;
 

	
 
	} while (bytesSent < data.size());
 
}
 

	
 
//------------------------------------------------------------------------
 

	
 
bool SchannelServerContext::setServerCertificate(CertificateWithKey::ref certificate)
 
{
 
	boost::shared_ptr<CAPICertificate> capiCertificate = boost::dynamic_pointer_cast<CAPICertificate>(certificate);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CAPICertificate> capiCertificate = std::dynamic_pointer_cast<CAPICertificate>(certificate);
 
	if (!capiCertificate || capiCertificate->isNull()) {
 
		return false;
 
	}
 

	
 
	// We assume that the Certificate Store Name/Certificate Name
 
	// are valid at this point
 
	m_cert_store_name = capiCertificate->getCertStoreName();
 
	m_cert_name = capiCertificate->getCertName();
 
	return true;
 
}
 

	
 
//------------------------------------------------------------------------
 
@@ -542,25 +542,25 @@ Certificate::ref SchannelServerContext::getPeerCertificate() const
 
	SECURITY_STATUS status = QueryContextAttributes(m_ctxtHandle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, pServerCert.Reset());
 
	if (status != SEC_E_OK)
 
		return pCertificate;
 

	
 
	pCertificate.reset( new SchannelCertificate(pServerCert) );
 
	return pCertificate;
 
}
 

	
 
//------------------------------------------------------------------------
 

	
 
CertificateVerificationError::ref SchannelServerContext::getPeerCertificateVerificationError() const 
 
{
 
	boost::shared_ptr<CertificateVerificationError> pCertError;
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError> pCertError;
 

	
 
	if (m_state == Error)
 
		pCertError.reset( new CertificateVerificationError(m_verificationError) );
 
	
 
	return pCertError;
 
}
 

	
 
//------------------------------------------------------------------------
 

	
 
ByteArray SchannelServerContext::getFinishMessage() const
 
{
 
	// TODO: Implement
include/Swiften/TLS/Schannel/SchannelServerContext.h
Show inline comments
 
/*
 
 * Copyright (c) 2011 Soren Dreijer
 
 * Licensed under the simplified BSD license.
 
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include "Swiften/Base/boost_bsignals.h"
 

	
 
#include "Swiften/TLS/TLSServerContext.h"
 
#include "Swiften/TLS/Schannel/SchannelUtil.h"
 
#include <Swiften/TLS/CertificateWithKey.h>
 
#include "Swiften/Base/ByteArray.h"
 

	
 
#define SECURITY_WIN32
 
#include <Windows.h>
 
#include <Schannel.h>
 
#include <security.h>
 
#include <schnlsp.h>
 

	
 
#include <boost/noncopyable.hpp>
 

	
 
namespace Swift 
 
{	
 
	class SchannelServerContext : public TLSServerContext, boost::noncopyable 
 
	{
 
	public:
 
		typedef boost::shared_ptr<SchannelServerContext> sp_t;
 
		typedef SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<SchannelServerContext> sp_t;
 

	
 
	public:
 
		SchannelServerContext();
 

	
 
		~SchannelServerContext();
 

	
 
		//
 
		// TLSContext
 
		//
 
		virtual void	connect();
 
		virtual bool	setServerCertificate(CertificateWithKey::ref cert);
 

	
include/Swiften/TLS/SecureTransport/SecureTransportServerContext.h
Show inline comments
 
@@ -29,30 +29,30 @@ class SecureTransportServerContext : public TLSServerContext {
 

	
 
		virtual ByteArray getFinishMessage() const;
 
	
 
	private:
 
		static OSStatus SSLSocketReadCallback(SSLConnectionRef connection, void *data, size_t *dataLength); 
 
		static OSStatus SSLSocketWriteCallback(SSLConnectionRef connection, const void *data, size_t *dataLength);
 

	
 
	private:
 
		enum State { None, Handshake, HandshakeDone, Error};
 
		static std::string stateToString(State state);
 
		void setState(State newState);
 

	
 
		static boost::shared_ptr<TLSError> nativeToTLSError(OSStatus error);
 
		boost::shared_ptr<CertificateVerificationError> CSSMErrorToVerificationError(OSStatus resultCode);
 
		static SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<TLSError> nativeToTLSError(OSStatus error);
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError> CSSMErrorToVerificationError(OSStatus resultCode);
 

	
 
		void processHandshake();
 
		void verifyServerCertificate();
 

	
 
		void fatalError(boost::shared_ptr<TLSError> error, boost::shared_ptr<CertificateVerificationError> certificateError);
 
		void fatalError(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<TLSError> error, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError> certificateError);
 

	
 
	private:
 
		boost::shared_ptr<SSLContext> sslContext_;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<SSLContext> sslContext_;
 
		SafeByteArray readingBuffer_;
 
		State state_;
 
		CertificateVerificationError::ref verificationError_;
 
		CertificateWithKey::ref clientCertificate_;
 
		bool checkCertificateRevocation_;
 
};
 

	
 
}
include/Swiften/TLS/SecureTransport/SecureTransportServerContext.mm
Show inline comments
 
@@ -30,25 +30,25 @@ T bridge_cast(S source) {
 
#pragma clang diagnostic push
 
#pragma clang diagnostic ignored "-Wold-style-cast"
 
	return (__bridge T)(source);
 
#pragma clang diagnostic pop
 
}
 

	
 
namespace Swift {
 

	
 
namespace {
 

	
 
	
 
CFArrayRef CreateClientCertificateChainAsCFArrayRef(CertificateWithKey::ref key) {
 
	boost::shared_ptr<PKCS12Certificate> pkcs12 = boost::dynamic_pointer_cast<PKCS12Certificate>(key);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<PKCS12Certificate> pkcs12 = std::dynamic_pointer_cast<PKCS12Certificate>(key);
 
	if (!key) {
 
		return NULL;
 
	}
 

	
 
	SafeByteArray safePassword = pkcs12->getPassword();
 
	CFIndex passwordSize = 0;
 
	try {
 
		passwordSize = boost::numeric_cast<CFIndex>(safePassword.size());
 
	} catch (...) {
 
		return NULL;
 
	}
 

	
 
@@ -95,25 +95,25 @@ CFArrayRef CreateClientCertificateChainAsCFArrayRef(CertificateWithKey::ref key)
 
		CFArrayAppendValue(certChain, nsItems[0][@"identity"]);
 

	
 
		for (CFIndex index = 0; index < CFArrayGetCount(bridge_cast<CFArrayRef>(nsItems[0][@"chain"])); index++) {
 
			CFArrayAppendValue(certChain, CFArrayGetValueAtIndex(bridge_cast<CFArrayRef>(nsItems[0][@"chain"]), index));
 
		}
 
	}
 
	return certChain;
 
}
 

	
 
}
 

	
 
SecureTransportContext::SecureTransportServerContext(bool checkCertificateRevocation) : state_(None), checkCertificateRevocation_(checkCertificateRevocation) {
 
	sslContext_ = boost::shared_ptr<SSLContext>(SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType), CFRelease);
 
	sslContext_ = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<SSLContext>(SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType), CFRelease);
 

	
 
	OSStatus error = noErr;
 
	// set IO callbacks
 
	error = SSLSetIOFuncs(sslContext_.get(), &SecureTransportContext::SSLSocketReadCallback, &SecureTransportContext::SSLSocketWriteCallback);
 
	if (error != noErr) {
 
		SWIFT_LOG(error) << "Unable to set IO functions to SSL context." << std::endl;
 
		sslContext_.reset();
 
	}
 

	
 
	error = SSLSetConnection(sslContext_.get(), this);
 
	if (error != noErr) {
 
		SWIFT_LOG(error) << "Unable to set connection to SSL context." << std::endl;
 
@@ -154,25 +154,25 @@ std::string SecureTransportContext::stateToString(State state) {
 
}
 

	
 
void SecureTransportServerContext::setState(State newState) {
 
	SWIFT_LOG(debug) << "Switch state from " << stateToString(state_) << " to " << stateToString(newState) << "." << std::endl;
 
	state_ = newState;
 
}
 

	
 
void SecureTransportServerContext::connect() {
 
	SWIFT_LOG_ASSERT(state_ == None, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
 
	if (clientCertificate_) {
 
		CFArrayRef certs = CreateClientCertificateChainAsCFArrayRef(clientCertificate_);
 
		if (certs) {
 
			boost::shared_ptr<CFArray> certRefs(certs, CFRelease);
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CFArray> certRefs(certs, CFRelease);
 
			OSStatus result = SSLSetCertificate(sslContext_.get(), certRefs.get());
 
			if (result != noErr) {
 
				SWIFT_LOG(error) << "SSLSetCertificate failed with error " << result << "." << std::endl;
 
			}
 
		}
 
	}
 
	processHandshake();
 
}
 

	
 
void SecureTransportServerContext::processHandshake() {
 
	SWIFT_LOG_ASSERT(state_ == None || state_ == Handshake, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
 
	OSStatus error = SSLHandshake(sslContext_.get());
 
@@ -182,108 +182,108 @@ void SecureTransportServerContext::processHandshake() {
 
	else if (error == noErr) {
 
		SWIFT_LOG(debug) << "TLS handshake successful." << std::endl;
 
		setState(HandshakeDone);
 
		onConnected();
 
	}
 
	else if (error == errSSLPeerAuthCompleted) {
 
		SWIFT_LOG(debug) << "Received server certificate. Start verification." << std::endl;
 
		setState(Handshake);
 
		verifyServerCertificate();
 
	}
 
	else {
 
		SWIFT_LOG(debug) << "Error returned from SSLHandshake call is " << error << "." << std::endl;
 
		fatalError(nativeToTLSError(error), boost::make_shared<CertificateVerificationError>());
 
		fatalError(nativeToTLSError(error), SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>());
 
	}
 
}
 

	
 

	
 
#pragma clang diagnostic push
 
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
 

	
 
void SecureTransportServerContext::verifyServerCertificate() {
 
	SecTrustRef trust = NULL;
 
	OSStatus error = SSLCopyPeerTrust(sslContext_.get(), &trust);
 
	if (error != noErr) {
 
		fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
 
		fatalError(SWIFTEN_SHRPTR_NAMESPACE::make_shared<TLSError>(), SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>());
 
		return;
 
	}
 
	boost::shared_ptr<SecTrust> trustRef = boost::shared_ptr<SecTrust>(trust, CFRelease);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<SecTrust> trustRef = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<SecTrust>(trust, CFRelease);
 

	
 
	if (checkCertificateRevocation_) {
 
		error = SecTrustSetOptions(trust, kSecTrustOptionRequireRevPerCert | kSecTrustOptionFetchIssuerFromNet);
 
		if (error != noErr) {
 
			fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
 
			fatalError(SWIFTEN_SHRPTR_NAMESPACE::make_shared<TLSError>(), SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>());
 
			return;
 
		}
 
	}
 

	
 
	SecTrustResultType trustResult;
 
	error = SecTrustEvaluate(trust, &trustResult);
 
	if (error != errSecSuccess) {
 
		fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
 
		fatalError(SWIFTEN_SHRPTR_NAMESPACE::make_shared<TLSError>(), SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>());
 
		return;
 
	}
 

	
 
	OSStatus cssmResult = 0;
 
	switch(trustResult) {
 
		case kSecTrustResultUnspecified:
 
			SWIFT_LOG(warning) << "Successful implicit validation. Result unspecified." << std::endl;
 
			break;
 
		case kSecTrustResultProceed:
 
			SWIFT_LOG(warning) << "Validation resulted in explicitly trusted." << std::endl;
 
			break;
 
		case kSecTrustResultRecoverableTrustFailure:
 
			SWIFT_LOG(warning) << "recoverable trust failure" << std::endl;
 
			error = SecTrustGetCssmResultCode(trust, &cssmResult);
 
			if (error == errSecSuccess) {
 
				verificationError_ = CSSMErrorToVerificationError(cssmResult);
 
				if (cssmResult == CSSMERR_TP_VERIFY_ACTION_FAILED || cssmResult == CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK ) {
 
					// Find out the reason why the verification failed.
 
					CFArrayRef certChain;
 
					CSSM_TP_APPLE_EVIDENCE_INFO* statusChain;
 
					error = SecTrustGetResult(trustRef.get(), &trustResult, &certChain, &statusChain);
 
					if (error == errSecSuccess) {
 
						boost::shared_ptr<CFArray> certChainRef = boost::shared_ptr<CFArray>(certChain, CFRelease);
 
						SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CFArray> certChainRef = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CFArray>(certChain, CFRelease);
 
						for (CFIndex index = 0; index < CFArrayGetCount(certChainRef.get()); index++) {
 
							for (CFIndex n = 0; n < statusChain[index].NumStatusCodes; n++) {
 
								// Even though Secure Transport reported CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK on the whole certificate
 
								// chain, the actual cause can be that a revocation check for a specific cert returned CSSMERR_TP_CERT_REVOKED.
 
								if (!verificationError_ || verificationError_->getType() == CertificateVerificationError::RevocationCheckFailed) {
 
									verificationError_ = CSSMErrorToVerificationError(statusChain[index].StatusCodes[n]);
 
								}
 
							}
 
						}
 
					}
 
					else {
 

	
 
					}
 
				}
 
			}
 
			else {
 
				verificationError_ = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
 
				verificationError_ = SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
 
			}
 
			break;
 
		case kSecTrustResultOtherError:
 
			verificationError_ = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
 
			verificationError_ = SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
 
			break;
 
		default:
 
			SWIFT_LOG(warning) << "Unhandled trust result " << trustResult << "." << std::endl;
 
			break;
 
	}
 
	
 
	if (verificationError_) {
 
		setState(Error);
 
		SSLClose(sslContext_.get());
 
		sslContext_.reset();
 
		onError(boost::make_shared<TLSError>());
 
		onError(SWIFTEN_SHRPTR_NAMESPACE::make_shared<TLSError>());
 
	}
 
	else {
 
		// proceed with handshake
 
		processHandshake();
 
	}
 
}
 

	
 
#pragma clang diagnostic pop
 

	
 
bool SecureTransportServerContext::setClientCertificate(CertificateWithKey::ref cert) {
 
	CFArrayRef nativeClientChain = CreateClientCertificateChainAsCFArrayRef(cert);
 
	if (nativeClientChain) {
 
@@ -317,25 +317,25 @@ void SecureTransportServerContext::handleDataFromNetwork(const SafeByteArray& da
 
			while (error == noErr) {
 
				applicationData.resize(readingBuffer_.size());
 
				error = SSLRead(sslContext_.get(), applicationData.data(), applicationData.size(), &bytesRead);
 
				if (error == noErr) {
 
					// Read successful.
 
				}
 
				else if (error == errSSLWouldBlock) {
 
					// Secure Transport does not want more data.
 
					break;
 
				}
 
				else {
 
					SWIFT_LOG(error) << "SSLRead failed with error " << error << ", read bytes: " << bytesRead << "." << std::endl;
 
					fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
 
					fatalError(SWIFTEN_SHRPTR_NAMESPACE::make_shared<TLSError>(), SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>());
 
					return;
 
				}
 

	
 
				if (bytesRead > 0) {
 
					applicationData.resize(bytesRead);
 
					onDataForApplication(applicationData);
 
				}
 
				else {
 
					break;	
 
				}
 
			}
 
			break;
 
@@ -349,45 +349,45 @@ void SecureTransportServerContext::handleDataFromNetwork(const SafeByteArray& da
 
void SecureTransportServerContext::handleDataFromApplication(const SafeByteArray& data) {
 
	size_t processedBytes = 0;
 
	OSStatus error = SSLWrite(sslContext_.get(), data.data(), data.size(), &processedBytes);
 
	switch(error) {
 
		case errSSLWouldBlock:
 
			SWIFT_LOG(warning) << "Unexpected because the write callback does not block." << std::endl;
 
			return;
 
		case errSSLClosedGraceful:
 
		case noErr:
 
			return;
 
		default:
 
			SWIFT_LOG(warning) << "SSLWrite returned error code: " << error << ", processed bytes: " << processedBytes << std::endl;
 
			fatalError(boost::make_shared<TLSError>(), boost::shared_ptr<CertificateVerificationError>());
 
			fatalError(SWIFTEN_SHRPTR_NAMESPACE::make_shared<TLSError>(), SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError>());
 
	}
 
}
 

	
 
std::vector<Certificate::ref> SecureTransportServerContext::getPeerCertificateChain() const {
 
	std::vector<Certificate::ref> peerCertificateChain;
 

	
 
	if (sslContext_) {
 
			typedef boost::remove_pointer<SecTrustRef>::type SecTrust;
 
			boost::shared_ptr<SecTrust> securityTrust;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<SecTrust> securityTrust;
 

	
 
			SecTrustRef secTrust = NULL;;
 
			OSStatus error = SSLCopyPeerTrust(sslContext_.get(), &secTrust);
 
			if (error == noErr) {
 
				securityTrust = boost::shared_ptr<SecTrust>(secTrust, CFRelease);
 
				securityTrust = SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<SecTrust>(secTrust, CFRelease);
 

	
 
				CFIndex chainSize = SecTrustGetCertificateCount(securityTrust.get());
 
				for (CFIndex n = 0; n < chainSize; n++) {
 
					SecCertificateRef certificate = SecTrustGetCertificateAtIndex(securityTrust.get(), n);
 
					if (certificate) {
 
						peerCertificateChain.push_back(boost::make_shared<SecureTransportCertificate>(certificate));
 
						peerCertificateChain.push_back(SWIFTEN_SHRPTR_NAMESPACE::make_shared<SecureTransportCertificate>(certificate));
 
					}
 
				}
 
			}
 
			else {
 
				SWIFT_LOG(warning) << "Failed to obtain peer trust structure; error = " << error << "." << std::endl;
 
			}
 
	}
 

	
 
	return peerCertificateChain;
 
}
 

	
 
CertificateVerificationError::ref SecureTransportServerContext::getPeerCertificateVerificationError() const {
 
@@ -427,74 +427,74 @@ OSStatus SecureTransportServerContext::SSLSocketReadCallback(SSLConnectionRef co
 
OSStatus SecureTransportServerContext::SSLSocketWriteCallback(SSLConnectionRef connection, const void *data, size_t *dataLength) {
 
	SecureTransportContext* context = const_cast<SecureTransportContext*>(static_cast<const SecureTransportContext*>(connection));
 
	OSStatus retValue = noErr;
 
	
 
	SafeByteArray safeData;
 
	safeData.resize(*dataLength);
 
	memcpy(safeData.data(), data, safeData.size());
 
	
 
	context->onDataForNetwork(safeData);
 
	return retValue;
 
}
 

	
 
boost::shared_ptr<TLSError> SecureTransportServerContext::nativeToTLSError(OSStatus /* error */) {
 
	boost::shared_ptr<TLSError> swiftenError;
 
	swiftenError = boost::make_shared<TLSError>();
 
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<TLSError> SecureTransportServerContext::nativeToTLSError(OSStatus /* error */) {
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<TLSError> swiftenError;
 
	swiftenError = SWIFTEN_SHRPTR_NAMESPACE::make_shared<TLSError>();
 
	return swiftenError;
 
}
 

	
 
boost::shared_ptr<CertificateVerificationError> SecureTransportServerContext::CSSMErrorToVerificationError(OSStatus resultCode) {
 
	boost::shared_ptr<CertificateVerificationError> error;
 
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError> SecureTransportServerContext::CSSMErrorToVerificationError(OSStatus resultCode) {
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError> error;
 
	switch(resultCode) {
 
		case CSSMERR_TP_NOT_TRUSTED:
 
			SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_NOT_TRUSTED" << std::endl;
 
			error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::Untrusted);
 
			error = SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>(CertificateVerificationError::Untrusted);
 
			break;
 
		case CSSMERR_TP_CERT_NOT_VALID_YET:
 
			SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_NOT_VALID_YET" << std::endl;
 
			error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::NotYetValid);
 
			error = SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>(CertificateVerificationError::NotYetValid);
 
			break;
 
		case CSSMERR_TP_CERT_EXPIRED:
 
			SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_EXPIRED" << std::endl;
 
			error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::Expired);
 
			error = SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>(CertificateVerificationError::Expired);
 
			break;
 
		case CSSMERR_TP_CERT_REVOKED:
 
			SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_REVOKED" << std::endl;
 
			error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::Revoked);
 
			error = SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>(CertificateVerificationError::Revoked);
 
			break;
 
		case CSSMERR_TP_VERIFY_ACTION_FAILED:
 
			SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_VERIFY_ACTION_FAILED" << std::endl;
 
			break;
 
		case CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK:
 
			SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK" << std::endl;
 
			if (checkCertificateRevocation_) {
 
				error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::RevocationCheckFailed);
 
				error = SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>(CertificateVerificationError::RevocationCheckFailed);
 
			}
 
			break;
 
		case CSSMERR_APPLETP_OCSP_UNAVAILABLE:
 
			SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_OCSP_UNAVAILABLE" << std::endl;
 
			if (checkCertificateRevocation_) {
 
				error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::RevocationCheckFailed);
 
				error = SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>(CertificateVerificationError::RevocationCheckFailed);
 
			}
 
			break;
 
		case CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE:
 
			SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE" << std::endl;
 
			error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidPurpose);
 
			error = SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidPurpose);
 
			break;
 
		default:
 
			SWIFT_LOG(warning) << "unhandled CSSM error: " << resultCode << ", CSSM_TP_BASE_TP_ERROR: " << CSSM_TP_BASE_TP_ERROR << std::endl;
 
			error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
 
			error = SWIFTEN_SHRPTR_NAMESPACE::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
 
			break;
 
	}
 
	return error;
 
}
 

	
 
void SecureTransportServerContext::fatalError(boost::shared_ptr<TLSError> error, boost::shared_ptr<CertificateVerificationError> certificateError) {
 
void SecureTransportServerContext::fatalError(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<TLSError> error, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<CertificateVerificationError> certificateError) {
 
	setState(Error);
 
	if (sslContext_) {
 
		SSLClose(sslContext_.get());
 
	}
 
	verificationError_ = certificateError;
 
	onError(error);
 
}
 

	
 
}
include/Swiften/TLS/TLSServerContext.h
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#pragma once
 

	
 
#include "Swiften/Base/boost_bsignals.h"
 
#include <boost/shared_ptr.hpp>
 
#include <boost/signals.hpp>
 

	
 
#include "Swiften/Base/SafeByteArray.h"
 
#include "Swiften/TLS/Certificate.h"
 
#include <Swiften/TLS/CertificateWithKey.h>
 
#include "Swiften/TLS/CertificateVerificationError.h"
 

	
 
namespace Swift {
 
	class PKCS12Certificate;
 

	
 
	class TLSServerContext {
 
		public:
 
			virtual ~TLSServerContext();
include/boost/dll/import.hpp
Show inline comments
 
@@ -21,207 +21,207 @@
 
#endif
 

	
 
/// \file boost/dll/import.hpp
 
/// \brief Contains all the boost::dll::import* reference counting
 
/// functions that hold a shared pointer to the instance of
 
/// boost::dll::shared_library.
 

	
 
namespace boost { namespace dll {
 

	
 
namespace detail {
 
    template <class T>
 
    class refc_function {
 
        boost::shared_ptr<shared_library>   lib_;
 
        SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<shared_library>   lib_;
 
        T*                                  func_ptr_;
 

	
 
    public:
 
        refc_function(const boost::shared_ptr<shared_library>& lib, T* func_ptr) BOOST_NOEXCEPT
 
        refc_function(const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<shared_library>& lib, T* func_ptr) BOOST_NOEXCEPT
 
            : lib_(lib)
 
            , func_ptr_(func_ptr)
 
        {}
 

	
 
        operator T*() const BOOST_NOEXCEPT {
 
            return func_ptr_;
 
        }
 
    };
 

	
 
    template <class T, class = void>
 
    struct import_type;
 

	
 
    template <class T>
 
    struct import_type<T, typename boost::disable_if<boost::is_object<T> >::type> {
 
        typedef boost::dll::detail::refc_function<T> base_type;
 
        typedef boost::function<
 
            typename boost::dll::detail::strip_calling_convention<T>::type
 
        > type;
 
    };
 

	
 
    template <class T>
 
    struct import_type<T, typename boost::enable_if<boost::is_object<T> >::type> {
 
        typedef boost::shared_ptr<T> base_type;
 
        typedef boost::shared_ptr<T> type;
 
        typedef SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<T> base_type;
 
        typedef SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<T> type;
 
    };
 
} // namespace detail
 

	
 

	
 
#ifndef BOOST_DLL_DOXYGEN
 
#   define BOOST_DLL_IMPORT_RESULT_TYPE inline typename boost::dll::detail::import_type<T>::type
 
#endif
 

	
 

	
 
/*!
 
* Returns boost::function<T> or boost::shared_ptr<T> that holds an imported function or variable
 
* Returns boost::function<T> or SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<T> that holds an imported function or variable
 
* from the loaded library and refcounts usage
 
* of the loaded shared library, so that it won't get unload until all copies of return value
 
* are not destroyed.
 
*
 
* This call will succeed if call to \forcedlink{shared_library}`::has(const char* )`
 
* function with the same symbol name returned `true`.
 
*
 
* For importing symbols by \b alias names use \forcedlink{import_alias} method.
 
*
 
* \b Examples:
 
* \code
 
* boost::function<int(int)> f = import<int(int)>(
 
*           boost::make_shared<shared_library>("test_lib.so"),
 
*           SWIFTEN_SHRPTR_NAMESPACE::make_shared<shared_library>("test_lib.so"),
 
*           "integer_func_name"
 
*       );
 
* \endcode
 
*
 
* \code
 
* boost::function<int(int)> f = import<int(int)>("test_lib.so", "integer_func_name");
 
* \endcode
 
*
 
* \code
 
* boost::shared_ptr<int> i = import<int>("test_lib.so", "integer_name");
 
* SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<int> i = import<int>("test_lib.so", "integer_name");
 
* \endcode
 
*
 
* \b Template \b parameter \b T:    Type of the symbol that we are going to import. Must be explicitly specified.
 
*
 
* \param lib Path or shared pointer to library to load function from.
 
* \param name Null-terminated C or C++ mangled name of the function to import. Can handle std::string, char*, const char*.
 
* \param mode An mode that will be used on library load.
 
*
 
* \return boost::function<T> if T is a function type, or boost::shared_ptr<T> if T is an object type.
 
* \return boost::function<T> if T is a function type, or SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<T> if T is an object type.
 
*
 
* \throw boost::system::system_error if symbol does not exist or if the DLL/DSO was not loaded.
 
*       Overload that accepts path also throws std::bad_alloc in case of insufficient memory.
 
*/
 
template <class T>
 
BOOST_DLL_IMPORT_RESULT_TYPE import(const boost::filesystem::path& lib, const char* name,
 
    load_mode::type mode = load_mode::default_mode);
 

	
 
//! \overload boost::dll::import(const boost::filesystem::path& lib, const char* name, load_mode::type mode)
 
template <class T>
 
BOOST_DLL_IMPORT_RESULT_TYPE import(const boost::filesystem::path& lib, const std::string& name,
 
    load_mode::type mode = load_mode::default_mode)
 
{
 
    return boost::dll::import<T>(
 
        boost::make_shared<boost::dll::shared_library>(lib, mode),
 
        SWIFTEN_SHRPTR_NAMESPACE::make_shared<boost::dll::shared_library>(lib, mode),
 
        name.c_str()
 
    );
 
}
 

	
 
//! \overload boost::dll::import(const boost::filesystem::path& lib, const char* name, load_mode::type mode)
 
template <class T>
 
BOOST_DLL_IMPORT_RESULT_TYPE import(const boost::shared_ptr<shared_library>& lib, const char* name) {
 
BOOST_DLL_IMPORT_RESULT_TYPE import(const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<shared_library>& lib, const char* name) {
 
    typedef typename boost::dll::detail::import_type<T>::base_type type;
 
    return type(lib, &lib->get<T>(name));
 
}
 

	
 
//! \overload boost::dll::import(const boost::filesystem::path& lib, const char* name, load_mode::type mode)
 
template <class T>
 
BOOST_DLL_IMPORT_RESULT_TYPE import(const boost::shared_ptr<shared_library>& lib, const std::string& name) {
 
BOOST_DLL_IMPORT_RESULT_TYPE import(const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<shared_library>& lib, const std::string& name) {
 
    return boost::dll::import<T>(lib, name.c_str());
 
}
 

	
 
template <class T>
 
BOOST_DLL_IMPORT_RESULT_TYPE import(const boost::filesystem::path& lib, const char* name, load_mode::type mode) {
 
    return boost::dll::import<T>(
 
        boost::make_shared<boost::dll::shared_library>(lib, mode),
 
        SWIFTEN_SHRPTR_NAMESPACE::make_shared<boost::dll::shared_library>(lib, mode),
 
        name
 
    );
 
}
 

	
 

	
 

	
 

	
 
/*!
 
* Returns boost::function<T> or boost::shared_ptr<T> that holds an imported function or variable
 
* Returns boost::function<T> or SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<T> that holds an imported function or variable
 
* from the loaded library and refcounts usage
 
* of the loaded shared library, so that it won't get unload until all copies of return value
 
* are not destroyed.
 
*
 
* This call will succeed if call to \forcedlink{shared_library}`::has(const char* )`
 
* function with the same symbol name returned `true`.
 
*
 
* For importing symbols by \b non \b alias names use \forcedlink{import} method.
 
*
 
* \b Examples:
 
* \code
 
* boost::function<int(int)> f = import_alias<int(int)>(
 
*           boost::make_shared<shared_library>("test_lib.so"),
 
*           SWIFTEN_SHRPTR_NAMESPACE::make_shared<shared_library>("test_lib.so"),
 
*           "integer_func_alias_name"
 
*       );
 
* \endcode
 
*
 
* \code
 
* boost::function<int(int)> f = import_alias<int(int)>("test_lib.so", "integer_func_alias_name");
 
* \endcode
 
*
 
* \code
 
* boost::shared_ptr<int> i = import_alias<int>("test_lib.so", "integer_alias_name");
 
* SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<int> i = import_alias<int>("test_lib.so", "integer_alias_name");
 
* \endcode
 
*
 
* \b Template \b parameter \b T:    Type of the symbol alias that we are going to import. Must be explicitly specified.
 
*
 
* \param lib Path or shared pointer to library to load function from.
 
* \param name Null-terminated C or C++ mangled name of the function or variable to import. Can handle std::string, char*, const char*.
 
* \param mode An mode that will be used on library load.
 
*
 
* \return boost::function<T> if T is a function type, or boost::shared_ptr<T> if T is an object type.
 
* \return boost::function<T> if T is a function type, or SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<T> if T is an object type.
 
*
 
* \throw boost::system::system_error if symbol does not exist or if the DLL/DSO was not loaded.
 
*       Overload that accepts path also throws std::bad_alloc in case of insufficient memory.
 
*/
 
template <class T>
 
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const boost::filesystem::path& lib, const char* name,
 
    load_mode::type mode = load_mode::default_mode);
 

	
 
//! \overload boost::dll::import_alias(const boost::filesystem::path& lib, const char* name, load_mode::type mode)
 
template <class T>
 
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const boost::filesystem::path& lib, const std::string& name,
 
    load_mode::type mode = load_mode::default_mode)
 
{
 
    return boost::dll::import_alias<T>(
 
        boost::make_shared<boost::dll::shared_library>(lib, mode),
 
        SWIFTEN_SHRPTR_NAMESPACE::make_shared<boost::dll::shared_library>(lib, mode),
 
        name.c_str()
 
    );
 
}
 

	
 
//! \overload boost::dll::import_alias(const boost::filesystem::path& lib, const char* name, load_mode::type mode)
 
template <class T>
 
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const boost::shared_ptr<shared_library>& lib, const std::string& name) {
 
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<shared_library>& lib, const std::string& name) {
 
    return boost::dll::import_alias<T>(lib, name.c_str());
 
}
 

	
 
//! \overload boost::dll::import_alias(const boost::filesystem::path& lib, const char* name, load_mode::type mode)
 
template <class T>
 
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const boost::shared_ptr<shared_library>& lib, const char* name) {
 
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<shared_library>& lib, const char* name) {
 
    typedef typename boost::dll::detail::import_type<T>::base_type type;
 
    return type(lib, lib->get<T*>(name));
 
}
 

	
 
template <class T>
 
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const boost::filesystem::path& lib, const char* name, load_mode::type mode) {
 
    return boost::dll::import_alias<T>(
 
        boost::make_shared<boost::dll::shared_library>(lib, mode),
 
        SWIFTEN_SHRPTR_NAMESPACE::make_shared<boost::dll::shared_library>(lib, mode),
 
        name
 
    );
 
}
 
#undef BOOST_DLL_IMPORT_RESULT_TYPE
 

	
 

	
 
}} // boost::dll
 

	
 
#endif // BOOST_DLL_IMPORT_HPP
 

	
include/boost/dll/shared_library.hpp
Show inline comments
 
@@ -3,24 +3,27 @@
 
//
 
// Distributed under the Boost Software License, Version 1.0.
 
// (See accompanying file LICENSE_1_0.txt
 
// or copy at http://www.boost.org/LICENSE_1_0.txt)
 

	
 
#ifndef BOOST_DLL_SHARED_LIBRARY_HPP
 
#define BOOST_DLL_SHARED_LIBRARY_HPP
 

	
 
/// \file boost/dll/shared_library.hpp
 
/// \brief Contains the boost::dll::shared_library class, core class for all the
 
/// DLL/DSO operations.
 

	
 
// Walkaround for compatibility with boost 1.54
 
#include <boost/move/move.hpp>
 

	
 
#include <boost/config.hpp>
 
#include <boost/predef/os.h>
 
#include <boost/utility/explicit_operator_bool.hpp>
 
#include <boost/dll/detail/system_error.hpp>
 
#include <boost/dll/detail/aggressive_ptr_cast.hpp>
 

	
 
#if BOOST_OS_WINDOWS
 
#   include <boost/dll/detail/windows/shared_library_impl.hpp>
 
#else
 
#   include <boost/dll/detail/posix/shared_library_impl.hpp>
 
#endif
 

	
include/boost/signalslib.hpp
Show inline comments
 
new file 100644
 
/*
 
 * Walkaroung for Boost, Qt namespace clash
 
 *
 
 * Taken from boost documantation:
 
 * http://www.boost.org/doc/libs/1_55_0/doc/html/signals/s04.html
 
 */
 

	
 

	
 
#ifndef SIGNALSLIB_HPP_INCLUDED
 
#define SIGNALSLIB_HPP_INCLUDED
 

	
 
#if defined(signals) && defined(QOBJECTDEFS_H) && \
 
  !defined(QT_MOC_CPP)
 
#  undef signals
 
#  define signals signals
 
#endif
 

	
 
#include <boost/signal.hpp>
 
namespace boost
 
{
 
  namespace signalslib = signals;
 
}
 

	
 
#if defined(signals) && defined(QOBJECTDEFS_H) && \
 
  !defined(QT_MOC_CPP)
 
#  undef signals
 
// Restore the macro definition of "signals", as it was
 
// defined by Qt's <qobjectdefs.h>.
 
#  define signals protected
 
#endif
 

	
 
#endif
 

	
include/transport/Config.h
Show inline comments
 
@@ -17,25 +17,25 @@
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/program_options.hpp>
 
#include <boost/foreach.hpp>
 
#include <boost/format.hpp>
 
#include <boost/algorithm/string.hpp>
 
#include <boost/assign.hpp>
 
#include <boost/bind.hpp>
 
#include <boost/signal.hpp>
 
#include <boost/signalslib.hpp>
 

	
 
namespace Transport {
 

	
 
template <class myType>
 
const myType &safeAs(const boost::program_options::variable_value &var, const myType &def) {
 
	try  {
 
		return var.as<myType>();
 
	}
 
	catch(...) {
 
		return def;
 
	}
 
}
include/transport/Conversation.h
Show inline comments
 
@@ -16,24 +16,25 @@
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include <list>
 
#include "Swiften/Elements/Message.h"
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Transport {
 

	
 
class ConversationManager;
 

	
 
/// Represents one XMPP-Legacy network conversation.
 
class Conversation {
 
	public:
 
		typedef enum {
 
			PARTICIPANT_FLAG_NONE = 0,
 
			PARTICIPANT_FLAG_MODERATOR = 1,
 
			PARTICIPANT_FLAG_CONFLICT = 2,
 
@@ -54,27 +55,27 @@ class Conversation {
 
		/// Destructor.
 
		virtual ~Conversation();
 

	
 
		/// Returns legacy network name of this conversation.
 

	
 
		/// \return legacy network name of this conversation.
 
		const std::string &getLegacyName() { return m_legacyName; }
 

	
 
		/// Handles new message from Legacy network and forwards it to XMPP.
 

	
 
		/// \param message Message received from legacy network.
 
		/// \param nickname For MUC conversation this is nickname of room participant who sent this message.
 
		void handleMessage(boost::shared_ptr<Swift::Message> &message, const std::string &nickname = "");
 
		void handleMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &message, const std::string &nickname = "");
 

	
 
		void handleRawMessage(boost::shared_ptr<Swift::Message> &message);
 
		void handleRawMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &message);
 
		void handleRawPresence(Swift::Presence::ref presence);
 

	
 
		/// Handles participant change in MUC.
 

	
 
		/// \param nickname Nickname of participant which changed.
 
		/// \param flag ParticipantFlag.
 
		/// \param status Current status of this participant.
 
		/// \param statusMessage Current status message of this participant.
 
		/// \param newname If participant was renamed, this variable contains his new name.
 
		void handleParticipantChanged(const std::string &nickname, ParticipantFlag flag, int status = Swift::StatusShow::None, const std::string &statusMessage = "", const std::string &newname = "", const std::string &iconhash = "", const std::string &alias = "");
 

	
 
		/// Sets XMPP user nickname in MUC rooms.
 
@@ -98,25 +99,25 @@ class Conversation {
 
			m_jids.clear();
 
		}
 

	
 
		void removeJID(const Swift::JID &jid);
 

	
 
		const std::list<Swift::JID> &getJIDs() {
 
			return m_jids;
 
		}
 

	
 
		/// Sends message to Legacy network.
 

	
 
		/// \param message Message.
 
		virtual void sendMessage(boost::shared_ptr<Swift::Message> &message) = 0;
 
		virtual void sendMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &message) = 0;
 

	
 
		/// Returns ConversationManager associated with this Conversation.
 

	
 
		/// \return  ConversationManager associated with this Conversation.
 
		ConversationManager *getConversationManager() {
 
			return m_conversationManager;
 
		}
 

	
 
		/// Returns True if this conversation is MUC room.
 

	
 
		/// \return  True if this conversation is MUC room.
 
		bool isMUC() {
 
@@ -138,43 +139,43 @@ class Conversation {
 

	
 
		void destroyRoom();
 

	
 
		std::string getParticipants();
 
		void sendParticipants(const Swift::JID &to, const std::string &nickname);
 

	
 
		void sendCachedMessages(const Swift::JID &to = Swift::JID());
 

	
 
		void setMUCEscaping(bool mucEscaping);
 

	
 
	private:
 
		Swift::Presence::ref generatePresence(const std::string &nick, int flag, int status, const std::string &statusMessage, const std::string &newname = "", const std::string &iconhash = "");
 
		void cacheMessage(boost::shared_ptr<Swift::Message> &message);
 
		void cacheMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &message);
 

	
 
	private:
 
		ConversationManager *m_conversationManager;
 
		std::string m_legacyName;
 
		std::string m_nickname;
 
		std::string m_room;
 
		bool m_muc;
 
		Swift::JID m_jid;
 
		std::list<Swift::JID> m_jids;
 
		bool m_sentInitialPresence;
 
		bool m_nicknameChanged;
 
		bool m_mucEscaping;
 
		bool m_sentInitialSubject;
 

	
 
		// TODO: Move this to some extra class to cache the most used
 
		// rooms across different accounts. Just now if we have 10 users
 
		// connected to single room, we store all those things 10 times.
 
		// It would be also great to store last 100 messages per room
 
		// every time, so we can get history messages for IRC for example.
 
		boost::shared_ptr<Swift::Message> m_subject;
 
		std::list<boost::shared_ptr<Swift::Message> > m_cachedMessages;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> m_subject;
 
		std::list<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> > m_cachedMessages;
 

	
 
		typedef struct {
 
			Swift::Presence::ref presence;
 
			std::string alias;
 
		} Participant;
 
		std::map<std::string, Participant> m_participants;
 
};
 

	
 
}
include/transport/FileTransferManager.h
Show inline comments
 
@@ -40,34 +40,34 @@
 
#endif
 

	
 
namespace Transport {
 

	
 
class UserManager;
 
class User;
 
class Component;
 
class Buddy;
 

	
 
class FileTransferManager {
 
	public:
 
		typedef struct Transfer {
 
			boost::shared_ptr<Swift::OutgoingFileTransfer> ft;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::OutgoingFileTransfer> ft;
 
			Swift::JID from;
 
			Swift::JID to;
 
			boost::shared_ptr<Swift::ReadBytestream> readByteStream;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::ReadBytestream> readByteStream;
 
		} Transfer;
 

	
 
		FileTransferManager(Component *component, UserManager *userManager);
 
		virtual ~FileTransferManager();
 
		
 
		FileTransferManager::Transfer sendFile(User *user, Buddy *buddy, boost::shared_ptr<Swift::ReadBytestream> byteStream, const Swift::StreamInitiationFileInfo &info);
 
		FileTransferManager::Transfer sendFile(User *user, Buddy *buddy, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::ReadBytestream> byteStream, const Swift::StreamInitiationFileInfo &info);
 

	
 
	private:
 
		Component *m_component;
 
		UserManager *m_userManager;
 
		Swift::CombinedOutgoingFileTransferManager* m_outgoingFTManager;
 
		Swift::RemoteJingleTransportCandidateSelectorFactory* m_remoteCandidateSelectorFactory;
 
		Swift::LocalJingleTransportCandidateGeneratorFactory* m_localCandidateGeneratorFactory;
 
		Swift::JingleSessionManager *m_jingleSessionManager;
 
		Swift::SOCKS5BytestreamRegistry* m_bytestreamRegistry;
 
#if HAVE_SWIFTEN_3
 
		Swift::SOCKS5BytestreamServerManager* m_proxyServerManager;
 
		Swift::SOCKS5BytestreamProxiesManager *m_proxyManager;
include/transport/Frontend.h
Show inline comments
 
@@ -21,24 +21,25 @@
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include <Swiften/EventLoop/EventLoop.h>
 
#include <Swiften/Network/NetworkFactories.h>
 
#include "Swiften/Elements/RosterPayload.h"
 
#include "Swiften/Elements/VCard.h"
 
#include "Swiften/Elements/Message.h"
 
#include "Swiften/Elements/IQ.h"
 
#include "Swiften/Elements/DiscoInfo.h"
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/SwiftenCompat.h"
 

	
 
#include <boost/signal.hpp>
 

	
 
namespace Transport {
 

	
 
class Config;
 
class UserRegistry;
 
class Component;
 
class User;
 
class Buddy;
 
class RosterManager;
 
class UserManager;
 
@@ -65,47 +66,47 @@ class Frontend {
 
		virtual void init(Component *component, Swift::EventLoop *loop, Swift::NetworkFactories *factories, Config *config, UserRegistry *userRegistry) = 0;
 

	
 
		virtual void connectToServer() = 0;
 

	
 
		virtual void disconnectFromServer() = 0;
 

	
 
		virtual void sendPresence(Swift::Presence::ref presence) = 0;
 

	
 
		virtual void sendVCard(Swift::VCard::ref vcard, Swift::JID to) = 0;
 

	
 
		virtual void sendRosterRequest(Swift::RosterPayload::ref, Swift::JID to) = 0;
 

	
 
		virtual void sendMessage(boost::shared_ptr<Swift::Message> message) = 0;
 
		virtual void sendMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> message) = 0;
 

	
 
		virtual void sendIQ(boost::shared_ptr<Swift::IQ>) = 0;
 
		virtual void sendIQ(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::IQ>) = 0;
 

	
 
		virtual boost::shared_ptr<Swift::DiscoInfo> sendCapabilitiesRequest(Swift::JID to) = 0;
 
		virtual SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::DiscoInfo> sendCapabilitiesRequest(Swift::JID to) = 0;
 

	
 
		virtual void reconnectUser(const std::string &user) = 0;
 

	
 
		virtual RosterManager *createRosterManager(User *user, Component *component) = 0;
 

	
 
		virtual User *createUser(const Swift::JID &jid, UserInfo &userInfo, Component *component, UserManager *userManager) = 0;
 

	
 
		virtual UserManager *createUserManager(Component *component, UserRegistry *userRegistry, StorageBackend *storageBackend = NULL) = 0;
 

	
 
		virtual void clearRoomList() = 0;
 
		virtual void addRoomToRoomList(const std::string &handle, const std::string &name) = 0;
 

	
 
		virtual std::string setOAuth2Code(const std::string &code, const std::string &state) { return "OAuth2 code is not needed for this frontend."; }
 
		virtual std::string getOAuth2URL(const std::vector<std::string> &args) { return ""; }
 
		virtual std::string getRegistrationFields() { return "Jabber ID\n3rd-party network username\n3rd-party network password"; }
 

	
 
		virtual bool isRawXMLEnabled() { return false; }
 

	
 
		boost::signal<void (User *, const std::string &name, unsigned int id)> onVCardRequired;
 
		boost::signal<void (User *, boost::shared_ptr<Swift::VCard> vcard)> onVCardUpdated;
 
		boost::signal<void (User *, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::VCard> vcard)> onVCardUpdated;
 
		boost::signal<void (Buddy *, const Swift::RosterItemPayload &item)> onBuddyUpdated;
 
		boost::signal<void (Buddy *)> onBuddyRemoved;
 
		boost::signal<void (Buddy *, const Swift::RosterItemPayload &item)> onBuddyAdded;
 
		boost::signal<void (Swift::Message::ref message)> onMessageReceived;
 
		boost::signal<void (bool /* isAvailable */)> onAvailableChanged;
 
		boost::signal<void (boost::shared_ptr<Swift::Presence>) > onPresenceReceived;
 
		boost::signal<void (const Swift::JID& jid, boost::shared_ptr<Swift::DiscoInfo> info)> onCapabilitiesReceived;
 
		boost::signal<void (SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Presence>) > onPresenceReceived;
 
		boost::signal<void (const Swift::JID& jid, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::DiscoInfo> info)> onCapabilitiesReceived;
 
};
 

	
 
}
include/transport/MemoryReadBytestream.h
Show inline comments
 
@@ -13,37 +13,39 @@
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <map>
 
#include <boost/signal.hpp>
 

	
 
#include "Swiften/FileTransfer/ReadBytestream.h"
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Transport {
 

	
 
class MemoryReadBytestream : public Swift::ReadBytestream {
 
	public:
 
		MemoryReadBytestream(unsigned long size);
 
		virtual ~MemoryReadBytestream();
 

	
 
		unsigned long appendData(const std::string &data);
 

	
 
		virtual boost::shared_ptr<std::vector<unsigned char> > read(size_t size);
 
		virtual SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<std::vector<unsigned char> > read(size_t size);
 

	
 
		void setFinished() { m_finished = true; }
 
		bool isFinished() const;
 

	
 
		boost::signal<void ()> onDataNeeded;
 

	
 
	private:
 
		bool m_finished;
 
		std::string m_data;
 
		bool neededData;
 
		unsigned long m_sent;
 
		unsigned long m_size;
include/transport/NetworkPluginServer.h
Show inline comments
 
@@ -30,24 +30,25 @@
 
#include "Swiften/Elements/ChatState.h"
 
#include "Swiften/Elements/RosterItemPayload.h"
 
#include "Swiften/Elements/VCard.h"
 
#include "Swiften/Elements/Message.h"
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/Elements/IQ.h"
 
#include "Swiften/Network/Timer.h"
 
#include "Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h"
 
#include "Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h"
 
#include "Swiften/Parser/XMPPParser.h"
 
#include "Swiften/Parser/XMPPParserClient.h"
 
#include "Swiften/Serializer/XMPPSerializer.h"
 
#include "Swiften/SwiftenCompat.h"
 
#include <Swiften/Version.h>
 
#include <Swiften/FileTransfer/FileTransfer.h>
 
#define HAVE_SWIFTEN_3  (SWIFTEN_VERSION >= 0x030000)
 

	
 
#define NETWORK_PLUGIN_API_VERSION (1)
 

	
 
namespace Transport {
 

	
 
class UserManager;
 
class User;
 
class Component;
 
class Buddy;
 
@@ -59,25 +60,25 @@ class RosterResponder;
 
class BlockResponder;
 
class DummyReadBytestream;
 
class AdminInterface;
 
class FileTransferManager;
 
class FileTransfer;
 

	
 
class NetworkPluginServer : Swift::XMPPParserClient {
 
	public:
 
		struct Backend {
 
			int pongReceived;
 
			std::list<User *> users;
 
			Swift::SafeByteArray data;
 
			boost::shared_ptr<Swift::Connection> connection;
 
			SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> connection;
 
			unsigned long res;
 
			unsigned long init_res;
 
			unsigned long shared;
 
			bool acceptUsers;
 
			bool longRun;
 
			bool willDie;
 
			std::string id;
 
		};
 

	
 
		NetworkPluginServer(Component *component, Config *config, UserManager *userManager, FileTransferManager *ftManager);
 

	
 
		virtual ~NetworkPluginServer();
 
@@ -95,31 +96,31 @@ class NetworkPluginServer : Swift::XMPPParserClient {
 
		const std::list<Backend *> &getBackends() {
 
			return m_clients;
 
		}
 

	
 
		const std::vector<std::string> &getCrashedBackends() {
 
			return m_crashedBackends;
 
		}
 

	
 
		void collectBackend();
 

	
 
		bool moveToLongRunBackend(User *user);
 

	
 
		void handleMessageReceived(NetworkConversation *conv, boost::shared_ptr<Swift::Message> &message);
 
		void handleMessageReceived(NetworkConversation *conv, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &message);
 

	
 
	public:
 
		void handleNewClientConnection(boost::shared_ptr<Swift::Connection> c);
 
		void handleNewClientConnection(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> c);
 
		void handleSessionFinished(Backend *c);
 
		void handlePongReceived(Backend *c);
 
		void handleDataRead(Backend *c, boost::shared_ptr<Swift::SafeByteArray> data);
 
		void handleDataRead(Backend *c, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::SafeByteArray> data);
 

	
 
		void handleConnectedPayload(const std::string &payload);
 
		void handleDisconnectedPayload(const std::string &payload);
 
		void handleBuddyChangedPayload(const std::string &payload);
 
		void handleBuddyRemovedPayload(const std::string &payload);
 
		void handleConvMessagePayload(const std::string &payload, bool subject = false);
 
		void handleConvMessageAckPayload(const std::string &payload);
 
		void handleParticipantChangedPayload(const std::string &payload);
 
		void handleRoomChangedPayload(const std::string &payload);
 
		void handleVCardPayload(const std::string &payload);
 
		void handleChatStatePayload(const std::string &payload, Swift::ChatState::ChatStateType type);
 
		void handleAuthorizationPayload(const std::string &payload);
 
@@ -139,59 +140,59 @@ class NetworkPluginServer : Swift::XMPPParserClient {
 
		void handleUserReadyToConnect(User *user);
 
		void handleUserPresenceChanged(User *user, Swift::Presence::ref presence);
 
		void handleUserDestroyed(User *user);
 

	
 
		void handleBuddyUpdated(Buddy *buddy, const Swift::RosterItemPayload &item);
 
		void handleBuddyRemoved(Buddy *buddy);
 
		void handleBuddyAdded(Buddy *buddy, const Swift::RosterItemPayload &item);
 
		void handleUserBuddyAdded(User *user, Buddy *buddy);
 
		void handleUserBuddyRemoved(User *user, Buddy *buddy);
 

	
 
		void handleBlockToggled(Buddy *buddy);
 

	
 
		void handleVCardUpdated(User *user, boost::shared_ptr<Swift::VCard> vcard);
 
		void handleVCardUpdated(User *user, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::VCard> vcard);
 
		void handleVCardRequired(User *user, const std::string &name, unsigned int id);
 

	
 
		void handleFTStateChanged(Swift::FileTransfer::State state, const std::string &userName, const std::string &buddyName, const std::string &fileName, unsigned long size, unsigned long id);
 
		void handleFTAccepted(User *user, const std::string &buddyName, const std::string &fileName, unsigned long size, unsigned long ftID);
 
		void handleFTRejected(User *user, const std::string &buddyName, const std::string &fileName, unsigned long size);
 
		void handleFTDataNeeded(Backend *b, unsigned long ftid);
 

	
 
		void handlePIDTerminated(unsigned long pid);
 
	private:
 
		void send(boost::shared_ptr<Swift::Connection> &, const std::string &data);
 
		void send(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> &, const std::string &data);
 

	
 
		void pingTimeout();
 
		void sendPing(Backend *c);
 
		void sendAPIVersion(Backend *c);
 
		Backend *getFreeClient(bool acceptUsers = true, bool longRun = false, bool check = false);
 
		void connectWaitingUsers();
 
		void loginDelayFinished();
 
		void handleRawIQReceived(boost::shared_ptr<Swift::IQ> iq);
 
		void handleRawPresenceReceived(boost::shared_ptr<Swift::Presence> presence);
 
		void handleRawIQReceived(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::IQ> iq);
 
		void handleRawPresenceReceived(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Presence> presence);
 

	
 
		void handleStreamStart(const Swift::ProtocolHeader&) {}
 
#if HAVE_SWIFTEN_3
 
		void handleElement(boost::shared_ptr<Swift::ToplevelElement> element);
 
		void handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::ToplevelElement> element);
 
#else
 
		void handleElement(boost::shared_ptr<Swift::Element> element);
 
		void handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Element> element);
 
#endif
 
		void handleStreamEnd() {}
 

	
 
		UserManager *m_userManager;
 
		VCardResponder *m_vcardResponder;
 
		RosterResponder *m_rosterResponder;
 
		BlockResponder *m_blockResponder;
 
		Config *m_config;
 
		boost::shared_ptr<Swift::ConnectionServer> m_server;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::ConnectionServer> m_server;
 
		std::list<Backend *>  m_clients;
 
		std::vector<unsigned long> m_pids;
 
		Swift::Timer::ref m_pingTimer;
 
		Swift::Timer::ref m_collectTimer;
 
		Swift::Timer::ref m_loginTimer;
 
		Component *m_component;
 
		std::list<User *> m_waitingUsers;
 
		bool m_isNextLongRun;
 
		std::map<unsigned long, FileTransferManager::Transfer> m_filetransfers;
 
		FileTransferManager *m_ftManager;
 
		std::vector<std::string> m_crashedBackends;
 
		AdminInterface *m_adminInterface;
include/transport/PresenceOracle.h
Show inline comments
 
@@ -13,30 +13,30 @@
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include <map>
 

	
 
#include <boost/signals.hpp>
 

	
 
#include <string>
 
#include <Swiften/Elements/Presence.h>
 
#include <Swiften/Client/StanzaChannel.h>
 

	
 
#include <Swiften/Base/boost_bsignals.h>
 

	
 
namespace Transport {
 

	
 
class Frontend;
 

	
 
class PresenceOracle {
 
	public:
 
		PresenceOracle(Frontend* frontend);
 
		~PresenceOracle();
 

	
 
		Swift::Presence::ref getLastPresence(const Swift::JID&) const;
 
		Swift::Presence::ref getHighestPriorityPresence(const Swift::JID& bareJID) const;
 
		std::vector<Swift::Presence::ref> getAllPresence(const Swift::JID& bareJID) const;
include/transport/RosterManager.h
Show inline comments
 
@@ -14,24 +14,25 @@
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include <map>
 
#include <boost/signal.hpp>
 
#include <boost/pool/pool_alloc.hpp>
 
#include <boost/pool/object_pool.hpp>
 
// #include "rosterstorage.h"
 
#include "Swiften/Elements/RosterPayload.h"
 
#include "Swiften/Queries/GenericRequest.h"
 
#include "Swiften/Roster/SetRosterRequest.h"
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/Network/Timer.h"
 

	
 
namespace Transport {
 

	
 
class Buddy;
include/transport/Transport.h
Show inline comments
 
@@ -12,31 +12,33 @@
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include <boost/signal.hpp>
 
#include <boost/bind.hpp>
 
#include "Swiften/Network/BoostTimerFactory.h"
 
#include "Swiften/Network/BoostIOServiceThread.h"
 
#include "Swiften/Network/NetworkFactories.h"
 
#include "Swiften/Elements/DiscoInfo.h"
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/Elements/IQ.h"
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Transport {
 
	class StorageBackend;
 
	class Factory;
 
	class UserRegistry;
 
	class Frontend;
 
	class PresenceOracle;
 
	class Factory;
 
	class Config;
 
	class UserManager;
 
	class AdminInterface;
 

	
 
@@ -99,25 +101,25 @@ namespace Transport {
 
			boost::signal<void ()> onConnected;
 

	
 
			/// This signal is emitted when XML stanza is sent to server.
 

	
 
			Config *getConfig() { return m_config; }
 

	
 
			/// It's emitted only for presences addressed to transport itself
 
			/// (for example to="j2j.domain.tld") and for presences comming to
 
			/// MUC (for example to="#chat%irc.freenode.org@irc.domain.tld")
 
			/// \param presence Presence.
 
			boost::signal<void (Swift::Presence::ref presence)> onUserPresenceReceived;
 

	
 
			boost::signal<void (boost::shared_ptr<Swift::IQ>)> onRawIQReceived;
 
			boost::signal<void (SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::IQ>)> onRawIQReceived;
 

	
 
			boost::signal<void ()> onAdminInterfaceSet;
 
			
 
			void handlePresence(Swift::Presence::ref presence);
 
			void handleConnected();
 
			void handleConnectionError(const std::string &error);
 
			void handleDataRead(const std::string &data);
 
			void handleDataWritten(const std::string &data);
 

	
 
			Frontend *getFrontend() {
 
				return m_frontend;
 
			}
 
@@ -125,25 +127,25 @@ namespace Transport {
 
			PresenceOracle *getPresenceOracle();
 

	
 
			void setAdminInterface(AdminInterface *adminInterface) {
 
				m_adminInterface = adminInterface;
 
				onAdminInterfaceSet();
 
			}
 

	
 
			AdminInterface *getAdminInterface() {
 
				return m_adminInterface;
 
			}
 

	
 
		private:
 
			void handleDiscoInfoResponse(boost::shared_ptr<Swift::DiscoInfo> info, Swift::ErrorPayload::ref error, const Swift::JID& jid);
 
			void handleDiscoInfoResponse(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::DiscoInfo> info, Swift::ErrorPayload::ref error, const Swift::JID& jid);
 
			void handleCapsChanged(const Swift::JID& jid);
 

	
 
			void handleBackendConfigChanged();
 

	
 
			Swift::NetworkFactories *m_factories;
 
			Swift::Timer::ref m_reconnectTimer;
 
			PresenceOracle *m_presenceOracle;
 
			
 
			Transport::UserRegistry *m_userRegistry;
 
			StorageBackend *m_storageBackend;
 
			int m_reconnectCount;
 
			Config* m_config;
include/transport/User.h
Show inline comments
 
@@ -11,34 +11,36 @@
 
 * This program is distributed in the hope that it will be useful,
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/signal.hpp>
 
#include <time.h>
 
#include "transport/StorageBackend.h"
 
#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
 
#include "Swiften/Elements/SpectrumErrorPayload.h"
 
#include "Swiften/JID/JID.h"
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/Elements/Message.h"
 
#include "Swiften/Elements/DiscoInfo.h"
 
#include "Swiften/Network/Timer.h"
 
#include "Swiften/Network/Connection.h"
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Transport {
 

	
 
class Component;
 
class RosterManager;
 
class ConversationManager;
 
class UserManager;
 
class PresenceOracle;
 

	
 
/// Represents online XMPP user.
 
class User {
 
	public:
 
@@ -80,25 +82,25 @@ class User {
 
		virtual void addRoomToRoomList(const std::string &handle, const std::string &name) {}
 
		virtual void requestVCard() {}
 

	
 
		void setData(void *data) { m_data = data; }
 
		void *getData() { return m_data; }
 

	
 
		/// Handles presence from XMPP JID associated with this user.
 
		/// \param presence Swift::Presence.
 
		void handlePresence(Swift::Presence::ref presence, bool forceJoin = false);
 

	
 
		void handleSubscription(Swift::Presence::ref presence);
 

	
 
		void handleDiscoInfo(const Swift::JID& jid, boost::shared_ptr<Swift::DiscoInfo> info);
 
		void handleDiscoInfo(const Swift::JID& jid, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::DiscoInfo> info);
 

	
 
		time_t &getLastActivity() {
 
			return m_lastActivity;
 
		}
 

	
 
		void updateLastActivity() {
 
			m_lastActivity = time(NULL);
 
		}
 

	
 
		/// Returns language.
 
		/// \return language
 
		const char *getLang() { return "en"; }
 
@@ -160,26 +162,26 @@ class User {
 
		Swift::JID m_jid;
 
		Component *m_component;
 
		RosterManager *m_rosterManager;
 
		UserManager *m_userManager;
 
		ConversationManager *m_conversationManager;
 
		PresenceOracle *m_presenceOracle;
 
		UserInfo m_userInfo;
 
		void *m_data;
 
		bool m_connected;
 
		bool m_readyForConnect;
 
		bool m_ignoreDisconnect;
 
		Swift::Timer::ref m_reconnectTimer;
 
		boost::shared_ptr<Swift::Connection> connection;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> connection;
 
		time_t m_lastActivity;
 
		std::map<Swift::JID, Swift::DiscoInfo::ref> m_legacyCaps;
 
		std::vector<boost::shared_ptr<Swift::OutgoingFileTransfer> > m_filetransfers;
 
		std::vector<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::OutgoingFileTransfer> > m_filetransfers;
 
		int m_resources;
 
		int m_reconnectCounter;
 
		std::list<Swift::Presence::ref> m_joinedRooms;
 
		std::map<std::string, std::string> m_settings;
 
		bool m_cacheMessages;
 
		int m_reconnectLimit;
 
		StorageBackend *m_storageBackend;
 
};
 

	
 
}
include/transport/UserManager.h
Show inline comments
 
@@ -11,33 +11,35 @@
 
 * This program is distributed in the hope that it will be useful,
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/signal.hpp>
 
#include <string>
 
#include <map>
 
#include "Swiften/Elements/Message.h"
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/JID/JID.h"
 
#include "Swiften/Disco/EntityCapsProvider.h"
 
#include "Swiften/Elements/DiscoInfo.h"
 
#include "Swiften/Elements/VCard.h"
 
#include "Swiften/Network/Timer.h"
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Transport {
 

	
 
class User;
 
class Component;
 
class StorageBackend;
 
class StorageResponder;
 
class RosterResponder;
 
class UserRegistration;
 
class UserRegistry;
 

	
 
/// Manages online XMPP Users.
 
@@ -134,25 +136,25 @@ class UserManager /*: public Swift::EntityCapsProvider*/ {
 
		unsigned long getMessagesToBackend() { return m_sentToBackend; }
 
		
 

	
 
	private:
 
		void handlePresence(Swift::Presence::ref presence);
 
		void handleMessageReceived(Swift::Message::ref message);
 
		void handleGeneralPresenceReceived(Swift::Presence::ref presence);
 
		void handleProbePresence(Swift::Presence::ref presence);
 
		void handleErrorPresence(Swift::Presence::ref presence);
 
		void handleSubscription(Swift::Presence::ref presence);
 
		void handleMUCPresence(Swift::Presence::ref presence);
 
		void handleRemoveTimeout(const std::string jid, User *user, bool reconnect);
 
		void handleDiscoInfo(const Swift::JID& jid, boost::shared_ptr<Swift::DiscoInfo> info);
 
		void handleDiscoInfo(const Swift::JID& jid, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::DiscoInfo> info);
 
		void addUser(User *user);
 

	
 
		long m_onlineBuddies;
 
		User *m_cachedUser;
 
		std::map<std::string, User *> m_users;
 
		Component *m_component;
 
		StorageBackend *m_storageBackend;
 
		StorageResponder *m_storageResponder;
 
		UserRegistry *m_userRegistry;
 
		Swift::Timer::ref m_removeTimer;
 
		unsigned long m_sentToXMPP;
 
		unsigned long m_sentToBackend;
include/transport/WebSocketClient.h
Show inline comments
 
@@ -22,24 +22,25 @@
 

	
 
#include <Swiften/Network/TLSConnectionFactory.h>
 
#include <Swiften/Network/HostAddressPort.h>
 
#include <Swiften/TLS/PlatformTLSFactories.h>
 
#include <Swiften/Network/DomainNameResolveError.h>
 
#include <Swiften/Network/DomainNameAddressQuery.h>
 
#include <Swiften/Network/DomainNameResolver.h>
 
#include <Swiften/Network/HostAddress.h>
 
#include <Swiften/Network/Connection.h>
 
#include <Swiften/Base/SafeByteArray.h>
 
#include "Swiften/Version.h"
 
#include "Swiften/Network/Timer.h"
 
#include "Swiften/SwiftenCompat.h"
 

	
 
#define HAVE_SWIFTEN_3  (SWIFTEN_VERSION >= 0x030000)
 

	
 
#if HAVE_SWIFTEN_3
 
#include <Swiften/TLS/TLSOptions.h>
 
#endif
 

	
 
#include <string>
 
#include <algorithm>
 
#include <map>
 

	
 
#include <boost/signal.hpp>
 
@@ -57,33 +58,33 @@ class WebSocketClient {
 
		void connectServer(const std::string &u);
 
		void disconnectServer();
 

	
 
		void write(const std::string &data);
 

	
 
		boost::signal<void (const std::string &payload)> onPayloadReceived;
 

	
 
		boost::signal<void ()> onWebSocketConnected;
 
		boost::signal<void (const boost::optional<Swift::Connection::Error> &error)> onWebSocketDisconnected;
 

	
 
	private:
 
		void handleDNSResult(const std::vector<Swift::HostAddress>&, boost::optional<Swift::DomainNameResolveError>);
 
		void handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data);
 
		void handleDataRead(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::SafeByteArray> data);
 
		void handleConnected(bool error);
 
		void handleDisconnected(const boost::optional<Swift::Connection::Error> &error);
 

	
 
		void connectServer();
 

	
 
	private:
 
		Component *m_component;
 
		boost::shared_ptr<Swift::DomainNameAddressQuery> m_dnsQuery;
 
		boost::shared_ptr<Swift::Connection> m_conn;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::DomainNameAddressQuery> m_dnsQuery;
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> m_conn;
 
		Swift::TLSConnectionFactory *m_tlsConnectionFactory;
 
		Swift::PlatformTLSFactories *m_tlsFactory;
 
		std::string m_host;
 
		std::string m_path;
 
		std::string m_buffer;
 
		bool m_upgraded;
 
		Swift::Timer::ref m_reconnectTimer;
 
		std::string m_user;
 
};
 

	
 
}
libtransport/Buddy.cpp
Show inline comments
 
@@ -128,28 +128,28 @@ std::vector<Swift::Presence::ref> &Buddy::generatePresenceStanzas(int features,
 
		presence->setStatus(statusMessage);
 

	
 
	if (s.getType() == Swift::StatusShow::None)
 
		presence->setType(Swift::Presence::Unavailable);
 

	
 
	presence->setShow(s.getType());
 

	
 
	if (presence->getType() != Swift::Presence::Unavailable) {
 
		// caps
 
	
 

	
 
// 		if (features & 0/*TRANSPORT_FEATURE_AVATARS*/) {
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::VCardUpdate (getIconHash())));
 
			presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(new Swift::VCardUpdate (getIconHash())));
 
// 		}
 
// 		if (isBlocked()) {
 
// 			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Transport::BlockPayload ()));
 
// 			presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(new Transport::BlockPayload ()));
 
// 		}
 
	}
 

	
 
	BOOST_FOREACH(Swift::Presence::ref &p, m_presences) {
 
		if (p->getFrom() == presence->getFrom()) {
 
			p = presence;
 
			return m_presences;
 
		}
 
	}
 

	
 
	m_presences.push_back(presence);
 

	
libtransport/CMakeLists.txt
Show inline comments
 
@@ -50,16 +50,17 @@ if (WIN32)
 
	TARGET_LINK_LIBRARIES(transport transport-plugin sqlite3 ${PQXX_LIBRARY} ${CURL_LIBRARIES} ${PQ_LIBRARY} ${MYSQL_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES} ${PROTOBUF_LIBRARY} psapi.lib)
 
else()
 
	TARGET_LINK_LIBRARIES(transport transport-plugin ${PQXX_LIBRARY} ${CURL_LIBRARIES} ${PQ_LIBRARY} ${SQLITE3_LIBRARIES} ${MYSQL_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES} ${POPT_LIBRARY} ${PROTOBUF_LIBRARY})
 
endif()
 

	
 
SET_TARGET_PROPERTIES(transport PROPERTIES
 
      VERSION ${TRANSPORT_VERSION} SOVERSION ${TRANSPORT_VERSION}
 
)
 
if (APPLE)
 
	TARGET_LINK_LIBRARIES(transport ${APPLE_FRAMEWORKS})
 
endif()
 

	
 

	
 
INSTALL(TARGETS transport LIBRARY DESTINATION ${LIB_INSTALL_DIR} ARCHIVE DESTINATION ${LIB_INSTALL_DIR} COMPONENT libraries)
 

	
 
#CONFIGURE_FILE(transport.pc.in "${CMAKE_CURRENT_BINARY_DIR}/transport.pc")
 
#INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/transport.pc" DESTINATION lib/pkgconfig)
libtransport/Conversation.cpp
Show inline comments
 
@@ -79,49 +79,49 @@ void Conversation::destroyRoom() {
 
		item.actor = "Transport";
 
		item.reason = "Spectrum 2 transport is being shut down.";
 
		Swift::MUCUserPayload *p = new Swift::MUCUserPayload ();
 
		p->addItem(item);
 

	
 
		Swift::MUCUserPayload::StatusCode c;
 
		c.code = 332;
 
		p->addStatusCode(c);
 
		Swift::MUCUserPayload::StatusCode c2;
 
		c2.code = 307;
 
		p->addStatusCode(c2);
 

	
 
		presence->addPayload(boost::shared_ptr<Swift::Payload>(p));
 
		presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(p));
 
		BOOST_FOREACH(const Swift::JID &jid, m_jids) {
 
			presence->setTo(jid);
 
			m_conversationManager->getComponent()->getFrontend()->sendPresence(presence);
 
		}
 
	}
 
}
 

	
 
void Conversation::setRoom(const std::string &room) {
 
	m_room = room;
 
	m_legacyName = m_room + "/" + m_legacyName;
 
}
 

	
 
void Conversation::cacheMessage(boost::shared_ptr<Swift::Message> &message) {
 
void Conversation::cacheMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &message) {
 
	boost::posix_time::ptime timestamp = boost::posix_time::second_clock::universal_time();
 
	boost::shared_ptr<Swift::Delay> delay(boost::make_shared<Swift::Delay>());
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Delay> delay(SWIFTEN_SHRPTR_NAMESPACE::make_shared<Swift::Delay>());
 
	delay->setStamp(timestamp);
 
	message->addPayload(delay);
 
	m_cachedMessages.push_back(message);
 
	if (m_cachedMessages.size() > 100) {
 
		m_cachedMessages.pop_front();
 
	}
 
}
 

	
 
void Conversation::handleRawMessage(boost::shared_ptr<Swift::Message> &message) {
 
void Conversation::handleRawMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &message) {
 
	if (message->getType() != Swift::Message::Groupchat) {
 
		if (m_conversationManager->getComponent()->inServerMode() && m_conversationManager->getUser()->shouldCacheMessages()) {
 
			cacheMessage(message);
 
		}
 
		else {
 
			m_conversationManager->getComponent()->getFrontend()->sendMessage(message);
 
		}
 
	}
 
	else {
 
		if (m_jids.empty()) {
 
			cacheMessage(message);
 
		}
 
@@ -136,25 +136,25 @@ void Conversation::handleRawMessage(boost::shared_ptr<Swift::Message> &message)
 
						return;
 
					}
 
					else {
 
						LOG4CXX_INFO(logger, m_jid.toString() << ": Forwarding subject message.");
 
					}
 
				}
 
				m_conversationManager->getComponent()->getFrontend()->sendMessage(message);
 
			}
 
		}
 
	}
 
}
 

	
 
void Conversation::handleMessage(boost::shared_ptr<Swift::Message> &message, const std::string &nickname) {
 
void Conversation::handleMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &message, const std::string &nickname) {
 
	if (m_muc) {
 
		message->setType(Swift::Message::Groupchat);
 
	}
 
	else {
 
		if (message->getType() == Swift::Message::Headline) {
 
			if (m_conversationManager->getUser()->getUserSetting("send_headlines") != "1") {
 
				message->setType(Swift::Message::Chat);
 
			}
 
		}
 
		else {
 
			message->setType(Swift::Message::Chat);
 
		}
 
@@ -260,25 +260,25 @@ void Conversation::sendParticipants(const Swift::JID &to, const std::string &nic
 
	// Self presence has to be sent as first.
 
	Swift::Presence::ref presence = generatePresence(m_nickname, 0, (int) Swift::StatusShow::Online, "", "", "");
 
	presence->setTo(to);
 
	m_conversationManager->getComponent()->getFrontend()->sendPresence(presence);
 

	
 
	for (std::map<std::string, Participant>::iterator it = m_participants.begin(); it != m_participants.end(); it++) {
 
		(*it).second.presence->setTo(to);
 
		m_conversationManager->getComponent()->getFrontend()->sendPresence((*it).second.presence);
 
	}
 
}
 

	
 
void Conversation::sendCachedMessages(const Swift::JID &to) {
 
	for (std::list<boost::shared_ptr<Swift::Message> >::const_iterator it = m_cachedMessages.begin(); it != m_cachedMessages.end(); it++) {
 
	for (std::list<SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> >::const_iterator it = m_cachedMessages.begin(); it != m_cachedMessages.end(); it++) {
 
		if (to.isValid()) {
 
			(*it)->setTo(to);
 
		}
 
		else {
 
			(*it)->setTo(m_jid.toBare());
 
		}
 
		m_conversationManager->getComponent()->getFrontend()->sendMessage(*it);
 
	}
 

	
 
	if (m_subject) {
 
		if (to.isValid()) {
 
			m_subject->setTo(to);
 
@@ -312,42 +312,42 @@ Swift::Presence::ref Conversation::generatePresence(const std::string &nick, int
 

	
 
	if (s.getType() == Swift::StatusShow::None) {
 
		presence->setType(Swift::Presence::Unavailable);
 
	}
 

	
 
	presence->setShow(s.getType());
 

	
 
	Swift::MUCUserPayload *p = new Swift::MUCUserPayload ();
 
	if (m_nickname == nickname) {
 
		if (flag & PARTICIPANT_FLAG_CONFLICT) {
 
			delete p;
 
			presence->setType(Swift::Presence::Error);
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::MUCPayload()));
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::ErrorPayload(Swift::ErrorPayload::Conflict)));
 
			presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(new Swift::MUCPayload()));
 
			presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(new Swift::ErrorPayload(Swift::ErrorPayload::Conflict)));
 
			LOG4CXX_INFO(logger, m_jid.toString() << ": Generating error presence: PARTICIPANT_FLAG_CONFLICT");
 
			return presence;
 
		}
 
		else if (flag & PARTICIPANT_FLAG_NOT_AUTHORIZED) {
 
			delete p;
 
			presence->setType(Swift::Presence::Error);
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::MUCPayload()));
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::ErrorPayload(Swift::ErrorPayload::NotAuthorized, Swift::ErrorPayload::Auth, statusMessage)));
 
			presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(new Swift::MUCPayload()));
 
			presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(new Swift::ErrorPayload(Swift::ErrorPayload::NotAuthorized, Swift::ErrorPayload::Auth, statusMessage)));
 
			LOG4CXX_INFO(logger, m_jid.toString() << ": Generating error presence: PARTICIPANT_FLAG_NOT_AUTHORIZED");
 
			return presence;
 
		}
 
		else if (flag & PARTICIPANT_FLAG_ROOM_NOT_FOUD) {
 
			delete p;
 
			presence->setType(Swift::Presence::Error);
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::MUCPayload()));
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::ErrorPayload(Swift::ErrorPayload::ItemNotFound, Swift::ErrorPayload::Cancel, statusMessage)));
 
			presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(new Swift::MUCPayload()));
 
			presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(new Swift::ErrorPayload(Swift::ErrorPayload::ItemNotFound, Swift::ErrorPayload::Cancel, statusMessage)));
 
			LOG4CXX_INFO(logger, m_jid.toString() << ": Generating error presence: PARTICIPANT_FLAG_ROOM_NOT_FOUND");
 
			return presence;
 
		}
 
		else {
 
			Swift::MUCUserPayload::StatusCode c;
 
			c.code = 110;
 
			p->addStatusCode(c);
 
			if (m_nicknameChanged) {
 
				Swift::MUCUserPayload::StatusCode c;
 
				c.code = 210;
 
				p->addStatusCode(c);
 
				m_nicknameChanged = false;
 
@@ -367,29 +367,29 @@ Swift::Presence::ref Conversation::generatePresence(const std::string &nick, int
 
		item.role = Swift::MUCOccupant::Moderator;
 
	}
 

	
 
	if (!newname.empty()) {
 
		item.nick = newname;
 
		Swift::MUCUserPayload::StatusCode c;
 
		c.code = 303;
 
		p->addStatusCode(c);
 
		presence->setType(Swift::Presence::Unavailable);
 
	}
 

	
 
	if (!iconhash.empty()) {
 
		presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::VCardUpdate (iconhash)));
 
		presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(new Swift::VCardUpdate (iconhash)));
 
	}
 
	
 
	p->addItem(item);
 
	presence->addPayload(boost::shared_ptr<Swift::Payload>(p));
 
	presence->addPayload(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Payload>(p));
 
	return presence;
 
}
 

	
 

	
 
void Conversation::setNickname(const std::string &nickname) {
 
	if (!nickname.empty() && m_nickname != nickname) {
 
		m_nicknameChanged = true;
 
	}
 
	m_nickname = nickname;
 
}
 

	
 
void Conversation::handleRawPresence(Swift::Presence::ref presence) {
libtransport/FileTransferManager.cpp
Show inline comments
 
@@ -37,25 +37,25 @@ FileTransferManager::FileTransferManager(Component *component, UserManager *user
 
// 	m_jingleSessionManager = new Swift::JingleSessionManager(m_component->getIQRouter());
 
// #if !HAVE_SWIFTEN_3
 
// 	m_connectivityManager = new Swift::ConnectivityManager(m_component->getNetworkFactories()->getNATTraverser());
 
// #endif
 
// 	m_bytestreamRegistry = new Swift::SOCKS5BytestreamRegistry();
 
// #if !HAVE_SWIFTEN_3
 
// 	m_bytestreamProxy = new Swift::SOCKS5BytestreamProxy(m_component->getNetworkFactories()->getConnectionFactory(), m_component->getNetworkFactories()->getTimerFactory());
 
// 	m_localCandidateGeneratorFactory = new Swift::DefaultLocalJingleTransportCandidateGeneratorFactory(m_connectivityManager, m_bytestreamRegistry, m_bytestreamProxy, "thishouldnotbeused");
 
// 	m_remoteCandidateSelectorFactory = new Swift::DefaultRemoteJingleTransportCandidateSelectorFactory(m_component->getNetworkFactories()->getConnectionFactory(), m_component->getNetworkFactories()->getTimerFactory());
 
// #else
 
// 	m_proxyManager = new Swift::SOCKS5BytestreamProxiesManager(m_component->getNetworkFactories()->getConnectionFactory(), m_component->getNetworkFactories()->getTimerFactory(), m_component->getNetworkFactories()->getDomainNameResolver(), m_component->getIQRouter(), "bar.com");
 
// #endif
 
// 	boost::shared_ptr<Swift::ConnectionServer> server = m_component->getNetworkFactories()->getConnectionServerFactory()->createConnectionServer(19645);
 
// 	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::ConnectionServer> server = m_component->getNetworkFactories()->getConnectionServerFactory()->createConnectionServer(19645);
 
// 	server->start();
 
// #if HAVE_SWIFTEN_3
 
// 	m_proxyServerManager = new Swift::SOCKS5BytestreamServerManager(m_bytestreamRegistry, m_component->getNetworkFactories()->getConnectionServerFactory(), m_component->getNetworkFactories()->getNetworkEnvironment(), m_component->getNetworkFactories()->getNATTraverser());
 
// #else
 
// 	m_bytestreamServer = new Swift::SOCKS5BytestreamServer(server, m_bytestreamRegistry);
 
// 	m_bytestreamServer->start();
 
// 	m_outgoingFTManager = new Swift::CombinedOutgoingFileTransferManager(m_jingleSessionManager, m_component->getIQRouter(),
 
// 		m_userManager, m_remoteCandidateSelectorFactory,
 
// 		m_localCandidateGeneratorFactory, m_bytestreamRegistry,
 
// 		m_bytestreamProxy, m_component->getPresenceOracle(),
 
// 		m_bytestreamServer);
 
// #endif
 
@@ -73,25 +73,25 @@ FileTransferManager::~FileTransferManager() {
 
// 	delete m_localCandidateGeneratorFactory;
 
// #endif
 
// 	delete m_outgoingFTManager;
 
// 	delete m_jingleSessionManager;
 
// 	delete m_bytestreamRegistry;
 
// #if !HAVE_SWIFTEN_3
 
// 	delete m_bytestreamServer;
 
// 	delete m_bytestreamProxy;
 
// 	delete m_connectivityManager;
 
// #endif
 
}
 

	
 
FileTransferManager::Transfer FileTransferManager::sendFile(User *user, Buddy *buddy, boost::shared_ptr<Swift::ReadBytestream> byteStream, const Swift::StreamInitiationFileInfo &info) {
 
FileTransferManager::Transfer FileTransferManager::sendFile(User *user, Buddy *buddy, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::ReadBytestream> byteStream, const Swift::StreamInitiationFileInfo &info) {
 
 	FileTransferManager::Transfer transfer;
 
// 	transfer.from = buddy->getJID();
 
// 	transfer.to = user->getJID();
 
// 	transfer.readByteStream = byteStream;
 
// 
 
// 	LOG4CXX_INFO(logger, "Starting FT from '" << transfer.from << "' to '" << transfer.to << "'")
 
// 
 
// 	transfer.ft = m_outgoingFTManager->createOutgoingFileTransfer(transfer.from, transfer.to, transfer.readByteStream, info);
 
// // 	if (transfer.ft) {
 
// // 		m_filetransfers.push_back(ft);
 
// // 		ft->onStateChange.connect(boost::bind(&User::handleFTStateChanged, this, _1, Buddy::JIDToLegacyName(from), info.getName(), info.getSize(), id));
 
// // 		transfer.ft->start();
libtransport/MemoryReadByteStream.cpp
Show inline comments
 
@@ -32,40 +32,40 @@ MemoryReadBytestream::MemoryReadBytestream(unsigned long size) {
 

	
 
MemoryReadBytestream::~MemoryReadBytestream() {
 
	
 
}
 

	
 
unsigned long MemoryReadBytestream::appendData(const std::string &data) {
 
	m_data += data;
 
	onDataAvailable();
 
	neededData = false;
 
	return m_data.size();
 
}
 

	
 
boost::shared_ptr<std::vector<unsigned char> > MemoryReadBytestream::read(size_t size) {
 
SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<std::vector<unsigned char> > MemoryReadBytestream::read(size_t size) {
 
	if (m_data.empty()) {
 
		onDataNeeded();
 
		return boost::shared_ptr<std::vector<unsigned char> >(new std::vector<unsigned char>());
 
		return SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<std::vector<unsigned char> >(new std::vector<unsigned char>());
 
	}
 

	
 
	if (m_data.size() < size) {
 
		boost::shared_ptr<std::vector<unsigned char> > ptr(new std::vector<unsigned char>(m_data.begin(), m_data.end()));
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<std::vector<unsigned char> > ptr(new std::vector<unsigned char>(m_data.begin(), m_data.end()));
 
		m_sent += m_data.size();
 
		m_data.clear();
 
		if (m_sent == m_size)
 
			m_finished = true;
 
		onDataNeeded();
 
		return ptr;
 
	}
 
	boost::shared_ptr<std::vector<unsigned char> > ptr(new std::vector<unsigned char>(m_data.begin(), m_data.begin() + size));
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<std::vector<unsigned char> > ptr(new std::vector<unsigned char>(m_data.begin(), m_data.begin() + size));
 
	m_data.erase(m_data.begin(), m_data.begin() + size);
 
	m_sent += size;
 
	if (m_sent == m_size)
 
		m_finished = true;
 
	if (m_data.size() < 500000 && !neededData) {
 
		neededData = true;
 
		onDataNeeded();
 
	}
 
	return ptr;
 
}
 

	
 
bool MemoryReadBytestream::isFinished() const {
libtransport/MySQLBackend.cpp
Show inline comments
 
@@ -77,26 +77,24 @@
 
	if (ret == 0) \
 
		exec_ok = true; \
 
	else if (ret == 2013) { \
 
		LOG4CXX_INFO(logger, "MySQL connection lost. Reconnecting...");\
 
		disconnect(); \
 
		connect(); \
 
		return METHOD; \
 
	} \
 
	else \
 
		exec_ok = false; \
 
	}
 

	
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "MySQLBackend");
 
static bool exec_ok;
 

	
 
MySQLBackend::Statement::Statement(MYSQL *conn, const std::string &format, const std::string &statement) {
 
	m_resultOffset = -1;
 
	m_conn = conn;
 
	m_offset = 0;
 
	m_string = statement;
 
	m_stmt = mysql_stmt_init(conn);
 
	if (mysql_stmt_prepare(m_stmt, statement.c_str(), statement.size())) {
libtransport/NetworkPluginServer.cpp
Show inline comments
 
@@ -74,29 +74,29 @@ static unsigned long backend_id;
 
static unsigned long bytestream_id;
 

	
 
DEFINE_LOGGER(logger, "NetworkPluginServer");
 

	
 
static NetworkPluginServer *_server;
 

	
 
class NetworkConversation : public Conversation {
 
	public:
 
		NetworkConversation(ConversationManager *conversationManager, const std::string &legacyName, bool muc = false) : Conversation(conversationManager, legacyName, muc) {
 
		}
 

	
 
		// Called when there's new message to legacy network from XMPP network
 
		void sendMessage(boost::shared_ptr<Swift::Message> &message) {
 
		void sendMessage(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &message) {
 
			onMessageToSend(this, message);
 
		}
 

	
 
		boost::signal<void (NetworkConversation *, boost::shared_ptr<Swift::Message> &)> onMessageToSend;
 
		boost::signal<void (NetworkConversation *, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &)> onMessageToSend;
 
};
 

	
 
class NetworkFactory : public Factory {
 
	public:
 
		NetworkFactory(NetworkPluginServer *nps) {
 
			m_nps = nps;
 
		}
 

	
 
		virtual ~NetworkFactory() {}
 

	
 
		// Creates new conversation (NetworkConversation in this case)
 
		Conversation *createConversation(ConversationManager *conversationManager, const std::string &legacyName, bool isMuc) {
 
@@ -380,25 +380,25 @@ void NetworkPluginServer::start() {
 
		signal(SIGCHLD, SigCatcher);
 
#endif
 
		// quit the while loop
 
		break;
 
	}
 
}
 

	
 
void NetworkPluginServer::loginDelayFinished() {
 
	m_loginTimer->stop();
 
	connectWaitingUsers();
 
}
 

	
 
void NetworkPluginServer::handleNewClientConnection(boost::shared_ptr<Swift::Connection> c) {
 
void NetworkPluginServer::handleNewClientConnection(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> c) {
 
	// Create new Backend instance
 
	Backend *client = new Backend;
 
	client->pongReceived = -1;
 
	client->connection = c;
 
	client->res = 0;
 
	client->init_res = 0;
 
	client->shared = 0;
 
	// Until we receive first PONG from backend, backend is in willDie state.
 
	client->willDie = true;
 
	// Backend does not accept new clients automatically if it's long-running
 
	client->acceptUsers = !m_isNextLongRun;
 
	client->longRun = m_isNextLongRun;
 
@@ -486,25 +486,25 @@ void NetworkPluginServer::handleDisconnectedPayload(const std::string &data) {
 
	user->handleDisconnected(payload.message(), (Swift::SpectrumErrorPayload::Error) payload.error());
 
}
 

	
 
void NetworkPluginServer::handleVCardPayload(const std::string &data) {
 
	pbnetwork::VCard payload;
 
	if (payload.ParseFromString(data) == false) {
 
		std::cout << "PARSING ERROR\n";
 
		// TODO: ERROR
 
		return;
 
	}
 
	std::string field;
 

	
 
	boost::shared_ptr<Swift::VCard> vcard(new Swift::VCard());
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::VCard> vcard(new Swift::VCard());
 

	
 
	utf8::replace_invalid(payload.fullname().begin(), payload.fullname().end(), std::back_inserter(field), '_');
 
	vcard->setFullName(field);
 

	
 
	field.clear();
 

	
 
	utf8::replace_invalid(payload.nickname().begin(), payload.nickname().end(), std::back_inserter(field), '_');
 
	vcard->setNickname(field);
 

	
 
	vcard->setPhoto(Swift::createByteArray(payload.photo()));
 

	
 
	m_userManager->sendVCard(payload.id(), vcard);
 
@@ -550,26 +550,26 @@ void NetworkPluginServer::handleChatStatePayload(const std::string &data, Swift:
 
	User *user = m_userManager->getUser(payload.username());
 
	if (!user)
 
		return;
 

	
 
	// We're not creating new Conversation just because of chatstates.
 
	// Some networks/clients spams with chatstates a lot and it leads to bigger memory usage.
 
	NetworkConversation *conv = (NetworkConversation *) user->getConversationManager()->getConversation(payload.buddyname());
 
	if (!conv) {
 
		return;
 
	}
 

	
 
	// Forward chatstate
 
	boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	msg->addPayload(boost::make_shared<Swift::ChatState>(type));
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	msg->addPayload(SWIFTEN_SHRPTR_NAMESPACE::make_shared<Swift::ChatState>(type));
 

	
 
	conv->handleMessage(msg);
 
}
 

	
 
void NetworkPluginServer::handleBuddyChangedPayload(const std::string &data) {
 
	pbnetwork::Buddy payload;
 
	if (payload.ParseFromString(data) == false) {
 
		// TODO: ERROR
 
		return;
 
	}
 

	
 
	User *user = m_userManager->getUser(payload.username());
 
@@ -670,44 +670,44 @@ void NetworkPluginServer::handleConvMessagePayload(const std::string &data, bool
 
	}
 

	
 
	User *user = m_userManager->getUser(payload.username());
 
	if (!user) {
 
		LOG4CXX_ERROR(logger, "handleConvMessagePayload: unknown username " << payload.username());
 
		return;
 
	}
 

	
 
	// Message from legacy network triggers network acticity
 
	user->updateLastActivity();
 

	
 
	// Set proper body.
 
	boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	if (subject) {
 
		msg->setSubject(payload.message());
 
	}
 
	else {
 
		msg->setBody(payload.message());
 
	}
 

	
 
	if (payload.headline()) {
 
		msg->setType(Swift::Message::Headline);
 
	}
 

	
 
	// Add xhtml-im payload.
 
	if (CONFIG_BOOL(m_config, "service.enable_xhtml") && !payload.xhtml().empty()) {
 
		msg->addPayload(boost::make_shared<Swift::XHTMLIMPayload>(payload.xhtml()));
 
		msg->addPayload(SWIFTEN_SHRPTR_NAMESPACE::make_shared<Swift::XHTMLIMPayload>(payload.xhtml()));
 
	}
 

	
 
	if (!payload.timestamp().empty()) {
 
		boost::posix_time::ptime timestamp = boost::posix_time::from_iso_string(payload.timestamp());
 
		boost::shared_ptr<Swift::Delay> delay(boost::make_shared<Swift::Delay>());
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Delay> delay(SWIFTEN_SHRPTR_NAMESPACE::make_shared<Swift::Delay>());
 
		delay->setStamp(timestamp);
 
		msg->addPayload(delay);
 
	}
 

	
 
	NetworkConversation *conv = (NetworkConversation *) user->getConversationManager()->getConversation(payload.buddyname());
 

	
 
	// We can't create Conversation for payload with nickname, because this means the message is from room,
 
	// but this user is not in any room, so it's OK to just reject this message
 
	if (!conv && !payload.nickname().empty()) {
 
		LOG4CXX_WARN(logger, "handleConvMessagePayload: No conversation with name " << payload.buddyname());
 
		return;
 
	}
 
@@ -745,52 +745,52 @@ void NetworkPluginServer::handleConvMessageAckPayload(const std::string &data) {
 
		return;
 
	}
 

	
 
	User *user = m_userManager->getUser(payload.username());
 
	if (!user)
 
		return;
 

	
 
	if (payload.id().empty()) {
 
		LOG4CXX_WARN(logger, "Received message ack with empty ID, not forwarding to XMPP.");
 
		return;
 
	}
 

	
 
	boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	msg->addPayload(boost::make_shared<Swift::DeliveryReceipt>(payload.id()));
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	msg->addPayload(SWIFTEN_SHRPTR_NAMESPACE::make_shared<Swift::DeliveryReceipt>(payload.id()));
 

	
 
	NetworkConversation *conv = (NetworkConversation *) user->getConversationManager()->getConversation(payload.buddyname());
 

	
 
	// Receipts don't create conversation
 
	if (!conv) {
 
		return;
 
	}
 

	
 
	// Forward it
 
	conv->handleMessage(msg);
 
}
 

	
 
void NetworkPluginServer::handleAttentionPayload(const std::string &data) {
 
	pbnetwork::ConversationMessage payload;
 
	if (payload.ParseFromString(data) == false) {
 
		// TODO: ERROR
 
		return;
 
	}
 

	
 
	User *user = m_userManager->getUser(payload.username());
 
	if (!user)
 
		return;
 

	
 
	boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	msg->setBody(payload.message());
 
	msg->addPayload(boost::make_shared<Swift::AttentionPayload>());
 
	msg->addPayload(SWIFTEN_SHRPTR_NAMESPACE::make_shared<Swift::AttentionPayload>());
 

	
 
	// Attentions trigger new Conversation creation
 
	NetworkConversation *conv = (NetworkConversation *) user->getConversationManager()->getConversation(payload.buddyname());
 
	if (!conv) {
 
		conv = new NetworkConversation(user->getConversationManager(), payload.buddyname());
 
		user->getConversationManager()->addConversation(conv);
 
		conv->onMessageToSend.connect(boost::bind(&NetworkPluginServer::handleMessageReceived, this, _1, _2));
 
	}
 

	
 
	conv->handleMessage(msg);
 
}
 

	
 
@@ -822,25 +822,25 @@ void NetworkPluginServer::handleFTStartPayload(const std::string &data) {
 
	
 
	LocalBuddy *buddy = (LocalBuddy *) user->getRosterManager()->getBuddy(payload.buddyname());
 
	if (!buddy) {
 
		// TODO: escape? reject?
 
		return;
 
	}
 

	
 
	Swift::StreamInitiationFileInfo fileInfo;
 
	fileInfo.setSize(payload.size());
 
	fileInfo.setName(payload.filename());
 

	
 
	Backend *c = (Backend *) user->getData();
 
	boost::shared_ptr<MemoryReadBytestream> bytestream(new MemoryReadBytestream(payload.size()));
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<MemoryReadBytestream> bytestream(new MemoryReadBytestream(payload.size()));
 
	bytestream->onDataNeeded.connect(boost::bind(&NetworkPluginServer::handleFTDataNeeded, this, c, bytestream_id + 1));
 

	
 
	LOG4CXX_INFO(logger, "jid=" << buddy->getJID());
 

	
 
	FileTransferManager::Transfer transfer = m_ftManager->sendFile(user, buddy, bytestream, fileInfo);
 
	if (!transfer.ft) {
 
		handleFTRejected(user, payload.buddyname(), payload.filename(), payload.size());
 
		return;
 
	}
 

	
 
	m_filetransfers[++bytestream_id] = transfer;
 
#if !HAVE_SWIFTEN_3
 
@@ -957,25 +957,25 @@ void NetworkPluginServer::handlePongReceived(Backend *c) {
 

	
 
void NetworkPluginServer::handleQueryPayload(Backend *b, const std::string &data) {
 
	pbnetwork::BackendConfig payload;
 
	if (payload.ParseFromString(data) == false) {
 
		// TODO: ERROR
 
		return;
 
	}
 

	
 
	if (!m_adminInterface) {
 
		return;
 
	}
 

	
 
	boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	msg->setBody(payload.config());
 
	m_adminInterface->handleQuery(msg);
 

	
 
	pbnetwork::BackendConfig response;
 
#if HAVE_SWIFTEN_3
 
	response.set_config(msg->getBody().get_value_or(""));
 
#else
 
	response.set_config(msg->getBody());
 
#endif
 

	
 
	std::string message;
 
	response.SerializeToString(&message);
 
@@ -1013,29 +1013,29 @@ void NetworkPluginServer::handleRoomListPayload(const std::string &data) {
 
		for (int i = 0; i < payload.room_size() && i < payload.name_size(); i++) {
 
			user->addRoomToRoomList(Swift::JID::getEscapedNode(payload.room(i)) + "@" + m_component->getJID().toString(), payload.name(i));
 
		}
 
	}
 
	else {
 
		m_component->getFrontend()->clearRoomList();
 
		for (int i = 0; i < payload.room_size() && i < payload.name_size(); i++) {
 
			m_component->getFrontend()->addRoomToRoomList(Swift::JID::getEscapedNode(payload.room(i)) + "@" + m_component->getJID().toString(), payload.name(i));
 
		}
 
	}
 
}
 
#if HAVE_SWIFTEN_3
 
void NetworkPluginServer::handleElement(boost::shared_ptr<Swift::ToplevelElement> element) {
 
void NetworkPluginServer::handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::ToplevelElement> element) {
 
#else
 
void NetworkPluginServer::handleElement(boost::shared_ptr<Swift::Element> element) {
 
void NetworkPluginServer::handleElement(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Element> element) {
 
#endif
 
	boost::shared_ptr<Swift::Stanza> stanza = boost::dynamic_pointer_cast<Swift::Stanza>(element);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Stanza> stanza = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Swift::Stanza>(element);
 
	if (!stanza) {
 
		return;
 
	}
 

	
 
	User *user = m_userManager->getUser(stanza->getTo().toBare());
 
	if (!user)
 
		return;
 

	
 
	Swift::JID originalJID = stanza->getFrom();
 
	NetworkConversation *conv = (NetworkConversation *) user->getConversationManager()->getConversation(originalJID.toBare());
 

	
 
	LocalBuddy *buddy = (LocalBuddy *) user->getRosterManager()->getBuddy(stanza->getFrom().toBare());
 
@@ -1064,78 +1064,78 @@ void NetworkPluginServer::handleElement(boost::shared_ptr<Swift::Element> elemen
 
					name.replace(name.find_last_of("@"), 1, "%");
 
				}
 
			}
 
		}
 
		if (stanza->getFrom().getResource().empty()) {
 
			stanza->setFrom(Swift::JID(name, m_component->getJID().toString()));
 
		}
 
		else {
 
			stanza->setFrom(Swift::JID(name, m_component->getJID().toString(), stanza->getFrom().getResource()));
 
		}
 
	}
 

	
 
	boost::shared_ptr<Swift::Message> message = boost::dynamic_pointer_cast<Swift::Message>(stanza);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> message = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Swift::Message>(stanza);
 
	if (message) {
 
		if (conv) {
 
			conv->handleRawMessage(message);
 
			return;
 
		}
 

	
 
		m_component->getFrontend()->sendMessage(message);
 
		return;
 
	}
 

	
 
	boost::shared_ptr<Swift::Presence> presence = boost::dynamic_pointer_cast<Swift::Presence>(stanza);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Presence> presence = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Swift::Presence>(stanza);
 
	if (presence) {
 
		if (buddy) {
 
			if (!buddy->isAvailable() && presence->getType() != Swift::Presence::Unavailable) {
 
				buddy->m_status.setType(Swift::StatusShow::Online);
 
			}
 
			buddy->handleRawPresence(presence);
 
		}
 
		else if (conv) {
 
			conv->handleRawPresence(presence);
 
		}
 
		else {
 
			m_component->getFrontend()->sendPresence(presence);
 
		}
 

	
 
		return;
 
	}
 

	
 
	// TODO: Move m_id2resource in User and clean it up
 
	boost::shared_ptr<Swift::IQ> iq = boost::dynamic_pointer_cast<Swift::IQ>(stanza);
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::IQ> iq = SWIFTEN_SHRPTR_NAMESPACE::dynamic_pointer_cast<Swift::IQ>(stanza);
 
	if (iq) {
 
		if (m_id2resource.find(stanza->getTo().toBare().toString() + stanza->getID()) != m_id2resource.end()) {
 
			iq->setTo(Swift::JID(iq->getTo().getNode(), iq->getTo().getDomain(), m_id2resource[stanza->getTo().toBare().toString() + stanza->getID()]));
 
			m_id2resource.erase(stanza->getTo().toBare().toString() + stanza->getID());
 
		}
 
		else {
 
			Swift::Presence::ref highest = m_component->getPresenceOracle()->getHighestPriorityPresence(user->getJID());
 
			if (highest) {
 
			    iq->setTo(highest->getFrom());
 
			} else {
 
			    iq->setTo(user->getJID());
 
			}
 
		}
 
		m_component->getFrontend()->sendIQ(iq);
 
		return;
 
	}
 
}
 

	
 
void NetworkPluginServer::handleRawXML(const std::string &xml) {
 
	m_xmppParser->parse(xml);
 
}
 

	
 
void NetworkPluginServer::handleRawPresenceReceived(boost::shared_ptr<Swift::Presence> presence) {
 
void NetworkPluginServer::handleRawPresenceReceived(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Presence> presence) {
 
	if (!CONFIG_BOOL_DEFAULTED(m_config, "features.rawxml", false)) {
 
		return;
 
	}
 

	
 
	User *user = m_userManager->getUser(presence->getFrom().toBare());
 
	if (!user)
 
		return;
 

	
 
	Backend *c = (Backend *) user->getData();
 
	if (!c) {
 
		return;
 
	}
 
@@ -1144,25 +1144,25 @@ void NetworkPluginServer::handleRawPresenceReceived(boost::shared_ptr<Swift::Pre
 
	if (!presence->getTo().getResource().empty()) {
 
		presence->setTo(Swift::JID(legacyname.getNode(), legacyname.getDomain(), presence->getTo().getResource()));
 
	}
 
	else {
 
		presence->setTo(Swift::JID(legacyname.getNode(), legacyname.getDomain()));
 
	}
 

	
 
	std::string xml = safeByteArrayToString(m_serializer->serializeElement(presence));
 
	WRAP(xml, pbnetwork::WrapperMessage_Type_TYPE_RAW_XML);
 
	send(c->connection, xml);
 
}
 

	
 
void NetworkPluginServer::handleRawIQReceived(boost::shared_ptr<Swift::IQ> iq) {
 
void NetworkPluginServer::handleRawIQReceived(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::IQ> iq) {
 
	User *user = m_userManager->getUser(iq->getFrom().toBare());
 
	if (!user)
 
		return;
 

	
 
	Backend *c = (Backend *) user->getData();
 
	if (!c) {
 
		return;
 
	}
 

	
 
	if (iq->getType() == Swift::IQ::Get) {
 
		m_id2resource[iq->getFrom().toBare().toString() + iq->getID()] = iq->getFrom().getResource();
 
	}
 
@@ -1171,25 +1171,25 @@ void NetworkPluginServer::handleRawIQReceived(boost::shared_ptr<Swift::IQ> iq) {
 
	if (!iq->getTo().getResource().empty()) {
 
		iq->setTo(Swift::JID(legacyname.getNode(), legacyname.getDomain(), iq->getTo().getResource()));
 
	}
 
	else {
 
		iq->setTo(Swift::JID(legacyname.getNode(), legacyname.getDomain()));
 
	}
 

	
 
	std::string xml = safeByteArrayToString(m_serializer->serializeElement(iq));
 
	WRAP(xml, pbnetwork::WrapperMessage_Type_TYPE_RAW_XML);
 
	send(c->connection, xml);
 
}
 

	
 
void NetworkPluginServer::handleDataRead(Backend *c, boost::shared_ptr<Swift::SafeByteArray> data) {
 
void NetworkPluginServer::handleDataRead(Backend *c, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::SafeByteArray> data) {
 
	// Append data to buffer
 
	c->data.insert(c->data.end(), data->begin(), data->end());
 

	
 
	// Parse data while there are some
 
	while (c->data.size() != 0) {
 
		// expected_size of wrapper message
 
		unsigned int expected_size;
 

	
 
		// if data is >= 4, we have whole header and we can
 
		// read expected_size.
 
		if (c->data.size() >= 4) {
 
			expected_size = *((unsigned int*) &c->data[0]);
 
@@ -1291,25 +1291,25 @@ void NetworkPluginServer::handleDataRead(Backend *c, boost::shared_ptr<Swift::Sa
 
			case pbnetwork::WrapperMessage_Type_TYPE_CONV_MESSAGE_ACK:
 
				handleConvMessageAckPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_RAW_XML:
 
				handleRawXML(wrapper.payload());
 
				break;
 
			default:
 
				return;
 
		}
 
	}
 
}
 

	
 
void NetworkPluginServer::send(boost::shared_ptr<Swift::Connection> &c, const std::string &data) {
 
void NetworkPluginServer::send(SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Connection> &c, const std::string &data) {
 
	// generate header - size of wrapper message
 
	uint32_t size = htonl(data.size());
 
	char *header = (char *) &size;
 

	
 
	// send header together with wrapper message
 
	c->write(Swift::createSafeByteArray(std::string(header, 4) + data));
 
}
 

	
 
void NetworkPluginServer::pingTimeout() {
 
	LOG4CXX_INFO(logger, "Sending PING to backends");
 
	// TODO: move to separate timer, those 2 loops could be expensive
 
	// Some users are connected for weeks and they are blocking backend to be destroyed and its memory
 
@@ -1628,46 +1628,46 @@ void NetworkPluginServer::handleUserDestroyed(User *user) {
 
	}
 
	send(c->connection, message);
 
	c->users.remove(user);
 

	
 
	// If backend should handle only one user, it must not accept another one before 
 
	// we kill it, so set up willDie to true
 
	if (c->users.size() == 0 && CONFIG_INT(m_config, "service.users_per_backend") == 1) {
 
		LOG4CXX_INFO(logger, "Backend " << c->id << " will die, because the last user disconnected");
 
		c->willDie = true;
 
	}
 
}
 

	
 
void NetworkPluginServer::handleMessageReceived(NetworkConversation *conv, boost::shared_ptr<Swift::Message> &msg) {
 
void NetworkPluginServer::handleMessageReceived(NetworkConversation *conv, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::Message> &msg) {
 
	conv->getConversationManager()->getUser()->updateLastActivity();
 

	
 
	if (CONFIG_BOOL_DEFAULTED(m_config, "features.rawxml", false)) {
 
		Backend *c = (Backend *) conv->getConversationManager()->getUser()->getData();
 
		if (!c) {
 
			return;
 
		}
 
		Swift::JID legacyname = Swift::JID(Buddy::JIDToLegacyName(msg->getTo()));
 
		if (!msg->getTo().getResource().empty()) {
 
			msg->setTo(Swift::JID(legacyname.getNode(), legacyname.getDomain(), msg->getTo().getResource()));
 
		}
 
		else {
 
			msg->setTo(Swift::JID(legacyname.getNode(), legacyname.getDomain()));
 
		}
 
		std::string xml = safeByteArrayToString(m_serializer->serializeElement(msg));
 
		WRAP(xml, pbnetwork::WrapperMessage_Type_TYPE_RAW_XML);
 
		send(c->connection, xml);
 
		return;
 
	}
 

	
 
	boost::shared_ptr<Swift::ChatState> statePayload = msg->getPayload<Swift::ChatState>();
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::ChatState> statePayload = msg->getPayload<Swift::ChatState>();
 
	if (statePayload) {
 
		pbnetwork::WrapperMessage_Type type = pbnetwork::WrapperMessage_Type_TYPE_BUDDY_CHANGED;
 
		switch (statePayload->getChatState()) {
 
			case Swift::ChatState::Active:
 
				type = pbnetwork::WrapperMessage_Type_TYPE_BUDDY_STOPPED_TYPING;
 
				break;
 
			case Swift::ChatState::Composing:
 
				type = pbnetwork::WrapperMessage_Type_TYPE_BUDDY_TYPING;
 
				break;
 
			case Swift::ChatState::Paused:
 
				type = pbnetwork::WrapperMessage_Type_TYPE_BUDDY_TYPED;
 
				break;
 
@@ -1683,25 +1683,25 @@ void NetworkPluginServer::handleMessageReceived(NetworkConversation *conv, boost
 
			buddy.SerializeToString(&message);
 

	
 
			WRAP(message, type);
 

	
 
			Backend *c = (Backend *) conv->getConversationManager()->getUser()->getData();
 
			if (!c) {
 
				return;
 
			}
 
			send(c->connection, message);
 
		}
 
	}
 

	
 
	boost::shared_ptr<Swift::AttentionPayload> attentionPayload = msg->getPayload<Swift::AttentionPayload>();
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::AttentionPayload> attentionPayload = msg->getPayload<Swift::AttentionPayload>();
 
	if (attentionPayload) {
 
		pbnetwork::ConversationMessage m;
 
		m.set_username(conv->getConversationManager()->getUser()->getJID().toBare());
 
		m.set_buddyname(conv->getLegacyName());
 
#if HAVE_SWIFTEN_3
 
		m.set_message(msg->getBody().get_value_or(""));
 
#else
 
		m.set_message(msg->getBody());
 
#endif
 

	
 
		std::string message;
 
		m.SerializeToString(&message);
 
@@ -1722,42 +1722,42 @@ void NetworkPluginServer::handleMessageReceived(NetworkConversation *conv, boost
 
		std::string message;
 
		m.SerializeToString(&message);
 

	
 
		WRAP(message, pbnetwork::WrapperMessage_Type_TYPE_ROOM_SUBJECT_CHANGED);
 

	
 
		Backend *c = (Backend *) conv->getConversationManager()->getUser()->getData();
 
		send(c->connection, message);
 
		return;
 
	}
 
	
 

	
 
	std::string xhtml;
 
	boost::shared_ptr<Swift::XHTMLIMPayload> xhtmlPayload = msg->getPayload<Swift::XHTMLIMPayload>();
 
	SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::XHTMLIMPayload> xhtmlPayload = msg->getPayload<Swift::XHTMLIMPayload>();
 
	if (xhtmlPayload) {
 
		xhtml = xhtmlPayload->getBody();
 
	}
 

	
 
	// Send normal message
 
#if HAVE_SWIFTEN_3
 
	std::string body = msg->getBody().get_value_or("");
 
#else
 
	std::string body = msg->getBody();
 
#endif
 
	if (!body.empty() || !xhtml.empty()) {
 
		pbnetwork::ConversationMessage m;
 
		m.set_username(conv->getConversationManager()->getUser()->getJID().toBare());
 
		m.set_buddyname(conv->getLegacyName());
 
		m.set_message(body);
 
		m.set_xhtml(xhtml);
 
		boost::shared_ptr<Swift::DeliveryReceiptRequest> receiptPayload = msg->getPayload<Swift::DeliveryReceiptRequest>();
 
		SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::DeliveryReceiptRequest> receiptPayload = msg->getPayload<Swift::DeliveryReceiptRequest>();
 
		if (receiptPayload && !msg->getID().empty()) {
 
			m.set_id(msg->getID());
 
		}
 

	
 
		std::string message;
 
		m.SerializeToString(&message);
 

	
 
		WRAP(message, pbnetwork::WrapperMessage_Type_TYPE_CONV_MESSAGE);
 

	
 
		Backend *c = (Backend *) conv->getConversationManager()->getUser()->getData();
 
		if (!c) {
 
			return;
 
@@ -1864,25 +1864,25 @@ void NetworkPluginServer::handleBlockToggled(Buddy *b) {
 
	buddy.SerializeToString(&message);
 

	
 
	WRAP(message, pbnetwork::WrapperMessage_Type_TYPE_BUDDY_CHANGED);
 

	
 
	Backend *c = (Backend *) user->getData();
 
	if (!c) {
 
		return;
 
	}
 
	send(c->connection, message);
 
}
 

	
 

	
 
void NetworkPluginServer::handleVCardUpdated(User *user, boost::shared_ptr<Swift::VCard> v) {
 
void NetworkPluginServer::handleVCardUpdated(User *user, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::VCard> v) {
 
	if (!v) {
 
		LOG4CXX_INFO(logger, user->getJID().toString() << ": Received empty VCard");
 
		return;
 
	}
 

	
 
	pbnetwork::VCard vcard;
 
	vcard.set_username(user->getJID().toBare());
 
	vcard.set_buddyname("");
 
	vcard.set_id(0);
 
	vcard.set_photo(&v->getPhoto()[0], v->getPhoto().size());
 
	vcard.set_nickname(v->getNickname());
 

	
libtransport/PQXXBackend.cpp
Show inline comments
 
@@ -17,25 +17,24 @@
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#ifdef WITH_PQXX
 

	
 
#include "transport/PQXXBackend.h"
 
#include "transport/Util.h"
 
#include <boost/bind.hpp>
 
#include "log4cxx/logger.h"
 

	
 
using namespace log4cxx;
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
static LoggerPtr logger = Logger::getLogger("PQXXBackend");
 

	
 
PQXXBackend::PQXXBackend(Config *config) {
 
	m_config = config;
 
	m_prefix = CONFIG_STRING(m_config, "database.prefix");
 
}
 

	
 
PQXXBackend::~PQXXBackend(){
 
	disconnect();
libtransport/PresenceOracle.cpp
Show inline comments
 
@@ -37,48 +37,48 @@ PresenceOracle::PresenceOracle(Frontend* frontend) {
 
PresenceOracle::~PresenceOracle() {
 
	frontend_->onPresenceReceived.disconnect(boost::bind(&PresenceOracle::handleIncomingPresence, this, _1));
 
	frontend_->onAvailableChanged.disconnect(boost::bind(&PresenceOracle::handleStanzaChannelAvailableChanged, this, _1));
 
}
 

	
 
void PresenceOracle::handleStanzaChannelAvailableChanged(bool available) {
 
	if (available) {
 
		entries_.clear();
 
	}
 
}
 

	
 
void PresenceOracle::clearPresences(const Swift::JID& bareJID) {
 
	std::map<JID, boost::shared_ptr<Presence> > jidMap = entries_[bareJID];
 
	std::map<JID, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Presence> > jidMap = entries_[bareJID];
 
	jidMap.clear();
 
	entries_[bareJID] = jidMap;
 
}
 

	
 
void PresenceOracle::handleIncomingPresence(Presence::ref presence) {
 
	// ignore presences for some contact, we're checking only presences for the transport itself here.
 
	// filter out login/logout presence spam
 
	if (!presence->getTo().getNode().empty())
 
		return;
 

	
 
	JID bareJID(presence->getFrom().toBare());
 
	if (presence->getType() == Presence::Subscribe || presence->getType() == Presence::Subscribed) {
 
	}
 
	else {
 
		Presence::ref passedPresence = presence;
 
		if (presence->getType() == Presence::Unsubscribe || presence->getType() == Presence::Unsubscribed) {
 
			/* 3921bis says that we don't follow up with an unavailable, so simulate this ourselves */
 
			passedPresence = Presence::ref(new Presence());
 
			passedPresence->setType(Presence::Unavailable);
 
			passedPresence->setFrom(bareJID);
 
			passedPresence->setStatus(presence->getStatus());
 
		}
 
		std::map<JID, boost::shared_ptr<Presence> > jidMap = entries_[bareJID];
 
		std::map<JID, SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Presence> > jidMap = entries_[bareJID];
 
		if (passedPresence->getFrom().isBare() && presence->getType() == Presence::Unavailable) {
 
			/* Have a bare-JID only presence of offline */
 
			jidMap.clear();
 
		} else if (passedPresence->getType() == Presence::Available) {
 
			/* Don't have a bare-JID only offline presence once there are available presences */
 
			jidMap.erase(bareJID);
 
		}
 
		if (passedPresence->getType() == Presence::Unavailable && jidMap.size() > 1) {
 
			jidMap.erase(passedPresence->getFrom());
 
		} else {
 
			jidMap[passedPresence->getFrom()] = passedPresence;
 
		}
libtransport/RosterManager.cpp
Show inline comments
 
@@ -103,25 +103,25 @@ void RosterManager::sendBuddyUnsubscribePresence(Buddy *buddy) {
 
	response->setTo(m_user->getJID());
 
	response->setFrom(buddy->getJID());
 
	response->setType(Swift::Presence::Unsubscribed);
 
	m_component->getFrontend()->sendPresence(response);
 
}
 

	
 
void RosterManager::sendBuddySubscribePresence(Buddy *buddy) {
 
	Swift::Presence::ref response = Swift::Presence::create();
 
	response->setTo(m_user->getJID());
 
	response->setFrom(buddy->getJID().toBare());
 
	response->setType(Swift::Presence::Subscribe);
 
	if (!buddy->getAlias().empty()) {
 
		response->addPayload(boost::make_shared<Swift::Nickname>(buddy->getAlias()));
 
		response->addPayload(SWIFTEN_SHRPTR_NAMESPACE::make_shared<Swift::Nickname>(buddy->getAlias()));
 
	}
 
	m_component->getFrontend()->sendPresence(response);
 
}
 

	
 
void RosterManager::handleBuddyChanged(Buddy *buddy) {
 
}
 

	
 
void RosterManager::setBuddy(Buddy *buddy) {
 
	std::string name = buddy->getName();
 
	name = boost::locale::to_lower(name);
 
	LOG4CXX_INFO(logger, "Associating buddy " << name << " with " << m_user->getJID().toString());
 
	m_buddies[name] = buddy;
libtransport/SQLite3Backend.cpp
Show inline comments
 
@@ -52,26 +52,24 @@
 
							(void)STATEMENT##_id_get;
 

	
 
#define BIND_INT(STATEMENT, VARIABLE) sqlite3_bind_int(STATEMENT, STATEMENT##_id++, VARIABLE)
 
#define BIND_STR(STATEMENT, VARIABLE) sqlite3_bind_text(STATEMENT, STATEMENT##_id++, VARIABLE.c_str(), -1, SQLITE_STATIC)
 
#define RESET_GET_COUNTER(STATEMENT)	STATEMENT##_id_get = 0;
 
#define GET_INT(STATEMENT)	sqlite3_column_int(STATEMENT, STATEMENT##_id_get++)
 
#define GET_STR(STATEMENT)	(const char *) sqlite3_column_text(STATEMENT, STATEMENT##_id_get++)
 
#define GET_BLOB(STATEMENT)	(const void *) sqlite3_column_blob(STATEMENT, STATEMENT##_id_get++)
 
#define EXECUTE_STATEMENT(STATEMENT, NAME) 	if(sqlite3_step(STATEMENT) != SQLITE_DONE) {\
 
		LOG4CXX_ERROR(logger, NAME<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));\
 
			}
 

	
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "SQLite3Backend");
 

	
 
SQLite3Backend::SQLite3Backend(Config *config) {
 
	m_config = config;
 
	m_db = NULL;
 
	m_prefix = CONFIG_STRING(m_config, "database.prefix");
 
}
 

	
 
SQLite3Backend::~SQLite3Backend(){
 
	if (m_db) {
libtransport/ThreadPool.cpp
Show inline comments
 
#include "transport/ThreadPool.h"
 
#include "transport/Logging.h"
 

	
 
#include "Swiften/SwiftenCompat.h"
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "ThreadPool")
 
boost::signals2::signal< void (Thread*, int) > onWorkCompleted;
 

	
 
static void Worker(Thread *t, int wid, Swift::EventLoop *loop)
 
{
 
	LOG4CXX_INFO(logger, "Starting thread " << wid)
 
	t->run();
 
	loop->postEvent(boost::bind(boost::ref(onWorkCompleted), t, wid), boost::shared_ptr<Swift::EventOwner>());
 
	loop->postEvent(boost::bind(boost::ref(onWorkCompleted), t, wid), SWIFTEN_SHRPTR_NAMESPACE::shared_ptr<Swift::EventOwner>());
 
}
 

	
 

	
 
ThreadPool::ThreadPool(Swift::EventLoop *loop, int maxthreads) : MAX_THREADS(maxthreads)
 
{
 
	this->loop = loop;
 
	activeThreads = 0;
 
	worker = (boost::thread **) malloc(sizeof(boost::thread *) * MAX_THREADS);
 
	for(int i=0 ; i<MAX_THREADS ; i++) {
 
		worker[i] = NULL;
 
		freeThreads.push(i);
 
	}

Changeset was too big and was cut off... Show full diff anyway

0 comments (0 inline, 0 general)