Changeset - f4b6ded08443
backends/frotz/CMakeLists.txt
Show inline comments
 
cmake_minimum_required(VERSION 2.6)
 
 
ADD_SUBDIRECTORY(dfrotz)
 
 
FILE(GLOB SRC *.c *.cpp)
 
 
ADD_EXECUTABLE(spectrum2_frotz_backend ${SRC})
 
 
target_link_libraries(spectrum2_frotz_backend transport pthread transport-plugin)
 
target_link_libraries(spectrum2_frotz_backend transport pthread transport-plugin ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
 
 
INSTALL(TARGETS spectrum2_frotz_backend RUNTIME DESTINATION bin)
 
backends/frotz/main.cpp
Show inline comments
 
@@ -137,26 +137,45 @@ static void start_dfrotz(dfrotz &p, const std::string &game) {
 

	
 
		execlp("dfrotz", "-p", game.c_str(), NULL);
 

	
 
	}
 
	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;
 

	
 
		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) {
 
			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);
 
			np->handleBuddyChanged(user, "zcode", "ZCode", "ZCode", pbnetwork::STATUS_ONLINE);
 
// 			sleep(1);
 
// 			np->handleMessage(np->m_user, "zork", first_msg);
 
		}
 

	
 
		void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
 
			if (games.find(user) != games.end()) {
 
				kill(games[user].pid, SIGTERM);
 
@@ -211,25 +230,26 @@ class FrotzNetworkPlugin : public NetworkPlugin {
 
		std::vector<std::string> getGames() {
 
			std::vector<std::string> games;
 
			path p(".");
 
			directory_iterator end_itr;
 
			for (directory_iterator itr(p); itr != end_itr; ++itr) {
 
				if (extension(itr->path()) == ".z5") {
 
					games.push_back(itr->path().leaf());
 
				}
 
			}
 
			return games;
 
		}
 

	
 
		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &/*xhtml*/) {
 
		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml = "") {
 
			std::cout << "aaa\n";
 
			if (message.find("start") == 0) {
 
				std::string game = message.substr(6);
 
				std::vector<std::string> lst = getGames();
 
				if (std::find(lst.begin(), lst.end(), game) == lst.end()) {
 
					np->handleMessage(user, "zcode", "Unknown game");
 
					return;
 
				}
 
				np->handleMessage(user, "zcode", "Starting the game");
 

	
 
				dfrotz d;
 
				d.game = game;
 
				start_dfrotz(d, game);
backends/libpurple/main.cpp
Show inline comments
 
@@ -491,65 +491,66 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
 

	
 
			if (!KEYFILE_STRING("backend", "default_avatar").empty() && !ret) {
 
				ret = g_file_get_contents (KEYFILE_STRING("backend", "default_avatar").c_str(),
 
											&contents, &length, NULL);
 
			}
 

	
 
			if (ret) {
 
				purple_buddy_icons_set_account_icon(account, (guchar *) contents, length);
 
			}
 
		}
 

	
 
		void setDefaultAccountOptions(PurpleAccount *account) {
 
// 			for (std::map<std::string,std::string>::const_iterator it = config->getUnregistered().begin();
 
// 				it != config->getUnregistered().end(); it++) {
 
// 				if ((*it).first.find("purple.") == 0) {
 
// 					std::string key = (*it).first.substr((*it).first.find(".") + 1);
 
// 
 
// 					PurplePlugin *plugin = purple_find_prpl(purple_account_get_protocol_id(account));
 
// 					PurplePluginProtocolInfo *prpl_info = PURPLE_PLUGIN_PROTOCOL_INFO(plugin);
 
// 					bool found = false;
 
// 					for (GList *l = prpl_info->protocol_options; l != NULL; l = l->next) {
 
// 						PurpleAccountOption *option = (PurpleAccountOption *) l->data;
 
// 						PurplePrefType type = purple_account_option_get_type(option);
 
// 						std::string key2(purple_account_option_get_setting(option));
 
// 						std::cout << key << " " << key2 << " " << (*it).second << "\n";
 
// 						if (key != key2)
 
// 							continue;
 
// 						
 
// 						found = true;
 
// 						switch (type) {
 
// 							case PURPLE_PREF_BOOLEAN:
 
// 								purple_account_set_bool(account, key.c_str(), fromString<bool>((*it).second));
 
// 								break;
 
// 
 
// 							case PURPLE_PREF_INT:
 
// 								purple_account_set_int(account, key.c_str(), fromString<int>((*it).second));
 
// 								break;
 
// 
 
// 							case PURPLE_PREF_STRING:
 
// 							case PURPLE_PREF_STRING_LIST:
 
// 								purple_account_set_string(account, key.c_str(), (*it).second.c_str());
 
// 								break;
 
// 							default:
 
// 								continue;
 
// 						}
 
// 						break;
 
// 					}
 
// 
 
// 					if (!found) {
 
// 						purple_account_set_string(account, key.c_str(), (*it).second.c_str());
 
// 					}
 
// 				}
 
// 			}
 
			int i = 0;
 
			gchar **keys = g_key_file_get_keys (keyfile, "purple", NULL, NULL);
 
			while (keys && keys[i] != NULL) {
 
				std::string key = keys[i];
 

	
 
				PurplePlugin *plugin = purple_find_prpl(purple_account_get_protocol_id(account));
 
				PurplePluginProtocolInfo *prpl_info = PURPLE_PLUGIN_PROTOCOL_INFO(plugin);
 
				bool found = false;
 
				for (GList *l = prpl_info->protocol_options; l != NULL; l = l->next) {
 
					PurpleAccountOption *option = (PurpleAccountOption *) l->data;
 
					PurplePrefType type = purple_account_option_get_type(option);
 
					std::string key2(purple_account_option_get_setting(option));
 
					if (key != key2) {
 
						continue;
 
					}
 
					
 
					found = true;
 
					switch (type) {
 
						case PURPLE_PREF_BOOLEAN:
 
							purple_account_set_bool(account, key.c_str(), fromString<bool>(KEYFILE_STRING("purple", key)));
 
							break;
 

	
 
						case PURPLE_PREF_INT:
 
							purple_account_set_int(account, key.c_str(), fromString<int>(KEYFILE_STRING("purple", key)));
 
							break;
 

	
 
						case PURPLE_PREF_STRING:
 
						case PURPLE_PREF_STRING_LIST:
 
							purple_account_set_string(account, key.c_str(), KEYFILE_STRING("purple", key).c_str());
 
							break;
 
						default:
 
							continue;
 
					}
 
					break;
 
				}
 

	
 
				if (!found) {
 
					purple_account_set_string(account, key.c_str(), KEYFILE_STRING("purple", key).c_str());
 
				}
 
				i++;
 
			}
 
			g_strfreev (keys);
 
		}
 

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
			PurpleAccount *account = NULL;
 
			
 
			std::string name;
 
			std::string protocol;
 
			getProtocolAndName(legacyName, name, protocol);
 

	
 
			if (password.empty()) {
 
				np->handleDisconnected(user, 0, "Empty password.");
 
				return;
 
@@ -725,25 +726,24 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
 
			}
 
		}
 

	
 
		void handleVCardRequest(const std::string &user, const std::string &legacyName, unsigned int id) {
 
			PurpleAccount *account = m_sessions[user];
 
			if (account) {
 
				std::string name = legacyName;
 
				if (KEYFILE_STRING("service", "protocol") == "any" && legacyName.find("prpl-") == 0) {
 
					name = name.substr(name.find(".") + 1);
 
				}
 
				m_vcards[user + name] = id;
 

	
 
				std::cout << name << " " << purple_account_get_username(account) << "\n";
 
				if (KEYFILE_BOOL("backend", "no_vcard_fetch") && name != purple_account_get_username(account)) {
 
					PurpleNotifyUserInfo *user_info = purple_notify_user_info_new();
 
					notify_user_info(purple_account_get_connection(account), name.c_str(), user_info);
 
					purple_notify_user_info_destroy(user_info);
 
				}
 
				else {
 
					serv_get_info(purple_account_get_connection(account), name.c_str());
 
				}
 
				
 
			}
 
		}
 

	
 
@@ -1007,25 +1007,25 @@ static std::vector<std::string> getGroups(PurpleBuddy *m_buddy) {
 
	std::vector<std::string> groups;
 
	groups.push_back((purple_buddy_get_group(m_buddy) && purple_group_get_name(purple_buddy_get_group(m_buddy))) ? std::string(purple_group_get_name(purple_buddy_get_group(m_buddy))) : std::string("Buddies"));
 
	return groups;
 
}
 

	
 
static void buddyListNewNode(PurpleBlistNode *node) {
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY(node))
 
		return;
 
	PurpleBuddy *buddy = (PurpleBuddy *) node;
 
	PurpleAccount *account = purple_buddy_get_account(buddy);
 

	
 
	// Status
 
	pbnetwork::StatusType status;
 
	pbnetwork::StatusType status = pbnetwork::STATUS_NONE;
 
	std::string message;
 
	getStatus(buddy, status, message);
 

	
 
	// Tooltip
 
	PurplePlugin *prpl = purple_find_prpl(purple_account_get_protocol_id(account));
 
	PurplePluginProtocolInfo *prpl_info = PURPLE_PLUGIN_PROTOCOL_INFO(prpl);
 

	
 
	bool blocked = false;
 
	if (KEYFILE_BOOL("service", "enable_privacy_lists")) {
 
		if (prpl_info && prpl_info->tooltip_text) {
 
			PurpleNotifyUserInfo *user_info = purple_notify_user_info_new();
 
			prpl_info->tooltip_text(buddy, user_info, true);
 
@@ -1061,25 +1061,24 @@ static void buddyListNewNode(PurpleBlistNode *node) {
 
	np->handleBuddyChanged(np->m_accounts[account], purple_buddy_get_name(buddy), getAlias(buddy), getGroups(buddy)[0], status, message, getIconHash(buddy),
 
		blocked
 
	);
 
}
 

	
 
static void buddyListUpdate(PurpleBuddyList *list, PurpleBlistNode *node) {
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY(node))
 
		return;
 
	buddyListNewNode(node);
 
}
 

	
 
static void buddyPrivacyChanged(PurpleBlistNode *node, void *data) {
 
	std::cout << "PRIVACY CHANGED\n";
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY(node))
 
		return;
 
	buddyListUpdate(NULL, node);
 
}
 

	
 
static void NodeRemoved(PurpleBlistNode *node, void *data) {
 
	if (!PURPLE_BLIST_NODE_IS_BUDDY(node))
 
		return;
 
// 	PurpleBuddy *buddy = (PurpleBuddy *) node;
 
}
 

	
 
static PurpleBlistUiOps blistUiOps =
 
@@ -1250,25 +1249,24 @@ static void *notify_user_info(PurpleConnection *gc, const char *who, PurpleNotif
 
		}
 
		vcardEntries = vcardEntries->next;
 
	}
 

	
 
	if ((!firstName.empty() || !lastName.empty()) && fullName.empty())
 
		fullName = firstName + " " + lastName;
 

	
 
	if (nickname.empty() && !fullName.empty()) {
 
		nickname = fullName;
 
	}
 

	
 
	bool ownInfo = name == purple_account_get_username(account);
 
	std::cout << "RECEIVED " << name << " " << purple_account_get_username(account) << "\n";
 

	
 
	if (ownInfo) {
 
		const gchar *displayname = purple_connection_get_display_name(gc);
 
		if (!displayname) {
 
			displayname = purple_account_get_name_for_display(account);
 
		}
 

	
 
		if (displayname && nickname.empty()) {
 
			nickname = displayname;
 
		}
 

	
 
		// avatar
 
@@ -1691,33 +1689,38 @@ static void spectrum_sigchld_handler(int sig)
 
	do {
 
		pid = waitpid(-1, &status, WNOHANG);
 
	} while (pid != 0 && pid != (pid_t)-1);
 

	
 
	if ((pid == (pid_t) - 1) && (errno != ECHILD)) {
 
		char errmsg[BUFSIZ];
 
		snprintf(errmsg, BUFSIZ, "Warning: waitpid() returned %d", pid);
 
		perror(errmsg);
 
	}
 
}
 

	
 
