Changeset - aa0f0c64cfde
backends/libcommuni/singleircnetworkplugin.cpp
Show inline comments
 
@@ -55,12 +55,13 @@ void SingleIRCNetworkPlugin::handleLoginRequest(const std::string &user, const s
 
	MyIrcSession *session = new MyIrcSession(user, this);
 
	session->setUserName(FROM_UTF8(legacyName));
 
	session->setNickName(FROM_UTF8(legacyName));
 
	session->setRealName(FROM_UTF8(legacyName));
 
	session->setHost(FROM_UTF8(m_server));
 
	session->setPort(6667);
 
	session->setEncoding( "utf-8" );
 

	
 
	if (!password.empty()) {
 
		std::string identify = m_identify;
 
		boost::replace_all(identify, "$password", password);
 
		boost::replace_all(identify, "$name", legacyName);
 
		session->setIdentify(identify);
backends/libpurple/main.cpp
Show inline comments
 
@@ -387,14 +387,12 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
 
				}
 
// 				VALGRIND_DO_LEAK_CHECK;
 
				m_sessions.erase(user);
 
				purple_account_disconnect(account);
 
				purple_account_set_enabled(account, "spectrum", FALSE);
 

	
 
				g_free(account->ui_data);
 
				account->ui_data = NULL;
 
				m_accounts.erase(account);
 

	
 
				purple_accounts_delete(account);
 
#ifndef WIN32
 
				malloc_trim(0);
 
#endif
backends/libyahoo2/main.cpp
Show inline comments
 
@@ -13,12 +13,13 @@
 
#include "yahoohandler.h"
 
#include "yahoolocalaccount.h"
 
#include "httpfetch.h"
 

	
 
// Swiften
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Network/TLSConnectionFactory.h"
 
#include "Swiften/TLS/OpenSSL/OpenSSLContextFactory.h"
 

	
 
// for signal handler
 
#include "unistd.h"
 
#include "signal.h"
 
#include "sys/wait.h"
include/transport/adhoccommand.h
Show inline comments
 
@@ -38,12 +38,14 @@ class AdHocCommand {
 

	
 
		/// Destructor.
 
		virtual ~AdHocCommand();
 

	
 
		virtual boost::shared_ptr<Swift::Command> handleRequest(boost::shared_ptr<Swift::Command> payload) = 0;
 

	
 
		void addFormField(Swift::FormField::ref field);
 

	
 
		const std::string &getId() {
 
			return m_id;
 
		}
 

	
 
		void refreshLastActivity() {
 
			m_lastActivity = time(NULL);
 
@@ -54,15 +56,16 @@ class AdHocCommand {
 
		}
 

	
 
	protected:
 
		Component *m_component;
 
		Swift::JID m_initiator;
 
		Swift::JID m_to;
 
		std::vector<Swift::FormField::ref> m_fields;
 
		std::string m_id;
 

	
 
	private:
 
		std::string m_id;
 
		// This is used to remove AdHocCommand after long inactivity to prevent memory leaks
 
		// caused by users which disconnect before they finish the command.
 
		// AdHocManager uses this to garbage collect old AdHocCommands.
 
		time_t m_lastActivity;
 
};
 

	
include/transport/admininterface.h
Show inline comments
 
@@ -27,23 +27,27 @@
 
namespace Transport {
 

	
 
class Component;
 
class StorageBackend;
 
class UserManager;
 
class NetworkPluginServer;
 
class UserRegistration;
 

	
 
class AdminInterface {
 
	public:
 
		AdminInterface(Component *component, UserManager *userManager, NetworkPluginServer *server = NULL, StorageBackend *storageBackend = NULL);
 
		AdminInterface(Component *component, UserManager *userManager, NetworkPluginServer *server = NULL, StorageBackend *storageBackend = NULL, UserRegistration *userRegistration = NULL);
 

	
 
		~AdminInterface();
 

	
 
		void handleQuery(Swift::Message::ref message);
 

	
 
	private:
 
		void handleMessageReceived(Swift::Message::ref message);
 

	
 
		Component *m_component;
 
		StorageBackend *m_storageBackend;
 
		UserManager *m_userManager;
 
		NetworkPluginServer *m_server;
 
		UserRegistration *m_userRegistration;
 
};
 

	
 
}
include/transport/mysqlbackend.h
Show inline comments
 
@@ -86,12 +86,15 @@ class MySQLBackend : public StorageBackend
 

	
 
		long addBuddy(long userId, const BuddyInfo &buddyInfo);
 

	
 
		void updateBuddy(long userId, const BuddyInfo &buddyInfo);
 
		void removeBuddy(long id) {}
 

	
 
		void getBuddySetting(long userId, long buddyId, const std::string &variable, int &type, std::string &value) {}
 
		void updateBuddySetting(long userId, long buddyId, const std::string &variable, int type, const std::string &value) {}
 

	
 
		void getUserSetting(long userId, const std::string &variable, int &type, std::string &value);
 
		void updateUserSetting(long userId, const std::string &variable, const std::string &value);
 

	
 
		void beginTransaction();
 
		void commitTransaction();
 

	
include/transport/networkpluginserver.h
Show inline comments
 
@@ -39,12 +39,13 @@ class LocalBuddy;
 
class Config;
 
class NetworkConversation;
 
class VCardResponder;
 
class RosterResponder;
 
class BlockResponder;
 
class DummyReadBytestream;
 
class AdminInterface;
 

	
 
class NetworkPluginServer {
 
	public:
 
		struct Backend {
 
			int pongReceived;
 
			std::list<User *> users;
 
@@ -60,12 +61,16 @@ class NetworkPluginServer {
 
		};
 

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

	
 
		virtual ~NetworkPluginServer();
 

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

	
 
		int getBackendCount() {
 
			return m_clients.size();
 
		}
 

	
 
		const std::list<Backend *> &getBackends() {
 
			return m_clients;
 
@@ -81,12 +86,13 @@ class NetworkPluginServer {
 

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

	
 
	private:
 
		void handleNewClientConnection(boost::shared_ptr<Swift::Connection> c);
 
		void handleSessionFinished(Backend *c);
 
		void handlePongReceived(Backend *c);
 
		void handleDataRead(Backend *c, boost::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);
 
@@ -97,13 +103,14 @@ class NetworkPluginServer {
 
		void handleChatStatePayload(const std::string &payload, Swift::ChatState::ChatStateType type);
 
		void handleAuthorizationPayload(const std::string &payload);
 
		void handleAttentionPayload(const std::string &payload);
 
		void handleStatsPayload(Backend *c, const std::string &payload);
 
		void handleFTStartPayload(const std::string &payload);
 
		void handleFTFinishPayload(const std::string &payload);
 
		void handleFTDataPayload(Backend *b ,const std::string &payload);
 
		void handleFTDataPayload(Backend *b, const std::string &payload);
 
		void handleQueryPayload(Backend *b, const std::string &payload);
 

	
 
		void handleUserCreated(User *user);
 
		void handleRoomJoined(User *user, const Swift::JID &who, const std::string &room, const std::string &nickname, const std::string &password);
 
		void handleRoomLeft(User *user, const std::string &room);
 
		void handleUserReadyToConnect(User *user);
 
		void handleUserPresenceChanged(User *user, Swift::Presence::ref presence);
 
@@ -141,9 +148,10 @@ class NetworkPluginServer {
 
		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/pqxxbackend.h
Show inline comments
 
@@ -86,12 +86,15 @@ class PQXXBackend : public StorageBackend
 

	
 
		long addBuddy(long userId, const BuddyInfo &buddyInfo);
 

	
 
		void updateBuddy(long userId, const BuddyInfo &buddyInfo);
 
		void removeBuddy(long id) {}
 

	
 
		void getBuddySetting(long userId, long buddyId, const std::string &variable, int &type, std::string &value) {}
 
		void updateBuddySetting(long userId, long buddyId, const std::string &variable, int type, const std::string &value) {}
 

	
 
		void getUserSetting(long userId, const std::string &variable, int &type, std::string &value);
 
		void updateUserSetting(long userId, const std::string &variable, const std::string &value);
 

	
 
		void beginTransaction();
 
		void commitTransaction();
 

	
include/transport/protocol.proto
Show inline comments
 
@@ -155,11 +155,12 @@ message WrapperMessage {
 
		TYPE_FT_FINISH				= 25;
 
		TYPE_FT_DATA				= 26;
 
		TYPE_FT_PAUSE				= 27;
 
		TYPE_FT_CONTINUE			= 28;
 
		TYPE_EXIT					= 29;
 
		TYPE_BACKEND_CONFIG			= 30;
 
		TYPE_QUERY					= 31;
 
	}
 
	required Type type = 1;
 
	optional bytes payload = 2;
 
}
 
;
include/transport/rosterstorage.h
Show inline comments
 
@@ -37,12 +37,14 @@ class RosterStorage {
 
		virtual ~RosterStorage();
 

	
 
		// Add buddy to store queue and store it in future. Nothing
 
		// will happen if buddy is already added.
 
		void storeBuddy(Buddy *buddy);
 

	
 
		void removeBuddy(Buddy *buddy);
 

	
 
		// Store all buddies from queue immediately. Returns true
 
		// if some buddies were stored.
 
		bool storeBuddies();
 

	
 
		// Remove buddy from storage queue.
 
		void removeBuddyFromQueue(Buddy *buddy);
include/transport/settingsadhoccommand.h
Show inline comments
 
@@ -31,18 +31,25 @@
 
namespace Transport {
 

	
 
class Component;
 

	
 
class SettingsAdHocCommand : public AdHocCommand {
 
	public:
 
		typedef enum { Init, WaitingForResponse } State;
 

	
 
		SettingsAdHocCommand(Component *component, const Swift::JID &initiator, const Swift::JID &to);
 

	
 
		/// Destructor.
 
		virtual ~SettingsAdHocCommand();
 

	
 
		virtual boost::shared_ptr<Swift::Command> handleRequest(boost::shared_ptr<Swift::Command> payload);
 

	
 
	private:
 
		boost::shared_ptr<Swift::Command> getForm();
 
		boost::shared_ptr<Swift::Command> handleResponse(boost::shared_ptr<Swift::Command> payload);
 
		State m_state;
 
};
 

	
 
class SettingsAdHocCommandFactory : public AdHocCommandFactory {
 
	public:
 
		SettingsAdHocCommandFactory() {}
 
		virtual ~SettingsAdHocCommandFactory() {}
include/transport/sqlite3backend.h
Show inline comments
 
@@ -83,13 +83,16 @@ class SQLite3Backend : public StorageBackend
 
		/// \return true if user has been found in database and roster has been fetched
 
		bool getBuddies(long id, std::list<BuddyInfo> &roster);
 

	
 
		long addBuddy(long userId, const BuddyInfo &buddyInfo);
 

	
 
		void updateBuddy(long userId, const BuddyInfo &buddyInfo);
 
		void removeBuddy(long id) {}
 
		void removeBuddy(long id);
 

	
 
		void getBuddySetting(long userId, long buddyId, const std::string &variable, int &type, std::string &value);
 
		void updateBuddySetting(long userId, long buddyId, const std::string &variable, int type, const std::string &value);
 

	
 
		void getUserSetting(long userId, const std::string &variable, int &type, std::string &value);
 
		void updateUserSetting(long userId, const std::string &variable, const std::string &value);
 

	
 
		void beginTransaction();
 
		void commitTransaction();
 
@@ -108,15 +111,18 @@ class SQLite3Backend : public StorageBackend
 
		sqlite3_stmt *m_setUserSetting;
 
		sqlite3_stmt *m_updateUserSetting;
 
		sqlite3_stmt *m_removeUser;
 
		sqlite3_stmt *m_removeUserBuddies;
 
		sqlite3_stmt *m_removeUserSettings;
 
		sqlite3_stmt *m_removeUserBuddiesSettings;
 
		sqlite3_stmt *m_removeBuddy;
 
		sqlite3_stmt *m_removeBuddySettings;
 
		sqlite3_stmt *m_addBuddy;
 
		sqlite3_stmt *m_updateBuddy;
 
		sqlite3_stmt *m_updateBuddySetting;
 
		sqlite3_stmt *m_getBuddySetting;
 
		sqlite3_stmt *m_getBuddies;
 
		sqlite3_stmt *m_getBuddiesSettings;
 
		sqlite3_stmt *m_setUserOnline;
 
		sqlite3_stmt *m_getOnlineUsers;
 
};
 

	
include/transport/storagebackend.h
Show inline comments
 
@@ -116,12 +116,15 @@ class StorageBackend
 
		virtual bool getOnlineUsers(std::vector<std::string> &users) = 0;
 

	
 
		virtual long addBuddy(long userId, const BuddyInfo &buddyInfo) = 0;
 
		virtual void updateBuddy(long userId, const BuddyInfo &buddyInfo) = 0;
 
		virtual void removeBuddy(long id) = 0;
 

	
 
		virtual void getBuddySetting(long userId, long buddyId, const std::string &variable, int &type, std::string &value) = 0;
 
		virtual void updateBuddySetting(long userId, long buddyId, const std::string &variable, int type, const std::string &value) = 0;
 

	
 
		virtual void getUserSetting(long userId, const std::string &variable, int &type, std::string &value) = 0;
 
		virtual void updateUserSetting(long userId, const std::string &variable, const std::string &value) = 0;
 

	
 
		virtual void beginTransaction() = 0;
 
		virtual void commitTransaction() = 0;
 

	
spectrum/src/main.cpp
Show inline comments
 
@@ -204,12 +204,22 @@ int main(int argc, char **argv)
 
		boost::filesystem::create_directories(CONFIG_STRING(&config, "service.working_dir"));
 
	}
 
	catch (...) {
 
		std::cerr << "Can't create service.working_dir directory " << CONFIG_STRING(&config, "service.working_dir") << ".\n";
 
		return 1;
 
	}
 
	// create directories
 
	try {
 
		boost::filesystem::create_directories(
 
			boost::filesystem::path(CONFIG_STRING(&config, "service.portfile")).parent_path().string()
 
		);
 
	}
 
	catch (...) {
 
		std::cerr << "Can't create service.portfile directory " << CONFIG_STRING(&config, "service.portfile") << ".\n";
 
		return 1;
 
	}
 

	
 
#ifndef WIN32
 
	if (!CONFIG_STRING(&config, "service.group").empty() ||!CONFIG_STRING(&config, "service.user").empty() ) {
 
		struct group *gr;
 
		if ((gr = getgrnam(CONFIG_STRING(&config, "service.group").c_str())) == NULL) {
 
			std::cerr << "Invalid service.group name " << CONFIG_STRING(&config, "service.group") << "\n";
 
@@ -220,12 +230,26 @@ int main(int argc, char **argv)
 
			std::cerr << "Invalid service.user name " << CONFIG_STRING(&config, "service.user") << "\n";
 
			return 1;
 
		}
 
		chown(CONFIG_STRING(&config, "service.working_dir").c_str(), pw->pw_uid, gr->gr_gid);
 
	}
 

	
 
	char backendport[20];
 
	FILE* port_file_f;
 
	port_file_f = fopen(CONFIG_STRING(&config, "service.portfile").c_str(), "w+");
 
	if (port_file_f == NULL) {
 
		std::cerr << "Cannot create port_file file " << CONFIG_STRING(&config, "service.portfile").c_str() << ". Exiting\n";
 
		exit(1);
 
	}
 
	sprintf(backendport,"%s\n",CONFIG_STRING(&config, "service.backend_port").c_str());
 
	if (fwrite(backendport,1,strlen(backendport),port_file_f) < strlen(backendport)) {
 
		std::cerr << "Cannot write to port file " << CONFIG_STRING(&config, "service.portfile") << ". Exiting\n";
 
		exit(1);
 
	}
 
	fclose(port_file_f);
 

	
 
	if (!no_daemon) {
 
		// daemonize
 
		daemonize(CONFIG_STRING(&config, "service.working_dir").c_str(), CONFIG_STRING(&config, "service.pidfile").c_str());
 
// 		removeOldIcons(CONFIG_STRING(&config, "service.working_dir") + "/icons");
 
    }
 
#endif
 
@@ -306,13 +330,15 @@ int main(int argc, char **argv)
 
	}
 

	
 
	FileTransferManager ftManager(&transport, &userManager);
 

	
 
	NetworkPluginServer plugin(&transport, &config, &userManager, &ftManager);
 

	
 
	AdminInterface adminInterface(&transport, &userManager, &plugin, storageBackend);
 
	AdminInterface adminInterface(&transport, &userManager, &plugin, storageBackend, userRegistration);
 
	plugin.setAdminInterface(&adminInterface);
 

	
 
	StatsResponder statsResponder(&transport, &userManager, &plugin, storageBackend);
 
	statsResponder.start();
 

	
 
	GatewayResponder gatewayResponder(transport.getIQRouter(), &userManager);
 
	gatewayResponder.start();
 

	
spectrum_manager/src/CMakeLists.txt
Show inline comments
 
cmake_minimum_required(VERSION 2.6)
 
FILE(GLOB SRC *.cpp)
 
 
ADD_EXECUTABLE(spectrum2_manager ${SRC} ../../src/config.cpp ../../src/util.cpp)
 
ADD_EXECUTABLE(spectrum2_manager ${SRC} ../../src/config.cpp ../../src/util.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../../include/transport/protocol.pb.cc)
 
 
target_link_libraries(spectrum2_manager ${SWIFTEN_LIBRARY})
 
target_link_libraries(spectrum2_manager ${SWIFTEN_LIBRARY} ${PROTOBUF_LIBRARIES})
 
 
INSTALL(TARGETS spectrum2_manager RUNTIME DESTINATION bin)
 
 
INSTALL(FILES
 
	spectrum_manager.cfg
 
	DESTINATION /etc/spectrum2
spectrum_manager/src/main.cpp
Show inline comments
 
#include "managerconfig.h"
 
#include "transport/config.h"
 
#include "transport/protocol.pb.h"
 
#include "Swiften/Swiften.h"
 
#include "Swiften/EventLoop/SimpleEventLoop.h"
 
 
#include <boost/foreach.hpp>
 
#include <iostream>
 
#include <fstream>
 
#include <iterator>
 
#include <algorithm>
 
#include <boost/filesystem.hpp>
 
#include "signal.h"
 
#include "sys/wait.h"
 
 
#define WRAP(MESSAGE, TYPE) 	pbnetwork::WrapperMessage wrap; \
 
	wrap.set_type(TYPE); \
 
	wrap.set_payload(MESSAGE); \
 
	wrap.SerializeToString(&MESSAGE);
 
 
 
using namespace Transport;
 
 
using namespace boost::filesystem;
 
 
using namespace boost;
 
 
static int finished;
 
static std::string *m;
 
 
static void handleDisconnected(Swift::Client *client, const boost::optional<Swift::ClientError> &, const std::string &server) {
 
	std::cout << "[ DISCONNECTED ] " << server << "\n";
 
	if (--finished == 0) {
 
		exit(0);
 
	}
 
}
 
 
static void handleConnected(Swift::Client *client, const std::string &server) {
 
	boost::shared_ptr<Swift::Message> message(new Swift::Message());
 
	message->setTo(server);
 
	message->setFrom(client->getJID());
 
	message->setBody(*m);
 
 
	client->sendMessage(message);
 
}
 
 
static void handleMessageReceived(Swift::Client *client, Swift::Message::ref message, const std::string &server) {
 
	std::string body = message->getBody();
 
	boost::replace_all(body, "\n", "\n[      OK      ] " + server + ": ");
 
	std::cout << "[      OK      ] " << server << ": " << body <<  "\n";
 
	if (--finished == 0) {
 
		exit(0);
 
	}
 
}
 
std::string _data;
 
 
static std::string searchForBinary(const std::string &binary) {
 
	std::vector<std::string> path_list;
 
	char * env_path = getenv("PATH");
 
 
	if (env_path != NULL) {
 
@@ -100,12 +80,28 @@ static unsigned long exec_(std::string path, std::string config, std::string jid
 
		waitpid(pid, 0, 0);
 
	}
 
 
	return (unsigned long) pid;
 
}
 
 
static int getPort(const std::string &portfile) {
 
	path p(portfile);
 
	if (!exists(p) || is_directory(p)) {
 
		return 0;
 
	}
 
 
	std::ifstream f(p.string().c_str(), std::ios_base::in);
 
	std::string port;
 
	f >> port;
 
 
	if (port.empty())
 
		return 0;
 
 
	return boost::lexical_cast<int>(port);
 
}
 
 
static int isRunning(const std::string &pidfile) {
 
	path p(pidfile);
 
	if (!exists(p) || is_directory(p)) {
 
		return 0;
 
	}
 
 
@@ -285,13 +281,81 @@ static int show_status(ManagerConfig *config) {
 
		std::cerr << "boost filesystem error\n";
 
		exit(5);
 
	}
 
	return ret;
 
}
 
 
static void ask_local_servers(ManagerConfig *config, Swift::BoostNetworkFactories &networkFactories, const std::string &message) {
 
static void handleDataRead(boost::shared_ptr<Swift::Connection> m_conn, boost::shared_ptr<Swift::SafeByteArray> data) {
 
	_data += std::string(data->begin(), data->end());
 
 
	// Parse data while there are some
 
	while (_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 (_data.size() >= 4) {
 
			expected_size = *((unsigned int*) &_data[0]);
 
			expected_size = ntohl(expected_size);
 
			// If we don't have whole wrapper message, wait for next
 
			// handleDataRead call.
 
			if (_data.size() - 4 < expected_size)
 
				return;
 
		}
 
		else {
 
			return;
 
		}
 
 
		// Parse wrapper message and erase it from buffer.
 
		pbnetwork::WrapperMessage wrapper;
 
		if (wrapper.ParseFromArray(&_data[4], expected_size) == false) {
 
			std::cout << "PARSING ERROR " << expected_size << "\n";
 
			_data.erase(_data.begin(), _data.begin() + 4 + expected_size);
 
			continue;
 
		}
 
		_data.erase(_data.begin(), _data.begin() + 4 + expected_size);
 
 
		if (wrapper.type() == pbnetwork::WrapperMessage_Type_TYPE_QUERY) {
 
			pbnetwork::BackendConfig payload;
 
			if (payload.ParseFromString(wrapper.payload()) == false) {
 
				std::cout << "PARSING ERROR\n";
 
				// TODO: ERROR
 
				continue;
 
			}
 
 
			std::cout << payload.config() << "\n";
 
			exit(0);
 
		}
 
	}
 
}
 
 
static void handleConnected(boost::shared_ptr<Swift::Connection> m_conn, const std::string &msg, bool error) {
 
	if (error) {
 
		std::cerr << "Can't connect the server\n";
 
		exit(50);
 
	}
 
	else {
 
		pbnetwork::BackendConfig m;
 
		m.set_config(msg);
 
 
		std::string message;
 
		m.SerializeToString(&message);
 
 
		WRAP(message, pbnetwork::WrapperMessage_Type_TYPE_QUERY);
 
 
		uint32_t size = htonl(message.size());
 
		char *header = (char *) &size;
 
 
		
 
		// send header together with wrapper message
 
		m_conn->write(Swift::createSafeByteArray(std::string(header, 4) + message));
 
	}
 
}
 
 
static void ask_local_server(ManagerConfig *config, Swift::BoostNetworkFactories &networkFactories, const std::string &jid, const std::string &message) {
 
	path p(CONFIG_STRING(config, "service.config_directory"));
 
 
	try {
 
		if (!exists(p)) {
 
			std::cerr << "Config directory " << CONFIG_STRING(config, "service.config_directory") << " does not exist\n";
 
			exit(6);
 
@@ -299,62 +363,122 @@ static void ask_local_servers(ManagerConfig *config, Swift::BoostNetworkFactorie
 
 
		if (!is_directory(p)) {
 
			std::cerr << "Config directory " << CONFIG_STRING(config, "service.config_directory") << " does not exist\n";
 
			exit(7);
 
		}
 
 
		bool found = false;
 
		directory_iterator end_itr;
 
		for (directory_iterator itr(p); itr != end_itr; ++itr) {
 
			if (is_regular(itr->path()) && extension(itr->path()) == ".cfg") {
 
				Config cfg;
 
				if (cfg.load(itr->path().string()) == false) {
 
					std::cerr << "Can't load config file " << itr->path().string() << ". Skipping...\n";
 
					continue;
 
				}
 
 
				if (CONFIG_VECTOR(&cfg, "service.admin_jid").empty() || CONFIG_STRING(&cfg, "service.admin_password").empty()) {
 
					std::cerr << itr->path().string() << ": service.admin_jid or service.admin_password empty. This server can't be queried over XMPP.\n";
 
				if (CONFIG_STRING(&cfg, "service.jid") != jid) {
 
					continue;
 
				}
 
 
				finished++;
 
				Swift::Client *client = new Swift::Client(CONFIG_VECTOR(&cfg, "service.admin_jid")[0], CONFIG_STRING(&cfg, "service.admin_password"), &networkFactories);
 
				client->setAlwaysTrustCertificates();
 
				client->onConnected.connect(boost::bind(&handleConnected, client, CONFIG_STRING(&cfg, "service.jid")));
 
				client->onDisconnected.connect(bind(&handleDisconnected, client, _1, CONFIG_STRING(&cfg, "service.jid")));
 
				client->onMessageReceived.connect(bind(&handleMessageReceived, client, _1, CONFIG_STRING(&cfg, "service.jid")));
 
				Swift::ClientOptions opt;
 
				opt.allowPLAINWithoutTLS = true;
 
				client->connect(opt);
 
				found = true;
 
 
				boost::shared_ptr<Swift::Connection> m_conn;
 
				m_conn = networkFactories.getConnectionFactory()->createConnection();
 
				m_conn->onDataRead.connect(boost::bind(&handleDataRead, m_conn, _1));
 
				m_conn->onConnectFinished.connect(boost::bind(&handleConnected, m_conn, message, _1));
 
				m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(CONFIG_STRING(&cfg, "service.backend_host")), getPort(CONFIG_STRING(&cfg, "service.portfile"))));
 
 
// 				finished++;
 
// 				Swift::Client *client = new Swift::Client(CONFIG_VECTOR(&cfg, "service.admin_jid")[0], CONFIG_STRING(&cfg, "service.admin_password"), &networkFactories);
 
// 				client->setAlwaysTrustCertificates();
 
// 				client->onConnected.connect(boost::bind(&handleConnected, client, CONFIG_STRING(&cfg, "service.jid")));
 
// 				client->onDisconnected.connect(bind(&handleDisconnected, client, _1, CONFIG_STRING(&cfg, "service.jid")));
 
// 				client->onMessageReceived.connect(bind(&handleMessageReceived, client, _1, CONFIG_STRING(&cfg, "service.jid")));
 
// 				Swift::ClientOptions opt;
 
// 				opt.allowPLAINWithoutTLS = true;
 
// 				client->connect(opt);
 
			}
 
		}
 
 
		if (!found) {
 
			std::cerr << "Config file for Spectrum instance with this JID was not found\n";
 
			exit(20);
 
		}
 
	}
 
	catch (const filesystem_error& ex) {
 
		std::cerr << "boost filesystem error\n";
 
		exit(5);
 
	}
 
}
 
 
// static void ask_local_servers(ManagerConfig *config, Swift::BoostNetworkFactories &networkFactories, const std::string &message) {
 
// 	path p(CONFIG_STRING(config, "service.config_directory"));
 
// 
 
// 	try {
 
// 		if (!exists(p)) {
 
// 			std::cerr << "Config directory " << CONFIG_STRING(config, "service.config_directory") << " does not exist\n";
 
// 			exit(6);
 
// 		}
 
// 
 
// 		if (!is_directory(p)) {
 
// 			std::cerr << "Config directory " << CONFIG_STRING(config, "service.config_directory") << " does not exist\n";
 
// 			exit(7);
 
// 		}
 
// 
 
// 		directory_iterator end_itr;
 
// 		for (directory_iterator itr(p); itr != end_itr; ++itr) {
 
// 			if (is_regular(itr->path()) && extension(itr->path()) == ".cfg") {
 
// 				Config cfg;
 
// 				if (cfg.load(itr->path().string()) == false) {
 
// 					std::cerr << "Can't load config file " << itr->path().string() << ". Skipping...\n";
 
// 					continue;
 
// 				}
 
// 
 
// 				if (CONFIG_VECTOR(&cfg, "service.admin_jid").empty() || CONFIG_STRING(&cfg, "service.admin_password").empty()) {
 
// 					std::cerr << itr->path().string() << ": service.admin_jid or service.admin_password empty. This server can't be queried over XMPP.\n";
 
// 					continue;
 
// 				}
 
// 
 
// 				finished++;
 
// 				Swift::Client *client = new Swift::Client(CONFIG_VECTOR(&cfg, "service.admin_jid")[0], CONFIG_STRING(&cfg, "service.admin_password"), &networkFactories);
 
// 				client->setAlwaysTrustCertificates();
 
// 				client->onConnected.connect(boost::bind(&handleConnected, client, CONFIG_STRING(&cfg, "service.jid")));
 
// 				client->onDisconnected.connect(bind(&handleDisconnected, client, _1, CONFIG_STRING(&cfg, "service.jid")));
 
// 				client->onMessageReceived.connect(bind(&handleMessageReceived, client, _1, CONFIG_STRING(&cfg, "service.jid")));
 
// 				Swift::ClientOptions opt;
 
// 				opt.allowPLAINWithoutTLS = true;
 
// 				client->connect(opt);
 
// 			}
 
// 		}
 
// 	}
 
// 	catch (const filesystem_error& ex) {
 
// 		std::cerr << "boost filesystem error\n";
 
// 		exit(5);
 
// 	}
 
// }
 
 
 
int main(int argc, char **argv)
 
{
 
	ManagerConfig config;
 
	std::string config_file;
 
	std::string command;
 
	std::vector<std::string> command;
 
	boost::program_options::variables_map vm;
 
 
	boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <COMMAND>\nCommands:\n"
 
	boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <COMMAND>\n"
 
													 "       spectrum [OPTIONS] <instance_JID> <other>\nCommands:\n"
 
													 " start - start all local Spectrum2 instances\n"
 
													 " stop  - stop all  local Spectrum2 instances\n"
 
													 " stop  - stop all local Spectrum2 instances\n"
 
													 " status - status of local Spectrum2 instances\n"
 
													 " <other> - send command to all local + remote Spectrum2 instances and print output\n"
 
													 " <other> - send command to local Spectrum2 instance and print output\n"
 
													 "Allowed options");
 
	desc.add_options()
 
		("help,h", "Show help output")
 
		("config,c", boost::program_options::value<std::string>(&config_file)->default_value("/etc/spectrum2/spectrum_manager.cfg"), "Spectrum manager config file")
 
		("command", boost::program_options::value<std::string>(&command)->default_value(""), "Command")
 
		("command", boost::program_options::value<std::vector<std::string> >(&command), "Command")
 
		;
 
	try
 
	{
 
		boost::program_options::positional_options_description p;
 
		p.add("command", -1);
 
		boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
 
@@ -385,41 +509,36 @@ int main(int argc, char **argv)
 
 
	if (command.empty()) {
 
		std::cout << desc << "\n";
 
		return 1;
 
	}
 
 
	if (command == "start") {
 
	if (command[0] == "start") {
 
		start_all_instances(&config);
 
	}
 
	else if (command == "stop") {
 
	else if (command[0] == "stop") {
 
		stop_all_instances(&config);
 
	}
 
	else if (command == "status") {
 
	else if (command[0] == "status") {
 
		return show_status(&config);
 
	}
 
	else {
 
		if (command.size() < 2) {
 
			std::cout << desc << "\n";
 
			return 11;
 
		}
 
		Swift::SimpleEventLoop eventLoop;
 
		Swift::BoostNetworkFactories networkFactories(&eventLoop);
 
 
		std::string message = command;
 
		m = &message;
 
 
		ask_local_servers(&config, networkFactories, message);
 
 
		std::vector<std::string> servers = CONFIG_VECTOR(&config, "servers.server");
 
		for (std::vector<std::string>::const_iterator it = servers.begin(); it != servers.end(); it++) {
 
			finished++;
 
			Swift::Client *client = new Swift::Client(CONFIG_STRING(&config, "service.admin_username") + "@" + *it, CONFIG_STRING(&config, "service.admin_password"), &networkFactories);
 
			client->setAlwaysTrustCertificates();
 
			client->onConnected.connect(boost::bind(&handleConnected, client, *it));
 
			client->onDisconnected.connect(bind(&handleDisconnected, client, _1, *it));
 
			client->onMessageReceived.connect(bind(&handleMessageReceived, client, _1, *it));
 
			Swift::ClientOptions opt;
 
			opt.allowPLAINWithoutTLS = true;
 
			client->connect(opt);
 
	// 		std::cout << *it << "\n";
 
		}
 
		std::string jid = command[0];
 
		command.erase(command.begin());
 
		std::string cmd = boost::algorithm::join(command, " ");
 
 
		ask_local_server(&config, networkFactories, jid, cmd);
 
// 		std::string message = command;
 
// 		m = &message;
 
 
// 		ask_local_server(&config, networkFactories, message);
 
 
		eventLoop.run();
 
	}
 
}
src/adhoccommand.cpp
Show inline comments
 
@@ -42,7 +42,11 @@ AdHocCommand::AdHocCommand(Component *component, const Swift::JID &initiator, co
 
	}
 
}
 

	
 
AdHocCommand::~AdHocCommand() {
 
}
 

	
 
void AdHocCommand::addFormField(Swift::FormField::ref field) {
 
	m_fields.push_back(field);
 
}
 

	
 
}
src/admininterface.cpp
Show inline comments
 
@@ -24,12 +24,13 @@
 
#include "transport/storagebackend.h"
 
#include "transport/conversationmanager.h"
 
#include "transport/rostermanager.h"
 
#include "transport/usermanager.h"
 
#include "transport/networkpluginserver.h"
 
#include "transport/logging.h"
 
#include "transport/userregistration.h"
 
#include "storageresponder.h"
 
#include "transport/memoryusage.h"
 
#include <boost/foreach.hpp>
 

	
 
namespace Transport {
 

	
 
@@ -40,40 +41,26 @@ static std::string getArg(const std::string &body) {
 
	if (body.find(" ") == std::string::npos)
 
		return ret;
 

	
 
	return body.substr(body.find(" ") + 1);
 
}
 

	
 
AdminInterface::AdminInterface(Component *component, UserManager *userManager, NetworkPluginServer *server, StorageBackend *storageBackend) {
 
AdminInterface::AdminInterface(Component *component, UserManager *userManager, NetworkPluginServer *server, StorageBackend *storageBackend, UserRegistration *userRegistration) {
 
	m_component = component;
 
	m_storageBackend = storageBackend;
 
	m_userManager = userManager;
 
	m_server = server;
 
	m_userRegistration = userRegistration;
 

	
 
	m_component->getStanzaChannel()->onMessageReceived.connect(bind(&AdminInterface::handleMessageReceived, this, _1));
 
}
 

	
 
AdminInterface::~AdminInterface() {
 
}
 

	
 
void AdminInterface::handleMessageReceived(Swift::Message::ref message) {
 
	if (!message->getTo().getNode().empty())
 
		return;
 

	
 
	std::vector<std::string> const &x = CONFIG_VECTOR(m_component->getConfig(),"service.admin_jid");
 
	if (std::find(x.begin(), x.end(), message->getFrom().toBare().toString()) == x.end()) {
 
	    LOG4CXX_WARN(logger, "Message not from admin user, but from " << message->getFrom().toBare().toString());
 
	    return;
 
	
 
	}
 
	
 
	// Ignore empty messages
 
	if (message->getBody().empty()) {
 
		return;
 
	}
 

	
 
void AdminInterface::handleQuery(Swift::Message::ref message) {
 
	LOG4CXX_INFO(logger, "Message from admin received");
 
	message->setTo(message->getFrom());
 
	message->setFrom(m_component->getJID());
 

	
 
	if (message->getBody() == "status") {
 
		int users = m_userManager->getUserCount();
 
@@ -264,22 +251,66 @@ void AdminInterface::handleMessageReceived(Swift::Message::ref message) {
 
		message->setBody(boost::lexical_cast<std::string>(msgCount));
 
	}
 
	else if (message->getBody() == "messages_to_xmpp") {
 
		int msgCount = m_userManager->getMessagesToXMPP();
 
		message->setBody(boost::lexical_cast<std::string>(msgCount));
 
	}
 
	else if (message->getBody().find("register ") == 0 && m_userRegistration) {
 
		std::string body = message->getBody();
 
		std::vector<std::string> args;
 
		boost::split(args, body, boost::is_any_of(" "));
 
		if (args.size() == 4) {
 
			UserInfo res;
 
			res.jid = args[1];
 
			res.uin = args[2];
 
			res.password = args[3];
 
			res.language = "en";
 
			res.encoding = "utf-8";
 
			res.vip = 0;
 

	
 
			if (m_userRegistration->registerUser(res)) {
 
				message->setBody("User registered.");
 
			}
 
			else {
 
				message->setBody("Registration failed: User is already registered");
 
			}
 
		}
 
		else {
 
			message->setBody("Bad argument count. See 'help'.");
 
		}
 
	}
 
	else if (message->getBody().find("unregister ") == 0 && m_userRegistration) {
 
		std::string body = message->getBody();
 
		std::vector<std::string> args;
 
		boost::split(args, body, boost::is_any_of(" "));
 
		if (args.size() == 2) {
 
			if (m_userRegistration->unregisterUser(args[1])) {
 
				message->setBody("User unregistered.");
 
			}
 
			else {
 
				message->setBody("Registration failed: User is not registered");
 
			}
 
		}
 
		else {
 
			message->setBody("Bad argument count. See 'help'.");
 
		}
 
	}
 
	else if (message->getBody().find("help") == 0) {
 
		std::string help;
 
		help += "General:\n";
 
		help += "    status - shows instance status\n";
 
		help += "    reload - Reloads config file\n";
 
		help += "Users:\n";
 
		help += "    online_users - returns list of all online users\n";
 
		help += "    online_users_count - number of online users\n";
 
		help += "    online_users_per_backend - shows online users per backends\n";
 
		help += "    has_online_user <bare_JID> - returns 1 if user is online\n";
 
		if (m_userRegistration) {
 
			help += "    register <bare_JID> <legacyName> <password> - registers the new user\n";
 
			help += "    unregister <bare_JID> - unregisters existing user\n";
 
		}
 
		help += "Messages:\n";
 
		help += "    messages_from_xmpp - get number of messages received from XMPP users\n";
 
		help += "    messages_to_xmpp - get number of messages sent to XMPP users\n";
 
		help += "Backends:\n";
 
		help += "    backends_count - number of active backends\n";
 
		help += "    crashed_backends - returns IDs of crashed backends\n";
 
@@ -296,11 +327,30 @@ void AdminInterface::handleMessageReceived(Swift::Message::ref message) {
 
		
 
		message->setBody(help);
 
	}
 
	else {
 
		message->setBody("Unknown command. Try \"help\"");
 
	}
 
}
 

	
 
void AdminInterface::handleMessageReceived(Swift::Message::ref message) {
 
	if (!message->getTo().getNode().empty())
 
		return;
 

	
 
	std::vector<std::string> const &x = CONFIG_VECTOR(m_component->getConfig(),"service.admin_jid");
 
	if (std::find(x.begin(), x.end(), message->getFrom().toBare().toString()) == x.end()) {
 
	    LOG4CXX_WARN(logger, "Message not from admin user, but from " << message->getFrom().toBare().toString());
 
	    return;
 
	
 
	}
 
	
 
	// Ignore empty messages
 
	if (message->getBody().empty()) {
 
		return;
 
	}
 

	
 
	handleQuery(message);
 

	
 
	m_component->getStanzaChannel()->sendMessage(message);
 
}
 

	
 
}
src/config.cpp
Show inline comments
 
@@ -72,12 +72,13 @@ bool Config::load(std::istream &ifs, boost::program_options::options_description
 
		("service.port", value<int>()->default_value(0), "Port the server is listening on")
 
		("service.user", value<std::string>()->default_value(""), "The name of user Spectrum runs as.")
 
		("service.group", value<std::string>()->default_value(""), "The name of group Spectrum runs as.")
 
		("service.backend", value<std::string>()->default_value("libpurple_backend"), "Backend")
 
		("service.protocol", value<std::string>()->default_value(""), "Protocol")
 
		("service.pidfile", value<std::string>()->default_value("/var/run/spectrum2/$jid.pid"), "Full path to pid file")
 
		("service.portfile", value<std::string>()->default_value("/var/run/spectrum2/$jid.port"), "File to store backend_port to. It's used by spectrum2_manager.")
 
		("service.working_dir", value<std::string>()->default_value("/var/lib/spectrum2/$jid"), "Working dir")
 
		("service.allowed_servers", value<std::vector<std::string> >()->multitoken(), "Only users from these servers can connect")
 
		("service.server_mode", value<bool>()->default_value(false), "True if Spectrum should behave as server")
 
		("service.users_per_backend", value<int>()->default_value(100), "Number of users per one legacy network backend")
 
		("service.backend_host", value<std::string>()->default_value("localhost"), "Host to bind backend server to")
 
		("service.backend_port", value<std::string>()->default_value("0"), "Port to bind backend server to")
src/networkpluginserver.cpp
Show inline comments
 
@@ -29,12 +29,13 @@
 
#include "transport/config.h"
 
#include "transport/conversation.h"
 
#include "transport/vcardresponder.h"
 
#include "transport/rosterresponder.h"
 
#include "transport/memoryreadbytestream.h"
 
#include "transport/logging.h"
 
#include "transport/admininterface.h"
 
#include "blockresponder.h"
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Server/ServerStanzaChannel.h"
 
#include "Swiften/Elements/StreamError.h"
 
#include "Swiften/Network/BoostConnectionServer.h"
 
#include "Swiften/Elements/AttentionPayload.h"
 
@@ -201,13 +202,12 @@ static void SigCatcher(int n) {
 

	
 
static void handleBuddyPayload(LocalBuddy *buddy, const pbnetwork::Buddy &payload) {
 
	buddy->setName(payload.buddyname());
 
	// Set alias only if it's not empty. Backends are allowed to send empty alias if it has
 
	// not changed.
 
	if (!payload.alias().empty()) {
 
		LOG4CXX_INFO(logger, "Setting alias to " << payload.alias() << " " << buddy->getAlias());
 
		buddy->setAlias(payload.alias());
 
	}
 

	
 
	// Change groups if it's not empty. The same as above...
 
	std::vector<std::string> groups;
 
	for (int i = 0; i < payload.group_size(); i++) {
 
@@ -225,12 +225,13 @@ static void handleBuddyPayload(LocalBuddy *buddy, const pbnetwork::Buddy &payloa
 
NetworkPluginServer::NetworkPluginServer(Component *component, Config *config, UserManager *userManager, FileTransferManager *ftManager) {
 
	m_ftManager = ftManager;
 
	m_userManager = userManager;
 
	m_config = config;
 
	m_component = component;
 
	m_isNextLongRun = false;
 
	m_adminInterface = NULL;
 
	m_component->m_factory = new NetworkFactory(this);
 
	m_userManager->onUserCreated.connect(boost::bind(&NetworkPluginServer::handleUserCreated, this, _1));
 
	m_userManager->onUserDestroyed.connect(boost::bind(&NetworkPluginServer::handleUserDestroyed, this, _1));
 

	
 
	m_pingTimer = component->getNetworkFactories()->getTimerFactory()->createTimer(20000);
 
	m_pingTimer->onTick.connect(boost::bind(&NetworkPluginServer::pingTimeout, this));
 
@@ -315,56 +316,30 @@ void NetworkPluginServer::handleNewClientConnection(boost::shared_ptr<Swift::Con
 
	Backend *client = new Backend;
 
	client->pongReceived = -1;
 
	client->connection = c;
 
	client->res = 0;
 
	client->init_res = 0;
 
	client->shared = 0;
 
	client->willDie = 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;
 

	
 
	LOG4CXX_INFO(logger, "New" + (client->longRun ? std::string(" long-running") : "") +  " backend " << client << " connected. Current backend count=" << (m_clients.size() + 1));
 

	
 
	if (m_clients.size() == 0) {
 
		// first backend connected, start the server, we're ready.
 
		m_component->start();
 
	}
 

	
 
	m_clients.push_front(client);
 

	
 
	c->onDisconnected.connect(boost::bind(&NetworkPluginServer::handleSessionFinished, this, client));
 
	c->onDataRead.connect(boost::bind(&NetworkPluginServer::handleDataRead, this, client, _1));
 
	sendPing(client);
 

	
 
	// sendPing sets pongReceived to 0, but we want to have it -1 to ignore this backend
 
	// in first ::pingTimeout call, because it can be called right after this function
 
	// and backend wouldn't have any time to response to ping.
 
	client->pongReceived = -1;
 

	
 
	// some users are in queue waiting for this backend
 
	while(!m_waitingUsers.empty()) {
 
		// There's no new backend, so stop associating users and wait for new backend,
 
		// which has been already spawned in getFreeClient() call.
 
		if (getFreeClient() == NULL)
 
			break;
 

	
 
		User *u = m_waitingUsers.front();
 
		m_waitingUsers.pop_front();
 

	
 
		LOG4CXX_INFO(logger, "Associating " << u->getJID().toString() << " with this backend");
 

	
 
		// associate backend with user
 
		handleUserCreated(u);
 

	
 
		// connect user if it's ready
 
		if (u->isReadyToConnect()) {
 
			handleUserReadyToConnect(u);
 
		}
 

	
 
	}
 
}
 

	
 
void NetworkPluginServer::handleSessionFinished(Backend *c) {
 
	LOG4CXX_INFO(logger, "Backend " << c << " (ID=" << c->id << ") disconnected. Current backend count=" << (m_clients.size() - 1));
 

	
 
	// This backend will do, so we can't reconnect users to it in User::handleDisconnected call
 
@@ -750,12 +725,74 @@ void NetworkPluginServer::handleFTDataNeeded(Backend *b, unsigned long ftid) {
 

	
 
	WRAP(message, pbnetwork::WrapperMessage_Type_TYPE_FT_CONTINUE);
 

	
 
	send(b->connection, message);
 
}
 

	
 
void NetworkPluginServer::handlePongReceived(Backend *c) {
 
	// This could be first PONG from the backend
 
	if (c->pongReceived == -1) {
 
		// Backend is fully ready to handle requests
 
		c->willDie = false;
 

	
 
		if (m_clients.size() == 1) {
 
			// first backend connected, start the server, we're ready.
 
			m_component->start();
 
		}
 

	
 
		// some users are in queue waiting for this backend
 
		while(!m_waitingUsers.empty()) {
 
			// There's no new backend, so stop associating users and wait for new backend,
 
			// which has been already spawned in getFreeClient() call.
 
			if (getFreeClient() == NULL)
 
				break;
 

	
 
			User *u = m_waitingUsers.front();
 
			m_waitingUsers.pop_front();
 

	
 
			LOG4CXX_INFO(logger, "Associating " << u->getJID().toString() << " with this backend");
 

	
 
			// associate backend with user
 
			handleUserCreated(u);
 

	
 
			// connect user if it's ready
 
			if (u->isReadyToConnect()) {
 
				handleUserReadyToConnect(u);
 
			}
 
		}
 
	}
 

	
 
	c->pongReceived = true;
 
}
 

	
 
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());
 
	msg->setBody(payload.config());
 
	m_adminInterface->handleQuery(msg);
 

	
 
	pbnetwork::BackendConfig vcard;
 
	vcard.set_config(msg->getBody());
 

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

	
 
	WRAP(message, pbnetwork::WrapperMessage_Type_TYPE_QUERY);
 

	
 
	send(b->connection, message);
 
}
 

	
 
void NetworkPluginServer::handleDataRead(Backend *c, boost::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) {
 
@@ -800,13 +837,13 @@ void NetworkPluginServer::handleDataRead(Backend *c, boost::shared_ptr<Swift::Sa
 
				handleConvMessagePayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_ROOM_SUBJECT_CHANGED:
 
				handleConvMessagePayload(wrapper.payload(), true);
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_PONG:
 
				c->pongReceived = true;
 
				handlePongReceived(c);
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_PARTICIPANT_CHANGED:
 
				handleParticipantChangedPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_ROOM_NICKNAME_CHANGED:
 
				handleRoomChangedPayload(wrapper.payload());
 
@@ -841,12 +878,15 @@ void NetworkPluginServer::handleDataRead(Backend *c, boost::shared_ptr<Swift::Sa
 
			case pbnetwork::WrapperMessage_Type_TYPE_FT_DATA:
 
				handleFTDataPayload(c, wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_BUDDY_REMOVED:
 
				handleBuddyRemovedPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_QUERY:
 
				handleQueryPayload(c, wrapper.payload());
 
				break;
 
			default:
 
				return;
 
		}
 
	}
 
}
 

	
 
@@ -894,13 +934,17 @@ void NetworkPluginServer::pingTimeout() {
 
	// check ping responses
 
	std::vector<Backend *> toRemove;
 
	for (std::list<Backend *>::const_iterator it = m_clients.begin(); it != m_clients.end(); it++) {
 
		// pong has been received OR backend just connected and did not have time to answer the ping
 
		// request.
 
		if ((*it)->pongReceived || (*it)->pongReceived == -1) {
 
			sendPing((*it));
 
			// Don't send another ping if pongReceived == -1, because we've already sent one
 
			// when registering backend.
 
			if ((*it)->pongReceived) {
 
				sendPing((*it));
 
			}
 
		}
 
		else {
 
			LOG4CXX_INFO(logger, "Disconnecting backend " << (*it) << " (ID=" << (*it)->id << "). PING response not received.");
 
			toRemove.push_back(*it);
 
		}
 

	
src/rostermanager.cpp
Show inline comments
 
@@ -110,12 +110,15 @@ void RosterManager::removeBuddy(const std::string &name) {
 
		sendBuddyRosterRemove(buddy);
 
	}
 
	else {
 
		sendBuddyUnsubscribePresence(buddy);
 
	}
 

	
 
	if (m_rosterStorage)
 
		m_rosterStorage->removeBuddy(buddy);
 

	
 
	unsetBuddy(buddy);
 
	delete buddy;
 
}
 

	
 
void RosterManager::sendBuddyRosterRemove(Buddy *buddy) {
 
	Swift::RosterPayload::ref p = Swift::RosterPayload::ref(new Swift::RosterPayload());
src/rosterstorage.cpp
Show inline comments
 
@@ -82,12 +82,18 @@ RosterStorage::RosterStorage(User *user, StorageBackend *storageBackend) {
 
}
 

	
 
RosterStorage::~RosterStorage() {
 
	m_storageTimer->stop();
 
}
 

	
 
void RosterStorage::removeBuddy(Buddy *buddy) {
 
	if (buddy->getID() != -1) {
 
		m_storageBackend->removeBuddy(buddy->getID());
 
	}
 
}
 

	
 
void RosterStorage::storeBuddy(Buddy *buddy) {
 
	if (!buddy) {
 
		return;
 
	}
 
	if (buddy->getName().empty()) {
 
		return;
src/settingsadhoccommand.cpp
Show inline comments
 
@@ -28,20 +28,52 @@
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "SettingsAdHocCommand");
 

	
 
SettingsAdHocCommand::SettingsAdHocCommand(Component *component, const Swift::JID &initiator, const Swift::JID &to) : AdHocCommand(component, initiator, to) {
 
	m_state = Init;
 
}
 

	
 
SettingsAdHocCommand::~SettingsAdHocCommand() {
 
}
 

	
 
boost::shared_ptr<Swift::Command> SettingsAdHocCommand::handleRequest(boost::shared_ptr<Swift::Command> payload) {
 
	boost::shared_ptr<Swift::Command> response;
 
boost::shared_ptr<Swift::Command> SettingsAdHocCommand::getForm() {
 
	boost::shared_ptr<Swift::Command> response(new Swift::Command("settings", m_id, Swift::Command::Executing));
 
	boost::shared_ptr<Swift::Form> form(new Swift::Form());
 

	
 
	BOOST_FOREACH(Swift::FormField::ref field, m_fields) {
 
		form->addField(field);
 
	}
 

	
 
	response->setForm(form);
 
	return response;
 
}
 

	
 
boost::shared_ptr<Swift::Command> SettingsAdHocCommand::handleResponse(boost::shared_ptr<Swift::Command> payload) {
 
	
 
	
 

	
 
	boost::shared_ptr<Swift::Command> response;
 
	response->setStatus(Swift::Command::Completed);
 
	return response;
 
}
 

	
 
boost::shared_ptr<Swift::Command> SettingsAdHocCommand::handleRequest(boost::shared_ptr<Swift::Command> payload) {
 
	boost::shared_ptr<Swift::Command> response;
 

	
 
	switch (m_state) {
 
		case Init:
 
			response = getForm();
 
			m_state = WaitingForResponse;
 
			break;
 
		case WaitingForResponse:
 
			response = handleResponse(payload);
 
			break;
 
		default:
 
			break;
 
	}
 
	
 
	return response;
 
}
 

	
 
}
src/sqlite3backend.cpp
Show inline comments
 
@@ -85,20 +85,23 @@ SQLite3Backend::~SQLite3Backend(){
 
		FINALIZE_STMT(m_setUser);
 
		FINALIZE_STMT(m_getUser);
 
		FINALIZE_STMT(m_removeUser);
 
		FINALIZE_STMT(m_removeUserBuddies);
 
		FINALIZE_STMT(m_removeUserSettings);
 
		FINALIZE_STMT(m_removeUserBuddiesSettings);
 
		FINALIZE_STMT(m_removeBuddy);
 
		FINALIZE_STMT(m_removeBuddySettings);
 
		FINALIZE_STMT(m_addBuddy);
 
		FINALIZE_STMT(m_updateBuddy);
 
		FINALIZE_STMT(m_getBuddies);
 
		FINALIZE_STMT(m_getBuddiesSettings);
 
		FINALIZE_STMT(m_getUserSetting);
 
		FINALIZE_STMT(m_setUserSetting);
 
		FINALIZE_STMT(m_updateUserSetting);
 
		FINALIZE_STMT(m_updateBuddySetting);
 
		FINALIZE_STMT(m_getBuddySetting);
 
		FINALIZE_STMT(m_setUserOnline);
 
		FINALIZE_STMT(m_getOnlineUsers);
 
		sqlite3_close(m_db);
 
	}
 
}
 

	
 
@@ -119,17 +122,21 @@ bool SQLite3Backend::connect() {
 

	
 
	PREP_STMT(m_removeUser, "DELETE FROM " + m_prefix + "users WHERE id=?");
 
	PREP_STMT(m_removeUserBuddies, "DELETE FROM " + m_prefix + "buddies WHERE user_id=?");
 
	PREP_STMT(m_removeUserSettings, "DELETE FROM " + m_prefix + "users_settings WHERE user_id=?");
 
	PREP_STMT(m_removeUserBuddiesSettings, "DELETE FROM " + m_prefix + "buddies_settings WHERE user_id=?");
 

	
 
	PREP_STMT(m_removeBuddy, "DELETE FROM " + m_prefix + "buddies WHERE id=?");
 
	PREP_STMT(m_removeBuddySettings, "DELETE FROM " + m_prefix + "buddies_settings WHERE buddy_id=?");
 

	
 
	PREP_STMT(m_addBuddy, "INSERT INTO " + m_prefix + "buddies (user_id, uin, subscription, groups, nickname, flags) VALUES (?, ?, ?, ?, ?, ?)");
 
	PREP_STMT(m_updateBuddy, "UPDATE " + m_prefix + "buddies SET groups=?, nickname=?, flags=?, subscription=? WHERE user_id=? AND uin=?");
 
	PREP_STMT(m_getBuddies, "SELECT id, uin, subscription, nickname, groups, flags FROM " + m_prefix + "buddies WHERE user_id=? ORDER BY id ASC");
 
	PREP_STMT(m_getBuddiesSettings, "SELECT buddy_id, type, var, value FROM " + m_prefix + "buddies_settings WHERE user_id=? ORDER BY buddy_id ASC");
 
	PREP_STMT(m_updateBuddySetting, "INSERT OR REPLACE INTO " + m_prefix + "buddies_settings (user_id, buddy_id, var, type, value) VALUES (?, ?, ?, ?, ?)");
 
	PREP_STMT(m_getBuddySetting, "SELECT type, value FROM " + m_prefix + "buddies_settings WHERE user_id=? AND buddy_id=? AND var=?");
 
	
 
	PREP_STMT(m_getUserSetting, "SELECT type, value FROM " + m_prefix + "users_settings WHERE user_id=? AND var=?");
 
	PREP_STMT(m_setUserSetting, "INSERT INTO " + m_prefix + "users_settings (user_id, var, type, value) VALUES (?,?,?,?)");
 
	PREP_STMT(m_updateUserSetting, "UPDATE " + m_prefix + "users_settings SET value=? WHERE user_id=? AND var=?");
 

	
 
	PREP_STMT(m_setUserOnline, "UPDATE " + m_prefix + "users SET online=?, last_login=DATETIME('NOW') WHERE id=?");
 
@@ -196,13 +203,17 @@ bool SQLite3Backend::createDatabase() {
 
}
 

	
 
bool SQLite3Backend::exec(const std::string &query) {
 
	char *errMsg = 0;
 
	int rc = sqlite3_exec(m_db, query.c_str(), NULL, 0, &errMsg);
 
	if (rc != SQLITE_OK) {
 
		LOG4CXX_ERROR(logger, errMsg << " during statement " << query);
 
		// This error is OK, because we try to create buddies table every time
 
		// to detect if DB is created properly.
 
		if (errMsg != "table buddies already exists") {
 
			LOG4CXX_ERROR(logger, errMsg << " during statement " << query);
 
		}
 
		sqlite3_free(errMsg);
 
		return false;
 
	}
 
	return true;
 
}
 

	
 
@@ -398,12 +409,28 @@ bool SQLite3Backend::getBuddies(long id, std::list<BuddyInfo> &roster) {
 
		return false;
 
	}
 
	
 
	return true;
 
}
 

	
 
void SQLite3Backend::removeBuddy(long id) {
 
	sqlite3_reset(m_removeBuddy);
 
	sqlite3_bind_int(m_removeBuddy, 1, id);
 
	if(sqlite3_step(m_removeBuddy) != SQLITE_DONE) {
 
		LOG4CXX_ERROR(logger, "removeBuddy query"<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));
 
		return;
 
	}
 

	
 
	sqlite3_reset(m_removeBuddySettings);
 
	sqlite3_bind_int(m_removeBuddySettings, 1, id);
 
	if(sqlite3_step(m_removeBuddySettings) != SQLITE_DONE) {
 
		LOG4CXX_ERROR(logger, "removeBuddySettings query"<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));
 
		return;
 
	}
 
}
 

	
 
bool SQLite3Backend::removeUser(long id) {
 
	sqlite3_reset(m_removeUser);
 
	sqlite3_bind_int(m_removeUser, 1, id);
 
	if(sqlite3_step(m_removeUser) != SQLITE_DONE) {
 
		LOG4CXX_ERROR(logger, "removeUser query"<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));
 
		return false;
 
@@ -460,12 +487,37 @@ void SQLite3Backend::updateUserSetting(long id, const std::string &variable, con
 
	BIND_STR(m_updateUserSetting, value);
 
	BIND_INT(m_updateUserSetting, id);
 
	BIND_STR(m_updateUserSetting, variable);
 
	EXECUTE_STATEMENT(m_updateUserSetting, "m_updateUserSetting");
 
}
 

	
 
void SQLite3Backend::getBuddySetting(long userId, long buddyId, const std::string &variable, int &type, std::string &value) {
 
	BEGIN(m_getBuddySetting);
 
	BIND_INT(m_getBuddySetting, userId);
 
	BIND_INT(m_getBuddySetting, buddyId);
 
	BIND_STR(m_getBuddySetting, variable);
 
	if(sqlite3_step(m_getBuddySetting) == SQLITE_ROW) {
 
		type = GET_INT(m_getBuddySetting);
 
		value = GET_STR(m_getBuddySetting);
 
	}
 

	
 
	int ret;
 
	while((ret = sqlite3_step(m_getBuddySetting)) == SQLITE_ROW) {
 
	}
 
}
 

	
 
void SQLite3Backend::updateBuddySetting(long userId, long buddyId, const std::string &variable, int type, const std::string &value) {
 
	BEGIN(m_updateBuddySetting);
 
	BIND_INT(m_updateBuddySetting, userId);
 
	BIND_INT(m_updateBuddySetting, buddyId);
 
	BIND_STR(m_updateBuddySetting, variable);
 
	BIND_INT(m_updateBuddySetting, type);
 
	BIND_STR(m_updateBuddySetting, value);
 
	EXECUTE_STATEMENT(m_updateBuddySetting, "m_updateBuddySetting");
 
}
 

	
 
void SQLite3Backend::beginTransaction() {
 
	exec("BEGIN TRANSACTION;");
 
}
 

	
 
void SQLite3Backend::commitTransaction() {
 
	exec("COMMIT TRANSACTION;");
src/transport.cpp
Show inline comments
 
@@ -188,12 +188,15 @@ void Component::setBuddyFeatures(std::list<std::string> &features) {
 
	m_discoInfoResponder->setBuddyFeatures(features);
 
}
 

	
 
void Component::start() {
 
	if (m_component && !m_component->isAvailable()) {
 
		LOG4CXX_INFO(logger, "Connecting XMPP server " << CONFIG_STRING(m_config, "service.server") << " port " << CONFIG_INT(m_config, "service.port"));
 
		if (CONFIG_INT(m_config, "service.port") == 5222) {
 
			LOG4CXX_WARN(logger, "Port 5222 is usually used for client connections, not for component connections! Are you sure you are using right port?");
 
		}
 
		m_reconnectCount++;
 
		m_component->connect(CONFIG_STRING(m_config, "service.server"), CONFIG_INT(m_config, "service.port"));
 
		m_reconnectTimer->stop();
 
	}
 
	else if (m_server) {
 
		LOG4CXX_INFO(logger, "Starting component in server mode on port " << CONFIG_INT(m_config, "service.port"));
0 comments (0 inline, 0 general)