Changeset - 90e0395fb34c
CMakeLists.txt
Show inline comments
 
@@ -107,13 +107,13 @@ endif()
 

	
 
###### Database ######
 

	
 
# FIND SQLITE3
 
if (ENABLE_SQLITE3)
 
	if (NOT CMAKE_COMPILER_IS_GNUCXX)
 
		ADD_SUBDIRECTORY(${CMAKE_SOURCE_DIR}/msvc-deps/sqlite3)
 
		ADD_SUBDIRECTORY(${CMAKE_SOURCE_DIR}/msvc-deps)
 
	else()
 
		if (WIN32)
 
			ADD_SUBDIRECTORY(${CMAKE_SOURCE_DIR}/msvc-deps/sqlite3)
 
		else()
 
			set(sqlite3_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
			find_package(sqlite3)
 
@@ -211,16 +211,16 @@ find_package(event)
 

	
 
if (NOT WIN32 AND ENABLE_SKYPE)
 
set(dbus_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(dbus)
 
endif()
 

	
 
if(ENABLE_YAHOO2)
 
	set(yahoo2_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
	find_package(yahoo2)
 
endif()
 
# if(ENABLE_YAHOO2)
 
# 	set(yahoo2_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
# 	find_package(yahoo2)
 
# endif()
 

	
 
####### Miscallanous ######
 

	
 
if(ENABLE_DOCS)
 
	find_package(Doxygen)
 
endif()
 
@@ -387,22 +387,23 @@ if (PROTOBUF_FOUND)
 
	else()
 
		message("Frotz plugin      : no (does not run on Win32)")
 
		message("SMSTools3 plugin  : no (does not run on Win32)")
 
		message("Skype plugin      : no (does not run on Win32)")
 
	endif()
 

	
 
 	if(YAHOO2_FOUND)
 
		message("Libyahoo2 plugin  : yes")
 
 		include_directories(${YAHOO2_INCLUDE_DIR})
 
	else()
 
#  	if(YAHOO2_FOUND)
 
# 		message("Libyahoo2 plugin  : yes")
 
#  		include_directories(${YAHOO2_INCLUDE_DIR})
 
# 	else()
 
		if(ENABLE_YAHOO2)
 
			message("Libyahoo2 plugin  : no (install libyahoo2-devel)")
 
			set(YAHOO2_FOUND 1)
 
			message("Libyahoo2 plugin  : yes")
 
		else(ENABLE_YAHOO2)
 
			message("Libyahoo2 plugin  : no (user disabled)")
 
		endif()
 
 	endif()
 
#  	endif()
 

	
 
	if(ENABLE_SWIFTEN)
 
		message("Swiften plugin    : yes")
 
	else()
 
		message("Swiften plugin    : no (user disabled)")
 
	endif()
backends/libpurple/main.cpp
Show inline comments
 
@@ -336,15 +336,18 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
 
			purple_account_set_bool_wrapped(account, "direct_connect", FALSE);
 

	
 
			setDefaultAccountOptions(account);
 

	
 
			// Enable account + privacy lists
 
			purple_account_set_enabled_wrapped(account, "spectrum", TRUE);
 

	
 
#if PURPLE_MAJOR_VERSION >= 2 && PURPLE_MINOR_VERSION >= 7
 
			if (CONFIG_BOOL(config, "service.enable_privacy_lists")) {
 
				purple_account_set_privacy_type_wrapped(account, PURPLE_PRIVACY_DENY_USERS);
 
			}
 
#endif
 

	
 
			// Set the status
 
			const PurpleStatusType *status_type = purple_account_get_status_type_with_primitive_wrapped(account, PURPLE_STATUS_AVAILABLE);
 
			if (status_type != NULL) {
 
				purple_account_set_status_wrapped(account, purple_status_type_get_id_wrapped(status_type), TRUE, NULL);
 
			}
 
@@ -480,13 +483,15 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
 
		}
 

	
 
		void handleVCardUpdatedRequest(const std::string &user, const std::string &image, const std::string &nickname) {
 
			PurpleAccount *account = m_sessions[user];
 
			if (account) {
 
				purple_account_set_alias_wrapped(account, nickname.c_str());
 
#if PURPLE_MAJOR_VERSION >= 2 && PURPLE_MINOR_VERSION >= 7
 
				purple_account_set_public_alias_wrapped(account, nickname.c_str(), NULL, NULL);
 
#endif
 
				gssize size = image.size();
 
				// this will be freed by libpurple
 
				guchar *photo = (guchar *) g_malloc(size * sizeof(guchar));
 
				memcpy(photo, image.c_str(), size);
 

	
 
				if (!photo)
 
@@ -1112,15 +1117,17 @@ static void *notify_user_info(PurpleConnection *gc, const char *who, PurpleNotif
 
	}
 

	
 
	bool ownInfo = name == purple_account_get_username_wrapped(account);
 

	
 
	if (ownInfo) {
 
		const gchar *displayname = purple_connection_get_display_name_wrapped(gc);
 
#if PURPLE_MAJOR_VERSION >= 2 && PURPLE_MINOR_VERSION >= 7
 
		if (!displayname) {
 
			displayname = purple_account_get_name_for_display_wrapped(account);
 
		}
 
#endif
 

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

	
 
		// avatar
 
@@ -1562,13 +1569,13 @@ static bool initPurple() {
 

	
 
	purple_util_set_user_dir_wrapped(userDir.c_str());
 
	remove("./accounts.xml");
 
	remove("./blist.xml");
 

	
 
	purple_debug_set_ui_ops_wrapped(&debugUiOps);
 
	purple_debug_set_verbose_wrapped(true);
 
// 	purple_debug_set_verbose_wrapped(true);
 

	
 
	purple_core_set_ui_ops_wrapped(&coreUiOps);
 
	if (CONFIG_STRING_DEFAULTED(config, "service.eventloop", "") == "libev") {
 
		LOG4CXX_INFO(logger, "Will use libev based event loop");
 
	}
 
	else {
backends/skype/main.cpp
Show inline comments
 
@@ -3,21 +3,19 @@
 

	
 
#include "transport/config.h"
 
#include "transport/logging.h"
 
#include "transport/transport.h"
 
#include "transport/usermanager.h"
 
#include "transport/memoryusage.h"
 
#include "transport/logger.h"
 
#include "transport/sqlite3backend.h"
 
#include "transport/userregistration.h"
 
#include "transport/user.h"
 
#include "transport/storagebackend.h"
 
#include "transport/rostermanager.h"
 
#include "transport/conversation.h"
 
#include "transport/networkplugin.h"
 
#include "transport/logger.h"
 
#include <boost/filesystem.hpp>
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
// #include "valgrind/memcheck.h"
 
#ifndef __FreeBSD__
 
#include "malloc.h"
 
@@ -694,12 +692,26 @@ static void handle_skype_message(std::string &message, Skype *sk) {
 
			GET_PROPERTY(st, "USER", cmd[1], "ONLINESTATUS");
 
			pbnetwork::StatusType status = getStatus(st);
 

	
 
			std::vector<std::string> groups;
 
			np->handleBuddyChanged(sk->getUser(), cmd[1], alias, groups, status, mood_text);
 
		}
 
		//TODO: handle RECEIVEDAUTHREQUEST and reply it with:
 
// 				void
 
// 				skype_auth_allow(gpointer sender)
 
// 				{
 
// 					skype_send_message("SET USER %s ISAUTHORIZED TRUE", sender);
 
// 					g_free(sender);
 
// 				}
 
// 
 
// 				void
 
// 				skype_auth_deny(gpointer sender)
 
// 				{
 
// 					skype_send_message("SET USER %s ISAUTHORIZED FALSE", sender);
 
// 					g_free(sender);
 
// 				}
 
	}
 
	else if (cmd[0] == "CHATMESSAGE") {
 
		if (cmd[3] == "RECEIVED") {
 
			GET_PROPERTY(body, "CHATMESSAGE", cmd[1], "BODY");
 
			GET_PROPERTY(from_handle, "CHATMESSAGE", cmd[1], "FROM_HANDLE");
 

	
backends/twitter/CMakeLists.txt
Show inline comments
 
@@ -2,10 +2,11 @@ include_directories (${libtransport_SOURCE_DIR}/backends/twitter/libtwitcurl)
 
FILE(GLOB SRC *.cpp libtwitcurl/*.cpp Requests/*.cpp)
 
add_executable(spectrum2_twitter_backend ${SRC})
 

	
 
if (NOT WIN32)
 
target_link_libraries(spectrum2_twitter_backend curl transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
 
else ()
 
include_directories("${CMAKE_SOURCE_DIR}/msvc-deps/curl/include")
 
target_link_libraries(spectrum2_twitter_backend libcurl_imp transport ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
 
endif()
 

	
 
INSTALL(TARGETS spectrum2_twitter_backend RUNTIME DESTINATION bin)
docs/guide/postgresql.textile
Show inline comments
 

	
 
h2. 1. Editing the configuration file
 

	
 
To configure Spectrum 2 to use PostgreSQL database, you have to edit following options in database section:
 
To configure Spectrum 2 to use PostgreSQL database, you have to edit some or more of the following options in database section.  Please note that connectionstring overrides everything else (aside from type).
 

	
 
|_. Section |_. Key |_. Type |_. Change to value |_. Description |
 
| database| type | string | pqxx | Database type - "none", "mysql", "sqlite3", "pqxx". |
 
| database| database | string | Name of the already create empty database | Database used to store data. |
 
| database| server | string | Database server | Database server. |
 
| database| port | string | Database port | Database port. |
 
| database| user | string | PostgreSQL user. | PostgreSQL user. |
 
| database| password | string | PostgreSQL Password. | PostgreSQL Password. |
 
| database| prefix | string | | Prefix of tables in database. |
 
| database| connectionstring | string | Postgres connection string | If you set this, it will ignore all other options above aside from type and prefix.  This allows you to set any typical postgres connection string option, separated by spaces (no semicolons). |
 

	
 
h2. 2. Creating the database
 

	
 
Spectrum 2 will create the database on the first execution. Once the database is created, you can remove the CREATE TABLE permissions to the PostgreSQL database user you use to connect the SQL.
 
\ No newline at end of file
 
Spectrum 2 will create the database on the first execution. Once the database is created, you can remove the CREATE TABLE permissions to the PostgreSQL database user you use to connect the SQL.
 

	
 
h2. 3. Some examples
 

	
 
Using connectionstring:
 
[database]
 
type=pqxx
 
connectionstring=host=localhost database=spectrum2 user=myuser password=whatever
 

	
 
Using traditional options:
 
[database]
 
type=pqxx
 
server=localhost
 
database=spectrum2
 
user=myuser
 
password=whatever
include/transport/buddy.h
Show inline comments
 
@@ -119,16 +119,13 @@ class Buddy {
 
		RosterManager *getRosterManager() { return m_rosterManager; }
 

	
 
		/// Returns legacy network username which does not contain unsafe characters,
 
		/// so it can be used in JIDs.
 
		std::string getSafeName();
 

	
 
		/// This method should be called whenever some information returned by virtual functions changes.
 

	
 
		/// This method sends presence to XMPP user.
 
		void handleBuddyChanged();
 
		void sendPresence();
 

	
 
		/// Handles VCard from legacy network and forwards it to XMPP user.
 

	
 
		/// \param id ID used in IQ-result.
 
		/// \param vcard VCard which will be sent.
 
		void handleVCardReceived(const std::string &id, Swift::VCard::ref vcard);
include/transport/localbuddy.h
Show inline comments
 
@@ -42,24 +42,16 @@ class LocalBuddy : public Buddy {
 
		bool getStatus(Swift::StatusShow &status, std::string &statusMessage) {
 
			status = m_status;
 
			statusMessage = m_statusMessage;
 
			return true;
 
		}
 

	
 
		void setStatus(const Swift::StatusShow &status, const std::string &statusMessage) {
 
			m_status = status;
 
			m_statusMessage = statusMessage;
 
		}
 
		void setStatus(const Swift::StatusShow &status, const std::string &statusMessage);
 

	
 
		std::string getIconHash() { return m_iconHash; }
 
		void setIconHash(const std::string &iconHash) {
 
			bool changed = m_iconHash != iconHash;
 
			m_iconHash = iconHash;
 
			if (changed)
 
				getRosterManager()->storeBuddy(this);
 
		}
 
		void setIconHash(const std::string &iconHash);
 

	
 
		std::vector<std::string> getGroups() { return m_groups; }
 
		void setGroups(const std::vector<std::string> &groups);
 

	
 
		bool isValid() {
 
			std::string safeName = getSafeName();
include/transport/logger.h
Show inline comments
 
deleted file
include/transport/networkpluginserver.h
Show inline comments
 
@@ -133,12 +133,13 @@ class NetworkPluginServer {
 

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

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

	
 
		void pingTimeout();
 
		void sendPing(Backend *c);
 
		Backend *getFreeClient(bool acceptUsers = true, bool longRun = false, bool check = false);
 
@@ -149,12 +150,13 @@ class NetworkPluginServer {
 
		VCardResponder *m_vcardResponder;
 
		RosterResponder *m_rosterResponder;
 
		BlockResponder *m_blockResponder;
 
		Config *m_config;
 
		boost::shared_ptr<Swift::ConnectionServer> m_server;
 
		std::list<Backend *>  m_clients;
 
		std::vector<unsigned long> m_pids;
 
		Swift::Timer::ref m_pingTimer;
 
		Swift::Timer::ref m_collectTimer;
 
		Swift::Timer::ref m_loginTimer;
 
		Component *m_component;
 
		std::list<User *> m_waitingUsers;
 
		bool m_isNextLongRun;
include/transport/userregistration.h
Show inline comments
 
@@ -68,12 +68,13 @@ class UserRegistration : public Swift::Responder<Swift::InBandRegistrationPayloa
 
		boost::signal<void (const UserInfo &userInfo)> onUserUpdated;
 

	
 
	private:
 
		virtual bool handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::InBandRegistrationPayload> payload);
 
		virtual bool handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::InBandRegistrationPayload> payload);
 

	
 
		void handleRegisterRemoteRosterResponse(boost::shared_ptr<Swift::RosterPayload> payload, Swift::ErrorPayload::ref error, const UserInfo &row);
 
		void handleUnregisterRemoteRosterResponse(boost::shared_ptr<Swift::RosterPayload> payload, Swift::ErrorPayload::ref error, const std::string &barejid);
 
		
 
		Component *m_component;
 
		StorageBackend *m_storageBackend;
 
		UserManager *m_userManager;
 
		Config *m_config;
packaging/fedora/spectrum2.spec
Show inline comments
 
@@ -22,13 +22,13 @@ BuildRequires: protobuf-devel
 
BuildRequires: protobuf-compiler
 
BuildRequires: popt-devel
 
BuildRequires: libidn-devel
 
BuildRequires: expat-devel
 
BuildRequires: avahi-devel
 
BuildRequires: log4cxx-devel
 
BuildRequires: swiften-devel
 
#BuildRequires: swiften-devel
 
BuildRequires: libcommuni-devel
 
Requires:      libtransport%{?_isa} = %{version}-%{release}
 

	
 
%description
 
Spectrum 2 is an XMPP transport/gateway and also simple XMPP server.
 

	
spectrum/src/backend-logging.cfg
Show inline comments
 
log4j.rootLogger=debug, R
 

	
 
log4j.appender.R=org.apache.log4j.RollingFileAppender
 
log4j.appender.R.File=/var/log/spectrum2/${jid}/backends/backend-${pid}.log
 
log4j.appender.R.File=/var/log/spectrum2/${jid}/backends/backend-${id}.log
 

	
 
log4j.appender.R.MaxFileSize=10000KB
 
# Keep one backup file
 
log4j.appender.R.MaxBackupIndex=1
 

	
 
log4j.appender.R.layout=org.apache.log4j.PatternLayout
 
log4j.appender.R.layout.ConversionPattern=%d %-5p %c: %m%n
 
log4j.appender.R.layout.ConversionPattern=${pid}: %d %-5p %c: %m%n
spectrum/src/main.cpp
Show inline comments
 
#include "transport/config.h"
 
#include "transport/transport.h"
 
#include "transport/filetransfermanager.h"
 
#include "transport/usermanager.h"
 
#include "transport/logger.h"
 
#include "transport/sqlite3backend.h"
 
#include "transport/mysqlbackend.h"
 
#include "transport/pqxxbackend.h"
 
#include "transport/userregistration.h"
 
#include "transport/networkpluginserver.h"
 
#include "transport/admininterface.h"
 
@@ -129,12 +128,38 @@ static void daemonize(const char *cwd, const char *lock_file) {
 
		std::cout << "EE cannot open /dev/null. Exiting\n";
 
		exit(1);
 
	}
 
}
 
#endif
 

	
 
static void _createDirectories(Transport::Config *config, boost::filesystem::path ph) {
 
	if (ph.empty() || exists(ph)) {
 
		return;
 
	}
 

	
 
	// First create branch, by calling ourself recursively
 
	_createDirectories(config, ph.branch_path());
 
	
 
	// Now that parent's path exists, create the directory
 
	boost::filesystem::create_directory(ph);
 

	
 
#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";
 
		}
 
		struct passwd *pw;
 
		if ((pw = getpwnam(CONFIG_STRING(config, "service.user").c_str())) == NULL) {
 
			std::cerr << "Invalid service.user name " << CONFIG_STRING(config, "service.user") << "\n";
 
		}
 
		chown(ph.string().c_str(), pw->pw_uid, gr->gr_gid);
 
	}
 
#endif
 
}
 

	
 
int mainloop() {
 

	
 
#ifndef WIN32
 
	mode_t old_cmask = umask(0007);
 
#endif
 

	
 
@@ -214,12 +239,15 @@ int mainloop() {
 
	if (storageBackend) {
 
		userRegistration = new UserRegistration(&transport, &userManager, storageBackend);
 
		userRegistration->start();
 

	
 
		usersReconnecter = new UsersReconnecter(&transport, storageBackend);
 
	}
 
	else if (!CONFIG_BOOL(config_, "service.server_mode")) {
 
		LOG4CXX_WARN(logger, "Registrations won't work, you have specified [database] type=none in config file.");
 
	}
 

	
 
	FileTransferManager ftManager(&transport, &userManager);
 

	
 
	NetworkPluginServer plugin(&transport, config_, &userManager, &ftManager, &discoItemsResponder);
 
	plugin.start();
 

	
 
@@ -395,14 +423,13 @@ int main(int argc, char **argv)
 
		std::cerr << "Can't load configuration file.\n";
 
		return 1;
 
	}
 

	
 
	// create directories
 
	try {
 
		
 
		Transport::Util::createDirectories(&config, CONFIG_STRING(&config, "service.working_dir"));
 
		_createDirectories(&config, boost::filesystem::path(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;
 
	}
 
#ifndef WIN32
 
@@ -448,13 +475,19 @@ int main(int argc, char **argv)
 
	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");
 
    }
 
	}
 
	else {
 
		if ((chdir(CONFIG_STRING(&config, "service.working_dir").c_str())) < 0) {
 
			std::cerr << "Cannot change directory to " << CONFIG_STRING(&config, "service.working_dir") << "\n";
 
			exit(1);
 
		}
 
	}
 
#endif
 
#ifdef WIN32
 
	if (!run_service_name.empty()) {
 
		ServiceWrapper ntservice((char *)run_service_name.c_str());
 
		if (ntservice.IsInstalled()) {
 
			ntservice.RunService();
spectrum/src/sample2.cfg
Show inline comments
 
@@ -93,12 +93,16 @@ type = none
 
# Paasword.
 
#password = secret
 

	
 
# Prefix used for tables
 
#prefix = jabber_
 

	
 
# Connection string (for pqxx only!)
 
# If you set this, it ignores every other database option except for type and prefix.
 
#connectionstring = host=localhost user=specturm password=secret
 

	
 
[registration]
 
# Enable public registrations
 
enable_public_registration=1
 

	
 
# Text to display upon user registration form
 
#username_label=Jabber JID (e.g. user@server.tld):
spectrum_manager/src/main.cpp
Show inline comments
 
@@ -79,12 +79,13 @@ int main(int argc, char **argv)
 
	boost::program_options::variables_map vm;
 
 
	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"
 
													 " restart  - restart all local Spectrum2 instances\n"
 
													 " status - status of local Spectrum2 instances\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")
 
@@ -161,12 +162,15 @@ int main(int argc, char **argv)
 
			return start_instances(&config, jid);
 
		}
 
		else if (cmd == "stop") {
 
			stop_instances(&config, jid);
 
			return 0;
 
		}
 
		else if (cmd == "restart") {
 
			return restart_instances(&config, jid);
 
		}
 
 
		ask_local_server(&config, networkFactories, jid, cmd);
 
// 		std::string message = command;
 
// 		m = &message;
 
 
// 		ask_local_server(&config, networkFactories, message);
spectrum_manager/src/methods.cpp
Show inline comments
 
@@ -273,12 +273,106 @@ void stop_instances(ManagerConfig *config, const std::string &_jid) {
 
	catch (const filesystem_error& ex) {
 
		std::cerr << "Filesystem error: " << ex.what() << "\n";
 
		exit(5);
 
	}
 
}
 

	
 
int restart_instances(ManagerConfig *config, const std::string &_jid) {
 
	response = "";
 
	path p(CONFIG_STRING(config, "service.config_directory"));
 
	int rv = 0;
 
	int rc;
 

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

	
 
		std::string spectrum2_binary = searchForBinary("spectrum2");
 
		if (spectrum2_binary.empty()) {
 
			std::cerr << "spectrum2 binary not found in PATH\n";
 
			return 8;
 
		}
 

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

	
 
				std::vector<std::string> vhosts;
 
				if (CONFIG_HAS_KEY(&cfg, "vhosts.vhost"))
 
					vhosts = CONFIG_VECTOR(&cfg, "vhosts.vhost");
 
				vhosts.push_back(CONFIG_STRING(&cfg, "service.jid"));
 

	
 
				BOOST_FOREACH(std::string &vhost, vhosts) {
 
					Config vhostCfg;
 
					if (vhostCfg.load(itr->path().string(), vhost) == false) {
 
						std::cerr << "Can't load config file " << itr->path().string() << ". Skipping...\n";
 
						continue;
 
					}
 

	
 
					if (!_jid.empty() && _jid != vhost) {
 
						continue;
 
					}
 

	
 
					int pid = isRunning(CONFIG_STRING(&vhostCfg, "service.pidfile"));
 
					if (pid) {
 
						response ="Stopping " + itr->path().string() + ": ";
 
						std::cout << "Stopping " << itr->path() << ": ";
 
						kill(pid, SIGTERM);
 

	
 
						sleep(1);
 
						int count = 20;
 
						while (kill(pid, 0) == 0 && count != 0) {
 
							std::cout << ".";
 
							sleep(1);
 
							count--;
 
						}
 
						if (count == 0) {
 
							response += "ERROR (timeout)\n";
 
							std::cout << " ERROR (timeout)\n";
 
						}
 
						else {
 
							response += "OK\n";
 
							std::cout << " OK\n";
 

	
 
							response = "Starting " + itr->path().string() + ": OK\n";
 
							std::cout << "Starting " << itr->path() << ": OK\n";
 
							exec_(spectrum2_binary, itr->path().string(), vhost, rc);
 
							if (rv == 0) {
 
								rv = rc;
 
							}
 
						}
 

	
 
						
 
					}
 
					else {
 
						response = "Stopping " + itr->path().string() + ": Not running\n";
 
						std::cout << "Stopping " << itr->path() << ": Not running\n";
 
					}
 
				}
 
			}
 
		}
 
	}
 
	catch (const filesystem_error& ex) {
 
		std::cerr << "Filesystem error: " << ex.what() << "\n";
 
		exit(5);
 
	}
 

	
 
	return rv;
 
}
 

	
 
int show_status(ManagerConfig *config) {
 
	int ret = 0;
 
	path p(CONFIG_STRING(config, "service.config_directory"));
 

	
 
	try {
 
		if (!exists(p)) {
spectrum_manager/src/methods.h
Show inline comments
 
@@ -42,12 +42,13 @@ std::string searchForBinary(const std::string &binary);
 
unsigned long exec_(std::string path, std::string config, std::string jid = "");
 

	
 
int getPort(const std::string &portfile);
 

	
 
int isRunning(const std::string &pidfile);
 
int start_instances(ManagerConfig *config, const std::string &_jid = "");
 
int restart_instances(ManagerConfig *config, const std::string &_jid = "");
 
void stop_instances(ManagerConfig *config, const std::string &_jid = "");
 

	
 
int show_status(ManagerConfig *config);
 

	
 
void ask_local_server(ManagerConfig *config, Swift::BoostNetworkFactories &networkFactories, const std::string &jid, const std::string &message);
 

	
src/buddy.cpp
Show inline comments
 
@@ -34,12 +34,19 @@ Buddy::Buddy(RosterManager *rosterManager, long id, BuddyFlag flags) : m_id(id),
 
}
 

	
 
Buddy::~Buddy() {
 
// 	m_rosterManager->unsetBuddy(this);
 
}
 

	
 
void Buddy::sendPresence() {
 
	Swift::Presence::ref presence = generatePresenceStanza(255);
 
	if (presence) {
 
		m_rosterManager->getUser()->getComponent()->getStanzaChannel()->sendPresence(presence);
 
	}
 
}
 

	
 
void Buddy::generateJID() {
 
	m_jid = Swift::JID();
 
	m_jid = Swift::JID(getSafeName(), m_rosterManager->getUser()->getComponent()->getJID().toString(), "bot");
 
}
 

	
 
void Buddy::setID(long id) {
 
@@ -147,19 +154,12 @@ std::string Buddy::getSafeName() {
 
// 	if (name.empty()) {
 
// 		Log("SpectrumBuddy::getSafeName", "Name is EMPTY! Previous was " << getName() << ".");
 
// 	}
 
	return name;
 
}
 

	
 
void Buddy::handleBuddyChanged() {
 
	Swift::Presence::ref presence = generatePresenceStanza(255);
 
	if (presence) {
 
		m_rosterManager->getUser()->getComponent()->getStanzaChannel()->sendPresence(presence);
 
	}
 
}
 

	
 
void Buddy::handleVCardReceived(const std::string &id, Swift::VCard::ref vcard) {
 
	boost::shared_ptr<Swift::GenericRequest<Swift::VCard> > request(new Swift::GenericRequest<Swift::VCard>(Swift::IQ::Result, m_rosterManager->getUser()->getJID(), vcard, m_rosterManager->getUser()->getComponent()->getIQRouter()));
 
	request->send();
 
}
 

	
 
std::string Buddy::JIDToLegacyName(const Swift::JID &jid) {
src/config.cpp
Show inline comments
 
@@ -360,13 +360,13 @@ Config *Config::createFromArgs(int argc, char **argv, std::string &error, std::s
 
			error = os.str();
 
			return NULL;
 
		}
 
	}
 
	catch (std::runtime_error& e)
 
	{
 
		error = os.str();
 
		error = std::string(e.what()) + "\n" + os.str();
 
		return NULL;
 
	}
 
	catch (...)
 
	{
 
		error = os.str();
 
		return NULL;
src/localbuddy.cpp
Show inline comments
 
@@ -34,12 +34,30 @@ LocalBuddy::LocalBuddy(RosterManager *rosterManager, long id, const std::string
 
	}
 
}
 

	
 
LocalBuddy::~LocalBuddy() {
 
}
 

	
 
void LocalBuddy::setStatus(const Swift::StatusShow &status, const std::string &statusMessage) {
 
	bool changed = ((m_status.getType() != status.getType()) || (m_statusMessage != statusMessage));
 
	if (changed) {
 
		m_status = status;
 
		m_statusMessage = statusMessage;
 
		sendPresence();
 
	}
 
}
 

	
 
void LocalBuddy::setIconHash(const std::string &iconHash) {
 
	bool changed = m_iconHash != iconHash;
 
	m_iconHash = iconHash;
 
	if (changed) {
 
		getRosterManager()->storeBuddy(this);
 
		sendPresence();
 
	}
 
}
 

	
 
bool LocalBuddy::setName(const std::string &name) {
 
	if (name == m_name) {
 
		return true;
 
	}
 
	std::string oldName = name;
 
	m_name = name;
src/logger.cpp
Show inline comments
 
deleted file
src/logging.cpp
Show inline comments
 
@@ -88,14 +88,17 @@ private:
 
};
 

	
 
static intercept_stream* intercepter_cout;
 
static intercept_stream* intercepter_cerr;
 

	
 

	
 
static void initLogging(Config *config, std::string key) {
 
static void initLogging(Config *config, std::string key, bool only_create_dir = false) {
 
	if (CONFIG_STRING(config, key).empty()) {
 
		if (only_create_dir) {
 
			return;
 
		}
 
		root = log4cxx::Logger::getRootLogger();
 
#ifdef _MSC_VER
 
		root->addAppender(new ConsoleAppender(new PatternLayout(L"%d %-5p %c: %m%n")));
 
#else
 
		root->addAppender(new ConsoleAppender(new PatternLayout("%d %-5p %c: %m%n")));
 
#endif
 
@@ -116,30 +119,35 @@ static void initLogging(Config *config, std::string key) {
 

	
 
		if (!istream) {
 
			return;
 
		}
 

	
 
		p.load(istream);
 
		LogString pid, jid;
 
		LogString pid, jid, id;
 
		log4cxx::helpers::Transcoder::decode(boost::lexical_cast<std::string>(getpid()), pid);
 
		log4cxx::helpers::Transcoder::decode(CONFIG_STRING(config, "service.jid"), jid);
 
		log4cxx::helpers::Transcoder::decode(CONFIG_STRING_DEFAULTED(config, "service.backend_id", ""), id);
 
#ifdef _MSC_VER
 
		p.setProperty(L"pid", pid);
 
		p.setProperty(L"jid", jid);
 
		p.setProperty(L"id", id);
 
#else
 
		p.setProperty("pid", pid);
 
		p.setProperty("jid", jid);
 
		p.setProperty("id", id);
 
#endif
 

	
 
		std::string dir;
 
		BOOST_FOREACH(const log4cxx::LogString &prop, p.propertyNames()) {
 
			if (boost::ends_with(prop, ".File")) {
 
// 			if (boost::ends_with(prop, ".File")) {
 
				log4cxx::helpers::Transcoder::encode(p.get(prop), dir);
 
				boost::replace_all(dir, "${jid}", jid);
 
				boost::replace_all(dir, "${pid}", pid);
 
				boost::replace_all(dir, "${id}", id);
 
				break;
 
			}
 
// 			}
 
		}
 
		mode_t old_cmask;
 
		if (!dir.empty()) {
 
			// create directories
 
#ifndef WIN32
 
			old_cmask = umask(0007);
 
@@ -149,12 +157,16 @@ static void initLogging(Config *config, std::string key) {
 
			}
 
			catch (const boost::filesystem::filesystem_error &e) {
 
				std::cerr << "Can't create logging directory directory " << boost::filesystem::path(dir).parent_path().string() << ": " << e.what() << ".\n";
 
			}
 
		}
 

	
 
		if (only_create_dir) {
 
			return;
 
		}
 

	
 
		log4cxx::PropertyConfigurator::configure(p);
 

	
 
		// Change owner of main log file
 
#ifndef WIN32
 
	if (!CONFIG_STRING(config, "service.group").empty() && !CONFIG_STRING(config, "service.user").empty()) {
 
		struct group *gr;
 
@@ -182,12 +194,13 @@ void initBackendLogging(Config *config) {
 

	
 
	redirect_stderr();
 
}
 

	
 
void initMainLogging(Config *config) {
 
	initLogging(config, "logging.config");
 
	initLogging(config, "logging.backend_config", true);
 
}
 

	
 
void redirect_stderr() {
 
	 intercepter_cerr = new intercept_stream(std::cerr, "cerr");
 
	 intercepter_cout = new intercept_stream(std::cout, "cout");
 
}
src/networkpluginserver.cpp
Show inline comments
 
@@ -68,12 +68,14 @@ namespace Transport {
 

	
 
static unsigned long backend_id;
 
static unsigned long bytestream_id;
 

	
 
DEFINE_LOGGER(logger, "NetworkPluginServer");
 

	
 
static NetworkPluginServer *_server;
 

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

	
 
		// Called when there's new message to legacy network from XMPP network
 
@@ -125,13 +127,13 @@ class NetworkFactory : public Factory {
 
#define WRAP(MESSAGE, TYPE) 	pbnetwork::WrapperMessage wrap; \
 
	wrap.set_type(TYPE); \
 
	wrap.set_payload(MESSAGE); \
 
	wrap.SerializeToString(&MESSAGE);
 

	
 
// Executes new backend
 
static unsigned long exec_(const std::string& exePath, const char *host, const char *port, const char *cmdlineArgs) {
 
static unsigned long exec_(const std::string& exePath, const char *host, const char *port, const char *log_id, const char *cmdlineArgs) {
 
	// BACKEND_ID is replaced with unique ID. The ID is increasing for every backend.
 
	std::string finalExePath = boost::replace_all_copy(exePath, "BACKEND_ID", boost::lexical_cast<std::string>(backend_id++));	
 

	
 
#ifdef _WIN32
 
	// Add host and port.
 
	std::ostringstream fullCmdLine;
 
@@ -168,13 +170,13 @@ static unsigned long exec_(const std::string& exePath, const char *host, const c
 
		LOG4CXX_ERROR(logger, "Could not start process");
 
	}
 

	
 
	return 0;
 
#else
 
	// Add host and port.
 
	finalExePath += std::string(" --host ") + host + " --port " + port + " " + cmdlineArgs;
 
	finalExePath += std::string(" --host ") + host + " --port " + port + " --service.backend_id=" + log_id + " " + cmdlineArgs;
 
	LOG4CXX_INFO(logger, "Starting new backend " << finalExePath);
 

	
 
	// Create array of char * from string using -lpopt library
 
	char *p = (char *) malloc(finalExePath.size() + 1);
 
	strcpy(p, finalExePath.c_str());
 
	int argc;
 
@@ -211,12 +213,13 @@ static void SigCatcher(int n) {
 
	pid_t result;
 
	int status;
 
	// Read exit code from all children to not have zombies arround
 
	// WARNING: Do not put LOG4CXX_ here, because it can lead to deadlock
 
	while ((result = waitpid(-1, &status, WNOHANG)) > 0) {
 
		if (result != 0) {
 
			_server->handlePIDTerminated((unsigned long)result);
 
			if (WIFEXITED(status)) {
 
				if (WEXITSTATUS(status) != 0) {
 
// 					LOG4CXX_ERROR(logger, "Backend can not be started, exit_code=" << WEXITSTATUS(status));
 
				}
 
			}
 
			else {
 
@@ -248,12 +251,13 @@ static void handleBuddyPayload(LocalBuddy *buddy, const pbnetwork::Buddy &payloa
 
	buddy->setStatus(Swift::StatusShow((Swift::StatusShow::Type) payload.status()), payload.statusmessage());
 
	buddy->setIconHash(payload.iconhash());
 
	buddy->setBlocked(payload.blocked());
 
}
 

	
 
NetworkPluginServer::NetworkPluginServer(Component *component, Config *config, UserManager *userManager, FileTransferManager *ftManager, DiscoItemsResponder *discoItemsResponder) {
 
	_server = this;
 
	m_ftManager = ftManager;
 
	m_userManager = userManager;
 
	m_config = config;
 
	m_component = component;
 
	m_isNextLongRun = false;
 
	m_adminInterface = NULL;
 
@@ -321,13 +325,13 @@ NetworkPluginServer::~NetworkPluginServer() {
 
void NetworkPluginServer::start() {
 
	m_server->start();
 

	
 
	LOG4CXX_INFO(logger, "Listening on host " << CONFIG_STRING(m_config, "service.backend_host") << " port " << CONFIG_STRING(m_config, "service.backend_port"));
 

	
 
	while (true) {
 
		unsigned long pid = exec_(CONFIG_STRING(m_config, "service.backend"), CONFIG_STRING(m_config, "service.backend_host").c_str(), CONFIG_STRING(m_config, "service.backend_port").c_str(), m_config->getCommandLineArgs().c_str());
 
		unsigned long pid = exec_(CONFIG_STRING(m_config, "service.backend"), CONFIG_STRING(m_config, "service.backend_host").c_str(), CONFIG_STRING(m_config, "service.backend_port").c_str(), "1", m_config->getCommandLineArgs().c_str());
 
		LOG4CXX_INFO(logger, "Tried to spawn first backend with pid " << pid);
 
		LOG4CXX_INFO(logger, "Backend should now connect to Spectrum2 instance. Spectrum2 won't accept any connection before backend connects");
 

	
 
#ifndef _WIN32
 
		// wait if the backend process will still be alive after 1 second
 
		sleep(1);
 
@@ -350,12 +354,14 @@ void NetworkPluginServer::start() {
 
			else {
 
				LOG4CXX_ERROR(logger, "Backend can not be started");
 
				continue;
 
			}
 
		}
 

	
 
		m_pids.push_back(pid);
 

	
 
		signal(SIGCHLD, SigCatcher);
 
#endif
 
		// quit the while loop
 
		break;
 
	}
 
}
 
@@ -552,13 +558,12 @@ void NetworkPluginServer::handleBuddyChangedPayload(const std::string &data) {
 
	if (!user)
 
		return;
 

	
 
	LocalBuddy *buddy = (LocalBuddy *) user->getRosterManager()->getBuddy(payload.buddyname());
 
	if (buddy) {
 
		handleBuddyPayload(buddy, payload);
 
		buddy->handleBuddyChanged();
 
	}
 
	else {
 
		if (payload.buddyname() == user->getUserInfo().uin) {
 
			return;
 
		}
 

	
 
@@ -574,16 +579,16 @@ void NetworkPluginServer::handleBuddyChangedPayload(const std::string &data) {
 
		}
 
		if (!buddy->isValid()) {
 
			delete buddy;
 
			return;
 
		}
 

	
 
		buddy->setStatus(Swift::StatusShow((Swift::StatusShow::Type) payload.status()), payload.statusmessage());
 
		buddy->setIconHash(payload.iconhash());
 
		buddy->setBlocked(payload.blocked());
 
		user->getRosterManager()->setBuddy(buddy);
 
		buddy->setStatus(Swift::StatusShow((Swift::StatusShow::Type) payload.status()), payload.statusmessage());
 
		buddy->setIconHash(payload.iconhash());
 
	}
 
}
 

	
 
void NetworkPluginServer::handleBuddyRemovedPayload(const std::string &data) {
 
	pbnetwork::Buddy payload;
 
	if (payload.ParseFromString(data) == false) {
 
@@ -705,12 +710,16 @@ void NetworkPluginServer::handleConvMessageAckPayload(const std::string &data) {
 
	}
 

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

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

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

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

	
 
@@ -1653,19 +1662,74 @@ void NetworkPluginServer::sendPing(Backend *c) {
 
		send(c->connection, message);
 
		c->pongReceived = false;
 
	}
 
// 	LOG4CXX_INFO(logger, "PING to " << c);
 
}
 

	
 
void NetworkPluginServer::handlePIDTerminated(unsigned long pid) {
 
	std::vector<unsigned long>::iterator log_id_it;
 
	log_id_it = std::find(m_pids.begin(), m_pids.end(), pid);
 
	if (log_id_it != m_pids.end()) {
 
		*log_id_it = 0;
 
	}
 
}
 

	
 
#ifndef _WIN32
 

	
 
static int sig_block_count = 0;
 
static sigset_t block_mask;
 

	
 
static void __block_signals ( void )
 
{
 
  static int init_done = 0;
 

	
 
  if ( (sig_block_count++) != 1 ) return;
 

	
 
  if ( init_done == 0 ) {
 
    sigemptyset ( &block_mask );
 
    sigaddset ( &block_mask, SIGPIPE );
 
    sigaddset ( &block_mask, SIGHUP );
 
    sigaddset ( &block_mask, SIGINT );
 
    sigaddset ( &block_mask, SIGQUIT );
 
    sigaddset ( &block_mask, SIGTERM );
 
    sigaddset ( &block_mask, SIGABRT );
 
    sigaddset ( &block_mask, SIGCHLD );
 
    init_done = 1;
 
  }
 

	
 
  sigprocmask ( SIG_BLOCK, &block_mask, NULL );
 
  return;
 
}
 

	
 
static void __unblock_signals ( void )
 
{
 
  sigset_t sigset;
 

	
 
  if ( (sig_block_count--) != 0 ) return;
 
  sigprocmask ( SIG_UNBLOCK, &block_mask, NULL );
 

	
 
  if ( sigpending ( &sigset ) == 0 ) {
 
    if ( sigismember ( &sigset, SIGCHLD ) ) {
 
      raise ( SIGCHLD );
 
    }
 
  }
 
}
 

	
 
#endif
 

	
 
NetworkPluginServer::Backend *NetworkPluginServer::getFreeClient(bool acceptUsers, bool longRun, bool check) {
 
	NetworkPluginServer::Backend *c = NULL;
 

	
 
	unsigned long diff = CONFIG_INT(m_config, "service.login_delay");
 
	time_t now = time(NULL);
 
	if (diff && (now - m_lastLogin < diff)) {
 
		m_loginTimer->stop();
 
		m_loginTimer = m_component->getNetworkFactories()->getTimerFactory()->createTimer((diff - (now - m_lastLogin)) * 1000);
 
		m_loginTimer->onTick.connect(boost::bind(&NetworkPluginServer::loginDelayFinished, this));
 
		m_loginTimer->start();
 
		LOG4CXX_INFO(logger, "Postponing login because of service.login_delay setting");
 
		return NULL;
 
	}
 

	
 
	if (!check) {
 
		m_lastLogin = time(NULL);
 
	}
 
@@ -1673,25 +1737,47 @@ NetworkPluginServer::Backend *NetworkPluginServer::getFreeClient(bool acceptUser
 
	// Check all backends and find free one
 
	for (std::list<Backend *>::const_iterator it = m_clients.begin(); it != m_clients.end(); it++) {
 
		if ((*it)->willDie == false && (*it)->acceptUsers == acceptUsers && (*it)->users.size() < CONFIG_INT(m_config, "service.users_per_backend") && (*it)->connection && (*it)->longRun == longRun) {
 
			c = *it;
 
			// if we're not reusing all backends and backend is full, stop accepting new users on this backend
 
			if (!CONFIG_BOOL(m_config, "service.reuse_old_backends")) {
 
				if (c->users.size() + 1 >= CONFIG_INT(m_config, "service.users_per_backend")) {
 
				if (!check && c->users.size() + 1 >= CONFIG_INT(m_config, "service.users_per_backend")) {
 
					c->acceptUsers = false;
 
				}
 
			}
 
			break;
 
		}
 
	}
 

	
 
	// there's no free backend, so spawn one.
 
	if (c == NULL && !m_startingBackend) {
 
		m_isNextLongRun = longRun;
 
		m_startingBackend = true;
 
		exec_(CONFIG_STRING(m_config, "service.backend"), CONFIG_STRING(m_config, "service.backend_host").c_str(), CONFIG_STRING(m_config, "service.backend_port").c_str(), m_config->getCommandLineArgs().c_str());
 

	
 
#ifndef _WIN32
 
		__block_signals();
 
#endif
 
		std::vector<unsigned long>::iterator log_id_it;
 
		log_id_it = std::find(m_pids.begin(), m_pids.end(), 0);
 
		std::string log_id = "";
 
		if (log_id_it == m_pids.end()) {
 
			log_id = boost::lexical_cast<std::string>(m_pids.size() + 1);
 
		}
 
		else {
 
			log_id = boost::lexical_cast<std::string>(log_id_it - m_pids.begin() + 1);
 
		}
 
		unsigned long pid = exec_(CONFIG_STRING(m_config, "service.backend"), CONFIG_STRING(m_config, "service.backend_host").c_str(), CONFIG_STRING(m_config, "service.backend_port").c_str(), log_id.c_str(), m_config->getCommandLineArgs().c_str());
 
		if (log_id_it == m_pids.end()) {
 
			m_pids.push_back(pid);
 
		}
 
		else {
 
			*log_id_it = pid;
 
		}
 
#ifndef _WIN32
 
		__unblock_signals();
 
#endif
 
	}
 

	
 
	return c;
 
}
 

	
 
}
src/pqxxbackend.cpp
Show inline comments
 
@@ -45,24 +45,40 @@ void PQXXBackend::disconnect() {
 
	LOG4CXX_INFO(logger, "Disconnecting");
 

	
 
	delete m_conn;
 
}
 

	
 
bool PQXXBackend::connect() {
 
	LOG4CXX_INFO(logger, "Connecting PostgreSQL server " << CONFIG_STRING(m_config, "database.server") << ", user " <<
 
		CONFIG_STRING(m_config, "database.user") << ", database " << CONFIG_STRING(m_config, "database.database") <<
 
		", port " << CONFIG_INT(m_config, "database.port")
 
	);
 
	
 
	std::string str = "dbname=";
 
	str += CONFIG_STRING(m_config, "database.database") + " ";
 

	
 
	str += "user=" + CONFIG_STRING(m_config, "database.user") + " ";
 
	std::string connection_str;
 
	connection_str = CONFIG_STRING_DEFAULTED(m_config, "database.connectionstring", "");
 
	if (connection_str.empty()) {
 
		LOG4CXX_INFO(logger, "Connecting PostgreSQL server " << CONFIG_STRING(m_config, "database.server") << ", user " <<
 
			CONFIG_STRING(m_config, "database.user") << ", dbname " << CONFIG_STRING(m_config, "database.database") <<
 
			", port " << CONFIG_INT(m_config, "database.port")
 
		);
 
		connection_str = "dbname=";
 
		connection_str += CONFIG_STRING(m_config, "database.database");
 
		if (!CONFIG_STRING(m_config, "database.server").empty()) {
 
			connection_str += " host=" + CONFIG_STRING(m_config, "database.server");
 
		}
 
		if (!CONFIG_STRING(m_config, "database.user").empty()) {
 
			connection_str += " user=" + CONFIG_STRING(m_config, "database.user");
 
		}
 
		if (!CONFIG_STRING(m_config, "database.password").empty()) {
 
			connection_str += " password=" + CONFIG_STRING(m_config, "database.password");
 
		}
 
		if (CONFIG_INT(m_config, "database.port") != 0) {
 
			connection_str += " port=" + boost::lexical_cast<std::string>(CONFIG_INT(m_config, "database.port"));
 
		}
 
	}
 
	else {
 
		LOG4CXX_INFO(logger, "Connecting PostgreSQL server via provided connection string.");
 
	}
 

	
 
	try {
 
		m_conn = new pqxx::connection(str);
 
		m_conn = new pqxx::connection(connection_str);
 
	}
 
	catch (std::exception& e) {
 
		LOG4CXX_ERROR(logger, e.what());
 
		return false;
 
	}
 

	
src/rostermanager.cpp
Show inline comments
 
@@ -254,13 +254,16 @@ void RosterManager::storeBuddy(Buddy *buddy) {
 
	}
 
}
 

	
 
void RosterManager::handleBuddyRosterPushResponse(Swift::ErrorPayload::ref error, Swift::SetRosterRequest::ref request, const std::string &key) {
 
	LOG4CXX_INFO(logger, "handleBuddyRosterPushResponse called for buddy " << key);
 
	if (m_buddies[key] != NULL) {
 
		m_buddies[key]->handleBuddyChanged();
 
		Swift::Presence::ref presence = m_buddies[key]->generatePresenceStanza(255);
 
		if (presence && presence->getType() == Swift::Presence::Available) {
 
			m_component->getStanzaChannel()->sendPresence(presence);
 
		}
 
	}
 
	else {
 
		LOG4CXX_WARN(logger, "handleBuddyRosterPushResponse called for unknown buddy " << key);
 
	}
 

	
 
	m_requests.remove(request);
 
@@ -574,13 +577,13 @@ void RosterManager::sendCurrentPresences(const Swift::JID &to) {
 
	for (std::map<std::string, Buddy *, std::less<std::string>, boost::pool_allocator< std::pair<std::string, Buddy *> > >::iterator it = m_buddies.begin(); it != m_buddies.end(); it++) {
 
		Buddy *buddy = (*it).second;
 
		if (!buddy) {
 
			continue;
 
		}
 
		Swift::Presence::ref presence = buddy->generatePresenceStanza(255);
 
		if (presence) {
 
		if (presence && presence->getType() == Swift::Presence::Available) {
 
			presence->setTo(to);
 
			m_component->getStanzaChannel()->sendPresence(presence);
 
		}
 
	}
 
}
 

	
 
@@ -606,13 +609,13 @@ void RosterManager::sendUnavailablePresences(const Swift::JID &to) {
 
	for (std::map<std::string, Buddy *, std::less<std::string>, boost::pool_allocator< std::pair<std::string, Buddy *> > >::iterator it = m_buddies.begin(); it != m_buddies.end(); it++) {
 
		Buddy *buddy = (*it).second;
 
		if (!buddy) {
 
			continue;
 
		}
 
		Swift::Presence::ref presence = buddy->generatePresenceStanza(255);
 
		if (presence) {
 
		if (presence && presence->getType() == Swift::Presence::Available) {
 
			presence->setTo(to);
 
			presence->setType(Swift::Presence::Unavailable);
 
			m_component->getStanzaChannel()->sendPresence(presence);
 
		}
 
	}
 

	
src/sqlite3backend.cpp
Show inline comments
 
@@ -346,12 +346,13 @@ bool SQLite3Backend::getBuddies(long id, std::list<BuddyInfo> &roster) {
 

	
 
	SettingVariableInfo var;
 
	long buddy_id = -1;
 
	std::string key;
 

	
 
	int ret;
 
	int ret2 = -10;
 
	while((ret = sqlite3_step(m_getBuddies)) == SQLITE_ROW) {
 
		BuddyInfo b;
 
		RESET_GET_COUNTER(m_getBuddies);
 
		b.id = GET_INT(m_getBuddies);
 
		b.legacyName = GET_STR(m_getBuddies);
 
		b.subscription = GET_STR(m_getBuddies);
 
@@ -363,13 +364,13 @@ bool SQLite3Backend::getBuddies(long id, std::list<BuddyInfo> &roster) {
 
		if (buddy_id == b.id) {
 
			std::cout << "Adding buddy info " << key << "\n";
 
			b.settings[key] = var;
 
			buddy_id = -1;
 
		}
 

	
 
		while(buddy_id == -1 && (ret = sqlite3_step(m_getBuddiesSettings)) == SQLITE_ROW) {
 
		while(buddy_id == -1 && ret2 != SQLITE_DONE && ret2 != SQLITE_ERROR && (ret2 = sqlite3_step(m_getBuddiesSettings)) == SQLITE_ROW) {
 
			RESET_GET_COUNTER(m_getBuddiesSettings);
 
			buddy_id = GET_INT(m_getBuddiesSettings);
 
			
 
			var.type = GET_INT(m_getBuddiesSettings);
 
			key = GET_STR(m_getBuddiesSettings);
 
			std::string val = GET_STR(m_getBuddiesSettings);
 
@@ -400,19 +401,31 @@ bool SQLite3Backend::getBuddies(long id, std::list<BuddyInfo> &roster) {
 
// 			return false;
 
// 		}
 

	
 
		roster.push_back(b);
 
	}
 

	
 
	while((ret = sqlite3_step(m_getBuddiesSettings)) == SQLITE_ROW) {
 
	}
 

	
 
	if (ret != SQLITE_DONE) {
 
		LOG4CXX_ERROR(logger, "getBuddies query"<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));
 
		LOG4CXX_ERROR(logger, "getBuddies query "<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));
 
		return false;
 
	}
 

	
 
	if (ret2 != SQLITE_DONE) {
 
		if (ret2 == SQLITE_ERROR) {
 
			LOG4CXX_ERROR(logger, "getBuddiesSettings query "<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));
 
			return false;
 
		}
 

	
 
		while((ret2 = sqlite3_step(m_getBuddiesSettings)) == SQLITE_ROW) {
 
		}
 

	
 
		if (ret2 != SQLITE_DONE) {
 
			LOG4CXX_ERROR(logger, "getBuddiesSettings query "<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));
 
			return false;
 
		}
 
	}
 
	
 
	return true;
 
}
 

	
 
void SQLite3Backend::removeBuddy(long id) {
 
	sqlite3_reset(m_removeBuddy);
src/tests/basictest.cpp
Show inline comments
 
@@ -255,16 +255,16 @@ void BasicTest::add2Buddies() {
 
	User *user = userManager->getUser("user@localhost");
 
	CPPUNIT_ASSERT(user);
 

	
 
	std::vector<std::string> grp;
 
	grp.push_back("group1");
 
	LocalBuddy *buddy = new LocalBuddy(user->getRosterManager(), -1, "buddy1", "Buddy 1", grp, BUDDY_JID_ESCAPING);
 
	buddy->setStatus(Swift::StatusShow(Swift::StatusShow::Away), "status1");
 
	user->getRosterManager()->setBuddy(buddy);
 
	buddy->setStatus(Swift::StatusShow(Swift::StatusShow::Away), "status1");
 

	
 
	std::vector<std::string> grp2;
 
	grp2.push_back("group2");
 
	buddy = new LocalBuddy(user->getRosterManager(), -1, "buddy2", "Buddy 2", grp2, BUDDY_JID_ESCAPING);
 
	buddy->setStatus(Swift::StatusShow(Swift::StatusShow::Away), "status2");
 
	user->getRosterManager()->setBuddy(buddy);
 
	buddy->setStatus(Swift::StatusShow(Swift::StatusShow::Away), "status2");
 
}
 

	
src/tests/localbuddy.cpp
Show inline comments
 
@@ -23,13 +23,13 @@ using namespace Transport;
 
class LocalBuddyTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
	CPPUNIT_TEST_SUITE(LocalBuddyTest);
 
	CPPUNIT_TEST(createWithInvalidName);
 
	CPPUNIT_TEST(buddyFlagsFromJID);
 
	CPPUNIT_TEST(JIDToLegacyName);
 
	CPPUNIT_TEST(getSafeName);
 
	CPPUNIT_TEST(handleBuddyChanged);
 
	CPPUNIT_TEST(sendPresence);
 
	CPPUNIT_TEST(setAlias);
 
	CPPUNIT_TEST_SUITE_END();
 

	
 
	public:
 
		void setUp (void) {
 
			setMeUp();
 
@@ -87,24 +87,24 @@ class LocalBuddyTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 

	
 
	void buddyFlagsFromJID() {
 
		CPPUNIT_ASSERT_EQUAL(BUDDY_JID_ESCAPING, Buddy::buddyFlagsFromJID("hanzz\\40test@localhost/bot"));
 
		CPPUNIT_ASSERT_EQUAL(BUDDY_NO_FLAG, Buddy::buddyFlagsFromJID("hanzz%test@localhost/bot"));
 
	}
 

	
 
	void handleBuddyChanged() {
 
	void sendPresence() {
 
		User *user = userManager->getUser("user@localhost");
 
		CPPUNIT_ASSERT(user);
 

	
 
		std::vector<std::string> grp;
 
		grp.push_back("group1");
 
		LocalBuddy *buddy = new LocalBuddy(user->getRosterManager(), -1, "buddy1", "Buddy 1", grp, BUDDY_JID_ESCAPING);
 
		buddy->setStatus(Swift::StatusShow(Swift::StatusShow::Away), "status1");
 
		user->getRosterManager()->setBuddy(buddy);
 
		received.clear();
 

	
 
		buddy->handleBuddyChanged();
 
		buddy->sendPresence();
 
		CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[0])));
 
		CPPUNIT_ASSERT_EQUAL(Swift::StatusShow::Away, dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getShow());
 
		CPPUNIT_ASSERT_EQUAL(std::string("status1"), dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getStatus());
 
	}
 

	
src/tests/networkpluginserver.cpp
Show inline comments
 
@@ -49,12 +49,13 @@ class Clock {
 
class NetworkPluginServerTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
	CPPUNIT_TEST_SUITE(NetworkPluginServerTest);
 
	CPPUNIT_TEST(handleBuddyChangedPayload);
 
	CPPUNIT_TEST(handleBuddyChangedPayloadNoEscaping);
 
	CPPUNIT_TEST(handleBuddyChangedPayloadUserContactInRoster);
 
	CPPUNIT_TEST(handleMessageHeadline);
 
	CPPUNIT_TEST(handleConvMessageAckPayload);
 

	
 
	CPPUNIT_TEST(benchmarkHandleBuddyChangedPayload);
 
	CPPUNIT_TEST_SUITE_END();
 

	
 
	public:
 
		NetworkPluginServer *serv;
 
@@ -71,19 +72,45 @@ class NetworkPluginServerTest : public CPPUNIT_NS :: TestFixture, public BasicTe
 
			received.clear();
 
			disconnectUser();
 
			delete serv;
 
			tearMeDown();
 
		}
 

	
 
		void handleConvMessageAckPayload() {
 
			handleMessageHeadline();
 
			received.clear();
 
			User *user = userManager->getUser("user@localhost");
 

	
 
			pbnetwork::ConversationMessage m;
 
			m.set_username("user@localhost");
 
			m.set_buddyname("user");
 
			m.set_message("");
 
			m.set_nickname("");
 
			m.set_id("testingid");
 
			m.set_xhtml("");
 
			m.set_timestamp("");
 
			m.set_headline(true);
 

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

	
 
			serv->handleConvMessageAckPayload(message);
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[0]))->getPayload<Swift::DeliveryReceipt>());
 
			CPPUNIT_ASSERT_EQUAL(std::string("testingid"), dynamic_cast<Swift::Message *>(getStanza(received[0]))->getPayload<Swift::DeliveryReceipt>()->getReceivedID());
 
		}
 

	
 
		void benchmarkHandleBuddyChangedPayload() {
 
			Clock clk;
 
			std::vector<std::string> lst;
 
			for (int i = 0; i < 2000; i++) {
 
				pbnetwork::Buddy buddy;
 
				buddy.set_username("user@localhost");
 
				buddy.set_buddyname("buddy" + boost::lexical_cast<std::string>(i)  + "@test");
 
				buddy.set_status((pbnetwork::StatusType) 5);
 

	
 
				std::string message;
 
				buddy.SerializeToString(&message);
 
				lst.push_back(message);
 
			}
 

	
 
@@ -115,12 +142,13 @@ class NetworkPluginServerTest : public CPPUNIT_NS :: TestFixture, public BasicTe
 
		void handleBuddyChangedPayload() {
 
			User *user = userManager->getUser("user@localhost");
 

	
 
			pbnetwork::Buddy buddy;
 
			buddy.set_username("user@localhost");
 
			buddy.set_buddyname("buddy1@test");
 
			buddy.set_status(pbnetwork::STATUS_NONE);
 

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

	
 
			serv->handleBuddyChangedPayload(message);
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
@@ -135,12 +163,13 @@ class NetworkPluginServerTest : public CPPUNIT_NS :: TestFixture, public BasicTe
 
			cfg->load(ifs);
 
			User *user = userManager->getUser("user@localhost");
 

	
 
			pbnetwork::Buddy buddy;
 
			buddy.set_username("user@localhost");
 
			buddy.set_buddyname("buddy1@test");
 
			buddy.set_status(pbnetwork::STATUS_NONE);
 

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

	
 
			serv->handleBuddyChangedPayload(message);
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
@@ -190,11 +219,10 @@ class NetworkPluginServerTest : public CPPUNIT_NS :: TestFixture, public BasicTe
 
			received.clear();
 
			user->addUserSetting("send_headlines", "1");
 
			serv->handleConvMessagePayload(message, false);
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::Message::Headline, dynamic_cast<Swift::Message *>(getStanza(received[0]))->getType());
 

	
 
		}
 
};
 

	
 
CPPUNIT_TEST_SUITE_REGISTRATION (NetworkPluginServerTest);
src/tests/rostermanager.cpp
Show inline comments
 
@@ -21,12 +21,13 @@
 
using namespace Transport;
 

	
 
class RosterManagerTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
	CPPUNIT_TEST_SUITE(RosterManagerTest);
 
	CPPUNIT_TEST(setBuddy);
 
	CPPUNIT_TEST(sendCurrentPresences);
 
	CPPUNIT_TEST(sendUnavailablePresences);
 
	CPPUNIT_TEST(sendCurrentPresence);
 
	CPPUNIT_TEST(sendBuddySubscribePresence);
 
	CPPUNIT_TEST(removeBuddy);
 
	CPPUNIT_TEST(subscribeExistingBuddy);
 
	CPPUNIT_TEST(subscribeNewBuddy);
 
	CPPUNIT_TEST(unsubscribeExistingBuddy);
 
@@ -70,41 +71,41 @@ class RosterManagerTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
		CPPUNIT_ASSERT_EQUAL(std::string("Buddy 1"), getStanza(received[0])->getPayload<Swift::Nickname>()->getNickname());
 
		
 
	}
 

	
 
	void setBuddy() {
 
		add2Buddies();
 
		CPPUNIT_ASSERT_EQUAL(2, (int) received.size());
 
		CPPUNIT_ASSERT_EQUAL(4, (int) received.size());
 

	
 
		Swift::RosterPayload::ref payload1 = getStanza(received[0])->getPayload<Swift::RosterPayload>();
 
		CPPUNIT_ASSERT(payload1);
 
		CPPUNIT_ASSERT_EQUAL(1, (int) payload1->getItems().size());
 
		Swift::RosterItemPayload item = payload1->getItems()[0];
 
		CPPUNIT_ASSERT_EQUAL(std::string("buddy1"), Buddy::JIDToLegacyName(item.getJID()));
 
		CPPUNIT_ASSERT_EQUAL(std::string("Buddy 1"), item.getName());
 

	
 
		Swift::RosterPayload::ref payload2 = getStanza(received[1])->getPayload<Swift::RosterPayload>();
 
		Swift::RosterPayload::ref payload2 = getStanza(received[2])->getPayload<Swift::RosterPayload>();
 
		CPPUNIT_ASSERT(payload2);
 
		CPPUNIT_ASSERT_EQUAL(1, (int) payload2->getItems().size());
 
		item = payload2->getItems()[0];
 
		CPPUNIT_ASSERT_EQUAL(std::string("buddy2"), Buddy::JIDToLegacyName(item.getJID()));
 
		CPPUNIT_ASSERT_EQUAL(std::string("Buddy 2"), item.getName());
 

	
 
		// send responses back
 
		injectIQ(Swift::IQ::createResult(getStanza(received[0])->getFrom(), getStanza(received[0])->getTo(), getStanza(received[0])->getID()));
 
		injectIQ(Swift::IQ::createResult(getStanza(received[1])->getFrom(), getStanza(received[1])->getTo(), getStanza(received[1])->getID()));
 
		injectIQ(Swift::IQ::createResult(getStanza(received[2])->getFrom(), getStanza(received[2])->getTo(), getStanza(received[2])->getID()));
 

	
 
		// we should get presences
 
		CPPUNIT_ASSERT_EQUAL(4, (int) received.size());
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[2])));
 
		CPPUNIT_ASSERT_EQUAL(Swift::StatusShow::Away, dynamic_cast<Swift::Presence *>(getStanza(received[2]))->getShow());
 
		CPPUNIT_ASSERT_EQUAL(std::string("status1"), dynamic_cast<Swift::Presence *>(getStanza(received[2]))->getStatus());
 

	
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[3])));
 
		CPPUNIT_ASSERT_EQUAL(Swift::StatusShow::Away, dynamic_cast<Swift::Presence *>(getStanza(received[3]))->getShow());
 
		CPPUNIT_ASSERT_EQUAL(std::string("status2"), dynamic_cast<Swift::Presence *>(getStanza(received[3]))->getStatus());
 
		CPPUNIT_ASSERT_EQUAL(6, (int) received.size());
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[4])));
 
		CPPUNIT_ASSERT_EQUAL(Swift::StatusShow::Away, dynamic_cast<Swift::Presence *>(getStanza(received[4]))->getShow());
 
		CPPUNIT_ASSERT_EQUAL(std::string("status1"), dynamic_cast<Swift::Presence *>(getStanza(received[4]))->getStatus());
 

	
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[5])));
 
		CPPUNIT_ASSERT_EQUAL(Swift::StatusShow::Away, dynamic_cast<Swift::Presence *>(getStanza(received[5]))->getShow());
 
		CPPUNIT_ASSERT_EQUAL(std::string("status2"), dynamic_cast<Swift::Presence *>(getStanza(received[5]))->getStatus());
 
	}
 

	
 
	void sendCurrentPresences() {
 
		setBuddy();
 
		received.clear();
 

	
 
@@ -117,12 +118,28 @@ class RosterManagerTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[i])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::StatusShow::Away, dynamic_cast<Swift::Presence *>(getStanza(received[i]))->getShow());
 
			CPPUNIT_ASSERT_EQUAL(std::string("user@localhost/resource"), dynamic_cast<Swift::Presence *>(getStanza(received[i]))->getTo().toString());
 
		}
 
	}
 

	
 
	void sendUnavailablePresences() {
 
		setBuddy();
 
		received.clear();
 

	
 
		User *user = userManager->getUser("user@localhost");
 
		user->getRosterManager()->sendUnavailablePresences("user@localhost/resource");
 

	
 
		CPPUNIT_ASSERT_EQUAL(3, (int) received.size());
 

	
 
		for (int i = 0; i < 3; i++) {
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[i])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::Presence::Unavailable, dynamic_cast<Swift::Presence *>(getStanza(received[i]))->getType());
 
			CPPUNIT_ASSERT_EQUAL(std::string("user@localhost/resource"), dynamic_cast<Swift::Presence *>(getStanza(received[i]))->getTo().toString());
 
		}
 
	}
 

	
 
	void sendCurrentPresence() {
 
		setBuddy();
 
		received.clear();
 

	
 
		User *user = userManager->getUser("user@localhost");
 
		user->getRosterManager()->sendCurrentPresence("buddy1@localhost", "user@localhost/resource");
 
@@ -139,13 +156,13 @@ class RosterManagerTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
		CPPUNIT_ASSERT_EQUAL(Swift::Presence::Unavailable, dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getType());
 
		CPPUNIT_ASSERT_EQUAL(std::string("user@localhost/resource"), dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getTo().toString());
 
	}
 

	
 
	void removeBuddy() {
 
		add2Buddies();
 
		CPPUNIT_ASSERT_EQUAL(2, (int) received.size());
 
		CPPUNIT_ASSERT_EQUAL(4, (int) received.size());
 

	
 
		received.clear();
 
		User *user = userManager->getUser("user@localhost");
 
		user->getRosterManager()->removeBuddy("buddy1");
 
		CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 

	
src/tests/usermanager.cpp
Show inline comments
 
@@ -31,12 +31,14 @@ class UserManagerTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
	CPPUNIT_TEST(handleProbePresence);
 
	CPPUNIT_TEST(disconnectUser);
 
	CPPUNIT_TEST(disconnectUserBouncer);
 
	CPPUNIT_TEST_SUITE_END();
 

	
 
	public:
 
		Swift::Presence::ref changedPresence;
 

	
 
		void setUp (void) {
 
			setMeUp();
 
		}
 

	
 
		void tearDown (void) {
 
			tearMeDown();
 
@@ -162,26 +164,49 @@ class UserManagerTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
		dynamic_cast<Swift::ServerStanzaChannel *>(component->getStanzaChannel())->onPresenceReceived(response);
 
		loop->processEvents();
 

	
 
		CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
	}
 

	
 
	void handleUserPresenceChanged(User *user, Swift::Presence::ref presence) {
 
		changedPresence = presence;
 
	}
 

	
 
	void connectTwoResources() {
 
		connectUser();
 
		add2Buddies();
 
		connectSecondResource();
 

	
 
		User *user = userManager->getUser("user@localhost");
 
		user->onPresenceChanged.connect(boost::bind(&UserManagerTest::handleUserPresenceChanged, this, user, _1));
 

	
 
		// we should get presences
 
		CPPUNIT_ASSERT_EQUAL(4, (int) received2.size());
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received2[2])));
 
		CPPUNIT_ASSERT_EQUAL(Swift::StatusShow::Away, dynamic_cast<Swift::Presence *>(getStanza(received2[2]))->getShow());
 
		CPPUNIT_ASSERT_EQUAL(std::string("status1"), dynamic_cast<Swift::Presence *>(getStanza(received2[2]))->getStatus());
 

	
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received2[3])));
 
		CPPUNIT_ASSERT_EQUAL(Swift::StatusShow::Away, dynamic_cast<Swift::Presence *>(getStanza(received2[3]))->getShow());
 
		CPPUNIT_ASSERT_EQUAL(std::string("status2"), dynamic_cast<Swift::Presence *>(getStanza(received2[3]))->getStatus());
 

	
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setTo("localhost");
 
		response->setFrom("user@localhost/resource");
 
		response->setType(Swift::Presence::Unavailable);
 
		injectPresence(response);
 

	
 
		CPPUNIT_ASSERT_EQUAL(Swift::Presence::Available, changedPresence->getType());
 

	
 
		Swift::Presence::ref response2 = Swift::Presence::create();
 
		response2->setTo("localhost");
 
		response2->setFrom("user@localhost/resource2");
 
		response2->setType(Swift::Presence::Unavailable);
 
		injectPresence(response2);
 

	
 
		CPPUNIT_ASSERT_EQUAL(Swift::Presence::Unavailable, changedPresence->getType());
 
	}
 

	
 
	void disconnectUserBouncer() {
 
		connectUser();
 
		User *user = userManager->getUser("user@localhost");
 
		user->addUserSetting("stay_connected", "1");
 
@@ -189,13 +214,12 @@ class UserManagerTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
		userManager->disconnectUser("user@localhost");
 
		dynamic_cast<Swift::DummyTimerFactory *>(factories->getTimerFactory())->setTime(10);
 
		loop->processEvents();
 

	
 
		CPPUNIT_ASSERT_EQUAL(1, userManager->getUserCount());
 
		CPPUNIT_ASSERT_EQUAL(0, (int) received.size());
 
		CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[0])));
 
		CPPUNIT_ASSERT(userManager->getUser("user@localhost"));
 

	
 
		userManager->removeAllUsers();
 
		loop->processEvents();
 
		CPPUNIT_ASSERT_EQUAL(0, userManager->getUserCount());
 
	}
src/tests/userregistration.cpp
Show inline comments
 
@@ -23,12 +23,13 @@ using namespace Transport;
 

	
 
class UserRegistrationTest : public CPPUNIT_NS :: TestFixture, public BasicTest {
 
	CPPUNIT_TEST_SUITE(UserRegistrationTest);
 
	CPPUNIT_TEST(getForm);
 
	CPPUNIT_TEST(getFormRegistered);
 
	CPPUNIT_TEST(registerUser);
 
	CPPUNIT_TEST(registerUserWithoutRR);
 
	CPPUNIT_TEST(unregisterUser);
 
	CPPUNIT_TEST(unregisterEmptyPayload);
 
	CPPUNIT_TEST(registerUserNotify);
 
	CPPUNIT_TEST(unregisterUserNotify);
 
	CPPUNIT_TEST(changePassword);
 
	CPPUNIT_TEST(registerUserEmpty);
 
@@ -93,25 +94,60 @@ class UserRegistrationTest : public CPPUNIT_NS :: TestFixture, public BasicTest
 
			iq->setFrom("user@localhost");
 
			injectIQ(iq);
 
			loop->processEvents();
 

	
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received.size());
 

	
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::Presence::Subscribe, dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getType());
 
			CPPUNIT_ASSERT(getStanza(received[0])->getPayload<Swift::RosterPayload>());
 

	
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::IQ *>(getStanza(received[1])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::IQ::Result, dynamic_cast<Swift::IQ *>(getStanza(received[1]))->getType());
 

	
 
			iq = Swift::IQ::createResult(Swift::JID("localhost"), getStanza(received[0])->getTo(), getStanza(received[0])->getID(), boost::shared_ptr<Swift::Payload>(new Swift::RosterPayload()));
 
			received.clear();
 
			injectIQ(iq);
 
			loop->processEvents();
 

	
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::IQ *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::IQ::Set, dynamic_cast<Swift::IQ *>(getStanza(received[0]))->getType());
 
			CPPUNIT_ASSERT(getStanza(received[0])->getPayload<Swift::RosterPayload>());
 

	
 
			CPPUNIT_ASSERT_EQUAL(std::string("localhost"), getStanza(received[0])->getPayload<Swift::RosterPayload>()->getItems()[0].getJID().toString());
 

	
 
			UserInfo user;
 
			CPPUNIT_ASSERT_EQUAL(true, storage->getUser("user@localhost", user));
 

	
 
			CPPUNIT_ASSERT_EQUAL(std::string("legacyname"), user.uin);
 
			CPPUNIT_ASSERT_EQUAL(std::string("password"), user.password);
 
		}
 

	
 
		void registerUserWithoutRR(){
 
			Swift::InBandRegistrationPayload *reg = new Swift::InBandRegistrationPayload();
 
			reg->setUsername("legacyname");
 
			reg->setPassword("password");
 
			boost::shared_ptr<Swift::IQ> iq = Swift::IQ::createRequest(Swift::IQ::Set, Swift::JID("localhost"), "id", boost::shared_ptr<Swift::Payload>(reg));
 
			iq->setFrom("user@localhost");
 
			injectIQ(iq);
 
			loop->processEvents();
 

	
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received.size());
 

	
 
			CPPUNIT_ASSERT(getStanza(received[0])->getPayload<Swift::RosterPayload>());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::IQ *>(getStanza(received[1])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::IQ::Result, dynamic_cast<Swift::IQ *>(getStanza(received[1]))->getType());
 

	
 
			iq = Swift::IQ::createError(Swift::JID("localhost"), getStanza(received[0])->getTo(), getStanza(received[0])->getID());
 
			received.clear();
 
			injectIQ(iq);
 
			loop->processEvents();
 

	
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::Presence::Subscribe, dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getType());
 
		}
 

	
 
		void unregisterUser() {
 
			registerUser();
 
			received.clear();
 

	
 
			Swift::InBandRegistrationPayload *reg = new Swift::InBandRegistrationPayload();
 
			reg->setRemove(true);
 
@@ -150,23 +186,33 @@ class UserRegistrationTest : public CPPUNIT_NS :: TestFixture, public BasicTest
 
			reg->setPassword("password");
 
			boost::shared_ptr<Swift::IQ> iq = Swift::IQ::createRequest(Swift::IQ::Set, Swift::JID("localhost"), "id", boost::shared_ptr<Swift::Payload>(reg));
 
			iq->setFrom("user@localhost");
 
			injectIQ(iq);
 
			loop->processEvents();
 

	
 
			CPPUNIT_ASSERT_EQUAL(3, (int) received.size());
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received.size());
 

	
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::Presence::Subscribe, dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getType());
 
			CPPUNIT_ASSERT(getStanza(received[0])->getPayload<Swift::RosterPayload>());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::IQ *>(getStanza(received[1])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::IQ::Result, dynamic_cast<Swift::IQ *>(getStanza(received[1]))->getType());
 

	
 
			iq = Swift::IQ::createResult(Swift::JID("localhost"), getStanza(received[0])->getTo(), getStanza(received[0])->getID(), boost::shared_ptr<Swift::Payload>(new Swift::RosterPayload()));
 
			received.clear();
 
			injectIQ(iq);
 
			loop->processEvents();
 

	
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received.size());
 

	
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::IQ *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::IQ::Set, dynamic_cast<Swift::IQ *>(getStanza(received[0]))->getType());
 
			CPPUNIT_ASSERT(getStanza(received[0])->getPayload<Swift::RosterPayload>());
 
			CPPUNIT_ASSERT_EQUAL(std::string("localhost"), getStanza(received[0])->getPayload<Swift::RosterPayload>()->getItems()[0].getJID().toString());
 

	
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Message *>(getStanza(received[1])));
 
			CPPUNIT_ASSERT_EQUAL(std::string("registered: user@localhost"), dynamic_cast<Swift::Message *>(getStanza(received[1]))->getBody());
 

	
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::IQ *>(getStanza(received[2])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::IQ::Result, dynamic_cast<Swift::IQ *>(getStanza(received[2]))->getType());
 

	
 
			UserInfo user;
 
			CPPUNIT_ASSERT_EQUAL(true, storage->getUser("user@localhost", user));
 

	
 
			CPPUNIT_ASSERT_EQUAL(std::string("legacyname"), user.uin);
 
			CPPUNIT_ASSERT_EQUAL(std::string("password"), user.password);
 
		}
 
@@ -290,18 +336,28 @@ class UserRegistrationTest : public CPPUNIT_NS :: TestFixture, public BasicTest
 
			iq->setFrom("user@localhost");
 
			injectIQ(iq);
 
			loop->processEvents();
 

	
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received.size());
 

	
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::Presence *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::Presence::Subscribe, dynamic_cast<Swift::Presence *>(getStanza(received[0]))->getType());
 

	
 
			CPPUNIT_ASSERT(getStanza(received[0])->getPayload<Swift::RosterPayload>());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::IQ *>(getStanza(received[1])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::IQ::Result, dynamic_cast<Swift::IQ *>(getStanza(received[1]))->getType());
 

	
 
			iq = Swift::IQ::createResult(Swift::JID("localhost"), getStanza(received[0])->getTo(), getStanza(received[0])->getID(), boost::shared_ptr<Swift::Payload>(new Swift::RosterPayload()));
 
			received.clear();
 
			injectIQ(iq);
 
			loop->processEvents();
 

	
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received.size());
 
			CPPUNIT_ASSERT(dynamic_cast<Swift::IQ *>(getStanza(received[0])));
 
			CPPUNIT_ASSERT_EQUAL(Swift::IQ::Set, dynamic_cast<Swift::IQ *>(getStanza(received[0]))->getType());
 
			CPPUNIT_ASSERT(getStanza(received[0])->getPayload<Swift::RosterPayload>());
 

	
 
			CPPUNIT_ASSERT_EQUAL(std::string("localhost"), getStanza(received[0])->getPayload<Swift::RosterPayload>()->getItems()[0].getJID().toString());
 

	
 
			UserInfo user;
 
			CPPUNIT_ASSERT_EQUAL(true, storage->getUser("user@localhost", user));
 

	
 
			CPPUNIT_ASSERT_EQUAL(std::string("legacyname"), user.uin);
 
			CPPUNIT_ASSERT_EQUAL(std::string(""), user.password);
 
		}
src/transport.cpp
Show inline comments
 
@@ -228,14 +228,18 @@ void Component::handleConnected() {
 
	m_reconnectCount = 0;
 
	m_reconnectTimer->stop();
 
}
 

	
 
void Component::handleServerStopped(boost::optional<Swift::BoostConnectionServer::Error> e) {
 
	if(e != NULL ) {
 
		if(*e == Swift::BoostConnectionServer::Conflict)
 
		if(*e == Swift::BoostConnectionServer::Conflict) {
 
			LOG4CXX_INFO(logger, "Port "<< CONFIG_INT(m_config, "service.port") << " already in use! Stopping server..");
 
			if (CONFIG_INT(m_config, "service.port") == 5347) {
 
				LOG4CXX_INFO(logger, "Port 5347 is usually used for components. You are using server_mode=1. Are you sure you don't want to use server_mode=0 and run spectrum as component?");
 
			}
 
		}
 
		if(*e == Swift::BoostConnectionServer::UnknownError)
 
			LOG4CXX_INFO(logger, "Unknown error occured! Stopping server..");
 
		exit(1);
 
	}
 
}
 

	
src/user.cpp
Show inline comments
 
@@ -345,13 +345,12 @@ void User::handlePresence(Swift::Presence::ref presence, bool forceJoin) {
 
	if (presence->getType() != Swift::Presence::Unavailable && currentResourcesCount != m_resources) {
 
		m_rosterManager->sendCurrentPresences(presence->getFrom());
 
	}
 

	
 
	m_resources = currentResourcesCount;
 

	
 

	
 
	// Change legacy network presence
 
	if (m_readyForConnect) {
 
		Swift::Presence::ref highest = m_presenceOracle->getHighestPriorityPresence(m_jid.toBare());
 
		if (highest) {
 
			if (highest->getType() == Swift::Presence::Unavailable && getUserSetting("stay_connected") == "1") {
 
				m_resources = 0;
src/userregistration.cpp
Show inline comments
 
@@ -53,27 +53,17 @@ bool UserRegistration::registerUser(const UserInfo &row) {
 
	// This user is already registered
 
	if (registered)
 
		return false;
 

	
 
	m_storageBackend->setUser(row);
 

	
 
	Swift::Presence::ref response = Swift::Presence::create();
 
	response->setFrom(m_component->getJID());
 
	response->setTo(Swift::JID(row.jid));
 
	response->setType(Swift::Presence::Subscribe);
 
	m_component->getStanzaChannel()->sendPresence(response);
 

	
 
	onUserRegistered(row);
 
	//same as in unregisterUser but here we have to pass UserInfo to handleRegisterRRResponse
 
	AddressedRosterRequest::ref request = AddressedRosterRequest::ref(new AddressedRosterRequest(m_component->getIQRouter(),row.jid));
 
	request->onResponse.connect(boost::bind(&UserRegistration::handleRegisterRemoteRosterResponse, this, _1, _2, row));
 
	request->send();
 

	
 
	BOOST_FOREACH(const std::string &notify_jid, CONFIG_VECTOR(m_component->getConfig(),"registration.notify_jid")) {
 
		boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
		msg->setBody(std::string("registered: ") + row.jid);
 
		msg->setTo(notify_jid);
 
		msg->setFrom(m_component->getJID());
 
		m_component->getStanzaChannel()->sendMessage(msg);
 
	}
 
	return true;
 
}
 

	
 
bool UserRegistration::unregisterUser(const std::string &barejid) {
 
	UserInfo userInfo;
 
	bool registered = m_storageBackend->getUser(barejid, userInfo);
 
@@ -88,12 +78,41 @@ bool UserRegistration::unregisterUser(const std::string &barejid) {
 
	request->onResponse.connect(boost::bind(&UserRegistration::handleUnregisterRemoteRosterResponse, this, _1, _2, barejid));
 
	request->send();
 

	
 
	return true;
 
}
 

	
 
void UserRegistration::handleRegisterRemoteRosterResponse(boost::shared_ptr<Swift::RosterPayload> payload, Swift::ErrorPayload::ref remoteRosterNotSupported /*error*/, const UserInfo &row){
 
	if (remoteRosterNotSupported || !payload) {
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setFrom(m_component->getJID());
 
		response->setTo(Swift::JID(row.jid));
 
		response->setType(Swift::Presence::Subscribe);
 
		m_component->getStanzaChannel()->sendPresence(response);
 
	}
 
	else{
 
		Swift::RosterPayload::ref payload = Swift::RosterPayload::ref(new Swift::RosterPayload());
 
		Swift::RosterItemPayload item;
 
		item.setJID(m_component->getJID());
 
		item.setSubscription(Swift::RosterItemPayload::Both);
 
		payload->addItem(item);
 
		Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(payload, row.jid, m_component->getIQRouter());
 
		request->send();
 
	}
 
	onUserRegistered(row);
 

	
 
	std::vector<std::string> const &x = CONFIG_VECTOR(m_component->getConfig(),"registration.notify_jid");
 
	BOOST_FOREACH(const std::string &notify_jid, x) {
 
		boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
		msg->setBody(std::string("registered: ") + row.jid);
 
		msg->setTo(notify_jid);
 
		msg->setFrom(m_component->getJID());
 
		m_component->getStanzaChannel()->sendMessage(msg);
 
	}
 
}
 

	
 
void UserRegistration::handleUnregisterRemoteRosterResponse(boost::shared_ptr<Swift::RosterPayload> payload, Swift::ErrorPayload::ref remoteRosterNotSupported /*error*/, const std::string &barejid) {
 
	UserInfo userInfo;
 
	bool registered = m_storageBackend->getUser(barejid, userInfo);
 
	// This user is not registered
 
	if (!registered)
 
		return;
 
@@ -171,13 +190,14 @@ void UserRegistration::handleUnregisterRemoteRosterResponse(boost::shared_ptr<Sw
 
		payload->addItem(item);
 

	
 
		Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(payload, barejid, m_component->getIQRouter());
 
		request->send();
 
	}
 

	
 
	BOOST_FOREACH(const std::string &notify_jid, CONFIG_VECTOR(m_component->getConfig(),"registration.notify_jid")) {
 
	std::vector<std::string> const &x = CONFIG_VECTOR(m_component->getConfig(),"registration.notify_jid");
 
	BOOST_FOREACH(const std::string &notify_jid, x) {
 
		boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
		msg->setBody(std::string("unregistered: ") + barejid);
 
		msg->setTo(notify_jid);
 
		msg->setFrom(m_component->getJID());
 
		m_component->getStanzaChannel()->sendMessage(msg);
 
	}
 
@@ -488,12 +508,13 @@ bool UserRegistration::handleSetRequest(const Swift::JID& from, const Swift::JID
 
		res.jid = barejid;
 
		res.uin = newUsername;
 
		res.password = *payload->getPassword();
 
		res.language = language;
 
		res.encoding = encoding;
 
		res.vip = 0;
 
		res.id = 0;
 
		registerUser(res);
 
	}
 
	else {
 
		res.jid = barejid;
 
		res.uin = newUsername;
 
		res.password = *payload->getPassword();
0 comments (0 inline, 0 general)