static void transportDataReceived(gpointer data, gint source, PurpleInputCondition cond) {
 
	char buffer[65535];
 
	char *ptr = buffer;
 
	ssize_t n = read(source, ptr, sizeof(buffer));
 
	if (n <= 0) {
 
		LOG4CXX_INFO(logger, "Diconnecting from spectrum2 server");
 
		exit(errno);
 
	if (cond & PURPLE_INPUT_READ) {
 
		char buffer[65535];
 
		char *ptr = buffer;
 
		ssize_t n = read(source, ptr, sizeof(buffer));
 
		if (n <= 0) {
 
			LOG4CXX_INFO(logger, "Diconnecting from spectrum2 server");
 
			exit(errno);
 
		}
 
		std::string d = std::string(buffer, n);
 
		np->handleDataRead(d);
 
	}
 
	else {
 
		np->readyForData();
 
	}
 
	std::string d = std::string(buffer, n);
 
	np->handleDataRead(d);
 
}
 

	
 
int main(int argc, char **argv) {
 
	GError *error = NULL;
 
	GOptionContext *context;
 
	context = g_option_context_new("config_file_name or profile name");
 
	g_option_context_add_main_entries(context, options_entries, "");
 
	if (!g_option_context_parse (context, &argc, &argv, &error)) {
 
		std::cout << "option parsing failed: " << error->message << "\n";
 
		return -1;
 
	}
 

	
 
@@ -1812,24 +1815,25 @@ int main(int argc, char **argv) {
 
		serv_addr.sin_addr.s_addr = *((unsigned long *) hos->h_addr_list[0]);
 

	
 
		if (connect(m_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
 
			close(m_sock);
 
			m_sock = 0;
 
		}
 

	
 
		int flags = fcntl(m_sock, F_GETFL);
 
		flags |= O_NONBLOCK;
 
		fcntl(m_sock, F_SETFL, flags);
 

	
 
		purple_input_add(m_sock, PURPLE_INPUT_READ, &transportDataReceived, NULL);
 
// 		purple_input_add(m_sock, PURPLE_INPUT_WRITE, &transportDataReceived, NULL);
 

	
 
		np = new SpectrumNetworkPlugin(host, port);
 
		bool libev = KEYFILE_STRING("service", "eventloop") == "libev";
 

	
 
		GMainLoop *m_loop;
 
#ifdef WITH_LIBEVENT
 
		if (!libev) {
 
			m_loop = g_main_loop_new(NULL, FALSE);
 
		}
 
		else {
 
			event_init();
 
		}
cmake_modules/SwiftenConfig.cmake
Show inline comments
 
FIND_LIBRARY(SWIFTEN_LIBRARY NAMES Swiften)
 
FIND_PATH(SWIFTEN_INCLUDE_DIR NAMES "Swiften.h" PATH_SUFFIXES libSwiften Swiften )
 

	
 
if( SWIFTEN_LIBRARY AND SWIFTEN_INCLUDE_DIR )
 
	find_program(SWIFTEN_CONFIG_EXECUTABLE NAMES swiften-config DOC "swiften-config executable")
 
	set( SWIFTEN_CFLAGS "" )
 
	if (SWIFTEN_CONFIG_EXECUTABLE)
 
		execute_process(
 
			COMMAND swiften-config --libs
 
			COMMAND SWIFTEN_CONFIG_EXECUTABLE --libs
 
			OUTPUT_VARIABLE SWIFTEN_LIBRARY)
 
		string(REGEX REPLACE "[\r\n]"                  " " SWIFTEN_LIBRARY "${SWIFTEN_LIBRARY}")
 
		string(REGEX REPLACE " +$"                     ""  SWIFTEN_LIBRARY "${SWIFTEN_LIBRARY}")
 
	else()
 
		message( FATAL_ERROR "Could NOT find swiften-config" )
 
	endif()
 

	
 
	set( SWIFTEN_INCLUDE_DIR ${SWIFTEN_INCLUDE_DIR}/.. )
 
	message( STATUS "Found libSwiften: ${SWIFTEN_LIBRARY}, ${SWIFTEN_INCLUDE_DIR}")
 
	set( SWIFTEN_FOUND 1 )
 
else( SWIFTEN_LIBRARY AND SWIFTEN_INCLUDE_DIR )
 
    message( FATAL_ERROR "Could NOT find libSwiften" )
include/Swiften/Network/DummyNetworkFactories.cpp
Show inline comments
 
@@ -8,22 +8,24 @@
 
#include <Swiften/Network/DummyTimerFactory.h>
 
#include <Swiften/Network/DummyConnectionFactory.h>
 
#include <Swiften/Network/PlatformDomainNameResolver.h>
 
#include <Swiften/Network/DummyConnectionServerFactory.h>
 

	
 
namespace Swift {
 

	
 
DummyNetworkFactories::DummyNetworkFactories(EventLoop* eventLoop) {
 
	timerFactory = new DummyTimerFactory();
 
	connectionFactory = new DummyConnectionFactory(eventLoop);
 
	domainNameResolver = new PlatformDomainNameResolver(eventLoop);
 
	connectionServerFactory = new DummyConnectionServerFactory(eventLoop);
 
	m_platformXMLParserFactory =  new PlatformXMLParserFactory();
 
}
 

	
 
DummyNetworkFactories::~DummyNetworkFactories() {
 
	delete connectionServerFactory;
 
	delete domainNameResolver;
 
	delete connectionFactory;
 
	delete timerFactory;
 
	delete m_platformXMLParserFactory;
 
}
 

	
 
}
include/Swiften/Network/DummyNetworkFactories.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/Network/NetworkFactories.h>
 
#include <Swiften/Parser/PlatformXMLParserFactory.h>
 

	
 
namespace Swift {
 
	class EventLoop;
 

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

	
 
			virtual TimerFactory* getTimerFactory() const {
 
				return timerFactory;
 
			}
 
@@ -28,22 +29,31 @@ namespace Swift {
 
				return domainNameResolver;
 
			}
 

	
 
			ConnectionServerFactory* getConnectionServerFactory() const {
 
				return connectionServerFactory;
 
			}
 

	
 
			virtual Swift::NATTraverser* getNATTraverser() const {
 
				return 0;
 
			}
 

	
 
			Swift::XMLParserFactory* getXMLParserFactory() const {
 
				return 0;
 
				return m_platformXMLParserFactory;
 
			}
 

	
 
            Swift::TLSContextFactory* getTLSContextFactory() const {
 
                return 0;
 
            }
 

	
 
            Swift::ProxyProvider* getProxyProvider() const {
 
                return 0;
 
            }
 

	
 
		private:
 
			PlatformXMLParserFactory *m_platformXMLParserFactory;
 
			TimerFactory* timerFactory;
 
			ConnectionFactory* connectionFactory;
 
			DomainNameResolver* domainNameResolver;
 
			ConnectionServerFactory* connectionServerFactory;
 
	};
 
}
include/Swiften/Server/ServerFromClientSession.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/ServerFromClientSession.h>
 

	
 
#include <boost/bind.hpp>
 

	
 
#include <Swiften/Elements/ProtocolHeader.h>
 
#include <Swiften/Elements/StreamError.h>
 
#include <Swiften/Elements/Message.h>
 
#include <Swiften/Server/UserRegistry.h>
 
#include <Swiften/Network/Connection.h>
 
#include <Swiften/StreamStack/XMPPLayer.h>
 
#include <Swiften/Elements/StreamFeatures.h>
 
#include <Swiften/Elements/ResourceBind.h>
 
#include <Swiften/Elements/StartSession.h>
 
#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>
 
@@ -25,52 +27,59 @@
 
#include <Swiften/Elements/StartTLSRequest.h>
 
#include <Swiften/Elements/TLSProceed.h>
 
#include <iostream>
 

	
 
namespace Swift {
 

	
 
ServerFromClientSession::ServerFromClientSession(
 
		const std::string& id,
 
		boost::shared_ptr<Connection> connection, 
 
		PayloadParserFactoryCollection* payloadParserFactories, 
 
		PayloadSerializerCollection* payloadSerializers,
 
		UserRegistry* userRegistry,
 
		XMLParserFactory* factory) : 
 
		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()));
 
		authenticated_ = true;
 
		getXMPPLayer()->resetParser();
 
	}
 
}
 

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

	
 
void ServerFromClientSession::handleElement(boost::shared_ptr<Element> element) {
 
	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") {
include/Swiften/Server/ServerFromClientSession.h
Show inline comments
 
@@ -30,41 +30,42 @@ namespace Swift {
 
	class TLSServerLayer;
 
	class TLSServerContextFactory;
 
	class PKCS12Certificate;
 

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

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

	
 
			void addTLSEncryption(TLSServerContextFactory* tlsContextFactory, const PKCS12Certificate& cert);
 

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

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

	
 
		private:
 
			void handleElement(boost::shared_ptr<Element>);
 
			void handleStreamStart(const ProtocolHeader& header);
 
			void handleSessionFinished(const boost::optional<SessionError>&);
 

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

	
 
			void handleTLSError() { }
include/Swiften/Server/ServerStanzaChannel.cpp
Show inline comments
 
@@ -20,25 +20,24 @@ namespace {
 
// 	};
 

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

	
 
void ServerStanzaChannel::addSession(boost::shared_ptr<ServerFromClientSession> session) {
 
	std::cout << "ADDING SESSION\n";
 
	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));
 
}
 

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

	
include/transport/CMakeLists.txt
Show inline comments
 
if (PROTOBUF_FOUND)
 
	add_custom_target(pb
 
		${PROTOBUF_PROTOC_EXECUTABLE}
 
		--cpp_out  ${CMAKE_CURRENT_BINARY_DIR} --proto_path ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}/protocol.proto
 
		COMMENT "Running C++ protocol buffer compiler on protocol.proto"
 
		DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/protocol.proto
 
		VERBATIM )
 
    ADD_CUSTOM_COMMAND(
 
        OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/protocol.pb.cc ${CMAKE_CURRENT_BINARY_DIR}/protocol.pb.h
 
        COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} --cpp_out  ${CMAKE_CURRENT_BINARY_DIR} --proto_path ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}/protocol.proto
 
        COMMENT "Running C++ protocol buffer compiler on protocol.proto"
 
        DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/protocol.proto
 
    )
 
    ADD_CUSTOM_TARGET(pb DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/protocol.pb.cc)
 
endif()
 

	
 
FILE(GLOB HEADERS *.h protocol.h)
 

	
 
INSTALL(FILES ${HEADERS} DESTINATION include/transport COMPONENT headers)
 
\ No newline at end of file
include/transport/userregistry.h
Show inline comments
 
@@ -73,25 +73,25 @@ class UserRegistry : public Swift::UserRegistry {
 

	
 
		/// Called when user disconnects during login process. Disconnects user from legacy network.
 
		/// \param user JID.
 
		/// \param session Session.
 
		void stopLogin(const Swift::JID& user, Swift::ServerFromClientSession *session);
 

	
 
		/// Informs user that the password is valid and finishes login process.
 
		/// \param user JID.
 
		void onPasswordValid(const Swift::JID &user);
 

	
 
		/// Informs user that the password is invalid and disconnects him.
 
		/// \param user JID.
 
		void onPasswordInvalid(const Swift::JID &user);
 
		void onPasswordInvalid(const Swift::JID &user, const std::string &error = "");
 

	
 
		/// Removes session later.
 
		/// \param user JID.
 
		void removeLater(const Swift::JID &user);
 

	
 
		/// Returns current password for particular user
 
		/// \param barejid JID.
 
		const std::string getUserPassword(const std::string &barejid);
 

	
 
		/// Emitted when user wants to connect legacy network to validate the password.
 
		boost::signal<void (const Swift::JID &user)> onConnectUser;
 

	
plugin/CMakeLists.txt
Show inline comments
 
new file 100644
 
ADD_SUBDIRECTORY(src)
plugin/src/CMakeLists.txt
Show inline comments
 
new file 100644
 
cmake_minimum_required(VERSION 2.6)
 
FILE(GLOB SRC *.cpp *.h)
 
FILE(GLOB HEADERS ../include/transport/*.h)
 
 
ADD_LIBRARY(transport-plugin SHARED ${HEADERS} ${SRC} ${PROTOBUF_SRC} ${PROTOBUF_HDRS} ../../src/memoryusage.cpp ${CMAKE_CURRENT_BINARY_DIR}/../../include/transport/protocol.pb.cc)
 
ADD_DEPENDENCIES(transport-plugin pb)
 
SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_BINARY_DIR}/../../include/transport/protocol.pb.cc PROPERTIES GENERATED 1)
 
ADD_DEFINITIONS(-fPIC)
 
 
TARGET_LINK_LIBRARIES(transport-plugin ${PROTOBUF_LIBRARIES} ${LOG4CXX_LIBRARIES})
 
 
SET_TARGET_PROPERTIES(transport-plugin PROPERTIES
 
      VERSION ${TRANSPORT_VERSION} SOVERSION ${TRANSPORT_VERSION}
 
)
 
 
INSTALL(TARGETS transport-plugin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib COMPONENT libraries)
 
 
#CONFIGURE_FILE(transport.pc.in "${CMAKE_CURRENT_BINARY_DIR}/transport.pc")
 
#INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/transport.pc" DESTINATION lib/pkgconfig)
plugin/src/networkplugin.cpp
Show inline comments
 
@@ -478,25 +478,24 @@ void NetworkPlugin::handleDataRead(std::string &data) {
 
			return;
 
		}
 
		m_data.erase(m_data.begin(), m_data.begin() + 4 + expected_size);
 

	
 
		switch(wrapper.type()) {
 
			case pbnetwork::WrapperMessage_Type_TYPE_LOGIN:
 
				handleLoginPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_LOGOUT:
 
				handleLogoutPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_PING:
 
				LOG4CXX_INFO(logger, "PING RECEIVED");
 
				sendPong();
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_CONV_MESSAGE:
 
				handleConvMessagePayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_JOIN_ROOM:
 
				handleJoinRoomPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_LEAVE_ROOM:
 
				handleLeaveRoomPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_VCARD:
 
@@ -549,25 +548,24 @@ void NetworkPlugin::send(const std::string &data) {
 
	*((int*)(header)) = htonl(data.size());
 
	sendData(std::string(header, 4) + data);
 
}
 

	
 
void NetworkPlugin::sendPong() {
 
	m_pingReceived = true;
 
	std::string message;
 
	pbnetwork::WrapperMessage wrap;
 
	wrap.set_type(pbnetwork::WrapperMessage_Type_TYPE_PONG);
 
	wrap.SerializeToString(&message);
 

	
 
	send(message);
 
	LOG4CXX_INFO(logger, "PONG");
 
	sendMemoryUsage();
 
}
 

	
 
void NetworkPlugin::sendMemoryUsage() {
 
	pbnetwork::Stats stats;
 

	
 
	stats.set_init_res(m_init_res);
 
	double res;
 
	double shared;
 
#ifndef WIN32
 
	process_mem_usage(shared, res);
 
#endif
spectrum/src/CMakeLists.txt
Show inline comments
 
cmake_minimum_required(VERSION 2.6)
 
FILE(GLOB SRC *.cpp)
 
 
ADD_EXECUTABLE(spectrum2 ${SRC})
 
 
ADD_DEPENDENCIES(spectrum2 spectrum2_libpurple_backend)
 
ADD_DEPENDENCIES(spectrum2 spectrum2_libircclient-qt_backend)
 
 
target_link_libraries(spectrum2 transport)
 
target_link_libraries(spectrum2 transport ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
 
 
INSTALL(TARGETS spectrum2 RUNTIME DESTINATION bin)
 
 
INSTALL(FILES
 
	sample2.cfg
 
	RENAME spectrum.cfg.example
 
	DESTINATION /etc/spectrum2
 
	)
 
 
INSTALL(FILES
 
	backend-logging.cfg
 
	DESTINATION /etc/spectrum2
src/CMakeLists.txt
Show inline comments
 
@@ -11,31 +11,33 @@ if (CPPUNIT_FOUND)
 
	target_link_libraries(libtransport_test transport ${CPPUNIT_LIBRARIES} ${Boost_LIBRARIES})
 
endif()
 

	
 
if (NOT WIN32)
 
include_directories(${POPT_INCLUDE_DIR})
 
endif()
 

	
 
# SOURCE_GROUP(headers FILES ${HEADERS})
 

	
 

	
 
if (PROTOBUF_FOUND)
 
if (CMAKE_COMPILER_IS_GNUCXX)
 
	ADD_LIBRARY(transport SHARED ${HEADERS} ${SRC} ${SWIFTEN_SRC} ../include/transport/protocol.pb.cc)
 
    ADD_LIBRARY(transport SHARED ${HEADERS} ${SRC} ${SWIFTEN_SRC} ${CMAKE_CURRENT_BINARY_DIR}/../include/transport/protocol.pb.cc)
 
else()
 
	ADD_LIBRARY(transport STATIC ${HEADERS} ${SRC} ${SWIFTEN_SRC} ../include/transport/protocol.pb.cc)
 
    ADD_LIBRARY(transport STATIC ${HEADERS} ${SRC} ${SWIFTEN_SRC} ${CMAKE_CURRENT_BINARY_DIR}/../include/transport/protocol.pb.cc)    
 
endif()    
 
	SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_BINARY_DIR}/../include/transport/protocol.pb.cc PROPERTIES GENERATED 1)
 
endif()
 
	ADD_DEPENDENCIES(transport pb)
 
    ADD_DEPENDENCIES(transport pb) 
 
else()
 
	ADD_LIBRARY(transport SHARED ${HEADERS} ${SRC} ${SWIFTEN_SRC})
 
    ADD_LIBRARY(transport SHARED ${HEADERS} ${SRC} ${SWIFTEN_SRC})
 
endif()
 

	
 
if (CMAKE_COMPILER_IS_GNUCXX)
 
ADD_DEFINITIONS(-fPIC)
 
endif()
 

	
 
if (WIN32)
 
TARGET_LINK_LIBRARIES(transport ${Boost_LIBRARIES} ${SQLITE3_LIBRARIES} ${MYSQL_LIBRARIES} ${SWIFTEN_LIBRARY} ${PROTOBUF_LIBRARIES} ${LOG4CXX_LIBRARIES})
 
else ()
 
TARGET_LINK_LIBRARIES(transport ${Boost_LIBRARIES} ${SQLITE3_LIBRARIES} ${MYSQL_LIBRARIES} ${SWIFTEN_LIBRARY} ${PROTOBUF_LIBRARIES} ${LOG4CXX_LIBRARIES} ${POPT_LIBRARY})
 
endif()
 

	
src/buddy.cpp
Show inline comments
 
@@ -121,25 +121,24 @@ Swift::Presence::ref Buddy::generatePresenceStanza(int features, bool only_new)
 

	
 
	return presence;
 
}
 

	
 
std::string Buddy::getSafeName() {
 
	if (m_jid.isValid()) {
 
		return m_jid.getNode();
 
	}
 
	std::string name = getName();
 
// 	Transport::instance()->protocol()->prepareUsername(name, purple_buddy_get_account(m_buddy));
 
	if (getFlags() & BUDDY_JID_ESCAPING) {
 
		name = Swift::JID::getEscapedNode(name);
 
		std::cout << "OUT '" << getName() << "' '" << name << "'\n";
 
	}
 
	else {
 
		if (name.find_last_of("@") != std::string::npos) {
 
			name.replace(name.find_last_of("@"), 1, "%"); // OK
 
		}
 
	}
 
// 	if (name.empty()) {
 
// 		Log("SpectrumBuddy::getSafeName", "Name is EMPTY! Previous was " << getName() << ".");
 
// 	}
 
	return name;
 
}
 

	
src/mysqlbackend.cpp
Show inline comments
 
@@ -248,24 +248,26 @@ MySQLBackend::Statement& MySQLBackend::Statement::operator >> (std::string& t) {
 
	if (!m_results[m_resultOffset].is_null) {
 
		t = (char *) m_results[m_resultOffset].buffer;
 
	}
 

	
 
	if (++m_resultOffset == m_results.size())
 
		m_resultOffset = 0;
 
	return *this;
 
}
 

	
 
MySQLBackend::MySQLBackend(Config *config) {
 
	m_config = config;
 
	mysql_init(&m_conn);
 
	my_bool my_true = 1;
 
	mysql_options(&m_conn, MYSQL_OPT_RECONNECT, &my_true);
 
	m_prefix = CONFIG_STRING(m_config, "database.prefix");
 
}
 

	
 
MySQLBackend::~MySQLBackend(){
 
	delete m_setUser;
 
	delete m_getUser;
 
	delete m_removeUser;
 
	delete m_removeUserBuddies;
 
	delete m_removeUserSettings;
 
	delete m_removeUserBuddiesSettings;
 
	delete m_addBuddy;
 
	delete m_updateBuddy;
 
@@ -459,49 +461,49 @@ bool MySQLBackend::getBuddies(long id, std::list<BuddyInfo> &roster) {
 

	
 
		if (!group.empty())
 
			b.groups.push_back(group);
 

	
 
		roster.push_back(b);
 
	}
 

	
 
	if (!m_getBuddiesSettings->execute())
 
		return false;
 

	
 
	BOOST_FOREACH(BuddyInfo &b, roster) {
 
		if (buddy_id == b.id) {
 
			std::cout << "Adding buddy info setting " << key << "\n";
 
// 			std::cout << "Adding buddy info setting " << key << "\n";
 
			b.settings[key] = var;
 
			buddy_id = -1;
 
		}
 

	
 
		while(buddy_id == -1 && m_getBuddiesSettings->fetch() == 0) {
 
			std::string val;
 
			*m_getBuddiesSettings >> buddy_id >> var.type >> key >> val;
 

	
 
			switch (var.type) {
 
				case TYPE_BOOLEAN:
 
					var.b = atoi(val.c_str());
 
					break;
 
				case TYPE_STRING:
 
					var.s = val;
 
					break;
 
				default:
 
					if (buddy_id == b.id) {
 
						buddy_id = -1;
 
					}
 
					continue;
 
					break;
 
			}
 
			if (buddy_id == b.id) {
 
				std::cout << "Adding buddy info setting " << key << "=" << val << "\n";
 
// 				std::cout << "Adding buddy info setting " << key << "=" << val << "\n";
 
				b.settings[key] = var;
 
				buddy_id = -1;
 
			}
 
		}
 
	}
 

	
 
	while(m_getBuddiesSettings->fetch() == 0) {
 
		// TODO: probably remove those settings, because there's no buddy for them.
 
		// It should not happend, but one never know...
 
	}
 
	
 
	return true;
src/networkpluginserver.cpp
Show inline comments
 
@@ -360,25 +360,25 @@ void NetworkPluginServer::handleConnectedPayload(const std::string &data) {
 

	
 
	user->setConnected(true);
 
	m_component->m_userRegistry->onPasswordValid(payload.user());
 
}
 

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

	
 
	m_component->m_userRegistry->onPasswordInvalid(payload.user());
 
	m_component->m_userRegistry->onPasswordInvalid(payload.user(), payload.message());
 

	
 
	User *user = m_userManager->getUser(payload.user());
 
	if (!user) {
 
		return;
 
	}
 
	user->handleDisconnected(payload.message());
 
}
 

	
 
void NetworkPluginServer::handleVCardPayload(const std::string &data) {
 
	pbnetwork::VCard payload;
 
	if (payload.ParseFromString(data) == false) {
 
		std::cout << "PARSING ERROR\n";
src/tests/component.cpp
Show inline comments
 
#include "transport/userregistry.h"
 
#include "transport/config.h"
 
#include "transport/transport.h"
 
#include "transport/conversation.h"
 
#include "transport/localbuddy.h"
 
#include <cppunit/TestFixture.h>
 
#include <cppunit/extensions/HelperMacros.h>
 
#include <Swiften/Swiften.h>
 
#include <Swiften/EventLoop/DummyEventLoop.h>
 
#include <Swiften/Server/Server.h>
 
#include <Swiften/Network/DummyNetworkFactories.h>
 
#include <Swiften/Network/DummyConnectionServer.h>
 
#include "Swiften/Server/ServerStanzaChannel.h"
 
#include "Swiften/Server/ServerFromClientSession.h"
 
#include "Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h"
 

	
 
using namespace Transport;
 

	
 
class TestingConversation : public Conversation {
 
	public:
 
		TestingConversation(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) {
 
			
 
		}
 
@@ -39,62 +43,102 @@ class TestingFactory : public Factory {
 
			LocalBuddy *buddy = new LocalBuddy(rosterManager, buddyInfo.id);
 
			buddy->setAlias(buddyInfo.alias);
 
			buddy->setName(buddyInfo.legacyName);
 
			buddy->setSubscription(buddyInfo.subscription);
 
			buddy->setGroups(buddyInfo.groups);
 
			buddy->setFlags((BuddyFlag) buddyInfo.flags);
 
			if (buddyInfo.settings.find("icon_hash") != buddyInfo.settings.end())
 
				buddy->setIconHash(buddyInfo.settings.find("icon_hash")->second.s);
 
			return buddy;
 
		}
 
};
 

	
 
class ComponentTest : public CPPUNIT_NS :: TestFixture {
 
class ComponentTest : public CPPUNIT_NS :: TestFixture, public Swift::XMPPParserClient {
 
	CPPUNIT_TEST_SUITE(ComponentTest);
 
	CPPUNIT_TEST(presence);
 
	CPPUNIT_TEST(handlePresenceWithNode);
 
	CPPUNIT_TEST_SUITE_END();
 

	
 
	public:
 
		void setUp (void) {
 
			std::istringstream ifs("service.server_mode = 1\n");
 
			cfg = new Config();
 
			cfg->load(ifs);
 

	
 
			factory = new TestingFactory();
 

	
 
			loop = new Swift::DummyEventLoop();
 
			factories = new Swift::DummyNetworkFactories(loop);
 

	
 
			userRegistry = new UserRegistry(cfg, factories);
 

	
 
			component = new Component(loop, factories, cfg, factory, userRegistry);
 
			component->start();
 

	
 
			payloadSerializers = new Swift::FullPayloadSerializerCollection();
 
			payloadParserFactories = new Swift::FullPayloadParserFactoryCollection();
 
			parser = new Swift::XMPPParser(this, payloadParserFactories, factories->getXMLParserFactory());
 

	
 
			serverFromClientSession = boost::shared_ptr<Swift::ServerFromClientSession>(new Swift::ServerFromClientSession("id", factories->getConnectionFactory()->createConnection(), 
 
					payloadParserFactories, payloadSerializers, userRegistry, factories->getXMLParserFactory(), Swift::JID("user@localhost/resource")));
 
			serverFromClientSession->startSession();
 

	
 
			serverFromClientSession->onDataWritten.connect(boost::bind(&ComponentTest::handleDataReceived, this, _1));
 

	
 
			dynamic_cast<Swift::ServerStanzaChannel *>(component->getStanzaChannel())->addSession(serverFromClientSession);
 
			parser->parse("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='localhost' version='1.0'>");
 
			received.clear();
 
			loop->processEvents();
 
		}
 

	
 
		void tearDown (void) {
 
			dynamic_cast<Swift::ServerStanzaChannel *>(component->getStanzaChannel())->removeSession(serverFromClientSession);
 
			delete component;
 
			delete userRegistry;
 
			delete factories;
 
			delete factory;
 
			delete loop;
 
			delete cfg;
 
			delete parser;
 
			received.clear();
 
		}
 

	
 
	void presence() {
 
	void handleDataReceived(const Swift::SafeByteArray &data) {
 
		parser->parse(safeByteArrayToString(data));
 
	}
 

	
 
	void handleStreamStart(const Swift::ProtocolHeader&) {
 
		
 
	}
 

	
 
	void handleElement(boost::shared_ptr<Swift::Element> element) {
 
		received.push_back(element);
 
	}
 

	
 
	void handleStreamEnd() {
 
		
 
	}
 

	
 
	void handlePresenceWithNode() {
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setTo("localhost");
 
		response->setFrom("user@localhost/resource");
 
		dynamic_cast<Swift::ServerStanzaChannel *>(component->getStanzaChannel())->onPresenceReceived(response);
 
		
 
		loop->processEvents();
 
	}
 

	
 
	private:
 
		boost::shared_ptr<Swift::ServerFromClientSession> serverFromClientSession;
 
		Swift::FullPayloadSerializerCollection* payloadSerializers;
 
		Swift::FullPayloadParserFactoryCollection* payloadParserFactories;
 
		Swift::XMPPParser *parser;
 
		UserRegistry *userRegistry;
 
		Config *cfg;
 
		Swift::Server *server;
 
		Swift::DummyNetworkFactories *factories;
 
		Swift::DummyEventLoop *loop;
 
		TestingFactory *factory;
 
		Component *component;
 
		std::vector<std::string> received;
 
		std::vector<boost::shared_ptr<Swift::Element> > received;
 
};
 

	
 
CPPUNIT_TEST_SUITE_REGISTRATION (ComponentTest);
src/transport.cpp
Show inline comments
 
@@ -98,24 +98,36 @@ Component::Component(Swift::EventLoop *loop, Swift::NetworkFactories *factories,
 

	
 
		m_server->onDataRead.connect(boost::bind(&Component::handleDataRead, this, _1));
 
		m_server->onDataWritten.connect(boost::bind(&Component::handleDataWritten, this, _1));
 
	}
 
	else {
 
		LOG4CXX_INFO(logger, "Creating component in gateway mode");
 
		m_component = new Swift::Component(loop, m_factories, m_jid, CONFIG_STRING(m_config, "service.password"));
 
		m_component->setSoftwareVersion("", "");
 
		m_component->onConnected.connect(bind(&Component::handleConnected, this));
 
		m_component->onError.connect(boost::bind(&Component::handleConnectionError, this, _1));
 
		m_component->onDataRead.connect(boost::bind(&Component::handleDataRead, this, _1));
 
		m_component->onDataWritten.connect(boost::bind(&Component::handleDataWritten, this, _1));
 

	
 
		m_component->addPayloadParserFactory(new GenericPayloadParserFactory<StorageParser>("private", "jabber:iq:private"));
 
		m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::AttentionParser>("attention", "urn:xmpp:attention:0"));
 
		m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::XHTMLIMParser>("html", "http://jabber.org/protocol/xhtml-im"));
 
		m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Transport::BlockParser>("block", "urn:xmpp:block:0"));
 
		m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::InvisibleParser>("invisible", "urn:xmpp:invisible:0"));
 

	
 
		m_component->addPayloadSerializer(new Swift::AttentionSerializer());
 
		m_component->addPayloadSerializer(new Swift::XHTMLIMSerializer());
 
		m_component->addPayloadSerializer(new Transport::BlockSerializer());
 
		m_component->addPayloadSerializer(new Swift::InvisibleSerializer());
 

	
 
		m_stanzaChannel = m_component->getStanzaChannel();
 
		m_iqRouter = m_component->getIQRouter();
 
	}
 

	
 
	m_capsMemoryStorage = new CapsMemoryStorage();
 
	m_capsManager = new CapsManager(m_capsMemoryStorage, m_stanzaChannel, m_iqRouter);
 
	m_entityCapsManager = new EntityCapsManager(m_capsManager, m_stanzaChannel);
 
 	m_entityCapsManager->onCapsChanged.connect(boost::bind(&Component::handleCapsChanged, this, _1));
 
	
 
	m_presenceOracle = new PresenceOracle(m_stanzaChannel);
 
	m_presenceOracle->onPresenceChange.connect(bind(&Component::handlePresence, this, _1));
 

	
src/user.cpp
Show inline comments
 
@@ -155,25 +155,24 @@ void User::sendCurrentPresence() {
 
	}
 
}
 

	
 
void User::setConnected(bool connected) {
 
	m_connected = connected;
 
	setIgnoreDisconnect(false);
 
	updateLastActivity();
 

	
 
	sendCurrentPresence();
 
}
 

	
 
void User::handlePresence(Swift::Presence::ref presence) {
 
	std::cout << "PRESENCE " << presence->getFrom().toString() << "\n";
 
	if (!m_connected) {
 
		// we are not connected to legacy network, so we should do it when disco#info arrive :)
 
		if (m_readyForConnect == false) {
 
			
 
			// Forward status message to legacy network, but only if it's sent from active resource
 
// 					if (m_activeResource == presence->getFrom().getResource().getUTF8String()) {
 
// 						forwardStatus(presenceShow, stanzaStatus);
 
// 					}
 
			boost::shared_ptr<Swift::CapsInfo> capsInfo = presence->getPayload<Swift::CapsInfo>();
 
			if (capsInfo && capsInfo->getHash() == "sha-1") {
 
				if (m_entityCapsManager->getCaps(presence->getFrom()) != Swift::DiscoInfo::ref()) {
 
					LOG4CXX_INFO(logger, m_jid.toString() << ": Ready to be connected to legacy network");
 
@@ -290,23 +289,23 @@ void User::handleDisconnected(const std::string &error) {
 
	msg->setTo(m_jid.toBare());
 
	msg->setFrom(m_component->getJID());
 
	m_component->getStanzaChannel()->sendMessage(msg);
 

	
 
	// In server mode, server finishes the session and pass unavailable session to userManager if we're connected to legacy network,
 
	// so we can't removeUser() in server mode, because it would be removed twice.
 
	// Once in finishSession and once in m_userManager->removeUser.
 
	if (m_component->inServerMode()) {
 
		// Remove user later just to be sure there won't be double-free.
 
		// We can't be sure finishSession sends unavailable presence everytime, so check if user gets removed
 
		// in finishSession(...) call and if not, remove it here.
 
		std::string jid = m_jid.toBare().toString();		
 
		dynamic_cast<Swift::ServerStanzaChannel *>(m_component->getStanzaChannel())->finishSession(m_jid, boost::shared_ptr<Swift::Element>(new Swift::StreamError()));
 
		dynamic_cast<Swift::ServerStanzaChannel *>(m_component->getStanzaChannel())->finishSession(m_jid, boost::shared_ptr<Swift::Element>(new Swift::StreamError(Swift::StreamError::UndefinedCondition, "test")));
 
		if (m_userManager->getUser(jid) != NULL) {
 
			m_userManager->removeUser(this);
 
		}
 
	}
 
	else {
 
		m_userManager->removeUser(this);
 
	}
 
}
 

	
 
}
src/userregistry.cpp
Show inline comments
 
@@ -94,29 +94,29 @@ void UserRegistry::stopLogin(const Swift::JID& user, Swift::ServerFromClientSess
 
void UserRegistry::onPasswordValid(const Swift::JID &user) {
 
	std::string key = user.toBare().toString();
 
	if (users.find(key) != users.end()) {
 
		LOG4CXX_INFO(logger, key << ": Password is valid");
 
		users[key].session->handlePasswordValid();
 
		users.erase(key);
 
	}
 
	else {
 
		LOG4CXX_INFO(logger, key << ": onPasswordValid called for invalid user");
 
	}
 
}
 

	
 
void UserRegistry::onPasswordInvalid(const Swift::JID &user) {
 
void UserRegistry::onPasswordInvalid(const Swift::JID &user, const std::string &error) {
 
	std::string key = user.toBare().toString();
 
	if (users.find(key) != users.end()) {
 
		LOG4CXX_INFO(logger, key << ": Password is invalid");
 
		users[key].session->handlePasswordInvalid();
 
		users[key].session->handlePasswordInvalid(error);
 
		users.erase(key);
 
	}
 
	else {
 
		LOG4CXX_INFO(logger, key << ": onPasswordInvalid called for invalid user");
 
	}
 
}
 

	
 
void UserRegistry::handleRemoveTimeout(const Swift::JID &user) {
 
	m_inRemoveLater = true;
 
	onPasswordInvalid(user);
 
	m_inRemoveLater = false;
 
}
src/vcardresponder.cpp
Show inline comments
 
@@ -33,25 +33,25 @@
 
using namespace log4cxx;
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 

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

	
 
VCardResponder::VCardResponder(Swift::IQRouter *router, Swift::NetworkFactories *factories, UserManager *userManager) : Swift::Responder<VCard>(router) {
 
	m_id = 0;
 
	m_userManager = userManager;
 
	m_collectTimer = factories->getTimerFactory()->createTimer(20);
 
	m_collectTimer = factories->getTimerFactory()->createTimer(20000);
 
	m_collectTimer->onTick.connect(boost::bind(&VCardResponder::collectTimeouted, this));
 
	m_collectTimer->start();
 
}
 

	
 
VCardResponder::~VCardResponder() {
 
}
 

	
 
void VCardResponder::sendVCard(unsigned int id, boost::shared_ptr<Swift::VCard> vcard) {
 
	if (m_queries.find(id) == m_queries.end()) {
 
		LOG4CXX_WARN(logger, "Unexpected VCard from legacy network with id " << id);
 
		return;
 
	}
0 comments (0 inline, 0 general)